From 128593419c835b37dbcc14b70463d6c9d820a71e Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Wed, 17 Jun 2026 03:21:49 +0000 Subject: [PATCH] [typespec-go] Regenerate tests from Azure/typespec-azure PR #4628 --- .../accessgroup/LICENSE.txt | 21 + .../accessgroup/fake/zz_access_server.go | 78 + .../fake/zz_accesspublicoperation_server.go | 128 + .../zz_accesssharedmodelinoperation_server.go | 102 + .../accessgroup/fake/zz_internal.go | 31 + .../client-generator-core/accessgroup/go.mod | 17 + .../client-generator-core/accessgroup/go.sum | 25 + .../internaloperation_client_test.go | 42 + .../publicoperation_client_test.go | 32 + .../relativemodelinoperation_client_test.go | 36 + .../sharedmodelinoperation_client_test.go | 32 + .../accessgroup/testdata/_metadata.json | 3 + .../accessgroup/zz_access_client.go | 72 + .../zz_accessinternaloperation_client.go | 168 + .../zz_accesspublicoperation_client.go | 119 + ...z_accessrelativemodelinoperation_client.go | 136 + .../zz_accesssharedmodelinoperation_client.go | 119 + .../accessgroup/zz_interfaces.go | 14 + .../accessgroup/zz_models.go | 85 + .../accessgroup/zz_models_serde.go | 314 + .../accessgroup/zz_options.go | 59 + .../accessgroup/zz_polymorphic_helpers.go | 28 + .../accessgroup/zz_responses.go | 59 + .../accessgroup/zz_responses_serde.go | 15 + .../accessgroup/zz_version.go | 10 + .../apiversionheadergroup/LICENSE.txt | 21 + .../fake/zz_header_server.go | 101 + .../apiversionheadergroup/fake/zz_internal.go | 20 + .../api-version/apiversionheadergroup/go.mod | 17 + .../api-version/apiversionheadergroup/go.sum | 25 + .../header_client_test.go | 23 + .../testdata/_metadata.json | 6 + .../apiversionheadergroup/zz_constants.go | 9 + .../apiversionheadergroup/zz_header_client.go | 85 + .../apiversionheadergroup/zz_options.go | 10 + .../apiversionheadergroup/zz_responses.go | 10 + .../apiversionheadergroup/zz_version.go | 10 + .../apiversionpathgroup/LICENSE.txt | 21 + .../apiversionpathgroup/fake/zz_internal.go | 20 + .../fake/zz_path_server.go | 101 + .../api-version/apiversionpathgroup/go.mod | 11 + .../api-version/apiversionpathgroup/go.sum | 16 + .../apiversionpathgroup/path_client_test.go | 12 + .../testdata/_metadata.json | 6 + .../apiversionpathgroup/zz_constants.go | 9 + .../apiversionpathgroup/zz_options.go | 10 + .../apiversionpathgroup/zz_path_client.go | 86 + .../apiversionpathgroup/zz_responses.go | 10 + .../apiversionpathgroup/zz_version.go | 10 + .../apiversionquerygroup/LICENSE.txt | 21 + .../apiversionquerygroup/fake/zz_internal.go | 20 + .../fake/zz_query_server.go | 101 + .../api-version/apiversionquerygroup/go.mod | 17 + .../api-version/apiversionquerygroup/go.sum | 25 + .../apiversionquerygroup/query_client_test.go | 22 + .../testdata/_metadata.json | 6 + .../apiversionquerygroup/zz_constants.go | 9 + .../apiversionquerygroup/zz_options.go | 10 + .../apiversionquerygroup/zz_query_client.go | 88 + .../apiversionquerygroup/zz_responses.go | 10 + .../apiversionquerygroup/zz_version.go | 10 + .../clientinitdefaultgroup/LICENSE.txt | 21 + .../fake/zz_headerparam_server.go | 131 + .../fake/zz_internal.go | 30 + .../fake/zz_mixedparams_server.go | 132 + .../fake/zz_multipleparams_server.go | 131 + .../fake/zz_paramalias_server.go | 139 + .../fake/zz_pathparam_server.go | 178 + .../fake/zz_queryparam_server.go | 159 + .../clientinitdefaultgroup/go.mod | 17 + .../clientinitdefaultgroup/go.sum | 25 + .../headerparam_client_test.go | 31 + .../mixedparams_client_test.go | 31 + .../multipleparams_client_test.go | 31 + .../paramalias_client_test.go | 28 + .../pathparam_client_test.go | 47 + .../queryparam_client_test.go | 47 + .../testdata/_metadata.json | 3 + .../zz_headerparam_client.go | 123 + .../zz_mixedparams_client.go | 127 + .../clientinitdefaultgroup/zz_models.go | 32 + .../clientinitdefaultgroup/zz_models_serde.go | 155 + .../zz_multipleparams_client.go | 130 + .../clientinitdefaultgroup/zz_options.go | 75 + .../zz_paramalias_client.go | 126 + .../zz_pathparam_client.go | 179 + .../zz_queryparam_client.go | 173 + .../clientinitdefaultgroup/zz_responses.go | 77 + .../clientinitdefaultgroup/zz_version.go | 10 + .../clientinitindividuallygroup/LICENSE.txt | 21 + .../zz_individuallynestedwithheader_server.go | 159 + .../zz_individuallynestedwithmixed_server.go | 161 + ...z_individuallynestedwithmultiple_server.go | 159 + ...individuallynestedwithparamalias_server.go | 139 + .../zz_individuallynestedwithpath_server.go | 178 + .../zz_individuallynestedwithquery_server.go | 159 + .../fake/zz_internal.go | 30 + .../clientinitindividuallygroup/go.mod | 17 + .../clientinitindividuallygroup/go.sum | 25 + ...ndividuallynestedwithheader_client_test.go | 39 + ...individuallynestedwithmixed_client_test.go | 39 + ...ividuallynestedwithmultiple_client_test.go | 39 + ...iduallynestedwithparamalias_client_test.go | 28 + .../individuallynestedwithpath_client_test.go | 47 + ...individuallynestedwithquery_client_test.go | 47 + .../testdata/_metadata.json | 3 + .../zz_individuallynestedwithheader_client.go | 159 + .../zz_individuallynestedwithmixed_client.go | 166 + ...z_individuallynestedwithmultiple_client.go | 168 + ...individuallynestedwithparamalias_client.go | 126 + .../zz_individuallynestedwithpath_client.go | 181 + .../zz_individuallynestedwithquery_client.go | 174 + .../clientinitindividuallygroup/zz_models.go | 22 + .../zz_models_serde.go | 101 + .../clientinitindividuallygroup/zz_options.go | 107 + .../zz_responses.go | 92 + .../clientinitindividuallygroup/zz_version.go | 10 + .../LICENSE.txt | 21 + .../fake/zz_individuallyparent_server.go | 114 + ...dividuallyparentnestedwithheader_server.go | 159 + ...ndividuallyparentnestedwithmixed_server.go | 161 + ...viduallyparentnestedwithmultiple_server.go | 159 + ...duallyparentnestedwithparamalias_server.go | 139 + ...individuallyparentnestedwithpath_server.go | 178 + ...ndividuallyparentnestedwithquery_server.go | 159 + .../fake/zz_internal.go | 39 + .../clientinitindividuallyparentgroup/go.mod | 17 + .../clientinitindividuallyparentgroup/go.sum | 25 + ...uallyparentnestedwithheader_client_test.go | 42 + ...duallyparentnestedwithmixed_client_test.go | 42 + ...llyparentnestedwithmultiple_client_test.go | 42 + ...yparentnestedwithparamalias_client_test.go | 30 + ...iduallyparentnestedwithpath_client_test.go | 50 + ...duallyparentnestedwithquery_client_test.go | 50 + .../testdata/_metadata.json | 3 + .../zz_individuallyparent_client.go | 95 + ...dividuallyparentnestedwithheader_client.go | 160 + ...ndividuallyparentnestedwithmixed_client.go | 167 + ...viduallyparentnestedwithmultiple_client.go | 169 + ...duallyparentnestedwithparamalias_client.go | 127 + ...individuallyparentnestedwithpath_client.go | 181 + ...ndividuallyparentnestedwithquery_client.go | 175 + .../zz_models.go | 22 + .../zz_models_serde.go | 101 + .../zz_options.go | 107 + .../zz_responses.go | 95 + .../zz_version.go | 10 + .../LICENSE.txt | 21 + .../fake/zz_internal.go | 31 + .../fake/zz_movetoexistingsub_server.go | 78 + ...movetoexistingsubadminoperations_server.go | 126 + ..._movetoexistingsubuseroperations_server.go | 101 + .../go.mod | 17 + .../go.sum | 25 + .../movetoexistingsub_client_test.go | 27 + .../testdata/_metadata.json | 3 + .../zz_movetoexistingsub_client.go | 56 + ...movetoexistingsubadminoperations_client.go | 90 + ..._movetoexistingsubuseroperations_client.go | 55 + .../zz_options.go | 23 + .../zz_responses.go | 20 + .../zz_version.go | 10 + .../LICENSE.txt | 21 + .../fake/zz_internal.go | 31 + .../fake/zz_movemethodparameterto_server.go | 69 + ...emethodparametertobloboperations_server.go | 102 + .../go.mod | 17 + .../go.sum | 25 + .../movemethodparameterto_client_test.go | 31 + .../testdata/_metadata.json | 3 + .../zz_models.go | 19 + .../zz_models_serde.go | 71 + .../zz_movemethodparameterto_client.go | 48 + ...emethodparametertobloboperations_client.go | 73 + .../zz_options.go | 11 + .../zz_responses.go | 10 + .../zz_version.go | 10 + .../LICENSE.txt | 21 + .../fake/zz_internal.go | 31 + .../fake/zz_movetonewsub_server.go | 78 + ...zz_movetonewsubarchiveoperations_server.go | 101 + ...zz_movetonewsubproductoperations_server.go | 101 + .../go.mod | 17 + .../go.sum | 25 + .../movetonewsub_client_test.go | 24 + .../testdata/_metadata.json | 3 + .../zz_movetonewsub_client.go | 56 + ...zz_movetonewsubarchiveoperations_client.go | 55 + ...zz_movetonewsubproductoperations_client.go | 55 + .../zz_options.go | 17 + .../zz_responses.go | 15 + .../zz_version.go | 10 + .../LICENSE.txt | 21 + .../fake/zz_internal.go | 31 + .../fake/zz_movetoroot_server.go | 128 + .../zz_movetorootresourceoperations_server.go | 101 + .../go.mod | 17 + .../go.sum | 25 + .../movetoroot_client_test.go | 23 + .../testdata/_metadata.json | 3 + .../zz_movetoroot_client.go | 86 + .../zz_movetorootresourceoperations_client.go | 55 + .../zz_options.go | 16 + .../zz_responses.go | 15 + .../zz_version.go | 10 + .../coreusagegroup/LICENSE.txt | 21 + .../coreusagegroup/fake/zz_internal.go | 31 + .../coreusagegroup/fake/zz_usage_server.go | 78 + .../fake/zz_usagemodelinoperation_server.go | 188 + .../fake/zz_usagenamespaceusage_server.go | 105 + .../coreusagegroup/go.mod | 17 + .../coreusagegroup/go.sum | 25 + .../modelinoperation_client_test.go | 57 + .../coreusagegroup/testdata/_metadata.json | 3 + .../coreusagegroup/zz_models.go | 46 + .../coreusagegroup/zz_models_serde.go | 225 + .../coreusagegroup/zz_options.go | 35 + .../coreusagegroup/zz_responses.go | 31 + .../coreusagegroup/zz_usage_client.go | 56 + .../zz_usagemodelinoperation_client.go | 224 + .../zz_usagenamespaceusage_client.go | 65 + .../coreusagegroup/zz_version.go | 10 + .../defaultvaluegroup/LICENSE.txt | 21 + .../clientdefaultvalue_client_test.go | 53 + .../fake/zz_clientdefaultvalue_server.go | 232 + .../defaultvaluegroup/fake/zz_internal.go | 49 + .../defaultvaluegroup/go.mod | 17 + .../defaultvaluegroup/go.sum | 25 + .../defaultvaluegroup/testdata/_metadata.json | 3 + .../zz_clientdefaultvalue_client.go | 234 + .../defaultvaluegroup/zz_models.go | 20 + .../defaultvaluegroup/zz_models_serde.go | 81 + .../defaultvaluegroup/zz_options.go | 38 + .../defaultvaluegroup/zz_responses.go | 26 + .../defaultvaluegroup/zz_version.go | 10 + .../emptystringgroup/LICENSE.txt | 21 + ...eserializeemptystringasnull_client_test.go | 19 + .../zz_deserializeemptystringasnull_server.go | 101 + .../emptystringgroup/fake/zz_internal.go | 20 + .../emptystringgroup/go.mod | 17 + .../emptystringgroup/go.sum | 25 + .../emptystringgroup/testdata/_metadata.json | 3 + .../zz_deserializeemptystringasnull_client.go | 89 + .../emptystringgroup/zz_models.go | 11 + .../emptystringgroup/zz_models_serde.go | 61 + .../emptystringgroup/zz_options.go | 11 + .../emptystringgroup/zz_responses.go | 11 + .../emptystringgroup/zz_version.go | 10 + .../flattengroup/LICENSE.txt | 21 + .../fake/zz_flattenproperty_server.go | 192 + .../flattengroup/fake/zz_internal.go | 20 + .../flattenproperty_client_test.go | 87 + .../client-generator-core/flattengroup/go.mod | 17 + .../client-generator-core/flattengroup/go.sum | 25 + .../flattengroup/testdata/_metadata.json | 3 + .../flattengroup/zz_flattenproperty_client.go | 243 + .../flattengroup/zz_models.go | 67 + .../flattengroup/zz_models_serde.go | 263 + .../flattengroup/zz_options.go | 29 + .../flattengroup/zz_responses.go | 29 + .../flattengroup/zz_version.go | 10 + .../hierarchygroup/LICENSE.txt | 21 + .../fake/zz_hierarchybuilding_server.go | 87 + ...ierarchybuildinganimaloperations_server.go | 142 + ...z_hierarchybuildingdogoperations_server.go | 105 + ...z_hierarchybuildingpetoperations_server.go | 142 + .../hierarchygroup/fake/zz_internal.go | 44 + .../fake/zz_polymorphic_helpers.go | 54 + .../hierarchygroup/go.mod | 17 + .../hierarchygroup/go.sum | 25 + .../hierarchygroup/hierarchy_client_test.go | 109 + .../hierarchygroup/testdata/_metadata.json | 3 + .../zz_hierarchybuilding_client.go | 64 + ...ierarchybuildinganimaloperations_client.go | 120 + ...z_hierarchybuildingdogoperations_client.go | 70 + ...z_hierarchybuildingpetoperations_client.go | 120 + .../hierarchygroup/zz_interfaces.go | 24 + .../hierarchygroup/zz_models.go | 69 + .../hierarchygroup/zz_models_serde.go | 137 + .../hierarchygroup/zz_options.go | 35 + .../hierarchygroup/zz_polymorphic_helpers.go | 51 + .../hierarchygroup/zz_responses.go | 30 + .../hierarchygroup/zz_responses_serde.go | 45 + .../hierarchygroup/zz_version.go | 10 + .../nextlinkverbgroup/LICENSE.txt | 21 + .../nextlinkverbgroup/fake/zz_internal.go | 56 + .../fake/zz_nextlinkverb_server.go | 113 + .../nextlinkverbgroup/go.mod | 17 + .../nextlinkverbgroup/go.sum | 25 + .../nextlinkverb_client_test.go | 38 + .../nextlinkverbgroup/testdata/_metadata.json | 3 + .../nextlinkverbgroup/zz_models.go | 20 + .../nextlinkverbgroup/zz_models_serde.go | 90 + .../zz_nextlinkverb_client.go | 90 + .../nextlinkverbgroup/zz_options.go | 10 + .../nextlinkverbgroup/zz_responses.go | 11 + .../nextlinkverbgroup/zz_version.go | 10 + .../overridegroup/LICENSE.txt | 21 + .../overridegroup/fake/zz_internal.go | 39 + .../overridegroup/fake/zz_override_server.go | 96 + .../fake/zz_overridegroupparameters_server.go | 106 + ..._overrideremoveoptionalparameter_server.go | 121 + .../zz_overridereorderparameters_server.go | 117 + ...overriderequireoptionalparameter_server.go | 117 + .../overridegroup/go.mod | 17 + .../overridegroup/go.sum | 25 + .../overridegroupparameters_client_test.go | 23 + .../overrideremoveoptionalparameter_test.go | 21 + .../overridereorderparameters_client_test.go | 20 + .../overriderequireoptionalparameter_test.go | 20 + .../overridegroup/testdata/_metadata.json | 3 + .../overridegroup/zz_options.go | 35 + .../overridegroup/zz_override_client.go | 72 + .../zz_overridegroupparameters_client.go | 61 + ..._overrideremoveoptionalparameter_client.go | 67 + .../zz_overridereorderparameters_client.go | 66 + ...overriderequireoptionalparameter_client.go | 66 + .../overridegroup/zz_responses.go | 25 + .../overridegroup/zz_version.go | 10 + .../azure/core/azurepagegroup/LICENSE.txt | 21 + .../core/azurepagegroup/custom_client_test.go | 145 + .../core/azurepagegroup/fake/zz_internal.go | 72 + .../azurepagegroup/fake/zz_page_server.go | 257 + .../fake/zz_pagetwomodelsaspageitem_server.go | 148 + .../azure/core/azurepagegroup/go.mod | 17 + .../azure/core/azurepagegroup/go.sum | 25 + .../azurepagegroup/testdata/_metadata.json | 6 + .../twomodelsaspageitem_client_test.go | 49 + .../azure/core/azurepagegroup/zz_constants.go | 27 + .../azure/core/azurepagegroup/zz_models.go | 87 + .../core/azurepagegroup/zz_models_serde.go | 311 + .../azure/core/azurepagegroup/zz_options.go | 40 + .../core/azurepagegroup/zz_page_client.go | 259 + .../zz_pagetwomodelsaspageitem_client.go | 123 + .../azure/core/azurepagegroup/zz_responses.go | 40 + .../azure/core/azurepagegroup/zz_version.go | 10 + .../azure/core/basicgroup/LICENSE.txt | 21 + .../core/basicgroup/basic_client_test.go | 139 + .../core/basicgroup/fake/zz_basic_server.go | 421 + .../azure/core/basicgroup/fake/zz_internal.go | 83 + .../azure/core/basicgroup/go.mod | 17 + .../azure/core/basicgroup/go.sum | 25 + .../core/basicgroup/testdata/_metadata.json | 6 + .../azure/core/basicgroup/zz_basic_client.go | 443 + .../azure/core/basicgroup/zz_constants.go | 9 + .../azure/core/basicgroup/zz_models.go | 48 + .../azure/core/basicgroup/zz_models_serde.go | 164 + .../azure/core/basicgroup/zz_options.go | 59 + .../azure/core/basicgroup/zz_responses.go | 45 + .../azure/core/basicgroup/zz_version.go | 10 + .../azure/core/coremodelgroup/LICENSE.txt | 21 + .../core/coremodelgroup/fake/zz_internal.go | 31 + .../coremodelgroup/fake/zz_model_server.go | 69 + ...zz_modelazurecoreembeddingvector_server.go | 159 + .../azure/core/coremodelgroup/go.mod | 17 + .../azure/core/coremodelgroup/go.sum | 25 + ...delazurecoreembeddingvector_client_test.go | 43 + .../coremodelgroup/testdata/_metadata.json | 6 + .../core/coremodelgroup/zz_model_client.go | 48 + ...zz_modelazurecoreembeddingvector_client.go | 157 + .../azure/core/coremodelgroup/zz_models.go | 10 + .../core/coremodelgroup/zz_models_serde.go | 59 + .../azure/core/coremodelgroup/zz_options.go | 23 + .../azure/core/coremodelgroup/zz_responses.go | 20 + .../azure/core/coremodelgroup/zz_version.go | 10 + .../azure/core/corescalargroup/LICENSE.txt | 21 + .../azurelocationscalar_client_test.go | 57 + .../core/corescalargroup/fake/zz_internal.go | 39 + .../corescalargroup/fake/zz_scalar_server.go | 69 + .../zz_scalarazurelocationscalar_server.go | 210 + .../azure/core/corescalargroup/go.mod | 17 + .../azure/core/corescalargroup/go.sum | 25 + .../corescalargroup/testdata/_metadata.json | 6 + .../azure/core/corescalargroup/zz_models.go | 10 + .../core/corescalargroup/zz_models_serde.go | 59 + .../azure/core/corescalargroup/zz_options.go | 35 + .../core/corescalargroup/zz_responses.go | 30 + .../core/corescalargroup/zz_scalar_client.go | 48 + .../zz_scalarazurelocationscalar_client.go | 234 + .../azure/core/corescalargroup/zz_version.go | 10 + .../azure/core/lro/lrorpcgroup/LICENSE.txt | 21 + .../core/lro/lrorpcgroup/fake/zz_internal.go | 56 + .../lro/lrorpcgroup/fake/zz_rpc_server.go | 120 + .../azure/core/lro/lrorpcgroup/go.mod | 17 + .../azure/core/lro/lrorpcgroup/go.sum | 25 + .../core/lro/lrorpcgroup/rcp_client_test.go | 49 + .../lro/lrorpcgroup/testdata/_metadata.json | 6 + .../core/lro/lrorpcgroup/zz_constants.go | 9 + .../azure/core/lro/lrorpcgroup/zz_models.go | 17 + .../core/lro/lrorpcgroup/zz_models_serde.go | 86 + .../azure/core/lro/lrorpcgroup/zz_options.go | 11 + .../core/lro/lrorpcgroup/zz_responses.go | 11 + .../core/lro/lrorpcgroup/zz_rpc_client.go | 118 + .../azure/core/lro/lrorpcgroup/zz_version.go | 10 + .../azure/core/lro/lrostdgroup/LICENSE.txt | 21 + .../core/lro/lrostdgroup/fake/zz_internal.go | 56 + .../lrostdgroup/fake/zz_standard_server.go | 229 + .../azure/core/lro/lrostdgroup/go.mod | 17 + .../azure/core/lro/lrostdgroup/go.sum | 25 + .../lro/lrostdgroup/standard_client_test.go | 85 + .../lro/lrostdgroup/testdata/_metadata.json | 6 + .../core/lro/lrostdgroup/zz_constants.go | 9 + .../azure/core/lro/lrostdgroup/zz_models.go | 23 + .../core/lro/lrostdgroup/zz_models_serde.go | 94 + .../azure/core/lro/lrostdgroup/zz_options.go | 24 + .../core/lro/lrostdgroup/zz_responses.go | 22 + .../lro/lrostdgroup/zz_standard_client.go | 260 + .../azure/core/lro/lrostdgroup/zz_version.go | 10 + .../azure/core/traitsgroup/LICENSE.txt | 21 + .../core/traitsgroup/fake/zz_internal.go | 57 + .../core/traitsgroup/fake/zz_traits_server.go | 219 + .../azure/core/traitsgroup/go.mod | 17 + .../azure/core/traitsgroup/go.sum | 25 + .../core/traitsgroup/testdata/_metadata.json | 6 + .../core/traitsgroup/traits_client_test.go | 49 + .../azure/core/traitsgroup/zz_constants.go | 30 + .../azure/core/traitsgroup/zz_models.go | 26 + .../azure/core/traitsgroup/zz_models_serde.go | 117 + .../azure/core/traitsgroup/zz_options.go | 34 + .../azure/core/traitsgroup/zz_responses.go | 27 + .../core/traitsgroup/zz_traits_client.go | 194 + .../azure/core/traitsgroup/zz_version.go | 10 + .../encode/encodedurationgroup/LICENSE.txt | 21 + .../duration_client_test.go | 23 + .../fake/zz_duration_server.go | 105 + .../encodedurationgroup/fake/zz_internal.go | 20 + .../azure/encode/encodedurationgroup/go.mod | 17 + .../azure/encode/encodedurationgroup/go.sum | 25 + .../testdata/_metadata.json | 3 + .../encodedurationgroup/zz_duration_client.go | 82 + .../encode/encodedurationgroup/zz_models.go | 10 + .../encodedurationgroup/zz_models_serde.go | 59 + .../encode/encodedurationgroup/zz_options.go | 10 + .../encodedurationgroup/zz_responses.go | 10 + .../encode/encodedurationgroup/zz_version.go | 10 + .../example/examplebasicgroup/LICENSE.txt | 21 + .../basicserviceoperationgroup_client_test.go | 32 + .../fake/zz_azureexample_server.go | 106 + .../examplebasicgroup/fake/zz_internal.go | 28 + .../azure/example/examplebasicgroup/go.mod | 17 + .../azure/example/examplebasicgroup/go.sum | 25 + .../examplebasicgroup/testdata/_metadata.json | 6 + .../zz_azureexample_client.go | 106 + .../example/examplebasicgroup/zz_constants.go | 22 + .../example/examplebasicgroup/zz_models.go | 27 + .../examplebasicgroup/zz_models_serde.go | 145 + .../example/examplebasicgroup/zz_options.go | 10 + .../example/examplebasicgroup/zz_responses.go | 10 + .../example/examplebasicgroup/zz_version.go | 10 + .../azure/payload/pageablegroup/LICENSE.txt | 21 + .../payload/pageablegroup/fake/zz_internal.go | 67 + .../pageablegroup/fake/zz_pageable_server.go | 131 + .../azure/payload/pageablegroup/go.mod | 17 + .../azure/payload/pageablegroup/go.sum | 25 + .../pageablegroup/pageable_client_test.go | 38 + .../pageablegroup/testdata/_metadata.json | 3 + .../azure/payload/pageablegroup/zz_models.go | 20 + .../payload/pageablegroup/zz_models_serde.go | 90 + .../azure/payload/pageablegroup/zz_options.go | 11 + .../pageablegroup/zz_pageable_client.go | 95 + .../payload/pageablegroup/zz_responses.go | 11 + .../azure/payload/pageablegroup/zz_version.go | 10 + .../armmultipleservicegroup/LICENSE.txt | 21 + .../disk_client_test.go | 51 + .../fake/zz_disks_server.go | 175 + .../fake/zz_internal.go | 64 + .../fake/zz_server_factory.go | 73 + .../fake/zz_virtualmachines_server.go | 175 + .../armmultipleservicegroup/go.mod | 17 + .../armmultipleservicegroup/go.sum | 25 + .../testdata/_metadata.json | 7 + .../armmultipleservicegroup/utils_test.go | 43 + .../virtual_machine_client_test.go | 51 + .../zz_client_factory.go | 49 + .../armmultipleservicegroup/zz_constants.go | 55 + .../zz_disks_client.go | 181 + .../armmultipleservicegroup/zz_models.go | 87 + .../zz_models_serde.go | 265 + .../armmultipleservicegroup/zz_options.go | 28 + .../armmultipleservicegroup/zz_responses.go | 29 + .../armmultipleservicegroup/zz_version.go | 10 + .../zz_virtualmachines_client.go | 183 + .../armmultisharedmodelsgroup/LICENSE.txt | 21 + .../fake/zz_internal.go | 64 + .../fake/zz_server_factory.go | 75 + .../fake/zz_storageaccounts_server.go | 175 + .../fake/zz_virtualmachines_server.go | 175 + .../armmultisharedmodelsgroup/go.mod | 17 + .../armmultisharedmodelsgroup/go.sum | 25 + .../storage_accounts_client_test.go | 63 + .../testdata/_metadata.json | 7 + .../armmultisharedmodelsgroup/utils_test.go | 42 + .../virtual_machines_client_test.go | 63 + .../zz_client_factory.go | 49 + .../armmultisharedmodelsgroup/zz_constants.go | 55 + .../armmultisharedmodelsgroup/zz_models.go | 105 + .../zz_models_serde.go | 308 + .../armmultisharedmodelsgroup/zz_options.go | 29 + .../armmultisharedmodelsgroup/zz_responses.go | 29 + .../zz_storageaccounts_client.go | 181 + .../armmultisharedmodelsgroup/zz_version.go | 10 + .../zz_virtualmachines_client.go | 183 + .../commonpropsgroup/LICENSE.txt | 21 + .../commonpropsgroup/error_client_test.go | 49 + .../fake/zz_armresourceidentifiers_server.go | 160 + .../commonpropsgroup/fake/zz_error_server.go | 160 + .../commonpropsgroup/fake/zz_internal.go | 31 + .../fake/zz_managedidentity_server.go | 203 + .../fake/zz_server_factory.go | 82 + .../resource-manager/commonpropsgroup/go.mod | 17 + .../resource-manager/commonpropsgroup/go.sum | 25 + .../managedidentity_client_test.go | 112 + .../commonpropsgroup/testdata/_metadata.json | 6 + .../commonpropsgroup/utils_test.go | 48 + .../zz_armresourceidentifiers_client.go | 173 + .../commonpropsgroup/zz_client_factory.go | 57 + .../commonpropsgroup/zz_constants.go | 78 + .../commonpropsgroup/zz_error_client.go | 173 + .../zz_managedidentity_client.go | 240 + .../commonpropsgroup/zz_models.go | 163 + .../commonpropsgroup/zz_models_serde.go | 437 + .../commonpropsgroup/zz_options.go | 44 + .../commonpropsgroup/zz_responses.go | 47 + .../commonpropsgroup/zz_version.go | 10 + .../largeheadergroup/LICENSE.txt | 21 + .../largeheadergroup/fake/zz_internal.go | 64 + .../fake/zz_largeheaders_server.go | 132 + .../fake/zz_server_factory.go | 64 + .../resource-manager/largeheadergroup/go.mod | 17 + .../resource-manager/largeheadergroup/go.sum | 25 + .../largeheaders_client_test.go | 25 + .../largeheadergroup/testdata/_metadata.json | 6 + .../largeheadergroup/utils_test.go | 42 + .../largeheadergroup/zz_client_factory.go | 41 + .../largeheadergroup/zz_constants.go | 9 + .../zz_largeheaders_client.go | 113 + .../largeheadergroup/zz_models.go | 10 + .../largeheadergroup/zz_models_serde.go | 59 + .../largeheadergroup/zz_options.go | 11 + .../largeheadergroup/zz_responses.go | 10 + .../largeheadergroup/zz_version.go | 10 + .../methodsubscriptionidgroup/LICENSE.txt | 21 + .../fake/zz_internal.go | 64 + .../fake/zz_operations_server.go | 113 + ..._resourcegroupresourceoperations_server.go | 199 + .../fake/zz_server_factory.go | 100 + ..._subscriptionresource1operations_server.go | 199 + ..._subscriptionresource2operations_server.go | 199 + ...z_subscriptionresourceoperations_server.go | 199 + .../methodsubscriptionidgroup/go.mod | 17 + .../methodsubscriptionidgroup/go.sum | 25 + .../operations_client_test.go | 37 + ...urcegroupresourceoperations_client_test.go | 60 + ...criptionresource1operations_client_test.go | 69 + ...criptionresource2operations_client_test.go | 58 + ...scriptionresourceoperations_client_test.go | 58 + .../testdata/_metadata.json | 6 + .../methodsubscriptionidgroup/utils_test.go | 41 + .../zz_client_factory.go | 69 + .../methodsubscriptionidgroup/zz_constants.go | 91 + .../methodsubscriptionidgroup/zz_models.go | 194 + .../zz_models_serde.go | 526 + .../zz_operations_client.go | 85 + .../methodsubscriptionidgroup/zz_options.go | 82 + ..._resourcegroupresourceoperations_client.go | 225 + .../methodsubscriptionidgroup/zz_responses.go | 79 + ..._subscriptionresource1operations_client.go | 210 + ..._subscriptionresource2operations_client.go | 210 + ...z_subscriptionresourceoperations_client.go | 210 + .../methodsubscriptionidgroup/zz_version.go | 10 + .../nonresourcegroup/LICENSE.txt | 21 + .../nonresourcegroup/fake/zz_internal.go | 31 + .../fake/zz_nonresourceoperations_server.go | 160 + .../fake/zz_server_factory.go | 66 + .../resource-manager/nonresourcegroup/go.mod | 17 + .../resource-manager/nonresourcegroup/go.sum | 25 + .../nonresourceoperations_client_test.go | 33 + .../nonresourcegroup/testdata/_metadata.json | 6 + .../nonresourcegroup/utils_test.go | 41 + .../nonresourcegroup/zz_client_factory.go | 41 + .../nonresourcegroup/zz_constants.go | 9 + .../nonresourcegroup/zz_models.go | 17 + .../nonresourcegroup/zz_models_serde.go | 67 + .../zz_nonresourceoperations_client.go | 173 + .../nonresourcegroup/zz_options.go | 15 + .../nonresourcegroup/zz_responses.go | 17 + .../nonresourcegroup/zz_version.go | 10 + .../resource-manager/resources/LICENSE.txt | 21 + .../extensionsresources_client_test.go | 435 + .../fake/zz_extensionsresources_server.go | 303 + .../resources/fake/zz_internal.go | 64 + .../fake/zz_locationresources_server.go | 290 + .../resources/fake/zz_nested_server.go | 349 + .../resources/fake/zz_server_factory.go | 96 + .../resources/fake/zz_singleton_server.go | 252 + .../resources/fake/zz_toplevel_server.go | 413 + .../azure/resource-manager/resources/go.mod | 17 + .../azure/resource-manager/resources/go.sum | 25 + .../locationresources_client_test.go | 123 + .../resources/nested_client_test.go | 117 + .../resources/singleton_client_test.go | 106 + .../resources/testdata/_metadata.json | 6 + .../resources/toplevel_client_test.go | 155 + .../resource-manager/resources/utils_test.go | 42 + .../resources/zz_client_factory.go | 69 + .../resources/zz_constants.go | 61 + .../zz_extensionsresources_client.go | 337 + .../resources/zz_locationresources_client.go | 350 + .../resource-manager/resources/zz_models.go | 231 + .../resources/zz_models_serde.go | 681 ++ .../resources/zz_nested_client.go | 410 + .../resource-manager/resources/zz_options.go | 153 + .../resources/zz_responses.go | 156 + .../resources/zz_singleton_client.go | 292 + .../resources/zz_toplevel_client.go | 494 + .../resource-manager/resources/zz_version.go | 10 + .../templatesgroup/LICENSE.txt | 21 + .../checknameavailability_client_test.go | 48 + .../fake/zz_checknameavailability_server.go | 152 + .../templatesgroup/fake/zz_internal.go | 64 + .../templatesgroup/fake/zz_lro_server.go | 292 + .../fake/zz_lropaging_server.go | 132 + .../fake/zz_operations_server.go | 113 + .../fake/zz_optionalbody_server.go | 251 + .../templatesgroup/fake/zz_server_factory.go | 94 + .../resource-manager/templatesgroup/go.mod | 17 + .../resource-manager/templatesgroup/go.sum | 25 + .../templatesgroup/lro_client_test.go | 91 + .../templatesgroup/lropaging_client_test.go | 66 + .../optionalbody_client_test.go | 113 + .../templatesgroup/testdata/_metadata.json | 6 + .../templatesgroup/utils_test.go | 44 + .../zz_checknameavailability_client.go | 163 + .../templatesgroup/zz_client_factory.go | 72 + .../templatesgroup/zz_constants.go | 88 + .../templatesgroup/zz_lro_client.go | 329 + .../templatesgroup/zz_lropaging_client.go | 139 + .../templatesgroup/zz_models.go | 250 + .../templatesgroup/zz_models_serde.go | 747 ++ .../templatesgroup/zz_operations_client.go | 85 + .../templatesgroup/zz_optionalbody_client.go | 300 + .../templatesgroup/zz_options.go | 74 + .../templatesgroup/zz_responses.go | 72 + .../templatesgroup/zz_responses_serde.go | 12 + .../templatesgroup/zz_version.go | 10 + .../xmsclientreqidgroup/LICENSE.txt | 21 + .../xmsclientreqidgroup/fake/zz_internal.go | 38 + .../fake/zz_xmsclientrequestid_server.go | 108 + .../xmsclientreqidgroup/go.mod | 17 + .../xmsclientreqidgroup/go.sum | 25 + .../testdata/_metadata.json | 3 + .../xmsclientrequestid_client_test.go | 50 + .../xmsclientreqidgroup/zz_options.go | 10 + .../xmsclientreqidgroup/zz_responses.go | 10 + .../xmsclientreqidgroup/zz_version.go | 10 + .../zz_xmsclientrequestid_client.go | 80 + .../previewversiongroup/LICENSE.txt | 21 + .../previewversiongroup/fake/zz_internal.go | 30 + .../fake/zz_previewversion_server.go | 187 + .../versioning/previewversiongroup/go.mod | 17 + .../versioning/previewversiongroup/go.sum | 25 + .../previewversion_client_test.go | 44 + .../testdata/_metadata.json | 6 + .../previewversiongroup/zz_constants.go | 9 + .../previewversiongroup/zz_models.go | 28 + .../previewversiongroup/zz_models_serde.go | 121 + .../previewversiongroup/zz_options.go | 22 + .../zz_previewversion_client.go | 218 + .../previewversiongroup/zz_responses.go | 22 + .../previewversiongroup/zz_version.go | 10 + .../LICENSE.txt | 21 + .../fake/zz_internal.go | 30 + .../fake/zz_previewversion_server.go | 146 + .../previewversiongroupspecificversion/go.mod | 17 + .../previewversiongroupspecificversion/go.sum | 25 + .../previewversion_client_test.go | 25 + .../testdata/_metadata.json | 6 + .../zz_constants.go | 9 + .../zz_models.go | 19 + .../zz_models_serde.go | 90 + .../zz_options.go | 15 + .../zz_previewversion_client.go | 158 + .../zz_responses.go | 16 + .../zz_version.go | 10 + .../client/clientnamespacegroup/LICENSE.txt | 21 + .../clientnamespacefirst_client_test.go | 22 + .../clientnamespacesecond_client_test.go | 21 + .../fake/zz_clientnamespacefirst_server.go | 101 + .../fake/zz_clientnamespacesecond_server.go | 101 + .../clientnamespacegroup/fake/zz_internal.go | 20 + .../client/clientnamespacegroup/go.mod | 17 + .../client/clientnamespacegroup/go.sum | 25 + .../testdata/_metadata.json | 3 + .../zz_clientnamespacefirst_client.go | 89 + .../zz_clientnamespacesecond_client.go | 89 + .../clientnamespacegroup/zz_constants.go | 18 + .../client/clientnamespacegroup/zz_models.go | 15 + .../clientnamespacegroup/zz_models_serde.go | 86 + .../client/clientnamespacegroup/zz_options.go | 17 + .../clientnamespacegroup/zz_responses.go | 15 + .../client/clientnamespacegroup/zz_version.go | 10 + .../naming/enumconflictgroup/LICENSE.txt | 21 + ...enumconflictfirstoperations_client_test.go | 29 + ...numconflictsecondoperations_client_test.go | 29 + .../fake/zz_enumconflict_server.go | 78 + .../zz_enumconflictfirstoperations_server.go | 105 + .../zz_enumconflictsecondoperations_server.go | 105 + .../enumconflictgroup/fake/zz_internal.go | 31 + .../client/naming/enumconflictgroup/go.mod | 17 + .../client/naming/enumconflictgroup/go.sum | 25 + .../enumconflictgroup/testdata/_metadata.json | 3 + .../naming/enumconflictgroup/zz_constants.go | 41 + .../zz_enumconflict_client.go | 56 + .../zz_enumconflictfirstoperations_client.go | 70 + .../zz_enumconflictsecondoperations_client.go | 70 + .../naming/enumconflictgroup/zz_models.go | 21 + .../enumconflictgroup/zz_models_serde.go | 94 + .../naming/enumconflictgroup/zz_options.go | 17 + .../naming/enumconflictgroup/zz_responses.go | 15 + .../naming/enumconflictgroup/zz_version.go | 10 + .../client/naminggroup/LICENSE.txt | 21 + .../client/naminggroup/fake/zz_internal.go | 39 + .../naminggroup/fake/zz_naming_server.go | 181 + .../fake/zz_namingheader_server.go | 129 + .../naminggroup/fake/zz_namingmodel_server.go | 134 + .../fake/zz_namingproperty_server.go | 163 + .../fake/zz_namingunionenum_server.go | 134 + .../client/naminggroup/fakes_test.go | 61 + .../client/naminggroup/go.mod | 17 + .../client/naminggroup/go.sum | 25 + .../client/naminggroup/naming_client_test.go | 112 + .../naminggroup/testdata/_metadata.json | 3 + .../client/naminggroup/zz_constants.go | 33 + .../client/naminggroup/zz_models.go | 30 + .../client/naminggroup/zz_models_serde.go | 167 + .../client/naminggroup/zz_naming_client.go | 147 + .../naminggroup/zz_namingheader_client.go | 99 + .../naminggroup/zz_namingmodel_client.go | 96 + .../naminggroup/zz_namingproperty_client.go | 135 + .../naminggroup/zz_namingunionenum_client.go | 98 + .../client/naminggroup/zz_options.go | 63 + .../client/naminggroup/zz_responses.go | 60 + .../client/naminggroup/zz_version.go | 10 + .../client/overloadgroup/LICENSE.txt | 21 + .../client/overloadgroup/fake/zz_internal.go | 20 + .../overloadgroup/fake/zz_overload_server.go | 138 + .../client/overloadgroup/go.mod | 17 + .../client/overloadgroup/go.sum | 25 + .../overloadgroup/overload_client_test.go | 56 + .../overloadgroup/testdata/_metadata.json | 3 + .../client/overloadgroup/zz_models.go | 16 + .../client/overloadgroup/zz_models_serde.go | 67 + .../client/overloadgroup/zz_options.go | 15 + .../overloadgroup/zz_overload_client.go | 140 + .../client/overloadgroup/zz_responses.go | 15 + .../client/overloadgroup/zz_version.go | 10 + .../clientopgroup/first_client_test.go | 21 + .../clientopgroup/firstgroup3_client_test.go | 30 + .../clientopgroup/firstgroup4_client_test.go | 21 + .../clientopgroup/second_client_test.go | 21 + .../clientopgroup/secondgroup5_client_test.go | 21 + .../client/structure/defaultgroup/LICENSE.txt | 21 + .../defaultgroup/fake/zz_internal.go | 31 + .../defaultgroup/fake/zz_service_server.go | 171 + .../defaultgroup/fake/zz_servicebar_server.go | 126 + .../defaultgroup/fake/zz_servicebaz_server.go | 69 + .../fake/zz_servicebazfoo_server.go | 101 + .../defaultgroup/fake/zz_servicefoo_server.go | 126 + .../defaultgroup/fake/zz_servicequx_server.go | 128 + .../fake/zz_servicequxbar_server.go | 101 + .../client/structure/defaultgroup/go.mod | 17 + .../client/structure/defaultgroup/go.sum | 25 + .../defaultgroup/service_client_test.go | 28 + .../defaultgroup/servicebar_client_test.go | 36 + .../defaultgroup/servicefoo_client_test.go | 36 + .../defaultgroup/servicequx_client_test.go | 20 + .../defaultgroup/testdata/_metadata.json | 3 + .../structure/defaultgroup/zz_constants.go | 26 + .../structure/defaultgroup/zz_options.go | 50 + .../structure/defaultgroup/zz_responses.go | 50 + .../defaultgroup/zz_service_client.go | 154 + .../defaultgroup/zz_servicebar_client.go | 88 + .../defaultgroup/zz_servicebaz_client.go | 22 + .../defaultgroup/zz_servicebazfoo_client.go | 54 + .../defaultgroup/zz_servicefoo_client.go | 88 + .../defaultgroup/zz_servicequx_client.go | 62 + .../defaultgroup/zz_servicequxbar_client.go | 54 + .../structure/defaultgroup/zz_version.go | 10 + .../multiclientgroup/clienta_client_test.go | 36 + .../multiclientgroup/clientb_client_test.go | 36 + .../renamedopgroup/group_client_test.go | 36 + .../renamedoperation_client_test.go | 36 + .../twoopgroup/group1_client_test.go | 36 + .../twoopgroup/group2_client_test.go | 36 + .../resiliency/srvdrivennewgroup/LICENSE.txt | 21 + .../srvdrivennewgroup/fake/zz_internal.go | 30 + .../fake/zz_resiliencyservicedriven_server.go | 202 + .../resiliency/srvdrivennewgroup/go.mod | 17 + .../resiliency/srvdrivennewgroup/go.sum | 25 + .../resiliencyservicedriven_client_test.go | 96 + .../srvdrivennewgroup/testdata/_metadata.json | 6 + .../srvdrivennewgroup/zz_options.go | 35 + .../zz_resiliencyservicedriven_client.go | 231 + .../srvdrivennewgroup/zz_responses.go | 26 + .../srvdrivennewgroup/zz_version.go | 10 + .../resiliency/srvdrivenoldgroup/LICENSE.txt | 21 + .../srvdrivenoldgroup/fake/zz_internal.go | 30 + .../fake/zz_resiliencyservicedriven_server.go | 160 + .../resiliency/srvdrivenoldgroup/go.mod | 17 + .../resiliency/srvdrivenoldgroup/go.sum | 25 + .../resiliencyservicedriven_client_test.go | 65 + .../srvdrivenoldgroup/testdata/_metadata.json | 6 + .../srvdrivenoldgroup/zz_options.go | 24 + .../zz_resiliencyservicedriven_client.go | 176 + .../srvdrivenoldgroup/zz_responses.go | 21 + .../srvdrivenoldgroup/zz_version.go | 10 + .../service/multipleservicesgroup/LICENSE.txt | 21 + .../multipleservicesgroup/fake/zz_internal.go | 31 + .../fake/zz_servicea_server.go | 78 + .../fake/zz_serviceaoperations_server.go | 101 + .../fake/zz_serviceasubnamespace_server.go | 101 + .../fake/zz_serviceb_server.go | 78 + .../fake/zz_serviceboperations_server.go | 101 + .../fake/zz_servicebsubnamespace_server.go | 101 + .../multipleservicesgroup/fakes_test.go | 88 + .../service/multipleservicesgroup/go.mod | 17 + .../service/multipleservicesgroup/go.sum | 25 + .../multipleservices_client_test.go | 40 + .../testdata/_metadata.json | 7 + .../multipleservicesgroup/zz_constants.go | 10 + .../multipleservicesgroup/zz_options.go | 25 + .../multipleservicesgroup/zz_responses.go | 25 + .../zz_servicea_client.go | 57 + .../zz_serviceaoperations_client.go | 60 + .../zz_serviceasubnamespace_client.go | 61 + .../zz_serviceb_client.go | 57 + .../zz_serviceboperations_client.go | 60 + .../zz_servicebsubnamespace_client.go | 61 + .../multipleservicesgroup/zz_version.go | 10 + .../service/multiservicegroup/LICENSE.txt | 21 + .../multiservicegroup/combined_client_test.go | 24 + .../fake/zz_combined_server.go | 78 + .../fake/zz_combinedbar_server.go | 101 + .../fake/zz_combinedfoo_server.go | 101 + .../multiservicegroup/fake/zz_internal.go | 31 + .../service/multiservicegroup/go.mod | 17 + .../service/multiservicegroup/go.sum | 25 + .../multiservicegroup/testdata/_metadata.json | 7 + .../multiservicegroup/zz_combined_client.go | 56 + .../zz_combinedbar_client.go | 60 + .../zz_combinedfoo_client.go | 60 + .../service/multiservicegroup/zz_constants.go | 10 + .../service/multiservicegroup/zz_options.go | 15 + .../service/multiservicegroup/zz_responses.go | 15 + .../service/multiservicegroup/zz_version.go | 10 + .../authentication/apikeygroup/LICENSE.txt | 21 + .../apikeygroup/apikey_client_test.go | 31 + .../apikeygroup/custom_client.go | 27 + .../apikeygroup/fake/zz_apikey_server.go | 126 + .../apikeygroup/fake/zz_internal.go | 20 + .../authentication/apikeygroup/go.mod | 17 + .../authentication/apikeygroup/go.sum | 25 + .../apikeygroup/testdata/_metadata.json | 3 + .../authentication/apikeygroup/version.go | 8 + .../apikeygroup/zz_apikey_client.go | 93 + .../authentication/apikeygroup/zz_options.go | 15 + .../apikeygroup/zz_responses.go | 15 + .../authentication/apikeygroup/zz_version.go | 10 + .../http/customgroup/LICENSE.txt | 21 + .../http/customgroup/custom_client.go | 28 + .../http/customgroup/custom_client_test.go | 29 + .../http/customgroup/fake/zz_custom_server.go | 126 + .../http/customgroup/fake/zz_internal.go | 20 + .../authentication/http/customgroup/go.mod | 17 + .../authentication/http/customgroup/go.sum | 25 + .../http/customgroup/testdata/_metadata.json | 3 + .../http/customgroup/version.go | 8 + .../http/customgroup/zz_custom_client.go | 93 + .../http/customgroup/zz_options.go | 15 + .../http/customgroup/zz_responses.go | 15 + .../http/customgroup/zz_version.go | 10 + .../authentication/oauth2group/LICENSE.txt | 21 + .../oauth2group/fake/zz_internal.go | 20 + .../oauth2group/fake/zz_oauth2_server.go | 126 + .../authentication/oauth2group/go.mod | 17 + .../authentication/oauth2group/go.sum | 25 + .../oauth2group/oauth2_client_test.go | 48 + .../oauth2group/testdata/_metadata.json | 3 + .../oauth2group/zz_cloud_config.go | 16 + .../oauth2group/zz_oauth2_client.go | 130 + .../authentication/oauth2group/zz_options.go | 15 + .../oauth2group/zz_responses.go | 15 + .../authentication/oauth2group/zz_version.go | 10 + .../authentication/unionauthgroup/LICENSE.txt | 21 + .../unionauthgroup/fake/zz_internal.go | 20 + .../unionauthgroup/fake/zz_union_server.go | 126 + .../authentication/unionauthgroup/go.mod | 17 + .../authentication/unionauthgroup/go.sum | 25 + .../unionauthgroup/testdata/_metadata.json | 3 + .../unionauthgroup/union_client_test.go | 37 + .../unionauthgroup/zz_cloud_config.go | 16 + .../unionauthgroup/zz_options.go | 15 + .../unionauthgroup/zz_responses.go | 15 + .../unionauthgroup/zz_union_client.go | 130 + .../unionauthgroup/zz_version.go | 10 + test/http-specs/encode/bytesgroup/LICENSE.txt | 21 + .../encode/bytesgroup/custom_client_test.go | 225 + .../encode/bytesgroup/fake/zz_bytes_server.go | 105 + .../bytesgroup/fake/zz_bytesheader_server.go | 198 + .../fake/zz_bytesproperty_server.go | 192 + .../bytesgroup/fake/zz_bytesquery_server.go | 202 + .../fake/zz_bytesrequestbody_server.go | 210 + .../fake/zz_bytesresponsebody_server.go | 216 + .../encode/bytesgroup/fake/zz_internal.go | 47 + test/http-specs/encode/bytesgroup/go.mod | 17 + test/http-specs/encode/bytesgroup/go.sum | 25 + .../encode/bytesgroup/testdata/_metadata.json | 3 + .../encode/bytesgroup/zz_bytes_client.go | 80 + .../bytesgroup/zz_bytesheader_client.go | 169 + .../bytesgroup/zz_bytesproperty_client.go | 217 + .../encode/bytesgroup/zz_bytesquery_client.go | 177 + .../bytesgroup/zz_bytesrequestbody_client.go | 215 + .../bytesgroup/zz_bytesresponsebody_client.go | 243 + .../http-specs/encode/bytesgroup/zz_models.go | 25 + .../encode/bytesgroup/zz_models_serde.go | 165 + .../encode/bytesgroup/zz_options.go | 118 + .../encode/bytesgroup/zz_responses.go | 122 + .../encode/bytesgroup/zz_version.go | 10 + .../encode/datetimegroup/LICENSE.txt | 21 + .../datetimegroup/custom_client_test.go | 201 + .../datetimegroup/fake/zz_datetime_server.go | 96 + .../fake/zz_datetimeheader_server.go | 235 + .../fake/zz_datetimeproperty_server.go | 221 + .../fake/zz_datetimequery_server.go | 240 + .../fake/zz_datetimeresponseheader_server.go | 189 + .../encode/datetimegroup/fake/zz_internal.go | 55 + test/http-specs/encode/datetimegroup/go.mod | 17 + test/http-specs/encode/datetimegroup/go.sum | 25 + .../datetimegroup/testdata/_metadata.json | 3 + .../datetimegroup/zz_datetime_client.go | 72 + .../datetimegroup/zz_datetimeheader_client.go | 206 + .../zz_datetimeproperty_client.go | 270 + .../datetimegroup/zz_datetimequery_client.go | 216 + .../zz_datetimeresponseheader_client.go | 219 + .../encode/datetimegroup/zz_models.go | 32 + .../encode/datetimegroup/zz_models_serde.go | 205 + .../encode/datetimegroup/zz_options.go | 108 + .../encode/datetimegroup/zz_responses.go | 102 + .../encode/datetimegroup/zz_version.go | 10 + .../encode/durationgroup/LICENSE.txt | 21 + .../durationgroup/custom_client_test.go | 403 + .../durationgroup/fake/zz_duration_server.go | 87 + .../fake/zz_durationheader_server.go | 524 + .../fake/zz_durationproperty_server.go | 482 + .../fake/zz_durationquery_server.go | 547 + .../encode/durationgroup/fake/zz_internal.go | 55 + test/http-specs/encode/durationgroup/go.mod | 17 + test/http-specs/encode/durationgroup/go.sum | 25 + .../durationgroup/testdata/_metadata.json | 3 + .../durationgroup/zz_duration_client.go | 64 + .../durationgroup/zz_durationheader_client.go | 525 + .../zz_durationproperty_client.go | 720 ++ .../durationgroup/zz_durationquery_client.go | 553 ++ .../encode/durationgroup/zz_models.go | 75 + .../encode/durationgroup/zz_models_serde.go | 410 + .../encode/durationgroup/zz_options.go | 245 + .../encode/durationgroup/zz_responses.go | 215 + .../encode/durationgroup/zz_version.go | 10 + .../encode/numericgroup/LICENSE.txt | 21 + .../encode/numericgroup/fake/zz_internal.go | 31 + .../numericgroup/fake/zz_numeric_server.go | 69 + .../fake/zz_numericproperty_server.go | 163 + test/http-specs/encode/numericgroup/go.mod | 17 + test/http-specs/encode/numericgroup/go.sum | 25 + .../numericproperty_client_test.go | 43 + .../numericgroup/testdata/_metadata.json | 3 + .../encode/numericgroup/zz_models.go | 19 + .../encode/numericgroup/zz_models_serde.go | 139 + .../encode/numericgroup/zz_numeric_client.go | 48 + .../numericgroup/zz_numericproperty_client.go | 170 + .../encode/numericgroup/zz_options.go | 23 + .../encode/numericgroup/zz_responses.go | 20 + .../encode/numericgroup/zz_version.go | 10 + .../parameters/basicparamsgroup/LICENSE.txt | 21 + .../basicexplicitbody_client_test.go | 23 + .../basicimplicitbody_client_test.go | 20 + .../basicparamsgroup/fake/zz_basic_server.go | 78 + .../fake/zz_basicexplicitbody_server.go | 105 + .../fake/zz_basicimplicitbody_server.go | 108 + .../basicparamsgroup/fake/zz_internal.go | 31 + .../parameters/basicparamsgroup/go.mod | 17 + .../parameters/basicparamsgroup/go.sum | 25 + .../basicparamsgroup/testdata/_metadata.json | 3 + .../basicparamsgroup/zz_basic_client.go | 56 + .../zz_basicexplicitbody_client.go | 59 + .../zz_basicimplicitbody_client.go | 64 + .../parameters/basicparamsgroup/zz_models.go | 11 + .../basicparamsgroup/zz_models_serde.go | 59 + .../parameters/basicparamsgroup/zz_options.go | 15 + .../basicparamsgroup/zz_responses.go | 15 + .../parameters/basicparamsgroup/zz_version.go | 10 + .../parameters/bodyoptionalgroup/LICENSE.txt | 21 + .../bodyoptionality_client_test.go | 31 + .../fake/zz_bodyoptionality_server.go | 164 + ..._bodyoptionalityoptionalexplicit_server.go | 147 + .../bodyoptionalgroup/fake/zz_internal.go | 31 + .../parameters/bodyoptionalgroup/go.mod | 17 + .../parameters/bodyoptionalgroup/go.sum | 25 + .../optionalexplicit_client_test.go | 33 + .../bodyoptionalgroup/testdata/_metadata.json | 3 + .../zz_bodyoptionality_client.go | 134 + ..._bodyoptionalityoptionalexplicit_client.go | 104 + .../parameters/bodyoptionalgroup/zz_models.go | 10 + .../bodyoptionalgroup/zz_models_serde.go | 59 + .../bodyoptionalgroup/zz_options.go | 29 + .../bodyoptionalgroup/zz_responses.go | 25 + .../bodyoptionalgroup/zz_version.go | 10 + .../parameters/collectionfmtgroup/LICENSE.txt | 21 + .../fake/zz_collectionformat_server.go | 78 + .../fake/zz_collectionformatheader_server.go | 101 + .../fake/zz_collectionformatquery_server.go | 180 + .../collectionfmtgroup/fake/zz_internal.go | 47 + .../parameters/collectionfmtgroup/go.mod | 17 + .../parameters/collectionfmtgroup/go.sum | 25 + .../collectionfmtgroup/header_client_test.go | 20 + .../collectionfmtgroup/query_client_test.go | 44 + .../testdata/_metadata.json | 3 + .../zz_collectionformat_client.go | 56 + .../zz_collectionformatheader_client.go | 58 + .../zz_collectionformatquery_client.go | 179 + .../collectionfmtgroup/zz_options.go | 30 + .../collectionfmtgroup/zz_responses.go | 30 + .../collectionfmtgroup/zz_version.go | 10 + .../parameters/pathgroup/LICENSE.txt | 21 + .../parameters/pathgroup/fake/zz_internal.go | 30 + .../pathgroup/fake/zz_path_server.go | 155 + test/http-specs/parameters/pathgroup/go.mod | 17 + test/http-specs/parameters/pathgroup/go.sum | 25 + .../parameters/pathgroup/path_client_test.go | 39 + .../pathgroup/testdata/_metadata.json | 3 + .../parameters/pathgroup/zz_options.go | 15 + .../parameters/pathgroup/zz_path_client.go | 126 + .../parameters/pathgroup/zz_responses.go | 15 + .../parameters/pathgroup/zz_version.go | 10 + .../parameters/querygroup/LICENSE.txt | 21 + .../parameters/querygroup/fake/zz_internal.go | 31 + .../querygroup/fake/zz_query_server.go | 78 + .../fake/zz_queryconstant_server.go | 101 + .../fake/zz_queryspecialchar_server.go | 102 + test/http-specs/parameters/querygroup/go.mod | 17 + test/http-specs/parameters/querygroup/go.sum | 25 + .../querygroup/queryconstant_client_test.go | 20 + .../querygroup/testdata/_metadata.json | 3 + .../parameters/querygroup/zz_options.go | 15 + .../parameters/querygroup/zz_query_client.go | 56 + .../querygroup/zz_queryconstant_client.go | 58 + .../querygroup/zz_queryspecialchar_client.go | 59 + .../parameters/querygroup/zz_responses.go | 15 + .../parameters/querygroup/zz_version.go | 10 + .../parameters/spreadgroup/LICENSE.txt | 21 + .../spreadgroup/fake/zz_internal.go | 39 + .../spreadgroup/fake/zz_spread_server.go | 78 + .../spreadgroup/fake/zz_spreadalias_server.go | 289 + .../spreadgroup/fake/zz_spreadmodel_server.go | 255 + .../parameters/spreadgroup/fakes_test.go | 53 + test/http-specs/parameters/spreadgroup/go.mod | 17 + test/http-specs/parameters/spreadgroup/go.sum | 25 + .../spreadgroup/spreadalias_client_test.go | 54 + .../spreadgroup/spreadmodel_client_test.go | 57 + .../spreadgroup/testdata/_metadata.json | 3 + .../parameters/spreadgroup/zz_models.go | 11 + .../parameters/spreadgroup/zz_models_serde.go | 59 + .../parameters/spreadgroup/zz_options.go | 69 + .../parameters/spreadgroup/zz_responses.go | 55 + .../spreadgroup/zz_spread_client.go | 56 + .../spreadgroup/zz_spreadalias_client.go | 279 + .../spreadgroup/zz_spreadmodel_client.go | 239 + .../parameters/spreadgroup/zz_version.go | 10 + .../payload/contentneggroup/LICENSE.txt | 21 + .../differentbody_client_test.go | 36 + .../fake/zz_contentnegotiation_server.go | 78 + ..._contentnegotiationdifferentbody_server.go | 132 + .../zz_contentnegotiationsamebody_server.go | 138 + .../contentneggroup/fake/zz_internal.go | 31 + .../http-specs/payload/contentneggroup/go.mod | 17 + .../http-specs/payload/contentneggroup/go.sum | 25 + .../contentneggroup/samebody_client_test.go | 38 + .../contentneggroup/testdata/_metadata.json | 3 + .../zz_contentnegotiation_client.go | 56 + ..._contentnegotiationdifferentbody_client.go | 113 + .../zz_contentnegotiationsamebody_client.go | 114 + .../payload/contentneggroup/zz_models.go | 10 + .../contentneggroup/zz_models_serde.go | 53 + .../payload/contentneggroup/zz_options.go | 29 + .../payload/contentneggroup/zz_responses.go | 33 + .../payload/contentneggroup/zz_version.go | 10 + .../payload/jmergepatchgroup/LICENSE.txt | 21 + .../jmergepatchgroup/fake/zz_internal.go | 20 + .../fake/zz_jsonmergepatch_server.go | 163 + .../payload/jmergepatchgroup/go.mod | 17 + .../payload/jmergepatchgroup/go.sum | 25 + .../jsonmergepatch_client_test.go | 131 + .../jmergepatchgroup/testdata/_metadata.json | 3 + .../zz_jsonmergepatch_client.go | 193 + .../payload/jmergepatchgroup/zz_models.go | 35 + .../jmergepatchgroup/zz_models_serde.go | 169 + .../payload/jmergepatchgroup/zz_options.go | 23 + .../payload/jmergepatchgroup/zz_responses.go | 23 + .../payload/jmergepatchgroup/zz_version.go | 10 + .../payload/mediatypegroup/LICENSE.txt | 21 + .../mediatypegroup/fake/zz_internal.go | 31 + .../fake/zz_mediatype_server.go | 69 + .../fake/zz_mediatypestringbody_server.go | 184 + test/http-specs/payload/mediatypegroup/go.mod | 17 + test/http-specs/payload/mediatypegroup/go.sum | 25 + .../mediatypegroup/stringbody_client_test.go | 46 + .../mediatypegroup/testdata/_metadata.json | 3 + .../mediatypegroup/zz_mediatype_client.go | 48 + .../zz_mediatypestringbody_client.go | 196 + .../payload/mediatypegroup/zz_options.go | 29 + .../payload/mediatypegroup/zz_responses.go | 25 + .../payload/mediatypegroup/zz_version.go | 10 + .../payload/multipartgroup/LICENSE.txt | 21 + .../multipartgroup/fake/zz_internal.go | 31 + .../fake/zz_multipart_server.go | 69 + .../fake/zz_multipartformdata_server.go | 666 ++ .../fake/zz_multipartformdatafile_server.go | 242 + .../zz_multipartformdatahttpparts_server.go | 203 + ...partformdatahttppartscontenttype_server.go | 240 + ...tipartformdatahttppartsnonstring_server.go | 135 + .../payload/multipartgroup/fakes_test.go | 194 + .../multipartgroup/formdata_client_test.go | 204 + .../formdatafile_client_test.go | 58 + .../formdatahttpparts_client_test.go | 54 + ...ormdatahttppartscontenttype_client_test.go | 60 + .../formdatahttppartsnonstring_client_test.go | 18 + test/http-specs/payload/multipartgroup/go.mod | 17 + test/http-specs/payload/multipartgroup/go.sum | 25 + .../payload/multipartgroup/helpers_test.go | 23 + .../multipartgroup/testdata/_metadata.json | 3 + .../payload/multipartgroup/zz_models.go | 101 + .../payload/multipartgroup/zz_models_serde.go | 172 + .../multipartgroup/zz_multipart_client.go | 48 + .../zz_multipartformdata_client.go | 412 + .../zz_multipartformdatafile_client.go | 146 + .../zz_multipartformdatahttpparts_client.go | 78 + ...partformdatahttppartscontenttype_client.go | 147 + ...tipartformdatahttppartsnonstring_client.go | 60 + .../payload/multipartgroup/zz_options.go | 105 + .../payload/multipartgroup/zz_responses.go | 90 + .../payload/multipartgroup/zz_version.go | 10 + .../payload/pageablegroup/LICENSE.txt | 21 + .../payload/pageablegroup/fake/zz_internal.go | 91 + .../pageablegroup/fake/zz_pageable_server.go | 87 + .../fake/zz_pageablepagesize_server.go | 159 + ...z_pageableserverdrivenpagination_server.go | 219 + ...enpaginationalternateinitialverb_server.go | 117 + ...rivenpaginationcontinuationtoken_server.go | 341 + .../fake/zz_pageablexmlpagination_server.go | 153 + test/http-specs/payload/pageablegroup/go.mod | 17 + test/http-specs/payload/pageablegroup/go.sum | 25 + .../pageablepagesize_client_test.go | 106 + ...eableserverdrivenpagination_client_test.go | 129 + ...inationalternateinitialverb_client_test.go | 53 + ...paginationcontinuationtoken_client_test.go | 507 + .../pageablexmlpagination_client_test.go | 89 + .../pageablegroup/testdata/_metadata.json | 3 + .../payload/pageablegroup/zz_models.go | 138 + .../payload/pageablegroup/zz_models_serde.go | 653 ++ .../payload/pageablegroup/zz_options.go | 101 + .../pageablegroup/zz_pageable_client.go | 64 + .../zz_pageablepagesize_client.go | 119 + ...z_pageableserverdrivenpagination_client.go | 171 + ...enpaginationalternateinitialverb_client.go | 70 + ...rivenpaginationcontinuationtoken_client.go | 412 + .../zz_pageablexmlpagination_client.go | 124 + .../payload/pageablegroup/zz_responses.go | 85 + .../payload/pageablegroup/zz_version.go | 10 + test/http-specs/payload/xmlgroup/LICENSE.txt | 21 + .../payload/xmlgroup/fake/zz_internal.go | 31 + .../payload/xmlgroup/fake/zz_xml_server.go | 294 + ...zz_xmlmodelwitharrayofmodelvalue_server.go | 130 + .../zz_xmlmodelwithattributesvalue_server.go | 130 + .../zz_xmlmodelwithdatetimevalue_server.go | 130 + .../zz_xmlmodelwithdictionaryvalue_server.go | 130 + .../zz_xmlmodelwithemptyarrayvalue_server.go | 130 + ...zz_xmlmodelwithencodednamesvalue_server.go | 130 + .../fake/zz_xmlmodelwithenumvalue_server.go | 130 + ...elwithnamespaceonpropertiesvalue_server.go | 130 + .../zz_xmlmodelwithnamespacevalue_server.go | 130 + .../zz_xmlmodelwithnestedmodelvalue_server.go | 130 + ...z_xmlmodelwithoptionalfieldvalue_server.go | 130 + ...z_xmlmodelwithrenamedarraysvalue_server.go | 130 + ...mlmodelwithrenamedattributevalue_server.go | 130 + ...z_xmlmodelwithrenamedfieldsvalue_server.go | 130 + ...modelwithrenamednestedmodelvalue_server.go | 130 + ...xmlmodelwithrenamedpropertyvalue_server.go | 130 + ...hrenamedunwrappedmodelarrayvalue_server.go | 130 + ...medwrappedanditemmodelarrayvalue_server.go | 130 + ...ithrenamedwrappedmodelarrayvalue_server.go | 130 + ...zz_xmlmodelwithsimplearraysvalue_server.go | 130 + .../fake/zz_xmlmodelwithtextvalue_server.go | 130 + ..._xmlmodelwithunwrappedarrayvalue_server.go | 130 + ...odelwithunwrappedmodelarrayvalue_server.go | 130 + ...pedprimitivecustomitemnamesvalue_server.go | 130 + .../fake/zz_xmlsimplemodelvalue_server.go | 130 + .../fake/zz_xmlxmlerrorvalue_server.go | 101 + test/http-specs/payload/xmlgroup/go.mod | 17 + test/http-specs/payload/xmlgroup/go.sum | 25 + .../payload/xmlgroup/testdata/_metadata.json | 3 + ...lmodelwitharrayofmodelvalue_client_test.go | 51 + ...xmlmodelwithattributesvalue_client_test.go | 37 + .../xmlmodelwithdatetimevalue_client_test.go | 41 + ...xmlmodelwithdictionaryvalue_client_test.go | 42 + ...xmlmodelwithemptyarrayvalue_client_test.go | 30 + ...lmodelwithencodednamesvalue_client_test.go | 41 + .../xmlmodelwithenumvalue_client_test.go | 33 + ...hnamespaceonpropertiesvalue_client_test.go | 38 + .../xmlmodelwithnamespacevalue_client_test.go | 36 + ...mlmodelwithnestedmodelvalue_client_test.go | 39 + ...modelwithoptionalfieldvalue_client_test.go | 33 + ...modelwithrenamedarraysvalue_client_test.go | 34 + ...elwithrenamedattributevalue_client_test.go | 37 + ...modelwithrenamedfieldsvalue_client_test.go | 47 + ...withrenamednestedmodelvalue_client_test.go | 38 + ...delwithrenamedpropertyvalue_client_test.go | 35 + ...medunwrappedmodelarrayvalue_client_test.go | 51 + ...appedanditemmodelarrayvalue_client_test.go | 47 + ...namedwrappedmodelarrayvalue_client_test.go | 51 + ...lmodelwithsimplearraysvalue_client_test.go | 34 + .../xmlmodelwithtextvalue_client_test.go | 35 + ...odelwithunwrappedarrayvalue_client_test.go | 34 + ...ithunwrappedmodelarrayvalue_client_test.go | 51 + ...imitivecustomitemnamesvalue_client_test.go | 32 + .../xmlsimplemodelvalue_client_test.go | 35 + .../xmlgroup/xmlxmlerrorvalue_client_test.go | 26 + .../payload/xmlgroup/zz_constants.go | 26 + test/http-specs/payload/xmlgroup/zz_models.go | 228 + .../payload/xmlgroup/zz_models_serde.go | 346 + .../http-specs/payload/xmlgroup/zz_options.go | 304 + .../payload/xmlgroup/zz_responses.go | 286 + .../http-specs/payload/xmlgroup/zz_version.go | 10 + .../payload/xmlgroup/zz_xml_client.go | 248 + .../payload/xmlgroup/zz_xml_helper.go | 83 + ...zz_xmlmodelwitharrayofmodelvalue_client.go | 105 + .../zz_xmlmodelwithattributesvalue_client.go | 105 + .../zz_xmlmodelwithdatetimevalue_client.go | 105 + .../zz_xmlmodelwithdictionaryvalue_client.go | 105 + .../zz_xmlmodelwithemptyarrayvalue_client.go | 105 + ...zz_xmlmodelwithencodednamesvalue_client.go | 105 + .../zz_xmlmodelwithenumvalue_client.go | 105 + ...elwithnamespaceonpropertiesvalue_client.go | 105 + .../zz_xmlmodelwithnamespacevalue_client.go | 105 + .../zz_xmlmodelwithnestedmodelvalue_client.go | 105 + ...z_xmlmodelwithoptionalfieldvalue_client.go | 105 + ...z_xmlmodelwithrenamedarraysvalue_client.go | 105 + ...mlmodelwithrenamedattributevalue_client.go | 105 + ...z_xmlmodelwithrenamedfieldsvalue_client.go | 105 + ...modelwithrenamednestedmodelvalue_client.go | 105 + ...xmlmodelwithrenamedpropertyvalue_client.go | 105 + ...hrenamedunwrappedmodelarrayvalue_client.go | 105 + ...medwrappedanditemmodelarrayvalue_client.go | 106 + ...ithrenamedwrappedmodelarrayvalue_client.go | 105 + ...zz_xmlmodelwithsimplearraysvalue_client.go | 105 + .../zz_xmlmodelwithtextvalue_client.go | 105 + ..._xmlmodelwithunwrappedarrayvalue_client.go | 105 + ...odelwithunwrappedmodelarrayvalue_client.go | 105 + ...pedprimitivecustomitemnamesvalue_client.go | 106 + .../xmlgroup/zz_xmlsimplemodelvalue_client.go | 103 + .../xmlgroup/zz_xmlxmlerrorvalue_client.go | 65 + .../encoded-name/jsongroup/LICENSE.txt | 21 + .../jsongroup/fake/zz_internal.go | 31 + .../jsongroup/fake/zz_json_server.go | 69 + .../jsongroup/fake/zz_jsonproperty_server.go | 130 + .../encoded-name/jsongroup/go.mod | 17 + .../encoded-name/jsongroup/go.sum | 25 + .../encoded-name/jsongroup/jsongroup_test.go | 28 + .../jsongroup/testdata/_metadata.json | 3 + .../encoded-name/jsongroup/zz_json_client.go | 48 + .../jsongroup/zz_jsonproperty_client.go | 103 + .../encoded-name/jsongroup/zz_models.go | 10 + .../encoded-name/jsongroup/zz_models_serde.go | 59 + .../encoded-name/jsongroup/zz_options.go | 15 + .../encoded-name/jsongroup/zz_responses.go | 15 + .../encoded-name/jsongroup/zz_version.go | 10 + .../endpoint/noendpointgroup/LICENSE.txt | 21 + .../noendpointgroup/fake/zz_internal.go | 20 + .../fake/zz_notdefined_server.go | 101 + .../server/endpoint/noendpointgroup/go.mod | 17 + .../server/endpoint/noendpointgroup/go.sum | 25 + .../noendpointgroup/notdefined_client_test.go | 20 + .../noendpointgroup/testdata/_metadata.json | 3 + .../noendpointgroup/zz_notdefined_client.go | 76 + .../endpoint/noendpointgroup/zz_options.go | 10 + .../endpoint/noendpointgroup/zz_responses.go | 11 + .../endpoint/noendpointgroup/zz_version.go | 10 + .../server/path/multiplegroup/LICENSE.txt | 21 + .../path/multiplegroup/fake/zz_internal.go | 20 + .../multiplegroup/fake/zz_multiple_server.go | 138 + .../server/path/multiplegroup/go.mod | 17 + .../server/path/multiplegroup/go.sum | 25 + .../multiplegroup/multiple_client_test.go | 28 + .../multiplegroup/testdata/_metadata.json | 6 + .../path/multiplegroup/zz_multiple_client.go | 130 + .../server/path/multiplegroup/zz_options.go | 16 + .../server/path/multiplegroup/zz_responses.go | 15 + .../server/path/multiplegroup/zz_version.go | 10 + .../server/path/singlegroup/LICENSE.txt | 21 + .../path/singlegroup/fake/zz_internal.go | 20 + .../path/singlegroup/fake/zz_single_server.go | 101 + .../http-specs/server/path/singlegroup/go.mod | 17 + .../http-specs/server/path/singlegroup/go.sum | 25 + .../path/singlegroup/single_client_test.go | 20 + .../path/singlegroup/testdata/_metadata.json | 3 + .../server/path/singlegroup/zz_options.go | 10 + .../server/path/singlegroup/zz_responses.go | 11 + .../path/singlegroup/zz_single_client.go | 75 + .../server/path/singlegroup/zz_version.go | 10 + .../versions/unversionedgroup/LICENSE.txt | 21 + .../unversionedgroup/fake/zz_internal.go | 20 + .../fake/zz_notversioned_server.go | 164 + .../server/versions/unversionedgroup/go.mod | 17 + .../server/versions/unversionedgroup/go.sum | 25 + .../notversioned_client_test.go | 36 + .../unversionedgroup/testdata/_metadata.json | 3 + .../zz_notversioned_client.go | 152 + .../versions/unversionedgroup/zz_options.go | 23 + .../versions/unversionedgroup/zz_responses.go | 23 + .../versions/unversionedgroup/zz_version.go | 10 + .../versions/versionedgroup/LICENSE.txt | 21 + .../versionedgroup/fake/zz_internal.go | 20 + .../fake/zz_versioned_server.go | 176 + .../server/versions/versionedgroup/go.mod | 17 + .../server/versions/versionedgroup/go.sum | 25 + .../versionedgroup/testdata/_metadata.json | 6 + .../versionedgroup/versioned_client_test.go | 49 + .../versions/versionedgroup/zz_constants.go | 9 + .../versions/versionedgroup/zz_options.go | 27 + .../versions/versionedgroup/zz_responses.go | 29 + .../versions/versionedgroup/zz_version.go | 10 + .../versionedgroup/zz_versioned_client.go | 191 + .../special-headers/condreqgroup/LICENSE.txt | 21 + .../conditionalrequest_client_test.go | 56 + .../fake/zz_conditionalrequest_server.go | 211 + .../condreqgroup/fake/zz_internal.go | 49 + .../special-headers/condreqgroup/go.mod | 17 + .../special-headers/condreqgroup/go.sum | 25 + .../condreqgroup/testdata/_metadata.json | 3 + .../zz_conditionalrequest_client.go | 195 + .../condreqgroup/zz_options.go | 39 + .../condreqgroup/zz_responses.go | 26 + .../condreqgroup/zz_version.go | 10 + test/http-specs/specialwordsgroup/LICENSE.txt | 21 + .../extensiblestrings_client_test.go | 21 + .../specialwordsgroup/fake/zz_internal.go | 31 + .../fake/zz_specialwords_server.go | 114 + ...zz_specialwordsextensiblestrings_server.go | 105 + .../zz_specialwordsmodelproperties_server.go | 163 + .../fake/zz_specialwordsmodels_server.go | 1033 ++ .../fake/zz_specialwordsoperations_server.go | 901 ++ .../fake/zz_specialwordsparameters_server.go | 960 ++ ...wordsreservedoperationbodyparams_server.go | 108 + test/http-specs/specialwordsgroup/go.mod | 17 + test/http-specs/specialwordsgroup/go.sum | 25 + .../modelproperties_client_test.go | 52 + .../specialwordsgroup/models_client_test.go | 343 + .../operations_client_test.go | 276 + .../parameters_client_test.go | 284 + ...reservedoperationbodyparams_client_test.go | 20 + .../specialwordsgroup/testdata/_metadata.json | 3 + .../specialwordsgroup/zz_constants.go | 83 + .../http-specs/specialwordsgroup/zz_models.go | 212 + .../specialwordsgroup/zz_models_serde.go | 1040 ++ .../specialwordsgroup/zz_options.go | 587 ++ .../specialwordsgroup/zz_responses.go | 530 + .../zz_specialwords_client.go | 125 + ...zz_specialwordsextensiblestrings_client.go | 70 + .../zz_specialwordsmodelproperties_client.go | 137 + .../zz_specialwordsmodels_client.go | 1307 +++ .../zz_specialwordsoperations_client.go | 1175 +++ .../zz_specialwordsparameters_client.go | 1313 +++ ...wordsreservedoperationbodyparams_client.go | 66 + .../specialwordsgroup/zz_version.go | 10 + test/http-specs/type/arraygroup/LICENSE.txt | 21 + .../type/arraygroup/arraygroup_test.go | 251 + .../type/arraygroup/fake/zz_array_server.go | 186 + .../fake/zz_arraybooleanvalue_server.go | 130 + .../fake/zz_arraydatetimevalue_server.go | 131 + .../fake/zz_arraydurationvalue_server.go | 130 + .../fake/zz_arrayfloat32value_server.go | 130 + .../fake/zz_arrayint32value_server.go | 130 + .../fake/zz_arrayint64value_server.go | 130 + .../fake/zz_arraymodelvalue_server.go | 130 + .../zz_arraynullablebooleanvalue_server.go | 130 + .../fake/zz_arraynullablefloatvalue_server.go | 130 + .../fake/zz_arraynullableint32value_server.go | 130 + .../fake/zz_arraynullablemodelvalue_server.go | 130 + .../zz_arraynullablestringvalue_server.go | 130 + .../fake/zz_arraystringvalue_server.go | 130 + .../fake/zz_arrayunknownvalue_server.go | 130 + .../type/arraygroup/fake/zz_internal.go | 31 + test/http-specs/type/arraygroup/go.mod | 17 + test/http-specs/type/arraygroup/go.sum | 25 + .../type/arraygroup/testdata/_metadata.json | 3 + .../type/arraygroup/zz_array_client.go | 152 + .../arraygroup/zz_arraybooleanvalue_client.go | 103 + .../zz_arraydatetimevalue_client.go | 111 + .../zz_arraydurationvalue_client.go | 103 + .../arraygroup/zz_arrayfloat32value_client.go | 103 + .../arraygroup/zz_arrayint32value_client.go | 103 + .../arraygroup/zz_arrayint64value_client.go | 103 + .../arraygroup/zz_arraymodelvalue_client.go | 103 + .../zz_arraynullablebooleanvalue_client.go | 105 + .../zz_arraynullablefloatvalue_client.go | 105 + .../zz_arraynullableint32value_client.go | 105 + .../zz_arraynullablemodelvalue_client.go | 105 + .../zz_arraynullablestringvalue_client.go | 105 + .../arraygroup/zz_arraystringvalue_client.go | 103 + .../arraygroup/zz_arrayunknownvalue_client.go | 103 + test/http-specs/type/arraygroup/zz_models.go | 12 + .../type/arraygroup/zz_models_serde.go | 63 + test/http-specs/type/arraygroup/zz_options.go | 147 + .../type/arraygroup/zz_responses.go | 147 + test/http-specs/type/arraygroup/zz_version.go | 10 + .../type/dictionarygroup/LICENSE.txt | 21 + .../dictionarygroup/dictionarygroup_test.go | 282 + .../fake/zz_dictionary_server.go | 159 + .../fake/zz_dictionarybooleanvalue_server.go | 130 + .../fake/zz_dictionarydatetimevalue_server.go | 131 + .../fake/zz_dictionarydurationvalue_server.go | 130 + .../fake/zz_dictionaryfloat32value_server.go | 130 + .../fake/zz_dictionaryint32value_server.go | 130 + .../fake/zz_dictionaryint64value_server.go | 130 + .../fake/zz_dictionarymodelvalue_server.go | 130 + .../zz_dictionarynullablefloatvalue_server.go | 130 + ...zz_dictionaryrecursivemodelvalue_server.go | 130 + .../fake/zz_dictionarystringvalue_server.go | 130 + .../fake/zz_dictionaryunknownvalue_server.go | 130 + .../type/dictionarygroup/fake/zz_internal.go | 31 + test/http-specs/type/dictionarygroup/go.mod | 17 + test/http-specs/type/dictionarygroup/go.sum | 25 + .../dictionarygroup/testdata/_metadata.json | 3 + .../dictionarygroup/zz_dictionary_client.go | 128 + .../zz_dictionarybooleanvalue_client.go | 105 + .../zz_dictionarydatetimevalue_client.go | 117 + .../zz_dictionarydurationvalue_client.go | 105 + .../zz_dictionaryfloat32value_client.go | 105 + .../zz_dictionaryint32value_client.go | 105 + .../zz_dictionaryint64value_client.go | 105 + .../zz_dictionarymodelvalue_client.go | 105 + .../zz_dictionarynullablefloatvalue_client.go | 105 + ...zz_dictionaryrecursivemodelvalue_client.go | 105 + .../zz_dictionarystringvalue_client.go | 105 + .../zz_dictionaryunknownvalue_client.go | 105 + .../type/dictionarygroup/zz_models.go | 12 + .../type/dictionarygroup/zz_models_serde.go | 63 + .../type/dictionarygroup/zz_options.go | 119 + .../type/dictionarygroup/zz_responses.go | 117 + .../type/dictionarygroup/zz_version.go | 10 + .../type/enum/extensiblegroup/LICENSE.txt | 21 + .../fake/zz_extensible_server.go | 69 + .../fake/zz_extensiblestring_server.go | 184 + .../enum/extensiblegroup/fake/zz_internal.go | 31 + .../type/enum/extensiblegroup/go.mod | 17 + .../type/enum/extensiblegroup/go.sum | 25 + .../extensiblegroup/string_client_test.go | 46 + .../extensiblegroup/testdata/_metadata.json | 3 + .../type/enum/extensiblegroup/zz_constants.go | 38 + .../extensiblegroup/zz_extensible_client.go | 48 + .../zz_extensiblestring_client.go | 190 + .../type/enum/extensiblegroup/zz_options.go | 29 + .../type/enum/extensiblegroup/zz_responses.go | 25 + .../type/enum/extensiblegroup/zz_version.go | 10 + .../type/enum/fixedgroup/LICENSE.txt | 21 + .../enum/fixedgroup/fake/zz_fixed_server.go | 69 + .../fixedgroup/fake/zz_fixedstring_server.go | 159 + .../type/enum/fixedgroup/fake/zz_internal.go | 31 + test/http-specs/type/enum/fixedgroup/go.mod | 17 + test/http-specs/type/enum/fixedgroup/go.sum | 25 + .../enum/fixedgroup/string_client_test.go | 41 + .../enum/fixedgroup/testdata/_metadata.json | 3 + .../type/enum/fixedgroup/zz_constants.go | 38 + .../type/enum/fixedgroup/zz_fixed_client.go | 48 + .../enum/fixedgroup/zz_fixedstring_client.go | 146 + .../type/enum/fixedgroup/zz_options.go | 20 + .../type/enum/fixedgroup/zz_responses.go | 20 + .../type/enum/fixedgroup/zz_version.go | 10 + .../type/model/emptygroup/LICENSE.txt | 21 + .../model/emptygroup/empty_client_test.go | 36 + .../model/emptygroup/fake/zz_empty_server.go | 159 + .../type/model/emptygroup/fake/zz_internal.go | 20 + test/http-specs/type/model/emptygroup/go.mod | 17 + test/http-specs/type/model/emptygroup/go.sum | 25 + .../model/emptygroup/testdata/_metadata.json | 3 + .../type/model/emptygroup/zz_empty_client.go | 175 + .../type/model/emptygroup/zz_models.go | 17 + .../type/model/emptygroup/zz_options.go | 20 + .../type/model/emptygroup/zz_responses.go | 22 + .../type/model/emptygroup/zz_version.go | 10 + .../inheritance/enumdiscgroup/LICENSE.txt | 21 + .../enumdiscriminator_client_test.go | 105 + .../fake/zz_enumdiscriminator_server.go | 292 + .../enumdiscgroup/fake/zz_internal.go | 35 + .../fake/zz_polymorphic_helpers.go | 52 + .../model/inheritance/enumdiscgroup/go.mod | 17 + .../model/inheritance/enumdiscgroup/go.sum | 25 + .../enumdiscgroup/testdata/_metadata.json | 3 + .../inheritance/enumdiscgroup/zz_constants.go | 35 + .../zz_enumdiscriminator_client.go | 399 + .../enumdiscgroup/zz_interfaces.go | 23 + .../inheritance/enumdiscgroup/zz_models.go | 65 + .../enumdiscgroup/zz_models_serde.go | 156 + .../inheritance/enumdiscgroup/zz_options.go | 53 + .../enumdiscgroup/zz_polymorphic_helpers.go | 49 + .../inheritance/enumdiscgroup/zz_responses.go | 51 + .../enumdiscgroup/zz_responses_serde.go | 65 + .../inheritance/enumdiscgroup/zz_version.go | 10 + .../model/inheritance/nodiscgroup/LICENSE.txt | 21 + .../nodiscgroup/fake/zz_internal.go | 20 + .../fake/zz_notdiscriminated_server.go | 159 + .../type/model/inheritance/nodiscgroup/go.mod | 17 + .../type/model/inheritance/nodiscgroup/go.sum | 25 + .../notdiscriminated_client_test.go | 50 + .../nodiscgroup/testdata/_metadata.json | 3 + .../inheritance/nodiscgroup/zz_models.go | 17 + .../nodiscgroup/zz_models_serde.go | 67 + .../nodiscgroup/zz_notdiscriminated_client.go | 178 + .../inheritance/nodiscgroup/zz_options.go | 20 + .../inheritance/nodiscgroup/zz_responses.go | 22 + .../inheritance/nodiscgroup/zz_version.go | 10 + .../inheritance/recursivegroup/LICENSE.txt | 21 + .../recursivegroup/fake/zz_internal.go | 20 + .../fake/zz_recursive_server.go | 130 + .../model/inheritance/recursivegroup/go.mod | 17 + .../model/inheritance/recursivegroup/go.sum | 25 + .../recursivegroup/recursive_client_test.go | 59 + .../recursivegroup/testdata/_metadata.json | 3 + .../inheritance/recursivegroup/zz_models.go | 12 + .../recursivegroup/zz_models_serde.go | 63 + .../inheritance/recursivegroup/zz_options.go | 15 + .../recursivegroup/zz_recursive_client.go | 126 + .../recursivegroup/zz_responses.go | 16 + .../inheritance/recursivegroup/zz_version.go | 10 + .../inheritance/singlediscgroup/LICENSE.txt | 21 + .../singlediscgroup/fake/zz_internal.go | 35 + .../fake/zz_polymorphic_helpers.go | 56 + .../fake/zz_singlediscriminator_server.go | 325 + .../model/inheritance/singlediscgroup/go.mod | 17 + .../model/inheritance/singlediscgroup/go.sum | 25 + .../singlediscriminator_client_test.go | 126 + .../singlediscgroup/testdata/_metadata.json | 3 + .../singlediscgroup/zz_interfaces.go | 32 + .../inheritance/singlediscgroup/zz_models.go | 130 + .../singlediscgroup/zz_models_serde.go | 292 + .../inheritance/singlediscgroup/zz_options.go | 57 + .../singlediscgroup/zz_polymorphic_helpers.go | 112 + .../singlediscgroup/zz_responses.go | 56 + .../singlediscgroup/zz_responses_serde.go | 65 + .../zz_singlediscriminator_client.go | 436 + .../inheritance/singlediscgroup/zz_version.go | 10 + .../type/model/usagegroup/LICENSE.txt | 21 + .../type/model/usagegroup/fake/zz_internal.go | 20 + .../model/usagegroup/fake/zz_usage_server.go | 159 + test/http-specs/type/model/usagegroup/go.mod | 17 + test/http-specs/type/model/usagegroup/go.sum | 25 + .../model/usagegroup/testdata/_metadata.json | 3 + .../model/usagegroup/usage_client_test.go | 43 + .../type/model/usagegroup/zz_models.go | 23 + .../type/model/usagegroup/zz_models_serde.go | 113 + .../type/model/usagegroup/zz_options.go | 20 + .../type/model/usagegroup/zz_responses.go | 22 + .../type/model/usagegroup/zz_usage_client.go | 175 + .../type/model/usagegroup/zz_version.go | 10 + .../type/model/visibilitygroup/LICENSE.txt | 21 + .../model/visibilitygroup/fake/zz_internal.go | 28 + .../fake/zz_visibility_server.go | 294 + .../type/model/visibilitygroup/go.mod | 17 + .../type/model/visibilitygroup/go.sum | 25 + .../visibilitygroup/testdata/_metadata.json | 3 + .../visibilitygroup/visibility_client_test.go | 103 + .../type/model/visibilitygroup/zz_models.go | 29 + .../model/visibilitygroup/zz_models_serde.go | 102 + .../type/model/visibilitygroup/zz_options.go | 40 + .../model/visibilitygroup/zz_responses.go | 43 + .../type/model/visibilitygroup/zz_version.go | 10 + .../visibilitygroup/zz_visibility_client.go | 330 + .../property/addlpropsgroup/custom_client.go | 19 + .../extendsfloat_client_test.go | 39 + .../extendsmodel_client_test.go | 47 + .../extendsmodelarray_client_test.go | 67 + .../extendsstring_client_test.go | 39 + .../extendsunknown_client_test.go | 43 + .../extendsunknownderived_client_test.go | 47 + ...extendsunknowndiscriminated_client_test.go | 49 + .../addlpropsgroup/isfloat_client_test.go | 39 + .../addlpropsgroup/ismodel_client_test.go | 47 + .../ismodelarray_client_test.go | 67 + .../addlpropsgroup/isstring_client_test.go | 39 + .../addlpropsgroup/isunknown_client_test.go | 43 + .../isunknownderived_client_test.go | 47 + .../isunknowndiscriminated_client_test.go | 49 + .../type/property/nullablegroup/LICENSE.txt | 21 + .../nullablegroup/bytes_client_test.go | 57 + .../collectionsbyte_client_test.go | 63 + .../collectionsmodel_client_test.go | 71 + .../collectionsstring_client_test.go | 55 + .../nullablegroup/datetime_client_test.go | 62 + .../nullablegroup/duration_client_test.go | 57 + .../nullablegroup/fake/zz_internal.go | 31 + .../nullablegroup/fake/zz_nullable_server.go | 123 + .../fake/zz_nullablebytes_server.go | 184 + .../fake/zz_nullablecollectionsbyte_server.go | 184 + .../zz_nullablecollectionsmodel_server.go | 184 + .../zz_nullablecollectionsstring_server.go | 184 + .../fake/zz_nullabledatetime_server.go | 184 + .../fake/zz_nullableduration_server.go | 184 + .../fake/zz_nullablestring_server.go | 184 + .../type/property/nullablegroup/go.mod | 17 + .../type/property/nullablegroup/go.sum | 25 + .../nullablegroup/string_client_test.go | 57 + .../nullablegroup/testdata/_metadata.json | 3 + .../type/property/nullablegroup/zz_models.go | 78 + .../property/nullablegroup/zz_models_serde.go | 334 + .../nullablegroup/zz_nullable_client.go | 96 + .../nullablegroup/zz_nullablebytes_client.go | 188 + .../zz_nullablecollectionsbyte_client.go | 190 + .../zz_nullablecollectionsmodel_client.go | 190 + .../zz_nullablecollectionsstring_client.go | 190 + .../zz_nullabledatetime_client.go | 190 + .../zz_nullableduration_client.go | 190 + .../nullablegroup/zz_nullablestring_client.go | 189 + .../type/property/nullablegroup/zz_options.go | 159 + .../property/nullablegroup/zz_responses.go | 159 + .../type/property/nullablegroup/zz_version.go | 10 + .../property/optionalitygroup/LICENSE.txt | 21 + .../optionalitygroup/fake/zz_internal.go | 31 + .../fake/zz_optional_server.go | 204 + .../fake/zz_optionalbooleanliteral_server.go | 184 + .../fake/zz_optionalbytes_server.go | 184 + .../fake/zz_optionalcollectionsbyte_server.go | 184 + .../zz_optionalcollectionsmodel_server.go | 184 + .../fake/zz_optionaldatetime_server.go | 184 + .../fake/zz_optionalduration_server.go | 184 + .../fake/zz_optionalfloatliteral_server.go | 184 + .../fake/zz_optionalintliteral_server.go | 184 + .../fake/zz_optionalplaindate_server.go | 184 + .../fake/zz_optionalplaintime_server.go | 184 + .../zz_optionalrequiredandoptional_server.go | 184 + .../fake/zz_optionalstring_server.go | 184 + .../fake/zz_optionalstringliteral_server.go | 184 + .../zz_optionalunionfloatliteral_server.go | 184 + .../fake/zz_optionalunionintliteral_server.go | 184 + .../zz_optionalunionstringliteral_server.go | 184 + .../type/property/optionalitygroup/go.mod | 17 + .../type/property/optionalitygroup/go.sum | 25 + .../optionalbooleanliteral_client_test.go | 48 + .../optionalbytes_client_test.go | 46 + .../optionalcollectionsbyte_client_test.go | 52 + .../optionalcollectionsmodel_client_test.go | 61 + .../optionaldatetime_client_test.go | 49 + .../optionalduration_client_test.go | 48 + .../optionalfloatliteral_client_test.go | 48 + .../optionalintliteral_client_test.go | 48 + .../optionalplaindate_client_test.go | 45 + .../optionalplaintime_client_test.go | 47 + ...optionalrequiredandoptional_client_test.go | 55 + .../optionalstring_client_test.go | 48 + .../optionalstringliteral_client_test.go | 48 + .../optionalunionfloatliteral_client_test.go | 48 + .../optionalunionintliteral_client_test.go | 48 + .../optionalunionstringliteral_client_test.go | 48 + .../optionalitygroup/testdata/_metadata.json | 3 + .../property/optionalitygroup/zz_constants.go | 50 + .../property/optionalitygroup/zz_models.go | 112 + .../optionalitygroup/zz_models_serde.go | 534 + .../optionalitygroup/zz_optional_client.go | 168 + .../zz_optionalbooleanliteral_client.go | 190 + .../zz_optionalbytes_client.go | 188 + .../zz_optionalcollectionsbyte_client.go | 190 + .../zz_optionalcollectionsmodel_client.go | 190 + .../zz_optionaldatetime_client.go | 188 + .../zz_optionalduration_client.go | 188 + .../zz_optionalfloatliteral_client.go | 190 + .../zz_optionalintliteral_client.go | 190 + .../zz_optionalplaindate_client.go | 190 + .../zz_optionalplaintime_client.go | 190 + .../zz_optionalrequiredandoptional_client.go | 190 + .../zz_optionalstring_client.go | 188 + .../zz_optionalstringliteral_client.go | 190 + .../zz_optionalunionfloatliteral_client.go | 190 + .../zz_optionalunionintliteral_client.go | 190 + .../zz_optionalunionstringliteral_client.go | 190 + .../property/optionalitygroup/zz_options.go | 359 + .../property/optionalitygroup/zz_responses.go | 357 + .../property/optionalitygroup/zz_version.go | 10 + .../type/property/valuetypesgroup/LICENSE.txt | 21 + .../valuetypesgroup/fake/zz_internal.go | 31 + .../fake/zz_valuetypes_server.go | 321 + .../fake/zz_valuetypesboolean_server.go | 130 + .../zz_valuetypesbooleanliteral_server.go | 130 + .../fake/zz_valuetypesbytes_server.go | 130 + .../zz_valuetypescollectionsint_server.go | 130 + .../zz_valuetypescollectionsmodel_server.go | 130 + .../zz_valuetypescollectionsstring_server.go | 130 + .../fake/zz_valuetypesdatetime_server.go | 130 + .../fake/zz_valuetypesdecimal128_server.go | 130 + .../fake/zz_valuetypesdecimal_server.go | 130 + .../zz_valuetypesdictionarystring_server.go | 130 + .../fake/zz_valuetypesduration_server.go | 130 + .../fake/zz_valuetypesenum_server.go | 130 + .../zz_valuetypesextensibleenum_server.go | 130 + .../fake/zz_valuetypesfloat_server.go | 130 + .../fake/zz_valuetypesfloatliteral_server.go | 130 + .../fake/zz_valuetypesint_server.go | 130 + .../fake/zz_valuetypesintliteral_server.go | 130 + .../fake/zz_valuetypesmodel_server.go | 130 + .../fake/zz_valuetypesnever_server.go | 130 + .../fake/zz_valuetypesstring_server.go | 130 + .../fake/zz_valuetypesstringliteral_server.go | 130 + .../zz_valuetypesunionenumvalue_server.go | 130 + .../zz_valuetypesunionfloatliteral_server.go | 130 + .../zz_valuetypesunionintliteral_server.go | 130 + .../zz_valuetypesunionstringliteral_server.go | 130 + .../fake/zz_valuetypesunknownarray_server.go | 130 + .../fake/zz_valuetypesunknowndict_server.go | 130 + .../fake/zz_valuetypesunknownint_server.go | 130 + .../fake/zz_valuetypesunknownstring_server.go | 130 + .../type/property/valuetypesgroup/go.mod | 17 + .../type/property/valuetypesgroup/go.sum | 25 + .../valuetypesgroup/testdata/_metadata.json | 3 + .../valuetypesboolean_client_test.go | 32 + .../valuetypesbooleanliteral_client_test.go | 29 + .../valuetypesbytes_client_test.go | 30 + .../valuetypescollectionsint_client_test.go | 30 + .../valuetypescollectionsmodel_client_test.go | 45 + ...valuetypescollectionsstring_client_test.go | 30 + .../valuetypesdatetime_client_test.go | 33 + .../valuetypesdecimal128_client_test.go | 32 + .../valuetypesdecimal_client_test.go | 32 + .../valuetypesdictionarystring_client_test.go | 37 + .../valuetypesduration_client_test.go | 32 + .../valuetypesenum_client_test.go | 32 + .../valuetypesextensibleenum_client_test.go | 32 + .../valuetypesfloat_client_test.go | 32 + .../valuetypesfloatliteral_client_test.go | 32 + .../valuetypesint_client_test.go | 32 + .../valuetypesintliteral_client_test.go | 29 + .../valuetypesmodel_client_test.go | 36 + .../valuetypesnever_client_test.go | 28 + .../valuetypesstring_client_test.go | 32 + .../valuetypesstringliteral_client_test.go | 29 + .../valuetypesunionenumvalue_client_test.go | 32 + ...valuetypesunionfloatliteral_client_test.go | 32 + .../valuetypesunionintliteral_client_test.go | 32 + ...aluetypesunionstringliteral_client_test.go | 32 + .../valuetypesunknownarray_client_test.go | 30 + .../valuetypesunknowndict_client_test.go | 36 + .../valuetypesunknownint_client_test.go | 30 + .../valuetypesunknownstring_client_test.go | 30 + .../property/valuetypesgroup/zz_constants.go | 99 + .../property/valuetypesgroup/zz_models.go | 191 + .../valuetypesgroup/zz_models_serde.go | 870 ++ .../property/valuetypesgroup/zz_options.go | 307 + .../property/valuetypesgroup/zz_responses.go | 324 + .../valuetypesgroup/zz_valuetypes_client.go | 272 + .../zz_valuetypesboolean_client.go | 104 + .../zz_valuetypesbooleanliteral_client.go | 106 + .../zz_valuetypesbytes_client.go | 104 + .../zz_valuetypescollectionsint_client.go | 106 + .../zz_valuetypescollectionsmodel_client.go | 106 + .../zz_valuetypescollectionsstring_client.go | 106 + .../zz_valuetypesdatetime_client.go | 104 + .../zz_valuetypesdecimal128_client.go | 106 + .../zz_valuetypesdecimal_client.go | 104 + .../zz_valuetypesdictionarystring_client.go | 106 + .../zz_valuetypesduration_client.go | 104 + .../zz_valuetypesenum_client.go | 104 + .../zz_valuetypesextensibleenum_client.go | 106 + .../zz_valuetypesfloat_client.go | 104 + .../zz_valuetypesfloatliteral_client.go | 106 + .../zz_valuetypesint_client.go | 104 + .../zz_valuetypesintliteral_client.go | 106 + .../zz_valuetypesmodel_client.go | 104 + .../zz_valuetypesnever_client.go | 104 + .../zz_valuetypesstring_client.go | 104 + .../zz_valuetypesstringliteral_client.go | 106 + .../zz_valuetypesunionenumvalue_client.go | 106 + .../zz_valuetypesunionfloatliteral_client.go | 106 + .../zz_valuetypesunionintliteral_client.go | 106 + .../zz_valuetypesunionstringliteral_client.go | 106 + .../zz_valuetypesunknownarray_client.go | 106 + .../zz_valuetypesunknowndict_client.go | 106 + .../zz_valuetypesunknownint_client.go | 106 + .../zz_valuetypesunknownstring_client.go | 106 + .../property/valuetypesgroup/zz_version.go | 10 + test/http-specs/type/scalargroup/LICENSE.txt | 21 + .../type/scalargroup/boolean_client_test.go | 29 + .../scalargroup/decimal128type_client_test.go | 37 + .../decimal128verify_client_test.go | 28 + .../scalargroup/decimaltype_client_test.go | 37 + .../scalargroup/decimalverify_client_test.go | 28 + .../type/scalargroup/fake/zz_internal.go | 39 + .../type/scalargroup/fake/zz_scalar_server.go | 123 + .../fake/zz_scalarboolean_server.go | 130 + .../fake/zz_scalardecimal128type_server.go | 161 + .../fake/zz_scalardecimal128verify_server.go | 130 + .../fake/zz_scalardecimaltype_server.go | 161 + .../fake/zz_scalardecimalverify_server.go | 130 + .../fake/zz_scalarstring_server.go | 130 + .../fake/zz_scalarunknown_server.go | 130 + test/http-specs/type/scalargroup/go.mod | 17 + test/http-specs/type/scalargroup/go.sum | 25 + .../type/scalargroup/string_client_test.go | 29 + .../type/scalargroup/testdata/_metadata.json | 3 + .../type/scalargroup/unknown_client_test.go | 28 + .../http-specs/type/scalargroup/zz_options.go | 94 + .../type/scalargroup/zz_responses.go | 85 + .../type/scalargroup/zz_scalar_client.go | 96 + .../scalargroup/zz_scalarboolean_client.go | 104 + .../zz_scalardecimal128type_client.go | 145 + .../zz_scalardecimal128verify_client.go | 105 + .../zz_scalardecimaltype_client.go | 145 + .../zz_scalardecimalverify_client.go | 105 + .../scalargroup/zz_scalarstring_client.go | 104 + .../scalargroup/zz_scalarunknown_client.go | 104 + .../http-specs/type/scalargroup/zz_version.go | 10 + .../versioning/madeoptionalgroup/LICENSE.txt | 21 + .../madeoptionalgroup/fake/zz_internal.go | 30 + .../fake/zz_madeoptional_server.go | 113 + .../versioning/madeoptionalgroup/go.mod | 17 + .../versioning/madeoptionalgroup/go.sum | 25 + .../madeoptional_client_test.go | 27 + .../madeoptionalgroup/testdata/_metadata.json | 6 + .../zz_madeoptional_client.go | 109 + .../versioning/madeoptionalgroup/zz_models.go | 11 + .../madeoptionalgroup/zz_models_serde.go | 63 + .../madeoptionalgroup/zz_options.go | 10 + .../madeoptionalgroup/zz_responses.go | 10 + .../madeoptionalgroup/zz_version.go | 10 + .../rettypechangedfromgroup/LICENSE.txt | 21 + .../fake/zz_internal.go | 20 + .../fake/zz_returntypechangedfrom_server.go | 105 + .../versioning/rettypechangedfromgroup/go.mod | 17 + .../versioning/rettypechangedfromgroup/go.sum | 25 + .../returntypechangedfrom_client_test.go | 21 + .../testdata/_metadata.json | 6 + .../rettypechangedfromgroup/zz_options.go | 10 + .../rettypechangedfromgroup/zz_responses.go | 10 + .../zz_returntypechangedfrom_client.go | 105 + .../rettypechangedfromgroup/zz_version.go | 10 + .../typechangedfromgroup/LICENSE.txt | 21 + .../typechangedfromgroup/fake/zz_internal.go | 20 + .../fake/zz_typechangedfrom_server.go | 106 + .../versioning/typechangedfromgroup/go.mod | 17 + .../versioning/typechangedfromgroup/go.sum | 25 + .../testdata/_metadata.json | 6 + .../typechangedfrom_client_test.go | 29 + .../typechangedfromgroup/zz_models.go | 13 + .../typechangedfromgroup/zz_models_serde.go | 63 + .../typechangedfromgroup/zz_options.go | 10 + .../typechangedfromgroup/zz_responses.go | 10 + .../zz_typechangedfrom_client.go | 107 + .../typechangedfromgroup/zz_version.go | 10 + test/local/armapicenter/LICENSE.txt | 21 + .../fake/zz_apidefinitions_server.go | 520 + .../local/armapicenter/fake/zz_apis_server.go | 340 + .../armapicenter/fake/zz_apisources_server.go | 340 + .../fake/zz_apiversions_server.go | 360 + .../fake/zz_deletedservices_server.go | 256 + .../fake/zz_deployments_server.go | 360 + .../fake/zz_environments_server.go | 340 + test/local/armapicenter/fake/zz_internal.go | 72 + .../fake/zz_metadataschemas_server.go | 320 + .../armapicenter/fake/zz_operations_server.go | 113 + .../armapicenter/fake/zz_server_factory.go | 140 + .../armapicenter/fake/zz_services_server.go | 387 + .../armapicenter/fake/zz_workspaces_server.go | 320 + test/local/armapicenter/go.mod | 11 + test/local/armapicenter/go.sum | 16 + .../armapicenter/testdata/_metadata.json | 6 + .../armapicenter/zz_apidefinitions_client.go | 627 ++ test/local/armapicenter/zz_apis_client.go | 388 + .../armapicenter/zz_apisources_client.go | 389 + .../armapicenter/zz_apiversions_client.go | 414 + test/local/armapicenter/zz_client_factory.go | 120 + test/local/armapicenter/zz_constants.go | 375 + .../armapicenter/zz_deletedservices_client.go | 272 + .../armapicenter/zz_deployments_client.go | 414 + .../armapicenter/zz_environments_client.go | 389 + .../armapicenter/zz_metadataschemas_client.go | 365 + test/local/armapicenter/zz_models.go | 717 ++ test/local/armapicenter/zz_models_serde.go | 2008 ++++ .../armapicenter/zz_operations_client.go | 85 + test/local/armapicenter/zz_options.go | 295 + test/local/armapicenter/zz_responses.go | 369 + test/local/armapicenter/zz_services_client.go | 477 + test/local/armapicenter/zz_version.go | 10 + .../armapicenter/zz_workspaces_client.go | 364 + test/local/armbillingbenefits/LICENSE.txt | 21 + .../fake/zz_applicablemaccs_server.go | 125 + ...zz_conditionalcreditcontributors_server.go | 222 + .../fake/zz_conditionalcredits_server.go | 467 + .../fake/zz_contributors_server.go | 222 + .../fake/zz_credits_server.go | 467 + .../fake/zz_discount_server.go | 175 + .../fake/zz_discounts_server.go | 372 + .../fake/zz_freeservices_server.go | 370 + .../armbillingbenefits/fake/zz_internal.go | 83 + .../fake/zz_maccs_server.go | 530 + .../fake/zz_operations_server.go | 113 + .../fake/zz_reservationorderalias_server.go | 167 + .../armbillingbenefits/fake/zz_rp_server.go | 105 + .../fake/zz_savingsplan_server.go | 344 + .../fake/zz_savingsplanorder_server.go | 194 + .../fake/zz_savingsplanorderalias_server.go | 167 + .../fake/zz_sellerresource_server.go | 105 + .../fake/zz_server_factory.go | 190 + .../fake/zz_sources_server.go | 310 + test/local/armbillingbenefits/go.mod | 11 + test/local/armbillingbenefits/go.sum | 16 + .../testdata/_metadata.json | 6 + .../zz_applicablemaccs_client.go | 93 + .../armbillingbenefits/zz_client_factory.go | 161 + ...zz_conditionalcreditcontributors_client.go | 233 + .../zz_conditionalcredits_client.go | 569 ++ test/local/armbillingbenefits/zz_constants.go | 836 ++ .../zz_contributors_client.go | 232 + .../armbillingbenefits/zz_credits_client.go | 564 ++ .../armbillingbenefits/zz_discount_client.go | 181 + .../armbillingbenefits/zz_discounts_client.go | 425 + .../zz_freeservices_client.go | 443 + .../local/armbillingbenefits/zz_interfaces.go | 52 + .../armbillingbenefits/zz_maccs_client.go | 667 ++ test/local/armbillingbenefits/zz_models.go | 2491 +++++ .../armbillingbenefits/zz_models_serde.go | 5226 ++++++++++ .../zz_operations_client.go | 85 + test/local/armbillingbenefits/zz_options.go | 401 + .../zz_polymorphic_helpers.go | 128 + .../zz_reservationorderalias_client.go | 161 + test/local/armbillingbenefits/zz_responses.go | 393 + test/local/armbillingbenefits/zz_rp_client.go | 90 + .../zz_savingsplan_client.go | 356 + .../zz_savingsplanorder_client.go | 198 + .../zz_savingsplanorderalias_client.go | 161 + .../zz_sellerresource_client.go | 90 + .../armbillingbenefits/zz_sources_client.go | 372 + test/local/armbillingbenefits/zz_version.go | 10 + test/local/armcodesigning/LICENSE.txt | 21 + .../armcodesigning/fake/zz_accounts_server.go | 405 + .../fake/zz_certificateprofiles_server.go | 336 + test/local/armcodesigning/fake/zz_internal.go | 64 + .../fake/zz_operations_server.go | 113 + .../armcodesigning/fake/zz_server_factory.go | 80 + test/local/armcodesigning/go.mod | 11 + test/local/armcodesigning/go.sum | 16 + .../armcodesigning/testdata/_metadata.json | 6 + .../armcodesigning/zz_accounts_client.go | 496 + .../zz_certificateprofiles_client.go | 393 + .../local/armcodesigning/zz_client_factory.go | 56 + test/local/armcodesigning/zz_constants.go | 227 + test/local/armcodesigning/zz_models.go | 309 + test/local/armcodesigning/zz_models_serde.go | 830 ++ .../armcodesigning/zz_operations_client.go | 85 + test/local/armcodesigning/zz_options.go | 82 + test/local/armcodesigning/zz_responses.go | 80 + test/local/armcodesigning/zz_version.go | 10 + test/local/armcognitiveservices/LICENSE.txt | 21 + .../fake/zz_accountcapabilityhosts_server.go | 289 + .../fake/zz_accountconnections_server.go | 326 + .../fake/zz_accounts_server.go | 587 ++ .../fake/zz_agentapplications_server.go | 487 + .../fake/zz_agentdeployments_server.go | 451 + .../fake/zz_commitmentplans_server.go | 773 ++ .../fake/zz_commitmenttiers_server.go | 125 + .../fake/zz_defenderforaisettings_server.go | 267 + .../fake/zz_deletedaccounts_server.go | 221 + .../fake/zz_deployments_server.go | 488 + .../fake/zz_encryptionscopes_server.go | 276 + .../armcognitiveservices/fake/zz_internal.go | 83 + .../zz_locationbasedmodelcapacities_server.go | 126 + .../zz_managednetworkprovisions_server.go | 147 + .../fake/zz_managednetworksettings_server.go | 349 + .../fake/zz_management_server.go | 187 + .../fake/zz_modelcapacities_server.go | 121 + .../fake/zz_models_server.go | 125 + ...ksecurityperimeterconfigurations_server.go | 229 + .../fake/zz_operations_server.go | 113 + .../fake/zz_outboundrule_server.go | 305 + .../fake/zz_outboundrules_server.go | 140 + .../zz_privateendpointconnections_server.go | 278 + .../fake/zz_privatelinkresources_server.go | 117 + .../fake/zz_projectcapabilityhosts_server.go | 305 + .../fake/zz_projectconnections_server.go | 346 + .../fake/zz_projects_server.go | 349 + .../fake/zz_quotatiers_server.go | 235 + .../fake/zz_raiblocklistitems_server.go | 386 + .../fake/zz_raiblocklists_server.go | 276 + .../fake/zz_raicontentfilters_server.go | 165 + .../zz_raiexternalsafetyprovider_server.go | 202 + .../zz_raiexternalsafetyproviders_server.go | 120 + .../fake/zz_raipolicies_server.go | 276 + .../fake/zz_raitoollabels_server.go | 276 + .../fake/zz_raitopics_server.go | 276 + .../fake/zz_resourceskus_server.go | 120 + .../fake/zz_server_factory.go | 384 + .../fake/zz_subscriptionraipolicy_server.go | 202 + ...zz_testraiexternalsafetyprovider_server.go | 125 + .../fake/zz_usages_server.go | 133 + test/local/armcognitiveservices/go.mod | 11 + test/local/armcognitiveservices/go.sum | 16 + .../testdata/_metadata.json | 6 + .../zz_accountcapabilityhosts_client.go | 344 + .../zz_accountconnections_client.go | 395 + .../zz_accounts_client.go | 756 ++ .../zz_agentapplications_client.go | 589 ++ .../zz_agentdeployments_client.go | 536 + .../armcognitiveservices/zz_client_factory.go | 344 + .../zz_commitmentplans_client.go | 1008 ++ .../zz_commitmenttiers_client.go | 100 + .../armcognitiveservices/zz_constants.go | 1646 +++ .../zz_defenderforaisettings_client.go | 319 + .../zz_deletedaccounts_client.go | 238 + .../zz_deployments_client.go | 618 ++ .../zz_encryptionscopes_client.go | 321 + .../armcognitiveservices/zz_interfaces.go | 45 + .../zz_locationbasedmodelcapacities_client.go | 106 + .../zz_managednetworkprovisions_client.go | 130 + .../zz_managednetworksettings_client.go | 429 + .../zz_management_client.go | 221 + .../zz_modelcapacities_client.go | 101 + test/local/armcognitiveservices/zz_models.go | 3778 +++++++ .../armcognitiveservices/zz_models_client.go | 99 + .../armcognitiveservices/zz_models_serde.go | 8811 +++++++++++++++++ ...ksecurityperimeterconfigurations_client.go | 250 + .../zz_operations_client.go | 85 + test/local/armcognitiveservices/zz_options.go | 877 ++ .../zz_outboundrule_client.go | 367 + .../zz_outboundrules_client.go | 153 + .../zz_polymorphic_helpers.go | 142 + .../zz_privateendpointconnections_client.go | 332 + .../zz_privatelinkresources_client.go | 105 + .../zz_projectcapabilityhosts_client.go | 364 + .../zz_projectconnections_client.go | 420 + .../zz_projects_client.go | 410 + .../zz_quotatiers_client.go | 286 + .../zz_raiblocklistitems_client.go | 476 + .../zz_raiblocklists_client.go | 320 + .../zz_raicontentfilters_client.go | 162 + .../zz_raiexternalsafetyprovider_client.go | 229 + .../zz_raiexternalsafetyproviders_client.go | 95 + .../zz_raipolicies_client.go | 319 + .../zz_raitoollabels_client.go | 320 + .../zz_raitopics_client.go | 319 + .../zz_resourceskus_client.go | 94 + .../armcognitiveservices/zz_responses.go | 847 ++ .../zz_subscriptionraipolicy_client.go | 229 + ...zz_testraiexternalsafetyprovider_client.go | 115 + .../armcognitiveservices/zz_usages_client.go | 102 + test/local/armcognitiveservices/zz_version.go | 10 + test/local/armcommunitymanagement/LICENSE.txt | 21 + .../fake/zz_communitytrainings_server.go | 370 + .../fake/zz_internal.go | 64 + .../fake/zz_operations_server.go | 113 + .../fake/zz_server_factory.go | 73 + test/local/armcommunitymanagement/go.mod | 11 + test/local/armcommunitymanagement/go.sum | 16 + .../testdata/_metadata.json | 6 + .../zz_client_factory.go | 48 + .../zz_communitytrainings_client.go | 441 + .../armcommunitymanagement/zz_constants.go | 128 + .../local/armcommunitymanagement/zz_models.go | 211 + .../armcommunitymanagement/zz_models_serde.go | 527 + .../zz_operations_client.go | 85 + .../armcommunitymanagement/zz_options.go | 48 + .../armcommunitymanagement/zz_responses.go | 46 + .../armcommunitymanagement/zz_version.go | 10 + test/local/armcomputeschedule/LICENSE.txt | 21 + .../armcomputeschedule/fake/zz_internal.go | 64 + .../fake/zz_occurrenceextension_server.go | 125 + .../fake/zz_occurrences_server.go | 333 + .../fake/zz_operations_server.go | 113 + .../zz_scheduledactionextension_server.go | 125 + .../fake/zz_scheduledactions_server.go | 1163 +++ .../fake/zz_server_factory.go | 98 + test/local/armcomputeschedule/go.mod | 11 + test/local/armcomputeschedule/go.sum | 16 + .../testdata/_metadata.json | 6 + .../armcomputeschedule/zz_client_factory.go | 70 + test/local/armcomputeschedule/zz_constants.go | 1236 +++ test/local/armcomputeschedule/zz_models.go | 2193 ++++ .../armcomputeschedule/zz_models_serde.go | 5461 ++++++++++ .../zz_occurrenceextension_client.go | 92 + .../zz_occurrences_client.go | 393 + .../zz_operations_client.go | 85 + test/local/armcomputeschedule/zz_options.go | 203 + test/local/armcomputeschedule/zz_responses.go | 206 + .../zz_scheduledactionextension_client.go | 92 + .../zz_scheduledactions_client.go | 1699 ++++ test/local/armcomputeschedule/zz_version.go | 10 + .../LICENSE.txt | 21 + .../fake/zz_bgppeers_server.go | 260 + .../fake/zz_internal.go | 64 + .../fake/zz_loadbalancers_server.go | 260 + .../fake/zz_operations_server.go | 113 + .../fake/zz_server_factory.go | 94 + .../fake/zz_services_server.go | 247 + .../fake/zz_storageclass_server.go | 329 + .../armcontainerorchestratorruntime/go.mod | 11 + .../armcontainerorchestratorruntime/go.sum | 16 + .../testdata/_metadata.json | 6 + .../zz_bgppeers_client.go | 271 + .../zz_client_factory.go | 65 + .../zz_constants.go | 292 + .../zz_interfaces.go | 15 + .../zz_loadbalancers_client.go | 271 + .../zz_models.go | 464 + .../zz_models_serde.go | 1073 ++ .../zz_operations_client.go | 85 + .../zz_options.go | 102 + .../zz_polymorphic_helpers.go | 36 + .../zz_responses.go | 109 + .../zz_services_client.go | 260 + .../zz_storageclass_client.go | 364 + .../zz_version.go | 10 + test/local/armdatabasewatcher/LICENSE.txt | 21 + .../fake/zz_alertruleresources_server.go | 263 + .../fake/zz_healthvalidations_server.go | 229 + .../armdatabasewatcher/fake/zz_internal.go | 64 + .../fake/zz_operations_server.go | 113 + .../fake/zz_server_factory.go | 105 + .../zz_sharedprivatelinkresources_server.go | 289 + .../fake/zz_targets_server.go | 263 + .../fake/zz_watchers_server.go | 474 + test/local/armdatabasewatcher/go.mod | 11 + test/local/armdatabasewatcher/go.sum | 16 + .../testdata/_metadata.json | 6 + .../zz_alertruleresources_client.go | 302 + .../armdatabasewatcher/zz_client_factory.go | 80 + test/local/armdatabasewatcher/zz_constants.go | 276 + .../zz_healthvalidations_client.go | 249 + .../local/armdatabasewatcher/zz_interfaces.go | 14 + test/local/armdatabasewatcher/zz_models.go | 556 ++ .../armdatabasewatcher/zz_models_serde.go | 1257 +++ .../zz_operations_client.go | 85 + test/local/armdatabasewatcher/zz_options.go | 143 + .../zz_polymorphic_helpers.go | 32 + test/local/armdatabasewatcher/zz_responses.go | 143 + .../zz_sharedprivatelinkresources_client.go | 332 + .../armdatabasewatcher/zz_targets_client.go | 300 + test/local/armdatabasewatcher/zz_version.go | 10 + .../armdatabasewatcher/zz_watchers_client.go | 581 ++ .../local/armdevopsinfrastructure/LICENSE.txt | 21 + .../fake/zz_imageversions_server.go | 129 + .../fake/zz_internal.go | 64 + .../fake/zz_operations_server.go | 113 + .../fake/zz_pools_server.go | 448 + .../fake/zz_resourcedetails_server.go | 129 + .../fake/zz_server_factory.go | 105 + .../fake/zz_sku_server.go | 125 + .../fake/zz_subscriptionusages_server.go | 125 + test/local/armdevopsinfrastructure/go.mod | 11 + test/local/armdevopsinfrastructure/go.sum | 16 + .../testdata/_metadata.json | 6 + .../zz_client_factory.go | 80 + .../armdevopsinfrastructure/zz_constants.go | 451 + .../zz_imageversions_client.go | 105 + .../armdevopsinfrastructure/zz_interfaces.go | 41 + .../armdevopsinfrastructure/zz_models.go | 786 ++ .../zz_models_serde.go | 1985 ++++ .../zz_operations_client.go | 85 + .../armdevopsinfrastructure/zz_options.go | 77 + .../zz_polymorphic_helpers.go | 97 + .../zz_pools_client.go | 553 ++ .../zz_resourcedetails_client.go | 105 + .../armdevopsinfrastructure/zz_responses.go | 81 + .../armdevopsinfrastructure/zz_sku_client.go | 99 + .../zz_subscriptionusages_client.go | 100 + .../armdevopsinfrastructure/zz_version.go | 10 + .../armhardwaresecuritymodules/LICENSE.txt | 21 + .../zz_cloudhsmclusterbackupstatus_server.go | 127 + ...lusterprivateendpointconnections_server.go | 226 + ...udhsmclusterprivatelinkresources_server.go | 129 + .../zz_cloudhsmclusterrestorestatus_server.go | 127 + .../fake/zz_cloudhsmclusters_server.go | 629 ++ .../fake/zz_dedicatedhsm_server.go | 454 + .../fake/zz_internal.go | 83 + .../fake/zz_operations_server.go | 113 + .../zz_privateendpointconnections_server.go | 129 + .../fake/zz_server_factory.go | 125 + test/local/armhardwaresecuritymodules/go.mod | 11 + test/local/armhardwaresecuritymodules/go.sum | 16 + .../testdata/_metadata.json | 6 + .../zz_client_factory.go | 96 + .../zz_cloudhsmclusterbackupstatus_client.go | 117 + ...lusterprivateendpointconnections_client.go | 263 + ...udhsmclusterprivatelinkresources_client.go | 106 + .../zz_cloudhsmclusterrestorestatus_client.go | 117 + .../zz_cloudhsmclusters_client.go | 772 ++ .../zz_constants.go | 343 + .../zz_dedicatedhsm_client.go | 512 + .../armhardwaresecuritymodules/zz_models.go | 547 + .../zz_models_serde.go | 1536 +++ .../zz_operations_client.go | 85 + .../armhardwaresecuritymodules/zz_options.go | 171 + .../zz_privateendpointconnections_client.go | 107 + .../zz_responses.go | 164 + .../armhardwaresecuritymodules/zz_version.go | 10 + test/local/armhealthbot/LICENSE.txt | 21 + .../local/armhealthbot/fake/zz_bots_server.go | 448 + test/local/armhealthbot/fake/zz_internal.go | 64 + .../armhealthbot/fake/zz_operations_server.go | 113 + .../armhealthbot/fake/zz_server_factory.go | 71 + test/local/armhealthbot/go.mod | 11 + test/local/armhealthbot/go.sum | 16 + .../armhealthbot/testdata/_metadata.json | 6 + test/local/armhealthbot/zz_bots_client.go | 561 ++ test/local/armhealthbot/zz_client_factory.go | 48 + test/local/armhealthbot/zz_constants.go | 74 + test/local/armhealthbot/zz_models.go | 206 + test/local/armhealthbot/zz_models_serde.go | 598 ++ .../armhealthbot/zz_operations_client.go | 88 + test/local/armhealthbot/zz_options.go | 53 + test/local/armhealthbot/zz_responses.go | 58 + test/local/armhealthbot/zz_version.go | 10 + test/local/armlargeinstance/LICENSE.txt | 21 + .../zz_azurelargestorageinstance_server.go | 331 + .../armlargeinstance/fake/zz_internal.go | 64 + .../fake/zz_operations_server.go | 113 + test/local/armlargeinstance/fake/zz_server.go | 498 + .../fake/zz_server_factory.go | 80 + test/local/armlargeinstance/go.mod | 11 + test/local/armlargeinstance/go.sum | 16 + .../armlargeinstance/testdata/_metadata.json | 6 + .../zz_azurelargestorageinstance_client.go | 411 + test/local/armlargeinstance/zz_client.go | 625 ++ .../armlargeinstance/zz_client_factory.go | 56 + test/local/armlargeinstance/zz_constants.go | 419 + test/local/armlargeinstance/zz_models.go | 389 + .../local/armlargeinstance/zz_models_serde.go | 1054 ++ .../armlargeinstance/zz_operations_client.go | 85 + test/local/armlargeinstance/zz_options.go | 98 + test/local/armlargeinstance/zz_responses.go | 104 + test/local/armlargeinstance/zz_version.go | 10 + test/local/armloadtestservice/LICENSE.txt | 21 + .../armloadtestservice/fake/zz_internal.go | 64 + .../fake/zz_loadtestmappings_server.go | 290 + .../fake/zz_loadtestprofilemappings_server.go | 290 + .../fake/zz_loadtests_server.go | 419 + ...lyvirtualuserhourslimitsresource_server.go | 160 + .../fake/zz_operations_server.go | 113 + .../fake/zz_quotas_server.go | 208 + .../fake/zz_server_factory.go | 105 + test/local/armloadtestservice/go.mod | 11 + test/local/armloadtestservice/go.sum | 16 + .../testdata/_metadata.json | 6 + .../armloadtestservice/zz_client_factory.go | 75 + test/local/armloadtestservice/zz_constants.go | 136 + .../zz_loadtestmappings_client.go | 325 + .../zz_loadtestprofilemappings_client.go | 328 + .../armloadtestservice/zz_loadtests_client.go | 502 + ...lyvirtualuserhourslimitsresource_client.go | 174 + test/local/armloadtestservice/zz_models.go | 480 + .../armloadtestservice/zz_models_serde.go | 1396 +++ .../zz_operations_client.go | 85 + test/local/armloadtestservice/zz_options.go | 134 + .../armloadtestservice/zz_quotas_client.go | 229 + test/local/armloadtestservice/zz_responses.go | 140 + test/local/armloadtestservice/zz_version.go | 10 + test/local/armmongocluster/LICENSE.txt | 21 + .../fake/zz_firewallrules_server.go | 289 + .../local/armmongocluster/fake/zz_internal.go | 64 + .../fake/zz_mongoclusters_server.go | 504 + .../fake/zz_operations_server.go | 113 + .../zz_privateendpointconnections_server.go | 289 + .../fake/zz_privatelinks_server.go | 129 + .../fake/zz_replicas_server.go | 129 + .../armmongocluster/fake/zz_server_factory.go | 112 + .../armmongocluster/fake/zz_users_server.go | 289 + test/local/armmongocluster/go.mod | 11 + test/local/armmongocluster/go.sum | 16 + .../armmongocluster/testdata/_metadata.json | 6 + .../armmongocluster/zz_client_factory.go | 88 + test/local/armmongocluster/zz_constants.go | 523 + .../zz_firewallrules_client.go | 331 + test/local/armmongocluster/zz_interfaces.go | 14 + test/local/armmongocluster/zz_models.go | 688 ++ test/local/armmongocluster/zz_models_serde.go | 1903 ++++ .../zz_mongoclusters_client.go | 646 ++ .../armmongocluster/zz_operations_client.go | 85 + test/local/armmongocluster/zz_options.go | 146 + .../armmongocluster/zz_polymorphic_helpers.go | 28 + .../zz_privateendpointconnections_client.go | 332 + .../armmongocluster/zz_privatelinks_client.go | 105 + .../armmongocluster/zz_replicas_client.go | 105 + test/local/armmongocluster/zz_responses.go | 144 + test/local/armmongocluster/zz_users_client.go | 330 + test/local/armmongocluster/zz_version.go | 10 + test/local/armoracledatabase/LICENSE.txt | 21 + .../zz_autonomousdatabasebackups_server.go | 349 + ..._autonomousdatabasecharactersets_server.go | 165 + ...ousdatabasenationalcharactersets_server.go | 165 + .../fake/zz_autonomousdatabases_server.go | 745 ++ .../zz_autonomousdatabaseversions_server.go | 165 + .../zz_cloudexadatainfrastructures_server.go | 478 + .../fake/zz_cloudvmclusters_server.go | 525 + .../fake/zz_dbnodes_server.go | 233 + .../fake/zz_dbservers_server.go | 173 + .../fake/zz_dbsystems_server.go | 370 + .../fake/zz_dbsystemshapes_server.go | 175 + .../fake/zz_dbversions_server.go | 190 + .../fake/zz_dnsprivateviews_server.go | 165 + .../fake/zz_dnsprivatezones_server.go | 165 + .../fake/zz_exadbvmclusters_server.go | 426 + .../fake/zz_exascaledbnodes_server.go | 233 + .../fake/zz_exascaledbstoragevaults_server.go | 370 + .../fake/zz_flexcomponents_server.go | 173 + .../fake/zz_giminorversions_server.go | 183 + .../fake/zz_giversions_server.go | 177 + .../armoracledatabase/fake/zz_internal.go | 83 + .../fake/zz_networkanchors_server.go | 370 + .../fake/zz_operations_server.go | 113 + .../fake/zz_oraclesubscriptions_server.go | 472 + .../fake/zz_resourceanchors_server.go | 370 + .../fake/zz_server_factory.go | 279 + .../fake/zz_systemversions_server.go | 165 + .../fake/zz_virtualnetworkaddresses_server.go | 289 + test/local/armoracledatabase/go.mod | 11 + test/local/armoracledatabase/go.sum | 16 + .../armoracledatabase/testdata/_metadata.json | 6 + .../zz_autonomousdatabasebackups_client.go | 413 + ..._autonomousdatabasecharactersets_client.go | 163 + ...ousdatabasenationalcharactersets_client.go | 163 + .../zz_autonomousdatabases_client.go | 965 ++ .../zz_autonomousdatabaseversions_client.go | 163 + .../armoracledatabase/zz_client_factory.go | 240 + .../zz_cloudexadatainfrastructures_client.go | 590 ++ .../zz_cloudvmclusters_client.go | 662 ++ test/local/armoracledatabase/zz_constants.go | 1683 ++++ .../armoracledatabase/zz_dbnodes_client.go | 253 + .../armoracledatabase/zz_dbservers_client.go | 172 + .../armoracledatabase/zz_dbsystems_client.go | 438 + .../zz_dbsystemshapes_client.go | 168 + .../armoracledatabase/zz_dbversions_client.go | 181 + .../zz_dnsprivateviews_client.go | 162 + .../zz_dnsprivatezones_client.go | 162 + .../zz_exadbvmclusters_client.go | 517 + .../zz_exascaledbnodes_client.go | 254 + .../zz_exascaledbstoragevaults_client.go | 441 + .../zz_flexcomponents_client.go | 165 + .../zz_giminorversions_client.go | 178 + .../armoracledatabase/zz_giversions_client.go | 171 + test/local/armoracledatabase/zz_interfaces.go | 24 + test/local/armoracledatabase/zz_models.go | 4684 +++++++++ .../armoracledatabase/zz_models_serde.go | 8441 ++++++++++++++++ .../zz_networkanchors_client.go | 440 + .../armoracledatabase/zz_operations_client.go | 85 + test/local/armoracledatabase/zz_options.go | 714 ++ .../zz_oraclesubscriptions_client.go | 594 ++ .../zz_polymorphic_helpers.go | 34 + .../zz_resourceanchors_client.go | 440 + test/local/armoracledatabase/zz_responses.go | 652 ++ .../zz_systemversions_client.go | 162 + test/local/armoracledatabase/zz_version.go | 10 + .../zz_virtualnetworkaddresses_client.go | 331 + test/local/armpageablelros/LICENSE.txt | 21 + .../local/armpageablelros/fake/zz_internal.go | 64 + test/local/armpageablelros/fake/zz_server.go | 133 + .../armpageablelros/fake/zz_server_factory.go | 64 + test/local/armpageablelros/go.mod | 11 + test/local/armpageablelros/go.sum | 16 + .../armpageablelros/testdata/_metadata.json | 3 + test/local/armpageablelros/zz_client.go | 138 + .../armpageablelros/zz_client_factory.go | 41 + test/local/armpageablelros/zz_models.go | 22 + test/local/armpageablelros/zz_models_serde.go | 117 + test/local/armpageablelros/zz_options.go | 11 + test/local/armpageablelros/zz_responses.go | 11 + test/local/armpageablelros/zz_version.go | 10 + test/local/armrandom/LICENSE.txt | 21 + test/local/armrandom/fake/zz_internal.go | 64 + test/local/armrandom/fake/zz_server.go | 113 + .../local/armrandom/fake/zz_server_factory.go | 71 + .../armrandom/fake/zz_someservice_server.go | 150 + test/local/armrandom/go.mod | 11 + test/local/armrandom/go.sum | 16 + test/local/armrandom/testdata/_metadata.json | 6 + test/local/armrandom/zz_client.go | 99 + test/local/armrandom/zz_client_factory.go | 48 + test/local/armrandom/zz_constants.go | 55 + test/local/armrandom/zz_models.go | 64 + test/local/armrandom/zz_models_serde.go | 203 + test/local/armrandom/zz_options.go | 22 + test/local/armrandom/zz_responses.go | 23 + test/local/armrandom/zz_someservice_client.go | 138 + test/local/armrandom/zz_version.go | 10 + test/local/armtest/LICENSE.txt | 21 + .../armtest/fake/zz_authorization_server.go | 113 + .../fake/zz_authorizationserver_server.go | 113 + .../local/armtest/fake/zz_bodyroots_server.go | 203 + .../armtest/fake/zz_configurations_server.go | 241 + test/local/armtest/fake/zz_internal.go | 104 + test/local/armtest/fake/zz_lro_server.go | 192 + .../fake/zz_mixedscopewidgets_server.go | 196 + .../zz_parametergroupoperations_server.go | 282 + test/local/armtest/fake/zz_pets_server.go | 207 + .../armtest/fake/zz_polymorphic_helpers.go | 33 + test/local/armtest/fake/zz_server_factory.go | 130 + .../armtest/fake/zz_tenantitems_server.go | 151 + test/local/armtest/go.mod | 11 + test/local/armtest/go.sum | 16 + test/local/armtest/testdata/_metadata.json | 6 + test/local/armtest/zz_authorization_client.go | 92 + .../armtest/zz_authorizationserver_client.go | 92 + test/local/armtest/zz_bodyroots_client.go | 228 + test/local/armtest/zz_client_factory.go | 99 + .../local/armtest/zz_configurations_client.go | 293 + test/local/armtest/zz_constants.go | 81 + test/local/armtest/zz_interfaces.go | 14 + test/local/armtest/zz_lro_client.go | 195 + .../armtest/zz_mixedscopewidgets_client.go | 206 + test/local/armtest/zz_models.go | 397 + test/local/armtest/zz_models_serde.go | 1060 ++ test/local/armtest/zz_options.go | 148 + .../zz_parametergroupoperations_client.go | 313 + test/local/armtest/zz_pets_client.go | 236 + test/local/armtest/zz_polymorphic_helpers.go | 30 + test/local/armtest/zz_responses.go | 142 + test/local/armtest/zz_responses_serde.go | 22 + test/local/armtest/zz_tenantitems_client.go | 140 + test/local/armtest/zz_version.go | 10 + test/local/azblob/LICENSE.txt | 21 + test/local/azblob/client.go | 20 + test/local/azblob/go.mod | 11 + test/local/azblob/go.sum | 16 + test/local/azblob/models_serde_test.go | 1276 +++ test/local/azblob/testdata/_metadata.json | 6 + test/local/azblob/zz_appendblob_client.go | 646 ++ test/local/azblob/zz_blockblob_client.go | 1211 +++ test/local/azblob/zz_client.go | 2682 +++++ test/local/azblob/zz_constants.go | 1046 ++ test/local/azblob/zz_container_client.go | 1542 +++ test/local/azblob/zz_models.go | 710 ++ test/local/azblob/zz_models_serde.go | 527 + test/local/azblob/zz_options.go | 2333 +++++ test/local/azblob/zz_pageblob_client.go | 1241 +++ test/local/azblob/zz_responses.go | 2055 ++++ test/local/azblob/zz_service_client.go | 601 ++ test/local/azblob/zz_version.go | 10 + test/local/azblob/zz_xml_helper.go | 83 + test/local/azclientoption/LICENSE.txt | 21 + test/local/azclientoption/fake/zz_internal.go | 20 + test/local/azclientoption/fake/zz_server.go | 129 + test/local/azclientoption/go.mod | 11 + test/local/azclientoption/go.sum | 16 + .../azclientoption/testdata/_metadata.json | 3 + test/local/azclientoption/zz_client.go | 137 + test/local/azclientoption/zz_models.go | 13 + test/local/azclientoption/zz_options.go | 15 + test/local/azclientoption/zz_responses.go | 16 + test/local/azclientoption/zz_version.go | 10 + test/local/azkeys/LICENSE.txt | 21 + test/local/azkeys/custom_client.go | 20 + test/local/azkeys/fake/zz_internal.go | 56 + test/local/azkeys/fake/zz_server.go | 1124 +++ test/local/azkeys/fake_test.go | 72 + test/local/azkeys/go.mod | 17 + test/local/azkeys/go.sum | 25 + test/local/azkeys/testdata/_metadata.json | 6 + test/local/azkeys/zz_client.go | 1684 ++++ test/local/azkeys/zz_constants.go | 331 + test/local/azkeys/zz_models.go | 514 + test/local/azkeys/zz_models_serde.go | 1500 +++ test/local/azkeys/zz_options.go | 140 + test/local/azkeys/zz_responses.go | 166 + test/local/azkeys/zz_version.go | 10 + test/local/azmodelsonly/LICENSE.txt | 21 + test/local/azmodelsonly/go.mod | 11 + test/local/azmodelsonly/go.sum | 16 + .../azmodelsonly/testdata/_metadata.json | 3 + test/local/azmodelsonly/version.go | 8 + test/local/azmodelsonly/zz_models.go | 26 + test/local/azmodelsonly/zz_models_serde.go | 121 + test/local/azmodelsonly/zz_version.go | 10 + test/local/azregressions/LICENSE.txt | 21 + test/local/azregressions/fake/zz_internal.go | 49 + test/local/azregressions/fake/zz_server.go | 716 ++ test/local/azregressions/go.mod | 17 + test/local/azregressions/go.sum | 25 + test/local/azregressions/server_test.go | 160 + .../azregressions/testdata/_metadata.json | 3 + test/local/azregressions/zz_client.go | 927 ++ test/local/azregressions/zz_constants.go | 56 + test/local/azregressions/zz_interfaces.go | 14 + test/local/azregressions/zz_models.go | 61 + test/local/azregressions/zz_models_serde.go | 206 + test/local/azregressions/zz_options.go | 116 + .../azregressions/zz_polymorphic_helpers.go | 26 + test/local/azregressions/zz_responses.go | 110 + .../local/azregressions/zz_responses_serde.go | 15 + test/local/azregressions/zz_version.go | 10 + test/local/azregressions/zz_xml_helper.go | 83 + test/local/internalpager/LICENSE.txt | 21 + test/local/internalpager/go.mod | 11 + test/local/internalpager/go.sum | 16 + .../internalpager/testdata/_metadata.json | 3 + test/local/internalpager/zz_constants.go | 22 + test/local/internalpager/zz_models.go | 18 + test/local/internalpager/zz_models_serde.go | 90 + test/local/internalpager/zz_options.go | 10 + test/local/internalpager/zz_pager_client.go | 48 + .../internalpager/zz_pagerwidgets_client.go | 64 + test/local/internalpager/zz_responses.go | 10 + test/local/internalpager/zz_version.go | 10 + test/local/nooptionalbody/LICENSE.txt | 21 + test/local/nooptionalbody/after_generate.go | 6 + test/local/nooptionalbody/go.mod | 11 + test/local/nooptionalbody/go.sum | 16 + .../nooptionalbody/testdata/_metadata.json | 3 + .../testdata/generate/transforms.go | 29 + test/local/nooptionalbody/zz_client.go | 151 + test/local/nooptionalbody/zz_models.go | 10 + test/local/nooptionalbody/zz_models_serde.go | 59 + test/local/nooptionalbody/zz_options.go | 20 + test/local/nooptionalbody/zz_responses.go | 20 + test/local/nooptionalbody/zz_version.go | 10 + test/local/rawjson/client.go | 13 + test/local/rawjson/go.mod | 11 + test/local/rawjson/go.sum | 16 + test/local/rawjson/subpkg/fake/zz_internal.go | 31 + .../rawjson/subpkg/fake/zz_rawjson_server.go | 87 + .../subpkg/fake/zz_rawjsoninputonly_server.go | 107 + .../subpkg/fake/zz_rawjsonmodelcase_server.go | 105 + .../fake/zz_rawjsonoutputonly_server.go | 106 + test/local/rawjson/subpkg/zz_models.go | 13 + test/local/rawjson/subpkg/zz_models_serde.go | 53 + test/local/rawjson/subpkg/zz_options.go | 20 + .../local/rawjson/subpkg/zz_rawjson_client.go | 38 + .../subpkg/zz_rawjsoninputonly_client.go | 60 + .../subpkg/zz_rawjsonmodelcase_client.go | 70 + .../subpkg/zz_rawjsonoutputonly_client.go | 67 + test/local/rawjson/subpkg/zz_responses.go | 20 + test/local/rawjson/version.go | 10 + 2542 files changed, 355817 insertions(+) create mode 100644 test/azure-http-specs/azure/client-generator-core/accessgroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/client-generator-core/accessgroup/fake/zz_access_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/accessgroup/fake/zz_accesspublicoperation_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/accessgroup/fake/zz_accesssharedmodelinoperation_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/accessgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/client-generator-core/accessgroup/go.mod create mode 100644 test/azure-http-specs/azure/client-generator-core/accessgroup/go.sum create mode 100644 test/azure-http-specs/azure/client-generator-core/accessgroup/internaloperation_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/accessgroup/publicoperation_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/accessgroup/relativemodelinoperation_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/accessgroup/sharedmodelinoperation_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/accessgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/client-generator-core/accessgroup/zz_access_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/accessgroup/zz_accessinternaloperation_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/accessgroup/zz_accesspublicoperation_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/accessgroup/zz_accessrelativemodelinoperation_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/accessgroup/zz_accesssharedmodelinoperation_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/accessgroup/zz_interfaces.go create mode 100644 test/azure-http-specs/azure/client-generator-core/accessgroup/zz_models.go create mode 100644 test/azure-http-specs/azure/client-generator-core/accessgroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/client-generator-core/accessgroup/zz_options.go create mode 100644 test/azure-http-specs/azure/client-generator-core/accessgroup/zz_polymorphic_helpers.go create mode 100644 test/azure-http-specs/azure/client-generator-core/accessgroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/client-generator-core/accessgroup/zz_responses_serde.go create mode 100644 test/azure-http-specs/azure/client-generator-core/accessgroup/zz_version.go create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/fake/zz_header_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/go.mod create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/go.sum create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/header_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/zz_constants.go create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/zz_header_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/zz_options.go create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/zz_version.go create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/fake/zz_path_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/go.mod create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/go.sum create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/path_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/zz_constants.go create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/zz_options.go create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/zz_path_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/zz_version.go create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/fake/zz_query_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/go.mod create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/go.sum create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/query_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/zz_constants.go create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/zz_options.go create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/zz_query_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/zz_version.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_headerparam_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_mixedparams_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_multipleparams_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_paramalias_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_pathparam_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_queryparam_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/go.mod create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/go.sum create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/headerparam_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/mixedparams_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/multipleparams_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/paramalias_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/pathparam_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/queryparam_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_headerparam_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_mixedparams_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_models.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_multipleparams_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_options.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_paramalias_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_pathparam_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_queryparam_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_version.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_individuallynestedwithheader_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_individuallynestedwithmixed_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_individuallynestedwithmultiple_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_individuallynestedwithparamalias_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_individuallynestedwithpath_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_individuallynestedwithquery_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/go.mod create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/go.sum create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/individuallynestedwithheader_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/individuallynestedwithmixed_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/individuallynestedwithmultiple_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/individuallynestedwithparamalias_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/individuallynestedwithpath_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/individuallynestedwithquery_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_individuallynestedwithheader_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_individuallynestedwithmixed_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_individuallynestedwithmultiple_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_individuallynestedwithparamalias_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_individuallynestedwithpath_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_individuallynestedwithquery_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_models.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_options.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_version.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparent_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparentindividuallyparentnestedwithheader_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparentindividuallyparentnestedwithmixed_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparentindividuallyparentnestedwithmultiple_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparentindividuallyparentnestedwithparamalias_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparentindividuallyparentnestedwithpath_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparentindividuallyparentnestedwithquery_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/go.mod create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/go.sum create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/individuallyparentindividuallyparentnestedwithheader_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/individuallyparentindividuallyparentnestedwithmixed_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/individuallyparentindividuallyparentnestedwithmultiple_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/individuallyparentindividuallyparentnestedwithparamalias_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/individuallyparentindividuallyparentnestedwithpath_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/individuallyparentindividuallyparentnestedwithquery_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparent_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparentindividuallyparentnestedwithheader_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparentindividuallyparentnestedwithmixed_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparentindividuallyparentnestedwithmultiple_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparentindividuallyparentnestedwithparamalias_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparentindividuallyparentnestedwithpath_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparentindividuallyparentnestedwithquery_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_models.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_options.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_version.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/fake/zz_movetoexistingsub_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/fake/zz_movetoexistingsubadminoperations_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/fake/zz_movetoexistingsubuseroperations_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/go.mod create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/go.sum create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/movetoexistingsub_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/zz_movetoexistingsub_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/zz_movetoexistingsubadminoperations_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/zz_movetoexistingsubuseroperations_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/zz_options.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/zz_version.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/fake/zz_movemethodparameterto_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/fake/zz_movemethodparametertobloboperations_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/go.mod create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/go.sum create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/movemethodparameterto_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_models.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_movemethodparameterto_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_movemethodparametertobloboperations_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_options.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_version.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/fake/zz_movetonewsub_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/fake/zz_movetonewsubarchiveoperations_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/fake/zz_movetonewsubproductoperations_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/go.mod create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/go.sum create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/movetonewsub_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/zz_movetonewsub_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/zz_movetonewsubarchiveoperations_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/zz_movetonewsubproductoperations_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/zz_options.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/zz_version.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/fake/zz_movetoroot_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/fake/zz_movetorootresourceoperations_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/go.mod create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/go.sum create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/movetoroot_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/zz_movetoroot_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/zz_movetorootresourceoperations_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/zz_options.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/zz_version.go create mode 100644 test/azure-http-specs/azure/client-generator-core/coreusagegroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/client-generator-core/coreusagegroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/client-generator-core/coreusagegroup/fake/zz_usage_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/coreusagegroup/fake/zz_usagemodelinoperation_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/coreusagegroup/fake/zz_usagenamespaceusage_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/coreusagegroup/go.mod create mode 100644 test/azure-http-specs/azure/client-generator-core/coreusagegroup/go.sum create mode 100644 test/azure-http-specs/azure/client-generator-core/coreusagegroup/modelinoperation_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/coreusagegroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_models.go create mode 100644 test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_options.go create mode 100644 test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_usage_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_usagemodelinoperation_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_usagenamespaceusage_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_version.go create mode 100644 test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/clientdefaultvalue_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/fake/zz_clientdefaultvalue_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/go.mod create mode 100644 test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/go.sum create mode 100644 test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/zz_clientdefaultvalue_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/zz_models.go create mode 100644 test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/zz_options.go create mode 100644 test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/zz_version.go create mode 100644 test/azure-http-specs/azure/client-generator-core/emptystringgroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/client-generator-core/emptystringgroup/deserializeemptystringasnull_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/emptystringgroup/fake/zz_deserializeemptystringasnull_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/emptystringgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/client-generator-core/emptystringgroup/go.mod create mode 100644 test/azure-http-specs/azure/client-generator-core/emptystringgroup/go.sum create mode 100644 test/azure-http-specs/azure/client-generator-core/emptystringgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/client-generator-core/emptystringgroup/zz_deserializeemptystringasnull_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/emptystringgroup/zz_models.go create mode 100644 test/azure-http-specs/azure/client-generator-core/emptystringgroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/client-generator-core/emptystringgroup/zz_options.go create mode 100644 test/azure-http-specs/azure/client-generator-core/emptystringgroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/client-generator-core/emptystringgroup/zz_version.go create mode 100644 test/azure-http-specs/azure/client-generator-core/flattengroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/client-generator-core/flattengroup/fake/zz_flattenproperty_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/flattengroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/client-generator-core/flattengroup/flattenproperty_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/flattengroup/go.mod create mode 100644 test/azure-http-specs/azure/client-generator-core/flattengroup/go.sum create mode 100644 test/azure-http-specs/azure/client-generator-core/flattengroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/client-generator-core/flattengroup/zz_flattenproperty_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/flattengroup/zz_models.go create mode 100644 test/azure-http-specs/azure/client-generator-core/flattengroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/client-generator-core/flattengroup/zz_options.go create mode 100644 test/azure-http-specs/azure/client-generator-core/flattengroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/client-generator-core/flattengroup/zz_version.go create mode 100644 test/azure-http-specs/azure/client-generator-core/hierarchygroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/client-generator-core/hierarchygroup/fake/zz_hierarchybuilding_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/hierarchygroup/fake/zz_hierarchybuildinganimaloperations_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/hierarchygroup/fake/zz_hierarchybuildingdogoperations_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/hierarchygroup/fake/zz_hierarchybuildingpetoperations_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/hierarchygroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/client-generator-core/hierarchygroup/fake/zz_polymorphic_helpers.go create mode 100644 test/azure-http-specs/azure/client-generator-core/hierarchygroup/go.mod create mode 100644 test/azure-http-specs/azure/client-generator-core/hierarchygroup/go.sum create mode 100644 test/azure-http-specs/azure/client-generator-core/hierarchygroup/hierarchy_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/hierarchygroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_hierarchybuilding_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_hierarchybuildinganimaloperations_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_hierarchybuildingdogoperations_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_hierarchybuildingpetoperations_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_interfaces.go create mode 100644 test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_models.go create mode 100644 test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_options.go create mode 100644 test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_polymorphic_helpers.go create mode 100644 test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_responses_serde.go create mode 100644 test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_version.go create mode 100644 test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/fake/zz_nextlinkverb_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/go.mod create mode 100644 test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/go.sum create mode 100644 test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/nextlinkverb_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/zz_models.go create mode 100644 test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/zz_nextlinkverb_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/zz_options.go create mode 100644 test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/zz_version.go create mode 100644 test/azure-http-specs/azure/client-generator-core/overridegroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/client-generator-core/overridegroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/client-generator-core/overridegroup/fake/zz_override_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/overridegroup/fake/zz_overridegroupparameters_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/overridegroup/fake/zz_overrideremoveoptionalparameter_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/overridegroup/fake/zz_overridereorderparameters_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/overridegroup/fake/zz_overriderequireoptionalparameter_server.go create mode 100644 test/azure-http-specs/azure/client-generator-core/overridegroup/go.mod create mode 100644 test/azure-http-specs/azure/client-generator-core/overridegroup/go.sum create mode 100644 test/azure-http-specs/azure/client-generator-core/overridegroup/overridegroupparameters_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/overridegroup/overrideremoveoptionalparameter_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/overridegroup/overridereorderparameters_client_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/overridegroup/overriderequireoptionalparameter_test.go create mode 100644 test/azure-http-specs/azure/client-generator-core/overridegroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/client-generator-core/overridegroup/zz_options.go create mode 100644 test/azure-http-specs/azure/client-generator-core/overridegroup/zz_override_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/overridegroup/zz_overridegroupparameters_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/overridegroup/zz_overrideremoveoptionalparameter_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/overridegroup/zz_overridereorderparameters_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/overridegroup/zz_overriderequireoptionalparameter_client.go create mode 100644 test/azure-http-specs/azure/client-generator-core/overridegroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/client-generator-core/overridegroup/zz_version.go create mode 100644 test/azure-http-specs/azure/core/azurepagegroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/core/azurepagegroup/custom_client_test.go create mode 100644 test/azure-http-specs/azure/core/azurepagegroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/core/azurepagegroup/fake/zz_page_server.go create mode 100644 test/azure-http-specs/azure/core/azurepagegroup/fake/zz_pagetwomodelsaspageitem_server.go create mode 100644 test/azure-http-specs/azure/core/azurepagegroup/go.mod create mode 100644 test/azure-http-specs/azure/core/azurepagegroup/go.sum create mode 100644 test/azure-http-specs/azure/core/azurepagegroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/core/azurepagegroup/twomodelsaspageitem_client_test.go create mode 100644 test/azure-http-specs/azure/core/azurepagegroup/zz_constants.go create mode 100644 test/azure-http-specs/azure/core/azurepagegroup/zz_models.go create mode 100644 test/azure-http-specs/azure/core/azurepagegroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/core/azurepagegroup/zz_options.go create mode 100644 test/azure-http-specs/azure/core/azurepagegroup/zz_page_client.go create mode 100644 test/azure-http-specs/azure/core/azurepagegroup/zz_pagetwomodelsaspageitem_client.go create mode 100644 test/azure-http-specs/azure/core/azurepagegroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/core/azurepagegroup/zz_version.go create mode 100644 test/azure-http-specs/azure/core/basicgroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/core/basicgroup/basic_client_test.go create mode 100644 test/azure-http-specs/azure/core/basicgroup/fake/zz_basic_server.go create mode 100644 test/azure-http-specs/azure/core/basicgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/core/basicgroup/go.mod create mode 100644 test/azure-http-specs/azure/core/basicgroup/go.sum create mode 100644 test/azure-http-specs/azure/core/basicgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/core/basicgroup/zz_basic_client.go create mode 100644 test/azure-http-specs/azure/core/basicgroup/zz_constants.go create mode 100644 test/azure-http-specs/azure/core/basicgroup/zz_models.go create mode 100644 test/azure-http-specs/azure/core/basicgroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/core/basicgroup/zz_options.go create mode 100644 test/azure-http-specs/azure/core/basicgroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/core/basicgroup/zz_version.go create mode 100644 test/azure-http-specs/azure/core/coremodelgroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/core/coremodelgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/core/coremodelgroup/fake/zz_model_server.go create mode 100644 test/azure-http-specs/azure/core/coremodelgroup/fake/zz_modelazurecoreembeddingvector_server.go create mode 100644 test/azure-http-specs/azure/core/coremodelgroup/go.mod create mode 100644 test/azure-http-specs/azure/core/coremodelgroup/go.sum create mode 100644 test/azure-http-specs/azure/core/coremodelgroup/modelazurecoreembeddingvector_client_test.go create mode 100644 test/azure-http-specs/azure/core/coremodelgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/core/coremodelgroup/zz_model_client.go create mode 100644 test/azure-http-specs/azure/core/coremodelgroup/zz_modelazurecoreembeddingvector_client.go create mode 100644 test/azure-http-specs/azure/core/coremodelgroup/zz_models.go create mode 100644 test/azure-http-specs/azure/core/coremodelgroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/core/coremodelgroup/zz_options.go create mode 100644 test/azure-http-specs/azure/core/coremodelgroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/core/coremodelgroup/zz_version.go create mode 100644 test/azure-http-specs/azure/core/corescalargroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/core/corescalargroup/azurelocationscalar_client_test.go create mode 100644 test/azure-http-specs/azure/core/corescalargroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/core/corescalargroup/fake/zz_scalar_server.go create mode 100644 test/azure-http-specs/azure/core/corescalargroup/fake/zz_scalarazurelocationscalar_server.go create mode 100644 test/azure-http-specs/azure/core/corescalargroup/go.mod create mode 100644 test/azure-http-specs/azure/core/corescalargroup/go.sum create mode 100644 test/azure-http-specs/azure/core/corescalargroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/core/corescalargroup/zz_models.go create mode 100644 test/azure-http-specs/azure/core/corescalargroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/core/corescalargroup/zz_options.go create mode 100644 test/azure-http-specs/azure/core/corescalargroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/core/corescalargroup/zz_scalar_client.go create mode 100644 test/azure-http-specs/azure/core/corescalargroup/zz_scalarazurelocationscalar_client.go create mode 100644 test/azure-http-specs/azure/core/corescalargroup/zz_version.go create mode 100644 test/azure-http-specs/azure/core/lro/lrorpcgroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/core/lro/lrorpcgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/core/lro/lrorpcgroup/fake/zz_rpc_server.go create mode 100644 test/azure-http-specs/azure/core/lro/lrorpcgroup/go.mod create mode 100644 test/azure-http-specs/azure/core/lro/lrorpcgroup/go.sum create mode 100644 test/azure-http-specs/azure/core/lro/lrorpcgroup/rcp_client_test.go create mode 100644 test/azure-http-specs/azure/core/lro/lrorpcgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_constants.go create mode 100644 test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_models.go create mode 100644 test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_options.go create mode 100644 test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_rpc_client.go create mode 100644 test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_version.go create mode 100644 test/azure-http-specs/azure/core/lro/lrostdgroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/core/lro/lrostdgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/core/lro/lrostdgroup/fake/zz_standard_server.go create mode 100644 test/azure-http-specs/azure/core/lro/lrostdgroup/go.mod create mode 100644 test/azure-http-specs/azure/core/lro/lrostdgroup/go.sum create mode 100644 test/azure-http-specs/azure/core/lro/lrostdgroup/standard_client_test.go create mode 100644 test/azure-http-specs/azure/core/lro/lrostdgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/core/lro/lrostdgroup/zz_constants.go create mode 100644 test/azure-http-specs/azure/core/lro/lrostdgroup/zz_models.go create mode 100644 test/azure-http-specs/azure/core/lro/lrostdgroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/core/lro/lrostdgroup/zz_options.go create mode 100644 test/azure-http-specs/azure/core/lro/lrostdgroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/core/lro/lrostdgroup/zz_standard_client.go create mode 100644 test/azure-http-specs/azure/core/lro/lrostdgroup/zz_version.go create mode 100644 test/azure-http-specs/azure/core/traitsgroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/core/traitsgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/core/traitsgroup/fake/zz_traits_server.go create mode 100644 test/azure-http-specs/azure/core/traitsgroup/go.mod create mode 100644 test/azure-http-specs/azure/core/traitsgroup/go.sum create mode 100644 test/azure-http-specs/azure/core/traitsgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/core/traitsgroup/traits_client_test.go create mode 100644 test/azure-http-specs/azure/core/traitsgroup/zz_constants.go create mode 100644 test/azure-http-specs/azure/core/traitsgroup/zz_models.go create mode 100644 test/azure-http-specs/azure/core/traitsgroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/core/traitsgroup/zz_options.go create mode 100644 test/azure-http-specs/azure/core/traitsgroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/core/traitsgroup/zz_traits_client.go create mode 100644 test/azure-http-specs/azure/core/traitsgroup/zz_version.go create mode 100644 test/azure-http-specs/azure/encode/encodedurationgroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/encode/encodedurationgroup/duration_client_test.go create mode 100644 test/azure-http-specs/azure/encode/encodedurationgroup/fake/zz_duration_server.go create mode 100644 test/azure-http-specs/azure/encode/encodedurationgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/encode/encodedurationgroup/go.mod create mode 100644 test/azure-http-specs/azure/encode/encodedurationgroup/go.sum create mode 100644 test/azure-http-specs/azure/encode/encodedurationgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/encode/encodedurationgroup/zz_duration_client.go create mode 100644 test/azure-http-specs/azure/encode/encodedurationgroup/zz_models.go create mode 100644 test/azure-http-specs/azure/encode/encodedurationgroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/encode/encodedurationgroup/zz_options.go create mode 100644 test/azure-http-specs/azure/encode/encodedurationgroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/encode/encodedurationgroup/zz_version.go create mode 100644 test/azure-http-specs/azure/example/examplebasicgroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/example/examplebasicgroup/basicserviceoperationgroup_client_test.go create mode 100644 test/azure-http-specs/azure/example/examplebasicgroup/fake/zz_azureexample_server.go create mode 100644 test/azure-http-specs/azure/example/examplebasicgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/example/examplebasicgroup/go.mod create mode 100644 test/azure-http-specs/azure/example/examplebasicgroup/go.sum create mode 100644 test/azure-http-specs/azure/example/examplebasicgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/example/examplebasicgroup/zz_azureexample_client.go create mode 100644 test/azure-http-specs/azure/example/examplebasicgroup/zz_constants.go create mode 100644 test/azure-http-specs/azure/example/examplebasicgroup/zz_models.go create mode 100644 test/azure-http-specs/azure/example/examplebasicgroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/example/examplebasicgroup/zz_options.go create mode 100644 test/azure-http-specs/azure/example/examplebasicgroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/example/examplebasicgroup/zz_version.go create mode 100644 test/azure-http-specs/azure/payload/pageablegroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/payload/pageablegroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/payload/pageablegroup/fake/zz_pageable_server.go create mode 100644 test/azure-http-specs/azure/payload/pageablegroup/go.mod create mode 100644 test/azure-http-specs/azure/payload/pageablegroup/go.sum create mode 100644 test/azure-http-specs/azure/payload/pageablegroup/pageable_client_test.go create mode 100644 test/azure-http-specs/azure/payload/pageablegroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/payload/pageablegroup/zz_models.go create mode 100644 test/azure-http-specs/azure/payload/pageablegroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/payload/pageablegroup/zz_options.go create mode 100644 test/azure-http-specs/azure/payload/pageablegroup/zz_pageable_client.go create mode 100644 test/azure-http-specs/azure/payload/pageablegroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/payload/pageablegroup/zz_version.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/disk_client_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/fake/zz_disks_server.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/fake/zz_server_factory.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/fake/zz_virtualmachines_server.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/go.mod create mode 100644 test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/go.sum create mode 100644 test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/utils_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/virtual_machine_client_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_client_factory.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_constants.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_disks_client.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_models.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_options.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_version.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_virtualmachines_client.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/fake/zz_server_factory.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/fake/zz_storageaccounts_server.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/fake/zz_virtualmachines_server.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/go.mod create mode 100644 test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/go.sum create mode 100644 test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/storage_accounts_client_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/utils_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/virtual_machines_client_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_client_factory.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_constants.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_models.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_options.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_storageaccounts_client.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_version.go create mode 100644 test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_virtualmachines_client.go create mode 100644 test/azure-http-specs/azure/resource-manager/commonpropsgroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/resource-manager/commonpropsgroup/error_client_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/commonpropsgroup/fake/zz_armresourceidentifiers_server.go create mode 100644 test/azure-http-specs/azure/resource-manager/commonpropsgroup/fake/zz_error_server.go create mode 100644 test/azure-http-specs/azure/resource-manager/commonpropsgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/resource-manager/commonpropsgroup/fake/zz_managedidentity_server.go create mode 100644 test/azure-http-specs/azure/resource-manager/commonpropsgroup/fake/zz_server_factory.go create mode 100644 test/azure-http-specs/azure/resource-manager/commonpropsgroup/go.mod create mode 100644 test/azure-http-specs/azure/resource-manager/commonpropsgroup/go.sum create mode 100644 test/azure-http-specs/azure/resource-manager/commonpropsgroup/managedidentity_client_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/commonpropsgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/resource-manager/commonpropsgroup/utils_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_armresourceidentifiers_client.go create mode 100644 test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_client_factory.go create mode 100644 test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_constants.go create mode 100644 test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_error_client.go create mode 100644 test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_managedidentity_client.go create mode 100644 test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_models.go create mode 100644 test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_options.go create mode 100644 test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_version.go create mode 100644 test/azure-http-specs/azure/resource-manager/largeheadergroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/resource-manager/largeheadergroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/resource-manager/largeheadergroup/fake/zz_largeheaders_server.go create mode 100644 test/azure-http-specs/azure/resource-manager/largeheadergroup/fake/zz_server_factory.go create mode 100644 test/azure-http-specs/azure/resource-manager/largeheadergroup/go.mod create mode 100644 test/azure-http-specs/azure/resource-manager/largeheadergroup/go.sum create mode 100644 test/azure-http-specs/azure/resource-manager/largeheadergroup/largeheaders_client_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/largeheadergroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/resource-manager/largeheadergroup/utils_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_client_factory.go create mode 100644 test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_constants.go create mode 100644 test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_largeheaders_client.go create mode 100644 test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_models.go create mode 100644 test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_options.go create mode 100644 test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_version.go create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_operations_server.go create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_resourcegroupresourceoperations_server.go create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_server_factory.go create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_subscriptionresource1operations_server.go create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_subscriptionresource2operations_server.go create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_subscriptionresourceoperations_server.go create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/go.mod create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/go.sum create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/operations_client_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/resourcegroupresourceoperations_client_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/subscriptionresource1operations_client_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/subscriptionresource2operations_client_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/subscriptionresourceoperations_client_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/utils_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_client_factory.go create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_constants.go create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_models.go create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_operations_client.go create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_options.go create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_resourcegroupresourceoperations_client.go create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_subscriptionresource1operations_client.go create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_subscriptionresource2operations_client.go create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_subscriptionresourceoperations_client.go create mode 100644 test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_version.go create mode 100644 test/azure-http-specs/azure/resource-manager/nonresourcegroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/resource-manager/nonresourcegroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/resource-manager/nonresourcegroup/fake/zz_nonresourceoperations_server.go create mode 100644 test/azure-http-specs/azure/resource-manager/nonresourcegroup/fake/zz_server_factory.go create mode 100644 test/azure-http-specs/azure/resource-manager/nonresourcegroup/go.mod create mode 100644 test/azure-http-specs/azure/resource-manager/nonresourcegroup/go.sum create mode 100644 test/azure-http-specs/azure/resource-manager/nonresourcegroup/nonresourceoperations_client_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/nonresourcegroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/resource-manager/nonresourcegroup/utils_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_client_factory.go create mode 100644 test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_constants.go create mode 100644 test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_models.go create mode 100644 test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_nonresourceoperations_client.go create mode 100644 test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_options.go create mode 100644 test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_version.go create mode 100644 test/azure-http-specs/azure/resource-manager/resources/LICENSE.txt create mode 100644 test/azure-http-specs/azure/resource-manager/resources/extensionsresources_client_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/resources/fake/zz_extensionsresources_server.go create mode 100644 test/azure-http-specs/azure/resource-manager/resources/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/resource-manager/resources/fake/zz_locationresources_server.go create mode 100644 test/azure-http-specs/azure/resource-manager/resources/fake/zz_nested_server.go create mode 100644 test/azure-http-specs/azure/resource-manager/resources/fake/zz_server_factory.go create mode 100644 test/azure-http-specs/azure/resource-manager/resources/fake/zz_singleton_server.go create mode 100644 test/azure-http-specs/azure/resource-manager/resources/fake/zz_toplevel_server.go create mode 100644 test/azure-http-specs/azure/resource-manager/resources/go.mod create mode 100644 test/azure-http-specs/azure/resource-manager/resources/go.sum create mode 100644 test/azure-http-specs/azure/resource-manager/resources/locationresources_client_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/resources/nested_client_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/resources/singleton_client_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/resources/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/resource-manager/resources/toplevel_client_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/resources/utils_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/resources/zz_client_factory.go create mode 100644 test/azure-http-specs/azure/resource-manager/resources/zz_constants.go create mode 100644 test/azure-http-specs/azure/resource-manager/resources/zz_extensionsresources_client.go create mode 100644 test/azure-http-specs/azure/resource-manager/resources/zz_locationresources_client.go create mode 100644 test/azure-http-specs/azure/resource-manager/resources/zz_models.go create mode 100644 test/azure-http-specs/azure/resource-manager/resources/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/resource-manager/resources/zz_nested_client.go create mode 100644 test/azure-http-specs/azure/resource-manager/resources/zz_options.go create mode 100644 test/azure-http-specs/azure/resource-manager/resources/zz_responses.go create mode 100644 test/azure-http-specs/azure/resource-manager/resources/zz_singleton_client.go create mode 100644 test/azure-http-specs/azure/resource-manager/resources/zz_toplevel_client.go create mode 100644 test/azure-http-specs/azure/resource-manager/resources/zz_version.go create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/checknameavailability_client_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_checknameavailability_server.go create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_lro_server.go create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_lropaging_server.go create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_operations_server.go create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_optionalbody_server.go create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_server_factory.go create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/go.mod create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/go.sum create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/lro_client_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/lropaging_client_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/optionalbody_client_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/utils_test.go create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/zz_checknameavailability_client.go create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/zz_client_factory.go create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/zz_constants.go create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/zz_lro_client.go create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/zz_lropaging_client.go create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/zz_models.go create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/zz_operations_client.go create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/zz_optionalbody_client.go create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/zz_options.go create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/zz_responses_serde.go create mode 100644 test/azure-http-specs/azure/resource-manager/templatesgroup/zz_version.go create mode 100644 test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/fake/zz_xmsclientrequestid_server.go create mode 100644 test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/go.mod create mode 100644 test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/go.sum create mode 100644 test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/xmsclientrequestid_client_test.go create mode 100644 test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/zz_options.go create mode 100644 test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/zz_version.go create mode 100644 test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/zz_xmsclientrequestid_client.go create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroup/LICENSE.txt create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroup/fake/zz_previewversion_server.go create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroup/go.mod create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroup/go.sum create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroup/previewversion_client_test.go create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroup/zz_constants.go create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroup/zz_models.go create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroup/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroup/zz_options.go create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroup/zz_previewversion_client.go create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroup/zz_responses.go create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroup/zz_version.go create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/LICENSE.txt create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/fake/zz_internal.go create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/fake/zz_previewversion_server.go create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/go.mod create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/go.sum create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/previewversion_client_test.go create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/testdata/_metadata.json create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_constants.go create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_models.go create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_models_serde.go create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_options.go create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_previewversion_client.go create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_responses.go create mode 100644 test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_version.go create mode 100644 test/azure-http-specs/client/clientnamespacegroup/LICENSE.txt create mode 100644 test/azure-http-specs/client/clientnamespacegroup/clientnamespacefirst_client_test.go create mode 100644 test/azure-http-specs/client/clientnamespacegroup/clientnamespacesecond_client_test.go create mode 100644 test/azure-http-specs/client/clientnamespacegroup/fake/zz_clientnamespacefirst_server.go create mode 100644 test/azure-http-specs/client/clientnamespacegroup/fake/zz_clientnamespacesecond_server.go create mode 100644 test/azure-http-specs/client/clientnamespacegroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/client/clientnamespacegroup/go.mod create mode 100644 test/azure-http-specs/client/clientnamespacegroup/go.sum create mode 100644 test/azure-http-specs/client/clientnamespacegroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/client/clientnamespacegroup/zz_clientnamespacefirst_client.go create mode 100644 test/azure-http-specs/client/clientnamespacegroup/zz_clientnamespacesecond_client.go create mode 100644 test/azure-http-specs/client/clientnamespacegroup/zz_constants.go create mode 100644 test/azure-http-specs/client/clientnamespacegroup/zz_models.go create mode 100644 test/azure-http-specs/client/clientnamespacegroup/zz_models_serde.go create mode 100644 test/azure-http-specs/client/clientnamespacegroup/zz_options.go create mode 100644 test/azure-http-specs/client/clientnamespacegroup/zz_responses.go create mode 100644 test/azure-http-specs/client/clientnamespacegroup/zz_version.go create mode 100644 test/azure-http-specs/client/naming/enumconflictgroup/LICENSE.txt create mode 100644 test/azure-http-specs/client/naming/enumconflictgroup/enumconflictfirstoperations_client_test.go create mode 100644 test/azure-http-specs/client/naming/enumconflictgroup/enumconflictsecondoperations_client_test.go create mode 100644 test/azure-http-specs/client/naming/enumconflictgroup/fake/zz_enumconflict_server.go create mode 100644 test/azure-http-specs/client/naming/enumconflictgroup/fake/zz_enumconflictfirstoperations_server.go create mode 100644 test/azure-http-specs/client/naming/enumconflictgroup/fake/zz_enumconflictsecondoperations_server.go create mode 100644 test/azure-http-specs/client/naming/enumconflictgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/client/naming/enumconflictgroup/go.mod create mode 100644 test/azure-http-specs/client/naming/enumconflictgroup/go.sum create mode 100644 test/azure-http-specs/client/naming/enumconflictgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/client/naming/enumconflictgroup/zz_constants.go create mode 100644 test/azure-http-specs/client/naming/enumconflictgroup/zz_enumconflict_client.go create mode 100644 test/azure-http-specs/client/naming/enumconflictgroup/zz_enumconflictfirstoperations_client.go create mode 100644 test/azure-http-specs/client/naming/enumconflictgroup/zz_enumconflictsecondoperations_client.go create mode 100644 test/azure-http-specs/client/naming/enumconflictgroup/zz_models.go create mode 100644 test/azure-http-specs/client/naming/enumconflictgroup/zz_models_serde.go create mode 100644 test/azure-http-specs/client/naming/enumconflictgroup/zz_options.go create mode 100644 test/azure-http-specs/client/naming/enumconflictgroup/zz_responses.go create mode 100644 test/azure-http-specs/client/naming/enumconflictgroup/zz_version.go create mode 100644 test/azure-http-specs/client/naminggroup/LICENSE.txt create mode 100644 test/azure-http-specs/client/naminggroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/client/naminggroup/fake/zz_naming_server.go create mode 100644 test/azure-http-specs/client/naminggroup/fake/zz_namingheader_server.go create mode 100644 test/azure-http-specs/client/naminggroup/fake/zz_namingmodel_server.go create mode 100644 test/azure-http-specs/client/naminggroup/fake/zz_namingproperty_server.go create mode 100644 test/azure-http-specs/client/naminggroup/fake/zz_namingunionenum_server.go create mode 100644 test/azure-http-specs/client/naminggroup/fakes_test.go create mode 100644 test/azure-http-specs/client/naminggroup/go.mod create mode 100644 test/azure-http-specs/client/naminggroup/go.sum create mode 100644 test/azure-http-specs/client/naminggroup/naming_client_test.go create mode 100644 test/azure-http-specs/client/naminggroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/client/naminggroup/zz_constants.go create mode 100644 test/azure-http-specs/client/naminggroup/zz_models.go create mode 100644 test/azure-http-specs/client/naminggroup/zz_models_serde.go create mode 100644 test/azure-http-specs/client/naminggroup/zz_naming_client.go create mode 100644 test/azure-http-specs/client/naminggroup/zz_namingheader_client.go create mode 100644 test/azure-http-specs/client/naminggroup/zz_namingmodel_client.go create mode 100644 test/azure-http-specs/client/naminggroup/zz_namingproperty_client.go create mode 100644 test/azure-http-specs/client/naminggroup/zz_namingunionenum_client.go create mode 100644 test/azure-http-specs/client/naminggroup/zz_options.go create mode 100644 test/azure-http-specs/client/naminggroup/zz_responses.go create mode 100644 test/azure-http-specs/client/naminggroup/zz_version.go create mode 100644 test/azure-http-specs/client/overloadgroup/LICENSE.txt create mode 100644 test/azure-http-specs/client/overloadgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/client/overloadgroup/fake/zz_overload_server.go create mode 100644 test/azure-http-specs/client/overloadgroup/go.mod create mode 100644 test/azure-http-specs/client/overloadgroup/go.sum create mode 100644 test/azure-http-specs/client/overloadgroup/overload_client_test.go create mode 100644 test/azure-http-specs/client/overloadgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/client/overloadgroup/zz_models.go create mode 100644 test/azure-http-specs/client/overloadgroup/zz_models_serde.go create mode 100644 test/azure-http-specs/client/overloadgroup/zz_options.go create mode 100644 test/azure-http-specs/client/overloadgroup/zz_overload_client.go create mode 100644 test/azure-http-specs/client/overloadgroup/zz_responses.go create mode 100644 test/azure-http-specs/client/overloadgroup/zz_version.go create mode 100644 test/azure-http-specs/client/structure/clientopgroup/first_client_test.go create mode 100644 test/azure-http-specs/client/structure/clientopgroup/firstgroup3_client_test.go create mode 100644 test/azure-http-specs/client/structure/clientopgroup/firstgroup4_client_test.go create mode 100644 test/azure-http-specs/client/structure/clientopgroup/second_client_test.go create mode 100644 test/azure-http-specs/client/structure/clientopgroup/secondgroup5_client_test.go create mode 100644 test/azure-http-specs/client/structure/defaultgroup/LICENSE.txt create mode 100644 test/azure-http-specs/client/structure/defaultgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/client/structure/defaultgroup/fake/zz_service_server.go create mode 100644 test/azure-http-specs/client/structure/defaultgroup/fake/zz_servicebar_server.go create mode 100644 test/azure-http-specs/client/structure/defaultgroup/fake/zz_servicebaz_server.go create mode 100644 test/azure-http-specs/client/structure/defaultgroup/fake/zz_servicebazfoo_server.go create mode 100644 test/azure-http-specs/client/structure/defaultgroup/fake/zz_servicefoo_server.go create mode 100644 test/azure-http-specs/client/structure/defaultgroup/fake/zz_servicequx_server.go create mode 100644 test/azure-http-specs/client/structure/defaultgroup/fake/zz_servicequxbar_server.go create mode 100644 test/azure-http-specs/client/structure/defaultgroup/go.mod create mode 100644 test/azure-http-specs/client/structure/defaultgroup/go.sum create mode 100644 test/azure-http-specs/client/structure/defaultgroup/service_client_test.go create mode 100644 test/azure-http-specs/client/structure/defaultgroup/servicebar_client_test.go create mode 100644 test/azure-http-specs/client/structure/defaultgroup/servicefoo_client_test.go create mode 100644 test/azure-http-specs/client/structure/defaultgroup/servicequx_client_test.go create mode 100644 test/azure-http-specs/client/structure/defaultgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/client/structure/defaultgroup/zz_constants.go create mode 100644 test/azure-http-specs/client/structure/defaultgroup/zz_options.go create mode 100644 test/azure-http-specs/client/structure/defaultgroup/zz_responses.go create mode 100644 test/azure-http-specs/client/structure/defaultgroup/zz_service_client.go create mode 100644 test/azure-http-specs/client/structure/defaultgroup/zz_servicebar_client.go create mode 100644 test/azure-http-specs/client/structure/defaultgroup/zz_servicebaz_client.go create mode 100644 test/azure-http-specs/client/structure/defaultgroup/zz_servicebazfoo_client.go create mode 100644 test/azure-http-specs/client/structure/defaultgroup/zz_servicefoo_client.go create mode 100644 test/azure-http-specs/client/structure/defaultgroup/zz_servicequx_client.go create mode 100644 test/azure-http-specs/client/structure/defaultgroup/zz_servicequxbar_client.go create mode 100644 test/azure-http-specs/client/structure/defaultgroup/zz_version.go create mode 100644 test/azure-http-specs/client/structure/multiclientgroup/clienta_client_test.go create mode 100644 test/azure-http-specs/client/structure/multiclientgroup/clientb_client_test.go create mode 100644 test/azure-http-specs/client/structure/renamedopgroup/group_client_test.go create mode 100644 test/azure-http-specs/client/structure/renamedopgroup/renamedoperation_client_test.go create mode 100644 test/azure-http-specs/client/structure/twoopgroup/group1_client_test.go create mode 100644 test/azure-http-specs/client/structure/twoopgroup/group2_client_test.go create mode 100644 test/azure-http-specs/resiliency/srvdrivennewgroup/LICENSE.txt create mode 100644 test/azure-http-specs/resiliency/srvdrivennewgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/resiliency/srvdrivennewgroup/fake/zz_resiliencyservicedriven_server.go create mode 100644 test/azure-http-specs/resiliency/srvdrivennewgroup/go.mod create mode 100644 test/azure-http-specs/resiliency/srvdrivennewgroup/go.sum create mode 100644 test/azure-http-specs/resiliency/srvdrivennewgroup/resiliencyservicedriven_client_test.go create mode 100644 test/azure-http-specs/resiliency/srvdrivennewgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/resiliency/srvdrivennewgroup/zz_options.go create mode 100644 test/azure-http-specs/resiliency/srvdrivennewgroup/zz_resiliencyservicedriven_client.go create mode 100644 test/azure-http-specs/resiliency/srvdrivennewgroup/zz_responses.go create mode 100644 test/azure-http-specs/resiliency/srvdrivennewgroup/zz_version.go create mode 100644 test/azure-http-specs/resiliency/srvdrivenoldgroup/LICENSE.txt create mode 100644 test/azure-http-specs/resiliency/srvdrivenoldgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/resiliency/srvdrivenoldgroup/fake/zz_resiliencyservicedriven_server.go create mode 100644 test/azure-http-specs/resiliency/srvdrivenoldgroup/go.mod create mode 100644 test/azure-http-specs/resiliency/srvdrivenoldgroup/go.sum create mode 100644 test/azure-http-specs/resiliency/srvdrivenoldgroup/resiliencyservicedriven_client_test.go create mode 100644 test/azure-http-specs/resiliency/srvdrivenoldgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/resiliency/srvdrivenoldgroup/zz_options.go create mode 100644 test/azure-http-specs/resiliency/srvdrivenoldgroup/zz_resiliencyservicedriven_client.go create mode 100644 test/azure-http-specs/resiliency/srvdrivenoldgroup/zz_responses.go create mode 100644 test/azure-http-specs/resiliency/srvdrivenoldgroup/zz_version.go create mode 100644 test/azure-http-specs/service/multipleservicesgroup/LICENSE.txt create mode 100644 test/azure-http-specs/service/multipleservicesgroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/service/multipleservicesgroup/fake/zz_servicea_server.go create mode 100644 test/azure-http-specs/service/multipleservicesgroup/fake/zz_serviceaoperations_server.go create mode 100644 test/azure-http-specs/service/multipleservicesgroup/fake/zz_serviceasubnamespace_server.go create mode 100644 test/azure-http-specs/service/multipleservicesgroup/fake/zz_serviceb_server.go create mode 100644 test/azure-http-specs/service/multipleservicesgroup/fake/zz_serviceboperations_server.go create mode 100644 test/azure-http-specs/service/multipleservicesgroup/fake/zz_servicebsubnamespace_server.go create mode 100644 test/azure-http-specs/service/multipleservicesgroup/fakes_test.go create mode 100644 test/azure-http-specs/service/multipleservicesgroup/go.mod create mode 100644 test/azure-http-specs/service/multipleservicesgroup/go.sum create mode 100644 test/azure-http-specs/service/multipleservicesgroup/multipleservices_client_test.go create mode 100644 test/azure-http-specs/service/multipleservicesgroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/service/multipleservicesgroup/zz_constants.go create mode 100644 test/azure-http-specs/service/multipleservicesgroup/zz_options.go create mode 100644 test/azure-http-specs/service/multipleservicesgroup/zz_responses.go create mode 100644 test/azure-http-specs/service/multipleservicesgroup/zz_servicea_client.go create mode 100644 test/azure-http-specs/service/multipleservicesgroup/zz_serviceaoperations_client.go create mode 100644 test/azure-http-specs/service/multipleservicesgroup/zz_serviceasubnamespace_client.go create mode 100644 test/azure-http-specs/service/multipleservicesgroup/zz_serviceb_client.go create mode 100644 test/azure-http-specs/service/multipleservicesgroup/zz_serviceboperations_client.go create mode 100644 test/azure-http-specs/service/multipleservicesgroup/zz_servicebsubnamespace_client.go create mode 100644 test/azure-http-specs/service/multipleservicesgroup/zz_version.go create mode 100644 test/azure-http-specs/service/multiservicegroup/LICENSE.txt create mode 100644 test/azure-http-specs/service/multiservicegroup/combined_client_test.go create mode 100644 test/azure-http-specs/service/multiservicegroup/fake/zz_combined_server.go create mode 100644 test/azure-http-specs/service/multiservicegroup/fake/zz_combinedbar_server.go create mode 100644 test/azure-http-specs/service/multiservicegroup/fake/zz_combinedfoo_server.go create mode 100644 test/azure-http-specs/service/multiservicegroup/fake/zz_internal.go create mode 100644 test/azure-http-specs/service/multiservicegroup/go.mod create mode 100644 test/azure-http-specs/service/multiservicegroup/go.sum create mode 100644 test/azure-http-specs/service/multiservicegroup/testdata/_metadata.json create mode 100644 test/azure-http-specs/service/multiservicegroup/zz_combined_client.go create mode 100644 test/azure-http-specs/service/multiservicegroup/zz_combinedbar_client.go create mode 100644 test/azure-http-specs/service/multiservicegroup/zz_combinedfoo_client.go create mode 100644 test/azure-http-specs/service/multiservicegroup/zz_constants.go create mode 100644 test/azure-http-specs/service/multiservicegroup/zz_options.go create mode 100644 test/azure-http-specs/service/multiservicegroup/zz_responses.go create mode 100644 test/azure-http-specs/service/multiservicegroup/zz_version.go create mode 100644 test/http-specs/authentication/apikeygroup/LICENSE.txt create mode 100644 test/http-specs/authentication/apikeygroup/apikey_client_test.go create mode 100644 test/http-specs/authentication/apikeygroup/custom_client.go create mode 100644 test/http-specs/authentication/apikeygroup/fake/zz_apikey_server.go create mode 100644 test/http-specs/authentication/apikeygroup/fake/zz_internal.go create mode 100644 test/http-specs/authentication/apikeygroup/go.mod create mode 100644 test/http-specs/authentication/apikeygroup/go.sum create mode 100644 test/http-specs/authentication/apikeygroup/testdata/_metadata.json create mode 100644 test/http-specs/authentication/apikeygroup/version.go create mode 100644 test/http-specs/authentication/apikeygroup/zz_apikey_client.go create mode 100644 test/http-specs/authentication/apikeygroup/zz_options.go create mode 100644 test/http-specs/authentication/apikeygroup/zz_responses.go create mode 100644 test/http-specs/authentication/apikeygroup/zz_version.go create mode 100644 test/http-specs/authentication/http/customgroup/LICENSE.txt create mode 100644 test/http-specs/authentication/http/customgroup/custom_client.go create mode 100644 test/http-specs/authentication/http/customgroup/custom_client_test.go create mode 100644 test/http-specs/authentication/http/customgroup/fake/zz_custom_server.go create mode 100644 test/http-specs/authentication/http/customgroup/fake/zz_internal.go create mode 100644 test/http-specs/authentication/http/customgroup/go.mod create mode 100644 test/http-specs/authentication/http/customgroup/go.sum create mode 100644 test/http-specs/authentication/http/customgroup/testdata/_metadata.json create mode 100644 test/http-specs/authentication/http/customgroup/version.go create mode 100644 test/http-specs/authentication/http/customgroup/zz_custom_client.go create mode 100644 test/http-specs/authentication/http/customgroup/zz_options.go create mode 100644 test/http-specs/authentication/http/customgroup/zz_responses.go create mode 100644 test/http-specs/authentication/http/customgroup/zz_version.go create mode 100644 test/http-specs/authentication/oauth2group/LICENSE.txt create mode 100644 test/http-specs/authentication/oauth2group/fake/zz_internal.go create mode 100644 test/http-specs/authentication/oauth2group/fake/zz_oauth2_server.go create mode 100644 test/http-specs/authentication/oauth2group/go.mod create mode 100644 test/http-specs/authentication/oauth2group/go.sum create mode 100644 test/http-specs/authentication/oauth2group/oauth2_client_test.go create mode 100644 test/http-specs/authentication/oauth2group/testdata/_metadata.json create mode 100644 test/http-specs/authentication/oauth2group/zz_cloud_config.go create mode 100644 test/http-specs/authentication/oauth2group/zz_oauth2_client.go create mode 100644 test/http-specs/authentication/oauth2group/zz_options.go create mode 100644 test/http-specs/authentication/oauth2group/zz_responses.go create mode 100644 test/http-specs/authentication/oauth2group/zz_version.go create mode 100644 test/http-specs/authentication/unionauthgroup/LICENSE.txt create mode 100644 test/http-specs/authentication/unionauthgroup/fake/zz_internal.go create mode 100644 test/http-specs/authentication/unionauthgroup/fake/zz_union_server.go create mode 100644 test/http-specs/authentication/unionauthgroup/go.mod create mode 100644 test/http-specs/authentication/unionauthgroup/go.sum create mode 100644 test/http-specs/authentication/unionauthgroup/testdata/_metadata.json create mode 100644 test/http-specs/authentication/unionauthgroup/union_client_test.go create mode 100644 test/http-specs/authentication/unionauthgroup/zz_cloud_config.go create mode 100644 test/http-specs/authentication/unionauthgroup/zz_options.go create mode 100644 test/http-specs/authentication/unionauthgroup/zz_responses.go create mode 100644 test/http-specs/authentication/unionauthgroup/zz_union_client.go create mode 100644 test/http-specs/authentication/unionauthgroup/zz_version.go create mode 100644 test/http-specs/encode/bytesgroup/LICENSE.txt create mode 100644 test/http-specs/encode/bytesgroup/custom_client_test.go create mode 100644 test/http-specs/encode/bytesgroup/fake/zz_bytes_server.go create mode 100644 test/http-specs/encode/bytesgroup/fake/zz_bytesheader_server.go create mode 100644 test/http-specs/encode/bytesgroup/fake/zz_bytesproperty_server.go create mode 100644 test/http-specs/encode/bytesgroup/fake/zz_bytesquery_server.go create mode 100644 test/http-specs/encode/bytesgroup/fake/zz_bytesrequestbody_server.go create mode 100644 test/http-specs/encode/bytesgroup/fake/zz_bytesresponsebody_server.go create mode 100644 test/http-specs/encode/bytesgroup/fake/zz_internal.go create mode 100644 test/http-specs/encode/bytesgroup/go.mod create mode 100644 test/http-specs/encode/bytesgroup/go.sum create mode 100644 test/http-specs/encode/bytesgroup/testdata/_metadata.json create mode 100644 test/http-specs/encode/bytesgroup/zz_bytes_client.go create mode 100644 test/http-specs/encode/bytesgroup/zz_bytesheader_client.go create mode 100644 test/http-specs/encode/bytesgroup/zz_bytesproperty_client.go create mode 100644 test/http-specs/encode/bytesgroup/zz_bytesquery_client.go create mode 100644 test/http-specs/encode/bytesgroup/zz_bytesrequestbody_client.go create mode 100644 test/http-specs/encode/bytesgroup/zz_bytesresponsebody_client.go create mode 100644 test/http-specs/encode/bytesgroup/zz_models.go create mode 100644 test/http-specs/encode/bytesgroup/zz_models_serde.go create mode 100644 test/http-specs/encode/bytesgroup/zz_options.go create mode 100644 test/http-specs/encode/bytesgroup/zz_responses.go create mode 100644 test/http-specs/encode/bytesgroup/zz_version.go create mode 100644 test/http-specs/encode/datetimegroup/LICENSE.txt create mode 100644 test/http-specs/encode/datetimegroup/custom_client_test.go create mode 100644 test/http-specs/encode/datetimegroup/fake/zz_datetime_server.go create mode 100644 test/http-specs/encode/datetimegroup/fake/zz_datetimeheader_server.go create mode 100644 test/http-specs/encode/datetimegroup/fake/zz_datetimeproperty_server.go create mode 100644 test/http-specs/encode/datetimegroup/fake/zz_datetimequery_server.go create mode 100644 test/http-specs/encode/datetimegroup/fake/zz_datetimeresponseheader_server.go create mode 100644 test/http-specs/encode/datetimegroup/fake/zz_internal.go create mode 100644 test/http-specs/encode/datetimegroup/go.mod create mode 100644 test/http-specs/encode/datetimegroup/go.sum create mode 100644 test/http-specs/encode/datetimegroup/testdata/_metadata.json create mode 100644 test/http-specs/encode/datetimegroup/zz_datetime_client.go create mode 100644 test/http-specs/encode/datetimegroup/zz_datetimeheader_client.go create mode 100644 test/http-specs/encode/datetimegroup/zz_datetimeproperty_client.go create mode 100644 test/http-specs/encode/datetimegroup/zz_datetimequery_client.go create mode 100644 test/http-specs/encode/datetimegroup/zz_datetimeresponseheader_client.go create mode 100644 test/http-specs/encode/datetimegroup/zz_models.go create mode 100644 test/http-specs/encode/datetimegroup/zz_models_serde.go create mode 100644 test/http-specs/encode/datetimegroup/zz_options.go create mode 100644 test/http-specs/encode/datetimegroup/zz_responses.go create mode 100644 test/http-specs/encode/datetimegroup/zz_version.go create mode 100644 test/http-specs/encode/durationgroup/LICENSE.txt create mode 100644 test/http-specs/encode/durationgroup/custom_client_test.go create mode 100644 test/http-specs/encode/durationgroup/fake/zz_duration_server.go create mode 100644 test/http-specs/encode/durationgroup/fake/zz_durationheader_server.go create mode 100644 test/http-specs/encode/durationgroup/fake/zz_durationproperty_server.go create mode 100644 test/http-specs/encode/durationgroup/fake/zz_durationquery_server.go create mode 100644 test/http-specs/encode/durationgroup/fake/zz_internal.go create mode 100644 test/http-specs/encode/durationgroup/go.mod create mode 100644 test/http-specs/encode/durationgroup/go.sum create mode 100644 test/http-specs/encode/durationgroup/testdata/_metadata.json create mode 100644 test/http-specs/encode/durationgroup/zz_duration_client.go create mode 100644 test/http-specs/encode/durationgroup/zz_durationheader_client.go create mode 100644 test/http-specs/encode/durationgroup/zz_durationproperty_client.go create mode 100644 test/http-specs/encode/durationgroup/zz_durationquery_client.go create mode 100644 test/http-specs/encode/durationgroup/zz_models.go create mode 100644 test/http-specs/encode/durationgroup/zz_models_serde.go create mode 100644 test/http-specs/encode/durationgroup/zz_options.go create mode 100644 test/http-specs/encode/durationgroup/zz_responses.go create mode 100644 test/http-specs/encode/durationgroup/zz_version.go create mode 100644 test/http-specs/encode/numericgroup/LICENSE.txt create mode 100644 test/http-specs/encode/numericgroup/fake/zz_internal.go create mode 100644 test/http-specs/encode/numericgroup/fake/zz_numeric_server.go create mode 100644 test/http-specs/encode/numericgroup/fake/zz_numericproperty_server.go create mode 100644 test/http-specs/encode/numericgroup/go.mod create mode 100644 test/http-specs/encode/numericgroup/go.sum create mode 100644 test/http-specs/encode/numericgroup/numericproperty_client_test.go create mode 100644 test/http-specs/encode/numericgroup/testdata/_metadata.json create mode 100644 test/http-specs/encode/numericgroup/zz_models.go create mode 100644 test/http-specs/encode/numericgroup/zz_models_serde.go create mode 100644 test/http-specs/encode/numericgroup/zz_numeric_client.go create mode 100644 test/http-specs/encode/numericgroup/zz_numericproperty_client.go create mode 100644 test/http-specs/encode/numericgroup/zz_options.go create mode 100644 test/http-specs/encode/numericgroup/zz_responses.go create mode 100644 test/http-specs/encode/numericgroup/zz_version.go create mode 100644 test/http-specs/parameters/basicparamsgroup/LICENSE.txt create mode 100644 test/http-specs/parameters/basicparamsgroup/basicexplicitbody_client_test.go create mode 100644 test/http-specs/parameters/basicparamsgroup/basicimplicitbody_client_test.go create mode 100644 test/http-specs/parameters/basicparamsgroup/fake/zz_basic_server.go create mode 100644 test/http-specs/parameters/basicparamsgroup/fake/zz_basicexplicitbody_server.go create mode 100644 test/http-specs/parameters/basicparamsgroup/fake/zz_basicimplicitbody_server.go create mode 100644 test/http-specs/parameters/basicparamsgroup/fake/zz_internal.go create mode 100644 test/http-specs/parameters/basicparamsgroup/go.mod create mode 100644 test/http-specs/parameters/basicparamsgroup/go.sum create mode 100644 test/http-specs/parameters/basicparamsgroup/testdata/_metadata.json create mode 100644 test/http-specs/parameters/basicparamsgroup/zz_basic_client.go create mode 100644 test/http-specs/parameters/basicparamsgroup/zz_basicexplicitbody_client.go create mode 100644 test/http-specs/parameters/basicparamsgroup/zz_basicimplicitbody_client.go create mode 100644 test/http-specs/parameters/basicparamsgroup/zz_models.go create mode 100644 test/http-specs/parameters/basicparamsgroup/zz_models_serde.go create mode 100644 test/http-specs/parameters/basicparamsgroup/zz_options.go create mode 100644 test/http-specs/parameters/basicparamsgroup/zz_responses.go create mode 100644 test/http-specs/parameters/basicparamsgroup/zz_version.go create mode 100644 test/http-specs/parameters/bodyoptionalgroup/LICENSE.txt create mode 100644 test/http-specs/parameters/bodyoptionalgroup/bodyoptionality_client_test.go create mode 100644 test/http-specs/parameters/bodyoptionalgroup/fake/zz_bodyoptionality_server.go create mode 100644 test/http-specs/parameters/bodyoptionalgroup/fake/zz_bodyoptionalityoptionalexplicit_server.go create mode 100644 test/http-specs/parameters/bodyoptionalgroup/fake/zz_internal.go create mode 100644 test/http-specs/parameters/bodyoptionalgroup/go.mod create mode 100644 test/http-specs/parameters/bodyoptionalgroup/go.sum create mode 100644 test/http-specs/parameters/bodyoptionalgroup/optionalexplicit_client_test.go create mode 100644 test/http-specs/parameters/bodyoptionalgroup/testdata/_metadata.json create mode 100644 test/http-specs/parameters/bodyoptionalgroup/zz_bodyoptionality_client.go create mode 100644 test/http-specs/parameters/bodyoptionalgroup/zz_bodyoptionalityoptionalexplicit_client.go create mode 100644 test/http-specs/parameters/bodyoptionalgroup/zz_models.go create mode 100644 test/http-specs/parameters/bodyoptionalgroup/zz_models_serde.go create mode 100644 test/http-specs/parameters/bodyoptionalgroup/zz_options.go create mode 100644 test/http-specs/parameters/bodyoptionalgroup/zz_responses.go create mode 100644 test/http-specs/parameters/bodyoptionalgroup/zz_version.go create mode 100644 test/http-specs/parameters/collectionfmtgroup/LICENSE.txt create mode 100644 test/http-specs/parameters/collectionfmtgroup/fake/zz_collectionformat_server.go create mode 100644 test/http-specs/parameters/collectionfmtgroup/fake/zz_collectionformatheader_server.go create mode 100644 test/http-specs/parameters/collectionfmtgroup/fake/zz_collectionformatquery_server.go create mode 100644 test/http-specs/parameters/collectionfmtgroup/fake/zz_internal.go create mode 100644 test/http-specs/parameters/collectionfmtgroup/go.mod create mode 100644 test/http-specs/parameters/collectionfmtgroup/go.sum create mode 100644 test/http-specs/parameters/collectionfmtgroup/header_client_test.go create mode 100644 test/http-specs/parameters/collectionfmtgroup/query_client_test.go create mode 100644 test/http-specs/parameters/collectionfmtgroup/testdata/_metadata.json create mode 100644 test/http-specs/parameters/collectionfmtgroup/zz_collectionformat_client.go create mode 100644 test/http-specs/parameters/collectionfmtgroup/zz_collectionformatheader_client.go create mode 100644 test/http-specs/parameters/collectionfmtgroup/zz_collectionformatquery_client.go create mode 100644 test/http-specs/parameters/collectionfmtgroup/zz_options.go create mode 100644 test/http-specs/parameters/collectionfmtgroup/zz_responses.go create mode 100644 test/http-specs/parameters/collectionfmtgroup/zz_version.go create mode 100644 test/http-specs/parameters/pathgroup/LICENSE.txt create mode 100644 test/http-specs/parameters/pathgroup/fake/zz_internal.go create mode 100644 test/http-specs/parameters/pathgroup/fake/zz_path_server.go create mode 100644 test/http-specs/parameters/pathgroup/go.mod create mode 100644 test/http-specs/parameters/pathgroup/go.sum create mode 100644 test/http-specs/parameters/pathgroup/path_client_test.go create mode 100644 test/http-specs/parameters/pathgroup/testdata/_metadata.json create mode 100644 test/http-specs/parameters/pathgroup/zz_options.go create mode 100644 test/http-specs/parameters/pathgroup/zz_path_client.go create mode 100644 test/http-specs/parameters/pathgroup/zz_responses.go create mode 100644 test/http-specs/parameters/pathgroup/zz_version.go create mode 100644 test/http-specs/parameters/querygroup/LICENSE.txt create mode 100644 test/http-specs/parameters/querygroup/fake/zz_internal.go create mode 100644 test/http-specs/parameters/querygroup/fake/zz_query_server.go create mode 100644 test/http-specs/parameters/querygroup/fake/zz_queryconstant_server.go create mode 100644 test/http-specs/parameters/querygroup/fake/zz_queryspecialchar_server.go create mode 100644 test/http-specs/parameters/querygroup/go.mod create mode 100644 test/http-specs/parameters/querygroup/go.sum create mode 100644 test/http-specs/parameters/querygroup/queryconstant_client_test.go create mode 100644 test/http-specs/parameters/querygroup/testdata/_metadata.json create mode 100644 test/http-specs/parameters/querygroup/zz_options.go create mode 100644 test/http-specs/parameters/querygroup/zz_query_client.go create mode 100644 test/http-specs/parameters/querygroup/zz_queryconstant_client.go create mode 100644 test/http-specs/parameters/querygroup/zz_queryspecialchar_client.go create mode 100644 test/http-specs/parameters/querygroup/zz_responses.go create mode 100644 test/http-specs/parameters/querygroup/zz_version.go create mode 100644 test/http-specs/parameters/spreadgroup/LICENSE.txt create mode 100644 test/http-specs/parameters/spreadgroup/fake/zz_internal.go create mode 100644 test/http-specs/parameters/spreadgroup/fake/zz_spread_server.go create mode 100644 test/http-specs/parameters/spreadgroup/fake/zz_spreadalias_server.go create mode 100644 test/http-specs/parameters/spreadgroup/fake/zz_spreadmodel_server.go create mode 100644 test/http-specs/parameters/spreadgroup/fakes_test.go create mode 100644 test/http-specs/parameters/spreadgroup/go.mod create mode 100644 test/http-specs/parameters/spreadgroup/go.sum create mode 100644 test/http-specs/parameters/spreadgroup/spreadalias_client_test.go create mode 100644 test/http-specs/parameters/spreadgroup/spreadmodel_client_test.go create mode 100644 test/http-specs/parameters/spreadgroup/testdata/_metadata.json create mode 100644 test/http-specs/parameters/spreadgroup/zz_models.go create mode 100644 test/http-specs/parameters/spreadgroup/zz_models_serde.go create mode 100644 test/http-specs/parameters/spreadgroup/zz_options.go create mode 100644 test/http-specs/parameters/spreadgroup/zz_responses.go create mode 100644 test/http-specs/parameters/spreadgroup/zz_spread_client.go create mode 100644 test/http-specs/parameters/spreadgroup/zz_spreadalias_client.go create mode 100644 test/http-specs/parameters/spreadgroup/zz_spreadmodel_client.go create mode 100644 test/http-specs/parameters/spreadgroup/zz_version.go create mode 100644 test/http-specs/payload/contentneggroup/LICENSE.txt create mode 100644 test/http-specs/payload/contentneggroup/differentbody_client_test.go create mode 100644 test/http-specs/payload/contentneggroup/fake/zz_contentnegotiation_server.go create mode 100644 test/http-specs/payload/contentneggroup/fake/zz_contentnegotiationdifferentbody_server.go create mode 100644 test/http-specs/payload/contentneggroup/fake/zz_contentnegotiationsamebody_server.go create mode 100644 test/http-specs/payload/contentneggroup/fake/zz_internal.go create mode 100644 test/http-specs/payload/contentneggroup/go.mod create mode 100644 test/http-specs/payload/contentneggroup/go.sum create mode 100644 test/http-specs/payload/contentneggroup/samebody_client_test.go create mode 100644 test/http-specs/payload/contentneggroup/testdata/_metadata.json create mode 100644 test/http-specs/payload/contentneggroup/zz_contentnegotiation_client.go create mode 100644 test/http-specs/payload/contentneggroup/zz_contentnegotiationdifferentbody_client.go create mode 100644 test/http-specs/payload/contentneggroup/zz_contentnegotiationsamebody_client.go create mode 100644 test/http-specs/payload/contentneggroup/zz_models.go create mode 100644 test/http-specs/payload/contentneggroup/zz_models_serde.go create mode 100644 test/http-specs/payload/contentneggroup/zz_options.go create mode 100644 test/http-specs/payload/contentneggroup/zz_responses.go create mode 100644 test/http-specs/payload/contentneggroup/zz_version.go create mode 100644 test/http-specs/payload/jmergepatchgroup/LICENSE.txt create mode 100644 test/http-specs/payload/jmergepatchgroup/fake/zz_internal.go create mode 100644 test/http-specs/payload/jmergepatchgroup/fake/zz_jsonmergepatch_server.go create mode 100644 test/http-specs/payload/jmergepatchgroup/go.mod create mode 100644 test/http-specs/payload/jmergepatchgroup/go.sum create mode 100644 test/http-specs/payload/jmergepatchgroup/jsonmergepatch_client_test.go create mode 100644 test/http-specs/payload/jmergepatchgroup/testdata/_metadata.json create mode 100644 test/http-specs/payload/jmergepatchgroup/zz_jsonmergepatch_client.go create mode 100644 test/http-specs/payload/jmergepatchgroup/zz_models.go create mode 100644 test/http-specs/payload/jmergepatchgroup/zz_models_serde.go create mode 100644 test/http-specs/payload/jmergepatchgroup/zz_options.go create mode 100644 test/http-specs/payload/jmergepatchgroup/zz_responses.go create mode 100644 test/http-specs/payload/jmergepatchgroup/zz_version.go create mode 100644 test/http-specs/payload/mediatypegroup/LICENSE.txt create mode 100644 test/http-specs/payload/mediatypegroup/fake/zz_internal.go create mode 100644 test/http-specs/payload/mediatypegroup/fake/zz_mediatype_server.go create mode 100644 test/http-specs/payload/mediatypegroup/fake/zz_mediatypestringbody_server.go create mode 100644 test/http-specs/payload/mediatypegroup/go.mod create mode 100644 test/http-specs/payload/mediatypegroup/go.sum create mode 100644 test/http-specs/payload/mediatypegroup/stringbody_client_test.go create mode 100644 test/http-specs/payload/mediatypegroup/testdata/_metadata.json create mode 100644 test/http-specs/payload/mediatypegroup/zz_mediatype_client.go create mode 100644 test/http-specs/payload/mediatypegroup/zz_mediatypestringbody_client.go create mode 100644 test/http-specs/payload/mediatypegroup/zz_options.go create mode 100644 test/http-specs/payload/mediatypegroup/zz_responses.go create mode 100644 test/http-specs/payload/mediatypegroup/zz_version.go create mode 100644 test/http-specs/payload/multipartgroup/LICENSE.txt create mode 100644 test/http-specs/payload/multipartgroup/fake/zz_internal.go create mode 100644 test/http-specs/payload/multipartgroup/fake/zz_multipart_server.go create mode 100644 test/http-specs/payload/multipartgroup/fake/zz_multipartformdata_server.go create mode 100644 test/http-specs/payload/multipartgroup/fake/zz_multipartformdatafile_server.go create mode 100644 test/http-specs/payload/multipartgroup/fake/zz_multipartformdatahttpparts_server.go create mode 100644 test/http-specs/payload/multipartgroup/fake/zz_multipartformdatahttppartscontenttype_server.go create mode 100644 test/http-specs/payload/multipartgroup/fake/zz_multipartformdatahttppartsnonstring_server.go create mode 100644 test/http-specs/payload/multipartgroup/fakes_test.go create mode 100644 test/http-specs/payload/multipartgroup/formdata_client_test.go create mode 100644 test/http-specs/payload/multipartgroup/formdatafile_client_test.go create mode 100644 test/http-specs/payload/multipartgroup/formdatahttpparts_client_test.go create mode 100644 test/http-specs/payload/multipartgroup/formdatahttppartscontenttype_client_test.go create mode 100644 test/http-specs/payload/multipartgroup/formdatahttppartsnonstring_client_test.go create mode 100644 test/http-specs/payload/multipartgroup/go.mod create mode 100644 test/http-specs/payload/multipartgroup/go.sum create mode 100644 test/http-specs/payload/multipartgroup/helpers_test.go create mode 100644 test/http-specs/payload/multipartgroup/testdata/_metadata.json create mode 100644 test/http-specs/payload/multipartgroup/zz_models.go create mode 100644 test/http-specs/payload/multipartgroup/zz_models_serde.go create mode 100644 test/http-specs/payload/multipartgroup/zz_multipart_client.go create mode 100644 test/http-specs/payload/multipartgroup/zz_multipartformdata_client.go create mode 100644 test/http-specs/payload/multipartgroup/zz_multipartformdatafile_client.go create mode 100644 test/http-specs/payload/multipartgroup/zz_multipartformdatahttpparts_client.go create mode 100644 test/http-specs/payload/multipartgroup/zz_multipartformdatahttppartscontenttype_client.go create mode 100644 test/http-specs/payload/multipartgroup/zz_multipartformdatahttppartsnonstring_client.go create mode 100644 test/http-specs/payload/multipartgroup/zz_options.go create mode 100644 test/http-specs/payload/multipartgroup/zz_responses.go create mode 100644 test/http-specs/payload/multipartgroup/zz_version.go create mode 100644 test/http-specs/payload/pageablegroup/LICENSE.txt create mode 100644 test/http-specs/payload/pageablegroup/fake/zz_internal.go create mode 100644 test/http-specs/payload/pageablegroup/fake/zz_pageable_server.go create mode 100644 test/http-specs/payload/pageablegroup/fake/zz_pageablepagesize_server.go create mode 100644 test/http-specs/payload/pageablegroup/fake/zz_pageableserverdrivenpagination_server.go create mode 100644 test/http-specs/payload/pageablegroup/fake/zz_pageableserverdrivenpaginationalternateinitialverb_server.go create mode 100644 test/http-specs/payload/pageablegroup/fake/zz_pageableserverdrivenpaginationcontinuationtoken_server.go create mode 100644 test/http-specs/payload/pageablegroup/fake/zz_pageablexmlpagination_server.go create mode 100644 test/http-specs/payload/pageablegroup/go.mod create mode 100644 test/http-specs/payload/pageablegroup/go.sum create mode 100644 test/http-specs/payload/pageablegroup/pageablepagesize_client_test.go create mode 100644 test/http-specs/payload/pageablegroup/pageableserverdrivenpagination_client_test.go create mode 100644 test/http-specs/payload/pageablegroup/pageableserverdrivenpaginationalternateinitialverb_client_test.go create mode 100644 test/http-specs/payload/pageablegroup/pageableserverdrivenpaginationcontinuationtoken_client_test.go create mode 100644 test/http-specs/payload/pageablegroup/pageablexmlpagination_client_test.go create mode 100644 test/http-specs/payload/pageablegroup/testdata/_metadata.json create mode 100644 test/http-specs/payload/pageablegroup/zz_models.go create mode 100644 test/http-specs/payload/pageablegroup/zz_models_serde.go create mode 100644 test/http-specs/payload/pageablegroup/zz_options.go create mode 100644 test/http-specs/payload/pageablegroup/zz_pageable_client.go create mode 100644 test/http-specs/payload/pageablegroup/zz_pageablepagesize_client.go create mode 100644 test/http-specs/payload/pageablegroup/zz_pageableserverdrivenpagination_client.go create mode 100644 test/http-specs/payload/pageablegroup/zz_pageableserverdrivenpaginationalternateinitialverb_client.go create mode 100644 test/http-specs/payload/pageablegroup/zz_pageableserverdrivenpaginationcontinuationtoken_client.go create mode 100644 test/http-specs/payload/pageablegroup/zz_pageablexmlpagination_client.go create mode 100644 test/http-specs/payload/pageablegroup/zz_responses.go create mode 100644 test/http-specs/payload/pageablegroup/zz_version.go create mode 100644 test/http-specs/payload/xmlgroup/LICENSE.txt create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_internal.go create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_xml_server.go create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwitharrayofmodelvalue_server.go create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithattributesvalue_server.go create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithdatetimevalue_server.go create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithdictionaryvalue_server.go create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithemptyarrayvalue_server.go create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithencodednamesvalue_server.go create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithenumvalue_server.go create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithnamespaceonpropertiesvalue_server.go create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithnamespacevalue_server.go create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithnestedmodelvalue_server.go create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithoptionalfieldvalue_server.go create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedarraysvalue_server.go create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedattributevalue_server.go create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedfieldsvalue_server.go create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamednestedmodelvalue_server.go create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedpropertyvalue_server.go create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedunwrappedmodelarrayvalue_server.go create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedwrappedanditemmodelarrayvalue_server.go create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedwrappedmodelarrayvalue_server.go create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithsimplearraysvalue_server.go create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithtextvalue_server.go create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithunwrappedarrayvalue_server.go create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithunwrappedmodelarrayvalue_server.go create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithwrappedprimitivecustomitemnamesvalue_server.go create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_xmlsimplemodelvalue_server.go create mode 100644 test/http-specs/payload/xmlgroup/fake/zz_xmlxmlerrorvalue_server.go create mode 100644 test/http-specs/payload/xmlgroup/go.mod create mode 100644 test/http-specs/payload/xmlgroup/go.sum create mode 100644 test/http-specs/payload/xmlgroup/testdata/_metadata.json create mode 100644 test/http-specs/payload/xmlgroup/xmlmodelwitharrayofmodelvalue_client_test.go create mode 100644 test/http-specs/payload/xmlgroup/xmlmodelwithattributesvalue_client_test.go create mode 100644 test/http-specs/payload/xmlgroup/xmlmodelwithdatetimevalue_client_test.go create mode 100644 test/http-specs/payload/xmlgroup/xmlmodelwithdictionaryvalue_client_test.go create mode 100644 test/http-specs/payload/xmlgroup/xmlmodelwithemptyarrayvalue_client_test.go create mode 100644 test/http-specs/payload/xmlgroup/xmlmodelwithencodednamesvalue_client_test.go create mode 100644 test/http-specs/payload/xmlgroup/xmlmodelwithenumvalue_client_test.go create mode 100644 test/http-specs/payload/xmlgroup/xmlmodelwithnamespaceonpropertiesvalue_client_test.go create mode 100644 test/http-specs/payload/xmlgroup/xmlmodelwithnamespacevalue_client_test.go create mode 100644 test/http-specs/payload/xmlgroup/xmlmodelwithnestedmodelvalue_client_test.go create mode 100644 test/http-specs/payload/xmlgroup/xmlmodelwithoptionalfieldvalue_client_test.go create mode 100644 test/http-specs/payload/xmlgroup/xmlmodelwithrenamedarraysvalue_client_test.go create mode 100644 test/http-specs/payload/xmlgroup/xmlmodelwithrenamedattributevalue_client_test.go create mode 100644 test/http-specs/payload/xmlgroup/xmlmodelwithrenamedfieldsvalue_client_test.go create mode 100644 test/http-specs/payload/xmlgroup/xmlmodelwithrenamednestedmodelvalue_client_test.go create mode 100644 test/http-specs/payload/xmlgroup/xmlmodelwithrenamedpropertyvalue_client_test.go create mode 100644 test/http-specs/payload/xmlgroup/xmlmodelwithrenamedunwrappedmodelarrayvalue_client_test.go create mode 100644 test/http-specs/payload/xmlgroup/xmlmodelwithrenamedwrappedanditemmodelarrayvalue_client_test.go create mode 100644 test/http-specs/payload/xmlgroup/xmlmodelwithrenamedwrappedmodelarrayvalue_client_test.go create mode 100644 test/http-specs/payload/xmlgroup/xmlmodelwithsimplearraysvalue_client_test.go create mode 100644 test/http-specs/payload/xmlgroup/xmlmodelwithtextvalue_client_test.go create mode 100644 test/http-specs/payload/xmlgroup/xmlmodelwithunwrappedarrayvalue_client_test.go create mode 100644 test/http-specs/payload/xmlgroup/xmlmodelwithunwrappedmodelarrayvalue_client_test.go create mode 100644 test/http-specs/payload/xmlgroup/xmlmodelwithwrappedprimitivecustomitemnamesvalue_client_test.go create mode 100644 test/http-specs/payload/xmlgroup/xmlsimplemodelvalue_client_test.go create mode 100644 test/http-specs/payload/xmlgroup/xmlxmlerrorvalue_client_test.go create mode 100644 test/http-specs/payload/xmlgroup/zz_constants.go create mode 100644 test/http-specs/payload/xmlgroup/zz_models.go create mode 100644 test/http-specs/payload/xmlgroup/zz_models_serde.go create mode 100644 test/http-specs/payload/xmlgroup/zz_options.go create mode 100644 test/http-specs/payload/xmlgroup/zz_responses.go create mode 100644 test/http-specs/payload/xmlgroup/zz_version.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xml_client.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xml_helper.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xmlmodelwitharrayofmodelvalue_client.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xmlmodelwithattributesvalue_client.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xmlmodelwithdatetimevalue_client.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xmlmodelwithdictionaryvalue_client.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xmlmodelwithemptyarrayvalue_client.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xmlmodelwithencodednamesvalue_client.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xmlmodelwithenumvalue_client.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xmlmodelwithnamespaceonpropertiesvalue_client.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xmlmodelwithnamespacevalue_client.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xmlmodelwithnestedmodelvalue_client.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xmlmodelwithoptionalfieldvalue_client.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedarraysvalue_client.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedattributevalue_client.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedfieldsvalue_client.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamednestedmodelvalue_client.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedpropertyvalue_client.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedunwrappedmodelarrayvalue_client.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedwrappedanditemmodelarrayvalue_client.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedwrappedmodelarrayvalue_client.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xmlmodelwithsimplearraysvalue_client.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xmlmodelwithtextvalue_client.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xmlmodelwithunwrappedarrayvalue_client.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xmlmodelwithunwrappedmodelarrayvalue_client.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xmlmodelwithwrappedprimitivecustomitemnamesvalue_client.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xmlsimplemodelvalue_client.go create mode 100644 test/http-specs/payload/xmlgroup/zz_xmlxmlerrorvalue_client.go create mode 100644 test/http-specs/serialization/encoded-name/jsongroup/LICENSE.txt create mode 100644 test/http-specs/serialization/encoded-name/jsongroup/fake/zz_internal.go create mode 100644 test/http-specs/serialization/encoded-name/jsongroup/fake/zz_json_server.go create mode 100644 test/http-specs/serialization/encoded-name/jsongroup/fake/zz_jsonproperty_server.go create mode 100644 test/http-specs/serialization/encoded-name/jsongroup/go.mod create mode 100644 test/http-specs/serialization/encoded-name/jsongroup/go.sum create mode 100644 test/http-specs/serialization/encoded-name/jsongroup/jsongroup_test.go create mode 100644 test/http-specs/serialization/encoded-name/jsongroup/testdata/_metadata.json create mode 100644 test/http-specs/serialization/encoded-name/jsongroup/zz_json_client.go create mode 100644 test/http-specs/serialization/encoded-name/jsongroup/zz_jsonproperty_client.go create mode 100644 test/http-specs/serialization/encoded-name/jsongroup/zz_models.go create mode 100644 test/http-specs/serialization/encoded-name/jsongroup/zz_models_serde.go create mode 100644 test/http-specs/serialization/encoded-name/jsongroup/zz_options.go create mode 100644 test/http-specs/serialization/encoded-name/jsongroup/zz_responses.go create mode 100644 test/http-specs/serialization/encoded-name/jsongroup/zz_version.go create mode 100644 test/http-specs/server/endpoint/noendpointgroup/LICENSE.txt create mode 100644 test/http-specs/server/endpoint/noendpointgroup/fake/zz_internal.go create mode 100644 test/http-specs/server/endpoint/noendpointgroup/fake/zz_notdefined_server.go create mode 100644 test/http-specs/server/endpoint/noendpointgroup/go.mod create mode 100644 test/http-specs/server/endpoint/noendpointgroup/go.sum create mode 100644 test/http-specs/server/endpoint/noendpointgroup/notdefined_client_test.go create mode 100644 test/http-specs/server/endpoint/noendpointgroup/testdata/_metadata.json create mode 100644 test/http-specs/server/endpoint/noendpointgroup/zz_notdefined_client.go create mode 100644 test/http-specs/server/endpoint/noendpointgroup/zz_options.go create mode 100644 test/http-specs/server/endpoint/noendpointgroup/zz_responses.go create mode 100644 test/http-specs/server/endpoint/noendpointgroup/zz_version.go create mode 100644 test/http-specs/server/path/multiplegroup/LICENSE.txt create mode 100644 test/http-specs/server/path/multiplegroup/fake/zz_internal.go create mode 100644 test/http-specs/server/path/multiplegroup/fake/zz_multiple_server.go create mode 100644 test/http-specs/server/path/multiplegroup/go.mod create mode 100644 test/http-specs/server/path/multiplegroup/go.sum create mode 100644 test/http-specs/server/path/multiplegroup/multiple_client_test.go create mode 100644 test/http-specs/server/path/multiplegroup/testdata/_metadata.json create mode 100644 test/http-specs/server/path/multiplegroup/zz_multiple_client.go create mode 100644 test/http-specs/server/path/multiplegroup/zz_options.go create mode 100644 test/http-specs/server/path/multiplegroup/zz_responses.go create mode 100644 test/http-specs/server/path/multiplegroup/zz_version.go create mode 100644 test/http-specs/server/path/singlegroup/LICENSE.txt create mode 100644 test/http-specs/server/path/singlegroup/fake/zz_internal.go create mode 100644 test/http-specs/server/path/singlegroup/fake/zz_single_server.go create mode 100644 test/http-specs/server/path/singlegroup/go.mod create mode 100644 test/http-specs/server/path/singlegroup/go.sum create mode 100644 test/http-specs/server/path/singlegroup/single_client_test.go create mode 100644 test/http-specs/server/path/singlegroup/testdata/_metadata.json create mode 100644 test/http-specs/server/path/singlegroup/zz_options.go create mode 100644 test/http-specs/server/path/singlegroup/zz_responses.go create mode 100644 test/http-specs/server/path/singlegroup/zz_single_client.go create mode 100644 test/http-specs/server/path/singlegroup/zz_version.go create mode 100644 test/http-specs/server/versions/unversionedgroup/LICENSE.txt create mode 100644 test/http-specs/server/versions/unversionedgroup/fake/zz_internal.go create mode 100644 test/http-specs/server/versions/unversionedgroup/fake/zz_notversioned_server.go create mode 100644 test/http-specs/server/versions/unversionedgroup/go.mod create mode 100644 test/http-specs/server/versions/unversionedgroup/go.sum create mode 100644 test/http-specs/server/versions/unversionedgroup/notversioned_client_test.go create mode 100644 test/http-specs/server/versions/unversionedgroup/testdata/_metadata.json create mode 100644 test/http-specs/server/versions/unversionedgroup/zz_notversioned_client.go create mode 100644 test/http-specs/server/versions/unversionedgroup/zz_options.go create mode 100644 test/http-specs/server/versions/unversionedgroup/zz_responses.go create mode 100644 test/http-specs/server/versions/unversionedgroup/zz_version.go create mode 100644 test/http-specs/server/versions/versionedgroup/LICENSE.txt create mode 100644 test/http-specs/server/versions/versionedgroup/fake/zz_internal.go create mode 100644 test/http-specs/server/versions/versionedgroup/fake/zz_versioned_server.go create mode 100644 test/http-specs/server/versions/versionedgroup/go.mod create mode 100644 test/http-specs/server/versions/versionedgroup/go.sum create mode 100644 test/http-specs/server/versions/versionedgroup/testdata/_metadata.json create mode 100644 test/http-specs/server/versions/versionedgroup/versioned_client_test.go create mode 100644 test/http-specs/server/versions/versionedgroup/zz_constants.go create mode 100644 test/http-specs/server/versions/versionedgroup/zz_options.go create mode 100644 test/http-specs/server/versions/versionedgroup/zz_responses.go create mode 100644 test/http-specs/server/versions/versionedgroup/zz_version.go create mode 100644 test/http-specs/server/versions/versionedgroup/zz_versioned_client.go create mode 100644 test/http-specs/special-headers/condreqgroup/LICENSE.txt create mode 100644 test/http-specs/special-headers/condreqgroup/conditionalrequest_client_test.go create mode 100644 test/http-specs/special-headers/condreqgroup/fake/zz_conditionalrequest_server.go create mode 100644 test/http-specs/special-headers/condreqgroup/fake/zz_internal.go create mode 100644 test/http-specs/special-headers/condreqgroup/go.mod create mode 100644 test/http-specs/special-headers/condreqgroup/go.sum create mode 100644 test/http-specs/special-headers/condreqgroup/testdata/_metadata.json create mode 100644 test/http-specs/special-headers/condreqgroup/zz_conditionalrequest_client.go create mode 100644 test/http-specs/special-headers/condreqgroup/zz_options.go create mode 100644 test/http-specs/special-headers/condreqgroup/zz_responses.go create mode 100644 test/http-specs/special-headers/condreqgroup/zz_version.go create mode 100644 test/http-specs/specialwordsgroup/LICENSE.txt create mode 100644 test/http-specs/specialwordsgroup/extensiblestrings_client_test.go create mode 100644 test/http-specs/specialwordsgroup/fake/zz_internal.go create mode 100644 test/http-specs/specialwordsgroup/fake/zz_specialwords_server.go create mode 100644 test/http-specs/specialwordsgroup/fake/zz_specialwordsextensiblestrings_server.go create mode 100644 test/http-specs/specialwordsgroup/fake/zz_specialwordsmodelproperties_server.go create mode 100644 test/http-specs/specialwordsgroup/fake/zz_specialwordsmodels_server.go create mode 100644 test/http-specs/specialwordsgroup/fake/zz_specialwordsoperations_server.go create mode 100644 test/http-specs/specialwordsgroup/fake/zz_specialwordsparameters_server.go create mode 100644 test/http-specs/specialwordsgroup/fake/zz_specialwordsreservedoperationbodyparams_server.go create mode 100644 test/http-specs/specialwordsgroup/go.mod create mode 100644 test/http-specs/specialwordsgroup/go.sum create mode 100644 test/http-specs/specialwordsgroup/modelproperties_client_test.go create mode 100644 test/http-specs/specialwordsgroup/models_client_test.go create mode 100644 test/http-specs/specialwordsgroup/operations_client_test.go create mode 100644 test/http-specs/specialwordsgroup/parameters_client_test.go create mode 100644 test/http-specs/specialwordsgroup/reservedoperationbodyparams_client_test.go create mode 100644 test/http-specs/specialwordsgroup/testdata/_metadata.json create mode 100644 test/http-specs/specialwordsgroup/zz_constants.go create mode 100644 test/http-specs/specialwordsgroup/zz_models.go create mode 100644 test/http-specs/specialwordsgroup/zz_models_serde.go create mode 100644 test/http-specs/specialwordsgroup/zz_options.go create mode 100644 test/http-specs/specialwordsgroup/zz_responses.go create mode 100644 test/http-specs/specialwordsgroup/zz_specialwords_client.go create mode 100644 test/http-specs/specialwordsgroup/zz_specialwordsextensiblestrings_client.go create mode 100644 test/http-specs/specialwordsgroup/zz_specialwordsmodelproperties_client.go create mode 100644 test/http-specs/specialwordsgroup/zz_specialwordsmodels_client.go create mode 100644 test/http-specs/specialwordsgroup/zz_specialwordsoperations_client.go create mode 100644 test/http-specs/specialwordsgroup/zz_specialwordsparameters_client.go create mode 100644 test/http-specs/specialwordsgroup/zz_specialwordsreservedoperationbodyparams_client.go create mode 100644 test/http-specs/specialwordsgroup/zz_version.go create mode 100644 test/http-specs/type/arraygroup/LICENSE.txt create mode 100644 test/http-specs/type/arraygroup/arraygroup_test.go create mode 100644 test/http-specs/type/arraygroup/fake/zz_array_server.go create mode 100644 test/http-specs/type/arraygroup/fake/zz_arraybooleanvalue_server.go create mode 100644 test/http-specs/type/arraygroup/fake/zz_arraydatetimevalue_server.go create mode 100644 test/http-specs/type/arraygroup/fake/zz_arraydurationvalue_server.go create mode 100644 test/http-specs/type/arraygroup/fake/zz_arrayfloat32value_server.go create mode 100644 test/http-specs/type/arraygroup/fake/zz_arrayint32value_server.go create mode 100644 test/http-specs/type/arraygroup/fake/zz_arrayint64value_server.go create mode 100644 test/http-specs/type/arraygroup/fake/zz_arraymodelvalue_server.go create mode 100644 test/http-specs/type/arraygroup/fake/zz_arraynullablebooleanvalue_server.go create mode 100644 test/http-specs/type/arraygroup/fake/zz_arraynullablefloatvalue_server.go create mode 100644 test/http-specs/type/arraygroup/fake/zz_arraynullableint32value_server.go create mode 100644 test/http-specs/type/arraygroup/fake/zz_arraynullablemodelvalue_server.go create mode 100644 test/http-specs/type/arraygroup/fake/zz_arraynullablestringvalue_server.go create mode 100644 test/http-specs/type/arraygroup/fake/zz_arraystringvalue_server.go create mode 100644 test/http-specs/type/arraygroup/fake/zz_arrayunknownvalue_server.go create mode 100644 test/http-specs/type/arraygroup/fake/zz_internal.go create mode 100644 test/http-specs/type/arraygroup/go.mod create mode 100644 test/http-specs/type/arraygroup/go.sum create mode 100644 test/http-specs/type/arraygroup/testdata/_metadata.json create mode 100644 test/http-specs/type/arraygroup/zz_array_client.go create mode 100644 test/http-specs/type/arraygroup/zz_arraybooleanvalue_client.go create mode 100644 test/http-specs/type/arraygroup/zz_arraydatetimevalue_client.go create mode 100644 test/http-specs/type/arraygroup/zz_arraydurationvalue_client.go create mode 100644 test/http-specs/type/arraygroup/zz_arrayfloat32value_client.go create mode 100644 test/http-specs/type/arraygroup/zz_arrayint32value_client.go create mode 100644 test/http-specs/type/arraygroup/zz_arrayint64value_client.go create mode 100644 test/http-specs/type/arraygroup/zz_arraymodelvalue_client.go create mode 100644 test/http-specs/type/arraygroup/zz_arraynullablebooleanvalue_client.go create mode 100644 test/http-specs/type/arraygroup/zz_arraynullablefloatvalue_client.go create mode 100644 test/http-specs/type/arraygroup/zz_arraynullableint32value_client.go create mode 100644 test/http-specs/type/arraygroup/zz_arraynullablemodelvalue_client.go create mode 100644 test/http-specs/type/arraygroup/zz_arraynullablestringvalue_client.go create mode 100644 test/http-specs/type/arraygroup/zz_arraystringvalue_client.go create mode 100644 test/http-specs/type/arraygroup/zz_arrayunknownvalue_client.go create mode 100644 test/http-specs/type/arraygroup/zz_models.go create mode 100644 test/http-specs/type/arraygroup/zz_models_serde.go create mode 100644 test/http-specs/type/arraygroup/zz_options.go create mode 100644 test/http-specs/type/arraygroup/zz_responses.go create mode 100644 test/http-specs/type/arraygroup/zz_version.go create mode 100644 test/http-specs/type/dictionarygroup/LICENSE.txt create mode 100644 test/http-specs/type/dictionarygroup/dictionarygroup_test.go create mode 100644 test/http-specs/type/dictionarygroup/fake/zz_dictionary_server.go create mode 100644 test/http-specs/type/dictionarygroup/fake/zz_dictionarybooleanvalue_server.go create mode 100644 test/http-specs/type/dictionarygroup/fake/zz_dictionarydatetimevalue_server.go create mode 100644 test/http-specs/type/dictionarygroup/fake/zz_dictionarydurationvalue_server.go create mode 100644 test/http-specs/type/dictionarygroup/fake/zz_dictionaryfloat32value_server.go create mode 100644 test/http-specs/type/dictionarygroup/fake/zz_dictionaryint32value_server.go create mode 100644 test/http-specs/type/dictionarygroup/fake/zz_dictionaryint64value_server.go create mode 100644 test/http-specs/type/dictionarygroup/fake/zz_dictionarymodelvalue_server.go create mode 100644 test/http-specs/type/dictionarygroup/fake/zz_dictionarynullablefloatvalue_server.go create mode 100644 test/http-specs/type/dictionarygroup/fake/zz_dictionaryrecursivemodelvalue_server.go create mode 100644 test/http-specs/type/dictionarygroup/fake/zz_dictionarystringvalue_server.go create mode 100644 test/http-specs/type/dictionarygroup/fake/zz_dictionaryunknownvalue_server.go create mode 100644 test/http-specs/type/dictionarygroup/fake/zz_internal.go create mode 100644 test/http-specs/type/dictionarygroup/go.mod create mode 100644 test/http-specs/type/dictionarygroup/go.sum create mode 100644 test/http-specs/type/dictionarygroup/testdata/_metadata.json create mode 100644 test/http-specs/type/dictionarygroup/zz_dictionary_client.go create mode 100644 test/http-specs/type/dictionarygroup/zz_dictionarybooleanvalue_client.go create mode 100644 test/http-specs/type/dictionarygroup/zz_dictionarydatetimevalue_client.go create mode 100644 test/http-specs/type/dictionarygroup/zz_dictionarydurationvalue_client.go create mode 100644 test/http-specs/type/dictionarygroup/zz_dictionaryfloat32value_client.go create mode 100644 test/http-specs/type/dictionarygroup/zz_dictionaryint32value_client.go create mode 100644 test/http-specs/type/dictionarygroup/zz_dictionaryint64value_client.go create mode 100644 test/http-specs/type/dictionarygroup/zz_dictionarymodelvalue_client.go create mode 100644 test/http-specs/type/dictionarygroup/zz_dictionarynullablefloatvalue_client.go create mode 100644 test/http-specs/type/dictionarygroup/zz_dictionaryrecursivemodelvalue_client.go create mode 100644 test/http-specs/type/dictionarygroup/zz_dictionarystringvalue_client.go create mode 100644 test/http-specs/type/dictionarygroup/zz_dictionaryunknownvalue_client.go create mode 100644 test/http-specs/type/dictionarygroup/zz_models.go create mode 100644 test/http-specs/type/dictionarygroup/zz_models_serde.go create mode 100644 test/http-specs/type/dictionarygroup/zz_options.go create mode 100644 test/http-specs/type/dictionarygroup/zz_responses.go create mode 100644 test/http-specs/type/dictionarygroup/zz_version.go create mode 100644 test/http-specs/type/enum/extensiblegroup/LICENSE.txt create mode 100644 test/http-specs/type/enum/extensiblegroup/fake/zz_extensible_server.go create mode 100644 test/http-specs/type/enum/extensiblegroup/fake/zz_extensiblestring_server.go create mode 100644 test/http-specs/type/enum/extensiblegroup/fake/zz_internal.go create mode 100644 test/http-specs/type/enum/extensiblegroup/go.mod create mode 100644 test/http-specs/type/enum/extensiblegroup/go.sum create mode 100644 test/http-specs/type/enum/extensiblegroup/string_client_test.go create mode 100644 test/http-specs/type/enum/extensiblegroup/testdata/_metadata.json create mode 100644 test/http-specs/type/enum/extensiblegroup/zz_constants.go create mode 100644 test/http-specs/type/enum/extensiblegroup/zz_extensible_client.go create mode 100644 test/http-specs/type/enum/extensiblegroup/zz_extensiblestring_client.go create mode 100644 test/http-specs/type/enum/extensiblegroup/zz_options.go create mode 100644 test/http-specs/type/enum/extensiblegroup/zz_responses.go create mode 100644 test/http-specs/type/enum/extensiblegroup/zz_version.go create mode 100644 test/http-specs/type/enum/fixedgroup/LICENSE.txt create mode 100644 test/http-specs/type/enum/fixedgroup/fake/zz_fixed_server.go create mode 100644 test/http-specs/type/enum/fixedgroup/fake/zz_fixedstring_server.go create mode 100644 test/http-specs/type/enum/fixedgroup/fake/zz_internal.go create mode 100644 test/http-specs/type/enum/fixedgroup/go.mod create mode 100644 test/http-specs/type/enum/fixedgroup/go.sum create mode 100644 test/http-specs/type/enum/fixedgroup/string_client_test.go create mode 100644 test/http-specs/type/enum/fixedgroup/testdata/_metadata.json create mode 100644 test/http-specs/type/enum/fixedgroup/zz_constants.go create mode 100644 test/http-specs/type/enum/fixedgroup/zz_fixed_client.go create mode 100644 test/http-specs/type/enum/fixedgroup/zz_fixedstring_client.go create mode 100644 test/http-specs/type/enum/fixedgroup/zz_options.go create mode 100644 test/http-specs/type/enum/fixedgroup/zz_responses.go create mode 100644 test/http-specs/type/enum/fixedgroup/zz_version.go create mode 100644 test/http-specs/type/model/emptygroup/LICENSE.txt create mode 100644 test/http-specs/type/model/emptygroup/empty_client_test.go create mode 100644 test/http-specs/type/model/emptygroup/fake/zz_empty_server.go create mode 100644 test/http-specs/type/model/emptygroup/fake/zz_internal.go create mode 100644 test/http-specs/type/model/emptygroup/go.mod create mode 100644 test/http-specs/type/model/emptygroup/go.sum create mode 100644 test/http-specs/type/model/emptygroup/testdata/_metadata.json create mode 100644 test/http-specs/type/model/emptygroup/zz_empty_client.go create mode 100644 test/http-specs/type/model/emptygroup/zz_models.go create mode 100644 test/http-specs/type/model/emptygroup/zz_options.go create mode 100644 test/http-specs/type/model/emptygroup/zz_responses.go create mode 100644 test/http-specs/type/model/emptygroup/zz_version.go create mode 100644 test/http-specs/type/model/inheritance/enumdiscgroup/LICENSE.txt create mode 100644 test/http-specs/type/model/inheritance/enumdiscgroup/enumdiscriminator_client_test.go create mode 100644 test/http-specs/type/model/inheritance/enumdiscgroup/fake/zz_enumdiscriminator_server.go create mode 100644 test/http-specs/type/model/inheritance/enumdiscgroup/fake/zz_internal.go create mode 100644 test/http-specs/type/model/inheritance/enumdiscgroup/fake/zz_polymorphic_helpers.go create mode 100644 test/http-specs/type/model/inheritance/enumdiscgroup/go.mod create mode 100644 test/http-specs/type/model/inheritance/enumdiscgroup/go.sum create mode 100644 test/http-specs/type/model/inheritance/enumdiscgroup/testdata/_metadata.json create mode 100644 test/http-specs/type/model/inheritance/enumdiscgroup/zz_constants.go create mode 100644 test/http-specs/type/model/inheritance/enumdiscgroup/zz_enumdiscriminator_client.go create mode 100644 test/http-specs/type/model/inheritance/enumdiscgroup/zz_interfaces.go create mode 100644 test/http-specs/type/model/inheritance/enumdiscgroup/zz_models.go create mode 100644 test/http-specs/type/model/inheritance/enumdiscgroup/zz_models_serde.go create mode 100644 test/http-specs/type/model/inheritance/enumdiscgroup/zz_options.go create mode 100644 test/http-specs/type/model/inheritance/enumdiscgroup/zz_polymorphic_helpers.go create mode 100644 test/http-specs/type/model/inheritance/enumdiscgroup/zz_responses.go create mode 100644 test/http-specs/type/model/inheritance/enumdiscgroup/zz_responses_serde.go create mode 100644 test/http-specs/type/model/inheritance/enumdiscgroup/zz_version.go create mode 100644 test/http-specs/type/model/inheritance/nodiscgroup/LICENSE.txt create mode 100644 test/http-specs/type/model/inheritance/nodiscgroup/fake/zz_internal.go create mode 100644 test/http-specs/type/model/inheritance/nodiscgroup/fake/zz_notdiscriminated_server.go create mode 100644 test/http-specs/type/model/inheritance/nodiscgroup/go.mod create mode 100644 test/http-specs/type/model/inheritance/nodiscgroup/go.sum create mode 100644 test/http-specs/type/model/inheritance/nodiscgroup/notdiscriminated_client_test.go create mode 100644 test/http-specs/type/model/inheritance/nodiscgroup/testdata/_metadata.json create mode 100644 test/http-specs/type/model/inheritance/nodiscgroup/zz_models.go create mode 100644 test/http-specs/type/model/inheritance/nodiscgroup/zz_models_serde.go create mode 100644 test/http-specs/type/model/inheritance/nodiscgroup/zz_notdiscriminated_client.go create mode 100644 test/http-specs/type/model/inheritance/nodiscgroup/zz_options.go create mode 100644 test/http-specs/type/model/inheritance/nodiscgroup/zz_responses.go create mode 100644 test/http-specs/type/model/inheritance/nodiscgroup/zz_version.go create mode 100644 test/http-specs/type/model/inheritance/recursivegroup/LICENSE.txt create mode 100644 test/http-specs/type/model/inheritance/recursivegroup/fake/zz_internal.go create mode 100644 test/http-specs/type/model/inheritance/recursivegroup/fake/zz_recursive_server.go create mode 100644 test/http-specs/type/model/inheritance/recursivegroup/go.mod create mode 100644 test/http-specs/type/model/inheritance/recursivegroup/go.sum create mode 100644 test/http-specs/type/model/inheritance/recursivegroup/recursive_client_test.go create mode 100644 test/http-specs/type/model/inheritance/recursivegroup/testdata/_metadata.json create mode 100644 test/http-specs/type/model/inheritance/recursivegroup/zz_models.go create mode 100644 test/http-specs/type/model/inheritance/recursivegroup/zz_models_serde.go create mode 100644 test/http-specs/type/model/inheritance/recursivegroup/zz_options.go create mode 100644 test/http-specs/type/model/inheritance/recursivegroup/zz_recursive_client.go create mode 100644 test/http-specs/type/model/inheritance/recursivegroup/zz_responses.go create mode 100644 test/http-specs/type/model/inheritance/recursivegroup/zz_version.go create mode 100644 test/http-specs/type/model/inheritance/singlediscgroup/LICENSE.txt create mode 100644 test/http-specs/type/model/inheritance/singlediscgroup/fake/zz_internal.go create mode 100644 test/http-specs/type/model/inheritance/singlediscgroup/fake/zz_polymorphic_helpers.go create mode 100644 test/http-specs/type/model/inheritance/singlediscgroup/fake/zz_singlediscriminator_server.go create mode 100644 test/http-specs/type/model/inheritance/singlediscgroup/go.mod create mode 100644 test/http-specs/type/model/inheritance/singlediscgroup/go.sum create mode 100644 test/http-specs/type/model/inheritance/singlediscgroup/singlediscriminator_client_test.go create mode 100644 test/http-specs/type/model/inheritance/singlediscgroup/testdata/_metadata.json create mode 100644 test/http-specs/type/model/inheritance/singlediscgroup/zz_interfaces.go create mode 100644 test/http-specs/type/model/inheritance/singlediscgroup/zz_models.go create mode 100644 test/http-specs/type/model/inheritance/singlediscgroup/zz_models_serde.go create mode 100644 test/http-specs/type/model/inheritance/singlediscgroup/zz_options.go create mode 100644 test/http-specs/type/model/inheritance/singlediscgroup/zz_polymorphic_helpers.go create mode 100644 test/http-specs/type/model/inheritance/singlediscgroup/zz_responses.go create mode 100644 test/http-specs/type/model/inheritance/singlediscgroup/zz_responses_serde.go create mode 100644 test/http-specs/type/model/inheritance/singlediscgroup/zz_singlediscriminator_client.go create mode 100644 test/http-specs/type/model/inheritance/singlediscgroup/zz_version.go create mode 100644 test/http-specs/type/model/usagegroup/LICENSE.txt create mode 100644 test/http-specs/type/model/usagegroup/fake/zz_internal.go create mode 100644 test/http-specs/type/model/usagegroup/fake/zz_usage_server.go create mode 100644 test/http-specs/type/model/usagegroup/go.mod create mode 100644 test/http-specs/type/model/usagegroup/go.sum create mode 100644 test/http-specs/type/model/usagegroup/testdata/_metadata.json create mode 100644 test/http-specs/type/model/usagegroup/usage_client_test.go create mode 100644 test/http-specs/type/model/usagegroup/zz_models.go create mode 100644 test/http-specs/type/model/usagegroup/zz_models_serde.go create mode 100644 test/http-specs/type/model/usagegroup/zz_options.go create mode 100644 test/http-specs/type/model/usagegroup/zz_responses.go create mode 100644 test/http-specs/type/model/usagegroup/zz_usage_client.go create mode 100644 test/http-specs/type/model/usagegroup/zz_version.go create mode 100644 test/http-specs/type/model/visibilitygroup/LICENSE.txt create mode 100644 test/http-specs/type/model/visibilitygroup/fake/zz_internal.go create mode 100644 test/http-specs/type/model/visibilitygroup/fake/zz_visibility_server.go create mode 100644 test/http-specs/type/model/visibilitygroup/go.mod create mode 100644 test/http-specs/type/model/visibilitygroup/go.sum create mode 100644 test/http-specs/type/model/visibilitygroup/testdata/_metadata.json create mode 100644 test/http-specs/type/model/visibilitygroup/visibility_client_test.go create mode 100644 test/http-specs/type/model/visibilitygroup/zz_models.go create mode 100644 test/http-specs/type/model/visibilitygroup/zz_models_serde.go create mode 100644 test/http-specs/type/model/visibilitygroup/zz_options.go create mode 100644 test/http-specs/type/model/visibilitygroup/zz_responses.go create mode 100644 test/http-specs/type/model/visibilitygroup/zz_version.go create mode 100644 test/http-specs/type/model/visibilitygroup/zz_visibility_client.go create mode 100644 test/http-specs/type/property/addlpropsgroup/custom_client.go create mode 100644 test/http-specs/type/property/addlpropsgroup/extendsfloat_client_test.go create mode 100644 test/http-specs/type/property/addlpropsgroup/extendsmodel_client_test.go create mode 100644 test/http-specs/type/property/addlpropsgroup/extendsmodelarray_client_test.go create mode 100644 test/http-specs/type/property/addlpropsgroup/extendsstring_client_test.go create mode 100644 test/http-specs/type/property/addlpropsgroup/extendsunknown_client_test.go create mode 100644 test/http-specs/type/property/addlpropsgroup/extendsunknownderived_client_test.go create mode 100644 test/http-specs/type/property/addlpropsgroup/extendsunknowndiscriminated_client_test.go create mode 100644 test/http-specs/type/property/addlpropsgroup/isfloat_client_test.go create mode 100644 test/http-specs/type/property/addlpropsgroup/ismodel_client_test.go create mode 100644 test/http-specs/type/property/addlpropsgroup/ismodelarray_client_test.go create mode 100644 test/http-specs/type/property/addlpropsgroup/isstring_client_test.go create mode 100644 test/http-specs/type/property/addlpropsgroup/isunknown_client_test.go create mode 100644 test/http-specs/type/property/addlpropsgroup/isunknownderived_client_test.go create mode 100644 test/http-specs/type/property/addlpropsgroup/isunknowndiscriminated_client_test.go create mode 100644 test/http-specs/type/property/nullablegroup/LICENSE.txt create mode 100644 test/http-specs/type/property/nullablegroup/bytes_client_test.go create mode 100644 test/http-specs/type/property/nullablegroup/collectionsbyte_client_test.go create mode 100644 test/http-specs/type/property/nullablegroup/collectionsmodel_client_test.go create mode 100644 test/http-specs/type/property/nullablegroup/collectionsstring_client_test.go create mode 100644 test/http-specs/type/property/nullablegroup/datetime_client_test.go create mode 100644 test/http-specs/type/property/nullablegroup/duration_client_test.go create mode 100644 test/http-specs/type/property/nullablegroup/fake/zz_internal.go create mode 100644 test/http-specs/type/property/nullablegroup/fake/zz_nullable_server.go create mode 100644 test/http-specs/type/property/nullablegroup/fake/zz_nullablebytes_server.go create mode 100644 test/http-specs/type/property/nullablegroup/fake/zz_nullablecollectionsbyte_server.go create mode 100644 test/http-specs/type/property/nullablegroup/fake/zz_nullablecollectionsmodel_server.go create mode 100644 test/http-specs/type/property/nullablegroup/fake/zz_nullablecollectionsstring_server.go create mode 100644 test/http-specs/type/property/nullablegroup/fake/zz_nullabledatetime_server.go create mode 100644 test/http-specs/type/property/nullablegroup/fake/zz_nullableduration_server.go create mode 100644 test/http-specs/type/property/nullablegroup/fake/zz_nullablestring_server.go create mode 100644 test/http-specs/type/property/nullablegroup/go.mod create mode 100644 test/http-specs/type/property/nullablegroup/go.sum create mode 100644 test/http-specs/type/property/nullablegroup/string_client_test.go create mode 100644 test/http-specs/type/property/nullablegroup/testdata/_metadata.json create mode 100644 test/http-specs/type/property/nullablegroup/zz_models.go create mode 100644 test/http-specs/type/property/nullablegroup/zz_models_serde.go create mode 100644 test/http-specs/type/property/nullablegroup/zz_nullable_client.go create mode 100644 test/http-specs/type/property/nullablegroup/zz_nullablebytes_client.go create mode 100644 test/http-specs/type/property/nullablegroup/zz_nullablecollectionsbyte_client.go create mode 100644 test/http-specs/type/property/nullablegroup/zz_nullablecollectionsmodel_client.go create mode 100644 test/http-specs/type/property/nullablegroup/zz_nullablecollectionsstring_client.go create mode 100644 test/http-specs/type/property/nullablegroup/zz_nullabledatetime_client.go create mode 100644 test/http-specs/type/property/nullablegroup/zz_nullableduration_client.go create mode 100644 test/http-specs/type/property/nullablegroup/zz_nullablestring_client.go create mode 100644 test/http-specs/type/property/nullablegroup/zz_options.go create mode 100644 test/http-specs/type/property/nullablegroup/zz_responses.go create mode 100644 test/http-specs/type/property/nullablegroup/zz_version.go create mode 100644 test/http-specs/type/property/optionalitygroup/LICENSE.txt create mode 100644 test/http-specs/type/property/optionalitygroup/fake/zz_internal.go create mode 100644 test/http-specs/type/property/optionalitygroup/fake/zz_optional_server.go create mode 100644 test/http-specs/type/property/optionalitygroup/fake/zz_optionalbooleanliteral_server.go create mode 100644 test/http-specs/type/property/optionalitygroup/fake/zz_optionalbytes_server.go create mode 100644 test/http-specs/type/property/optionalitygroup/fake/zz_optionalcollectionsbyte_server.go create mode 100644 test/http-specs/type/property/optionalitygroup/fake/zz_optionalcollectionsmodel_server.go create mode 100644 test/http-specs/type/property/optionalitygroup/fake/zz_optionaldatetime_server.go create mode 100644 test/http-specs/type/property/optionalitygroup/fake/zz_optionalduration_server.go create mode 100644 test/http-specs/type/property/optionalitygroup/fake/zz_optionalfloatliteral_server.go create mode 100644 test/http-specs/type/property/optionalitygroup/fake/zz_optionalintliteral_server.go create mode 100644 test/http-specs/type/property/optionalitygroup/fake/zz_optionalplaindate_server.go create mode 100644 test/http-specs/type/property/optionalitygroup/fake/zz_optionalplaintime_server.go create mode 100644 test/http-specs/type/property/optionalitygroup/fake/zz_optionalrequiredandoptional_server.go create mode 100644 test/http-specs/type/property/optionalitygroup/fake/zz_optionalstring_server.go create mode 100644 test/http-specs/type/property/optionalitygroup/fake/zz_optionalstringliteral_server.go create mode 100644 test/http-specs/type/property/optionalitygroup/fake/zz_optionalunionfloatliteral_server.go create mode 100644 test/http-specs/type/property/optionalitygroup/fake/zz_optionalunionintliteral_server.go create mode 100644 test/http-specs/type/property/optionalitygroup/fake/zz_optionalunionstringliteral_server.go create mode 100644 test/http-specs/type/property/optionalitygroup/go.mod create mode 100644 test/http-specs/type/property/optionalitygroup/go.sum create mode 100644 test/http-specs/type/property/optionalitygroup/optionalbooleanliteral_client_test.go create mode 100644 test/http-specs/type/property/optionalitygroup/optionalbytes_client_test.go create mode 100644 test/http-specs/type/property/optionalitygroup/optionalcollectionsbyte_client_test.go create mode 100644 test/http-specs/type/property/optionalitygroup/optionalcollectionsmodel_client_test.go create mode 100644 test/http-specs/type/property/optionalitygroup/optionaldatetime_client_test.go create mode 100644 test/http-specs/type/property/optionalitygroup/optionalduration_client_test.go create mode 100644 test/http-specs/type/property/optionalitygroup/optionalfloatliteral_client_test.go create mode 100644 test/http-specs/type/property/optionalitygroup/optionalintliteral_client_test.go create mode 100644 test/http-specs/type/property/optionalitygroup/optionalplaindate_client_test.go create mode 100644 test/http-specs/type/property/optionalitygroup/optionalplaintime_client_test.go create mode 100644 test/http-specs/type/property/optionalitygroup/optionalrequiredandoptional_client_test.go create mode 100644 test/http-specs/type/property/optionalitygroup/optionalstring_client_test.go create mode 100644 test/http-specs/type/property/optionalitygroup/optionalstringliteral_client_test.go create mode 100644 test/http-specs/type/property/optionalitygroup/optionalunionfloatliteral_client_test.go create mode 100644 test/http-specs/type/property/optionalitygroup/optionalunionintliteral_client_test.go create mode 100644 test/http-specs/type/property/optionalitygroup/optionalunionstringliteral_client_test.go create mode 100644 test/http-specs/type/property/optionalitygroup/testdata/_metadata.json create mode 100644 test/http-specs/type/property/optionalitygroup/zz_constants.go create mode 100644 test/http-specs/type/property/optionalitygroup/zz_models.go create mode 100644 test/http-specs/type/property/optionalitygroup/zz_models_serde.go create mode 100644 test/http-specs/type/property/optionalitygroup/zz_optional_client.go create mode 100644 test/http-specs/type/property/optionalitygroup/zz_optionalbooleanliteral_client.go create mode 100644 test/http-specs/type/property/optionalitygroup/zz_optionalbytes_client.go create mode 100644 test/http-specs/type/property/optionalitygroup/zz_optionalcollectionsbyte_client.go create mode 100644 test/http-specs/type/property/optionalitygroup/zz_optionalcollectionsmodel_client.go create mode 100644 test/http-specs/type/property/optionalitygroup/zz_optionaldatetime_client.go create mode 100644 test/http-specs/type/property/optionalitygroup/zz_optionalduration_client.go create mode 100644 test/http-specs/type/property/optionalitygroup/zz_optionalfloatliteral_client.go create mode 100644 test/http-specs/type/property/optionalitygroup/zz_optionalintliteral_client.go create mode 100644 test/http-specs/type/property/optionalitygroup/zz_optionalplaindate_client.go create mode 100644 test/http-specs/type/property/optionalitygroup/zz_optionalplaintime_client.go create mode 100644 test/http-specs/type/property/optionalitygroup/zz_optionalrequiredandoptional_client.go create mode 100644 test/http-specs/type/property/optionalitygroup/zz_optionalstring_client.go create mode 100644 test/http-specs/type/property/optionalitygroup/zz_optionalstringliteral_client.go create mode 100644 test/http-specs/type/property/optionalitygroup/zz_optionalunionfloatliteral_client.go create mode 100644 test/http-specs/type/property/optionalitygroup/zz_optionalunionintliteral_client.go create mode 100644 test/http-specs/type/property/optionalitygroup/zz_optionalunionstringliteral_client.go create mode 100644 test/http-specs/type/property/optionalitygroup/zz_options.go create mode 100644 test/http-specs/type/property/optionalitygroup/zz_responses.go create mode 100644 test/http-specs/type/property/optionalitygroup/zz_version.go create mode 100644 test/http-specs/type/property/valuetypesgroup/LICENSE.txt create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_internal.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypes_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesboolean_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesbooleanliteral_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesbytes_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypescollectionsint_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypescollectionsmodel_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypescollectionsstring_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesdatetime_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesdecimal128_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesdecimal_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesdictionarystring_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesduration_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesenum_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesextensibleenum_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesfloat_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesfloatliteral_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesint_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesintliteral_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesmodel_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesnever_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesstring_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesstringliteral_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunionenumvalue_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunionfloatliteral_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunionintliteral_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunionstringliteral_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunknownarray_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunknowndict_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunknownint_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunknownstring_server.go create mode 100644 test/http-specs/type/property/valuetypesgroup/go.mod create mode 100644 test/http-specs/type/property/valuetypesgroup/go.sum create mode 100644 test/http-specs/type/property/valuetypesgroup/testdata/_metadata.json create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypesboolean_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypesbooleanliteral_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypesbytes_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypescollectionsint_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypescollectionsmodel_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypescollectionsstring_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypesdatetime_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypesdecimal128_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypesdecimal_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypesdictionarystring_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypesduration_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypesenum_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypesextensibleenum_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypesfloat_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypesfloatliteral_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypesint_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypesintliteral_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypesmodel_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypesnever_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypesstring_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypesstringliteral_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypesunionenumvalue_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypesunionfloatliteral_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypesunionintliteral_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypesunionstringliteral_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypesunknownarray_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypesunknowndict_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypesunknownint_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/valuetypesunknownstring_client_test.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_constants.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_models.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_models_serde.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_options.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_responses.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypes_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypesboolean_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypesbooleanliteral_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypesbytes_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypescollectionsint_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypescollectionsmodel_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypescollectionsstring_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypesdatetime_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypesdecimal128_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypesdecimal_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypesdictionarystring_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypesduration_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypesenum_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypesextensibleenum_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypesfloat_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypesfloatliteral_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypesint_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypesintliteral_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypesmodel_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypesnever_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypesstring_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypesstringliteral_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypesunionenumvalue_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypesunionfloatliteral_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypesunionintliteral_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypesunionstringliteral_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypesunknownarray_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypesunknowndict_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypesunknownint_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_valuetypesunknownstring_client.go create mode 100644 test/http-specs/type/property/valuetypesgroup/zz_version.go create mode 100644 test/http-specs/type/scalargroup/LICENSE.txt create mode 100644 test/http-specs/type/scalargroup/boolean_client_test.go create mode 100644 test/http-specs/type/scalargroup/decimal128type_client_test.go create mode 100644 test/http-specs/type/scalargroup/decimal128verify_client_test.go create mode 100644 test/http-specs/type/scalargroup/decimaltype_client_test.go create mode 100644 test/http-specs/type/scalargroup/decimalverify_client_test.go create mode 100644 test/http-specs/type/scalargroup/fake/zz_internal.go create mode 100644 test/http-specs/type/scalargroup/fake/zz_scalar_server.go create mode 100644 test/http-specs/type/scalargroup/fake/zz_scalarboolean_server.go create mode 100644 test/http-specs/type/scalargroup/fake/zz_scalardecimal128type_server.go create mode 100644 test/http-specs/type/scalargroup/fake/zz_scalardecimal128verify_server.go create mode 100644 test/http-specs/type/scalargroup/fake/zz_scalardecimaltype_server.go create mode 100644 test/http-specs/type/scalargroup/fake/zz_scalardecimalverify_server.go create mode 100644 test/http-specs/type/scalargroup/fake/zz_scalarstring_server.go create mode 100644 test/http-specs/type/scalargroup/fake/zz_scalarunknown_server.go create mode 100644 test/http-specs/type/scalargroup/go.mod create mode 100644 test/http-specs/type/scalargroup/go.sum create mode 100644 test/http-specs/type/scalargroup/string_client_test.go create mode 100644 test/http-specs/type/scalargroup/testdata/_metadata.json create mode 100644 test/http-specs/type/scalargroup/unknown_client_test.go create mode 100644 test/http-specs/type/scalargroup/zz_options.go create mode 100644 test/http-specs/type/scalargroup/zz_responses.go create mode 100644 test/http-specs/type/scalargroup/zz_scalar_client.go create mode 100644 test/http-specs/type/scalargroup/zz_scalarboolean_client.go create mode 100644 test/http-specs/type/scalargroup/zz_scalardecimal128type_client.go create mode 100644 test/http-specs/type/scalargroup/zz_scalardecimal128verify_client.go create mode 100644 test/http-specs/type/scalargroup/zz_scalardecimaltype_client.go create mode 100644 test/http-specs/type/scalargroup/zz_scalardecimalverify_client.go create mode 100644 test/http-specs/type/scalargroup/zz_scalarstring_client.go create mode 100644 test/http-specs/type/scalargroup/zz_scalarunknown_client.go create mode 100644 test/http-specs/type/scalargroup/zz_version.go create mode 100644 test/http-specs/versioning/madeoptionalgroup/LICENSE.txt create mode 100644 test/http-specs/versioning/madeoptionalgroup/fake/zz_internal.go create mode 100644 test/http-specs/versioning/madeoptionalgroup/fake/zz_madeoptional_server.go create mode 100644 test/http-specs/versioning/madeoptionalgroup/go.mod create mode 100644 test/http-specs/versioning/madeoptionalgroup/go.sum create mode 100644 test/http-specs/versioning/madeoptionalgroup/madeoptional_client_test.go create mode 100644 test/http-specs/versioning/madeoptionalgroup/testdata/_metadata.json create mode 100644 test/http-specs/versioning/madeoptionalgroup/zz_madeoptional_client.go create mode 100644 test/http-specs/versioning/madeoptionalgroup/zz_models.go create mode 100644 test/http-specs/versioning/madeoptionalgroup/zz_models_serde.go create mode 100644 test/http-specs/versioning/madeoptionalgroup/zz_options.go create mode 100644 test/http-specs/versioning/madeoptionalgroup/zz_responses.go create mode 100644 test/http-specs/versioning/madeoptionalgroup/zz_version.go create mode 100644 test/http-specs/versioning/rettypechangedfromgroup/LICENSE.txt create mode 100644 test/http-specs/versioning/rettypechangedfromgroup/fake/zz_internal.go create mode 100644 test/http-specs/versioning/rettypechangedfromgroup/fake/zz_returntypechangedfrom_server.go create mode 100644 test/http-specs/versioning/rettypechangedfromgroup/go.mod create mode 100644 test/http-specs/versioning/rettypechangedfromgroup/go.sum create mode 100644 test/http-specs/versioning/rettypechangedfromgroup/returntypechangedfrom_client_test.go create mode 100644 test/http-specs/versioning/rettypechangedfromgroup/testdata/_metadata.json create mode 100644 test/http-specs/versioning/rettypechangedfromgroup/zz_options.go create mode 100644 test/http-specs/versioning/rettypechangedfromgroup/zz_responses.go create mode 100644 test/http-specs/versioning/rettypechangedfromgroup/zz_returntypechangedfrom_client.go create mode 100644 test/http-specs/versioning/rettypechangedfromgroup/zz_version.go create mode 100644 test/http-specs/versioning/typechangedfromgroup/LICENSE.txt create mode 100644 test/http-specs/versioning/typechangedfromgroup/fake/zz_internal.go create mode 100644 test/http-specs/versioning/typechangedfromgroup/fake/zz_typechangedfrom_server.go create mode 100644 test/http-specs/versioning/typechangedfromgroup/go.mod create mode 100644 test/http-specs/versioning/typechangedfromgroup/go.sum create mode 100644 test/http-specs/versioning/typechangedfromgroup/testdata/_metadata.json create mode 100644 test/http-specs/versioning/typechangedfromgroup/typechangedfrom_client_test.go create mode 100644 test/http-specs/versioning/typechangedfromgroup/zz_models.go create mode 100644 test/http-specs/versioning/typechangedfromgroup/zz_models_serde.go create mode 100644 test/http-specs/versioning/typechangedfromgroup/zz_options.go create mode 100644 test/http-specs/versioning/typechangedfromgroup/zz_responses.go create mode 100644 test/http-specs/versioning/typechangedfromgroup/zz_typechangedfrom_client.go create mode 100644 test/http-specs/versioning/typechangedfromgroup/zz_version.go create mode 100644 test/local/armapicenter/LICENSE.txt create mode 100644 test/local/armapicenter/fake/zz_apidefinitions_server.go create mode 100644 test/local/armapicenter/fake/zz_apis_server.go create mode 100644 test/local/armapicenter/fake/zz_apisources_server.go create mode 100644 test/local/armapicenter/fake/zz_apiversions_server.go create mode 100644 test/local/armapicenter/fake/zz_deletedservices_server.go create mode 100644 test/local/armapicenter/fake/zz_deployments_server.go create mode 100644 test/local/armapicenter/fake/zz_environments_server.go create mode 100644 test/local/armapicenter/fake/zz_internal.go create mode 100644 test/local/armapicenter/fake/zz_metadataschemas_server.go create mode 100644 test/local/armapicenter/fake/zz_operations_server.go create mode 100644 test/local/armapicenter/fake/zz_server_factory.go create mode 100644 test/local/armapicenter/fake/zz_services_server.go create mode 100644 test/local/armapicenter/fake/zz_workspaces_server.go create mode 100644 test/local/armapicenter/go.mod create mode 100644 test/local/armapicenter/go.sum create mode 100644 test/local/armapicenter/testdata/_metadata.json create mode 100644 test/local/armapicenter/zz_apidefinitions_client.go create mode 100644 test/local/armapicenter/zz_apis_client.go create mode 100644 test/local/armapicenter/zz_apisources_client.go create mode 100644 test/local/armapicenter/zz_apiversions_client.go create mode 100644 test/local/armapicenter/zz_client_factory.go create mode 100644 test/local/armapicenter/zz_constants.go create mode 100644 test/local/armapicenter/zz_deletedservices_client.go create mode 100644 test/local/armapicenter/zz_deployments_client.go create mode 100644 test/local/armapicenter/zz_environments_client.go create mode 100644 test/local/armapicenter/zz_metadataschemas_client.go create mode 100644 test/local/armapicenter/zz_models.go create mode 100644 test/local/armapicenter/zz_models_serde.go create mode 100644 test/local/armapicenter/zz_operations_client.go create mode 100644 test/local/armapicenter/zz_options.go create mode 100644 test/local/armapicenter/zz_responses.go create mode 100644 test/local/armapicenter/zz_services_client.go create mode 100644 test/local/armapicenter/zz_version.go create mode 100644 test/local/armapicenter/zz_workspaces_client.go create mode 100644 test/local/armbillingbenefits/LICENSE.txt create mode 100644 test/local/armbillingbenefits/fake/zz_applicablemaccs_server.go create mode 100644 test/local/armbillingbenefits/fake/zz_conditionalcreditcontributors_server.go create mode 100644 test/local/armbillingbenefits/fake/zz_conditionalcredits_server.go create mode 100644 test/local/armbillingbenefits/fake/zz_contributors_server.go create mode 100644 test/local/armbillingbenefits/fake/zz_credits_server.go create mode 100644 test/local/armbillingbenefits/fake/zz_discount_server.go create mode 100644 test/local/armbillingbenefits/fake/zz_discounts_server.go create mode 100644 test/local/armbillingbenefits/fake/zz_freeservices_server.go create mode 100644 test/local/armbillingbenefits/fake/zz_internal.go create mode 100644 test/local/armbillingbenefits/fake/zz_maccs_server.go create mode 100644 test/local/armbillingbenefits/fake/zz_operations_server.go create mode 100644 test/local/armbillingbenefits/fake/zz_reservationorderalias_server.go create mode 100644 test/local/armbillingbenefits/fake/zz_rp_server.go create mode 100644 test/local/armbillingbenefits/fake/zz_savingsplan_server.go create mode 100644 test/local/armbillingbenefits/fake/zz_savingsplanorder_server.go create mode 100644 test/local/armbillingbenefits/fake/zz_savingsplanorderalias_server.go create mode 100644 test/local/armbillingbenefits/fake/zz_sellerresource_server.go create mode 100644 test/local/armbillingbenefits/fake/zz_server_factory.go create mode 100644 test/local/armbillingbenefits/fake/zz_sources_server.go create mode 100644 test/local/armbillingbenefits/go.mod create mode 100644 test/local/armbillingbenefits/go.sum create mode 100644 test/local/armbillingbenefits/testdata/_metadata.json create mode 100644 test/local/armbillingbenefits/zz_applicablemaccs_client.go create mode 100644 test/local/armbillingbenefits/zz_client_factory.go create mode 100644 test/local/armbillingbenefits/zz_conditionalcreditcontributors_client.go create mode 100644 test/local/armbillingbenefits/zz_conditionalcredits_client.go create mode 100644 test/local/armbillingbenefits/zz_constants.go create mode 100644 test/local/armbillingbenefits/zz_contributors_client.go create mode 100644 test/local/armbillingbenefits/zz_credits_client.go create mode 100644 test/local/armbillingbenefits/zz_discount_client.go create mode 100644 test/local/armbillingbenefits/zz_discounts_client.go create mode 100644 test/local/armbillingbenefits/zz_freeservices_client.go create mode 100644 test/local/armbillingbenefits/zz_interfaces.go create mode 100644 test/local/armbillingbenefits/zz_maccs_client.go create mode 100644 test/local/armbillingbenefits/zz_models.go create mode 100644 test/local/armbillingbenefits/zz_models_serde.go create mode 100644 test/local/armbillingbenefits/zz_operations_client.go create mode 100644 test/local/armbillingbenefits/zz_options.go create mode 100644 test/local/armbillingbenefits/zz_polymorphic_helpers.go create mode 100644 test/local/armbillingbenefits/zz_reservationorderalias_client.go create mode 100644 test/local/armbillingbenefits/zz_responses.go create mode 100644 test/local/armbillingbenefits/zz_rp_client.go create mode 100644 test/local/armbillingbenefits/zz_savingsplan_client.go create mode 100644 test/local/armbillingbenefits/zz_savingsplanorder_client.go create mode 100644 test/local/armbillingbenefits/zz_savingsplanorderalias_client.go create mode 100644 test/local/armbillingbenefits/zz_sellerresource_client.go create mode 100644 test/local/armbillingbenefits/zz_sources_client.go create mode 100644 test/local/armbillingbenefits/zz_version.go create mode 100644 test/local/armcodesigning/LICENSE.txt create mode 100644 test/local/armcodesigning/fake/zz_accounts_server.go create mode 100644 test/local/armcodesigning/fake/zz_certificateprofiles_server.go create mode 100644 test/local/armcodesigning/fake/zz_internal.go create mode 100644 test/local/armcodesigning/fake/zz_operations_server.go create mode 100644 test/local/armcodesigning/fake/zz_server_factory.go create mode 100644 test/local/armcodesigning/go.mod create mode 100644 test/local/armcodesigning/go.sum create mode 100644 test/local/armcodesigning/testdata/_metadata.json create mode 100644 test/local/armcodesigning/zz_accounts_client.go create mode 100644 test/local/armcodesigning/zz_certificateprofiles_client.go create mode 100644 test/local/armcodesigning/zz_client_factory.go create mode 100644 test/local/armcodesigning/zz_constants.go create mode 100644 test/local/armcodesigning/zz_models.go create mode 100644 test/local/armcodesigning/zz_models_serde.go create mode 100644 test/local/armcodesigning/zz_operations_client.go create mode 100644 test/local/armcodesigning/zz_options.go create mode 100644 test/local/armcodesigning/zz_responses.go create mode 100644 test/local/armcodesigning/zz_version.go create mode 100644 test/local/armcognitiveservices/LICENSE.txt create mode 100644 test/local/armcognitiveservices/fake/zz_accountcapabilityhosts_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_accountconnections_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_accounts_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_agentapplications_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_agentdeployments_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_commitmentplans_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_commitmenttiers_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_defenderforaisettings_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_deletedaccounts_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_deployments_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_encryptionscopes_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_internal.go create mode 100644 test/local/armcognitiveservices/fake/zz_locationbasedmodelcapacities_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_managednetworkprovisions_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_managednetworksettings_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_management_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_modelcapacities_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_models_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_networksecurityperimeterconfigurations_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_operations_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_outboundrule_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_outboundrules_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_privateendpointconnections_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_privatelinkresources_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_projectcapabilityhosts_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_projectconnections_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_projects_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_quotatiers_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_raiblocklistitems_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_raiblocklists_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_raicontentfilters_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_raiexternalsafetyprovider_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_raiexternalsafetyproviders_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_raipolicies_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_raitoollabels_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_raitopics_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_resourceskus_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_server_factory.go create mode 100644 test/local/armcognitiveservices/fake/zz_subscriptionraipolicy_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_testraiexternalsafetyprovider_server.go create mode 100644 test/local/armcognitiveservices/fake/zz_usages_server.go create mode 100644 test/local/armcognitiveservices/go.mod create mode 100644 test/local/armcognitiveservices/go.sum create mode 100644 test/local/armcognitiveservices/testdata/_metadata.json create mode 100644 test/local/armcognitiveservices/zz_accountcapabilityhosts_client.go create mode 100644 test/local/armcognitiveservices/zz_accountconnections_client.go create mode 100644 test/local/armcognitiveservices/zz_accounts_client.go create mode 100644 test/local/armcognitiveservices/zz_agentapplications_client.go create mode 100644 test/local/armcognitiveservices/zz_agentdeployments_client.go create mode 100644 test/local/armcognitiveservices/zz_client_factory.go create mode 100644 test/local/armcognitiveservices/zz_commitmentplans_client.go create mode 100644 test/local/armcognitiveservices/zz_commitmenttiers_client.go create mode 100644 test/local/armcognitiveservices/zz_constants.go create mode 100644 test/local/armcognitiveservices/zz_defenderforaisettings_client.go create mode 100644 test/local/armcognitiveservices/zz_deletedaccounts_client.go create mode 100644 test/local/armcognitiveservices/zz_deployments_client.go create mode 100644 test/local/armcognitiveservices/zz_encryptionscopes_client.go create mode 100644 test/local/armcognitiveservices/zz_interfaces.go create mode 100644 test/local/armcognitiveservices/zz_locationbasedmodelcapacities_client.go create mode 100644 test/local/armcognitiveservices/zz_managednetworkprovisions_client.go create mode 100644 test/local/armcognitiveservices/zz_managednetworksettings_client.go create mode 100644 test/local/armcognitiveservices/zz_management_client.go create mode 100644 test/local/armcognitiveservices/zz_modelcapacities_client.go create mode 100644 test/local/armcognitiveservices/zz_models.go create mode 100644 test/local/armcognitiveservices/zz_models_client.go create mode 100644 test/local/armcognitiveservices/zz_models_serde.go create mode 100644 test/local/armcognitiveservices/zz_networksecurityperimeterconfigurations_client.go create mode 100644 test/local/armcognitiveservices/zz_operations_client.go create mode 100644 test/local/armcognitiveservices/zz_options.go create mode 100644 test/local/armcognitiveservices/zz_outboundrule_client.go create mode 100644 test/local/armcognitiveservices/zz_outboundrules_client.go create mode 100644 test/local/armcognitiveservices/zz_polymorphic_helpers.go create mode 100644 test/local/armcognitiveservices/zz_privateendpointconnections_client.go create mode 100644 test/local/armcognitiveservices/zz_privatelinkresources_client.go create mode 100644 test/local/armcognitiveservices/zz_projectcapabilityhosts_client.go create mode 100644 test/local/armcognitiveservices/zz_projectconnections_client.go create mode 100644 test/local/armcognitiveservices/zz_projects_client.go create mode 100644 test/local/armcognitiveservices/zz_quotatiers_client.go create mode 100644 test/local/armcognitiveservices/zz_raiblocklistitems_client.go create mode 100644 test/local/armcognitiveservices/zz_raiblocklists_client.go create mode 100644 test/local/armcognitiveservices/zz_raicontentfilters_client.go create mode 100644 test/local/armcognitiveservices/zz_raiexternalsafetyprovider_client.go create mode 100644 test/local/armcognitiveservices/zz_raiexternalsafetyproviders_client.go create mode 100644 test/local/armcognitiveservices/zz_raipolicies_client.go create mode 100644 test/local/armcognitiveservices/zz_raitoollabels_client.go create mode 100644 test/local/armcognitiveservices/zz_raitopics_client.go create mode 100644 test/local/armcognitiveservices/zz_resourceskus_client.go create mode 100644 test/local/armcognitiveservices/zz_responses.go create mode 100644 test/local/armcognitiveservices/zz_subscriptionraipolicy_client.go create mode 100644 test/local/armcognitiveservices/zz_testraiexternalsafetyprovider_client.go create mode 100644 test/local/armcognitiveservices/zz_usages_client.go create mode 100644 test/local/armcognitiveservices/zz_version.go create mode 100644 test/local/armcommunitymanagement/LICENSE.txt create mode 100644 test/local/armcommunitymanagement/fake/zz_communitytrainings_server.go create mode 100644 test/local/armcommunitymanagement/fake/zz_internal.go create mode 100644 test/local/armcommunitymanagement/fake/zz_operations_server.go create mode 100644 test/local/armcommunitymanagement/fake/zz_server_factory.go create mode 100644 test/local/armcommunitymanagement/go.mod create mode 100644 test/local/armcommunitymanagement/go.sum create mode 100644 test/local/armcommunitymanagement/testdata/_metadata.json create mode 100644 test/local/armcommunitymanagement/zz_client_factory.go create mode 100644 test/local/armcommunitymanagement/zz_communitytrainings_client.go create mode 100644 test/local/armcommunitymanagement/zz_constants.go create mode 100644 test/local/armcommunitymanagement/zz_models.go create mode 100644 test/local/armcommunitymanagement/zz_models_serde.go create mode 100644 test/local/armcommunitymanagement/zz_operations_client.go create mode 100644 test/local/armcommunitymanagement/zz_options.go create mode 100644 test/local/armcommunitymanagement/zz_responses.go create mode 100644 test/local/armcommunitymanagement/zz_version.go create mode 100644 test/local/armcomputeschedule/LICENSE.txt create mode 100644 test/local/armcomputeschedule/fake/zz_internal.go create mode 100644 test/local/armcomputeschedule/fake/zz_occurrenceextension_server.go create mode 100644 test/local/armcomputeschedule/fake/zz_occurrences_server.go create mode 100644 test/local/armcomputeschedule/fake/zz_operations_server.go create mode 100644 test/local/armcomputeschedule/fake/zz_scheduledactionextension_server.go create mode 100644 test/local/armcomputeschedule/fake/zz_scheduledactions_server.go create mode 100644 test/local/armcomputeschedule/fake/zz_server_factory.go create mode 100644 test/local/armcomputeschedule/go.mod create mode 100644 test/local/armcomputeschedule/go.sum create mode 100644 test/local/armcomputeschedule/testdata/_metadata.json create mode 100644 test/local/armcomputeschedule/zz_client_factory.go create mode 100644 test/local/armcomputeschedule/zz_constants.go create mode 100644 test/local/armcomputeschedule/zz_models.go create mode 100644 test/local/armcomputeschedule/zz_models_serde.go create mode 100644 test/local/armcomputeschedule/zz_occurrenceextension_client.go create mode 100644 test/local/armcomputeschedule/zz_occurrences_client.go create mode 100644 test/local/armcomputeschedule/zz_operations_client.go create mode 100644 test/local/armcomputeschedule/zz_options.go create mode 100644 test/local/armcomputeschedule/zz_responses.go create mode 100644 test/local/armcomputeschedule/zz_scheduledactionextension_client.go create mode 100644 test/local/armcomputeschedule/zz_scheduledactions_client.go create mode 100644 test/local/armcomputeschedule/zz_version.go create mode 100644 test/local/armcontainerorchestratorruntime/LICENSE.txt create mode 100644 test/local/armcontainerorchestratorruntime/fake/zz_bgppeers_server.go create mode 100644 test/local/armcontainerorchestratorruntime/fake/zz_internal.go create mode 100644 test/local/armcontainerorchestratorruntime/fake/zz_loadbalancers_server.go create mode 100644 test/local/armcontainerorchestratorruntime/fake/zz_operations_server.go create mode 100644 test/local/armcontainerorchestratorruntime/fake/zz_server_factory.go create mode 100644 test/local/armcontainerorchestratorruntime/fake/zz_services_server.go create mode 100644 test/local/armcontainerorchestratorruntime/fake/zz_storageclass_server.go create mode 100644 test/local/armcontainerorchestratorruntime/go.mod create mode 100644 test/local/armcontainerorchestratorruntime/go.sum create mode 100644 test/local/armcontainerorchestratorruntime/testdata/_metadata.json create mode 100644 test/local/armcontainerorchestratorruntime/zz_bgppeers_client.go create mode 100644 test/local/armcontainerorchestratorruntime/zz_client_factory.go create mode 100644 test/local/armcontainerorchestratorruntime/zz_constants.go create mode 100644 test/local/armcontainerorchestratorruntime/zz_interfaces.go create mode 100644 test/local/armcontainerorchestratorruntime/zz_loadbalancers_client.go create mode 100644 test/local/armcontainerorchestratorruntime/zz_models.go create mode 100644 test/local/armcontainerorchestratorruntime/zz_models_serde.go create mode 100644 test/local/armcontainerorchestratorruntime/zz_operations_client.go create mode 100644 test/local/armcontainerorchestratorruntime/zz_options.go create mode 100644 test/local/armcontainerorchestratorruntime/zz_polymorphic_helpers.go create mode 100644 test/local/armcontainerorchestratorruntime/zz_responses.go create mode 100644 test/local/armcontainerorchestratorruntime/zz_services_client.go create mode 100644 test/local/armcontainerorchestratorruntime/zz_storageclass_client.go create mode 100644 test/local/armcontainerorchestratorruntime/zz_version.go create mode 100644 test/local/armdatabasewatcher/LICENSE.txt create mode 100644 test/local/armdatabasewatcher/fake/zz_alertruleresources_server.go create mode 100644 test/local/armdatabasewatcher/fake/zz_healthvalidations_server.go create mode 100644 test/local/armdatabasewatcher/fake/zz_internal.go create mode 100644 test/local/armdatabasewatcher/fake/zz_operations_server.go create mode 100644 test/local/armdatabasewatcher/fake/zz_server_factory.go create mode 100644 test/local/armdatabasewatcher/fake/zz_sharedprivatelinkresources_server.go create mode 100644 test/local/armdatabasewatcher/fake/zz_targets_server.go create mode 100644 test/local/armdatabasewatcher/fake/zz_watchers_server.go create mode 100644 test/local/armdatabasewatcher/go.mod create mode 100644 test/local/armdatabasewatcher/go.sum create mode 100644 test/local/armdatabasewatcher/testdata/_metadata.json create mode 100644 test/local/armdatabasewatcher/zz_alertruleresources_client.go create mode 100644 test/local/armdatabasewatcher/zz_client_factory.go create mode 100644 test/local/armdatabasewatcher/zz_constants.go create mode 100644 test/local/armdatabasewatcher/zz_healthvalidations_client.go create mode 100644 test/local/armdatabasewatcher/zz_interfaces.go create mode 100644 test/local/armdatabasewatcher/zz_models.go create mode 100644 test/local/armdatabasewatcher/zz_models_serde.go create mode 100644 test/local/armdatabasewatcher/zz_operations_client.go create mode 100644 test/local/armdatabasewatcher/zz_options.go create mode 100644 test/local/armdatabasewatcher/zz_polymorphic_helpers.go create mode 100644 test/local/armdatabasewatcher/zz_responses.go create mode 100644 test/local/armdatabasewatcher/zz_sharedprivatelinkresources_client.go create mode 100644 test/local/armdatabasewatcher/zz_targets_client.go create mode 100644 test/local/armdatabasewatcher/zz_version.go create mode 100644 test/local/armdatabasewatcher/zz_watchers_client.go create mode 100644 test/local/armdevopsinfrastructure/LICENSE.txt create mode 100644 test/local/armdevopsinfrastructure/fake/zz_imageversions_server.go create mode 100644 test/local/armdevopsinfrastructure/fake/zz_internal.go create mode 100644 test/local/armdevopsinfrastructure/fake/zz_operations_server.go create mode 100644 test/local/armdevopsinfrastructure/fake/zz_pools_server.go create mode 100644 test/local/armdevopsinfrastructure/fake/zz_resourcedetails_server.go create mode 100644 test/local/armdevopsinfrastructure/fake/zz_server_factory.go create mode 100644 test/local/armdevopsinfrastructure/fake/zz_sku_server.go create mode 100644 test/local/armdevopsinfrastructure/fake/zz_subscriptionusages_server.go create mode 100644 test/local/armdevopsinfrastructure/go.mod create mode 100644 test/local/armdevopsinfrastructure/go.sum create mode 100644 test/local/armdevopsinfrastructure/testdata/_metadata.json create mode 100644 test/local/armdevopsinfrastructure/zz_client_factory.go create mode 100644 test/local/armdevopsinfrastructure/zz_constants.go create mode 100644 test/local/armdevopsinfrastructure/zz_imageversions_client.go create mode 100644 test/local/armdevopsinfrastructure/zz_interfaces.go create mode 100644 test/local/armdevopsinfrastructure/zz_models.go create mode 100644 test/local/armdevopsinfrastructure/zz_models_serde.go create mode 100644 test/local/armdevopsinfrastructure/zz_operations_client.go create mode 100644 test/local/armdevopsinfrastructure/zz_options.go create mode 100644 test/local/armdevopsinfrastructure/zz_polymorphic_helpers.go create mode 100644 test/local/armdevopsinfrastructure/zz_pools_client.go create mode 100644 test/local/armdevopsinfrastructure/zz_resourcedetails_client.go create mode 100644 test/local/armdevopsinfrastructure/zz_responses.go create mode 100644 test/local/armdevopsinfrastructure/zz_sku_client.go create mode 100644 test/local/armdevopsinfrastructure/zz_subscriptionusages_client.go create mode 100644 test/local/armdevopsinfrastructure/zz_version.go create mode 100644 test/local/armhardwaresecuritymodules/LICENSE.txt create mode 100644 test/local/armhardwaresecuritymodules/fake/zz_cloudhsmclusterbackupstatus_server.go create mode 100644 test/local/armhardwaresecuritymodules/fake/zz_cloudhsmclusterprivateendpointconnections_server.go create mode 100644 test/local/armhardwaresecuritymodules/fake/zz_cloudhsmclusterprivatelinkresources_server.go create mode 100644 test/local/armhardwaresecuritymodules/fake/zz_cloudhsmclusterrestorestatus_server.go create mode 100644 test/local/armhardwaresecuritymodules/fake/zz_cloudhsmclusters_server.go create mode 100644 test/local/armhardwaresecuritymodules/fake/zz_dedicatedhsm_server.go create mode 100644 test/local/armhardwaresecuritymodules/fake/zz_internal.go create mode 100644 test/local/armhardwaresecuritymodules/fake/zz_operations_server.go create mode 100644 test/local/armhardwaresecuritymodules/fake/zz_privateendpointconnections_server.go create mode 100644 test/local/armhardwaresecuritymodules/fake/zz_server_factory.go create mode 100644 test/local/armhardwaresecuritymodules/go.mod create mode 100644 test/local/armhardwaresecuritymodules/go.sum create mode 100644 test/local/armhardwaresecuritymodules/testdata/_metadata.json create mode 100644 test/local/armhardwaresecuritymodules/zz_client_factory.go create mode 100644 test/local/armhardwaresecuritymodules/zz_cloudhsmclusterbackupstatus_client.go create mode 100644 test/local/armhardwaresecuritymodules/zz_cloudhsmclusterprivateendpointconnections_client.go create mode 100644 test/local/armhardwaresecuritymodules/zz_cloudhsmclusterprivatelinkresources_client.go create mode 100644 test/local/armhardwaresecuritymodules/zz_cloudhsmclusterrestorestatus_client.go create mode 100644 test/local/armhardwaresecuritymodules/zz_cloudhsmclusters_client.go create mode 100644 test/local/armhardwaresecuritymodules/zz_constants.go create mode 100644 test/local/armhardwaresecuritymodules/zz_dedicatedhsm_client.go create mode 100644 test/local/armhardwaresecuritymodules/zz_models.go create mode 100644 test/local/armhardwaresecuritymodules/zz_models_serde.go create mode 100644 test/local/armhardwaresecuritymodules/zz_operations_client.go create mode 100644 test/local/armhardwaresecuritymodules/zz_options.go create mode 100644 test/local/armhardwaresecuritymodules/zz_privateendpointconnections_client.go create mode 100644 test/local/armhardwaresecuritymodules/zz_responses.go create mode 100644 test/local/armhardwaresecuritymodules/zz_version.go create mode 100644 test/local/armhealthbot/LICENSE.txt create mode 100644 test/local/armhealthbot/fake/zz_bots_server.go create mode 100644 test/local/armhealthbot/fake/zz_internal.go create mode 100644 test/local/armhealthbot/fake/zz_operations_server.go create mode 100644 test/local/armhealthbot/fake/zz_server_factory.go create mode 100644 test/local/armhealthbot/go.mod create mode 100644 test/local/armhealthbot/go.sum create mode 100644 test/local/armhealthbot/testdata/_metadata.json create mode 100644 test/local/armhealthbot/zz_bots_client.go create mode 100644 test/local/armhealthbot/zz_client_factory.go create mode 100644 test/local/armhealthbot/zz_constants.go create mode 100644 test/local/armhealthbot/zz_models.go create mode 100644 test/local/armhealthbot/zz_models_serde.go create mode 100644 test/local/armhealthbot/zz_operations_client.go create mode 100644 test/local/armhealthbot/zz_options.go create mode 100644 test/local/armhealthbot/zz_responses.go create mode 100644 test/local/armhealthbot/zz_version.go create mode 100644 test/local/armlargeinstance/LICENSE.txt create mode 100644 test/local/armlargeinstance/fake/zz_azurelargestorageinstance_server.go create mode 100644 test/local/armlargeinstance/fake/zz_internal.go create mode 100644 test/local/armlargeinstance/fake/zz_operations_server.go create mode 100644 test/local/armlargeinstance/fake/zz_server.go create mode 100644 test/local/armlargeinstance/fake/zz_server_factory.go create mode 100644 test/local/armlargeinstance/go.mod create mode 100644 test/local/armlargeinstance/go.sum create mode 100644 test/local/armlargeinstance/testdata/_metadata.json create mode 100644 test/local/armlargeinstance/zz_azurelargestorageinstance_client.go create mode 100644 test/local/armlargeinstance/zz_client.go create mode 100644 test/local/armlargeinstance/zz_client_factory.go create mode 100644 test/local/armlargeinstance/zz_constants.go create mode 100644 test/local/armlargeinstance/zz_models.go create mode 100644 test/local/armlargeinstance/zz_models_serde.go create mode 100644 test/local/armlargeinstance/zz_operations_client.go create mode 100644 test/local/armlargeinstance/zz_options.go create mode 100644 test/local/armlargeinstance/zz_responses.go create mode 100644 test/local/armlargeinstance/zz_version.go create mode 100644 test/local/armloadtestservice/LICENSE.txt create mode 100644 test/local/armloadtestservice/fake/zz_internal.go create mode 100644 test/local/armloadtestservice/fake/zz_loadtestmappings_server.go create mode 100644 test/local/armloadtestservice/fake/zz_loadtestprofilemappings_server.go create mode 100644 test/local/armloadtestservice/fake/zz_loadtests_server.go create mode 100644 test/local/armloadtestservice/fake/zz_loadtestsmaxmonthlyvirtualuserhourslimitsresource_server.go create mode 100644 test/local/armloadtestservice/fake/zz_operations_server.go create mode 100644 test/local/armloadtestservice/fake/zz_quotas_server.go create mode 100644 test/local/armloadtestservice/fake/zz_server_factory.go create mode 100644 test/local/armloadtestservice/go.mod create mode 100644 test/local/armloadtestservice/go.sum create mode 100644 test/local/armloadtestservice/testdata/_metadata.json create mode 100644 test/local/armloadtestservice/zz_client_factory.go create mode 100644 test/local/armloadtestservice/zz_constants.go create mode 100644 test/local/armloadtestservice/zz_loadtestmappings_client.go create mode 100644 test/local/armloadtestservice/zz_loadtestprofilemappings_client.go create mode 100644 test/local/armloadtestservice/zz_loadtests_client.go create mode 100644 test/local/armloadtestservice/zz_loadtestsmaxmonthlyvirtualuserhourslimitsresource_client.go create mode 100644 test/local/armloadtestservice/zz_models.go create mode 100644 test/local/armloadtestservice/zz_models_serde.go create mode 100644 test/local/armloadtestservice/zz_operations_client.go create mode 100644 test/local/armloadtestservice/zz_options.go create mode 100644 test/local/armloadtestservice/zz_quotas_client.go create mode 100644 test/local/armloadtestservice/zz_responses.go create mode 100644 test/local/armloadtestservice/zz_version.go create mode 100644 test/local/armmongocluster/LICENSE.txt create mode 100644 test/local/armmongocluster/fake/zz_firewallrules_server.go create mode 100644 test/local/armmongocluster/fake/zz_internal.go create mode 100644 test/local/armmongocluster/fake/zz_mongoclusters_server.go create mode 100644 test/local/armmongocluster/fake/zz_operations_server.go create mode 100644 test/local/armmongocluster/fake/zz_privateendpointconnections_server.go create mode 100644 test/local/armmongocluster/fake/zz_privatelinks_server.go create mode 100644 test/local/armmongocluster/fake/zz_replicas_server.go create mode 100644 test/local/armmongocluster/fake/zz_server_factory.go create mode 100644 test/local/armmongocluster/fake/zz_users_server.go create mode 100644 test/local/armmongocluster/go.mod create mode 100644 test/local/armmongocluster/go.sum create mode 100644 test/local/armmongocluster/testdata/_metadata.json create mode 100644 test/local/armmongocluster/zz_client_factory.go create mode 100644 test/local/armmongocluster/zz_constants.go create mode 100644 test/local/armmongocluster/zz_firewallrules_client.go create mode 100644 test/local/armmongocluster/zz_interfaces.go create mode 100644 test/local/armmongocluster/zz_models.go create mode 100644 test/local/armmongocluster/zz_models_serde.go create mode 100644 test/local/armmongocluster/zz_mongoclusters_client.go create mode 100644 test/local/armmongocluster/zz_operations_client.go create mode 100644 test/local/armmongocluster/zz_options.go create mode 100644 test/local/armmongocluster/zz_polymorphic_helpers.go create mode 100644 test/local/armmongocluster/zz_privateendpointconnections_client.go create mode 100644 test/local/armmongocluster/zz_privatelinks_client.go create mode 100644 test/local/armmongocluster/zz_replicas_client.go create mode 100644 test/local/armmongocluster/zz_responses.go create mode 100644 test/local/armmongocluster/zz_users_client.go create mode 100644 test/local/armmongocluster/zz_version.go create mode 100644 test/local/armoracledatabase/LICENSE.txt create mode 100644 test/local/armoracledatabase/fake/zz_autonomousdatabasebackups_server.go create mode 100644 test/local/armoracledatabase/fake/zz_autonomousdatabasecharactersets_server.go create mode 100644 test/local/armoracledatabase/fake/zz_autonomousdatabasenationalcharactersets_server.go create mode 100644 test/local/armoracledatabase/fake/zz_autonomousdatabases_server.go create mode 100644 test/local/armoracledatabase/fake/zz_autonomousdatabaseversions_server.go create mode 100644 test/local/armoracledatabase/fake/zz_cloudexadatainfrastructures_server.go create mode 100644 test/local/armoracledatabase/fake/zz_cloudvmclusters_server.go create mode 100644 test/local/armoracledatabase/fake/zz_dbnodes_server.go create mode 100644 test/local/armoracledatabase/fake/zz_dbservers_server.go create mode 100644 test/local/armoracledatabase/fake/zz_dbsystems_server.go create mode 100644 test/local/armoracledatabase/fake/zz_dbsystemshapes_server.go create mode 100644 test/local/armoracledatabase/fake/zz_dbversions_server.go create mode 100644 test/local/armoracledatabase/fake/zz_dnsprivateviews_server.go create mode 100644 test/local/armoracledatabase/fake/zz_dnsprivatezones_server.go create mode 100644 test/local/armoracledatabase/fake/zz_exadbvmclusters_server.go create mode 100644 test/local/armoracledatabase/fake/zz_exascaledbnodes_server.go create mode 100644 test/local/armoracledatabase/fake/zz_exascaledbstoragevaults_server.go create mode 100644 test/local/armoracledatabase/fake/zz_flexcomponents_server.go create mode 100644 test/local/armoracledatabase/fake/zz_giminorversions_server.go create mode 100644 test/local/armoracledatabase/fake/zz_giversions_server.go create mode 100644 test/local/armoracledatabase/fake/zz_internal.go create mode 100644 test/local/armoracledatabase/fake/zz_networkanchors_server.go create mode 100644 test/local/armoracledatabase/fake/zz_operations_server.go create mode 100644 test/local/armoracledatabase/fake/zz_oraclesubscriptions_server.go create mode 100644 test/local/armoracledatabase/fake/zz_resourceanchors_server.go create mode 100644 test/local/armoracledatabase/fake/zz_server_factory.go create mode 100644 test/local/armoracledatabase/fake/zz_systemversions_server.go create mode 100644 test/local/armoracledatabase/fake/zz_virtualnetworkaddresses_server.go create mode 100644 test/local/armoracledatabase/go.mod create mode 100644 test/local/armoracledatabase/go.sum create mode 100644 test/local/armoracledatabase/testdata/_metadata.json create mode 100644 test/local/armoracledatabase/zz_autonomousdatabasebackups_client.go create mode 100644 test/local/armoracledatabase/zz_autonomousdatabasecharactersets_client.go create mode 100644 test/local/armoracledatabase/zz_autonomousdatabasenationalcharactersets_client.go create mode 100644 test/local/armoracledatabase/zz_autonomousdatabases_client.go create mode 100644 test/local/armoracledatabase/zz_autonomousdatabaseversions_client.go create mode 100644 test/local/armoracledatabase/zz_client_factory.go create mode 100644 test/local/armoracledatabase/zz_cloudexadatainfrastructures_client.go create mode 100644 test/local/armoracledatabase/zz_cloudvmclusters_client.go create mode 100644 test/local/armoracledatabase/zz_constants.go create mode 100644 test/local/armoracledatabase/zz_dbnodes_client.go create mode 100644 test/local/armoracledatabase/zz_dbservers_client.go create mode 100644 test/local/armoracledatabase/zz_dbsystems_client.go create mode 100644 test/local/armoracledatabase/zz_dbsystemshapes_client.go create mode 100644 test/local/armoracledatabase/zz_dbversions_client.go create mode 100644 test/local/armoracledatabase/zz_dnsprivateviews_client.go create mode 100644 test/local/armoracledatabase/zz_dnsprivatezones_client.go create mode 100644 test/local/armoracledatabase/zz_exadbvmclusters_client.go create mode 100644 test/local/armoracledatabase/zz_exascaledbnodes_client.go create mode 100644 test/local/armoracledatabase/zz_exascaledbstoragevaults_client.go create mode 100644 test/local/armoracledatabase/zz_flexcomponents_client.go create mode 100644 test/local/armoracledatabase/zz_giminorversions_client.go create mode 100644 test/local/armoracledatabase/zz_giversions_client.go create mode 100644 test/local/armoracledatabase/zz_interfaces.go create mode 100644 test/local/armoracledatabase/zz_models.go create mode 100644 test/local/armoracledatabase/zz_models_serde.go create mode 100644 test/local/armoracledatabase/zz_networkanchors_client.go create mode 100644 test/local/armoracledatabase/zz_operations_client.go create mode 100644 test/local/armoracledatabase/zz_options.go create mode 100644 test/local/armoracledatabase/zz_oraclesubscriptions_client.go create mode 100644 test/local/armoracledatabase/zz_polymorphic_helpers.go create mode 100644 test/local/armoracledatabase/zz_resourceanchors_client.go create mode 100644 test/local/armoracledatabase/zz_responses.go create mode 100644 test/local/armoracledatabase/zz_systemversions_client.go create mode 100644 test/local/armoracledatabase/zz_version.go create mode 100644 test/local/armoracledatabase/zz_virtualnetworkaddresses_client.go create mode 100644 test/local/armpageablelros/LICENSE.txt create mode 100644 test/local/armpageablelros/fake/zz_internal.go create mode 100644 test/local/armpageablelros/fake/zz_server.go create mode 100644 test/local/armpageablelros/fake/zz_server_factory.go create mode 100644 test/local/armpageablelros/go.mod create mode 100644 test/local/armpageablelros/go.sum create mode 100644 test/local/armpageablelros/testdata/_metadata.json create mode 100644 test/local/armpageablelros/zz_client.go create mode 100644 test/local/armpageablelros/zz_client_factory.go create mode 100644 test/local/armpageablelros/zz_models.go create mode 100644 test/local/armpageablelros/zz_models_serde.go create mode 100644 test/local/armpageablelros/zz_options.go create mode 100644 test/local/armpageablelros/zz_responses.go create mode 100644 test/local/armpageablelros/zz_version.go create mode 100644 test/local/armrandom/LICENSE.txt create mode 100644 test/local/armrandom/fake/zz_internal.go create mode 100644 test/local/armrandom/fake/zz_server.go create mode 100644 test/local/armrandom/fake/zz_server_factory.go create mode 100644 test/local/armrandom/fake/zz_someservice_server.go create mode 100644 test/local/armrandom/go.mod create mode 100644 test/local/armrandom/go.sum create mode 100644 test/local/armrandom/testdata/_metadata.json create mode 100644 test/local/armrandom/zz_client.go create mode 100644 test/local/armrandom/zz_client_factory.go create mode 100644 test/local/armrandom/zz_constants.go create mode 100644 test/local/armrandom/zz_models.go create mode 100644 test/local/armrandom/zz_models_serde.go create mode 100644 test/local/armrandom/zz_options.go create mode 100644 test/local/armrandom/zz_responses.go create mode 100644 test/local/armrandom/zz_someservice_client.go create mode 100644 test/local/armrandom/zz_version.go create mode 100644 test/local/armtest/LICENSE.txt create mode 100644 test/local/armtest/fake/zz_authorization_server.go create mode 100644 test/local/armtest/fake/zz_authorizationserver_server.go create mode 100644 test/local/armtest/fake/zz_bodyroots_server.go create mode 100644 test/local/armtest/fake/zz_configurations_server.go create mode 100644 test/local/armtest/fake/zz_internal.go create mode 100644 test/local/armtest/fake/zz_lro_server.go create mode 100644 test/local/armtest/fake/zz_mixedscopewidgets_server.go create mode 100644 test/local/armtest/fake/zz_parametergroupoperations_server.go create mode 100644 test/local/armtest/fake/zz_pets_server.go create mode 100644 test/local/armtest/fake/zz_polymorphic_helpers.go create mode 100644 test/local/armtest/fake/zz_server_factory.go create mode 100644 test/local/armtest/fake/zz_tenantitems_server.go create mode 100644 test/local/armtest/go.mod create mode 100644 test/local/armtest/go.sum create mode 100644 test/local/armtest/testdata/_metadata.json create mode 100644 test/local/armtest/zz_authorization_client.go create mode 100644 test/local/armtest/zz_authorizationserver_client.go create mode 100644 test/local/armtest/zz_bodyroots_client.go create mode 100644 test/local/armtest/zz_client_factory.go create mode 100644 test/local/armtest/zz_configurations_client.go create mode 100644 test/local/armtest/zz_constants.go create mode 100644 test/local/armtest/zz_interfaces.go create mode 100644 test/local/armtest/zz_lro_client.go create mode 100644 test/local/armtest/zz_mixedscopewidgets_client.go create mode 100644 test/local/armtest/zz_models.go create mode 100644 test/local/armtest/zz_models_serde.go create mode 100644 test/local/armtest/zz_options.go create mode 100644 test/local/armtest/zz_parametergroupoperations_client.go create mode 100644 test/local/armtest/zz_pets_client.go create mode 100644 test/local/armtest/zz_polymorphic_helpers.go create mode 100644 test/local/armtest/zz_responses.go create mode 100644 test/local/armtest/zz_responses_serde.go create mode 100644 test/local/armtest/zz_tenantitems_client.go create mode 100644 test/local/armtest/zz_version.go create mode 100644 test/local/azblob/LICENSE.txt create mode 100644 test/local/azblob/client.go create mode 100644 test/local/azblob/go.mod create mode 100644 test/local/azblob/go.sum create mode 100644 test/local/azblob/models_serde_test.go create mode 100644 test/local/azblob/testdata/_metadata.json create mode 100644 test/local/azblob/zz_appendblob_client.go create mode 100644 test/local/azblob/zz_blockblob_client.go create mode 100644 test/local/azblob/zz_client.go create mode 100644 test/local/azblob/zz_constants.go create mode 100644 test/local/azblob/zz_container_client.go create mode 100644 test/local/azblob/zz_models.go create mode 100644 test/local/azblob/zz_models_serde.go create mode 100644 test/local/azblob/zz_options.go create mode 100644 test/local/azblob/zz_pageblob_client.go create mode 100644 test/local/azblob/zz_responses.go create mode 100644 test/local/azblob/zz_service_client.go create mode 100644 test/local/azblob/zz_version.go create mode 100644 test/local/azblob/zz_xml_helper.go create mode 100644 test/local/azclientoption/LICENSE.txt create mode 100644 test/local/azclientoption/fake/zz_internal.go create mode 100644 test/local/azclientoption/fake/zz_server.go create mode 100644 test/local/azclientoption/go.mod create mode 100644 test/local/azclientoption/go.sum create mode 100644 test/local/azclientoption/testdata/_metadata.json create mode 100644 test/local/azclientoption/zz_client.go create mode 100644 test/local/azclientoption/zz_models.go create mode 100644 test/local/azclientoption/zz_options.go create mode 100644 test/local/azclientoption/zz_responses.go create mode 100644 test/local/azclientoption/zz_version.go create mode 100644 test/local/azkeys/LICENSE.txt create mode 100644 test/local/azkeys/custom_client.go create mode 100644 test/local/azkeys/fake/zz_internal.go create mode 100644 test/local/azkeys/fake/zz_server.go create mode 100644 test/local/azkeys/fake_test.go create mode 100644 test/local/azkeys/go.mod create mode 100644 test/local/azkeys/go.sum create mode 100644 test/local/azkeys/testdata/_metadata.json create mode 100644 test/local/azkeys/zz_client.go create mode 100644 test/local/azkeys/zz_constants.go create mode 100644 test/local/azkeys/zz_models.go create mode 100644 test/local/azkeys/zz_models_serde.go create mode 100644 test/local/azkeys/zz_options.go create mode 100644 test/local/azkeys/zz_responses.go create mode 100644 test/local/azkeys/zz_version.go create mode 100644 test/local/azmodelsonly/LICENSE.txt create mode 100644 test/local/azmodelsonly/go.mod create mode 100644 test/local/azmodelsonly/go.sum create mode 100644 test/local/azmodelsonly/testdata/_metadata.json create mode 100644 test/local/azmodelsonly/version.go create mode 100644 test/local/azmodelsonly/zz_models.go create mode 100644 test/local/azmodelsonly/zz_models_serde.go create mode 100644 test/local/azmodelsonly/zz_version.go create mode 100644 test/local/azregressions/LICENSE.txt create mode 100644 test/local/azregressions/fake/zz_internal.go create mode 100644 test/local/azregressions/fake/zz_server.go create mode 100644 test/local/azregressions/go.mod create mode 100644 test/local/azregressions/go.sum create mode 100644 test/local/azregressions/server_test.go create mode 100644 test/local/azregressions/testdata/_metadata.json create mode 100644 test/local/azregressions/zz_client.go create mode 100644 test/local/azregressions/zz_constants.go create mode 100644 test/local/azregressions/zz_interfaces.go create mode 100644 test/local/azregressions/zz_models.go create mode 100644 test/local/azregressions/zz_models_serde.go create mode 100644 test/local/azregressions/zz_options.go create mode 100644 test/local/azregressions/zz_polymorphic_helpers.go create mode 100644 test/local/azregressions/zz_responses.go create mode 100644 test/local/azregressions/zz_responses_serde.go create mode 100644 test/local/azregressions/zz_version.go create mode 100644 test/local/azregressions/zz_xml_helper.go create mode 100644 test/local/internalpager/LICENSE.txt create mode 100644 test/local/internalpager/go.mod create mode 100644 test/local/internalpager/go.sum create mode 100644 test/local/internalpager/testdata/_metadata.json create mode 100644 test/local/internalpager/zz_constants.go create mode 100644 test/local/internalpager/zz_models.go create mode 100644 test/local/internalpager/zz_models_serde.go create mode 100644 test/local/internalpager/zz_options.go create mode 100644 test/local/internalpager/zz_pager_client.go create mode 100644 test/local/internalpager/zz_pagerwidgets_client.go create mode 100644 test/local/internalpager/zz_responses.go create mode 100644 test/local/internalpager/zz_version.go create mode 100644 test/local/nooptionalbody/LICENSE.txt create mode 100644 test/local/nooptionalbody/after_generate.go create mode 100644 test/local/nooptionalbody/go.mod create mode 100644 test/local/nooptionalbody/go.sum create mode 100644 test/local/nooptionalbody/testdata/_metadata.json create mode 100644 test/local/nooptionalbody/testdata/generate/transforms.go create mode 100644 test/local/nooptionalbody/zz_client.go create mode 100644 test/local/nooptionalbody/zz_models.go create mode 100644 test/local/nooptionalbody/zz_models_serde.go create mode 100644 test/local/nooptionalbody/zz_options.go create mode 100644 test/local/nooptionalbody/zz_responses.go create mode 100644 test/local/nooptionalbody/zz_version.go create mode 100644 test/local/rawjson/client.go create mode 100644 test/local/rawjson/go.mod create mode 100644 test/local/rawjson/go.sum create mode 100644 test/local/rawjson/subpkg/fake/zz_internal.go create mode 100644 test/local/rawjson/subpkg/fake/zz_rawjson_server.go create mode 100644 test/local/rawjson/subpkg/fake/zz_rawjsoninputonly_server.go create mode 100644 test/local/rawjson/subpkg/fake/zz_rawjsonmodelcase_server.go create mode 100644 test/local/rawjson/subpkg/fake/zz_rawjsonoutputonly_server.go create mode 100644 test/local/rawjson/subpkg/zz_models.go create mode 100644 test/local/rawjson/subpkg/zz_models_serde.go create mode 100644 test/local/rawjson/subpkg/zz_options.go create mode 100644 test/local/rawjson/subpkg/zz_rawjson_client.go create mode 100644 test/local/rawjson/subpkg/zz_rawjsoninputonly_client.go create mode 100644 test/local/rawjson/subpkg/zz_rawjsonmodelcase_client.go create mode 100644 test/local/rawjson/subpkg/zz_rawjsonoutputonly_client.go create mode 100644 test/local/rawjson/subpkg/zz_responses.go create mode 100644 test/local/rawjson/version.go diff --git a/test/azure-http-specs/azure/client-generator-core/accessgroup/LICENSE.txt b/test/azure-http-specs/azure/client-generator-core/accessgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/accessgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/client-generator-core/accessgroup/fake/zz_access_server.go b/test/azure-http-specs/azure/client-generator-core/accessgroup/fake/zz_access_server.go new file mode 100644 index 000000000000..1ecdbd6997cb --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/accessgroup/fake/zz_access_server.go @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// AccessServer is a fake server for instances of the accessgroup.AccessClient type. +type AccessServer struct { + // AccessPublicOperationServer contains the fakes for client AccessPublicOperationClient + AccessPublicOperationServer AccessPublicOperationServer + + // AccessSharedModelInOperationServer contains the fakes for client AccessSharedModelInOperationClient + AccessSharedModelInOperationServer AccessSharedModelInOperationServer +} + +// NewAccessServerTransport creates a new instance of AccessServerTransport with the provided implementation. +// The returned AccessServerTransport instance is connected to an instance of accessgroup.AccessClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAccessServerTransport(srv *AccessServer) *AccessServerTransport { + return &AccessServerTransport{srv: srv} +} + +// AccessServerTransport connects instances of accessgroup.AccessClient to instances of AccessServer. +// Don't use this type directly, use NewAccessServerTransport instead. +type AccessServerTransport struct { + srv *AccessServer + trMu sync.Mutex + trAccessPublicOperationServer *AccessPublicOperationServerTransport + trAccessSharedModelInOperationServer *AccessSharedModelInOperationServerTransport +} + +// Do implements the policy.Transporter interface for AccessServerTransport. +func (a *AccessServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (a *AccessServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "AccessPublicOperationClient": + initServer(&a.trMu, &a.trAccessPublicOperationServer, func() *AccessPublicOperationServerTransport { + return NewAccessPublicOperationServerTransport(&a.srv.AccessPublicOperationServer) + }) + resp, err = a.trAccessPublicOperationServer.Do(req) + case "AccessSharedModelInOperationClient": + initServer(&a.trMu, &a.trAccessSharedModelInOperationServer, func() *AccessSharedModelInOperationServerTransport { + return NewAccessSharedModelInOperationServerTransport(&a.srv.AccessSharedModelInOperationServer) + }) + resp, err = a.trAccessSharedModelInOperationServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to AccessServerTransport +var accessServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/accessgroup/fake/zz_accesspublicoperation_server.go b/test/azure-http-specs/azure/client-generator-core/accessgroup/fake/zz_accesspublicoperation_server.go new file mode 100644 index 000000000000..0b7d2cca01a1 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/accessgroup/fake/zz_accesspublicoperation_server.go @@ -0,0 +1,128 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "accessgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// AccessPublicOperationServer is a fake server for instances of the accessgroup.AccessPublicOperationClient type. +type AccessPublicOperationServer struct { + // NoDecoratorInPublic is the fake for method AccessPublicOperationClient.NoDecoratorInPublic + // HTTP status codes to indicate success: http.StatusOK + NoDecoratorInPublic func(ctx context.Context, name string, options *accessgroup.AccessPublicOperationClientNoDecoratorInPublicOptions) (resp azfake.Responder[accessgroup.AccessPublicOperationClientNoDecoratorInPublicResponse], errResp azfake.ErrorResponder) + + // PublicDecoratorInPublic is the fake for method AccessPublicOperationClient.PublicDecoratorInPublic + // HTTP status codes to indicate success: http.StatusOK + PublicDecoratorInPublic func(ctx context.Context, name string, options *accessgroup.AccessPublicOperationClientPublicDecoratorInPublicOptions) (resp azfake.Responder[accessgroup.AccessPublicOperationClientPublicDecoratorInPublicResponse], errResp azfake.ErrorResponder) +} + +// NewAccessPublicOperationServerTransport creates a new instance of AccessPublicOperationServerTransport with the provided implementation. +// The returned AccessPublicOperationServerTransport instance is connected to an instance of accessgroup.AccessPublicOperationClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAccessPublicOperationServerTransport(srv *AccessPublicOperationServer) *AccessPublicOperationServerTransport { + return &AccessPublicOperationServerTransport{srv: srv} +} + +// AccessPublicOperationServerTransport connects instances of accessgroup.AccessPublicOperationClient to instances of AccessPublicOperationServer. +// Don't use this type directly, use NewAccessPublicOperationServerTransport instead. +type AccessPublicOperationServerTransport struct { + srv *AccessPublicOperationServer +} + +// Do implements the policy.Transporter interface for AccessPublicOperationServerTransport. +func (a *AccessPublicOperationServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *AccessPublicOperationServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if accessPublicOperationServerTransportInterceptor != nil { + res.resp, res.err, intercepted = accessPublicOperationServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "AccessPublicOperationClient.NoDecoratorInPublic": + res.resp, res.err = a.dispatchNoDecoratorInPublic(req) + case "AccessPublicOperationClient.PublicDecoratorInPublic": + res.resp, res.err = a.dispatchPublicDecoratorInPublic(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *AccessPublicOperationServerTransport) dispatchNoDecoratorInPublic(req *http.Request) (*http.Response, error) { + if a.srv.NoDecoratorInPublic == nil { + return nil, &nonRetriableError{errors.New("fake for method NoDecoratorInPublic not implemented")} + } + qp := req.URL.Query() + respr, errRespr := a.srv.NoDecoratorInPublic(req.Context(), qp.Get("name"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).NoDecoratorModelInPublic, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AccessPublicOperationServerTransport) dispatchPublicDecoratorInPublic(req *http.Request) (*http.Response, error) { + if a.srv.PublicDecoratorInPublic == nil { + return nil, &nonRetriableError{errors.New("fake for method PublicDecoratorInPublic not implemented")} + } + qp := req.URL.Query() + respr, errRespr := a.srv.PublicDecoratorInPublic(req.Context(), qp.Get("name"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).PublicDecoratorModelInPublic, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to AccessPublicOperationServerTransport +var accessPublicOperationServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/accessgroup/fake/zz_accesssharedmodelinoperation_server.go b/test/azure-http-specs/azure/client-generator-core/accessgroup/fake/zz_accesssharedmodelinoperation_server.go new file mode 100644 index 000000000000..434301aaf3dc --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/accessgroup/fake/zz_accesssharedmodelinoperation_server.go @@ -0,0 +1,102 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "accessgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// AccessSharedModelInOperationServer is a fake server for instances of the accessgroup.AccessSharedModelInOperationClient type. +type AccessSharedModelInOperationServer struct { + // Public is the fake for method AccessSharedModelInOperationClient.Public + // HTTP status codes to indicate success: http.StatusOK + Public func(ctx context.Context, name string, options *accessgroup.AccessSharedModelInOperationClientPublicOptions) (resp azfake.Responder[accessgroup.AccessSharedModelInOperationClientPublicResponse], errResp azfake.ErrorResponder) +} + +// NewAccessSharedModelInOperationServerTransport creates a new instance of AccessSharedModelInOperationServerTransport with the provided implementation. +// The returned AccessSharedModelInOperationServerTransport instance is connected to an instance of accessgroup.AccessSharedModelInOperationClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAccessSharedModelInOperationServerTransport(srv *AccessSharedModelInOperationServer) *AccessSharedModelInOperationServerTransport { + return &AccessSharedModelInOperationServerTransport{srv: srv} +} + +// AccessSharedModelInOperationServerTransport connects instances of accessgroup.AccessSharedModelInOperationClient to instances of AccessSharedModelInOperationServer. +// Don't use this type directly, use NewAccessSharedModelInOperationServerTransport instead. +type AccessSharedModelInOperationServerTransport struct { + srv *AccessSharedModelInOperationServer +} + +// Do implements the policy.Transporter interface for AccessSharedModelInOperationServerTransport. +func (a *AccessSharedModelInOperationServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *AccessSharedModelInOperationServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if accessSharedModelInOperationServerTransportInterceptor != nil { + res.resp, res.err, intercepted = accessSharedModelInOperationServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "AccessSharedModelInOperationClient.Public": + res.resp, res.err = a.dispatchPublic(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *AccessSharedModelInOperationServerTransport) dispatchPublic(req *http.Request) (*http.Response, error) { + if a.srv.Public == nil { + return nil, &nonRetriableError{errors.New("fake for method Public not implemented")} + } + qp := req.URL.Query() + respr, errRespr := a.srv.Public(req.Context(), qp.Get("name"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).SharedModel, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to AccessSharedModelInOperationServerTransport +var accessSharedModelInOperationServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/accessgroup/fake/zz_internal.go b/test/azure-http-specs/azure/client-generator-core/accessgroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/accessgroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/azure-http-specs/azure/client-generator-core/accessgroup/go.mod b/test/azure-http-specs/azure/client-generator-core/accessgroup/go.mod new file mode 100644 index 000000000000..694297c4e2c5 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/accessgroup/go.mod @@ -0,0 +1,17 @@ +module accessgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/client-generator-core/accessgroup/go.sum b/test/azure-http-specs/azure/client-generator-core/accessgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/accessgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/client-generator-core/accessgroup/internaloperation_client_test.go b/test/azure-http-specs/azure/client-generator-core/accessgroup/internaloperation_client_test.go new file mode 100644 index 000000000000..3af30f0832af --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/accessgroup/internaloperation_client_test.go @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package accessgroup + +import ( + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestInternalOperationClient_internalDecoratorInInternal(t *testing.T) { + client, err := NewAccessClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewAccessInternalOperationClient().internalDecoratorInInternal(context.Background(), "sample", nil) + require.NoError(t, err) + require.Equal(t, internalDecoratorModelInInternal{ + Name: to.Ptr("sample"), + }, resp.internalDecoratorModelInInternal) +} + +func TestInternalOperationClient_noDecoratorInInternal(t *testing.T) { + client, err := NewAccessClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewAccessInternalOperationClient().noDecoratorInInternal(context.Background(), "sample", nil) + require.NoError(t, err) + require.Equal(t, noDecoratorModelInInternal{ + Name: to.Ptr("sample"), + }, resp.noDecoratorModelInInternal) +} + +func TestInternalOperationClient_publicDecoratorInInternal(t *testing.T) { + client, err := NewAccessClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewAccessInternalOperationClient().publicDecoratorInInternal(context.Background(), "sample", nil) + require.NoError(t, err) + require.Equal(t, PublicDecoratorModelInInternal{ + Name: to.Ptr("sample"), + }, resp.PublicDecoratorModelInInternal) +} diff --git a/test/azure-http-specs/azure/client-generator-core/accessgroup/publicoperation_client_test.go b/test/azure-http-specs/azure/client-generator-core/accessgroup/publicoperation_client_test.go new file mode 100644 index 000000000000..98b80b256c24 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/accessgroup/publicoperation_client_test.go @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package accessgroup + +import ( + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestPublicOperationClient_NoDecoratorInPublic(t *testing.T) { + client, err := NewAccessClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewAccessPublicOperationClient().NoDecoratorInPublic(context.Background(), "sample", nil) + require.NoError(t, err) + require.Equal(t, NoDecoratorModelInPublic{ + Name: to.Ptr("sample"), + }, resp.NoDecoratorModelInPublic) +} + +func TestPublicOperationClient_PublicDecoratorInPublic(t *testing.T) { + client, err := NewAccessClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewAccessPublicOperationClient().PublicDecoratorInPublic(context.Background(), "sample", nil) + require.NoError(t, err) + require.Equal(t, PublicDecoratorModelInPublic{ + Name: to.Ptr("sample"), + }, resp.PublicDecoratorModelInPublic) +} diff --git a/test/azure-http-specs/azure/client-generator-core/accessgroup/relativemodelinoperation_client_test.go b/test/azure-http-specs/azure/client-generator-core/accessgroup/relativemodelinoperation_client_test.go new file mode 100644 index 000000000000..9ba819d87be5 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/accessgroup/relativemodelinoperation_client_test.go @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package accessgroup + +import ( + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestRelativeModelInOperationClient_discriminator(t *testing.T) { + client, err := NewAccessClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewAccessRelativeModelInOperationClient().discriminator(context.Background(), "real", nil) + require.NoError(t, err) + require.Equal(t, &realModel{ + Kind: to.Ptr("real"), + Name: to.Ptr("Madge"), + }, resp.abstractModelClassification) +} + +func TestRelativeModelInOperationClient_operation(t *testing.T) { + client, err := NewAccessClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewAccessRelativeModelInOperationClient().operation(context.Background(), "Madge", nil) + require.NoError(t, err) + require.Equal(t, outerModel{ + Name: to.Ptr("Madge"), + Inner: &innerModel{ + Name: to.Ptr("Madge"), + }, + }, resp.outerModel) +} diff --git a/test/azure-http-specs/azure/client-generator-core/accessgroup/sharedmodelinoperation_client_test.go b/test/azure-http-specs/azure/client-generator-core/accessgroup/sharedmodelinoperation_client_test.go new file mode 100644 index 000000000000..90594e7c1dfc --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/accessgroup/sharedmodelinoperation_client_test.go @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package accessgroup + +import ( + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestSharedModelInOperationClient_internalMethod(t *testing.T) { + client, err := NewAccessClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewAccessSharedModelInOperationClient().internalMethod(context.Background(), "sample", nil) + require.NoError(t, err) + require.Equal(t, SharedModel{ + Name: to.Ptr("sample"), + }, resp.SharedModel) +} + +func TestSharedModelInOperationClient_Public(t *testing.T) { + client, err := NewAccessClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewAccessSharedModelInOperationClient().Public(context.Background(), "sample", nil) + require.NoError(t, err) + require.Equal(t, SharedModel{ + Name: to.Ptr("sample"), + }, resp.SharedModel) +} diff --git a/test/azure-http-specs/azure/client-generator-core/accessgroup/testdata/_metadata.json b/test/azure-http-specs/azure/client-generator-core/accessgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/accessgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_access_client.go b/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_access_client.go new file mode 100644 index 000000000000..8948fc91b4b2 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_access_client.go @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package accessgroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// AccessClient - Test for internal decorator. +// Don't use this type directly, use NewAccessClientWithNoCredential() instead. +type AccessClient struct { + internal *azcore.Client + endpoint string +} + +// AccessClientOptions contains the optional values for creating a [AccessClient]. +type AccessClientOptions struct { + azcore.ClientOptions +} + +// NewAccessClientWithNoCredential creates a new instance of AccessClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewAccessClientWithNoCredential(endpoint string, options *AccessClientOptions) (*AccessClient, error) { + if options == nil { + options = &AccessClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &AccessClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewAccessInternalOperationClient creates a new instance of [AccessInternalOperationClient]. +func (client *AccessClient) NewAccessInternalOperationClient() *AccessInternalOperationClient { + return &AccessInternalOperationClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewAccessPublicOperationClient creates a new instance of [AccessPublicOperationClient]. +func (client *AccessClient) NewAccessPublicOperationClient() *AccessPublicOperationClient { + return &AccessPublicOperationClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewAccessRelativeModelInOperationClient creates a new instance of [AccessRelativeModelInOperationClient]. +func (client *AccessClient) NewAccessRelativeModelInOperationClient() *AccessRelativeModelInOperationClient { + return &AccessRelativeModelInOperationClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewAccessSharedModelInOperationClient creates a new instance of [AccessSharedModelInOperationClient]. +func (client *AccessClient) NewAccessSharedModelInOperationClient() *AccessSharedModelInOperationClient { + return &AccessSharedModelInOperationClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_accessinternaloperation_client.go b/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_accessinternaloperation_client.go new file mode 100644 index 000000000000..837069e728ab --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_accessinternaloperation_client.go @@ -0,0 +1,168 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package accessgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// AccessInternalOperationClient contains the methods for the AccessInternalOperation group. +// Don't use this type directly, use [AccessClient.NewAccessInternalOperationClient] instead. +type AccessInternalOperationClient struct { + internal *azcore.Client + endpoint string +} + +// internalDecoratorInInternal - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - accessInternalOperationClientinternalDecoratorInInternalOptions contains the optional parameters for the AccessInternalOperationClient.internalDecoratorInInternal +// method. +func (client *AccessInternalOperationClient) internalDecoratorInInternal(ctx context.Context, name string, options *accessInternalOperationClientinternalDecoratorInInternalOptions) (accessInternalOperationClientinternalDecoratorInInternalResponse, error) { + var err error + const operationName = "AccessInternalOperationClient.internalDecoratorInInternal" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.internalDecoratorInInternalCreateRequest(ctx, name, options) + if err != nil { + return accessInternalOperationClientinternalDecoratorInInternalResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return accessInternalOperationClientinternalDecoratorInInternalResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return accessInternalOperationClientinternalDecoratorInInternalResponse{}, err + } + resp, err := client.internalDecoratorInInternalHandleResponse(httpResp) + return resp, err +} + +// internalDecoratorInInternalCreateRequest creates the internalDecoratorInInternal request. +func (client *AccessInternalOperationClient) internalDecoratorInInternalCreateRequest(ctx context.Context, name string, _ *accessInternalOperationClientinternalDecoratorInInternalOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/access/internalOperation/internalDecoratorInInternal" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("name", name) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// internalDecoratorInInternalHandleResponse handles the internalDecoratorInInternal response. +func (client *AccessInternalOperationClient) internalDecoratorInInternalHandleResponse(resp *http.Response) (accessInternalOperationClientinternalDecoratorInInternalResponse, error) { + result := accessInternalOperationClientinternalDecoratorInInternalResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.internalDecoratorModelInInternal); err != nil { + return accessInternalOperationClientinternalDecoratorInInternalResponse{}, err + } + return result, nil +} + +// noDecoratorInInternal - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - accessInternalOperationClientnoDecoratorInInternalOptions contains the optional parameters for the AccessInternalOperationClient.noDecoratorInInternal +// method. +func (client *AccessInternalOperationClient) noDecoratorInInternal(ctx context.Context, name string, options *accessInternalOperationClientnoDecoratorInInternalOptions) (accessInternalOperationClientnoDecoratorInInternalResponse, error) { + var err error + const operationName = "AccessInternalOperationClient.noDecoratorInInternal" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.noDecoratorInInternalCreateRequest(ctx, name, options) + if err != nil { + return accessInternalOperationClientnoDecoratorInInternalResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return accessInternalOperationClientnoDecoratorInInternalResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return accessInternalOperationClientnoDecoratorInInternalResponse{}, err + } + resp, err := client.noDecoratorInInternalHandleResponse(httpResp) + return resp, err +} + +// noDecoratorInInternalCreateRequest creates the noDecoratorInInternal request. +func (client *AccessInternalOperationClient) noDecoratorInInternalCreateRequest(ctx context.Context, name string, _ *accessInternalOperationClientnoDecoratorInInternalOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/access/internalOperation/noDecoratorInInternal" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("name", name) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// noDecoratorInInternalHandleResponse handles the noDecoratorInInternal response. +func (client *AccessInternalOperationClient) noDecoratorInInternalHandleResponse(resp *http.Response) (accessInternalOperationClientnoDecoratorInInternalResponse, error) { + result := accessInternalOperationClientnoDecoratorInInternalResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.noDecoratorModelInInternal); err != nil { + return accessInternalOperationClientnoDecoratorInInternalResponse{}, err + } + return result, nil +} + +// publicDecoratorInInternal - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - accessInternalOperationClientpublicDecoratorInInternalOptions contains the optional parameters for the AccessInternalOperationClient.publicDecoratorInInternal +// method. +func (client *AccessInternalOperationClient) publicDecoratorInInternal(ctx context.Context, name string, options *accessInternalOperationClientpublicDecoratorInInternalOptions) (accessInternalOperationClientpublicDecoratorInInternalResponse, error) { + var err error + const operationName = "AccessInternalOperationClient.publicDecoratorInInternal" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.publicDecoratorInInternalCreateRequest(ctx, name, options) + if err != nil { + return accessInternalOperationClientpublicDecoratorInInternalResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return accessInternalOperationClientpublicDecoratorInInternalResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return accessInternalOperationClientpublicDecoratorInInternalResponse{}, err + } + resp, err := client.publicDecoratorInInternalHandleResponse(httpResp) + return resp, err +} + +// publicDecoratorInInternalCreateRequest creates the publicDecoratorInInternal request. +func (client *AccessInternalOperationClient) publicDecoratorInInternalCreateRequest(ctx context.Context, name string, _ *accessInternalOperationClientpublicDecoratorInInternalOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/access/internalOperation/publicDecoratorInInternal" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("name", name) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// publicDecoratorInInternalHandleResponse handles the publicDecoratorInInternal response. +func (client *AccessInternalOperationClient) publicDecoratorInInternalHandleResponse(resp *http.Response) (accessInternalOperationClientpublicDecoratorInInternalResponse, error) { + result := accessInternalOperationClientpublicDecoratorInInternalResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PublicDecoratorModelInInternal); err != nil { + return accessInternalOperationClientpublicDecoratorInInternalResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_accesspublicoperation_client.go b/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_accesspublicoperation_client.go new file mode 100644 index 000000000000..c619eecfff88 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_accesspublicoperation_client.go @@ -0,0 +1,119 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package accessgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// AccessPublicOperationClient contains the methods for the AccessPublicOperation group. +// Don't use this type directly, use [AccessClient.NewAccessPublicOperationClient] instead. +type AccessPublicOperationClient struct { + internal *azcore.Client + endpoint string +} + +// NoDecoratorInPublic - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - AccessPublicOperationClientNoDecoratorInPublicOptions contains the optional parameters for the AccessPublicOperationClient.NoDecoratorInPublic +// method. +func (client *AccessPublicOperationClient) NoDecoratorInPublic(ctx context.Context, name string, options *AccessPublicOperationClientNoDecoratorInPublicOptions) (AccessPublicOperationClientNoDecoratorInPublicResponse, error) { + var err error + const operationName = "AccessPublicOperationClient.NoDecoratorInPublic" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.noDecoratorInPublicCreateRequest(ctx, name, options) + if err != nil { + return AccessPublicOperationClientNoDecoratorInPublicResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AccessPublicOperationClientNoDecoratorInPublicResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AccessPublicOperationClientNoDecoratorInPublicResponse{}, err + } + resp, err := client.noDecoratorInPublicHandleResponse(httpResp) + return resp, err +} + +// noDecoratorInPublicCreateRequest creates the NoDecoratorInPublic request. +func (client *AccessPublicOperationClient) noDecoratorInPublicCreateRequest(ctx context.Context, name string, _ *AccessPublicOperationClientNoDecoratorInPublicOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/access/publicOperation/noDecoratorInPublic" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("name", name) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// noDecoratorInPublicHandleResponse handles the NoDecoratorInPublic response. +func (client *AccessPublicOperationClient) noDecoratorInPublicHandleResponse(resp *http.Response) (AccessPublicOperationClientNoDecoratorInPublicResponse, error) { + result := AccessPublicOperationClientNoDecoratorInPublicResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.NoDecoratorModelInPublic); err != nil { + return AccessPublicOperationClientNoDecoratorInPublicResponse{}, err + } + return result, nil +} + +// PublicDecoratorInPublic - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - AccessPublicOperationClientPublicDecoratorInPublicOptions contains the optional parameters for the AccessPublicOperationClient.PublicDecoratorInPublic +// method. +func (client *AccessPublicOperationClient) PublicDecoratorInPublic(ctx context.Context, name string, options *AccessPublicOperationClientPublicDecoratorInPublicOptions) (AccessPublicOperationClientPublicDecoratorInPublicResponse, error) { + var err error + const operationName = "AccessPublicOperationClient.PublicDecoratorInPublic" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.publicDecoratorInPublicCreateRequest(ctx, name, options) + if err != nil { + return AccessPublicOperationClientPublicDecoratorInPublicResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AccessPublicOperationClientPublicDecoratorInPublicResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AccessPublicOperationClientPublicDecoratorInPublicResponse{}, err + } + resp, err := client.publicDecoratorInPublicHandleResponse(httpResp) + return resp, err +} + +// publicDecoratorInPublicCreateRequest creates the PublicDecoratorInPublic request. +func (client *AccessPublicOperationClient) publicDecoratorInPublicCreateRequest(ctx context.Context, name string, _ *AccessPublicOperationClientPublicDecoratorInPublicOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/access/publicOperation/publicDecoratorInPublic" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("name", name) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// publicDecoratorInPublicHandleResponse handles the PublicDecoratorInPublic response. +func (client *AccessPublicOperationClient) publicDecoratorInPublicHandleResponse(resp *http.Response) (AccessPublicOperationClientPublicDecoratorInPublicResponse, error) { + result := AccessPublicOperationClientPublicDecoratorInPublicResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PublicDecoratorModelInPublic); err != nil { + return AccessPublicOperationClientPublicDecoratorInPublicResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_accessrelativemodelinoperation_client.go b/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_accessrelativemodelinoperation_client.go new file mode 100644 index 000000000000..982b80a37757 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_accessrelativemodelinoperation_client.go @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package accessgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// AccessRelativeModelInOperationClient contains the methods for the AccessRelativeModelInOperation group. +// Don't use this type directly, use [AccessClient.NewAccessRelativeModelInOperationClient] instead. +type AccessRelativeModelInOperationClient struct { + internal *azcore.Client + endpoint string +} + +// discriminator - Expected query parameter: kind="real" +// Expected response body: +// ```json +// { +// "name": "Madge", +// "kind": "real" +// } +// ``` +// If the operation fails it returns an *azcore.ResponseError type. +// - options - accessRelativeModelInOperationClientdiscriminatorOptions contains the optional parameters for the AccessRelativeModelInOperationClient.discriminator +// method. +func (client *AccessRelativeModelInOperationClient) discriminator(ctx context.Context, kind string, options *accessRelativeModelInOperationClientdiscriminatorOptions) (accessRelativeModelInOperationClientdiscriminatorResponse, error) { + var err error + const operationName = "AccessRelativeModelInOperationClient.discriminator" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.discriminatorCreateRequest(ctx, kind, options) + if err != nil { + return accessRelativeModelInOperationClientdiscriminatorResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return accessRelativeModelInOperationClientdiscriminatorResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return accessRelativeModelInOperationClientdiscriminatorResponse{}, err + } + resp, err := client.discriminatorHandleResponse(httpResp) + return resp, err +} + +// discriminatorCreateRequest creates the discriminator request. +func (client *AccessRelativeModelInOperationClient) discriminatorCreateRequest(ctx context.Context, kind string, _ *accessRelativeModelInOperationClientdiscriminatorOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/access/relativeModelInOperation/discriminator" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("kind", kind) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// discriminatorHandleResponse handles the discriminator response. +func (client *AccessRelativeModelInOperationClient) discriminatorHandleResponse(resp *http.Response) (accessRelativeModelInOperationClientdiscriminatorResponse, error) { + result := accessRelativeModelInOperationClientdiscriminatorResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result); err != nil { + return accessRelativeModelInOperationClientdiscriminatorResponse{}, err + } + return result, nil +} + +// operation - Expected query parameter: name="Madge" +// Expected response body: +// ```json +// { +// "name": "Madge", +// "inner": +// { +// "name": "Madge" +// } +// } +// ``` +// If the operation fails it returns an *azcore.ResponseError type. +// - options - accessRelativeModelInOperationClientoperationOptions contains the optional parameters for the AccessRelativeModelInOperationClient.operation +// method. +func (client *AccessRelativeModelInOperationClient) operation(ctx context.Context, name string, options *accessRelativeModelInOperationClientoperationOptions) (accessRelativeModelInOperationClientoperationResponse, error) { + var err error + const operationName = "AccessRelativeModelInOperationClient.operation" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.operationCreateRequest(ctx, name, options) + if err != nil { + return accessRelativeModelInOperationClientoperationResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return accessRelativeModelInOperationClientoperationResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return accessRelativeModelInOperationClientoperationResponse{}, err + } + resp, err := client.operationHandleResponse(httpResp) + return resp, err +} + +// operationCreateRequest creates the operation request. +func (client *AccessRelativeModelInOperationClient) operationCreateRequest(ctx context.Context, name string, _ *accessRelativeModelInOperationClientoperationOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/access/relativeModelInOperation/operation" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("name", name) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// operationHandleResponse handles the operation response. +func (client *AccessRelativeModelInOperationClient) operationHandleResponse(resp *http.Response) (accessRelativeModelInOperationClientoperationResponse, error) { + result := accessRelativeModelInOperationClientoperationResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.outerModel); err != nil { + return accessRelativeModelInOperationClientoperationResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_accesssharedmodelinoperation_client.go b/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_accesssharedmodelinoperation_client.go new file mode 100644 index 000000000000..4f9232ad7caf --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_accesssharedmodelinoperation_client.go @@ -0,0 +1,119 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package accessgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// AccessSharedModelInOperationClient contains the methods for the AccessSharedModelInOperation group. +// Don't use this type directly, use [AccessClient.NewAccessSharedModelInOperationClient] instead. +type AccessSharedModelInOperationClient struct { + internal *azcore.Client + endpoint string +} + +// Public - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - AccessSharedModelInOperationClientPublicOptions contains the optional parameters for the AccessSharedModelInOperationClient.Public +// method. +func (client *AccessSharedModelInOperationClient) Public(ctx context.Context, name string, options *AccessSharedModelInOperationClientPublicOptions) (AccessSharedModelInOperationClientPublicResponse, error) { + var err error + const operationName = "AccessSharedModelInOperationClient.Public" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.publicCreateRequest(ctx, name, options) + if err != nil { + return AccessSharedModelInOperationClientPublicResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AccessSharedModelInOperationClientPublicResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AccessSharedModelInOperationClientPublicResponse{}, err + } + resp, err := client.publicHandleResponse(httpResp) + return resp, err +} + +// publicCreateRequest creates the Public request. +func (client *AccessSharedModelInOperationClient) publicCreateRequest(ctx context.Context, name string, _ *AccessSharedModelInOperationClientPublicOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/access/sharedModelInOperation/public" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("name", name) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// publicHandleResponse handles the Public response. +func (client *AccessSharedModelInOperationClient) publicHandleResponse(resp *http.Response) (AccessSharedModelInOperationClientPublicResponse, error) { + result := AccessSharedModelInOperationClientPublicResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SharedModel); err != nil { + return AccessSharedModelInOperationClientPublicResponse{}, err + } + return result, nil +} + +// internalMethod - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - accessSharedModelInOperationClientinternalMethodOptions contains the optional parameters for the AccessSharedModelInOperationClient.internalMethod +// method. +func (client *AccessSharedModelInOperationClient) internalMethod(ctx context.Context, name string, options *accessSharedModelInOperationClientinternalMethodOptions) (accessSharedModelInOperationClientinternalMethodResponse, error) { + var err error + const operationName = "AccessSharedModelInOperationClient.internalMethod" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.internalCreateRequest(ctx, name, options) + if err != nil { + return accessSharedModelInOperationClientinternalMethodResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return accessSharedModelInOperationClientinternalMethodResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return accessSharedModelInOperationClientinternalMethodResponse{}, err + } + resp, err := client.internalHandleResponse(httpResp) + return resp, err +} + +// internalCreateRequest creates the internalMethod request. +func (client *AccessSharedModelInOperationClient) internalCreateRequest(ctx context.Context, name string, _ *accessSharedModelInOperationClientinternalMethodOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/access/sharedModelInOperation/internal" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("name", name) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// internalHandleResponse handles the internalMethod response. +func (client *AccessSharedModelInOperationClient) internalHandleResponse(resp *http.Response) (accessSharedModelInOperationClientinternalMethodResponse, error) { + result := accessSharedModelInOperationClientinternalMethodResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SharedModel); err != nil { + return accessSharedModelInOperationClientinternalMethodResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_interfaces.go b/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_interfaces.go new file mode 100644 index 000000000000..507d4a18b511 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_interfaces.go @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package accessgroup + +// abstractModelClassification provides polymorphic access to related types. +// Call the interface's GetabstractModel() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *abstractModel, *realModel +type abstractModelClassification interface { + // GetabstractModel returns the abstractModel content of the underlying type. + GetabstractModel() *abstractModel +} diff --git a/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_models.go b/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_models.go new file mode 100644 index 000000000000..69bac53d6e7c --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_models.go @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package accessgroup + +// NoDecoratorModelInPublic - Used in a public operation, should be generated and exported. +type NoDecoratorModelInPublic struct { + // REQUIRED + Name *string +} + +// PublicDecoratorModelInInternal - Used in an internal operation but with public decorator, should be generated and exported. +type PublicDecoratorModelInInternal struct { + // REQUIRED + Name *string +} + +// PublicDecoratorModelInPublic - Used in a public operation, should be generated and exported. +type PublicDecoratorModelInPublic struct { + // REQUIRED + Name *string +} + +// SharedModel - Used by both public and internal operation. It should be generated and exported. +type SharedModel struct { + // REQUIRED + Name *string +} + +// abstractModel - Used in internal operations, should be generated but not exported. +type abstractModel struct { + // REQUIRED; Discriminator property for AbstractModel. + Kind *string + + // REQUIRED + Name *string +} + +// GetabstractModel implements the abstractModelClassification interface for type abstractModel. +func (a *abstractModel) GetabstractModel() *abstractModel { return a } + +// innerModel - Used in internal operations, should be generated but not exported. +type innerModel struct { + // REQUIRED + Name *string +} + +// internalDecoratorModelInInternal - Used in an internal operation, should be generated but not exported. +type internalDecoratorModelInInternal struct { + // REQUIRED + Name *string +} + +// noDecoratorModelInInternal - Used in an internal operation, should be generated but not exported. +type noDecoratorModelInInternal struct { + // REQUIRED + Name *string +} + +// outerModel - Used in internal operations, should be generated but not exported. +type outerModel struct { + // REQUIRED + Inner *innerModel + + // REQUIRED + Name *string +} + +// realModel - Used in internal operations, should be generated but not exported. +type realModel struct { + // REQUIRED + Kind *string + + // REQUIRED + Name *string +} + +// GetabstractModel implements the abstractModelClassification interface for type realModel. +func (r *realModel) GetabstractModel() *abstractModel { + return &abstractModel{ + Kind: r.Kind, + Name: r.Name, + } +} diff --git a/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_models_serde.go b/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_models_serde.go new file mode 100644 index 000000000000..ac3a80d568a6 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_models_serde.go @@ -0,0 +1,314 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package accessgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type NoDecoratorModelInPublic. +func (n NoDecoratorModelInPublic) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", n.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NoDecoratorModelInPublic. +func (n *NoDecoratorModelInPublic) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &n.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PublicDecoratorModelInInternal. +func (p PublicDecoratorModelInInternal) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", p.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PublicDecoratorModelInInternal. +func (p *PublicDecoratorModelInInternal) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PublicDecoratorModelInPublic. +func (p PublicDecoratorModelInPublic) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", p.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PublicDecoratorModelInPublic. +func (p *PublicDecoratorModelInPublic) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SharedModel. +func (s SharedModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", s.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SharedModel. +func (s *SharedModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type abstractModel. +func (a abstractModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "kind", a.Kind) + populate(objectMap, "name", a.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type abstractModel. +func (a *abstractModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &a.Kind) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type innerModel. +func (i innerModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", i.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type innerModel. +func (i *innerModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &i.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type internalDecoratorModelInInternal. +func (i internalDecoratorModelInInternal) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", i.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type internalDecoratorModelInInternal. +func (i *internalDecoratorModelInInternal) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &i.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type noDecoratorModelInInternal. +func (n noDecoratorModelInInternal) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", n.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type noDecoratorModelInInternal. +func (n *noDecoratorModelInInternal) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &n.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type outerModel. +func (o outerModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "inner", o.Inner) + populate(objectMap, "name", o.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type outerModel. +func (o *outerModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "inner": + err = unpopulate(val, "Inner", &o.Inner) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type realModel. +func (r realModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["kind"] = "real" + populate(objectMap, "name", r.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type realModel. +func (r *realModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &r.Kind) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_options.go b/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_options.go new file mode 100644 index 000000000000..a0b7b20a4929 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_options.go @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package accessgroup + +// AccessPublicOperationClientNoDecoratorInPublicOptions contains the optional parameters for the AccessPublicOperationClient.NoDecoratorInPublic +// method. +type AccessPublicOperationClientNoDecoratorInPublicOptions struct { + // placeholder for future optional parameters +} + +// AccessPublicOperationClientPublicDecoratorInPublicOptions contains the optional parameters for the AccessPublicOperationClient.PublicDecoratorInPublic +// method. +type AccessPublicOperationClientPublicDecoratorInPublicOptions struct { + // placeholder for future optional parameters +} + +// AccessSharedModelInOperationClientPublicOptions contains the optional parameters for the AccessSharedModelInOperationClient.Public +// method. +type AccessSharedModelInOperationClientPublicOptions struct { + // placeholder for future optional parameters +} + +// accessInternalOperationClientinternalDecoratorInInternalOptions contains the optional parameters for the AccessInternalOperationClient.internalDecoratorInInternal +// method. +type accessInternalOperationClientinternalDecoratorInInternalOptions struct { + // placeholder for future optional parameters +} + +// accessInternalOperationClientnoDecoratorInInternalOptions contains the optional parameters for the AccessInternalOperationClient.noDecoratorInInternal +// method. +type accessInternalOperationClientnoDecoratorInInternalOptions struct { + // placeholder for future optional parameters +} + +// accessInternalOperationClientpublicDecoratorInInternalOptions contains the optional parameters for the AccessInternalOperationClient.publicDecoratorInInternal +// method. +type accessInternalOperationClientpublicDecoratorInInternalOptions struct { + // placeholder for future optional parameters +} + +// accessRelativeModelInOperationClientdiscriminatorOptions contains the optional parameters for the AccessRelativeModelInOperationClient.discriminator +// method. +type accessRelativeModelInOperationClientdiscriminatorOptions struct { + // placeholder for future optional parameters +} + +// accessRelativeModelInOperationClientoperationOptions contains the optional parameters for the AccessRelativeModelInOperationClient.operation +// method. +type accessRelativeModelInOperationClientoperationOptions struct { + // placeholder for future optional parameters +} + +// accessSharedModelInOperationClientinternalMethodOptions contains the optional parameters for the AccessSharedModelInOperationClient.internalMethod +// method. +type accessSharedModelInOperationClientinternalMethodOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_polymorphic_helpers.go b/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_polymorphic_helpers.go new file mode 100644 index 000000000000..8a27651e3ce4 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_polymorphic_helpers.go @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package accessgroup + +import "encoding/json" + +func unmarshalabstractModelClassification(rawMsg json.RawMessage) (abstractModelClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b abstractModelClassification + switch m["kind"] { + case "real": + b = &realModel{} + default: + b = &abstractModel{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_responses.go b/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_responses.go new file mode 100644 index 000000000000..1c9987d45cd1 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_responses.go @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package accessgroup + +// AccessPublicOperationClientNoDecoratorInPublicResponse contains the response from method AccessPublicOperationClient.NoDecoratorInPublic. +type AccessPublicOperationClientNoDecoratorInPublicResponse struct { + // Used in a public operation, should be generated and exported. + NoDecoratorModelInPublic +} + +// AccessPublicOperationClientPublicDecoratorInPublicResponse contains the response from method AccessPublicOperationClient.PublicDecoratorInPublic. +type AccessPublicOperationClientPublicDecoratorInPublicResponse struct { + // Used in a public operation, should be generated and exported. + PublicDecoratorModelInPublic +} + +// AccessSharedModelInOperationClientPublicResponse contains the response from method AccessSharedModelInOperationClient.Public. +type AccessSharedModelInOperationClientPublicResponse struct { + // Used by both public and internal operation. It should be generated and exported. + SharedModel +} + +// accessInternalOperationClientinternalDecoratorInInternalResponse contains the response from method AccessInternalOperationClient.internalDecoratorInInternal. +type accessInternalOperationClientinternalDecoratorInInternalResponse struct { + // Used in an internal operation, should be generated but not exported. + internalDecoratorModelInInternal +} + +// accessInternalOperationClientnoDecoratorInInternalResponse contains the response from method AccessInternalOperationClient.noDecoratorInInternal. +type accessInternalOperationClientnoDecoratorInInternalResponse struct { + // Used in an internal operation, should be generated but not exported. + noDecoratorModelInInternal +} + +// accessInternalOperationClientpublicDecoratorInInternalResponse contains the response from method AccessInternalOperationClient.publicDecoratorInInternal. +type accessInternalOperationClientpublicDecoratorInInternalResponse struct { + // Used in an internal operation but with public decorator, should be generated and exported. + PublicDecoratorModelInInternal +} + +// accessRelativeModelInOperationClientdiscriminatorResponse contains the response from method AccessRelativeModelInOperationClient.discriminator. +type accessRelativeModelInOperationClientdiscriminatorResponse struct { + // Used in internal operations, should be generated but not exported. + abstractModelClassification +} + +// accessRelativeModelInOperationClientoperationResponse contains the response from method AccessRelativeModelInOperationClient.operation. +type accessRelativeModelInOperationClientoperationResponse struct { + // Used in internal operations, should be generated but not exported. + outerModel +} + +// accessSharedModelInOperationClientinternalMethodResponse contains the response from method AccessSharedModelInOperationClient.internalMethod. +type accessSharedModelInOperationClientinternalMethodResponse struct { + // Used by both public and internal operation. It should be generated and exported. + SharedModel +} diff --git a/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_responses_serde.go b/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_responses_serde.go new file mode 100644 index 000000000000..5f403a14f482 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_responses_serde.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package accessgroup + +// UnmarshalJSON implements the json.Unmarshaller interface for type accessRelativeModelInOperationClientdiscriminatorResponse. +func (a *accessRelativeModelInOperationClientdiscriminatorResponse) UnmarshalJSON(data []byte) error { + res, err := unmarshalabstractModelClassification(data) + if err != nil { + return err + } + a.abstractModelClassification = res + return nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_version.go b/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_version.go new file mode 100644 index 000000000000..f72a17a7a048 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/accessgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package accessgroup + +const ( + moduleName = "accessgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/LICENSE.txt b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/fake/zz_header_server.go b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/fake/zz_header_server.go new file mode 100644 index 000000000000..f79330917111 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/fake/zz_header_server.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "apiversionheadergroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// HeaderServer is a fake server for instances of the apiversionheadergroup.HeaderClient type. +type HeaderServer struct { + // HeaderAPIVersion is the fake for method HeaderClient.HeaderAPIVersion + // HTTP status codes to indicate success: http.StatusOK + HeaderAPIVersion func(ctx context.Context, options *apiversionheadergroup.HeaderClientHeaderAPIVersionOptions) (resp azfake.Responder[apiversionheadergroup.HeaderClientHeaderAPIVersionResponse], errResp azfake.ErrorResponder) +} + +// NewHeaderServerTransport creates a new instance of HeaderServerTransport with the provided implementation. +// The returned HeaderServerTransport instance is connected to an instance of apiversionheadergroup.HeaderClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewHeaderServerTransport(srv *HeaderServer) *HeaderServerTransport { + return &HeaderServerTransport{srv: srv} +} + +// HeaderServerTransport connects instances of apiversionheadergroup.HeaderClient to instances of HeaderServer. +// Don't use this type directly, use NewHeaderServerTransport instead. +type HeaderServerTransport struct { + srv *HeaderServer +} + +// Do implements the policy.Transporter interface for HeaderServerTransport. +func (h *HeaderServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return h.dispatchToMethodFake(req, method) +} + +func (h *HeaderServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if headerServerTransportInterceptor != nil { + res.resp, res.err, intercepted = headerServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "HeaderClient.HeaderAPIVersion": + res.resp, res.err = h.dispatchHeaderAPIVersion(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (h *HeaderServerTransport) dispatchHeaderAPIVersion(req *http.Request) (*http.Response, error) { + if h.srv.HeaderAPIVersion == nil { + return nil, &nonRetriableError{errors.New("fake for method HeaderAPIVersion not implemented")} + } + respr, errRespr := h.srv.HeaderAPIVersion(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to HeaderServerTransport +var headerServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/fake/zz_internal.go b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/fake/zz_internal.go new file mode 100644 index 000000000000..705f81eacafe --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/fake/zz_internal.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import "net/http" + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/go.mod b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/go.mod new file mode 100644 index 000000000000..fadc68ed6718 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/go.mod @@ -0,0 +1,17 @@ +module apiversionheadergroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/go.sum b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/header_client_test.go b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/header_client_test.go new file mode 100644 index 000000000000..e358728e336e --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/header_client_test.go @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package apiversionheadergroup_test + +import ( + "context" + "testing" + + "apiversionheadergroup" + + "github.com/stretchr/testify/require" +) + +func TestHeaderClient_HeaderAPIVersion(t *testing.T) { + client, err := apiversionheadergroup.NewHeaderClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + require.NotNil(t, client) + + resp, err := client.HeaderAPIVersion(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp) +} diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/testdata/_metadata.json b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/testdata/_metadata.json new file mode 100644 index 000000000000..886f54739049 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Client.AlternateApiVersion.Service.Header": "2025-01-01" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/zz_constants.go b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/zz_constants.go new file mode 100644 index 000000000000..3eb2812f5d80 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/zz_constants.go @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package apiversionheadergroup + +const ( + version20250101 string = "2025-01-01" +) diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/zz_header_client.go b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/zz_header_client.go new file mode 100644 index 000000000000..9c169266aedc --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/zz_header_client.go @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package apiversionheadergroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// HeaderClient contains the methods for the Header group. +// Don't use this type directly, use NewHeaderClientWithNoCredential() instead. +// +// Generated from API version 2025-01-01 +type HeaderClient struct { + internal *azcore.Client + endpoint string +} + +// HeaderClientOptions contains the optional values for creating a [HeaderClient]. +type HeaderClientOptions struct { + azcore.ClientOptions +} + +// NewHeaderClientWithNoCredential creates a new instance of HeaderClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewHeaderClientWithNoCredential(endpoint string, options *HeaderClientOptions) (*HeaderClient, error) { + if options == nil { + options = &HeaderClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{ + APIVersion: runtime.APIVersionOptions{ + Name: "x-ms-version", + Location: runtime.APIVersionLocationHeader, + }, + }, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &HeaderClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// HeaderAPIVersion - Header api version parameter. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - HeaderClientHeaderAPIVersionOptions contains the optional parameters for the HeaderClient.HeaderAPIVersion method. +func (client *HeaderClient) HeaderAPIVersion(ctx context.Context, options *HeaderClientHeaderAPIVersionOptions) (HeaderClientHeaderAPIVersionResponse, error) { + var err error + const operationName = "HeaderClient.HeaderAPIVersion" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.headerAPIVersionCreateRequest(ctx, options) + if err != nil { + return HeaderClientHeaderAPIVersionResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return HeaderClientHeaderAPIVersionResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return HeaderClientHeaderAPIVersionResponse{}, err + } + return HeaderClientHeaderAPIVersionResponse{}, nil +} + +// headerAPIVersionCreateRequest creates the HeaderAPIVersion request. +func (client *HeaderClient) headerAPIVersionCreateRequest(ctx context.Context, _ *HeaderClientHeaderAPIVersionOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/api-version/header" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["x-ms-version"] = []string{version20250101} + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/zz_options.go b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/zz_options.go new file mode 100644 index 000000000000..8c93a80aa2a0 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/zz_options.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package apiversionheadergroup + +// HeaderClientHeaderAPIVersionOptions contains the optional parameters for the HeaderClient.HeaderAPIVersion method. +type HeaderClientHeaderAPIVersionOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/zz_responses.go b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/zz_responses.go new file mode 100644 index 000000000000..c21c0641ec3b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/zz_responses.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package apiversionheadergroup + +// HeaderClientHeaderAPIVersionResponse contains the response from method HeaderClient.HeaderAPIVersion. +type HeaderClientHeaderAPIVersionResponse struct { + // placeholder for future response values +} diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/zz_version.go b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/zz_version.go new file mode 100644 index 000000000000..752a9f3096bf --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionheadergroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package apiversionheadergroup + +const ( + moduleName = "apiversionheadergroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/LICENSE.txt b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/fake/zz_internal.go b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/fake/zz_internal.go new file mode 100644 index 000000000000..705f81eacafe --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/fake/zz_internal.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import "net/http" + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/fake/zz_path_server.go b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/fake/zz_path_server.go new file mode 100644 index 000000000000..6a1c71b4227b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/fake/zz_path_server.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "apiversionpathgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// PathServer is a fake server for instances of the apiversionpathgroup.PathClient type. +type PathServer struct { + // PathAPIVersion is the fake for method PathClient.PathAPIVersion + // HTTP status codes to indicate success: http.StatusOK + PathAPIVersion func(ctx context.Context, options *apiversionpathgroup.PathClientPathAPIVersionOptions) (resp azfake.Responder[apiversionpathgroup.PathClientPathAPIVersionResponse], errResp azfake.ErrorResponder) +} + +// NewPathServerTransport creates a new instance of PathServerTransport with the provided implementation. +// The returned PathServerTransport instance is connected to an instance of apiversionpathgroup.PathClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewPathServerTransport(srv *PathServer) *PathServerTransport { + return &PathServerTransport{srv: srv} +} + +// PathServerTransport connects instances of apiversionpathgroup.PathClient to instances of PathServer. +// Don't use this type directly, use NewPathServerTransport instead. +type PathServerTransport struct { + srv *PathServer +} + +// Do implements the policy.Transporter interface for PathServerTransport. +func (p *PathServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return p.dispatchToMethodFake(req, method) +} + +func (p *PathServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if pathServerTransportInterceptor != nil { + res.resp, res.err, intercepted = pathServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "PathClient.PathAPIVersion": + res.resp, res.err = p.dispatchPathAPIVersion(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (p *PathServerTransport) dispatchPathAPIVersion(req *http.Request) (*http.Response, error) { + if p.srv.PathAPIVersion == nil { + return nil, &nonRetriableError{errors.New("fake for method PathAPIVersion not implemented")} + } + respr, errRespr := p.srv.PathAPIVersion(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to PathServerTransport +var pathServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/go.mod b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/go.mod new file mode 100644 index 000000000000..7183119c76b5 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/go.mod @@ -0,0 +1,11 @@ +module apiversionpathgroup + +go 1.25.0 + +require github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect +) diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/go.sum b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/go.sum new file mode 100644 index 000000000000..3fdb64caf441 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/go.sum @@ -0,0 +1,16 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/path_client_test.go b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/path_client_test.go new file mode 100644 index 000000000000..3c63b90d4089 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/path_client_test.go @@ -0,0 +1,12 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package apiversionpathgroup_test + +import ( + "testing" +) + +func TestPathClient_PathAPIVersion(t *testing.T) { + t.Skip("https://github.com/Azure/autorest.go/issues/1743") +} diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/testdata/_metadata.json b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/testdata/_metadata.json new file mode 100644 index 000000000000..d28ffd365ccf --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Client.AlternateApiVersion.Service.Path": "2025-01-01" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/zz_constants.go b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/zz_constants.go new file mode 100644 index 000000000000..cb6276c14c69 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/zz_constants.go @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package apiversionpathgroup + +const ( + version20250101 string = "2025-01-01" +) diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/zz_options.go b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/zz_options.go new file mode 100644 index 000000000000..d79236200f5c --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/zz_options.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package apiversionpathgroup + +// PathClientPathAPIVersionOptions contains the optional parameters for the PathClient.PathAPIVersion method. +type PathClientPathAPIVersionOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/zz_path_client.go b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/zz_path_client.go new file mode 100644 index 000000000000..228ffeb549ee --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/zz_path_client.go @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package apiversionpathgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// PathClient contains the methods for the Path group. +// Don't use this type directly, use NewPathClientWithNoCredential() instead. +// +// Generated from API version 2025-01-01 +type PathClient struct { + internal *azcore.Client + endpoint string +} + +// PathClientOptions contains the optional values for creating a [PathClient]. +type PathClientOptions struct { + azcore.ClientOptions +} + +// NewPathClientWithNoCredential creates a new instance of PathClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewPathClientWithNoCredential(endpoint string, options *PathClientOptions) (*PathClient, error) { + if options == nil { + options = &PathClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{ + APIVersion: runtime.APIVersionOptions{ + Location: runtime.APIVersionLocationPath, + }, + }, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &PathClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// PathAPIVersion - Path api version parameter. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - PathClientPathAPIVersionOptions contains the optional parameters for the PathClient.PathAPIVersion method. +func (client *PathClient) PathAPIVersion(ctx context.Context, options *PathClientPathAPIVersionOptions) (PathClientPathAPIVersionResponse, error) { + var err error + const operationName = "PathClient.PathAPIVersion" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.pathAPIVersionCreateRequest(ctx, options) + if err != nil { + return PathClientPathAPIVersionResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PathClientPathAPIVersionResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PathClientPathAPIVersionResponse{}, err + } + return PathClientPathAPIVersionResponse{}, nil +} + +// pathAPIVersionCreateRequest creates the PathAPIVersion request. +func (client *PathClient) pathAPIVersionCreateRequest(ctx context.Context, _ *PathClientPathAPIVersionOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/api-version/path/{version}" + urlPath = strings.ReplaceAll(urlPath, "{version}", url.PathEscape(version20250101)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/zz_responses.go b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/zz_responses.go new file mode 100644 index 000000000000..97b562846c71 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/zz_responses.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package apiversionpathgroup + +// PathClientPathAPIVersionResponse contains the response from method PathClient.PathAPIVersion. +type PathClientPathAPIVersionResponse struct { + // placeholder for future response values +} diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/zz_version.go b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/zz_version.go new file mode 100644 index 000000000000..eec0e7aabc45 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionpathgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package apiversionpathgroup + +const ( + moduleName = "apiversionpathgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/LICENSE.txt b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/fake/zz_internal.go b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/fake/zz_internal.go new file mode 100644 index 000000000000..705f81eacafe --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/fake/zz_internal.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import "net/http" + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/fake/zz_query_server.go b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/fake/zz_query_server.go new file mode 100644 index 000000000000..c0cdd837642e --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/fake/zz_query_server.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "apiversionquerygroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// QueryServer is a fake server for instances of the apiversionquerygroup.QueryClient type. +type QueryServer struct { + // QueryAPIVersion is the fake for method QueryClient.QueryAPIVersion + // HTTP status codes to indicate success: http.StatusOK + QueryAPIVersion func(ctx context.Context, options *apiversionquerygroup.QueryClientQueryAPIVersionOptions) (resp azfake.Responder[apiversionquerygroup.QueryClientQueryAPIVersionResponse], errResp azfake.ErrorResponder) +} + +// NewQueryServerTransport creates a new instance of QueryServerTransport with the provided implementation. +// The returned QueryServerTransport instance is connected to an instance of apiversionquerygroup.QueryClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewQueryServerTransport(srv *QueryServer) *QueryServerTransport { + return &QueryServerTransport{srv: srv} +} + +// QueryServerTransport connects instances of apiversionquerygroup.QueryClient to instances of QueryServer. +// Don't use this type directly, use NewQueryServerTransport instead. +type QueryServerTransport struct { + srv *QueryServer +} + +// Do implements the policy.Transporter interface for QueryServerTransport. +func (q *QueryServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return q.dispatchToMethodFake(req, method) +} + +func (q *QueryServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if queryServerTransportInterceptor != nil { + res.resp, res.err, intercepted = queryServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "QueryClient.QueryAPIVersion": + res.resp, res.err = q.dispatchQueryAPIVersion(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (q *QueryServerTransport) dispatchQueryAPIVersion(req *http.Request) (*http.Response, error) { + if q.srv.QueryAPIVersion == nil { + return nil, &nonRetriableError{errors.New("fake for method QueryAPIVersion not implemented")} + } + respr, errRespr := q.srv.QueryAPIVersion(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to QueryServerTransport +var queryServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/go.mod b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/go.mod new file mode 100644 index 000000000000..41e36a1937b1 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/go.mod @@ -0,0 +1,17 @@ +module apiversionquerygroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/go.sum b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/query_client_test.go b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/query_client_test.go new file mode 100644 index 000000000000..593229b1ab69 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/query_client_test.go @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package apiversionquerygroup_test + +import ( + "context" + "testing" + + "apiversionquerygroup" + "github.com/stretchr/testify/require" +) + +func TestQueryClient_QueryAPIVersion(t *testing.T) { + client, err := apiversionquerygroup.NewQueryClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + require.NotNil(t, client) + + resp, err := client.QueryAPIVersion(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp) +} diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/testdata/_metadata.json b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/testdata/_metadata.json new file mode 100644 index 000000000000..782f66780cbd --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Client.AlternateApiVersion.Service.Query": "2025-01-01" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/zz_constants.go b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/zz_constants.go new file mode 100644 index 000000000000..9be21d85f420 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/zz_constants.go @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package apiversionquerygroup + +const ( + version20250101 string = "2025-01-01" +) diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/zz_options.go b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/zz_options.go new file mode 100644 index 000000000000..9e9c372b5474 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/zz_options.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package apiversionquerygroup + +// QueryClientQueryAPIVersionOptions contains the optional parameters for the QueryClient.QueryAPIVersion method. +type QueryClientQueryAPIVersionOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/zz_query_client.go b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/zz_query_client.go new file mode 100644 index 000000000000..226d7ef8036b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/zz_query_client.go @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package apiversionquerygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// QueryClient contains the methods for the Query group. +// Don't use this type directly, use NewQueryClientWithNoCredential() instead. +// +// Generated from API version 2025-01-01 +type QueryClient struct { + internal *azcore.Client + endpoint string +} + +// QueryClientOptions contains the optional values for creating a [QueryClient]. +type QueryClientOptions struct { + azcore.ClientOptions +} + +// NewQueryClientWithNoCredential creates a new instance of QueryClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewQueryClientWithNoCredential(endpoint string, options *QueryClientOptions) (*QueryClient, error) { + if options == nil { + options = &QueryClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{ + APIVersion: runtime.APIVersionOptions{ + Name: "version", + Location: runtime.APIVersionLocationQueryParam, + }, + }, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &QueryClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// QueryAPIVersion - Query api version parameter. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - QueryClientQueryAPIVersionOptions contains the optional parameters for the QueryClient.QueryAPIVersion method. +func (client *QueryClient) QueryAPIVersion(ctx context.Context, options *QueryClientQueryAPIVersionOptions) (QueryClientQueryAPIVersionResponse, error) { + var err error + const operationName = "QueryClient.QueryAPIVersion" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.queryAPIVersionCreateRequest(ctx, options) + if err != nil { + return QueryClientQueryAPIVersionResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return QueryClientQueryAPIVersionResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return QueryClientQueryAPIVersionResponse{}, err + } + return QueryClientQueryAPIVersionResponse{}, nil +} + +// queryAPIVersionCreateRequest creates the QueryAPIVersion request. +func (client *QueryClient) queryAPIVersionCreateRequest(ctx context.Context, _ *QueryClientQueryAPIVersionOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/api-version/query" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("version", version20250101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/zz_responses.go b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/zz_responses.go new file mode 100644 index 000000000000..205664c96c71 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/zz_responses.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package apiversionquerygroup + +// QueryClientQueryAPIVersionResponse contains the response from method QueryClient.QueryAPIVersion. +type QueryClientQueryAPIVersionResponse struct { + // placeholder for future response values +} diff --git a/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/zz_version.go b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/zz_version.go new file mode 100644 index 000000000000..0afb6ae0666b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/api-version/apiversionquerygroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package apiversionquerygroup + +const ( + moduleName = "apiversionquerygroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/LICENSE.txt b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_headerparam_server.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_headerparam_server.go new file mode 100644 index 000000000000..b6a20d193ea5 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_headerparam_server.go @@ -0,0 +1,131 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "clientinitdefaultgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// HeaderParamServer is a fake server for instances of the clientinitdefaultgroup.HeaderParamClient type. +type HeaderParamServer struct { + // WithBody is the fake for method HeaderParamClient.WithBody + // HTTP status codes to indicate success: http.StatusNoContent + WithBody func(ctx context.Context, body clientinitdefaultgroup.Input, options *clientinitdefaultgroup.HeaderParamClientWithBodyOptions) (resp azfake.Responder[clientinitdefaultgroup.HeaderParamClientWithBodyResponse], errResp azfake.ErrorResponder) + + // WithQuery is the fake for method HeaderParamClient.WithQuery + // HTTP status codes to indicate success: http.StatusNoContent + WithQuery func(ctx context.Context, id string, options *clientinitdefaultgroup.HeaderParamClientWithQueryOptions) (resp azfake.Responder[clientinitdefaultgroup.HeaderParamClientWithQueryResponse], errResp azfake.ErrorResponder) +} + +// NewHeaderParamServerTransport creates a new instance of HeaderParamServerTransport with the provided implementation. +// The returned HeaderParamServerTransport instance is connected to an instance of clientinitdefaultgroup.HeaderParamClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewHeaderParamServerTransport(srv *HeaderParamServer) *HeaderParamServerTransport { + return &HeaderParamServerTransport{srv: srv} +} + +// HeaderParamServerTransport connects instances of clientinitdefaultgroup.HeaderParamClient to instances of HeaderParamServer. +// Don't use this type directly, use NewHeaderParamServerTransport instead. +type HeaderParamServerTransport struct { + srv *HeaderParamServer +} + +// Do implements the policy.Transporter interface for HeaderParamServerTransport. +func (h *HeaderParamServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return h.dispatchToMethodFake(req, method) +} + +func (h *HeaderParamServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if headerParamServerTransportInterceptor != nil { + res.resp, res.err, intercepted = headerParamServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "HeaderParamClient.WithBody": + res.resp, res.err = h.dispatchWithBody(req) + case "HeaderParamClient.WithQuery": + res.resp, res.err = h.dispatchWithQuery(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (h *HeaderParamServerTransport) dispatchWithBody(req *http.Request) (*http.Response, error) { + if h.srv.WithBody == nil { + return nil, &nonRetriableError{errors.New("fake for method WithBody not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[clientinitdefaultgroup.Input](req) + if err != nil { + return nil, err + } + respr, errRespr := h.srv.WithBody(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (h *HeaderParamServerTransport) dispatchWithQuery(req *http.Request) (*http.Response, error) { + if h.srv.WithQuery == nil { + return nil, &nonRetriableError{errors.New("fake for method WithQuery not implemented")} + } + qp := req.URL.Query() + respr, errRespr := h.srv.WithQuery(req.Context(), qp.Get("id"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to HeaderParamServerTransport +var headerParamServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_internal.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_internal.go new file mode 100644 index 000000000000..53ec711308cc --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_internal.go @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "reflect" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getOptional[T any](v T) *T { + if reflect.ValueOf(v).IsZero() { + return nil + } + return &v +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_mixedparams_server.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_mixedparams_server.go new file mode 100644 index 000000000000..bb4c02fbe3f9 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_mixedparams_server.go @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "clientinitdefaultgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// MixedParamsServer is a fake server for instances of the clientinitdefaultgroup.MixedParamsClient type. +type MixedParamsServer struct { + // WithBody is the fake for method MixedParamsClient.WithBody + // HTTP status codes to indicate success: http.StatusNoContent + WithBody func(ctx context.Context, region string, body clientinitdefaultgroup.WithBodyRequest, options *clientinitdefaultgroup.MixedParamsClientWithBodyOptions) (resp azfake.Responder[clientinitdefaultgroup.MixedParamsClientWithBodyResponse], errResp azfake.ErrorResponder) + + // WithQuery is the fake for method MixedParamsClient.WithQuery + // HTTP status codes to indicate success: http.StatusNoContent + WithQuery func(ctx context.Context, region string, id string, options *clientinitdefaultgroup.MixedParamsClientWithQueryOptions) (resp azfake.Responder[clientinitdefaultgroup.MixedParamsClientWithQueryResponse], errResp azfake.ErrorResponder) +} + +// NewMixedParamsServerTransport creates a new instance of MixedParamsServerTransport with the provided implementation. +// The returned MixedParamsServerTransport instance is connected to an instance of clientinitdefaultgroup.MixedParamsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewMixedParamsServerTransport(srv *MixedParamsServer) *MixedParamsServerTransport { + return &MixedParamsServerTransport{srv: srv} +} + +// MixedParamsServerTransport connects instances of clientinitdefaultgroup.MixedParamsClient to instances of MixedParamsServer. +// Don't use this type directly, use NewMixedParamsServerTransport instead. +type MixedParamsServerTransport struct { + srv *MixedParamsServer +} + +// Do implements the policy.Transporter interface for MixedParamsServerTransport. +func (m *MixedParamsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToMethodFake(req, method) +} + +func (m *MixedParamsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if mixedParamsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = mixedParamsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "MixedParamsClient.WithBody": + res.resp, res.err = m.dispatchWithBody(req) + case "MixedParamsClient.WithQuery": + res.resp, res.err = m.dispatchWithQuery(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *MixedParamsServerTransport) dispatchWithBody(req *http.Request) (*http.Response, error) { + if m.srv.WithBody == nil { + return nil, &nonRetriableError{errors.New("fake for method WithBody not implemented")} + } + qp := req.URL.Query() + body, err := server.UnmarshalRequestAsJSON[clientinitdefaultgroup.WithBodyRequest](req) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.WithBody(req.Context(), qp.Get("region"), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *MixedParamsServerTransport) dispatchWithQuery(req *http.Request) (*http.Response, error) { + if m.srv.WithQuery == nil { + return nil, &nonRetriableError{errors.New("fake for method WithQuery not implemented")} + } + qp := req.URL.Query() + respr, errRespr := m.srv.WithQuery(req.Context(), qp.Get("region"), qp.Get("id"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to MixedParamsServerTransport +var mixedParamsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_multipleparams_server.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_multipleparams_server.go new file mode 100644 index 000000000000..bfe515940d76 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_multipleparams_server.go @@ -0,0 +1,131 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "clientinitdefaultgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// MultipleParamsServer is a fake server for instances of the clientinitdefaultgroup.MultipleParamsClient type. +type MultipleParamsServer struct { + // WithBody is the fake for method MultipleParamsClient.WithBody + // HTTP status codes to indicate success: http.StatusNoContent + WithBody func(ctx context.Context, body clientinitdefaultgroup.Input, options *clientinitdefaultgroup.MultipleParamsClientWithBodyOptions) (resp azfake.Responder[clientinitdefaultgroup.MultipleParamsClientWithBodyResponse], errResp azfake.ErrorResponder) + + // WithQuery is the fake for method MultipleParamsClient.WithQuery + // HTTP status codes to indicate success: http.StatusNoContent + WithQuery func(ctx context.Context, id string, options *clientinitdefaultgroup.MultipleParamsClientWithQueryOptions) (resp azfake.Responder[clientinitdefaultgroup.MultipleParamsClientWithQueryResponse], errResp azfake.ErrorResponder) +} + +// NewMultipleParamsServerTransport creates a new instance of MultipleParamsServerTransport with the provided implementation. +// The returned MultipleParamsServerTransport instance is connected to an instance of clientinitdefaultgroup.MultipleParamsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewMultipleParamsServerTransport(srv *MultipleParamsServer) *MultipleParamsServerTransport { + return &MultipleParamsServerTransport{srv: srv} +} + +// MultipleParamsServerTransport connects instances of clientinitdefaultgroup.MultipleParamsClient to instances of MultipleParamsServer. +// Don't use this type directly, use NewMultipleParamsServerTransport instead. +type MultipleParamsServerTransport struct { + srv *MultipleParamsServer +} + +// Do implements the policy.Transporter interface for MultipleParamsServerTransport. +func (m *MultipleParamsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToMethodFake(req, method) +} + +func (m *MultipleParamsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if multipleParamsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = multipleParamsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "MultipleParamsClient.WithBody": + res.resp, res.err = m.dispatchWithBody(req) + case "MultipleParamsClient.WithQuery": + res.resp, res.err = m.dispatchWithQuery(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *MultipleParamsServerTransport) dispatchWithBody(req *http.Request) (*http.Response, error) { + if m.srv.WithBody == nil { + return nil, &nonRetriableError{errors.New("fake for method WithBody not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[clientinitdefaultgroup.Input](req) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.WithBody(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *MultipleParamsServerTransport) dispatchWithQuery(req *http.Request) (*http.Response, error) { + if m.srv.WithQuery == nil { + return nil, &nonRetriableError{errors.New("fake for method WithQuery not implemented")} + } + qp := req.URL.Query() + respr, errRespr := m.srv.WithQuery(req.Context(), qp.Get("id"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to MultipleParamsServerTransport +var multipleParamsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_paramalias_server.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_paramalias_server.go new file mode 100644 index 000000000000..fca26ea18b43 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_paramalias_server.go @@ -0,0 +1,139 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "clientinitdefaultgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "regexp" + "slices" +) + +// ParamAliasServer is a fake server for instances of the clientinitdefaultgroup.ParamAliasClient type. +type ParamAliasServer struct { + // WithAliasedName is the fake for method ParamAliasClient.WithAliasedName + // HTTP status codes to indicate success: http.StatusNoContent + WithAliasedName func(ctx context.Context, options *clientinitdefaultgroup.ParamAliasClientWithAliasedNameOptions) (resp azfake.Responder[clientinitdefaultgroup.ParamAliasClientWithAliasedNameResponse], errResp azfake.ErrorResponder) + + // WithOriginalName is the fake for method ParamAliasClient.WithOriginalName + // HTTP status codes to indicate success: http.StatusNoContent + WithOriginalName func(ctx context.Context, options *clientinitdefaultgroup.ParamAliasClientWithOriginalNameOptions) (resp azfake.Responder[clientinitdefaultgroup.ParamAliasClientWithOriginalNameResponse], errResp azfake.ErrorResponder) +} + +// NewParamAliasServerTransport creates a new instance of ParamAliasServerTransport with the provided implementation. +// The returned ParamAliasServerTransport instance is connected to an instance of clientinitdefaultgroup.ParamAliasClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewParamAliasServerTransport(srv *ParamAliasServer) *ParamAliasServerTransport { + return &ParamAliasServerTransport{srv: srv} +} + +// ParamAliasServerTransport connects instances of clientinitdefaultgroup.ParamAliasClient to instances of ParamAliasServer. +// Don't use this type directly, use NewParamAliasServerTransport instead. +type ParamAliasServerTransport struct { + srv *ParamAliasServer +} + +// Do implements the policy.Transporter interface for ParamAliasServerTransport. +func (p *ParamAliasServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return p.dispatchToMethodFake(req, method) +} + +func (p *ParamAliasServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if paramAliasServerTransportInterceptor != nil { + res.resp, res.err, intercepted = paramAliasServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ParamAliasClient.WithAliasedName": + res.resp, res.err = p.dispatchWithAliasedName(req) + case "ParamAliasClient.WithOriginalName": + res.resp, res.err = p.dispatchWithOriginalName(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (p *ParamAliasServerTransport) dispatchWithAliasedName(req *http.Request) (*http.Response, error) { + if p.srv.WithAliasedName == nil { + return nil, &nonRetriableError{errors.New("fake for method WithAliasedName not implemented")} + } + const regexStr = `/azure/client-generator-core/client-initialization/default/param-alias/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/with-aliased-name` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + respr, errRespr := p.srv.WithAliasedName(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (p *ParamAliasServerTransport) dispatchWithOriginalName(req *http.Request) (*http.Response, error) { + if p.srv.WithOriginalName == nil { + return nil, &nonRetriableError{errors.New("fake for method WithOriginalName not implemented")} + } + const regexStr = `/azure/client-generator-core/client-initialization/default/param-alias/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/with-original-name` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + respr, errRespr := p.srv.WithOriginalName(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ParamAliasServerTransport +var paramAliasServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_pathparam_server.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_pathparam_server.go new file mode 100644 index 000000000000..1cae430b3f20 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_pathparam_server.go @@ -0,0 +1,178 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "clientinitdefaultgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "regexp" + "slices" +) + +// PathParamServer is a fake server for instances of the clientinitdefaultgroup.PathParamClient type. +type PathParamServer struct { + // DeleteStandalone is the fake for method PathParamClient.DeleteStandalone + // HTTP status codes to indicate success: http.StatusNoContent + DeleteStandalone func(ctx context.Context, options *clientinitdefaultgroup.PathParamClientDeleteStandaloneOptions) (resp azfake.Responder[clientinitdefaultgroup.PathParamClientDeleteStandaloneResponse], errResp azfake.ErrorResponder) + + // GetStandalone is the fake for method PathParamClient.GetStandalone + // HTTP status codes to indicate success: http.StatusOK + GetStandalone func(ctx context.Context, options *clientinitdefaultgroup.PathParamClientGetStandaloneOptions) (resp azfake.Responder[clientinitdefaultgroup.PathParamClientGetStandaloneResponse], errResp azfake.ErrorResponder) + + // WithQuery is the fake for method PathParamClient.WithQuery + // HTTP status codes to indicate success: http.StatusNoContent + WithQuery func(ctx context.Context, options *clientinitdefaultgroup.PathParamClientWithQueryOptions) (resp azfake.Responder[clientinitdefaultgroup.PathParamClientWithQueryResponse], errResp azfake.ErrorResponder) +} + +// NewPathParamServerTransport creates a new instance of PathParamServerTransport with the provided implementation. +// The returned PathParamServerTransport instance is connected to an instance of clientinitdefaultgroup.PathParamClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewPathParamServerTransport(srv *PathParamServer) *PathParamServerTransport { + return &PathParamServerTransport{srv: srv} +} + +// PathParamServerTransport connects instances of clientinitdefaultgroup.PathParamClient to instances of PathParamServer. +// Don't use this type directly, use NewPathParamServerTransport instead. +type PathParamServerTransport struct { + srv *PathParamServer +} + +// Do implements the policy.Transporter interface for PathParamServerTransport. +func (p *PathParamServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return p.dispatchToMethodFake(req, method) +} + +func (p *PathParamServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if pathParamServerTransportInterceptor != nil { + res.resp, res.err, intercepted = pathParamServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "PathParamClient.DeleteStandalone": + res.resp, res.err = p.dispatchDeleteStandalone(req) + case "PathParamClient.GetStandalone": + res.resp, res.err = p.dispatchGetStandalone(req) + case "PathParamClient.WithQuery": + res.resp, res.err = p.dispatchWithQuery(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (p *PathParamServerTransport) dispatchDeleteStandalone(req *http.Request) (*http.Response, error) { + if p.srv.DeleteStandalone == nil { + return nil, &nonRetriableError{errors.New("fake for method DeleteStandalone not implemented")} + } + const regexStr = `/azure/client-generator-core/client-initialization/default/path/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + respr, errRespr := p.srv.DeleteStandalone(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (p *PathParamServerTransport) dispatchGetStandalone(req *http.Request) (*http.Response, error) { + if p.srv.GetStandalone == nil { + return nil, &nonRetriableError{errors.New("fake for method GetStandalone not implemented")} + } + const regexStr = `/azure/client-generator-core/client-initialization/default/path/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/get-standalone` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + respr, errRespr := p.srv.GetStandalone(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BlobProperties, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (p *PathParamServerTransport) dispatchWithQuery(req *http.Request) (*http.Response, error) { + if p.srv.WithQuery == nil { + return nil, &nonRetriableError{errors.New("fake for method WithQuery not implemented")} + } + const regexStr = `/azure/client-generator-core/client-initialization/default/path/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/with-query` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + formatParam := getOptional(qp.Get("format")) + var options *clientinitdefaultgroup.PathParamClientWithQueryOptions + if formatParam != nil { + options = &clientinitdefaultgroup.PathParamClientWithQueryOptions{ + Format: formatParam, + } + } + respr, errRespr := p.srv.WithQuery(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to PathParamServerTransport +var pathParamServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_queryparam_server.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_queryparam_server.go new file mode 100644 index 000000000000..8a4b69771b7d --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/fake/zz_queryparam_server.go @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "clientinitdefaultgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// QueryParamServer is a fake server for instances of the clientinitdefaultgroup.QueryParamClient type. +type QueryParamServer struct { + // DeleteStandalone is the fake for method QueryParamClient.DeleteStandalone + // HTTP status codes to indicate success: http.StatusNoContent + DeleteStandalone func(ctx context.Context, options *clientinitdefaultgroup.QueryParamClientDeleteStandaloneOptions) (resp azfake.Responder[clientinitdefaultgroup.QueryParamClientDeleteStandaloneResponse], errResp azfake.ErrorResponder) + + // GetStandalone is the fake for method QueryParamClient.GetStandalone + // HTTP status codes to indicate success: http.StatusOK + GetStandalone func(ctx context.Context, options *clientinitdefaultgroup.QueryParamClientGetStandaloneOptions) (resp azfake.Responder[clientinitdefaultgroup.QueryParamClientGetStandaloneResponse], errResp azfake.ErrorResponder) + + // WithQuery is the fake for method QueryParamClient.WithQuery + // HTTP status codes to indicate success: http.StatusNoContent + WithQuery func(ctx context.Context, options *clientinitdefaultgroup.QueryParamClientWithQueryOptions) (resp azfake.Responder[clientinitdefaultgroup.QueryParamClientWithQueryResponse], errResp azfake.ErrorResponder) +} + +// NewQueryParamServerTransport creates a new instance of QueryParamServerTransport with the provided implementation. +// The returned QueryParamServerTransport instance is connected to an instance of clientinitdefaultgroup.QueryParamClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewQueryParamServerTransport(srv *QueryParamServer) *QueryParamServerTransport { + return &QueryParamServerTransport{srv: srv} +} + +// QueryParamServerTransport connects instances of clientinitdefaultgroup.QueryParamClient to instances of QueryParamServer. +// Don't use this type directly, use NewQueryParamServerTransport instead. +type QueryParamServerTransport struct { + srv *QueryParamServer +} + +// Do implements the policy.Transporter interface for QueryParamServerTransport. +func (q *QueryParamServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return q.dispatchToMethodFake(req, method) +} + +func (q *QueryParamServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if queryParamServerTransportInterceptor != nil { + res.resp, res.err, intercepted = queryParamServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "QueryParamClient.DeleteStandalone": + res.resp, res.err = q.dispatchDeleteStandalone(req) + case "QueryParamClient.GetStandalone": + res.resp, res.err = q.dispatchGetStandalone(req) + case "QueryParamClient.WithQuery": + res.resp, res.err = q.dispatchWithQuery(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (q *QueryParamServerTransport) dispatchDeleteStandalone(req *http.Request) (*http.Response, error) { + if q.srv.DeleteStandalone == nil { + return nil, &nonRetriableError{errors.New("fake for method DeleteStandalone not implemented")} + } + respr, errRespr := q.srv.DeleteStandalone(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (q *QueryParamServerTransport) dispatchGetStandalone(req *http.Request) (*http.Response, error) { + if q.srv.GetStandalone == nil { + return nil, &nonRetriableError{errors.New("fake for method GetStandalone not implemented")} + } + respr, errRespr := q.srv.GetStandalone(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BlobProperties, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (q *QueryParamServerTransport) dispatchWithQuery(req *http.Request) (*http.Response, error) { + if q.srv.WithQuery == nil { + return nil, &nonRetriableError{errors.New("fake for method WithQuery not implemented")} + } + qp := req.URL.Query() + formatParam := getOptional(qp.Get("format")) + var options *clientinitdefaultgroup.QueryParamClientWithQueryOptions + if formatParam != nil { + options = &clientinitdefaultgroup.QueryParamClientWithQueryOptions{ + Format: formatParam, + } + } + respr, errRespr := q.srv.WithQuery(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to QueryParamServerTransport +var queryParamServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/go.mod b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/go.mod new file mode 100644 index 000000000000..cd219ca33aef --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/go.mod @@ -0,0 +1,17 @@ +module clientinitdefaultgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/go.sum b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/headerparam_client_test.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/headerparam_client_test.go new file mode 100644 index 000000000000..557485f4aca8 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/headerparam_client_test.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package clientinitdefaultgroup_test + +import ( + "clientinitdefaultgroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestHeaderParamClient_WithQuery(t *testing.T) { + client, err := clientinitdefaultgroup.NewHeaderParamClientWithNoCredential("http://localhost:3000", "test-name-value", nil) + require.NoError(t, err) + resp, err := client.WithQuery(context.Background(), "test-id", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestHeaderParamClient_WithBody(t *testing.T) { + client, err := clientinitdefaultgroup.NewHeaderParamClientWithNoCredential("http://localhost:3000", "test-name-value", nil) + require.NoError(t, err) + resp, err := client.WithBody(context.Background(), clientinitdefaultgroup.Input{ + Name: to.Ptr("test-name"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/mixedparams_client_test.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/mixedparams_client_test.go new file mode 100644 index 000000000000..c7d0d817e67e --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/mixedparams_client_test.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package clientinitdefaultgroup_test + +import ( + "clientinitdefaultgroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestMixedParamsClient_WithQuery(t *testing.T) { + client, err := clientinitdefaultgroup.NewMixedParamsClientWithNoCredential("http://localhost:3000", "test-name-value", nil) + require.NoError(t, err) + resp, err := client.WithQuery(context.Background(), "us-west", "test-id", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestMixedParamsClient_WithBody(t *testing.T) { + client, err := clientinitdefaultgroup.NewMixedParamsClientWithNoCredential("http://localhost:3000", "test-name-value", nil) + require.NoError(t, err) + resp, err := client.WithBody(context.Background(), "us-west", clientinitdefaultgroup.WithBodyRequest{ + Name: to.Ptr("test-name"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/multipleparams_client_test.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/multipleparams_client_test.go new file mode 100644 index 000000000000..fb45141aef5d --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/multipleparams_client_test.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package clientinitdefaultgroup_test + +import ( + "clientinitdefaultgroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestMultipleParamsClient_WithQuery(t *testing.T) { + client, err := clientinitdefaultgroup.NewMultipleParamsClientWithNoCredential("http://localhost:3000", "test-name-value", "us-west", nil) + require.NoError(t, err) + resp, err := client.WithQuery(context.Background(), "test-id", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestMultipleParamsClient_WithBody(t *testing.T) { + client, err := clientinitdefaultgroup.NewMultipleParamsClientWithNoCredential("http://localhost:3000", "test-name-value", "us-west", nil) + require.NoError(t, err) + resp, err := client.WithBody(context.Background(), clientinitdefaultgroup.Input{ + Name: to.Ptr("test-name"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/paramalias_client_test.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/paramalias_client_test.go new file mode 100644 index 000000000000..2d4ffc67ff20 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/paramalias_client_test.go @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package clientinitdefaultgroup_test + +import ( + "clientinitdefaultgroup" + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestParamAliasClient_WithAliasedName(t *testing.T) { + client, err := clientinitdefaultgroup.NewParamAliasClientWithNoCredential("http://localhost:3000", "sample-blob", nil) + require.NoError(t, err) + resp, err := client.WithAliasedName(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParamAliasClient_WithOriginalName(t *testing.T) { + client, err := clientinitdefaultgroup.NewParamAliasClientWithNoCredential("http://localhost:3000", "sample-blob", nil) + require.NoError(t, err) + resp, err := client.WithOriginalName(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/pathparam_client_test.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/pathparam_client_test.go new file mode 100644 index 000000000000..91735383ba77 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/pathparam_client_test.go @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package clientinitdefaultgroup_test + +import ( + "clientinitdefaultgroup" + "context" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestPathParamClient_WithQuery(t *testing.T) { + client, err := clientinitdefaultgroup.NewPathParamClientWithNoCredential("http://localhost:3000", "sample-blob", nil) + require.NoError(t, err) + resp, err := client.WithQuery(context.Background(), &clientinitdefaultgroup.PathParamClientWithQueryOptions{ + Format: to.Ptr("text"), + }) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestPathParamClient_GetStandalone(t *testing.T) { + client, err := clientinitdefaultgroup.NewPathParamClientWithNoCredential("http://localhost:3000", "sample-blob", nil) + require.NoError(t, err) + resp, err := client.GetStandalone(context.Background(), nil) + require.NoError(t, err) + expectedTime, err := time.Parse(time.RFC3339, "2025-04-01T12:00:00Z") + require.NoError(t, err) + require.EqualValues(t, clientinitdefaultgroup.BlobProperties{ + Name: to.Ptr("sample-blob"), + Size: to.Ptr[int64](42), + ContentType: to.Ptr("text/plain"), + CreatedOn: to.Ptr(expectedTime), + }, resp.BlobProperties) +} + +func TestPathParamClient_DeleteStandalone(t *testing.T) { + client, err := clientinitdefaultgroup.NewPathParamClientWithNoCredential("http://localhost:3000", "sample-blob", nil) + require.NoError(t, err) + resp, err := client.DeleteStandalone(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/queryparam_client_test.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/queryparam_client_test.go new file mode 100644 index 000000000000..973cfadf7581 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/queryparam_client_test.go @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package clientinitdefaultgroup_test + +import ( + "clientinitdefaultgroup" + "context" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestQueryParamClient_WithQuery(t *testing.T) { + client, err := clientinitdefaultgroup.NewQueryParamClientWithNoCredential("http://localhost:3000", "test-blob", nil) + require.NoError(t, err) + resp, err := client.WithQuery(context.Background(), &clientinitdefaultgroup.QueryParamClientWithQueryOptions{ + Format: to.Ptr("text"), + }) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestQueryParamClient_GetStandalone(t *testing.T) { + client, err := clientinitdefaultgroup.NewQueryParamClientWithNoCredential("http://localhost:3000", "test-blob", nil) + require.NoError(t, err) + resp, err := client.GetStandalone(context.Background(), nil) + require.NoError(t, err) + expectedTime, err := time.Parse(time.RFC3339, "2025-04-01T12:00:00Z") + require.NoError(t, err) + require.EqualValues(t, clientinitdefaultgroup.BlobProperties{ + Name: to.Ptr("test-blob"), + Size: to.Ptr[int64](42), + ContentType: to.Ptr("text/plain"), + CreatedOn: to.Ptr(expectedTime), + }, resp.BlobProperties) +} + +func TestQueryParamClient_DeleteStandalone(t *testing.T) { + client, err := clientinitdefaultgroup.NewQueryParamClientWithNoCredential("http://localhost:3000", "test-blob", nil) + require.NoError(t, err) + resp, err := client.DeleteStandalone(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/testdata/_metadata.json b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_headerparam_client.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_headerparam_client.go new file mode 100644 index 000000000000..30b680f47eb6 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_headerparam_client.go @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitdefaultgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// HeaderParamClient - Client for testing header parameter moved to client level. +// Don't use this type directly, use NewHeaderParamClientWithNoCredential() instead. +type HeaderParamClient struct { + internal *azcore.Client + endpoint string + name string +} + +// HeaderParamClientOptions contains the optional values for creating a [HeaderParamClient]. +type HeaderParamClientOptions struct { + azcore.ClientOptions +} + +// NewHeaderParamClientWithNoCredential creates a new instance of HeaderParamClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewHeaderParamClientWithNoCredential(endpoint string, name string, options *HeaderParamClientOptions) (*HeaderParamClient, error) { + if options == nil { + options = &HeaderParamClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &HeaderParamClient{ + endpoint: endpoint, + name: name, + internal: cl, + } + return client, nil +} + +// WithBody - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - HeaderParamClientWithBodyOptions contains the optional parameters for the HeaderParamClient.WithBody method. +func (client *HeaderParamClient) WithBody(ctx context.Context, body Input, options *HeaderParamClientWithBodyOptions) (HeaderParamClientWithBodyResponse, error) { + var err error + const operationName = "HeaderParamClient.WithBody" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withBodyCreateRequest(ctx, body, options) + if err != nil { + return HeaderParamClientWithBodyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return HeaderParamClientWithBodyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return HeaderParamClientWithBodyResponse{}, err + } + return HeaderParamClientWithBodyResponse{}, nil +} + +// withBodyCreateRequest creates the WithBody request. +func (client *HeaderParamClient) withBodyCreateRequest(ctx context.Context, body Input, _ *HeaderParamClientWithBodyOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/default/header-param/with-body" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["name"] = []string{client.name} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithQuery - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - HeaderParamClientWithQueryOptions contains the optional parameters for the HeaderParamClient.WithQuery method. +func (client *HeaderParamClient) WithQuery(ctx context.Context, id string, options *HeaderParamClientWithQueryOptions) (HeaderParamClientWithQueryResponse, error) { + var err error + const operationName = "HeaderParamClient.WithQuery" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withQueryCreateRequest(ctx, id, options) + if err != nil { + return HeaderParamClientWithQueryResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return HeaderParamClientWithQueryResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return HeaderParamClientWithQueryResponse{}, err + } + return HeaderParamClientWithQueryResponse{}, nil +} + +// withQueryCreateRequest creates the WithQuery request. +func (client *HeaderParamClient) withQueryCreateRequest(ctx context.Context, id string, _ *HeaderParamClientWithQueryOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/default/header-param/with-query" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("id", id) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["name"] = []string{client.name} + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_mixedparams_client.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_mixedparams_client.go new file mode 100644 index 000000000000..5a1b4e3b8f09 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_mixedparams_client.go @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitdefaultgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// MixedParamsClient - Client for testing a mix of client-level and method-level parameters. +// Don't use this type directly, use NewMixedParamsClientWithNoCredential() instead. +type MixedParamsClient struct { + internal *azcore.Client + endpoint string + name string +} + +// MixedParamsClientOptions contains the optional values for creating a [MixedParamsClient]. +type MixedParamsClientOptions struct { + azcore.ClientOptions +} + +// NewMixedParamsClientWithNoCredential creates a new instance of MixedParamsClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewMixedParamsClientWithNoCredential(endpoint string, name string, options *MixedParamsClientOptions) (*MixedParamsClient, error) { + if options == nil { + options = &MixedParamsClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &MixedParamsClient{ + endpoint: endpoint, + name: name, + internal: cl, + } + return client, nil +} + +// WithBody - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MixedParamsClientWithBodyOptions contains the optional parameters for the MixedParamsClient.WithBody method. +func (client *MixedParamsClient) WithBody(ctx context.Context, region string, body WithBodyRequest, options *MixedParamsClientWithBodyOptions) (MixedParamsClientWithBodyResponse, error) { + var err error + const operationName = "MixedParamsClient.WithBody" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withBodyCreateRequest(ctx, region, body, options) + if err != nil { + return MixedParamsClientWithBodyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MixedParamsClientWithBodyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MixedParamsClientWithBodyResponse{}, err + } + return MixedParamsClientWithBodyResponse{}, nil +} + +// withBodyCreateRequest creates the WithBody request. +func (client *MixedParamsClient) withBodyCreateRequest(ctx context.Context, region string, body WithBodyRequest, _ *MixedParamsClientWithBodyOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/default/mixed-params/with-body" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("region", region) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["name"] = []string{client.name} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithQuery - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MixedParamsClientWithQueryOptions contains the optional parameters for the MixedParamsClient.WithQuery method. +func (client *MixedParamsClient) WithQuery(ctx context.Context, region string, id string, options *MixedParamsClientWithQueryOptions) (MixedParamsClientWithQueryResponse, error) { + var err error + const operationName = "MixedParamsClient.WithQuery" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withQueryCreateRequest(ctx, region, id, options) + if err != nil { + return MixedParamsClientWithQueryResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MixedParamsClientWithQueryResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MixedParamsClientWithQueryResponse{}, err + } + return MixedParamsClientWithQueryResponse{}, nil +} + +// withQueryCreateRequest creates the WithQuery request. +func (client *MixedParamsClient) withQueryCreateRequest(ctx context.Context, region string, id string, _ *MixedParamsClientWithQueryOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/default/mixed-params/with-query" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("id", id) + reqQP.Set("region", region) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["name"] = []string{client.name} + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_models.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_models.go new file mode 100644 index 000000000000..05dc5e72558d --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_models.go @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitdefaultgroup + +import "time" + +// BlobProperties - Properties of a blob +type BlobProperties struct { + // REQUIRED + ContentType *string + + // REQUIRED + CreatedOn *time.Time + + // REQUIRED + Name *string + + // REQUIRED + Size *int64 +} + +type Input struct { + // REQUIRED + Name *string +} + +type WithBodyRequest struct { + // REQUIRED + Name *string +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_models_serde.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_models_serde.go new file mode 100644 index 000000000000..2e3ae9c4c4cd --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_models_serde.go @@ -0,0 +1,155 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitdefaultgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type BlobProperties. +func (b BlobProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "contentType", b.ContentType) + populateTime[datetime.RFC3339](objectMap, "createdOn", b.CreatedOn) + populate(objectMap, "name", b.Name) + populate(objectMap, "size", b.Size) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BlobProperties. +func (b *BlobProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "contentType": + err = unpopulate(val, "ContentType", &b.ContentType) + delete(rawMsg, key) + case "createdOn": + err = unpopulateTime[datetime.RFC3339](val, "CreatedOn", &b.CreatedOn) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &b.Name) + delete(rawMsg, key) + case "size": + err = unpopulate(val, "Size", &b.Size) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Input. +func (i Input) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", i.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Input. +func (i *Input) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &i.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type WithBodyRequest. +func (w WithBodyRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", w.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WithBodyRequest. +func (w *WithBodyRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &w.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_multipleparams_client.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_multipleparams_client.go new file mode 100644 index 000000000000..a8b969ba192e --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_multipleparams_client.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitdefaultgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// MultipleParamsClient - Client for testing multiple parameters (header and query) moved to client level. +// Don't use this type directly, use NewMultipleParamsClientWithNoCredential() instead. +type MultipleParamsClient struct { + internal *azcore.Client + endpoint string + name string + region string +} + +// MultipleParamsClientOptions contains the optional values for creating a [MultipleParamsClient]. +type MultipleParamsClientOptions struct { + azcore.ClientOptions +} + +// NewMultipleParamsClientWithNoCredential creates a new instance of MultipleParamsClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewMultipleParamsClientWithNoCredential(endpoint string, name string, region string, options *MultipleParamsClientOptions) (*MultipleParamsClient, error) { + if options == nil { + options = &MultipleParamsClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &MultipleParamsClient{ + endpoint: endpoint, + name: name, + region: region, + internal: cl, + } + return client, nil +} + +// WithBody - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MultipleParamsClientWithBodyOptions contains the optional parameters for the MultipleParamsClient.WithBody method. +func (client *MultipleParamsClient) WithBody(ctx context.Context, body Input, options *MultipleParamsClientWithBodyOptions) (MultipleParamsClientWithBodyResponse, error) { + var err error + const operationName = "MultipleParamsClient.WithBody" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withBodyCreateRequest(ctx, body, options) + if err != nil { + return MultipleParamsClientWithBodyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MultipleParamsClientWithBodyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MultipleParamsClientWithBodyResponse{}, err + } + return MultipleParamsClientWithBodyResponse{}, nil +} + +// withBodyCreateRequest creates the WithBody request. +func (client *MultipleParamsClient) withBodyCreateRequest(ctx context.Context, body Input, _ *MultipleParamsClientWithBodyOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/default/multiple-params/with-body" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("region", client.region) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["name"] = []string{client.name} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithQuery - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MultipleParamsClientWithQueryOptions contains the optional parameters for the MultipleParamsClient.WithQuery +// method. +func (client *MultipleParamsClient) WithQuery(ctx context.Context, id string, options *MultipleParamsClientWithQueryOptions) (MultipleParamsClientWithQueryResponse, error) { + var err error + const operationName = "MultipleParamsClient.WithQuery" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withQueryCreateRequest(ctx, id, options) + if err != nil { + return MultipleParamsClientWithQueryResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MultipleParamsClientWithQueryResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MultipleParamsClientWithQueryResponse{}, err + } + return MultipleParamsClientWithQueryResponse{}, nil +} + +// withQueryCreateRequest creates the WithQuery request. +func (client *MultipleParamsClient) withQueryCreateRequest(ctx context.Context, id string, _ *MultipleParamsClientWithQueryOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/default/multiple-params/with-query" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("id", id) + reqQP.Set("region", client.region) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["name"] = []string{client.name} + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_options.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_options.go new file mode 100644 index 000000000000..1a784c1e7426 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_options.go @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitdefaultgroup + +// HeaderParamClientWithBodyOptions contains the optional parameters for the HeaderParamClient.WithBody method. +type HeaderParamClientWithBodyOptions struct { + // placeholder for future optional parameters +} + +// HeaderParamClientWithQueryOptions contains the optional parameters for the HeaderParamClient.WithQuery method. +type HeaderParamClientWithQueryOptions struct { + // placeholder for future optional parameters +} + +// MixedParamsClientWithBodyOptions contains the optional parameters for the MixedParamsClient.WithBody method. +type MixedParamsClientWithBodyOptions struct { + // placeholder for future optional parameters +} + +// MixedParamsClientWithQueryOptions contains the optional parameters for the MixedParamsClient.WithQuery method. +type MixedParamsClientWithQueryOptions struct { + // placeholder for future optional parameters +} + +// MultipleParamsClientWithBodyOptions contains the optional parameters for the MultipleParamsClient.WithBody method. +type MultipleParamsClientWithBodyOptions struct { + // placeholder for future optional parameters +} + +// MultipleParamsClientWithQueryOptions contains the optional parameters for the MultipleParamsClient.WithQuery method. +type MultipleParamsClientWithQueryOptions struct { + // placeholder for future optional parameters +} + +// ParamAliasClientWithAliasedNameOptions contains the optional parameters for the ParamAliasClient.WithAliasedName method. +type ParamAliasClientWithAliasedNameOptions struct { + // placeholder for future optional parameters +} + +// ParamAliasClientWithOriginalNameOptions contains the optional parameters for the ParamAliasClient.WithOriginalName method. +type ParamAliasClientWithOriginalNameOptions struct { + // placeholder for future optional parameters +} + +// PathParamClientDeleteStandaloneOptions contains the optional parameters for the PathParamClient.DeleteStandalone method. +type PathParamClientDeleteStandaloneOptions struct { + // placeholder for future optional parameters +} + +// PathParamClientGetStandaloneOptions contains the optional parameters for the PathParamClient.GetStandalone method. +type PathParamClientGetStandaloneOptions struct { + // placeholder for future optional parameters +} + +// PathParamClientWithQueryOptions contains the optional parameters for the PathParamClient.WithQuery method. +type PathParamClientWithQueryOptions struct { + Format *string +} + +// QueryParamClientDeleteStandaloneOptions contains the optional parameters for the QueryParamClient.DeleteStandalone method. +type QueryParamClientDeleteStandaloneOptions struct { + // placeholder for future optional parameters +} + +// QueryParamClientGetStandaloneOptions contains the optional parameters for the QueryParamClient.GetStandalone method. +type QueryParamClientGetStandaloneOptions struct { + // placeholder for future optional parameters +} + +// QueryParamClientWithQueryOptions contains the optional parameters for the QueryParamClient.WithQuery method. +type QueryParamClientWithQueryOptions struct { + Format *string +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_paramalias_client.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_paramalias_client.go new file mode 100644 index 000000000000..e00ebd594145 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_paramalias_client.go @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitdefaultgroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ParamAliasClient - Operations demonstrating the @paramAlias decorator for renaming parameters in client code +// Don't use this type directly, use NewParamAliasClientWithNoCredential() instead. +type ParamAliasClient struct { + internal *azcore.Client + blobName string + endpoint string +} + +// ParamAliasClientOptions contains the optional values for creating a [ParamAliasClient]. +type ParamAliasClientOptions struct { + azcore.ClientOptions +} + +// NewParamAliasClientWithNoCredential creates a new instance of ParamAliasClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewParamAliasClientWithNoCredential(endpoint string, blobName string, options *ParamAliasClientOptions) (*ParamAliasClient, error) { + if options == nil { + options = &ParamAliasClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &ParamAliasClient{ + blobName: blobName, + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// WithAliasedName - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ParamAliasClientWithAliasedNameOptions contains the optional parameters for the ParamAliasClient.WithAliasedName +// method. +func (client *ParamAliasClient) WithAliasedName(ctx context.Context, options *ParamAliasClientWithAliasedNameOptions) (ParamAliasClientWithAliasedNameResponse, error) { + var err error + const operationName = "ParamAliasClient.WithAliasedName" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withAliasedNameCreateRequest(ctx, options) + if err != nil { + return ParamAliasClientWithAliasedNameResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ParamAliasClientWithAliasedNameResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ParamAliasClientWithAliasedNameResponse{}, err + } + return ParamAliasClientWithAliasedNameResponse{}, nil +} + +// withAliasedNameCreateRequest creates the WithAliasedName request. +func (client *ParamAliasClient) withAliasedNameCreateRequest(ctx context.Context, _ *ParamAliasClientWithAliasedNameOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/default/param-alias/{blob}/with-aliased-name" + if client.blobName == "" { + return nil, errors.New("parameter client.blobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{blob}", url.PathEscape(client.blobName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// WithOriginalName - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ParamAliasClientWithOriginalNameOptions contains the optional parameters for the ParamAliasClient.WithOriginalName +// method. +func (client *ParamAliasClient) WithOriginalName(ctx context.Context, options *ParamAliasClientWithOriginalNameOptions) (ParamAliasClientWithOriginalNameResponse, error) { + var err error + const operationName = "ParamAliasClient.WithOriginalName" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withOriginalNameCreateRequest(ctx, options) + if err != nil { + return ParamAliasClientWithOriginalNameResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ParamAliasClientWithOriginalNameResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ParamAliasClientWithOriginalNameResponse{}, err + } + return ParamAliasClientWithOriginalNameResponse{}, nil +} + +// withOriginalNameCreateRequest creates the WithOriginalName request. +func (client *ParamAliasClient) withOriginalNameCreateRequest(ctx context.Context, _ *ParamAliasClientWithOriginalNameOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/default/param-alias/{blobName}/with-original-name" + if client.blobName == "" { + return nil, errors.New("parameter client.blobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{blobName}", url.PathEscape(client.blobName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_pathparam_client.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_pathparam_client.go new file mode 100644 index 000000000000..b0f95c5e3163 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_pathparam_client.go @@ -0,0 +1,179 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitdefaultgroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// PathParamClient - Blob operations with path parameter that should be moved to client level +// Don't use this type directly, use NewPathParamClientWithNoCredential() instead. +type PathParamClient struct { + internal *azcore.Client + blobName string + endpoint string +} + +// PathParamClientOptions contains the optional values for creating a [PathParamClient]. +type PathParamClientOptions struct { + azcore.ClientOptions +} + +// NewPathParamClientWithNoCredential creates a new instance of PathParamClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewPathParamClientWithNoCredential(endpoint string, blobName string, options *PathParamClientOptions) (*PathParamClient, error) { + if options == nil { + options = &PathParamClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &PathParamClient{ + blobName: blobName, + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// DeleteStandalone - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - PathParamClientDeleteStandaloneOptions contains the optional parameters for the PathParamClient.DeleteStandalone +// method. +func (client *PathParamClient) DeleteStandalone(ctx context.Context, options *PathParamClientDeleteStandaloneOptions) (PathParamClientDeleteStandaloneResponse, error) { + var err error + const operationName = "PathParamClient.DeleteStandalone" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteStandaloneCreateRequest(ctx, options) + if err != nil { + return PathParamClientDeleteStandaloneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PathParamClientDeleteStandaloneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return PathParamClientDeleteStandaloneResponse{}, err + } + return PathParamClientDeleteStandaloneResponse{}, nil +} + +// deleteStandaloneCreateRequest creates the DeleteStandalone request. +func (client *PathParamClient) deleteStandaloneCreateRequest(ctx context.Context, _ *PathParamClientDeleteStandaloneOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/default/path/{blobName}" + if client.blobName == "" { + return nil, errors.New("parameter client.blobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{blobName}", url.PathEscape(client.blobName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// GetStandalone - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - PathParamClientGetStandaloneOptions contains the optional parameters for the PathParamClient.GetStandalone method. +func (client *PathParamClient) GetStandalone(ctx context.Context, options *PathParamClientGetStandaloneOptions) (PathParamClientGetStandaloneResponse, error) { + var err error + const operationName = "PathParamClient.GetStandalone" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getStandaloneCreateRequest(ctx, options) + if err != nil { + return PathParamClientGetStandaloneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PathParamClientGetStandaloneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PathParamClientGetStandaloneResponse{}, err + } + resp, err := client.getStandaloneHandleResponse(httpResp) + return resp, err +} + +// getStandaloneCreateRequest creates the GetStandalone request. +func (client *PathParamClient) getStandaloneCreateRequest(ctx context.Context, _ *PathParamClientGetStandaloneOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/default/path/{blobName}/get-standalone" + if client.blobName == "" { + return nil, errors.New("parameter client.blobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{blobName}", url.PathEscape(client.blobName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getStandaloneHandleResponse handles the GetStandalone response. +func (client *PathParamClient) getStandaloneHandleResponse(resp *http.Response) (PathParamClientGetStandaloneResponse, error) { + result := PathParamClientGetStandaloneResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BlobProperties); err != nil { + return PathParamClientGetStandaloneResponse{}, err + } + return result, nil +} + +// WithQuery - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - PathParamClientWithQueryOptions contains the optional parameters for the PathParamClient.WithQuery method. +func (client *PathParamClient) WithQuery(ctx context.Context, options *PathParamClientWithQueryOptions) (PathParamClientWithQueryResponse, error) { + var err error + const operationName = "PathParamClient.WithQuery" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withQueryCreateRequest(ctx, options) + if err != nil { + return PathParamClientWithQueryResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PathParamClientWithQueryResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return PathParamClientWithQueryResponse{}, err + } + return PathParamClientWithQueryResponse{}, nil +} + +// withQueryCreateRequest creates the WithQuery request. +func (client *PathParamClient) withQueryCreateRequest(ctx context.Context, options *PathParamClientWithQueryOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/default/path/{blobName}/with-query" + if client.blobName == "" { + return nil, errors.New("parameter client.blobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{blobName}", url.PathEscape(client.blobName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Format != nil { + reqQP.Set("format", *options.Format) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_queryparam_client.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_queryparam_client.go new file mode 100644 index 000000000000..79f68f5de52d --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_queryparam_client.go @@ -0,0 +1,173 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitdefaultgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// QueryParamClient - Blob operations with query parameter that should be moved to client level +// Don't use this type directly, use NewQueryParamClientWithNoCredential() instead. +type QueryParamClient struct { + internal *azcore.Client + blobName string + endpoint string +} + +// QueryParamClientOptions contains the optional values for creating a [QueryParamClient]. +type QueryParamClientOptions struct { + azcore.ClientOptions +} + +// NewQueryParamClientWithNoCredential creates a new instance of QueryParamClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewQueryParamClientWithNoCredential(endpoint string, blobName string, options *QueryParamClientOptions) (*QueryParamClient, error) { + if options == nil { + options = &QueryParamClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &QueryParamClient{ + blobName: blobName, + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// DeleteStandalone - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - QueryParamClientDeleteStandaloneOptions contains the optional parameters for the QueryParamClient.DeleteStandalone +// method. +func (client *QueryParamClient) DeleteStandalone(ctx context.Context, options *QueryParamClientDeleteStandaloneOptions) (QueryParamClientDeleteStandaloneResponse, error) { + var err error + const operationName = "QueryParamClient.DeleteStandalone" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteStandaloneCreateRequest(ctx, options) + if err != nil { + return QueryParamClientDeleteStandaloneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return QueryParamClientDeleteStandaloneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return QueryParamClientDeleteStandaloneResponse{}, err + } + return QueryParamClientDeleteStandaloneResponse{}, nil +} + +// deleteStandaloneCreateRequest creates the DeleteStandalone request. +func (client *QueryParamClient) deleteStandaloneCreateRequest(ctx context.Context, _ *QueryParamClientDeleteStandaloneOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/default/query/delete-resource" + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("blobName", client.blobName) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// GetStandalone - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - QueryParamClientGetStandaloneOptions contains the optional parameters for the QueryParamClient.GetStandalone +// method. +func (client *QueryParamClient) GetStandalone(ctx context.Context, options *QueryParamClientGetStandaloneOptions) (QueryParamClientGetStandaloneResponse, error) { + var err error + const operationName = "QueryParamClient.GetStandalone" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getStandaloneCreateRequest(ctx, options) + if err != nil { + return QueryParamClientGetStandaloneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return QueryParamClientGetStandaloneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return QueryParamClientGetStandaloneResponse{}, err + } + resp, err := client.getStandaloneHandleResponse(httpResp) + return resp, err +} + +// getStandaloneCreateRequest creates the GetStandalone request. +func (client *QueryParamClient) getStandaloneCreateRequest(ctx context.Context, _ *QueryParamClientGetStandaloneOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/default/query/get-standalone" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("blobName", client.blobName) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getStandaloneHandleResponse handles the GetStandalone response. +func (client *QueryParamClient) getStandaloneHandleResponse(resp *http.Response) (QueryParamClientGetStandaloneResponse, error) { + result := QueryParamClientGetStandaloneResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BlobProperties); err != nil { + return QueryParamClientGetStandaloneResponse{}, err + } + return result, nil +} + +// WithQuery - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - QueryParamClientWithQueryOptions contains the optional parameters for the QueryParamClient.WithQuery method. +func (client *QueryParamClient) WithQuery(ctx context.Context, options *QueryParamClientWithQueryOptions) (QueryParamClientWithQueryResponse, error) { + var err error + const operationName = "QueryParamClient.WithQuery" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withQueryCreateRequest(ctx, options) + if err != nil { + return QueryParamClientWithQueryResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return QueryParamClientWithQueryResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return QueryParamClientWithQueryResponse{}, err + } + return QueryParamClientWithQueryResponse{}, nil +} + +// withQueryCreateRequest creates the WithQuery request. +func (client *QueryParamClient) withQueryCreateRequest(ctx context.Context, options *QueryParamClientWithQueryOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/default/query/with-query" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("blobName", client.blobName) + if options != nil && options.Format != nil { + reqQP.Set("format", *options.Format) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_responses.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_responses.go new file mode 100644 index 000000000000..fc35285e713d --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_responses.go @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitdefaultgroup + +// HeaderParamClientWithBodyResponse contains the response from method HeaderParamClient.WithBody. +type HeaderParamClientWithBodyResponse struct { + // placeholder for future response values +} + +// HeaderParamClientWithQueryResponse contains the response from method HeaderParamClient.WithQuery. +type HeaderParamClientWithQueryResponse struct { + // placeholder for future response values +} + +// MixedParamsClientWithBodyResponse contains the response from method MixedParamsClient.WithBody. +type MixedParamsClientWithBodyResponse struct { + // placeholder for future response values +} + +// MixedParamsClientWithQueryResponse contains the response from method MixedParamsClient.WithQuery. +type MixedParamsClientWithQueryResponse struct { + // placeholder for future response values +} + +// MultipleParamsClientWithBodyResponse contains the response from method MultipleParamsClient.WithBody. +type MultipleParamsClientWithBodyResponse struct { + // placeholder for future response values +} + +// MultipleParamsClientWithQueryResponse contains the response from method MultipleParamsClient.WithQuery. +type MultipleParamsClientWithQueryResponse struct { + // placeholder for future response values +} + +// ParamAliasClientWithAliasedNameResponse contains the response from method ParamAliasClient.WithAliasedName. +type ParamAliasClientWithAliasedNameResponse struct { + // placeholder for future response values +} + +// ParamAliasClientWithOriginalNameResponse contains the response from method ParamAliasClient.WithOriginalName. +type ParamAliasClientWithOriginalNameResponse struct { + // placeholder for future response values +} + +// PathParamClientDeleteStandaloneResponse contains the response from method PathParamClient.DeleteStandalone. +type PathParamClientDeleteStandaloneResponse struct { + // placeholder for future response values +} + +// PathParamClientGetStandaloneResponse contains the response from method PathParamClient.GetStandalone. +type PathParamClientGetStandaloneResponse struct { + // Properties of a blob + BlobProperties +} + +// PathParamClientWithQueryResponse contains the response from method PathParamClient.WithQuery. +type PathParamClientWithQueryResponse struct { + // placeholder for future response values +} + +// QueryParamClientDeleteStandaloneResponse contains the response from method QueryParamClient.DeleteStandalone. +type QueryParamClientDeleteStandaloneResponse struct { + // placeholder for future response values +} + +// QueryParamClientGetStandaloneResponse contains the response from method QueryParamClient.GetStandalone. +type QueryParamClientGetStandaloneResponse struct { + // Properties of a blob + BlobProperties +} + +// QueryParamClientWithQueryResponse contains the response from method QueryParamClient.WithQuery. +type QueryParamClientWithQueryResponse struct { + // placeholder for future response values +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_version.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_version.go new file mode 100644 index 000000000000..a2211041cc92 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitdefaultgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package clientinitdefaultgroup + +const ( + moduleName = "clientinitdefaultgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/LICENSE.txt b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_individuallynestedwithheader_server.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_individuallynestedwithheader_server.go new file mode 100644 index 000000000000..adc7cffa2f8e --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_individuallynestedwithheader_server.go @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "clientinitindividuallygroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// IndividuallyNestedWithHeaderServer is a fake server for instances of the clientinitindividuallygroup.IndividuallyNestedWithHeaderClient type. +type IndividuallyNestedWithHeaderServer struct { + // DeleteStandalone is the fake for method IndividuallyNestedWithHeaderClient.DeleteStandalone + // HTTP status codes to indicate success: http.StatusNoContent + DeleteStandalone func(ctx context.Context, options *clientinitindividuallygroup.IndividuallyNestedWithHeaderClientDeleteStandaloneOptions) (resp azfake.Responder[clientinitindividuallygroup.IndividuallyNestedWithHeaderClientDeleteStandaloneResponse], errResp azfake.ErrorResponder) + + // GetStandalone is the fake for method IndividuallyNestedWithHeaderClient.GetStandalone + // HTTP status codes to indicate success: http.StatusNoContent + GetStandalone func(ctx context.Context, options *clientinitindividuallygroup.IndividuallyNestedWithHeaderClientGetStandaloneOptions) (resp azfake.Responder[clientinitindividuallygroup.IndividuallyNestedWithHeaderClientGetStandaloneResponse], errResp azfake.ErrorResponder) + + // WithQuery is the fake for method IndividuallyNestedWithHeaderClient.WithQuery + // HTTP status codes to indicate success: http.StatusNoContent + WithQuery func(ctx context.Context, options *clientinitindividuallygroup.IndividuallyNestedWithHeaderClientWithQueryOptions) (resp azfake.Responder[clientinitindividuallygroup.IndividuallyNestedWithHeaderClientWithQueryResponse], errResp azfake.ErrorResponder) +} + +// NewIndividuallyNestedWithHeaderServerTransport creates a new instance of IndividuallyNestedWithHeaderServerTransport with the provided implementation. +// The returned IndividuallyNestedWithHeaderServerTransport instance is connected to an instance of clientinitindividuallygroup.IndividuallyNestedWithHeaderClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewIndividuallyNestedWithHeaderServerTransport(srv *IndividuallyNestedWithHeaderServer) *IndividuallyNestedWithHeaderServerTransport { + return &IndividuallyNestedWithHeaderServerTransport{srv: srv} +} + +// IndividuallyNestedWithHeaderServerTransport connects instances of clientinitindividuallygroup.IndividuallyNestedWithHeaderClient to instances of IndividuallyNestedWithHeaderServer. +// Don't use this type directly, use NewIndividuallyNestedWithHeaderServerTransport instead. +type IndividuallyNestedWithHeaderServerTransport struct { + srv *IndividuallyNestedWithHeaderServer +} + +// Do implements the policy.Transporter interface for IndividuallyNestedWithHeaderServerTransport. +func (i *IndividuallyNestedWithHeaderServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return i.dispatchToMethodFake(req, method) +} + +func (i *IndividuallyNestedWithHeaderServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if individuallyNestedWithHeaderServerTransportInterceptor != nil { + res.resp, res.err, intercepted = individuallyNestedWithHeaderServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "IndividuallyNestedWithHeaderClient.DeleteStandalone": + res.resp, res.err = i.dispatchDeleteStandalone(req) + case "IndividuallyNestedWithHeaderClient.GetStandalone": + res.resp, res.err = i.dispatchGetStandalone(req) + case "IndividuallyNestedWithHeaderClient.WithQuery": + res.resp, res.err = i.dispatchWithQuery(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (i *IndividuallyNestedWithHeaderServerTransport) dispatchDeleteStandalone(req *http.Request) (*http.Response, error) { + if i.srv.DeleteStandalone == nil { + return nil, &nonRetriableError{errors.New("fake for method DeleteStandalone not implemented")} + } + respr, errRespr := i.srv.DeleteStandalone(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (i *IndividuallyNestedWithHeaderServerTransport) dispatchGetStandalone(req *http.Request) (*http.Response, error) { + if i.srv.GetStandalone == nil { + return nil, &nonRetriableError{errors.New("fake for method GetStandalone not implemented")} + } + respr, errRespr := i.srv.GetStandalone(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (i *IndividuallyNestedWithHeaderServerTransport) dispatchWithQuery(req *http.Request) (*http.Response, error) { + if i.srv.WithQuery == nil { + return nil, &nonRetriableError{errors.New("fake for method WithQuery not implemented")} + } + qp := req.URL.Query() + formatParam := getOptional(qp.Get("format")) + var options *clientinitindividuallygroup.IndividuallyNestedWithHeaderClientWithQueryOptions + if formatParam != nil { + options = &clientinitindividuallygroup.IndividuallyNestedWithHeaderClientWithQueryOptions{ + Format: formatParam, + } + } + respr, errRespr := i.srv.WithQuery(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to IndividuallyNestedWithHeaderServerTransport +var individuallyNestedWithHeaderServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_individuallynestedwithmixed_server.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_individuallynestedwithmixed_server.go new file mode 100644 index 000000000000..ca1e834136d7 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_individuallynestedwithmixed_server.go @@ -0,0 +1,161 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "clientinitindividuallygroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// IndividuallyNestedWithMixedServer is a fake server for instances of the clientinitindividuallygroup.IndividuallyNestedWithMixedClient type. +type IndividuallyNestedWithMixedServer struct { + // DeleteStandalone is the fake for method IndividuallyNestedWithMixedClient.DeleteStandalone + // HTTP status codes to indicate success: http.StatusNoContent + DeleteStandalone func(ctx context.Context, region string, options *clientinitindividuallygroup.IndividuallyNestedWithMixedClientDeleteStandaloneOptions) (resp azfake.Responder[clientinitindividuallygroup.IndividuallyNestedWithMixedClientDeleteStandaloneResponse], errResp azfake.ErrorResponder) + + // GetStandalone is the fake for method IndividuallyNestedWithMixedClient.GetStandalone + // HTTP status codes to indicate success: http.StatusNoContent + GetStandalone func(ctx context.Context, region string, options *clientinitindividuallygroup.IndividuallyNestedWithMixedClientGetStandaloneOptions) (resp azfake.Responder[clientinitindividuallygroup.IndividuallyNestedWithMixedClientGetStandaloneResponse], errResp azfake.ErrorResponder) + + // WithQuery is the fake for method IndividuallyNestedWithMixedClient.WithQuery + // HTTP status codes to indicate success: http.StatusNoContent + WithQuery func(ctx context.Context, region string, options *clientinitindividuallygroup.IndividuallyNestedWithMixedClientWithQueryOptions) (resp azfake.Responder[clientinitindividuallygroup.IndividuallyNestedWithMixedClientWithQueryResponse], errResp azfake.ErrorResponder) +} + +// NewIndividuallyNestedWithMixedServerTransport creates a new instance of IndividuallyNestedWithMixedServerTransport with the provided implementation. +// The returned IndividuallyNestedWithMixedServerTransport instance is connected to an instance of clientinitindividuallygroup.IndividuallyNestedWithMixedClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewIndividuallyNestedWithMixedServerTransport(srv *IndividuallyNestedWithMixedServer) *IndividuallyNestedWithMixedServerTransport { + return &IndividuallyNestedWithMixedServerTransport{srv: srv} +} + +// IndividuallyNestedWithMixedServerTransport connects instances of clientinitindividuallygroup.IndividuallyNestedWithMixedClient to instances of IndividuallyNestedWithMixedServer. +// Don't use this type directly, use NewIndividuallyNestedWithMixedServerTransport instead. +type IndividuallyNestedWithMixedServerTransport struct { + srv *IndividuallyNestedWithMixedServer +} + +// Do implements the policy.Transporter interface for IndividuallyNestedWithMixedServerTransport. +func (i *IndividuallyNestedWithMixedServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return i.dispatchToMethodFake(req, method) +} + +func (i *IndividuallyNestedWithMixedServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if individuallyNestedWithMixedServerTransportInterceptor != nil { + res.resp, res.err, intercepted = individuallyNestedWithMixedServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "IndividuallyNestedWithMixedClient.DeleteStandalone": + res.resp, res.err = i.dispatchDeleteStandalone(req) + case "IndividuallyNestedWithMixedClient.GetStandalone": + res.resp, res.err = i.dispatchGetStandalone(req) + case "IndividuallyNestedWithMixedClient.WithQuery": + res.resp, res.err = i.dispatchWithQuery(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (i *IndividuallyNestedWithMixedServerTransport) dispatchDeleteStandalone(req *http.Request) (*http.Response, error) { + if i.srv.DeleteStandalone == nil { + return nil, &nonRetriableError{errors.New("fake for method DeleteStandalone not implemented")} + } + qp := req.URL.Query() + respr, errRespr := i.srv.DeleteStandalone(req.Context(), qp.Get("region"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (i *IndividuallyNestedWithMixedServerTransport) dispatchGetStandalone(req *http.Request) (*http.Response, error) { + if i.srv.GetStandalone == nil { + return nil, &nonRetriableError{errors.New("fake for method GetStandalone not implemented")} + } + qp := req.URL.Query() + respr, errRespr := i.srv.GetStandalone(req.Context(), qp.Get("region"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (i *IndividuallyNestedWithMixedServerTransport) dispatchWithQuery(req *http.Request) (*http.Response, error) { + if i.srv.WithQuery == nil { + return nil, &nonRetriableError{errors.New("fake for method WithQuery not implemented")} + } + qp := req.URL.Query() + formatParam := getOptional(qp.Get("format")) + var options *clientinitindividuallygroup.IndividuallyNestedWithMixedClientWithQueryOptions + if formatParam != nil { + options = &clientinitindividuallygroup.IndividuallyNestedWithMixedClientWithQueryOptions{ + Format: formatParam, + } + } + respr, errRespr := i.srv.WithQuery(req.Context(), qp.Get("region"), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to IndividuallyNestedWithMixedServerTransport +var individuallyNestedWithMixedServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_individuallynestedwithmultiple_server.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_individuallynestedwithmultiple_server.go new file mode 100644 index 000000000000..af8f78c4e53d --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_individuallynestedwithmultiple_server.go @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "clientinitindividuallygroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// IndividuallyNestedWithMultipleServer is a fake server for instances of the clientinitindividuallygroup.IndividuallyNestedWithMultipleClient type. +type IndividuallyNestedWithMultipleServer struct { + // DeleteStandalone is the fake for method IndividuallyNestedWithMultipleClient.DeleteStandalone + // HTTP status codes to indicate success: http.StatusNoContent + DeleteStandalone func(ctx context.Context, options *clientinitindividuallygroup.IndividuallyNestedWithMultipleClientDeleteStandaloneOptions) (resp azfake.Responder[clientinitindividuallygroup.IndividuallyNestedWithMultipleClientDeleteStandaloneResponse], errResp azfake.ErrorResponder) + + // GetStandalone is the fake for method IndividuallyNestedWithMultipleClient.GetStandalone + // HTTP status codes to indicate success: http.StatusNoContent + GetStandalone func(ctx context.Context, options *clientinitindividuallygroup.IndividuallyNestedWithMultipleClientGetStandaloneOptions) (resp azfake.Responder[clientinitindividuallygroup.IndividuallyNestedWithMultipleClientGetStandaloneResponse], errResp azfake.ErrorResponder) + + // WithQuery is the fake for method IndividuallyNestedWithMultipleClient.WithQuery + // HTTP status codes to indicate success: http.StatusNoContent + WithQuery func(ctx context.Context, options *clientinitindividuallygroup.IndividuallyNestedWithMultipleClientWithQueryOptions) (resp azfake.Responder[clientinitindividuallygroup.IndividuallyNestedWithMultipleClientWithQueryResponse], errResp azfake.ErrorResponder) +} + +// NewIndividuallyNestedWithMultipleServerTransport creates a new instance of IndividuallyNestedWithMultipleServerTransport with the provided implementation. +// The returned IndividuallyNestedWithMultipleServerTransport instance is connected to an instance of clientinitindividuallygroup.IndividuallyNestedWithMultipleClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewIndividuallyNestedWithMultipleServerTransport(srv *IndividuallyNestedWithMultipleServer) *IndividuallyNestedWithMultipleServerTransport { + return &IndividuallyNestedWithMultipleServerTransport{srv: srv} +} + +// IndividuallyNestedWithMultipleServerTransport connects instances of clientinitindividuallygroup.IndividuallyNestedWithMultipleClient to instances of IndividuallyNestedWithMultipleServer. +// Don't use this type directly, use NewIndividuallyNestedWithMultipleServerTransport instead. +type IndividuallyNestedWithMultipleServerTransport struct { + srv *IndividuallyNestedWithMultipleServer +} + +// Do implements the policy.Transporter interface for IndividuallyNestedWithMultipleServerTransport. +func (i *IndividuallyNestedWithMultipleServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return i.dispatchToMethodFake(req, method) +} + +func (i *IndividuallyNestedWithMultipleServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if individuallyNestedWithMultipleServerTransportInterceptor != nil { + res.resp, res.err, intercepted = individuallyNestedWithMultipleServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "IndividuallyNestedWithMultipleClient.DeleteStandalone": + res.resp, res.err = i.dispatchDeleteStandalone(req) + case "IndividuallyNestedWithMultipleClient.GetStandalone": + res.resp, res.err = i.dispatchGetStandalone(req) + case "IndividuallyNestedWithMultipleClient.WithQuery": + res.resp, res.err = i.dispatchWithQuery(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (i *IndividuallyNestedWithMultipleServerTransport) dispatchDeleteStandalone(req *http.Request) (*http.Response, error) { + if i.srv.DeleteStandalone == nil { + return nil, &nonRetriableError{errors.New("fake for method DeleteStandalone not implemented")} + } + respr, errRespr := i.srv.DeleteStandalone(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (i *IndividuallyNestedWithMultipleServerTransport) dispatchGetStandalone(req *http.Request) (*http.Response, error) { + if i.srv.GetStandalone == nil { + return nil, &nonRetriableError{errors.New("fake for method GetStandalone not implemented")} + } + respr, errRespr := i.srv.GetStandalone(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (i *IndividuallyNestedWithMultipleServerTransport) dispatchWithQuery(req *http.Request) (*http.Response, error) { + if i.srv.WithQuery == nil { + return nil, &nonRetriableError{errors.New("fake for method WithQuery not implemented")} + } + qp := req.URL.Query() + formatParam := getOptional(qp.Get("format")) + var options *clientinitindividuallygroup.IndividuallyNestedWithMultipleClientWithQueryOptions + if formatParam != nil { + options = &clientinitindividuallygroup.IndividuallyNestedWithMultipleClientWithQueryOptions{ + Format: formatParam, + } + } + respr, errRespr := i.srv.WithQuery(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to IndividuallyNestedWithMultipleServerTransport +var individuallyNestedWithMultipleServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_individuallynestedwithparamalias_server.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_individuallynestedwithparamalias_server.go new file mode 100644 index 000000000000..c231973486f3 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_individuallynestedwithparamalias_server.go @@ -0,0 +1,139 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "clientinitindividuallygroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "regexp" + "slices" +) + +// IndividuallyNestedWithParamAliasServer is a fake server for instances of the clientinitindividuallygroup.IndividuallyNestedWithParamAliasClient type. +type IndividuallyNestedWithParamAliasServer struct { + // WithAliasedName is the fake for method IndividuallyNestedWithParamAliasClient.WithAliasedName + // HTTP status codes to indicate success: http.StatusNoContent + WithAliasedName func(ctx context.Context, options *clientinitindividuallygroup.IndividuallyNestedWithParamAliasClientWithAliasedNameOptions) (resp azfake.Responder[clientinitindividuallygroup.IndividuallyNestedWithParamAliasClientWithAliasedNameResponse], errResp azfake.ErrorResponder) + + // WithOriginalName is the fake for method IndividuallyNestedWithParamAliasClient.WithOriginalName + // HTTP status codes to indicate success: http.StatusNoContent + WithOriginalName func(ctx context.Context, options *clientinitindividuallygroup.IndividuallyNestedWithParamAliasClientWithOriginalNameOptions) (resp azfake.Responder[clientinitindividuallygroup.IndividuallyNestedWithParamAliasClientWithOriginalNameResponse], errResp azfake.ErrorResponder) +} + +// NewIndividuallyNestedWithParamAliasServerTransport creates a new instance of IndividuallyNestedWithParamAliasServerTransport with the provided implementation. +// The returned IndividuallyNestedWithParamAliasServerTransport instance is connected to an instance of clientinitindividuallygroup.IndividuallyNestedWithParamAliasClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewIndividuallyNestedWithParamAliasServerTransport(srv *IndividuallyNestedWithParamAliasServer) *IndividuallyNestedWithParamAliasServerTransport { + return &IndividuallyNestedWithParamAliasServerTransport{srv: srv} +} + +// IndividuallyNestedWithParamAliasServerTransport connects instances of clientinitindividuallygroup.IndividuallyNestedWithParamAliasClient to instances of IndividuallyNestedWithParamAliasServer. +// Don't use this type directly, use NewIndividuallyNestedWithParamAliasServerTransport instead. +type IndividuallyNestedWithParamAliasServerTransport struct { + srv *IndividuallyNestedWithParamAliasServer +} + +// Do implements the policy.Transporter interface for IndividuallyNestedWithParamAliasServerTransport. +func (i *IndividuallyNestedWithParamAliasServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return i.dispatchToMethodFake(req, method) +} + +func (i *IndividuallyNestedWithParamAliasServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if individuallyNestedWithParamAliasServerTransportInterceptor != nil { + res.resp, res.err, intercepted = individuallyNestedWithParamAliasServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "IndividuallyNestedWithParamAliasClient.WithAliasedName": + res.resp, res.err = i.dispatchWithAliasedName(req) + case "IndividuallyNestedWithParamAliasClient.WithOriginalName": + res.resp, res.err = i.dispatchWithOriginalName(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (i *IndividuallyNestedWithParamAliasServerTransport) dispatchWithAliasedName(req *http.Request) (*http.Response, error) { + if i.srv.WithAliasedName == nil { + return nil, &nonRetriableError{errors.New("fake for method WithAliasedName not implemented")} + } + const regexStr = `/azure/client-generator-core/client-initialization/individually/nested-default-individually-param-alias/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/with-aliased-name` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + respr, errRespr := i.srv.WithAliasedName(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (i *IndividuallyNestedWithParamAliasServerTransport) dispatchWithOriginalName(req *http.Request) (*http.Response, error) { + if i.srv.WithOriginalName == nil { + return nil, &nonRetriableError{errors.New("fake for method WithOriginalName not implemented")} + } + const regexStr = `/azure/client-generator-core/client-initialization/individually/nested-default-individually-param-alias/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/with-original-name` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + respr, errRespr := i.srv.WithOriginalName(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to IndividuallyNestedWithParamAliasServerTransport +var individuallyNestedWithParamAliasServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_individuallynestedwithpath_server.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_individuallynestedwithpath_server.go new file mode 100644 index 000000000000..81241f0f3f74 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_individuallynestedwithpath_server.go @@ -0,0 +1,178 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "clientinitindividuallygroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "regexp" + "slices" +) + +// IndividuallyNestedWithPathServer is a fake server for instances of the clientinitindividuallygroup.IndividuallyNestedWithPathClient type. +type IndividuallyNestedWithPathServer struct { + // DeleteStandalone is the fake for method IndividuallyNestedWithPathClient.DeleteStandalone + // HTTP status codes to indicate success: http.StatusNoContent + DeleteStandalone func(ctx context.Context, options *clientinitindividuallygroup.IndividuallyNestedWithPathClientDeleteStandaloneOptions) (resp azfake.Responder[clientinitindividuallygroup.IndividuallyNestedWithPathClientDeleteStandaloneResponse], errResp azfake.ErrorResponder) + + // GetStandalone is the fake for method IndividuallyNestedWithPathClient.GetStandalone + // HTTP status codes to indicate success: http.StatusOK + GetStandalone func(ctx context.Context, options *clientinitindividuallygroup.IndividuallyNestedWithPathClientGetStandaloneOptions) (resp azfake.Responder[clientinitindividuallygroup.IndividuallyNestedWithPathClientGetStandaloneResponse], errResp azfake.ErrorResponder) + + // WithQuery is the fake for method IndividuallyNestedWithPathClient.WithQuery + // HTTP status codes to indicate success: http.StatusNoContent + WithQuery func(ctx context.Context, options *clientinitindividuallygroup.IndividuallyNestedWithPathClientWithQueryOptions) (resp azfake.Responder[clientinitindividuallygroup.IndividuallyNestedWithPathClientWithQueryResponse], errResp azfake.ErrorResponder) +} + +// NewIndividuallyNestedWithPathServerTransport creates a new instance of IndividuallyNestedWithPathServerTransport with the provided implementation. +// The returned IndividuallyNestedWithPathServerTransport instance is connected to an instance of clientinitindividuallygroup.IndividuallyNestedWithPathClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewIndividuallyNestedWithPathServerTransport(srv *IndividuallyNestedWithPathServer) *IndividuallyNestedWithPathServerTransport { + return &IndividuallyNestedWithPathServerTransport{srv: srv} +} + +// IndividuallyNestedWithPathServerTransport connects instances of clientinitindividuallygroup.IndividuallyNestedWithPathClient to instances of IndividuallyNestedWithPathServer. +// Don't use this type directly, use NewIndividuallyNestedWithPathServerTransport instead. +type IndividuallyNestedWithPathServerTransport struct { + srv *IndividuallyNestedWithPathServer +} + +// Do implements the policy.Transporter interface for IndividuallyNestedWithPathServerTransport. +func (i *IndividuallyNestedWithPathServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return i.dispatchToMethodFake(req, method) +} + +func (i *IndividuallyNestedWithPathServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if individuallyNestedWithPathServerTransportInterceptor != nil { + res.resp, res.err, intercepted = individuallyNestedWithPathServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "IndividuallyNestedWithPathClient.DeleteStandalone": + res.resp, res.err = i.dispatchDeleteStandalone(req) + case "IndividuallyNestedWithPathClient.GetStandalone": + res.resp, res.err = i.dispatchGetStandalone(req) + case "IndividuallyNestedWithPathClient.WithQuery": + res.resp, res.err = i.dispatchWithQuery(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (i *IndividuallyNestedWithPathServerTransport) dispatchDeleteStandalone(req *http.Request) (*http.Response, error) { + if i.srv.DeleteStandalone == nil { + return nil, &nonRetriableError{errors.New("fake for method DeleteStandalone not implemented")} + } + const regexStr = `/azure/client-generator-core/client-initialization/individually/nested-default-individually/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + respr, errRespr := i.srv.DeleteStandalone(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (i *IndividuallyNestedWithPathServerTransport) dispatchGetStandalone(req *http.Request) (*http.Response, error) { + if i.srv.GetStandalone == nil { + return nil, &nonRetriableError{errors.New("fake for method GetStandalone not implemented")} + } + const regexStr = `/azure/client-generator-core/client-initialization/individually/nested-default-individually/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/get-standalone` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + respr, errRespr := i.srv.GetStandalone(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BlobProperties, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (i *IndividuallyNestedWithPathServerTransport) dispatchWithQuery(req *http.Request) (*http.Response, error) { + if i.srv.WithQuery == nil { + return nil, &nonRetriableError{errors.New("fake for method WithQuery not implemented")} + } + const regexStr = `/azure/client-generator-core/client-initialization/individually/nested-default-individually/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/with-query` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + formatParam := getOptional(qp.Get("format")) + var options *clientinitindividuallygroup.IndividuallyNestedWithPathClientWithQueryOptions + if formatParam != nil { + options = &clientinitindividuallygroup.IndividuallyNestedWithPathClientWithQueryOptions{ + Format: formatParam, + } + } + respr, errRespr := i.srv.WithQuery(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to IndividuallyNestedWithPathServerTransport +var individuallyNestedWithPathServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_individuallynestedwithquery_server.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_individuallynestedwithquery_server.go new file mode 100644 index 000000000000..c3ad7fcf40de --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_individuallynestedwithquery_server.go @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "clientinitindividuallygroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// IndividuallyNestedWithQueryServer is a fake server for instances of the clientinitindividuallygroup.IndividuallyNestedWithQueryClient type. +type IndividuallyNestedWithQueryServer struct { + // DeleteStandalone is the fake for method IndividuallyNestedWithQueryClient.DeleteStandalone + // HTTP status codes to indicate success: http.StatusNoContent + DeleteStandalone func(ctx context.Context, options *clientinitindividuallygroup.IndividuallyNestedWithQueryClientDeleteStandaloneOptions) (resp azfake.Responder[clientinitindividuallygroup.IndividuallyNestedWithQueryClientDeleteStandaloneResponse], errResp azfake.ErrorResponder) + + // GetStandalone is the fake for method IndividuallyNestedWithQueryClient.GetStandalone + // HTTP status codes to indicate success: http.StatusOK + GetStandalone func(ctx context.Context, options *clientinitindividuallygroup.IndividuallyNestedWithQueryClientGetStandaloneOptions) (resp azfake.Responder[clientinitindividuallygroup.IndividuallyNestedWithQueryClientGetStandaloneResponse], errResp azfake.ErrorResponder) + + // WithQuery is the fake for method IndividuallyNestedWithQueryClient.WithQuery + // HTTP status codes to indicate success: http.StatusNoContent + WithQuery func(ctx context.Context, options *clientinitindividuallygroup.IndividuallyNestedWithQueryClientWithQueryOptions) (resp azfake.Responder[clientinitindividuallygroup.IndividuallyNestedWithQueryClientWithQueryResponse], errResp azfake.ErrorResponder) +} + +// NewIndividuallyNestedWithQueryServerTransport creates a new instance of IndividuallyNestedWithQueryServerTransport with the provided implementation. +// The returned IndividuallyNestedWithQueryServerTransport instance is connected to an instance of clientinitindividuallygroup.IndividuallyNestedWithQueryClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewIndividuallyNestedWithQueryServerTransport(srv *IndividuallyNestedWithQueryServer) *IndividuallyNestedWithQueryServerTransport { + return &IndividuallyNestedWithQueryServerTransport{srv: srv} +} + +// IndividuallyNestedWithQueryServerTransport connects instances of clientinitindividuallygroup.IndividuallyNestedWithQueryClient to instances of IndividuallyNestedWithQueryServer. +// Don't use this type directly, use NewIndividuallyNestedWithQueryServerTransport instead. +type IndividuallyNestedWithQueryServerTransport struct { + srv *IndividuallyNestedWithQueryServer +} + +// Do implements the policy.Transporter interface for IndividuallyNestedWithQueryServerTransport. +func (i *IndividuallyNestedWithQueryServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return i.dispatchToMethodFake(req, method) +} + +func (i *IndividuallyNestedWithQueryServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if individuallyNestedWithQueryServerTransportInterceptor != nil { + res.resp, res.err, intercepted = individuallyNestedWithQueryServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "IndividuallyNestedWithQueryClient.DeleteStandalone": + res.resp, res.err = i.dispatchDeleteStandalone(req) + case "IndividuallyNestedWithQueryClient.GetStandalone": + res.resp, res.err = i.dispatchGetStandalone(req) + case "IndividuallyNestedWithQueryClient.WithQuery": + res.resp, res.err = i.dispatchWithQuery(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (i *IndividuallyNestedWithQueryServerTransport) dispatchDeleteStandalone(req *http.Request) (*http.Response, error) { + if i.srv.DeleteStandalone == nil { + return nil, &nonRetriableError{errors.New("fake for method DeleteStandalone not implemented")} + } + respr, errRespr := i.srv.DeleteStandalone(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (i *IndividuallyNestedWithQueryServerTransport) dispatchGetStandalone(req *http.Request) (*http.Response, error) { + if i.srv.GetStandalone == nil { + return nil, &nonRetriableError{errors.New("fake for method GetStandalone not implemented")} + } + respr, errRespr := i.srv.GetStandalone(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BlobProperties, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (i *IndividuallyNestedWithQueryServerTransport) dispatchWithQuery(req *http.Request) (*http.Response, error) { + if i.srv.WithQuery == nil { + return nil, &nonRetriableError{errors.New("fake for method WithQuery not implemented")} + } + qp := req.URL.Query() + formatParam := getOptional(qp.Get("format")) + var options *clientinitindividuallygroup.IndividuallyNestedWithQueryClientWithQueryOptions + if formatParam != nil { + options = &clientinitindividuallygroup.IndividuallyNestedWithQueryClientWithQueryOptions{ + Format: formatParam, + } + } + respr, errRespr := i.srv.WithQuery(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to IndividuallyNestedWithQueryServerTransport +var individuallyNestedWithQueryServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_internal.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_internal.go new file mode 100644 index 000000000000..53ec711308cc --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/fake/zz_internal.go @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "reflect" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getOptional[T any](v T) *T { + if reflect.ValueOf(v).IsZero() { + return nil + } + return &v +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/go.mod b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/go.mod new file mode 100644 index 000000000000..5a9d8f3b2cf3 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/go.mod @@ -0,0 +1,17 @@ +module clientinitindividuallygroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/go.sum b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/individuallynestedwithheader_client_test.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/individuallynestedwithheader_client_test.go new file mode 100644 index 000000000000..fbe0b25845e0 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/individuallynestedwithheader_client_test.go @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package clientinitindividuallygroup_test + +import ( + "clientinitindividuallygroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestIndividuallyNestedWithHeaderClient_WithQuery(t *testing.T) { + client, err := clientinitindividuallygroup.NewIndividuallyNestedWithHeaderClientWithNoCredential("http://localhost:3000", "test-name-value", nil) + require.NoError(t, err) + resp, err := client.WithQuery(context.Background(), &clientinitindividuallygroup.IndividuallyNestedWithHeaderClientWithQueryOptions{ + Format: to.Ptr("text"), + }) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestIndividuallyNestedWithHeaderClient_GetStandalone(t *testing.T) { + client, err := clientinitindividuallygroup.NewIndividuallyNestedWithHeaderClientWithNoCredential("http://localhost:3000", "test-name-value", nil) + require.NoError(t, err) + resp, err := client.GetStandalone(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestIndividuallyNestedWithHeaderClient_DeleteStandalone(t *testing.T) { + client, err := clientinitindividuallygroup.NewIndividuallyNestedWithHeaderClientWithNoCredential("http://localhost:3000", "test-name-value", nil) + require.NoError(t, err) + resp, err := client.DeleteStandalone(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/individuallynestedwithmixed_client_test.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/individuallynestedwithmixed_client_test.go new file mode 100644 index 000000000000..7abf56a5931f --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/individuallynestedwithmixed_client_test.go @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package clientinitindividuallygroup_test + +import ( + "clientinitindividuallygroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestIndividuallyNestedWithMixedClient_WithQuery(t *testing.T) { + client, err := clientinitindividuallygroup.NewIndividuallyNestedWithMixedClientWithNoCredential("http://localhost:3000", "test-name-value", nil) + require.NoError(t, err) + resp, err := client.WithQuery(context.Background(), "us-west", &clientinitindividuallygroup.IndividuallyNestedWithMixedClientWithQueryOptions{ + Format: to.Ptr("text"), + }) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestIndividuallyNestedWithMixedClient_GetStandalone(t *testing.T) { + client, err := clientinitindividuallygroup.NewIndividuallyNestedWithMixedClientWithNoCredential("http://localhost:3000", "test-name-value", nil) + require.NoError(t, err) + resp, err := client.GetStandalone(context.Background(), "us-west", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestIndividuallyNestedWithMixedClient_DeleteStandalone(t *testing.T) { + client, err := clientinitindividuallygroup.NewIndividuallyNestedWithMixedClientWithNoCredential("http://localhost:3000", "test-name-value", nil) + require.NoError(t, err) + resp, err := client.DeleteStandalone(context.Background(), "us-west", nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/individuallynestedwithmultiple_client_test.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/individuallynestedwithmultiple_client_test.go new file mode 100644 index 000000000000..5b7c462491c3 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/individuallynestedwithmultiple_client_test.go @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package clientinitindividuallygroup_test + +import ( + "clientinitindividuallygroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestIndividuallyNestedWithMultipleClient_WithQuery(t *testing.T) { + client, err := clientinitindividuallygroup.NewIndividuallyNestedWithMultipleClientWithNoCredential("http://localhost:3000", "test-name-value", "us-west", nil) + require.NoError(t, err) + resp, err := client.WithQuery(context.Background(), &clientinitindividuallygroup.IndividuallyNestedWithMultipleClientWithQueryOptions{ + Format: to.Ptr("text"), + }) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestIndividuallyNestedWithMultipleClient_GetStandalone(t *testing.T) { + client, err := clientinitindividuallygroup.NewIndividuallyNestedWithMultipleClientWithNoCredential("http://localhost:3000", "test-name-value", "us-west", nil) + require.NoError(t, err) + resp, err := client.GetStandalone(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestIndividuallyNestedWithMultipleClient_DeleteStandalone(t *testing.T) { + client, err := clientinitindividuallygroup.NewIndividuallyNestedWithMultipleClientWithNoCredential("http://localhost:3000", "test-name-value", "us-west", nil) + require.NoError(t, err) + resp, err := client.DeleteStandalone(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/individuallynestedwithparamalias_client_test.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/individuallynestedwithparamalias_client_test.go new file mode 100644 index 000000000000..b66d7730b1d7 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/individuallynestedwithparamalias_client_test.go @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package clientinitindividuallygroup_test + +import ( + "clientinitindividuallygroup" + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestIndividuallyNestedWithParamAliasClient_WithAliasedName(t *testing.T) { + client, err := clientinitindividuallygroup.NewIndividuallyNestedWithParamAliasClientWithNoCredential("http://localhost:3000", "sample-blob", nil) + require.NoError(t, err) + resp, err := client.WithAliasedName(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestIndividuallyNestedWithParamAliasClient_WithOriginalName(t *testing.T) { + client, err := clientinitindividuallygroup.NewIndividuallyNestedWithParamAliasClientWithNoCredential("http://localhost:3000", "sample-blob", nil) + require.NoError(t, err) + resp, err := client.WithOriginalName(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/individuallynestedwithpath_client_test.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/individuallynestedwithpath_client_test.go new file mode 100644 index 000000000000..8865ed2729c8 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/individuallynestedwithpath_client_test.go @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package clientinitindividuallygroup_test + +import ( + "clientinitindividuallygroup" + "context" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestIndividuallyNestedWithPathClient_WithQuery(t *testing.T) { + client, err := clientinitindividuallygroup.NewIndividuallyNestedWithPathClientWithNoCredential("http://localhost:3000", "test-blob", nil) + require.NoError(t, err) + resp, err := client.WithQuery(context.Background(), &clientinitindividuallygroup.IndividuallyNestedWithPathClientWithQueryOptions{ + Format: to.Ptr("text"), + }) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestIndividuallyNestedWithPathClient_GetStandalone(t *testing.T) { + client, err := clientinitindividuallygroup.NewIndividuallyNestedWithPathClientWithNoCredential("http://localhost:3000", "test-blob", nil) + require.NoError(t, err) + resp, err := client.GetStandalone(context.Background(), nil) + require.NoError(t, err) + expectedTime, err := time.Parse(time.RFC3339, "2023-01-01T12:00:00Z") + require.NoError(t, err) + require.EqualValues(t, clientinitindividuallygroup.BlobProperties{ + Name: to.Ptr("test-blob"), + Size: to.Ptr[int64](1024), + ContentType: to.Ptr("application/octet-stream"), + CreatedOn: to.Ptr(expectedTime), + }, resp.BlobProperties) +} + +func TestIndividuallyNestedWithPathClient_DeleteStandalone(t *testing.T) { + client, err := clientinitindividuallygroup.NewIndividuallyNestedWithPathClientWithNoCredential("http://localhost:3000", "test-blob", nil) + require.NoError(t, err) + resp, err := client.DeleteStandalone(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/individuallynestedwithquery_client_test.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/individuallynestedwithquery_client_test.go new file mode 100644 index 000000000000..e335997a491e --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/individuallynestedwithquery_client_test.go @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package clientinitindividuallygroup_test + +import ( + "clientinitindividuallygroup" + "context" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestIndividuallyNestedWithQueryClient_WithQuery(t *testing.T) { + client, err := clientinitindividuallygroup.NewIndividuallyNestedWithQueryClientWithNoCredential("http://localhost:3000", "test-blob", nil) + require.NoError(t, err) + resp, err := client.WithQuery(context.Background(), &clientinitindividuallygroup.IndividuallyNestedWithQueryClientWithQueryOptions{ + Format: to.Ptr("text"), + }) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestIndividuallyNestedWithQueryClient_GetStandalone(t *testing.T) { + client, err := clientinitindividuallygroup.NewIndividuallyNestedWithQueryClientWithNoCredential("http://localhost:3000", "test-blob", nil) + require.NoError(t, err) + resp, err := client.GetStandalone(context.Background(), nil) + require.NoError(t, err) + expectedTime, err := time.Parse(time.RFC3339, "2023-01-01T12:00:00Z") + require.NoError(t, err) + require.EqualValues(t, clientinitindividuallygroup.BlobProperties{ + Name: to.Ptr("test-blob"), + Size: to.Ptr[int64](1024), + ContentType: to.Ptr("application/octet-stream"), + CreatedOn: to.Ptr(expectedTime), + }, resp.BlobProperties) +} + +func TestIndividuallyNestedWithQueryClient_DeleteStandalone(t *testing.T) { + client, err := clientinitindividuallygroup.NewIndividuallyNestedWithQueryClientWithNoCredential("http://localhost:3000", "test-blob", nil) + require.NoError(t, err) + resp, err := client.DeleteStandalone(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/testdata/_metadata.json b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_individuallynestedwithheader_client.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_individuallynestedwithheader_client.go new file mode 100644 index 000000000000..75c619d7b1b2 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_individuallynestedwithheader_client.go @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitindividuallygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// IndividuallyNestedWithHeaderClient - Operations for nested default -> individually header parameters +// Don't use this type directly, use NewIndividuallyNestedWithHeaderClientWithNoCredential() instead. +type IndividuallyNestedWithHeaderClient struct { + internal *azcore.Client + endpoint string + name string +} + +// IndividuallyNestedWithHeaderClientOptions contains the optional values for creating a [IndividuallyNestedWithHeaderClient]. +type IndividuallyNestedWithHeaderClientOptions struct { + azcore.ClientOptions +} + +// NewIndividuallyNestedWithHeaderClientWithNoCredential creates a new instance of IndividuallyNestedWithHeaderClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewIndividuallyNestedWithHeaderClientWithNoCredential(endpoint string, name string, options *IndividuallyNestedWithHeaderClientOptions) (*IndividuallyNestedWithHeaderClient, error) { + if options == nil { + options = &IndividuallyNestedWithHeaderClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &IndividuallyNestedWithHeaderClient{ + endpoint: endpoint, + name: name, + internal: cl, + } + return client, nil +} + +// DeleteStandalone - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyNestedWithHeaderClientDeleteStandaloneOptions contains the optional parameters for the IndividuallyNestedWithHeaderClient.DeleteStandalone +// method. +func (client *IndividuallyNestedWithHeaderClient) DeleteStandalone(ctx context.Context, options *IndividuallyNestedWithHeaderClientDeleteStandaloneOptions) (IndividuallyNestedWithHeaderClientDeleteStandaloneResponse, error) { + var err error + const operationName = "IndividuallyNestedWithHeaderClient.DeleteStandalone" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteStandaloneCreateRequest(ctx, options) + if err != nil { + return IndividuallyNestedWithHeaderClientDeleteStandaloneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyNestedWithHeaderClientDeleteStandaloneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyNestedWithHeaderClientDeleteStandaloneResponse{}, err + } + return IndividuallyNestedWithHeaderClientDeleteStandaloneResponse{}, nil +} + +// deleteStandaloneCreateRequest creates the DeleteStandalone request. +func (client *IndividuallyNestedWithHeaderClient) deleteStandaloneCreateRequest(ctx context.Context, _ *IndividuallyNestedWithHeaderClientDeleteStandaloneOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually/nested-default-individually-header/delete-standalone" + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["name"] = []string{client.name} + return req, nil +} + +// GetStandalone - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyNestedWithHeaderClientGetStandaloneOptions contains the optional parameters for the IndividuallyNestedWithHeaderClient.GetStandalone +// method. +func (client *IndividuallyNestedWithHeaderClient) GetStandalone(ctx context.Context, options *IndividuallyNestedWithHeaderClientGetStandaloneOptions) (IndividuallyNestedWithHeaderClientGetStandaloneResponse, error) { + var err error + const operationName = "IndividuallyNestedWithHeaderClient.GetStandalone" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getStandaloneCreateRequest(ctx, options) + if err != nil { + return IndividuallyNestedWithHeaderClientGetStandaloneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyNestedWithHeaderClientGetStandaloneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyNestedWithHeaderClientGetStandaloneResponse{}, err + } + return IndividuallyNestedWithHeaderClientGetStandaloneResponse{}, nil +} + +// getStandaloneCreateRequest creates the GetStandalone request. +func (client *IndividuallyNestedWithHeaderClient) getStandaloneCreateRequest(ctx context.Context, _ *IndividuallyNestedWithHeaderClientGetStandaloneOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually/nested-default-individually-header/get-standalone" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["name"] = []string{client.name} + return req, nil +} + +// WithQuery - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyNestedWithHeaderClientWithQueryOptions contains the optional parameters for the IndividuallyNestedWithHeaderClient.WithQuery +// method. +func (client *IndividuallyNestedWithHeaderClient) WithQuery(ctx context.Context, options *IndividuallyNestedWithHeaderClientWithQueryOptions) (IndividuallyNestedWithHeaderClientWithQueryResponse, error) { + var err error + const operationName = "IndividuallyNestedWithHeaderClient.WithQuery" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withQueryCreateRequest(ctx, options) + if err != nil { + return IndividuallyNestedWithHeaderClientWithQueryResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyNestedWithHeaderClientWithQueryResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyNestedWithHeaderClientWithQueryResponse{}, err + } + return IndividuallyNestedWithHeaderClientWithQueryResponse{}, nil +} + +// withQueryCreateRequest creates the WithQuery request. +func (client *IndividuallyNestedWithHeaderClient) withQueryCreateRequest(ctx context.Context, options *IndividuallyNestedWithHeaderClientWithQueryOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually/nested-default-individually-header/with-query" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Format != nil { + reqQP.Set("format", *options.Format) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["name"] = []string{client.name} + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_individuallynestedwithmixed_client.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_individuallynestedwithmixed_client.go new file mode 100644 index 000000000000..1302f2d8db6f --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_individuallynestedwithmixed_client.go @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitindividuallygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// IndividuallyNestedWithMixedClient - Operations for nested default -> individually mixed parameters +// Don't use this type directly, use NewIndividuallyNestedWithMixedClientWithNoCredential() instead. +type IndividuallyNestedWithMixedClient struct { + internal *azcore.Client + endpoint string + name string +} + +// IndividuallyNestedWithMixedClientOptions contains the optional values for creating a [IndividuallyNestedWithMixedClient]. +type IndividuallyNestedWithMixedClientOptions struct { + azcore.ClientOptions +} + +// NewIndividuallyNestedWithMixedClientWithNoCredential creates a new instance of IndividuallyNestedWithMixedClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewIndividuallyNestedWithMixedClientWithNoCredential(endpoint string, name string, options *IndividuallyNestedWithMixedClientOptions) (*IndividuallyNestedWithMixedClient, error) { + if options == nil { + options = &IndividuallyNestedWithMixedClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &IndividuallyNestedWithMixedClient{ + endpoint: endpoint, + name: name, + internal: cl, + } + return client, nil +} + +// DeleteStandalone - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyNestedWithMixedClientDeleteStandaloneOptions contains the optional parameters for the IndividuallyNestedWithMixedClient.DeleteStandalone +// method. +func (client *IndividuallyNestedWithMixedClient) DeleteStandalone(ctx context.Context, region string, options *IndividuallyNestedWithMixedClientDeleteStandaloneOptions) (IndividuallyNestedWithMixedClientDeleteStandaloneResponse, error) { + var err error + const operationName = "IndividuallyNestedWithMixedClient.DeleteStandalone" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteStandaloneCreateRequest(ctx, region, options) + if err != nil { + return IndividuallyNestedWithMixedClientDeleteStandaloneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyNestedWithMixedClientDeleteStandaloneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyNestedWithMixedClientDeleteStandaloneResponse{}, err + } + return IndividuallyNestedWithMixedClientDeleteStandaloneResponse{}, nil +} + +// deleteStandaloneCreateRequest creates the DeleteStandalone request. +func (client *IndividuallyNestedWithMixedClient) deleteStandaloneCreateRequest(ctx context.Context, region string, _ *IndividuallyNestedWithMixedClientDeleteStandaloneOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually/nested-default-individually-mixed/delete-standalone" + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("region", region) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["name"] = []string{client.name} + return req, nil +} + +// GetStandalone - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyNestedWithMixedClientGetStandaloneOptions contains the optional parameters for the IndividuallyNestedWithMixedClient.GetStandalone +// method. +func (client *IndividuallyNestedWithMixedClient) GetStandalone(ctx context.Context, region string, options *IndividuallyNestedWithMixedClientGetStandaloneOptions) (IndividuallyNestedWithMixedClientGetStandaloneResponse, error) { + var err error + const operationName = "IndividuallyNestedWithMixedClient.GetStandalone" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getStandaloneCreateRequest(ctx, region, options) + if err != nil { + return IndividuallyNestedWithMixedClientGetStandaloneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyNestedWithMixedClientGetStandaloneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyNestedWithMixedClientGetStandaloneResponse{}, err + } + return IndividuallyNestedWithMixedClientGetStandaloneResponse{}, nil +} + +// getStandaloneCreateRequest creates the GetStandalone request. +func (client *IndividuallyNestedWithMixedClient) getStandaloneCreateRequest(ctx context.Context, region string, _ *IndividuallyNestedWithMixedClientGetStandaloneOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually/nested-default-individually-mixed/get-standalone" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("region", region) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["name"] = []string{client.name} + return req, nil +} + +// WithQuery - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyNestedWithMixedClientWithQueryOptions contains the optional parameters for the IndividuallyNestedWithMixedClient.WithQuery +// method. +func (client *IndividuallyNestedWithMixedClient) WithQuery(ctx context.Context, region string, options *IndividuallyNestedWithMixedClientWithQueryOptions) (IndividuallyNestedWithMixedClientWithQueryResponse, error) { + var err error + const operationName = "IndividuallyNestedWithMixedClient.WithQuery" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withQueryCreateRequest(ctx, region, options) + if err != nil { + return IndividuallyNestedWithMixedClientWithQueryResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyNestedWithMixedClientWithQueryResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyNestedWithMixedClientWithQueryResponse{}, err + } + return IndividuallyNestedWithMixedClientWithQueryResponse{}, nil +} + +// withQueryCreateRequest creates the WithQuery request. +func (client *IndividuallyNestedWithMixedClient) withQueryCreateRequest(ctx context.Context, region string, options *IndividuallyNestedWithMixedClientWithQueryOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually/nested-default-individually-mixed/with-query" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Format != nil { + reqQP.Set("format", *options.Format) + } + reqQP.Set("region", region) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["name"] = []string{client.name} + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_individuallynestedwithmultiple_client.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_individuallynestedwithmultiple_client.go new file mode 100644 index 000000000000..211ecdf3f80e --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_individuallynestedwithmultiple_client.go @@ -0,0 +1,168 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitindividuallygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// IndividuallyNestedWithMultipleClient - Operations for nested default -> individually multiple parameters +// Don't use this type directly, use NewIndividuallyNestedWithMultipleClientWithNoCredential() instead. +type IndividuallyNestedWithMultipleClient struct { + internal *azcore.Client + endpoint string + name string + region string +} + +// IndividuallyNestedWithMultipleClientOptions contains the optional values for creating a [IndividuallyNestedWithMultipleClient]. +type IndividuallyNestedWithMultipleClientOptions struct { + azcore.ClientOptions +} + +// NewIndividuallyNestedWithMultipleClientWithNoCredential creates a new instance of IndividuallyNestedWithMultipleClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewIndividuallyNestedWithMultipleClientWithNoCredential(endpoint string, name string, region string, options *IndividuallyNestedWithMultipleClientOptions) (*IndividuallyNestedWithMultipleClient, error) { + if options == nil { + options = &IndividuallyNestedWithMultipleClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &IndividuallyNestedWithMultipleClient{ + endpoint: endpoint, + name: name, + region: region, + internal: cl, + } + return client, nil +} + +// DeleteStandalone - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyNestedWithMultipleClientDeleteStandaloneOptions contains the optional parameters for the IndividuallyNestedWithMultipleClient.DeleteStandalone +// method. +func (client *IndividuallyNestedWithMultipleClient) DeleteStandalone(ctx context.Context, options *IndividuallyNestedWithMultipleClientDeleteStandaloneOptions) (IndividuallyNestedWithMultipleClientDeleteStandaloneResponse, error) { + var err error + const operationName = "IndividuallyNestedWithMultipleClient.DeleteStandalone" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteStandaloneCreateRequest(ctx, options) + if err != nil { + return IndividuallyNestedWithMultipleClientDeleteStandaloneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyNestedWithMultipleClientDeleteStandaloneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyNestedWithMultipleClientDeleteStandaloneResponse{}, err + } + return IndividuallyNestedWithMultipleClientDeleteStandaloneResponse{}, nil +} + +// deleteStandaloneCreateRequest creates the DeleteStandalone request. +func (client *IndividuallyNestedWithMultipleClient) deleteStandaloneCreateRequest(ctx context.Context, _ *IndividuallyNestedWithMultipleClientDeleteStandaloneOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually/nested-default-individually-multiple/delete-standalone" + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("region", client.region) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["name"] = []string{client.name} + return req, nil +} + +// GetStandalone - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyNestedWithMultipleClientGetStandaloneOptions contains the optional parameters for the IndividuallyNestedWithMultipleClient.GetStandalone +// method. +func (client *IndividuallyNestedWithMultipleClient) GetStandalone(ctx context.Context, options *IndividuallyNestedWithMultipleClientGetStandaloneOptions) (IndividuallyNestedWithMultipleClientGetStandaloneResponse, error) { + var err error + const operationName = "IndividuallyNestedWithMultipleClient.GetStandalone" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getStandaloneCreateRequest(ctx, options) + if err != nil { + return IndividuallyNestedWithMultipleClientGetStandaloneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyNestedWithMultipleClientGetStandaloneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyNestedWithMultipleClientGetStandaloneResponse{}, err + } + return IndividuallyNestedWithMultipleClientGetStandaloneResponse{}, nil +} + +// getStandaloneCreateRequest creates the GetStandalone request. +func (client *IndividuallyNestedWithMultipleClient) getStandaloneCreateRequest(ctx context.Context, _ *IndividuallyNestedWithMultipleClientGetStandaloneOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually/nested-default-individually-multiple/get-standalone" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("region", client.region) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["name"] = []string{client.name} + return req, nil +} + +// WithQuery - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyNestedWithMultipleClientWithQueryOptions contains the optional parameters for the IndividuallyNestedWithMultipleClient.WithQuery +// method. +func (client *IndividuallyNestedWithMultipleClient) WithQuery(ctx context.Context, options *IndividuallyNestedWithMultipleClientWithQueryOptions) (IndividuallyNestedWithMultipleClientWithQueryResponse, error) { + var err error + const operationName = "IndividuallyNestedWithMultipleClient.WithQuery" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withQueryCreateRequest(ctx, options) + if err != nil { + return IndividuallyNestedWithMultipleClientWithQueryResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyNestedWithMultipleClientWithQueryResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyNestedWithMultipleClientWithQueryResponse{}, err + } + return IndividuallyNestedWithMultipleClientWithQueryResponse{}, nil +} + +// withQueryCreateRequest creates the WithQuery request. +func (client *IndividuallyNestedWithMultipleClient) withQueryCreateRequest(ctx context.Context, options *IndividuallyNestedWithMultipleClientWithQueryOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually/nested-default-individually-multiple/with-query" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Format != nil { + reqQP.Set("format", *options.Format) + } + reqQP.Set("region", client.region) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["name"] = []string{client.name} + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_individuallynestedwithparamalias_client.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_individuallynestedwithparamalias_client.go new file mode 100644 index 000000000000..842651878a72 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_individuallynestedwithparamalias_client.go @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitindividuallygroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// IndividuallyNestedWithParamAliasClient - Operations for nested default -> individually param alias +// Don't use this type directly, use NewIndividuallyNestedWithParamAliasClientWithNoCredential() instead. +type IndividuallyNestedWithParamAliasClient struct { + internal *azcore.Client + blobName string + endpoint string +} + +// IndividuallyNestedWithParamAliasClientOptions contains the optional values for creating a [IndividuallyNestedWithParamAliasClient]. +type IndividuallyNestedWithParamAliasClientOptions struct { + azcore.ClientOptions +} + +// NewIndividuallyNestedWithParamAliasClientWithNoCredential creates a new instance of IndividuallyNestedWithParamAliasClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewIndividuallyNestedWithParamAliasClientWithNoCredential(endpoint string, blobName string, options *IndividuallyNestedWithParamAliasClientOptions) (*IndividuallyNestedWithParamAliasClient, error) { + if options == nil { + options = &IndividuallyNestedWithParamAliasClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &IndividuallyNestedWithParamAliasClient{ + blobName: blobName, + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// WithAliasedName - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyNestedWithParamAliasClientWithAliasedNameOptions contains the optional parameters for the IndividuallyNestedWithParamAliasClient.WithAliasedName +// method. +func (client *IndividuallyNestedWithParamAliasClient) WithAliasedName(ctx context.Context, options *IndividuallyNestedWithParamAliasClientWithAliasedNameOptions) (IndividuallyNestedWithParamAliasClientWithAliasedNameResponse, error) { + var err error + const operationName = "IndividuallyNestedWithParamAliasClient.WithAliasedName" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withAliasedNameCreateRequest(ctx, options) + if err != nil { + return IndividuallyNestedWithParamAliasClientWithAliasedNameResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyNestedWithParamAliasClientWithAliasedNameResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyNestedWithParamAliasClientWithAliasedNameResponse{}, err + } + return IndividuallyNestedWithParamAliasClientWithAliasedNameResponse{}, nil +} + +// withAliasedNameCreateRequest creates the WithAliasedName request. +func (client *IndividuallyNestedWithParamAliasClient) withAliasedNameCreateRequest(ctx context.Context, _ *IndividuallyNestedWithParamAliasClientWithAliasedNameOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually/nested-default-individually-param-alias/{blob}/with-aliased-name" + if client.blobName == "" { + return nil, errors.New("parameter client.blobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{blob}", url.PathEscape(client.blobName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// WithOriginalName - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyNestedWithParamAliasClientWithOriginalNameOptions contains the optional parameters for the IndividuallyNestedWithParamAliasClient.WithOriginalName +// method. +func (client *IndividuallyNestedWithParamAliasClient) WithOriginalName(ctx context.Context, options *IndividuallyNestedWithParamAliasClientWithOriginalNameOptions) (IndividuallyNestedWithParamAliasClientWithOriginalNameResponse, error) { + var err error + const operationName = "IndividuallyNestedWithParamAliasClient.WithOriginalName" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withOriginalNameCreateRequest(ctx, options) + if err != nil { + return IndividuallyNestedWithParamAliasClientWithOriginalNameResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyNestedWithParamAliasClientWithOriginalNameResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyNestedWithParamAliasClientWithOriginalNameResponse{}, err + } + return IndividuallyNestedWithParamAliasClientWithOriginalNameResponse{}, nil +} + +// withOriginalNameCreateRequest creates the WithOriginalName request. +func (client *IndividuallyNestedWithParamAliasClient) withOriginalNameCreateRequest(ctx context.Context, _ *IndividuallyNestedWithParamAliasClientWithOriginalNameOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually/nested-default-individually-param-alias/{blobName}/with-original-name" + if client.blobName == "" { + return nil, errors.New("parameter client.blobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{blobName}", url.PathEscape(client.blobName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_individuallynestedwithpath_client.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_individuallynestedwithpath_client.go new file mode 100644 index 000000000000..0e59b0b1ca92 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_individuallynestedwithpath_client.go @@ -0,0 +1,181 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitindividuallygroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// IndividuallyNestedWithPathClient - Operations for nested default -> individually +// Don't use this type directly, use NewIndividuallyNestedWithPathClientWithNoCredential() instead. +type IndividuallyNestedWithPathClient struct { + internal *azcore.Client + blobName string + endpoint string +} + +// IndividuallyNestedWithPathClientOptions contains the optional values for creating a [IndividuallyNestedWithPathClient]. +type IndividuallyNestedWithPathClientOptions struct { + azcore.ClientOptions +} + +// NewIndividuallyNestedWithPathClientWithNoCredential creates a new instance of IndividuallyNestedWithPathClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewIndividuallyNestedWithPathClientWithNoCredential(endpoint string, blobName string, options *IndividuallyNestedWithPathClientOptions) (*IndividuallyNestedWithPathClient, error) { + if options == nil { + options = &IndividuallyNestedWithPathClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &IndividuallyNestedWithPathClient{ + blobName: blobName, + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// DeleteStandalone - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyNestedWithPathClientDeleteStandaloneOptions contains the optional parameters for the IndividuallyNestedWithPathClient.DeleteStandalone +// method. +func (client *IndividuallyNestedWithPathClient) DeleteStandalone(ctx context.Context, options *IndividuallyNestedWithPathClientDeleteStandaloneOptions) (IndividuallyNestedWithPathClientDeleteStandaloneResponse, error) { + var err error + const operationName = "IndividuallyNestedWithPathClient.DeleteStandalone" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteStandaloneCreateRequest(ctx, options) + if err != nil { + return IndividuallyNestedWithPathClientDeleteStandaloneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyNestedWithPathClientDeleteStandaloneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyNestedWithPathClientDeleteStandaloneResponse{}, err + } + return IndividuallyNestedWithPathClientDeleteStandaloneResponse{}, nil +} + +// deleteStandaloneCreateRequest creates the DeleteStandalone request. +func (client *IndividuallyNestedWithPathClient) deleteStandaloneCreateRequest(ctx context.Context, _ *IndividuallyNestedWithPathClientDeleteStandaloneOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually/nested-default-individually/{blobName}" + if client.blobName == "" { + return nil, errors.New("parameter client.blobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{blobName}", url.PathEscape(client.blobName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// GetStandalone - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyNestedWithPathClientGetStandaloneOptions contains the optional parameters for the IndividuallyNestedWithPathClient.GetStandalone +// method. +func (client *IndividuallyNestedWithPathClient) GetStandalone(ctx context.Context, options *IndividuallyNestedWithPathClientGetStandaloneOptions) (IndividuallyNestedWithPathClientGetStandaloneResponse, error) { + var err error + const operationName = "IndividuallyNestedWithPathClient.GetStandalone" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getStandaloneCreateRequest(ctx, options) + if err != nil { + return IndividuallyNestedWithPathClientGetStandaloneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyNestedWithPathClientGetStandaloneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return IndividuallyNestedWithPathClientGetStandaloneResponse{}, err + } + resp, err := client.getStandaloneHandleResponse(httpResp) + return resp, err +} + +// getStandaloneCreateRequest creates the GetStandalone request. +func (client *IndividuallyNestedWithPathClient) getStandaloneCreateRequest(ctx context.Context, _ *IndividuallyNestedWithPathClientGetStandaloneOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually/nested-default-individually/{blobName}/get-standalone" + if client.blobName == "" { + return nil, errors.New("parameter client.blobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{blobName}", url.PathEscape(client.blobName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getStandaloneHandleResponse handles the GetStandalone response. +func (client *IndividuallyNestedWithPathClient) getStandaloneHandleResponse(resp *http.Response) (IndividuallyNestedWithPathClientGetStandaloneResponse, error) { + result := IndividuallyNestedWithPathClientGetStandaloneResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BlobProperties); err != nil { + return IndividuallyNestedWithPathClientGetStandaloneResponse{}, err + } + return result, nil +} + +// WithQuery - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyNestedWithPathClientWithQueryOptions contains the optional parameters for the IndividuallyNestedWithPathClient.WithQuery +// method. +func (client *IndividuallyNestedWithPathClient) WithQuery(ctx context.Context, options *IndividuallyNestedWithPathClientWithQueryOptions) (IndividuallyNestedWithPathClientWithQueryResponse, error) { + var err error + const operationName = "IndividuallyNestedWithPathClient.WithQuery" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withQueryCreateRequest(ctx, options) + if err != nil { + return IndividuallyNestedWithPathClientWithQueryResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyNestedWithPathClientWithQueryResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyNestedWithPathClientWithQueryResponse{}, err + } + return IndividuallyNestedWithPathClientWithQueryResponse{}, nil +} + +// withQueryCreateRequest creates the WithQuery request. +func (client *IndividuallyNestedWithPathClient) withQueryCreateRequest(ctx context.Context, options *IndividuallyNestedWithPathClientWithQueryOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually/nested-default-individually/{blobName}/with-query" + if client.blobName == "" { + return nil, errors.New("parameter client.blobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{blobName}", url.PathEscape(client.blobName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Format != nil { + reqQP.Set("format", *options.Format) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_individuallynestedwithquery_client.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_individuallynestedwithquery_client.go new file mode 100644 index 000000000000..d45bd01d657e --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_individuallynestedwithquery_client.go @@ -0,0 +1,174 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitindividuallygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// IndividuallyNestedWithQueryClient - Operations for nested default -> individually with query parameters +// Don't use this type directly, use NewIndividuallyNestedWithQueryClientWithNoCredential() instead. +type IndividuallyNestedWithQueryClient struct { + internal *azcore.Client + blobName string + endpoint string +} + +// IndividuallyNestedWithQueryClientOptions contains the optional values for creating a [IndividuallyNestedWithQueryClient]. +type IndividuallyNestedWithQueryClientOptions struct { + azcore.ClientOptions +} + +// NewIndividuallyNestedWithQueryClientWithNoCredential creates a new instance of IndividuallyNestedWithQueryClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewIndividuallyNestedWithQueryClientWithNoCredential(endpoint string, blobName string, options *IndividuallyNestedWithQueryClientOptions) (*IndividuallyNestedWithQueryClient, error) { + if options == nil { + options = &IndividuallyNestedWithQueryClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &IndividuallyNestedWithQueryClient{ + blobName: blobName, + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// DeleteStandalone - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyNestedWithQueryClientDeleteStandaloneOptions contains the optional parameters for the IndividuallyNestedWithQueryClient.DeleteStandalone +// method. +func (client *IndividuallyNestedWithQueryClient) DeleteStandalone(ctx context.Context, options *IndividuallyNestedWithQueryClientDeleteStandaloneOptions) (IndividuallyNestedWithQueryClientDeleteStandaloneResponse, error) { + var err error + const operationName = "IndividuallyNestedWithQueryClient.DeleteStandalone" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteStandaloneCreateRequest(ctx, options) + if err != nil { + return IndividuallyNestedWithQueryClientDeleteStandaloneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyNestedWithQueryClientDeleteStandaloneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyNestedWithQueryClientDeleteStandaloneResponse{}, err + } + return IndividuallyNestedWithQueryClientDeleteStandaloneResponse{}, nil +} + +// deleteStandaloneCreateRequest creates the DeleteStandalone request. +func (client *IndividuallyNestedWithQueryClient) deleteStandaloneCreateRequest(ctx context.Context, _ *IndividuallyNestedWithQueryClientDeleteStandaloneOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually/nested-default-individually-query/delete-resource" + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("blobName", client.blobName) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// GetStandalone - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyNestedWithQueryClientGetStandaloneOptions contains the optional parameters for the IndividuallyNestedWithQueryClient.GetStandalone +// method. +func (client *IndividuallyNestedWithQueryClient) GetStandalone(ctx context.Context, options *IndividuallyNestedWithQueryClientGetStandaloneOptions) (IndividuallyNestedWithQueryClientGetStandaloneResponse, error) { + var err error + const operationName = "IndividuallyNestedWithQueryClient.GetStandalone" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getStandaloneCreateRequest(ctx, options) + if err != nil { + return IndividuallyNestedWithQueryClientGetStandaloneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyNestedWithQueryClientGetStandaloneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return IndividuallyNestedWithQueryClientGetStandaloneResponse{}, err + } + resp, err := client.getStandaloneHandleResponse(httpResp) + return resp, err +} + +// getStandaloneCreateRequest creates the GetStandalone request. +func (client *IndividuallyNestedWithQueryClient) getStandaloneCreateRequest(ctx context.Context, _ *IndividuallyNestedWithQueryClientGetStandaloneOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually/nested-default-individually-query/get-standalone" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("blobName", client.blobName) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getStandaloneHandleResponse handles the GetStandalone response. +func (client *IndividuallyNestedWithQueryClient) getStandaloneHandleResponse(resp *http.Response) (IndividuallyNestedWithQueryClientGetStandaloneResponse, error) { + result := IndividuallyNestedWithQueryClientGetStandaloneResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BlobProperties); err != nil { + return IndividuallyNestedWithQueryClientGetStandaloneResponse{}, err + } + return result, nil +} + +// WithQuery - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyNestedWithQueryClientWithQueryOptions contains the optional parameters for the IndividuallyNestedWithQueryClient.WithQuery +// method. +func (client *IndividuallyNestedWithQueryClient) WithQuery(ctx context.Context, options *IndividuallyNestedWithQueryClientWithQueryOptions) (IndividuallyNestedWithQueryClientWithQueryResponse, error) { + var err error + const operationName = "IndividuallyNestedWithQueryClient.WithQuery" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withQueryCreateRequest(ctx, options) + if err != nil { + return IndividuallyNestedWithQueryClientWithQueryResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyNestedWithQueryClientWithQueryResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyNestedWithQueryClientWithQueryResponse{}, err + } + return IndividuallyNestedWithQueryClientWithQueryResponse{}, nil +} + +// withQueryCreateRequest creates the WithQuery request. +func (client *IndividuallyNestedWithQueryClient) withQueryCreateRequest(ctx context.Context, options *IndividuallyNestedWithQueryClientWithQueryOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually/nested-default-individually-query/with-query" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("blobName", client.blobName) + if options != nil && options.Format != nil { + reqQP.Set("format", *options.Format) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_models.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_models.go new file mode 100644 index 000000000000..2b042a08511a --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_models.go @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitindividuallygroup + +import "time" + +// BlobProperties - Properties of a blob +type BlobProperties struct { + // REQUIRED + ContentType *string + + // REQUIRED + CreatedOn *time.Time + + // REQUIRED + Name *string + + // REQUIRED + Size *int64 +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_models_serde.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_models_serde.go new file mode 100644 index 000000000000..1b2d375db7dd --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_models_serde.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitindividuallygroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type BlobProperties. +func (b BlobProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "contentType", b.ContentType) + populateTime[datetime.RFC3339](objectMap, "createdOn", b.CreatedOn) + populate(objectMap, "name", b.Name) + populate(objectMap, "size", b.Size) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BlobProperties. +func (b *BlobProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "contentType": + err = unpopulate(val, "ContentType", &b.ContentType) + delete(rawMsg, key) + case "createdOn": + err = unpopulateTime[datetime.RFC3339](val, "CreatedOn", &b.CreatedOn) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &b.Name) + delete(rawMsg, key) + case "size": + err = unpopulate(val, "Size", &b.Size) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_options.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_options.go new file mode 100644 index 000000000000..878d0fc8a560 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_options.go @@ -0,0 +1,107 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitindividuallygroup + +// IndividuallyNestedWithHeaderClientDeleteStandaloneOptions contains the optional parameters for the IndividuallyNestedWithHeaderClient.DeleteStandalone +// method. +type IndividuallyNestedWithHeaderClientDeleteStandaloneOptions struct { + // placeholder for future optional parameters +} + +// IndividuallyNestedWithHeaderClientGetStandaloneOptions contains the optional parameters for the IndividuallyNestedWithHeaderClient.GetStandalone +// method. +type IndividuallyNestedWithHeaderClientGetStandaloneOptions struct { + // placeholder for future optional parameters +} + +// IndividuallyNestedWithHeaderClientWithQueryOptions contains the optional parameters for the IndividuallyNestedWithHeaderClient.WithQuery +// method. +type IndividuallyNestedWithHeaderClientWithQueryOptions struct { + Format *string +} + +// IndividuallyNestedWithMixedClientDeleteStandaloneOptions contains the optional parameters for the IndividuallyNestedWithMixedClient.DeleteStandalone +// method. +type IndividuallyNestedWithMixedClientDeleteStandaloneOptions struct { + // placeholder for future optional parameters +} + +// IndividuallyNestedWithMixedClientGetStandaloneOptions contains the optional parameters for the IndividuallyNestedWithMixedClient.GetStandalone +// method. +type IndividuallyNestedWithMixedClientGetStandaloneOptions struct { + // placeholder for future optional parameters +} + +// IndividuallyNestedWithMixedClientWithQueryOptions contains the optional parameters for the IndividuallyNestedWithMixedClient.WithQuery +// method. +type IndividuallyNestedWithMixedClientWithQueryOptions struct { + Format *string +} + +// IndividuallyNestedWithMultipleClientDeleteStandaloneOptions contains the optional parameters for the IndividuallyNestedWithMultipleClient.DeleteStandalone +// method. +type IndividuallyNestedWithMultipleClientDeleteStandaloneOptions struct { + // placeholder for future optional parameters +} + +// IndividuallyNestedWithMultipleClientGetStandaloneOptions contains the optional parameters for the IndividuallyNestedWithMultipleClient.GetStandalone +// method. +type IndividuallyNestedWithMultipleClientGetStandaloneOptions struct { + // placeholder for future optional parameters +} + +// IndividuallyNestedWithMultipleClientWithQueryOptions contains the optional parameters for the IndividuallyNestedWithMultipleClient.WithQuery +// method. +type IndividuallyNestedWithMultipleClientWithQueryOptions struct { + Format *string +} + +// IndividuallyNestedWithParamAliasClientWithAliasedNameOptions contains the optional parameters for the IndividuallyNestedWithParamAliasClient.WithAliasedName +// method. +type IndividuallyNestedWithParamAliasClientWithAliasedNameOptions struct { + // placeholder for future optional parameters +} + +// IndividuallyNestedWithParamAliasClientWithOriginalNameOptions contains the optional parameters for the IndividuallyNestedWithParamAliasClient.WithOriginalName +// method. +type IndividuallyNestedWithParamAliasClientWithOriginalNameOptions struct { + // placeholder for future optional parameters +} + +// IndividuallyNestedWithPathClientDeleteStandaloneOptions contains the optional parameters for the IndividuallyNestedWithPathClient.DeleteStandalone +// method. +type IndividuallyNestedWithPathClientDeleteStandaloneOptions struct { + // placeholder for future optional parameters +} + +// IndividuallyNestedWithPathClientGetStandaloneOptions contains the optional parameters for the IndividuallyNestedWithPathClient.GetStandalone +// method. +type IndividuallyNestedWithPathClientGetStandaloneOptions struct { + // placeholder for future optional parameters +} + +// IndividuallyNestedWithPathClientWithQueryOptions contains the optional parameters for the IndividuallyNestedWithPathClient.WithQuery +// method. +type IndividuallyNestedWithPathClientWithQueryOptions struct { + Format *string +} + +// IndividuallyNestedWithQueryClientDeleteStandaloneOptions contains the optional parameters for the IndividuallyNestedWithQueryClient.DeleteStandalone +// method. +type IndividuallyNestedWithQueryClientDeleteStandaloneOptions struct { + // placeholder for future optional parameters +} + +// IndividuallyNestedWithQueryClientGetStandaloneOptions contains the optional parameters for the IndividuallyNestedWithQueryClient.GetStandalone +// method. +type IndividuallyNestedWithQueryClientGetStandaloneOptions struct { + // placeholder for future optional parameters +} + +// IndividuallyNestedWithQueryClientWithQueryOptions contains the optional parameters for the IndividuallyNestedWithQueryClient.WithQuery +// method. +type IndividuallyNestedWithQueryClientWithQueryOptions struct { + Format *string +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_responses.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_responses.go new file mode 100644 index 000000000000..044ce1a2d136 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_responses.go @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitindividuallygroup + +// IndividuallyNestedWithHeaderClientDeleteStandaloneResponse contains the response from method IndividuallyNestedWithHeaderClient.DeleteStandalone. +type IndividuallyNestedWithHeaderClientDeleteStandaloneResponse struct { + // placeholder for future response values +} + +// IndividuallyNestedWithHeaderClientGetStandaloneResponse contains the response from method IndividuallyNestedWithHeaderClient.GetStandalone. +type IndividuallyNestedWithHeaderClientGetStandaloneResponse struct { + // placeholder for future response values +} + +// IndividuallyNestedWithHeaderClientWithQueryResponse contains the response from method IndividuallyNestedWithHeaderClient.WithQuery. +type IndividuallyNestedWithHeaderClientWithQueryResponse struct { + // placeholder for future response values +} + +// IndividuallyNestedWithMixedClientDeleteStandaloneResponse contains the response from method IndividuallyNestedWithMixedClient.DeleteStandalone. +type IndividuallyNestedWithMixedClientDeleteStandaloneResponse struct { + // placeholder for future response values +} + +// IndividuallyNestedWithMixedClientGetStandaloneResponse contains the response from method IndividuallyNestedWithMixedClient.GetStandalone. +type IndividuallyNestedWithMixedClientGetStandaloneResponse struct { + // placeholder for future response values +} + +// IndividuallyNestedWithMixedClientWithQueryResponse contains the response from method IndividuallyNestedWithMixedClient.WithQuery. +type IndividuallyNestedWithMixedClientWithQueryResponse struct { + // placeholder for future response values +} + +// IndividuallyNestedWithMultipleClientDeleteStandaloneResponse contains the response from method IndividuallyNestedWithMultipleClient.DeleteStandalone. +type IndividuallyNestedWithMultipleClientDeleteStandaloneResponse struct { + // placeholder for future response values +} + +// IndividuallyNestedWithMultipleClientGetStandaloneResponse contains the response from method IndividuallyNestedWithMultipleClient.GetStandalone. +type IndividuallyNestedWithMultipleClientGetStandaloneResponse struct { + // placeholder for future response values +} + +// IndividuallyNestedWithMultipleClientWithQueryResponse contains the response from method IndividuallyNestedWithMultipleClient.WithQuery. +type IndividuallyNestedWithMultipleClientWithQueryResponse struct { + // placeholder for future response values +} + +// IndividuallyNestedWithParamAliasClientWithAliasedNameResponse contains the response from method IndividuallyNestedWithParamAliasClient.WithAliasedName. +type IndividuallyNestedWithParamAliasClientWithAliasedNameResponse struct { + // placeholder for future response values +} + +// IndividuallyNestedWithParamAliasClientWithOriginalNameResponse contains the response from method IndividuallyNestedWithParamAliasClient.WithOriginalName. +type IndividuallyNestedWithParamAliasClientWithOriginalNameResponse struct { + // placeholder for future response values +} + +// IndividuallyNestedWithPathClientDeleteStandaloneResponse contains the response from method IndividuallyNestedWithPathClient.DeleteStandalone. +type IndividuallyNestedWithPathClientDeleteStandaloneResponse struct { + // placeholder for future response values +} + +// IndividuallyNestedWithPathClientGetStandaloneResponse contains the response from method IndividuallyNestedWithPathClient.GetStandalone. +type IndividuallyNestedWithPathClientGetStandaloneResponse struct { + // Properties of a blob + BlobProperties +} + +// IndividuallyNestedWithPathClientWithQueryResponse contains the response from method IndividuallyNestedWithPathClient.WithQuery. +type IndividuallyNestedWithPathClientWithQueryResponse struct { + // placeholder for future response values +} + +// IndividuallyNestedWithQueryClientDeleteStandaloneResponse contains the response from method IndividuallyNestedWithQueryClient.DeleteStandalone. +type IndividuallyNestedWithQueryClientDeleteStandaloneResponse struct { + // placeholder for future response values +} + +// IndividuallyNestedWithQueryClientGetStandaloneResponse contains the response from method IndividuallyNestedWithQueryClient.GetStandalone. +type IndividuallyNestedWithQueryClientGetStandaloneResponse struct { + // Properties of a blob + BlobProperties +} + +// IndividuallyNestedWithQueryClientWithQueryResponse contains the response from method IndividuallyNestedWithQueryClient.WithQuery. +type IndividuallyNestedWithQueryClientWithQueryResponse struct { + // placeholder for future response values +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_version.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_version.go new file mode 100644 index 000000000000..2bc4c047e001 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallygroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package clientinitindividuallygroup + +const ( + moduleName = "clientinitindividuallygroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/LICENSE.txt b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparent_server.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparent_server.go new file mode 100644 index 000000000000..da6194331b1f --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparent_server.go @@ -0,0 +1,114 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// IndividuallyParentServer is a fake server for instances of the clientinitindividuallyparentgroup.IndividuallyParentClient type. +type IndividuallyParentServer struct { + // IndividuallyParentIndividuallyParentNestedWithHeaderServer contains the fakes for client IndividuallyParentIndividuallyParentNestedWithHeaderClient + IndividuallyParentIndividuallyParentNestedWithHeaderServer IndividuallyParentIndividuallyParentNestedWithHeaderServer + + // IndividuallyParentIndividuallyParentNestedWithMixedServer contains the fakes for client IndividuallyParentIndividuallyParentNestedWithMixedClient + IndividuallyParentIndividuallyParentNestedWithMixedServer IndividuallyParentIndividuallyParentNestedWithMixedServer + + // IndividuallyParentIndividuallyParentNestedWithMultipleServer contains the fakes for client IndividuallyParentIndividuallyParentNestedWithMultipleClient + IndividuallyParentIndividuallyParentNestedWithMultipleServer IndividuallyParentIndividuallyParentNestedWithMultipleServer + + // IndividuallyParentIndividuallyParentNestedWithParamAliasServer contains the fakes for client IndividuallyParentIndividuallyParentNestedWithParamAliasClient + IndividuallyParentIndividuallyParentNestedWithParamAliasServer IndividuallyParentIndividuallyParentNestedWithParamAliasServer + + // IndividuallyParentIndividuallyParentNestedWithPathServer contains the fakes for client IndividuallyParentIndividuallyParentNestedWithPathClient + IndividuallyParentIndividuallyParentNestedWithPathServer IndividuallyParentIndividuallyParentNestedWithPathServer + + // IndividuallyParentIndividuallyParentNestedWithQueryServer contains the fakes for client IndividuallyParentIndividuallyParentNestedWithQueryClient + IndividuallyParentIndividuallyParentNestedWithQueryServer IndividuallyParentIndividuallyParentNestedWithQueryServer +} + +// NewIndividuallyParentServerTransport creates a new instance of IndividuallyParentServerTransport with the provided implementation. +// The returned IndividuallyParentServerTransport instance is connected to an instance of clientinitindividuallyparentgroup.IndividuallyParentClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewIndividuallyParentServerTransport(srv *IndividuallyParentServer) *IndividuallyParentServerTransport { + return &IndividuallyParentServerTransport{srv: srv} +} + +// IndividuallyParentServerTransport connects instances of clientinitindividuallyparentgroup.IndividuallyParentClient to instances of IndividuallyParentServer. +// Don't use this type directly, use NewIndividuallyParentServerTransport instead. +type IndividuallyParentServerTransport struct { + srv *IndividuallyParentServer + trMu sync.Mutex + trIndividuallyParentIndividuallyParentNestedWithHeaderServer *IndividuallyParentIndividuallyParentNestedWithHeaderServerTransport + trIndividuallyParentIndividuallyParentNestedWithMixedServer *IndividuallyParentIndividuallyParentNestedWithMixedServerTransport + trIndividuallyParentIndividuallyParentNestedWithMultipleServer *IndividuallyParentIndividuallyParentNestedWithMultipleServerTransport + trIndividuallyParentIndividuallyParentNestedWithParamAliasServer *IndividuallyParentIndividuallyParentNestedWithParamAliasServerTransport + trIndividuallyParentIndividuallyParentNestedWithPathServer *IndividuallyParentIndividuallyParentNestedWithPathServerTransport + trIndividuallyParentIndividuallyParentNestedWithQueryServer *IndividuallyParentIndividuallyParentNestedWithQueryServerTransport +} + +// Do implements the policy.Transporter interface for IndividuallyParentServerTransport. +func (i *IndividuallyParentServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return i.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (i *IndividuallyParentServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "IndividuallyParentIndividuallyParentNestedWithHeaderClient": + initServer(&i.trMu, &i.trIndividuallyParentIndividuallyParentNestedWithHeaderServer, func() *IndividuallyParentIndividuallyParentNestedWithHeaderServerTransport { + return NewIndividuallyParentIndividuallyParentNestedWithHeaderServerTransport(&i.srv.IndividuallyParentIndividuallyParentNestedWithHeaderServer) + }) + resp, err = i.trIndividuallyParentIndividuallyParentNestedWithHeaderServer.Do(req) + case "IndividuallyParentIndividuallyParentNestedWithMixedClient": + initServer(&i.trMu, &i.trIndividuallyParentIndividuallyParentNestedWithMixedServer, func() *IndividuallyParentIndividuallyParentNestedWithMixedServerTransport { + return NewIndividuallyParentIndividuallyParentNestedWithMixedServerTransport(&i.srv.IndividuallyParentIndividuallyParentNestedWithMixedServer) + }) + resp, err = i.trIndividuallyParentIndividuallyParentNestedWithMixedServer.Do(req) + case "IndividuallyParentIndividuallyParentNestedWithMultipleClient": + initServer(&i.trMu, &i.trIndividuallyParentIndividuallyParentNestedWithMultipleServer, func() *IndividuallyParentIndividuallyParentNestedWithMultipleServerTransport { + return NewIndividuallyParentIndividuallyParentNestedWithMultipleServerTransport(&i.srv.IndividuallyParentIndividuallyParentNestedWithMultipleServer) + }) + resp, err = i.trIndividuallyParentIndividuallyParentNestedWithMultipleServer.Do(req) + case "IndividuallyParentIndividuallyParentNestedWithParamAliasClient": + initServer(&i.trMu, &i.trIndividuallyParentIndividuallyParentNestedWithParamAliasServer, func() *IndividuallyParentIndividuallyParentNestedWithParamAliasServerTransport { + return NewIndividuallyParentIndividuallyParentNestedWithParamAliasServerTransport(&i.srv.IndividuallyParentIndividuallyParentNestedWithParamAliasServer) + }) + resp, err = i.trIndividuallyParentIndividuallyParentNestedWithParamAliasServer.Do(req) + case "IndividuallyParentIndividuallyParentNestedWithPathClient": + initServer(&i.trMu, &i.trIndividuallyParentIndividuallyParentNestedWithPathServer, func() *IndividuallyParentIndividuallyParentNestedWithPathServerTransport { + return NewIndividuallyParentIndividuallyParentNestedWithPathServerTransport(&i.srv.IndividuallyParentIndividuallyParentNestedWithPathServer) + }) + resp, err = i.trIndividuallyParentIndividuallyParentNestedWithPathServer.Do(req) + case "IndividuallyParentIndividuallyParentNestedWithQueryClient": + initServer(&i.trMu, &i.trIndividuallyParentIndividuallyParentNestedWithQueryServer, func() *IndividuallyParentIndividuallyParentNestedWithQueryServerTransport { + return NewIndividuallyParentIndividuallyParentNestedWithQueryServerTransport(&i.srv.IndividuallyParentIndividuallyParentNestedWithQueryServer) + }) + resp, err = i.trIndividuallyParentIndividuallyParentNestedWithQueryServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to IndividuallyParentServerTransport +var individuallyParentServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparentindividuallyparentnestedwithheader_server.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparentindividuallyparentnestedwithheader_server.go new file mode 100644 index 000000000000..87c77390a5da --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparentindividuallyparentnestedwithheader_server.go @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "clientinitindividuallyparentgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// IndividuallyParentIndividuallyParentNestedWithHeaderServer is a fake server for instances of the clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithHeaderClient type. +type IndividuallyParentIndividuallyParentNestedWithHeaderServer struct { + // DeleteStandalone is the fake for method IndividuallyParentIndividuallyParentNestedWithHeaderClient.DeleteStandalone + // HTTP status codes to indicate success: http.StatusNoContent + DeleteStandalone func(ctx context.Context, options *clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithHeaderClientDeleteStandaloneOptions) (resp azfake.Responder[clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithHeaderClientDeleteStandaloneResponse], errResp azfake.ErrorResponder) + + // GetStandalone is the fake for method IndividuallyParentIndividuallyParentNestedWithHeaderClient.GetStandalone + // HTTP status codes to indicate success: http.StatusNoContent + GetStandalone func(ctx context.Context, options *clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithHeaderClientGetStandaloneOptions) (resp azfake.Responder[clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithHeaderClientGetStandaloneResponse], errResp azfake.ErrorResponder) + + // WithQuery is the fake for method IndividuallyParentIndividuallyParentNestedWithHeaderClient.WithQuery + // HTTP status codes to indicate success: http.StatusNoContent + WithQuery func(ctx context.Context, options *clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithHeaderClientWithQueryOptions) (resp azfake.Responder[clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithHeaderClientWithQueryResponse], errResp azfake.ErrorResponder) +} + +// NewIndividuallyParentIndividuallyParentNestedWithHeaderServerTransport creates a new instance of IndividuallyParentIndividuallyParentNestedWithHeaderServerTransport with the provided implementation. +// The returned IndividuallyParentIndividuallyParentNestedWithHeaderServerTransport instance is connected to an instance of clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithHeaderClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewIndividuallyParentIndividuallyParentNestedWithHeaderServerTransport(srv *IndividuallyParentIndividuallyParentNestedWithHeaderServer) *IndividuallyParentIndividuallyParentNestedWithHeaderServerTransport { + return &IndividuallyParentIndividuallyParentNestedWithHeaderServerTransport{srv: srv} +} + +// IndividuallyParentIndividuallyParentNestedWithHeaderServerTransport connects instances of clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithHeaderClient to instances of IndividuallyParentIndividuallyParentNestedWithHeaderServer. +// Don't use this type directly, use NewIndividuallyParentIndividuallyParentNestedWithHeaderServerTransport instead. +type IndividuallyParentIndividuallyParentNestedWithHeaderServerTransport struct { + srv *IndividuallyParentIndividuallyParentNestedWithHeaderServer +} + +// Do implements the policy.Transporter interface for IndividuallyParentIndividuallyParentNestedWithHeaderServerTransport. +func (i *IndividuallyParentIndividuallyParentNestedWithHeaderServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return i.dispatchToMethodFake(req, method) +} + +func (i *IndividuallyParentIndividuallyParentNestedWithHeaderServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if individuallyParentIndividuallyParentNestedWithHeaderServerTransportInterceptor != nil { + res.resp, res.err, intercepted = individuallyParentIndividuallyParentNestedWithHeaderServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "IndividuallyParentIndividuallyParentNestedWithHeaderClient.DeleteStandalone": + res.resp, res.err = i.dispatchDeleteStandalone(req) + case "IndividuallyParentIndividuallyParentNestedWithHeaderClient.GetStandalone": + res.resp, res.err = i.dispatchGetStandalone(req) + case "IndividuallyParentIndividuallyParentNestedWithHeaderClient.WithQuery": + res.resp, res.err = i.dispatchWithQuery(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (i *IndividuallyParentIndividuallyParentNestedWithHeaderServerTransport) dispatchDeleteStandalone(req *http.Request) (*http.Response, error) { + if i.srv.DeleteStandalone == nil { + return nil, &nonRetriableError{errors.New("fake for method DeleteStandalone not implemented")} + } + respr, errRespr := i.srv.DeleteStandalone(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (i *IndividuallyParentIndividuallyParentNestedWithHeaderServerTransport) dispatchGetStandalone(req *http.Request) (*http.Response, error) { + if i.srv.GetStandalone == nil { + return nil, &nonRetriableError{errors.New("fake for method GetStandalone not implemented")} + } + respr, errRespr := i.srv.GetStandalone(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (i *IndividuallyParentIndividuallyParentNestedWithHeaderServerTransport) dispatchWithQuery(req *http.Request) (*http.Response, error) { + if i.srv.WithQuery == nil { + return nil, &nonRetriableError{errors.New("fake for method WithQuery not implemented")} + } + qp := req.URL.Query() + formatParam := getOptional(qp.Get("format")) + var options *clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithHeaderClientWithQueryOptions + if formatParam != nil { + options = &clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithHeaderClientWithQueryOptions{ + Format: formatParam, + } + } + respr, errRespr := i.srv.WithQuery(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to IndividuallyParentIndividuallyParentNestedWithHeaderServerTransport +var individuallyParentIndividuallyParentNestedWithHeaderServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparentindividuallyparentnestedwithmixed_server.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparentindividuallyparentnestedwithmixed_server.go new file mode 100644 index 000000000000..34a8c59a11d8 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparentindividuallyparentnestedwithmixed_server.go @@ -0,0 +1,161 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "clientinitindividuallyparentgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// IndividuallyParentIndividuallyParentNestedWithMixedServer is a fake server for instances of the clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithMixedClient type. +type IndividuallyParentIndividuallyParentNestedWithMixedServer struct { + // DeleteStandalone is the fake for method IndividuallyParentIndividuallyParentNestedWithMixedClient.DeleteStandalone + // HTTP status codes to indicate success: http.StatusNoContent + DeleteStandalone func(ctx context.Context, region string, options *clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithMixedClientDeleteStandaloneOptions) (resp azfake.Responder[clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithMixedClientDeleteStandaloneResponse], errResp azfake.ErrorResponder) + + // GetStandalone is the fake for method IndividuallyParentIndividuallyParentNestedWithMixedClient.GetStandalone + // HTTP status codes to indicate success: http.StatusNoContent + GetStandalone func(ctx context.Context, region string, options *clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithMixedClientGetStandaloneOptions) (resp azfake.Responder[clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithMixedClientGetStandaloneResponse], errResp azfake.ErrorResponder) + + // WithQuery is the fake for method IndividuallyParentIndividuallyParentNestedWithMixedClient.WithQuery + // HTTP status codes to indicate success: http.StatusNoContent + WithQuery func(ctx context.Context, region string, options *clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithMixedClientWithQueryOptions) (resp azfake.Responder[clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithMixedClientWithQueryResponse], errResp azfake.ErrorResponder) +} + +// NewIndividuallyParentIndividuallyParentNestedWithMixedServerTransport creates a new instance of IndividuallyParentIndividuallyParentNestedWithMixedServerTransport with the provided implementation. +// The returned IndividuallyParentIndividuallyParentNestedWithMixedServerTransport instance is connected to an instance of clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithMixedClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewIndividuallyParentIndividuallyParentNestedWithMixedServerTransport(srv *IndividuallyParentIndividuallyParentNestedWithMixedServer) *IndividuallyParentIndividuallyParentNestedWithMixedServerTransport { + return &IndividuallyParentIndividuallyParentNestedWithMixedServerTransport{srv: srv} +} + +// IndividuallyParentIndividuallyParentNestedWithMixedServerTransport connects instances of clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithMixedClient to instances of IndividuallyParentIndividuallyParentNestedWithMixedServer. +// Don't use this type directly, use NewIndividuallyParentIndividuallyParentNestedWithMixedServerTransport instead. +type IndividuallyParentIndividuallyParentNestedWithMixedServerTransport struct { + srv *IndividuallyParentIndividuallyParentNestedWithMixedServer +} + +// Do implements the policy.Transporter interface for IndividuallyParentIndividuallyParentNestedWithMixedServerTransport. +func (i *IndividuallyParentIndividuallyParentNestedWithMixedServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return i.dispatchToMethodFake(req, method) +} + +func (i *IndividuallyParentIndividuallyParentNestedWithMixedServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if individuallyParentIndividuallyParentNestedWithMixedServerTransportInterceptor != nil { + res.resp, res.err, intercepted = individuallyParentIndividuallyParentNestedWithMixedServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "IndividuallyParentIndividuallyParentNestedWithMixedClient.DeleteStandalone": + res.resp, res.err = i.dispatchDeleteStandalone(req) + case "IndividuallyParentIndividuallyParentNestedWithMixedClient.GetStandalone": + res.resp, res.err = i.dispatchGetStandalone(req) + case "IndividuallyParentIndividuallyParentNestedWithMixedClient.WithQuery": + res.resp, res.err = i.dispatchWithQuery(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (i *IndividuallyParentIndividuallyParentNestedWithMixedServerTransport) dispatchDeleteStandalone(req *http.Request) (*http.Response, error) { + if i.srv.DeleteStandalone == nil { + return nil, &nonRetriableError{errors.New("fake for method DeleteStandalone not implemented")} + } + qp := req.URL.Query() + respr, errRespr := i.srv.DeleteStandalone(req.Context(), qp.Get("region"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (i *IndividuallyParentIndividuallyParentNestedWithMixedServerTransport) dispatchGetStandalone(req *http.Request) (*http.Response, error) { + if i.srv.GetStandalone == nil { + return nil, &nonRetriableError{errors.New("fake for method GetStandalone not implemented")} + } + qp := req.URL.Query() + respr, errRespr := i.srv.GetStandalone(req.Context(), qp.Get("region"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (i *IndividuallyParentIndividuallyParentNestedWithMixedServerTransport) dispatchWithQuery(req *http.Request) (*http.Response, error) { + if i.srv.WithQuery == nil { + return nil, &nonRetriableError{errors.New("fake for method WithQuery not implemented")} + } + qp := req.URL.Query() + formatParam := getOptional(qp.Get("format")) + var options *clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithMixedClientWithQueryOptions + if formatParam != nil { + options = &clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithMixedClientWithQueryOptions{ + Format: formatParam, + } + } + respr, errRespr := i.srv.WithQuery(req.Context(), qp.Get("region"), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to IndividuallyParentIndividuallyParentNestedWithMixedServerTransport +var individuallyParentIndividuallyParentNestedWithMixedServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparentindividuallyparentnestedwithmultiple_server.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparentindividuallyparentnestedwithmultiple_server.go new file mode 100644 index 000000000000..2829029bcff6 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparentindividuallyparentnestedwithmultiple_server.go @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "clientinitindividuallyparentgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// IndividuallyParentIndividuallyParentNestedWithMultipleServer is a fake server for instances of the clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithMultipleClient type. +type IndividuallyParentIndividuallyParentNestedWithMultipleServer struct { + // DeleteStandalone is the fake for method IndividuallyParentIndividuallyParentNestedWithMultipleClient.DeleteStandalone + // HTTP status codes to indicate success: http.StatusNoContent + DeleteStandalone func(ctx context.Context, options *clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithMultipleClientDeleteStandaloneOptions) (resp azfake.Responder[clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithMultipleClientDeleteStandaloneResponse], errResp azfake.ErrorResponder) + + // GetStandalone is the fake for method IndividuallyParentIndividuallyParentNestedWithMultipleClient.GetStandalone + // HTTP status codes to indicate success: http.StatusNoContent + GetStandalone func(ctx context.Context, options *clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithMultipleClientGetStandaloneOptions) (resp azfake.Responder[clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithMultipleClientGetStandaloneResponse], errResp azfake.ErrorResponder) + + // WithQuery is the fake for method IndividuallyParentIndividuallyParentNestedWithMultipleClient.WithQuery + // HTTP status codes to indicate success: http.StatusNoContent + WithQuery func(ctx context.Context, options *clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithMultipleClientWithQueryOptions) (resp azfake.Responder[clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithMultipleClientWithQueryResponse], errResp azfake.ErrorResponder) +} + +// NewIndividuallyParentIndividuallyParentNestedWithMultipleServerTransport creates a new instance of IndividuallyParentIndividuallyParentNestedWithMultipleServerTransport with the provided implementation. +// The returned IndividuallyParentIndividuallyParentNestedWithMultipleServerTransport instance is connected to an instance of clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithMultipleClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewIndividuallyParentIndividuallyParentNestedWithMultipleServerTransport(srv *IndividuallyParentIndividuallyParentNestedWithMultipleServer) *IndividuallyParentIndividuallyParentNestedWithMultipleServerTransport { + return &IndividuallyParentIndividuallyParentNestedWithMultipleServerTransport{srv: srv} +} + +// IndividuallyParentIndividuallyParentNestedWithMultipleServerTransport connects instances of clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithMultipleClient to instances of IndividuallyParentIndividuallyParentNestedWithMultipleServer. +// Don't use this type directly, use NewIndividuallyParentIndividuallyParentNestedWithMultipleServerTransport instead. +type IndividuallyParentIndividuallyParentNestedWithMultipleServerTransport struct { + srv *IndividuallyParentIndividuallyParentNestedWithMultipleServer +} + +// Do implements the policy.Transporter interface for IndividuallyParentIndividuallyParentNestedWithMultipleServerTransport. +func (i *IndividuallyParentIndividuallyParentNestedWithMultipleServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return i.dispatchToMethodFake(req, method) +} + +func (i *IndividuallyParentIndividuallyParentNestedWithMultipleServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if individuallyParentIndividuallyParentNestedWithMultipleServerTransportInterceptor != nil { + res.resp, res.err, intercepted = individuallyParentIndividuallyParentNestedWithMultipleServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "IndividuallyParentIndividuallyParentNestedWithMultipleClient.DeleteStandalone": + res.resp, res.err = i.dispatchDeleteStandalone(req) + case "IndividuallyParentIndividuallyParentNestedWithMultipleClient.GetStandalone": + res.resp, res.err = i.dispatchGetStandalone(req) + case "IndividuallyParentIndividuallyParentNestedWithMultipleClient.WithQuery": + res.resp, res.err = i.dispatchWithQuery(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (i *IndividuallyParentIndividuallyParentNestedWithMultipleServerTransport) dispatchDeleteStandalone(req *http.Request) (*http.Response, error) { + if i.srv.DeleteStandalone == nil { + return nil, &nonRetriableError{errors.New("fake for method DeleteStandalone not implemented")} + } + respr, errRespr := i.srv.DeleteStandalone(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (i *IndividuallyParentIndividuallyParentNestedWithMultipleServerTransport) dispatchGetStandalone(req *http.Request) (*http.Response, error) { + if i.srv.GetStandalone == nil { + return nil, &nonRetriableError{errors.New("fake for method GetStandalone not implemented")} + } + respr, errRespr := i.srv.GetStandalone(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (i *IndividuallyParentIndividuallyParentNestedWithMultipleServerTransport) dispatchWithQuery(req *http.Request) (*http.Response, error) { + if i.srv.WithQuery == nil { + return nil, &nonRetriableError{errors.New("fake for method WithQuery not implemented")} + } + qp := req.URL.Query() + formatParam := getOptional(qp.Get("format")) + var options *clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithMultipleClientWithQueryOptions + if formatParam != nil { + options = &clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithMultipleClientWithQueryOptions{ + Format: formatParam, + } + } + respr, errRespr := i.srv.WithQuery(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to IndividuallyParentIndividuallyParentNestedWithMultipleServerTransport +var individuallyParentIndividuallyParentNestedWithMultipleServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparentindividuallyparentnestedwithparamalias_server.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparentindividuallyparentnestedwithparamalias_server.go new file mode 100644 index 000000000000..d878ae921cef --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparentindividuallyparentnestedwithparamalias_server.go @@ -0,0 +1,139 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "clientinitindividuallyparentgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "regexp" + "slices" +) + +// IndividuallyParentIndividuallyParentNestedWithParamAliasServer is a fake server for instances of the clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithParamAliasClient type. +type IndividuallyParentIndividuallyParentNestedWithParamAliasServer struct { + // WithAliasedName is the fake for method IndividuallyParentIndividuallyParentNestedWithParamAliasClient.WithAliasedName + // HTTP status codes to indicate success: http.StatusNoContent + WithAliasedName func(ctx context.Context, options *clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithAliasedNameOptions) (resp azfake.Responder[clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithAliasedNameResponse], errResp azfake.ErrorResponder) + + // WithOriginalName is the fake for method IndividuallyParentIndividuallyParentNestedWithParamAliasClient.WithOriginalName + // HTTP status codes to indicate success: http.StatusNoContent + WithOriginalName func(ctx context.Context, options *clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithOriginalNameOptions) (resp azfake.Responder[clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithOriginalNameResponse], errResp azfake.ErrorResponder) +} + +// NewIndividuallyParentIndividuallyParentNestedWithParamAliasServerTransport creates a new instance of IndividuallyParentIndividuallyParentNestedWithParamAliasServerTransport with the provided implementation. +// The returned IndividuallyParentIndividuallyParentNestedWithParamAliasServerTransport instance is connected to an instance of clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithParamAliasClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewIndividuallyParentIndividuallyParentNestedWithParamAliasServerTransport(srv *IndividuallyParentIndividuallyParentNestedWithParamAliasServer) *IndividuallyParentIndividuallyParentNestedWithParamAliasServerTransport { + return &IndividuallyParentIndividuallyParentNestedWithParamAliasServerTransport{srv: srv} +} + +// IndividuallyParentIndividuallyParentNestedWithParamAliasServerTransport connects instances of clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithParamAliasClient to instances of IndividuallyParentIndividuallyParentNestedWithParamAliasServer. +// Don't use this type directly, use NewIndividuallyParentIndividuallyParentNestedWithParamAliasServerTransport instead. +type IndividuallyParentIndividuallyParentNestedWithParamAliasServerTransport struct { + srv *IndividuallyParentIndividuallyParentNestedWithParamAliasServer +} + +// Do implements the policy.Transporter interface for IndividuallyParentIndividuallyParentNestedWithParamAliasServerTransport. +func (i *IndividuallyParentIndividuallyParentNestedWithParamAliasServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return i.dispatchToMethodFake(req, method) +} + +func (i *IndividuallyParentIndividuallyParentNestedWithParamAliasServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if individuallyParentIndividuallyParentNestedWithParamAliasServerTransportInterceptor != nil { + res.resp, res.err, intercepted = individuallyParentIndividuallyParentNestedWithParamAliasServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "IndividuallyParentIndividuallyParentNestedWithParamAliasClient.WithAliasedName": + res.resp, res.err = i.dispatchWithAliasedName(req) + case "IndividuallyParentIndividuallyParentNestedWithParamAliasClient.WithOriginalName": + res.resp, res.err = i.dispatchWithOriginalName(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (i *IndividuallyParentIndividuallyParentNestedWithParamAliasServerTransport) dispatchWithAliasedName(req *http.Request) (*http.Response, error) { + if i.srv.WithAliasedName == nil { + return nil, &nonRetriableError{errors.New("fake for method WithAliasedName not implemented")} + } + const regexStr = `/azure/client-generator-core/client-initialization/individually-parent/nested-default-individually-parent-param-alias/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/with-aliased-name` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + respr, errRespr := i.srv.WithAliasedName(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (i *IndividuallyParentIndividuallyParentNestedWithParamAliasServerTransport) dispatchWithOriginalName(req *http.Request) (*http.Response, error) { + if i.srv.WithOriginalName == nil { + return nil, &nonRetriableError{errors.New("fake for method WithOriginalName not implemented")} + } + const regexStr = `/azure/client-generator-core/client-initialization/individually-parent/nested-default-individually-parent-param-alias/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/with-original-name` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + respr, errRespr := i.srv.WithOriginalName(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to IndividuallyParentIndividuallyParentNestedWithParamAliasServerTransport +var individuallyParentIndividuallyParentNestedWithParamAliasServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparentindividuallyparentnestedwithpath_server.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparentindividuallyparentnestedwithpath_server.go new file mode 100644 index 000000000000..7fd0887d5189 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparentindividuallyparentnestedwithpath_server.go @@ -0,0 +1,178 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "clientinitindividuallyparentgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "regexp" + "slices" +) + +// IndividuallyParentIndividuallyParentNestedWithPathServer is a fake server for instances of the clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithPathClient type. +type IndividuallyParentIndividuallyParentNestedWithPathServer struct { + // DeleteStandalone is the fake for method IndividuallyParentIndividuallyParentNestedWithPathClient.DeleteStandalone + // HTTP status codes to indicate success: http.StatusNoContent + DeleteStandalone func(ctx context.Context, options *clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithPathClientDeleteStandaloneOptions) (resp azfake.Responder[clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithPathClientDeleteStandaloneResponse], errResp azfake.ErrorResponder) + + // GetStandalone is the fake for method IndividuallyParentIndividuallyParentNestedWithPathClient.GetStandalone + // HTTP status codes to indicate success: http.StatusOK + GetStandalone func(ctx context.Context, options *clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithPathClientGetStandaloneOptions) (resp azfake.Responder[clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithPathClientGetStandaloneResponse], errResp azfake.ErrorResponder) + + // WithQuery is the fake for method IndividuallyParentIndividuallyParentNestedWithPathClient.WithQuery + // HTTP status codes to indicate success: http.StatusNoContent + WithQuery func(ctx context.Context, options *clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithPathClientWithQueryOptions) (resp azfake.Responder[clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithPathClientWithQueryResponse], errResp azfake.ErrorResponder) +} + +// NewIndividuallyParentIndividuallyParentNestedWithPathServerTransport creates a new instance of IndividuallyParentIndividuallyParentNestedWithPathServerTransport with the provided implementation. +// The returned IndividuallyParentIndividuallyParentNestedWithPathServerTransport instance is connected to an instance of clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithPathClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewIndividuallyParentIndividuallyParentNestedWithPathServerTransport(srv *IndividuallyParentIndividuallyParentNestedWithPathServer) *IndividuallyParentIndividuallyParentNestedWithPathServerTransport { + return &IndividuallyParentIndividuallyParentNestedWithPathServerTransport{srv: srv} +} + +// IndividuallyParentIndividuallyParentNestedWithPathServerTransport connects instances of clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithPathClient to instances of IndividuallyParentIndividuallyParentNestedWithPathServer. +// Don't use this type directly, use NewIndividuallyParentIndividuallyParentNestedWithPathServerTransport instead. +type IndividuallyParentIndividuallyParentNestedWithPathServerTransport struct { + srv *IndividuallyParentIndividuallyParentNestedWithPathServer +} + +// Do implements the policy.Transporter interface for IndividuallyParentIndividuallyParentNestedWithPathServerTransport. +func (i *IndividuallyParentIndividuallyParentNestedWithPathServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return i.dispatchToMethodFake(req, method) +} + +func (i *IndividuallyParentIndividuallyParentNestedWithPathServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if individuallyParentIndividuallyParentNestedWithPathServerTransportInterceptor != nil { + res.resp, res.err, intercepted = individuallyParentIndividuallyParentNestedWithPathServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "IndividuallyParentIndividuallyParentNestedWithPathClient.DeleteStandalone": + res.resp, res.err = i.dispatchDeleteStandalone(req) + case "IndividuallyParentIndividuallyParentNestedWithPathClient.GetStandalone": + res.resp, res.err = i.dispatchGetStandalone(req) + case "IndividuallyParentIndividuallyParentNestedWithPathClient.WithQuery": + res.resp, res.err = i.dispatchWithQuery(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (i *IndividuallyParentIndividuallyParentNestedWithPathServerTransport) dispatchDeleteStandalone(req *http.Request) (*http.Response, error) { + if i.srv.DeleteStandalone == nil { + return nil, &nonRetriableError{errors.New("fake for method DeleteStandalone not implemented")} + } + const regexStr = `/azure/client-generator-core/client-initialization/individually-parent/nested-default-individually-parent/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + respr, errRespr := i.srv.DeleteStandalone(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (i *IndividuallyParentIndividuallyParentNestedWithPathServerTransport) dispatchGetStandalone(req *http.Request) (*http.Response, error) { + if i.srv.GetStandalone == nil { + return nil, &nonRetriableError{errors.New("fake for method GetStandalone not implemented")} + } + const regexStr = `/azure/client-generator-core/client-initialization/individually-parent/nested-default-individually-parent/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/get-standalone` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + respr, errRespr := i.srv.GetStandalone(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BlobProperties, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (i *IndividuallyParentIndividuallyParentNestedWithPathServerTransport) dispatchWithQuery(req *http.Request) (*http.Response, error) { + if i.srv.WithQuery == nil { + return nil, &nonRetriableError{errors.New("fake for method WithQuery not implemented")} + } + const regexStr = `/azure/client-generator-core/client-initialization/individually-parent/nested-default-individually-parent/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/with-query` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + formatParam := getOptional(qp.Get("format")) + var options *clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithPathClientWithQueryOptions + if formatParam != nil { + options = &clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithPathClientWithQueryOptions{ + Format: formatParam, + } + } + respr, errRespr := i.srv.WithQuery(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to IndividuallyParentIndividuallyParentNestedWithPathServerTransport +var individuallyParentIndividuallyParentNestedWithPathServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparentindividuallyparentnestedwithquery_server.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparentindividuallyparentnestedwithquery_server.go new file mode 100644 index 000000000000..53132bebbd79 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_individuallyparentindividuallyparentnestedwithquery_server.go @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "clientinitindividuallyparentgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// IndividuallyParentIndividuallyParentNestedWithQueryServer is a fake server for instances of the clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithQueryClient type. +type IndividuallyParentIndividuallyParentNestedWithQueryServer struct { + // DeleteStandalone is the fake for method IndividuallyParentIndividuallyParentNestedWithQueryClient.DeleteStandalone + // HTTP status codes to indicate success: http.StatusNoContent + DeleteStandalone func(ctx context.Context, options *clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithQueryClientDeleteStandaloneOptions) (resp azfake.Responder[clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithQueryClientDeleteStandaloneResponse], errResp azfake.ErrorResponder) + + // GetStandalone is the fake for method IndividuallyParentIndividuallyParentNestedWithQueryClient.GetStandalone + // HTTP status codes to indicate success: http.StatusOK + GetStandalone func(ctx context.Context, options *clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithQueryClientGetStandaloneOptions) (resp azfake.Responder[clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithQueryClientGetStandaloneResponse], errResp azfake.ErrorResponder) + + // WithQuery is the fake for method IndividuallyParentIndividuallyParentNestedWithQueryClient.WithQuery + // HTTP status codes to indicate success: http.StatusNoContent + WithQuery func(ctx context.Context, options *clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithQueryClientWithQueryOptions) (resp azfake.Responder[clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithQueryClientWithQueryResponse], errResp azfake.ErrorResponder) +} + +// NewIndividuallyParentIndividuallyParentNestedWithQueryServerTransport creates a new instance of IndividuallyParentIndividuallyParentNestedWithQueryServerTransport with the provided implementation. +// The returned IndividuallyParentIndividuallyParentNestedWithQueryServerTransport instance is connected to an instance of clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithQueryClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewIndividuallyParentIndividuallyParentNestedWithQueryServerTransport(srv *IndividuallyParentIndividuallyParentNestedWithQueryServer) *IndividuallyParentIndividuallyParentNestedWithQueryServerTransport { + return &IndividuallyParentIndividuallyParentNestedWithQueryServerTransport{srv: srv} +} + +// IndividuallyParentIndividuallyParentNestedWithQueryServerTransport connects instances of clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithQueryClient to instances of IndividuallyParentIndividuallyParentNestedWithQueryServer. +// Don't use this type directly, use NewIndividuallyParentIndividuallyParentNestedWithQueryServerTransport instead. +type IndividuallyParentIndividuallyParentNestedWithQueryServerTransport struct { + srv *IndividuallyParentIndividuallyParentNestedWithQueryServer +} + +// Do implements the policy.Transporter interface for IndividuallyParentIndividuallyParentNestedWithQueryServerTransport. +func (i *IndividuallyParentIndividuallyParentNestedWithQueryServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return i.dispatchToMethodFake(req, method) +} + +func (i *IndividuallyParentIndividuallyParentNestedWithQueryServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if individuallyParentIndividuallyParentNestedWithQueryServerTransportInterceptor != nil { + res.resp, res.err, intercepted = individuallyParentIndividuallyParentNestedWithQueryServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "IndividuallyParentIndividuallyParentNestedWithQueryClient.DeleteStandalone": + res.resp, res.err = i.dispatchDeleteStandalone(req) + case "IndividuallyParentIndividuallyParentNestedWithQueryClient.GetStandalone": + res.resp, res.err = i.dispatchGetStandalone(req) + case "IndividuallyParentIndividuallyParentNestedWithQueryClient.WithQuery": + res.resp, res.err = i.dispatchWithQuery(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (i *IndividuallyParentIndividuallyParentNestedWithQueryServerTransport) dispatchDeleteStandalone(req *http.Request) (*http.Response, error) { + if i.srv.DeleteStandalone == nil { + return nil, &nonRetriableError{errors.New("fake for method DeleteStandalone not implemented")} + } + respr, errRespr := i.srv.DeleteStandalone(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (i *IndividuallyParentIndividuallyParentNestedWithQueryServerTransport) dispatchGetStandalone(req *http.Request) (*http.Response, error) { + if i.srv.GetStandalone == nil { + return nil, &nonRetriableError{errors.New("fake for method GetStandalone not implemented")} + } + respr, errRespr := i.srv.GetStandalone(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BlobProperties, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (i *IndividuallyParentIndividuallyParentNestedWithQueryServerTransport) dispatchWithQuery(req *http.Request) (*http.Response, error) { + if i.srv.WithQuery == nil { + return nil, &nonRetriableError{errors.New("fake for method WithQuery not implemented")} + } + qp := req.URL.Query() + formatParam := getOptional(qp.Get("format")) + var options *clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithQueryClientWithQueryOptions + if formatParam != nil { + options = &clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithQueryClientWithQueryOptions{ + Format: formatParam, + } + } + respr, errRespr := i.srv.WithQuery(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to IndividuallyParentIndividuallyParentNestedWithQueryServerTransport +var individuallyParentIndividuallyParentNestedWithQueryServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_internal.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_internal.go new file mode 100644 index 000000000000..35b717171f62 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/fake/zz_internal.go @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "reflect" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getOptional[T any](v T) *T { + if reflect.ValueOf(v).IsZero() { + return nil + } + return &v +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/go.mod b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/go.mod new file mode 100644 index 000000000000..a6878378c5d2 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/go.mod @@ -0,0 +1,17 @@ +module clientinitindividuallyparentgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/go.sum b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/individuallyparentindividuallyparentnestedwithheader_client_test.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/individuallyparentindividuallyparentnestedwithheader_client_test.go new file mode 100644 index 000000000000..a7779c4c5d11 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/individuallyparentindividuallyparentnestedwithheader_client_test.go @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package clientinitindividuallyparentgroup_test + +import ( + "clientinitindividuallyparentgroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestIndividuallyParentNestedWithHeaderClient_WithQuery(t *testing.T) { + parentClient, err := clientinitindividuallyparentgroup.NewIndividuallyParentClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + client := parentClient.NewIndividuallyParentIndividuallyParentNestedWithHeaderClient("test-name-value") + resp, err := client.WithQuery(context.Background(), &clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithHeaderClientWithQueryOptions{ + Format: to.Ptr("text"), + }) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestIndividuallyParentNestedWithHeaderClient_GetStandalone(t *testing.T) { + parentClient, err := clientinitindividuallyparentgroup.NewIndividuallyParentClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + client := parentClient.NewIndividuallyParentIndividuallyParentNestedWithHeaderClient("test-name-value") + resp, err := client.GetStandalone(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestIndividuallyParentNestedWithHeaderClient_DeleteStandalone(t *testing.T) { + parentClient, err := clientinitindividuallyparentgroup.NewIndividuallyParentClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + client := parentClient.NewIndividuallyParentIndividuallyParentNestedWithHeaderClient("test-name-value") + resp, err := client.DeleteStandalone(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/individuallyparentindividuallyparentnestedwithmixed_client_test.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/individuallyparentindividuallyparentnestedwithmixed_client_test.go new file mode 100644 index 000000000000..744de0a35fec --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/individuallyparentindividuallyparentnestedwithmixed_client_test.go @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package clientinitindividuallyparentgroup_test + +import ( + "clientinitindividuallyparentgroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestIndividuallyParentNestedWithMixedClient_WithQuery(t *testing.T) { + parentClient, err := clientinitindividuallyparentgroup.NewIndividuallyParentClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + client := parentClient.NewIndividuallyParentIndividuallyParentNestedWithMixedClient("test-name-value") + resp, err := client.WithQuery(context.Background(), "us-west", &clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithMixedClientWithQueryOptions{ + Format: to.Ptr("text"), + }) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestIndividuallyParentNestedWithMixedClient_GetStandalone(t *testing.T) { + parentClient, err := clientinitindividuallyparentgroup.NewIndividuallyParentClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + client := parentClient.NewIndividuallyParentIndividuallyParentNestedWithMixedClient("test-name-value") + resp, err := client.GetStandalone(context.Background(), "us-west", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestIndividuallyParentNestedWithMixedClient_DeleteStandalone(t *testing.T) { + parentClient, err := clientinitindividuallyparentgroup.NewIndividuallyParentClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + client := parentClient.NewIndividuallyParentIndividuallyParentNestedWithMixedClient("test-name-value") + resp, err := client.DeleteStandalone(context.Background(), "us-west", nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/individuallyparentindividuallyparentnestedwithmultiple_client_test.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/individuallyparentindividuallyparentnestedwithmultiple_client_test.go new file mode 100644 index 000000000000..6727c34e78b4 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/individuallyparentindividuallyparentnestedwithmultiple_client_test.go @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package clientinitindividuallyparentgroup_test + +import ( + "clientinitindividuallyparentgroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestIndividuallyParentNestedWithMultipleClient_WithQuery(t *testing.T) { + parentClient, err := clientinitindividuallyparentgroup.NewIndividuallyParentClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + client := parentClient.NewIndividuallyParentIndividuallyParentNestedWithMultipleClient("test-name-value", "us-west") + resp, err := client.WithQuery(context.Background(), &clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithMultipleClientWithQueryOptions{ + Format: to.Ptr("text"), + }) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestIndividuallyParentNestedWithMultipleClient_GetStandalone(t *testing.T) { + parentClient, err := clientinitindividuallyparentgroup.NewIndividuallyParentClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + client := parentClient.NewIndividuallyParentIndividuallyParentNestedWithMultipleClient("test-name-value", "us-west") + resp, err := client.GetStandalone(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestIndividuallyParentNestedWithMultipleClient_DeleteStandalone(t *testing.T) { + parentClient, err := clientinitindividuallyparentgroup.NewIndividuallyParentClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + client := parentClient.NewIndividuallyParentIndividuallyParentNestedWithMultipleClient("test-name-value", "us-west") + resp, err := client.DeleteStandalone(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/individuallyparentindividuallyparentnestedwithparamalias_client_test.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/individuallyparentindividuallyparentnestedwithparamalias_client_test.go new file mode 100644 index 000000000000..65c3966962e0 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/individuallyparentindividuallyparentnestedwithparamalias_client_test.go @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package clientinitindividuallyparentgroup_test + +import ( + "clientinitindividuallyparentgroup" + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestIndividuallyParentNestedWithParamAliasClient_WithAliasedName(t *testing.T) { + parentClient, err := clientinitindividuallyparentgroup.NewIndividuallyParentClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + client := parentClient.NewIndividuallyParentIndividuallyParentNestedWithParamAliasClient("sample-blob") + resp, err := client.WithAliasedName(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestIndividuallyParentNestedWithParamAliasClient_WithOriginalName(t *testing.T) { + parentClient, err := clientinitindividuallyparentgroup.NewIndividuallyParentClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + client := parentClient.NewIndividuallyParentIndividuallyParentNestedWithParamAliasClient("sample-blob") + resp, err := client.WithOriginalName(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/individuallyparentindividuallyparentnestedwithpath_client_test.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/individuallyparentindividuallyparentnestedwithpath_client_test.go new file mode 100644 index 000000000000..5815b361bb55 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/individuallyparentindividuallyparentnestedwithpath_client_test.go @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package clientinitindividuallyparentgroup_test + +import ( + "clientinitindividuallyparentgroup" + "context" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestIndividuallyParentNestedWithPathClient_WithQuery(t *testing.T) { + parentClient, err := clientinitindividuallyparentgroup.NewIndividuallyParentClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + client := parentClient.NewIndividuallyParentIndividuallyParentNestedWithPathClient("test-blob") + resp, err := client.WithQuery(context.Background(), &clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithPathClientWithQueryOptions{ + Format: to.Ptr("text"), + }) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestIndividuallyParentNestedWithPathClient_GetStandalone(t *testing.T) { + parentClient, err := clientinitindividuallyparentgroup.NewIndividuallyParentClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + client := parentClient.NewIndividuallyParentIndividuallyParentNestedWithPathClient("test-blob") + resp, err := client.GetStandalone(context.Background(), nil) + require.NoError(t, err) + expectedTime, err := time.Parse(time.RFC3339, "2023-01-01T12:00:00Z") + require.NoError(t, err) + require.EqualValues(t, clientinitindividuallyparentgroup.BlobProperties{ + Name: to.Ptr("test-blob"), + Size: to.Ptr[int64](1024), + ContentType: to.Ptr("application/octet-stream"), + CreatedOn: to.Ptr(expectedTime), + }, resp.BlobProperties) +} + +func TestIndividuallyParentNestedWithPathClient_DeleteStandalone(t *testing.T) { + parentClient, err := clientinitindividuallyparentgroup.NewIndividuallyParentClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + client := parentClient.NewIndividuallyParentIndividuallyParentNestedWithPathClient("test-blob") + resp, err := client.DeleteStandalone(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/individuallyparentindividuallyparentnestedwithquery_client_test.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/individuallyparentindividuallyparentnestedwithquery_client_test.go new file mode 100644 index 000000000000..dd5eb45c2f04 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/individuallyparentindividuallyparentnestedwithquery_client_test.go @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package clientinitindividuallyparentgroup_test + +import ( + "clientinitindividuallyparentgroup" + "context" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestIndividuallyParentNestedWithQueryClient_WithQuery(t *testing.T) { + parentClient, err := clientinitindividuallyparentgroup.NewIndividuallyParentClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + client := parentClient.NewIndividuallyParentIndividuallyParentNestedWithQueryClient("test-blob") + resp, err := client.WithQuery(context.Background(), &clientinitindividuallyparentgroup.IndividuallyParentIndividuallyParentNestedWithQueryClientWithQueryOptions{ + Format: to.Ptr("text"), + }) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestIndividuallyParentNestedWithQueryClient_GetStandalone(t *testing.T) { + parentClient, err := clientinitindividuallyparentgroup.NewIndividuallyParentClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + client := parentClient.NewIndividuallyParentIndividuallyParentNestedWithQueryClient("test-blob") + resp, err := client.GetStandalone(context.Background(), nil) + require.NoError(t, err) + expectedTime, err := time.Parse(time.RFC3339, "2023-01-01T12:00:00Z") + require.NoError(t, err) + require.EqualValues(t, clientinitindividuallyparentgroup.BlobProperties{ + Name: to.Ptr("test-blob"), + Size: to.Ptr[int64](1024), + ContentType: to.Ptr("application/octet-stream"), + CreatedOn: to.Ptr(expectedTime), + }, resp.BlobProperties) +} + +func TestIndividuallyParentNestedWithQueryClient_DeleteStandalone(t *testing.T) { + parentClient, err := clientinitindividuallyparentgroup.NewIndividuallyParentClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + client := parentClient.NewIndividuallyParentIndividuallyParentNestedWithQueryClient("test-blob") + resp, err := client.DeleteStandalone(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/testdata/_metadata.json b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparent_client.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparent_client.go new file mode 100644 index 000000000000..d52fc297cdfc --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparent_client.go @@ -0,0 +1,95 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitindividuallyparentgroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// IndividuallyParentClient - Test for client initialization decorator - moving parameters from method to client level +// Don't use this type directly, use NewIndividuallyParentClientWithNoCredential() instead. +type IndividuallyParentClient struct { + internal *azcore.Client + endpoint string +} + +// IndividuallyParentClientOptions contains the optional values for creating a [IndividuallyParentClient]. +type IndividuallyParentClientOptions struct { + azcore.ClientOptions +} + +// NewIndividuallyParentClientWithNoCredential creates a new instance of IndividuallyParentClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewIndividuallyParentClientWithNoCredential(endpoint string, options *IndividuallyParentClientOptions) (*IndividuallyParentClient, error) { + if options == nil { + options = &IndividuallyParentClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &IndividuallyParentClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewIndividuallyParentIndividuallyParentNestedWithHeaderClient creates a new instance of [IndividuallyParentIndividuallyParentNestedWithHeaderClient]. +func (client *IndividuallyParentClient) NewIndividuallyParentIndividuallyParentNestedWithHeaderClient(name string) *IndividuallyParentIndividuallyParentNestedWithHeaderClient { + return &IndividuallyParentIndividuallyParentNestedWithHeaderClient{ + endpoint: client.endpoint, + internal: client.internal, + name: name, + } +} + +// NewIndividuallyParentIndividuallyParentNestedWithMixedClient creates a new instance of [IndividuallyParentIndividuallyParentNestedWithMixedClient]. +func (client *IndividuallyParentClient) NewIndividuallyParentIndividuallyParentNestedWithMixedClient(name string) *IndividuallyParentIndividuallyParentNestedWithMixedClient { + return &IndividuallyParentIndividuallyParentNestedWithMixedClient{ + endpoint: client.endpoint, + internal: client.internal, + name: name, + } +} + +// NewIndividuallyParentIndividuallyParentNestedWithMultipleClient creates a new instance of [IndividuallyParentIndividuallyParentNestedWithMultipleClient]. +func (client *IndividuallyParentClient) NewIndividuallyParentIndividuallyParentNestedWithMultipleClient(name string, region string) *IndividuallyParentIndividuallyParentNestedWithMultipleClient { + return &IndividuallyParentIndividuallyParentNestedWithMultipleClient{ + endpoint: client.endpoint, + internal: client.internal, + name: name, + region: region, + } +} + +// NewIndividuallyParentIndividuallyParentNestedWithParamAliasClient creates a new instance of [IndividuallyParentIndividuallyParentNestedWithParamAliasClient]. +func (client *IndividuallyParentClient) NewIndividuallyParentIndividuallyParentNestedWithParamAliasClient(blobName string) *IndividuallyParentIndividuallyParentNestedWithParamAliasClient { + return &IndividuallyParentIndividuallyParentNestedWithParamAliasClient{ + blobName: blobName, + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewIndividuallyParentIndividuallyParentNestedWithPathClient creates a new instance of [IndividuallyParentIndividuallyParentNestedWithPathClient]. +func (client *IndividuallyParentClient) NewIndividuallyParentIndividuallyParentNestedWithPathClient(blobName string) *IndividuallyParentIndividuallyParentNestedWithPathClient { + return &IndividuallyParentIndividuallyParentNestedWithPathClient{ + blobName: blobName, + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewIndividuallyParentIndividuallyParentNestedWithQueryClient creates a new instance of [IndividuallyParentIndividuallyParentNestedWithQueryClient]. +func (client *IndividuallyParentClient) NewIndividuallyParentIndividuallyParentNestedWithQueryClient(blobName string) *IndividuallyParentIndividuallyParentNestedWithQueryClient { + return &IndividuallyParentIndividuallyParentNestedWithQueryClient{ + blobName: blobName, + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparentindividuallyparentnestedwithheader_client.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparentindividuallyparentnestedwithheader_client.go new file mode 100644 index 000000000000..d0d65e523783 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparentindividuallyparentnestedwithheader_client.go @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitindividuallyparentgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// IndividuallyParentIndividuallyParentNestedWithHeaderClient - Operations for nested default -> individually and parent header +// parameters +// Don't use this type directly, use NewIndividuallyParentIndividuallyParentNestedWithHeaderClientWithNoCredential() instead. +type IndividuallyParentIndividuallyParentNestedWithHeaderClient struct { + internal *azcore.Client + endpoint string + name string +} + +// IndividuallyParentIndividuallyParentNestedWithHeaderClientOptions contains the optional values for creating a [IndividuallyParentIndividuallyParentNestedWithHeaderClient]. +type IndividuallyParentIndividuallyParentNestedWithHeaderClientOptions struct { + azcore.ClientOptions +} + +// NewIndividuallyParentIndividuallyParentNestedWithHeaderClientWithNoCredential creates a new instance of IndividuallyParentIndividuallyParentNestedWithHeaderClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewIndividuallyParentIndividuallyParentNestedWithHeaderClientWithNoCredential(endpoint string, name string, options *IndividuallyParentIndividuallyParentNestedWithHeaderClientOptions) (*IndividuallyParentIndividuallyParentNestedWithHeaderClient, error) { + if options == nil { + options = &IndividuallyParentIndividuallyParentNestedWithHeaderClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &IndividuallyParentIndividuallyParentNestedWithHeaderClient{ + endpoint: endpoint, + name: name, + internal: cl, + } + return client, nil +} + +// DeleteStandalone - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyParentIndividuallyParentNestedWithHeaderClientDeleteStandaloneOptions contains the optional parameters +// for the IndividuallyParentIndividuallyParentNestedWithHeaderClient.DeleteStandalone method. +func (client *IndividuallyParentIndividuallyParentNestedWithHeaderClient) DeleteStandalone(ctx context.Context, options *IndividuallyParentIndividuallyParentNestedWithHeaderClientDeleteStandaloneOptions) (IndividuallyParentIndividuallyParentNestedWithHeaderClientDeleteStandaloneResponse, error) { + var err error + const operationName = "IndividuallyParentIndividuallyParentNestedWithHeaderClient.DeleteStandalone" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteStandaloneCreateRequest(ctx, options) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithHeaderClientDeleteStandaloneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithHeaderClientDeleteStandaloneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyParentIndividuallyParentNestedWithHeaderClientDeleteStandaloneResponse{}, err + } + return IndividuallyParentIndividuallyParentNestedWithHeaderClientDeleteStandaloneResponse{}, nil +} + +// deleteStandaloneCreateRequest creates the DeleteStandalone request. +func (client *IndividuallyParentIndividuallyParentNestedWithHeaderClient) deleteStandaloneCreateRequest(ctx context.Context, _ *IndividuallyParentIndividuallyParentNestedWithHeaderClientDeleteStandaloneOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually-parent/nested-default-individually-parent-header/delete-standalone" + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["name"] = []string{client.name} + return req, nil +} + +// GetStandalone - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyParentIndividuallyParentNestedWithHeaderClientGetStandaloneOptions contains the optional parameters +// for the IndividuallyParentIndividuallyParentNestedWithHeaderClient.GetStandalone method. +func (client *IndividuallyParentIndividuallyParentNestedWithHeaderClient) GetStandalone(ctx context.Context, options *IndividuallyParentIndividuallyParentNestedWithHeaderClientGetStandaloneOptions) (IndividuallyParentIndividuallyParentNestedWithHeaderClientGetStandaloneResponse, error) { + var err error + const operationName = "IndividuallyParentIndividuallyParentNestedWithHeaderClient.GetStandalone" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getStandaloneCreateRequest(ctx, options) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithHeaderClientGetStandaloneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithHeaderClientGetStandaloneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyParentIndividuallyParentNestedWithHeaderClientGetStandaloneResponse{}, err + } + return IndividuallyParentIndividuallyParentNestedWithHeaderClientGetStandaloneResponse{}, nil +} + +// getStandaloneCreateRequest creates the GetStandalone request. +func (client *IndividuallyParentIndividuallyParentNestedWithHeaderClient) getStandaloneCreateRequest(ctx context.Context, _ *IndividuallyParentIndividuallyParentNestedWithHeaderClientGetStandaloneOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually-parent/nested-default-individually-parent-header/get-standalone" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["name"] = []string{client.name} + return req, nil +} + +// WithQuery - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyParentIndividuallyParentNestedWithHeaderClientWithQueryOptions contains the optional parameters for +// the IndividuallyParentIndividuallyParentNestedWithHeaderClient.WithQuery method. +func (client *IndividuallyParentIndividuallyParentNestedWithHeaderClient) WithQuery(ctx context.Context, options *IndividuallyParentIndividuallyParentNestedWithHeaderClientWithQueryOptions) (IndividuallyParentIndividuallyParentNestedWithHeaderClientWithQueryResponse, error) { + var err error + const operationName = "IndividuallyParentIndividuallyParentNestedWithHeaderClient.WithQuery" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withQueryCreateRequest(ctx, options) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithHeaderClientWithQueryResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithHeaderClientWithQueryResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyParentIndividuallyParentNestedWithHeaderClientWithQueryResponse{}, err + } + return IndividuallyParentIndividuallyParentNestedWithHeaderClientWithQueryResponse{}, nil +} + +// withQueryCreateRequest creates the WithQuery request. +func (client *IndividuallyParentIndividuallyParentNestedWithHeaderClient) withQueryCreateRequest(ctx context.Context, options *IndividuallyParentIndividuallyParentNestedWithHeaderClientWithQueryOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually-parent/nested-default-individually-parent-header/with-query" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Format != nil { + reqQP.Set("format", *options.Format) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["name"] = []string{client.name} + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparentindividuallyparentnestedwithmixed_client.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparentindividuallyparentnestedwithmixed_client.go new file mode 100644 index 000000000000..581ef0e2c1ba --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparentindividuallyparentnestedwithmixed_client.go @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitindividuallyparentgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// IndividuallyParentIndividuallyParentNestedWithMixedClient - Operations for nested default -> individually and parent mixed +// parameters +// Don't use this type directly, use NewIndividuallyParentIndividuallyParentNestedWithMixedClientWithNoCredential() instead. +type IndividuallyParentIndividuallyParentNestedWithMixedClient struct { + internal *azcore.Client + endpoint string + name string +} + +// IndividuallyParentIndividuallyParentNestedWithMixedClientOptions contains the optional values for creating a [IndividuallyParentIndividuallyParentNestedWithMixedClient]. +type IndividuallyParentIndividuallyParentNestedWithMixedClientOptions struct { + azcore.ClientOptions +} + +// NewIndividuallyParentIndividuallyParentNestedWithMixedClientWithNoCredential creates a new instance of IndividuallyParentIndividuallyParentNestedWithMixedClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewIndividuallyParentIndividuallyParentNestedWithMixedClientWithNoCredential(endpoint string, name string, options *IndividuallyParentIndividuallyParentNestedWithMixedClientOptions) (*IndividuallyParentIndividuallyParentNestedWithMixedClient, error) { + if options == nil { + options = &IndividuallyParentIndividuallyParentNestedWithMixedClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &IndividuallyParentIndividuallyParentNestedWithMixedClient{ + endpoint: endpoint, + name: name, + internal: cl, + } + return client, nil +} + +// DeleteStandalone - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyParentIndividuallyParentNestedWithMixedClientDeleteStandaloneOptions contains the optional parameters +// for the IndividuallyParentIndividuallyParentNestedWithMixedClient.DeleteStandalone method. +func (client *IndividuallyParentIndividuallyParentNestedWithMixedClient) DeleteStandalone(ctx context.Context, region string, options *IndividuallyParentIndividuallyParentNestedWithMixedClientDeleteStandaloneOptions) (IndividuallyParentIndividuallyParentNestedWithMixedClientDeleteStandaloneResponse, error) { + var err error + const operationName = "IndividuallyParentIndividuallyParentNestedWithMixedClient.DeleteStandalone" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteStandaloneCreateRequest(ctx, region, options) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithMixedClientDeleteStandaloneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithMixedClientDeleteStandaloneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyParentIndividuallyParentNestedWithMixedClientDeleteStandaloneResponse{}, err + } + return IndividuallyParentIndividuallyParentNestedWithMixedClientDeleteStandaloneResponse{}, nil +} + +// deleteStandaloneCreateRequest creates the DeleteStandalone request. +func (client *IndividuallyParentIndividuallyParentNestedWithMixedClient) deleteStandaloneCreateRequest(ctx context.Context, region string, _ *IndividuallyParentIndividuallyParentNestedWithMixedClientDeleteStandaloneOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually-parent/nested-default-individually-parent-mixed/delete-standalone" + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("region", region) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["name"] = []string{client.name} + return req, nil +} + +// GetStandalone - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyParentIndividuallyParentNestedWithMixedClientGetStandaloneOptions contains the optional parameters +// for the IndividuallyParentIndividuallyParentNestedWithMixedClient.GetStandalone method. +func (client *IndividuallyParentIndividuallyParentNestedWithMixedClient) GetStandalone(ctx context.Context, region string, options *IndividuallyParentIndividuallyParentNestedWithMixedClientGetStandaloneOptions) (IndividuallyParentIndividuallyParentNestedWithMixedClientGetStandaloneResponse, error) { + var err error + const operationName = "IndividuallyParentIndividuallyParentNestedWithMixedClient.GetStandalone" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getStandaloneCreateRequest(ctx, region, options) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithMixedClientGetStandaloneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithMixedClientGetStandaloneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyParentIndividuallyParentNestedWithMixedClientGetStandaloneResponse{}, err + } + return IndividuallyParentIndividuallyParentNestedWithMixedClientGetStandaloneResponse{}, nil +} + +// getStandaloneCreateRequest creates the GetStandalone request. +func (client *IndividuallyParentIndividuallyParentNestedWithMixedClient) getStandaloneCreateRequest(ctx context.Context, region string, _ *IndividuallyParentIndividuallyParentNestedWithMixedClientGetStandaloneOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually-parent/nested-default-individually-parent-mixed/get-standalone" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("region", region) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["name"] = []string{client.name} + return req, nil +} + +// WithQuery - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyParentIndividuallyParentNestedWithMixedClientWithQueryOptions contains the optional parameters for +// the IndividuallyParentIndividuallyParentNestedWithMixedClient.WithQuery method. +func (client *IndividuallyParentIndividuallyParentNestedWithMixedClient) WithQuery(ctx context.Context, region string, options *IndividuallyParentIndividuallyParentNestedWithMixedClientWithQueryOptions) (IndividuallyParentIndividuallyParentNestedWithMixedClientWithQueryResponse, error) { + var err error + const operationName = "IndividuallyParentIndividuallyParentNestedWithMixedClient.WithQuery" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withQueryCreateRequest(ctx, region, options) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithMixedClientWithQueryResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithMixedClientWithQueryResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyParentIndividuallyParentNestedWithMixedClientWithQueryResponse{}, err + } + return IndividuallyParentIndividuallyParentNestedWithMixedClientWithQueryResponse{}, nil +} + +// withQueryCreateRequest creates the WithQuery request. +func (client *IndividuallyParentIndividuallyParentNestedWithMixedClient) withQueryCreateRequest(ctx context.Context, region string, options *IndividuallyParentIndividuallyParentNestedWithMixedClientWithQueryOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually-parent/nested-default-individually-parent-mixed/with-query" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Format != nil { + reqQP.Set("format", *options.Format) + } + reqQP.Set("region", region) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["name"] = []string{client.name} + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparentindividuallyparentnestedwithmultiple_client.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparentindividuallyparentnestedwithmultiple_client.go new file mode 100644 index 000000000000..93f57d00d0f1 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparentindividuallyparentnestedwithmultiple_client.go @@ -0,0 +1,169 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitindividuallyparentgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// IndividuallyParentIndividuallyParentNestedWithMultipleClient - Operations for nested default -> individually and parent +// multiple parameters +// Don't use this type directly, use NewIndividuallyParentIndividuallyParentNestedWithMultipleClientWithNoCredential() instead. +type IndividuallyParentIndividuallyParentNestedWithMultipleClient struct { + internal *azcore.Client + endpoint string + name string + region string +} + +// IndividuallyParentIndividuallyParentNestedWithMultipleClientOptions contains the optional values for creating a [IndividuallyParentIndividuallyParentNestedWithMultipleClient]. +type IndividuallyParentIndividuallyParentNestedWithMultipleClientOptions struct { + azcore.ClientOptions +} + +// NewIndividuallyParentIndividuallyParentNestedWithMultipleClientWithNoCredential creates a new instance of IndividuallyParentIndividuallyParentNestedWithMultipleClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewIndividuallyParentIndividuallyParentNestedWithMultipleClientWithNoCredential(endpoint string, name string, region string, options *IndividuallyParentIndividuallyParentNestedWithMultipleClientOptions) (*IndividuallyParentIndividuallyParentNestedWithMultipleClient, error) { + if options == nil { + options = &IndividuallyParentIndividuallyParentNestedWithMultipleClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &IndividuallyParentIndividuallyParentNestedWithMultipleClient{ + endpoint: endpoint, + name: name, + region: region, + internal: cl, + } + return client, nil +} + +// DeleteStandalone - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyParentIndividuallyParentNestedWithMultipleClientDeleteStandaloneOptions contains the optional parameters +// for the IndividuallyParentIndividuallyParentNestedWithMultipleClient.DeleteStandalone method. +func (client *IndividuallyParentIndividuallyParentNestedWithMultipleClient) DeleteStandalone(ctx context.Context, options *IndividuallyParentIndividuallyParentNestedWithMultipleClientDeleteStandaloneOptions) (IndividuallyParentIndividuallyParentNestedWithMultipleClientDeleteStandaloneResponse, error) { + var err error + const operationName = "IndividuallyParentIndividuallyParentNestedWithMultipleClient.DeleteStandalone" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteStandaloneCreateRequest(ctx, options) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithMultipleClientDeleteStandaloneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithMultipleClientDeleteStandaloneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyParentIndividuallyParentNestedWithMultipleClientDeleteStandaloneResponse{}, err + } + return IndividuallyParentIndividuallyParentNestedWithMultipleClientDeleteStandaloneResponse{}, nil +} + +// deleteStandaloneCreateRequest creates the DeleteStandalone request. +func (client *IndividuallyParentIndividuallyParentNestedWithMultipleClient) deleteStandaloneCreateRequest(ctx context.Context, _ *IndividuallyParentIndividuallyParentNestedWithMultipleClientDeleteStandaloneOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually-parent/nested-default-individually-parent-multiple/delete-standalone" + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("region", client.region) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["name"] = []string{client.name} + return req, nil +} + +// GetStandalone - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyParentIndividuallyParentNestedWithMultipleClientGetStandaloneOptions contains the optional parameters +// for the IndividuallyParentIndividuallyParentNestedWithMultipleClient.GetStandalone method. +func (client *IndividuallyParentIndividuallyParentNestedWithMultipleClient) GetStandalone(ctx context.Context, options *IndividuallyParentIndividuallyParentNestedWithMultipleClientGetStandaloneOptions) (IndividuallyParentIndividuallyParentNestedWithMultipleClientGetStandaloneResponse, error) { + var err error + const operationName = "IndividuallyParentIndividuallyParentNestedWithMultipleClient.GetStandalone" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getStandaloneCreateRequest(ctx, options) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithMultipleClientGetStandaloneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithMultipleClientGetStandaloneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyParentIndividuallyParentNestedWithMultipleClientGetStandaloneResponse{}, err + } + return IndividuallyParentIndividuallyParentNestedWithMultipleClientGetStandaloneResponse{}, nil +} + +// getStandaloneCreateRequest creates the GetStandalone request. +func (client *IndividuallyParentIndividuallyParentNestedWithMultipleClient) getStandaloneCreateRequest(ctx context.Context, _ *IndividuallyParentIndividuallyParentNestedWithMultipleClientGetStandaloneOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually-parent/nested-default-individually-parent-multiple/get-standalone" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("region", client.region) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["name"] = []string{client.name} + return req, nil +} + +// WithQuery - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyParentIndividuallyParentNestedWithMultipleClientWithQueryOptions contains the optional parameters +// for the IndividuallyParentIndividuallyParentNestedWithMultipleClient.WithQuery method. +func (client *IndividuallyParentIndividuallyParentNestedWithMultipleClient) WithQuery(ctx context.Context, options *IndividuallyParentIndividuallyParentNestedWithMultipleClientWithQueryOptions) (IndividuallyParentIndividuallyParentNestedWithMultipleClientWithQueryResponse, error) { + var err error + const operationName = "IndividuallyParentIndividuallyParentNestedWithMultipleClient.WithQuery" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withQueryCreateRequest(ctx, options) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithMultipleClientWithQueryResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithMultipleClientWithQueryResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyParentIndividuallyParentNestedWithMultipleClientWithQueryResponse{}, err + } + return IndividuallyParentIndividuallyParentNestedWithMultipleClientWithQueryResponse{}, nil +} + +// withQueryCreateRequest creates the WithQuery request. +func (client *IndividuallyParentIndividuallyParentNestedWithMultipleClient) withQueryCreateRequest(ctx context.Context, options *IndividuallyParentIndividuallyParentNestedWithMultipleClientWithQueryOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually-parent/nested-default-individually-parent-multiple/with-query" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Format != nil { + reqQP.Set("format", *options.Format) + } + reqQP.Set("region", client.region) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["name"] = []string{client.name} + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparentindividuallyparentnestedwithparamalias_client.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparentindividuallyparentnestedwithparamalias_client.go new file mode 100644 index 000000000000..7350697e6f87 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparentindividuallyparentnestedwithparamalias_client.go @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitindividuallyparentgroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// IndividuallyParentIndividuallyParentNestedWithParamAliasClient - Operations for nested default -> individually and parent +// param alias +// Don't use this type directly, use NewIndividuallyParentIndividuallyParentNestedWithParamAliasClientWithNoCredential() instead. +type IndividuallyParentIndividuallyParentNestedWithParamAliasClient struct { + internal *azcore.Client + blobName string + endpoint string +} + +// IndividuallyParentIndividuallyParentNestedWithParamAliasClientOptions contains the optional values for creating a [IndividuallyParentIndividuallyParentNestedWithParamAliasClient]. +type IndividuallyParentIndividuallyParentNestedWithParamAliasClientOptions struct { + azcore.ClientOptions +} + +// NewIndividuallyParentIndividuallyParentNestedWithParamAliasClientWithNoCredential creates a new instance of IndividuallyParentIndividuallyParentNestedWithParamAliasClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewIndividuallyParentIndividuallyParentNestedWithParamAliasClientWithNoCredential(endpoint string, blobName string, options *IndividuallyParentIndividuallyParentNestedWithParamAliasClientOptions) (*IndividuallyParentIndividuallyParentNestedWithParamAliasClient, error) { + if options == nil { + options = &IndividuallyParentIndividuallyParentNestedWithParamAliasClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &IndividuallyParentIndividuallyParentNestedWithParamAliasClient{ + blobName: blobName, + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// WithAliasedName - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithAliasedNameOptions contains the optional parameters +// for the IndividuallyParentIndividuallyParentNestedWithParamAliasClient.WithAliasedName method. +func (client *IndividuallyParentIndividuallyParentNestedWithParamAliasClient) WithAliasedName(ctx context.Context, options *IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithAliasedNameOptions) (IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithAliasedNameResponse, error) { + var err error + const operationName = "IndividuallyParentIndividuallyParentNestedWithParamAliasClient.WithAliasedName" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withAliasedNameCreateRequest(ctx, options) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithAliasedNameResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithAliasedNameResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithAliasedNameResponse{}, err + } + return IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithAliasedNameResponse{}, nil +} + +// withAliasedNameCreateRequest creates the WithAliasedName request. +func (client *IndividuallyParentIndividuallyParentNestedWithParamAliasClient) withAliasedNameCreateRequest(ctx context.Context, _ *IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithAliasedNameOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually-parent/nested-default-individually-parent-param-alias/{blob}/with-aliased-name" + if client.blobName == "" { + return nil, errors.New("parameter client.blobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{blob}", url.PathEscape(client.blobName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// WithOriginalName - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithOriginalNameOptions contains the optional parameters +// for the IndividuallyParentIndividuallyParentNestedWithParamAliasClient.WithOriginalName method. +func (client *IndividuallyParentIndividuallyParentNestedWithParamAliasClient) WithOriginalName(ctx context.Context, options *IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithOriginalNameOptions) (IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithOriginalNameResponse, error) { + var err error + const operationName = "IndividuallyParentIndividuallyParentNestedWithParamAliasClient.WithOriginalName" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withOriginalNameCreateRequest(ctx, options) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithOriginalNameResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithOriginalNameResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithOriginalNameResponse{}, err + } + return IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithOriginalNameResponse{}, nil +} + +// withOriginalNameCreateRequest creates the WithOriginalName request. +func (client *IndividuallyParentIndividuallyParentNestedWithParamAliasClient) withOriginalNameCreateRequest(ctx context.Context, _ *IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithOriginalNameOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually-parent/nested-default-individually-parent-param-alias/{blobName}/with-original-name" + if client.blobName == "" { + return nil, errors.New("parameter client.blobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{blobName}", url.PathEscape(client.blobName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparentindividuallyparentnestedwithpath_client.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparentindividuallyparentnestedwithpath_client.go new file mode 100644 index 000000000000..684a91b56bd1 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparentindividuallyparentnestedwithpath_client.go @@ -0,0 +1,181 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitindividuallyparentgroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// IndividuallyParentIndividuallyParentNestedWithPathClient - Operations for nested default -> individually and parent +// Don't use this type directly, use NewIndividuallyParentIndividuallyParentNestedWithPathClientWithNoCredential() instead. +type IndividuallyParentIndividuallyParentNestedWithPathClient struct { + internal *azcore.Client + blobName string + endpoint string +} + +// IndividuallyParentIndividuallyParentNestedWithPathClientOptions contains the optional values for creating a [IndividuallyParentIndividuallyParentNestedWithPathClient]. +type IndividuallyParentIndividuallyParentNestedWithPathClientOptions struct { + azcore.ClientOptions +} + +// NewIndividuallyParentIndividuallyParentNestedWithPathClientWithNoCredential creates a new instance of IndividuallyParentIndividuallyParentNestedWithPathClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewIndividuallyParentIndividuallyParentNestedWithPathClientWithNoCredential(endpoint string, blobName string, options *IndividuallyParentIndividuallyParentNestedWithPathClientOptions) (*IndividuallyParentIndividuallyParentNestedWithPathClient, error) { + if options == nil { + options = &IndividuallyParentIndividuallyParentNestedWithPathClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &IndividuallyParentIndividuallyParentNestedWithPathClient{ + blobName: blobName, + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// DeleteStandalone - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyParentIndividuallyParentNestedWithPathClientDeleteStandaloneOptions contains the optional parameters +// for the IndividuallyParentIndividuallyParentNestedWithPathClient.DeleteStandalone method. +func (client *IndividuallyParentIndividuallyParentNestedWithPathClient) DeleteStandalone(ctx context.Context, options *IndividuallyParentIndividuallyParentNestedWithPathClientDeleteStandaloneOptions) (IndividuallyParentIndividuallyParentNestedWithPathClientDeleteStandaloneResponse, error) { + var err error + const operationName = "IndividuallyParentIndividuallyParentNestedWithPathClient.DeleteStandalone" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteStandaloneCreateRequest(ctx, options) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithPathClientDeleteStandaloneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithPathClientDeleteStandaloneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyParentIndividuallyParentNestedWithPathClientDeleteStandaloneResponse{}, err + } + return IndividuallyParentIndividuallyParentNestedWithPathClientDeleteStandaloneResponse{}, nil +} + +// deleteStandaloneCreateRequest creates the DeleteStandalone request. +func (client *IndividuallyParentIndividuallyParentNestedWithPathClient) deleteStandaloneCreateRequest(ctx context.Context, _ *IndividuallyParentIndividuallyParentNestedWithPathClientDeleteStandaloneOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually-parent/nested-default-individually-parent/{blobName}" + if client.blobName == "" { + return nil, errors.New("parameter client.blobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{blobName}", url.PathEscape(client.blobName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// GetStandalone - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyParentIndividuallyParentNestedWithPathClientGetStandaloneOptions contains the optional parameters +// for the IndividuallyParentIndividuallyParentNestedWithPathClient.GetStandalone method. +func (client *IndividuallyParentIndividuallyParentNestedWithPathClient) GetStandalone(ctx context.Context, options *IndividuallyParentIndividuallyParentNestedWithPathClientGetStandaloneOptions) (IndividuallyParentIndividuallyParentNestedWithPathClientGetStandaloneResponse, error) { + var err error + const operationName = "IndividuallyParentIndividuallyParentNestedWithPathClient.GetStandalone" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getStandaloneCreateRequest(ctx, options) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithPathClientGetStandaloneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithPathClientGetStandaloneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return IndividuallyParentIndividuallyParentNestedWithPathClientGetStandaloneResponse{}, err + } + resp, err := client.getStandaloneHandleResponse(httpResp) + return resp, err +} + +// getStandaloneCreateRequest creates the GetStandalone request. +func (client *IndividuallyParentIndividuallyParentNestedWithPathClient) getStandaloneCreateRequest(ctx context.Context, _ *IndividuallyParentIndividuallyParentNestedWithPathClientGetStandaloneOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually-parent/nested-default-individually-parent/{blobName}/get-standalone" + if client.blobName == "" { + return nil, errors.New("parameter client.blobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{blobName}", url.PathEscape(client.blobName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getStandaloneHandleResponse handles the GetStandalone response. +func (client *IndividuallyParentIndividuallyParentNestedWithPathClient) getStandaloneHandleResponse(resp *http.Response) (IndividuallyParentIndividuallyParentNestedWithPathClientGetStandaloneResponse, error) { + result := IndividuallyParentIndividuallyParentNestedWithPathClientGetStandaloneResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BlobProperties); err != nil { + return IndividuallyParentIndividuallyParentNestedWithPathClientGetStandaloneResponse{}, err + } + return result, nil +} + +// WithQuery - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyParentIndividuallyParentNestedWithPathClientWithQueryOptions contains the optional parameters for +// the IndividuallyParentIndividuallyParentNestedWithPathClient.WithQuery method. +func (client *IndividuallyParentIndividuallyParentNestedWithPathClient) WithQuery(ctx context.Context, options *IndividuallyParentIndividuallyParentNestedWithPathClientWithQueryOptions) (IndividuallyParentIndividuallyParentNestedWithPathClientWithQueryResponse, error) { + var err error + const operationName = "IndividuallyParentIndividuallyParentNestedWithPathClient.WithQuery" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withQueryCreateRequest(ctx, options) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithPathClientWithQueryResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithPathClientWithQueryResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyParentIndividuallyParentNestedWithPathClientWithQueryResponse{}, err + } + return IndividuallyParentIndividuallyParentNestedWithPathClientWithQueryResponse{}, nil +} + +// withQueryCreateRequest creates the WithQuery request. +func (client *IndividuallyParentIndividuallyParentNestedWithPathClient) withQueryCreateRequest(ctx context.Context, options *IndividuallyParentIndividuallyParentNestedWithPathClientWithQueryOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually-parent/nested-default-individually-parent/{blobName}/with-query" + if client.blobName == "" { + return nil, errors.New("parameter client.blobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{blobName}", url.PathEscape(client.blobName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Format != nil { + reqQP.Set("format", *options.Format) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparentindividuallyparentnestedwithquery_client.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparentindividuallyparentnestedwithquery_client.go new file mode 100644 index 000000000000..60e56dcd4346 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_individuallyparentindividuallyparentnestedwithquery_client.go @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitindividuallyparentgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// IndividuallyParentIndividuallyParentNestedWithQueryClient - Operations for nested default -> individually and parent with +// query parameters +// Don't use this type directly, use NewIndividuallyParentIndividuallyParentNestedWithQueryClientWithNoCredential() instead. +type IndividuallyParentIndividuallyParentNestedWithQueryClient struct { + internal *azcore.Client + blobName string + endpoint string +} + +// IndividuallyParentIndividuallyParentNestedWithQueryClientOptions contains the optional values for creating a [IndividuallyParentIndividuallyParentNestedWithQueryClient]. +type IndividuallyParentIndividuallyParentNestedWithQueryClientOptions struct { + azcore.ClientOptions +} + +// NewIndividuallyParentIndividuallyParentNestedWithQueryClientWithNoCredential creates a new instance of IndividuallyParentIndividuallyParentNestedWithQueryClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewIndividuallyParentIndividuallyParentNestedWithQueryClientWithNoCredential(endpoint string, blobName string, options *IndividuallyParentIndividuallyParentNestedWithQueryClientOptions) (*IndividuallyParentIndividuallyParentNestedWithQueryClient, error) { + if options == nil { + options = &IndividuallyParentIndividuallyParentNestedWithQueryClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &IndividuallyParentIndividuallyParentNestedWithQueryClient{ + blobName: blobName, + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// DeleteStandalone - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyParentIndividuallyParentNestedWithQueryClientDeleteStandaloneOptions contains the optional parameters +// for the IndividuallyParentIndividuallyParentNestedWithQueryClient.DeleteStandalone method. +func (client *IndividuallyParentIndividuallyParentNestedWithQueryClient) DeleteStandalone(ctx context.Context, options *IndividuallyParentIndividuallyParentNestedWithQueryClientDeleteStandaloneOptions) (IndividuallyParentIndividuallyParentNestedWithQueryClientDeleteStandaloneResponse, error) { + var err error + const operationName = "IndividuallyParentIndividuallyParentNestedWithQueryClient.DeleteStandalone" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteStandaloneCreateRequest(ctx, options) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithQueryClientDeleteStandaloneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithQueryClientDeleteStandaloneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyParentIndividuallyParentNestedWithQueryClientDeleteStandaloneResponse{}, err + } + return IndividuallyParentIndividuallyParentNestedWithQueryClientDeleteStandaloneResponse{}, nil +} + +// deleteStandaloneCreateRequest creates the DeleteStandalone request. +func (client *IndividuallyParentIndividuallyParentNestedWithQueryClient) deleteStandaloneCreateRequest(ctx context.Context, _ *IndividuallyParentIndividuallyParentNestedWithQueryClientDeleteStandaloneOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually-parent/nested-default-individually-parent-query/delete-resource" + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("blobName", client.blobName) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// GetStandalone - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyParentIndividuallyParentNestedWithQueryClientGetStandaloneOptions contains the optional parameters +// for the IndividuallyParentIndividuallyParentNestedWithQueryClient.GetStandalone method. +func (client *IndividuallyParentIndividuallyParentNestedWithQueryClient) GetStandalone(ctx context.Context, options *IndividuallyParentIndividuallyParentNestedWithQueryClientGetStandaloneOptions) (IndividuallyParentIndividuallyParentNestedWithQueryClientGetStandaloneResponse, error) { + var err error + const operationName = "IndividuallyParentIndividuallyParentNestedWithQueryClient.GetStandalone" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getStandaloneCreateRequest(ctx, options) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithQueryClientGetStandaloneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithQueryClientGetStandaloneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return IndividuallyParentIndividuallyParentNestedWithQueryClientGetStandaloneResponse{}, err + } + resp, err := client.getStandaloneHandleResponse(httpResp) + return resp, err +} + +// getStandaloneCreateRequest creates the GetStandalone request. +func (client *IndividuallyParentIndividuallyParentNestedWithQueryClient) getStandaloneCreateRequest(ctx context.Context, _ *IndividuallyParentIndividuallyParentNestedWithQueryClientGetStandaloneOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually-parent/nested-default-individually-parent-query/get-standalone" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("blobName", client.blobName) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getStandaloneHandleResponse handles the GetStandalone response. +func (client *IndividuallyParentIndividuallyParentNestedWithQueryClient) getStandaloneHandleResponse(resp *http.Response) (IndividuallyParentIndividuallyParentNestedWithQueryClientGetStandaloneResponse, error) { + result := IndividuallyParentIndividuallyParentNestedWithQueryClientGetStandaloneResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BlobProperties); err != nil { + return IndividuallyParentIndividuallyParentNestedWithQueryClientGetStandaloneResponse{}, err + } + return result, nil +} + +// WithQuery - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - IndividuallyParentIndividuallyParentNestedWithQueryClientWithQueryOptions contains the optional parameters for +// the IndividuallyParentIndividuallyParentNestedWithQueryClient.WithQuery method. +func (client *IndividuallyParentIndividuallyParentNestedWithQueryClient) WithQuery(ctx context.Context, options *IndividuallyParentIndividuallyParentNestedWithQueryClientWithQueryOptions) (IndividuallyParentIndividuallyParentNestedWithQueryClientWithQueryResponse, error) { + var err error + const operationName = "IndividuallyParentIndividuallyParentNestedWithQueryClient.WithQuery" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withQueryCreateRequest(ctx, options) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithQueryClientWithQueryResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return IndividuallyParentIndividuallyParentNestedWithQueryClientWithQueryResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return IndividuallyParentIndividuallyParentNestedWithQueryClientWithQueryResponse{}, err + } + return IndividuallyParentIndividuallyParentNestedWithQueryClientWithQueryResponse{}, nil +} + +// withQueryCreateRequest creates the WithQuery request. +func (client *IndividuallyParentIndividuallyParentNestedWithQueryClient) withQueryCreateRequest(ctx context.Context, options *IndividuallyParentIndividuallyParentNestedWithQueryClientWithQueryOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-initialization/individually-parent/nested-default-individually-parent-query/with-query" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("blobName", client.blobName) + if options != nil && options.Format != nil { + reqQP.Set("format", *options.Format) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_models.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_models.go new file mode 100644 index 000000000000..7e5bc827eb14 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_models.go @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitindividuallyparentgroup + +import "time" + +// BlobProperties - Properties of a blob +type BlobProperties struct { + // REQUIRED + ContentType *string + + // REQUIRED + CreatedOn *time.Time + + // REQUIRED + Name *string + + // REQUIRED + Size *int64 +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_models_serde.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_models_serde.go new file mode 100644 index 000000000000..711b203158ed --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_models_serde.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitindividuallyparentgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type BlobProperties. +func (b BlobProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "contentType", b.ContentType) + populateTime[datetime.RFC3339](objectMap, "createdOn", b.CreatedOn) + populate(objectMap, "name", b.Name) + populate(objectMap, "size", b.Size) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BlobProperties. +func (b *BlobProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "contentType": + err = unpopulate(val, "ContentType", &b.ContentType) + delete(rawMsg, key) + case "createdOn": + err = unpopulateTime[datetime.RFC3339](val, "CreatedOn", &b.CreatedOn) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &b.Name) + delete(rawMsg, key) + case "size": + err = unpopulate(val, "Size", &b.Size) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_options.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_options.go new file mode 100644 index 000000000000..05b5b4fe99c6 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_options.go @@ -0,0 +1,107 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitindividuallyparentgroup + +// IndividuallyParentIndividuallyParentNestedWithHeaderClientDeleteStandaloneOptions contains the optional parameters for +// the IndividuallyParentIndividuallyParentNestedWithHeaderClient.DeleteStandalone method. +type IndividuallyParentIndividuallyParentNestedWithHeaderClientDeleteStandaloneOptions struct { + // placeholder for future optional parameters +} + +// IndividuallyParentIndividuallyParentNestedWithHeaderClientGetStandaloneOptions contains the optional parameters for the +// IndividuallyParentIndividuallyParentNestedWithHeaderClient.GetStandalone method. +type IndividuallyParentIndividuallyParentNestedWithHeaderClientGetStandaloneOptions struct { + // placeholder for future optional parameters +} + +// IndividuallyParentIndividuallyParentNestedWithHeaderClientWithQueryOptions contains the optional parameters for the IndividuallyParentIndividuallyParentNestedWithHeaderClient.WithQuery +// method. +type IndividuallyParentIndividuallyParentNestedWithHeaderClientWithQueryOptions struct { + Format *string +} + +// IndividuallyParentIndividuallyParentNestedWithMixedClientDeleteStandaloneOptions contains the optional parameters for the +// IndividuallyParentIndividuallyParentNestedWithMixedClient.DeleteStandalone method. +type IndividuallyParentIndividuallyParentNestedWithMixedClientDeleteStandaloneOptions struct { + // placeholder for future optional parameters +} + +// IndividuallyParentIndividuallyParentNestedWithMixedClientGetStandaloneOptions contains the optional parameters for the +// IndividuallyParentIndividuallyParentNestedWithMixedClient.GetStandalone method. +type IndividuallyParentIndividuallyParentNestedWithMixedClientGetStandaloneOptions struct { + // placeholder for future optional parameters +} + +// IndividuallyParentIndividuallyParentNestedWithMixedClientWithQueryOptions contains the optional parameters for the IndividuallyParentIndividuallyParentNestedWithMixedClient.WithQuery +// method. +type IndividuallyParentIndividuallyParentNestedWithMixedClientWithQueryOptions struct { + Format *string +} + +// IndividuallyParentIndividuallyParentNestedWithMultipleClientDeleteStandaloneOptions contains the optional parameters for +// the IndividuallyParentIndividuallyParentNestedWithMultipleClient.DeleteStandalone method. +type IndividuallyParentIndividuallyParentNestedWithMultipleClientDeleteStandaloneOptions struct { + // placeholder for future optional parameters +} + +// IndividuallyParentIndividuallyParentNestedWithMultipleClientGetStandaloneOptions contains the optional parameters for the +// IndividuallyParentIndividuallyParentNestedWithMultipleClient.GetStandalone method. +type IndividuallyParentIndividuallyParentNestedWithMultipleClientGetStandaloneOptions struct { + // placeholder for future optional parameters +} + +// IndividuallyParentIndividuallyParentNestedWithMultipleClientWithQueryOptions contains the optional parameters for the IndividuallyParentIndividuallyParentNestedWithMultipleClient.WithQuery +// method. +type IndividuallyParentIndividuallyParentNestedWithMultipleClientWithQueryOptions struct { + Format *string +} + +// IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithAliasedNameOptions contains the optional parameters for +// the IndividuallyParentIndividuallyParentNestedWithParamAliasClient.WithAliasedName method. +type IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithAliasedNameOptions struct { + // placeholder for future optional parameters +} + +// IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithOriginalNameOptions contains the optional parameters +// for the IndividuallyParentIndividuallyParentNestedWithParamAliasClient.WithOriginalName method. +type IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithOriginalNameOptions struct { + // placeholder for future optional parameters +} + +// IndividuallyParentIndividuallyParentNestedWithPathClientDeleteStandaloneOptions contains the optional parameters for the +// IndividuallyParentIndividuallyParentNestedWithPathClient.DeleteStandalone method. +type IndividuallyParentIndividuallyParentNestedWithPathClientDeleteStandaloneOptions struct { + // placeholder for future optional parameters +} + +// IndividuallyParentIndividuallyParentNestedWithPathClientGetStandaloneOptions contains the optional parameters for the IndividuallyParentIndividuallyParentNestedWithPathClient.GetStandalone +// method. +type IndividuallyParentIndividuallyParentNestedWithPathClientGetStandaloneOptions struct { + // placeholder for future optional parameters +} + +// IndividuallyParentIndividuallyParentNestedWithPathClientWithQueryOptions contains the optional parameters for the IndividuallyParentIndividuallyParentNestedWithPathClient.WithQuery +// method. +type IndividuallyParentIndividuallyParentNestedWithPathClientWithQueryOptions struct { + Format *string +} + +// IndividuallyParentIndividuallyParentNestedWithQueryClientDeleteStandaloneOptions contains the optional parameters for the +// IndividuallyParentIndividuallyParentNestedWithQueryClient.DeleteStandalone method. +type IndividuallyParentIndividuallyParentNestedWithQueryClientDeleteStandaloneOptions struct { + // placeholder for future optional parameters +} + +// IndividuallyParentIndividuallyParentNestedWithQueryClientGetStandaloneOptions contains the optional parameters for the +// IndividuallyParentIndividuallyParentNestedWithQueryClient.GetStandalone method. +type IndividuallyParentIndividuallyParentNestedWithQueryClientGetStandaloneOptions struct { + // placeholder for future optional parameters +} + +// IndividuallyParentIndividuallyParentNestedWithQueryClientWithQueryOptions contains the optional parameters for the IndividuallyParentIndividuallyParentNestedWithQueryClient.WithQuery +// method. +type IndividuallyParentIndividuallyParentNestedWithQueryClientWithQueryOptions struct { + Format *string +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_responses.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_responses.go new file mode 100644 index 000000000000..22dcd04b8cb1 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_responses.go @@ -0,0 +1,95 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientinitindividuallyparentgroup + +// IndividuallyParentIndividuallyParentNestedWithHeaderClientDeleteStandaloneResponse contains the response from method IndividuallyParentIndividuallyParentNestedWithHeaderClient.DeleteStandalone. +type IndividuallyParentIndividuallyParentNestedWithHeaderClientDeleteStandaloneResponse struct { + // placeholder for future response values +} + +// IndividuallyParentIndividuallyParentNestedWithHeaderClientGetStandaloneResponse contains the response from method IndividuallyParentIndividuallyParentNestedWithHeaderClient.GetStandalone. +type IndividuallyParentIndividuallyParentNestedWithHeaderClientGetStandaloneResponse struct { + // placeholder for future response values +} + +// IndividuallyParentIndividuallyParentNestedWithHeaderClientWithQueryResponse contains the response from method IndividuallyParentIndividuallyParentNestedWithHeaderClient.WithQuery. +type IndividuallyParentIndividuallyParentNestedWithHeaderClientWithQueryResponse struct { + // placeholder for future response values +} + +// IndividuallyParentIndividuallyParentNestedWithMixedClientDeleteStandaloneResponse contains the response from method IndividuallyParentIndividuallyParentNestedWithMixedClient.DeleteStandalone. +type IndividuallyParentIndividuallyParentNestedWithMixedClientDeleteStandaloneResponse struct { + // placeholder for future response values +} + +// IndividuallyParentIndividuallyParentNestedWithMixedClientGetStandaloneResponse contains the response from method IndividuallyParentIndividuallyParentNestedWithMixedClient.GetStandalone. +type IndividuallyParentIndividuallyParentNestedWithMixedClientGetStandaloneResponse struct { + // placeholder for future response values +} + +// IndividuallyParentIndividuallyParentNestedWithMixedClientWithQueryResponse contains the response from method IndividuallyParentIndividuallyParentNestedWithMixedClient.WithQuery. +type IndividuallyParentIndividuallyParentNestedWithMixedClientWithQueryResponse struct { + // placeholder for future response values +} + +// IndividuallyParentIndividuallyParentNestedWithMultipleClientDeleteStandaloneResponse contains the response from method +// IndividuallyParentIndividuallyParentNestedWithMultipleClient.DeleteStandalone. +type IndividuallyParentIndividuallyParentNestedWithMultipleClientDeleteStandaloneResponse struct { + // placeholder for future response values +} + +// IndividuallyParentIndividuallyParentNestedWithMultipleClientGetStandaloneResponse contains the response from method IndividuallyParentIndividuallyParentNestedWithMultipleClient.GetStandalone. +type IndividuallyParentIndividuallyParentNestedWithMultipleClientGetStandaloneResponse struct { + // placeholder for future response values +} + +// IndividuallyParentIndividuallyParentNestedWithMultipleClientWithQueryResponse contains the response from method IndividuallyParentIndividuallyParentNestedWithMultipleClient.WithQuery. +type IndividuallyParentIndividuallyParentNestedWithMultipleClientWithQueryResponse struct { + // placeholder for future response values +} + +// IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithAliasedNameResponse contains the response from method +// IndividuallyParentIndividuallyParentNestedWithParamAliasClient.WithAliasedName. +type IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithAliasedNameResponse struct { + // placeholder for future response values +} + +// IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithOriginalNameResponse contains the response from method +// IndividuallyParentIndividuallyParentNestedWithParamAliasClient.WithOriginalName. +type IndividuallyParentIndividuallyParentNestedWithParamAliasClientWithOriginalNameResponse struct { + // placeholder for future response values +} + +// IndividuallyParentIndividuallyParentNestedWithPathClientDeleteStandaloneResponse contains the response from method IndividuallyParentIndividuallyParentNestedWithPathClient.DeleteStandalone. +type IndividuallyParentIndividuallyParentNestedWithPathClientDeleteStandaloneResponse struct { + // placeholder for future response values +} + +// IndividuallyParentIndividuallyParentNestedWithPathClientGetStandaloneResponse contains the response from method IndividuallyParentIndividuallyParentNestedWithPathClient.GetStandalone. +type IndividuallyParentIndividuallyParentNestedWithPathClientGetStandaloneResponse struct { + // Properties of a blob + BlobProperties +} + +// IndividuallyParentIndividuallyParentNestedWithPathClientWithQueryResponse contains the response from method IndividuallyParentIndividuallyParentNestedWithPathClient.WithQuery. +type IndividuallyParentIndividuallyParentNestedWithPathClientWithQueryResponse struct { + // placeholder for future response values +} + +// IndividuallyParentIndividuallyParentNestedWithQueryClientDeleteStandaloneResponse contains the response from method IndividuallyParentIndividuallyParentNestedWithQueryClient.DeleteStandalone. +type IndividuallyParentIndividuallyParentNestedWithQueryClientDeleteStandaloneResponse struct { + // placeholder for future response values +} + +// IndividuallyParentIndividuallyParentNestedWithQueryClientGetStandaloneResponse contains the response from method IndividuallyParentIndividuallyParentNestedWithQueryClient.GetStandalone. +type IndividuallyParentIndividuallyParentNestedWithQueryClientGetStandaloneResponse struct { + // Properties of a blob + BlobProperties +} + +// IndividuallyParentIndividuallyParentNestedWithQueryClientWithQueryResponse contains the response from method IndividuallyParentIndividuallyParentNestedWithQueryClient.WithQuery. +type IndividuallyParentIndividuallyParentNestedWithQueryClientWithQueryResponse struct { + // placeholder for future response values +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_version.go b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_version.go new file mode 100644 index 000000000000..8ee4a82c20b3 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-initialization/clientinitindividuallyparentgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package clientinitindividuallyparentgroup + +const ( + moduleName = "clientinitindividuallyparentgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/LICENSE.txt b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/fake/zz_internal.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/fake/zz_movetoexistingsub_server.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/fake/zz_movetoexistingsub_server.go new file mode 100644 index 000000000000..18bde6a80d97 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/fake/zz_movetoexistingsub_server.go @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// MoveToExistingSubServer is a fake server for instances of the coreclientlocationmoveexistingsubclientgroup.MoveToExistingSubClient type. +type MoveToExistingSubServer struct { + // MoveToExistingSubAdminOperationsServer contains the fakes for client MoveToExistingSubAdminOperationsClient + MoveToExistingSubAdminOperationsServer MoveToExistingSubAdminOperationsServer + + // MoveToExistingSubUserOperationsServer contains the fakes for client MoveToExistingSubUserOperationsClient + MoveToExistingSubUserOperationsServer MoveToExistingSubUserOperationsServer +} + +// NewMoveToExistingSubServerTransport creates a new instance of MoveToExistingSubServerTransport with the provided implementation. +// The returned MoveToExistingSubServerTransport instance is connected to an instance of coreclientlocationmoveexistingsubclientgroup.MoveToExistingSubClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewMoveToExistingSubServerTransport(srv *MoveToExistingSubServer) *MoveToExistingSubServerTransport { + return &MoveToExistingSubServerTransport{srv: srv} +} + +// MoveToExistingSubServerTransport connects instances of coreclientlocationmoveexistingsubclientgroup.MoveToExistingSubClient to instances of MoveToExistingSubServer. +// Don't use this type directly, use NewMoveToExistingSubServerTransport instead. +type MoveToExistingSubServerTransport struct { + srv *MoveToExistingSubServer + trMu sync.Mutex + trMoveToExistingSubAdminOperationsServer *MoveToExistingSubAdminOperationsServerTransport + trMoveToExistingSubUserOperationsServer *MoveToExistingSubUserOperationsServerTransport +} + +// Do implements the policy.Transporter interface for MoveToExistingSubServerTransport. +func (m *MoveToExistingSubServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (m *MoveToExistingSubServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "MoveToExistingSubAdminOperationsClient": + initServer(&m.trMu, &m.trMoveToExistingSubAdminOperationsServer, func() *MoveToExistingSubAdminOperationsServerTransport { + return NewMoveToExistingSubAdminOperationsServerTransport(&m.srv.MoveToExistingSubAdminOperationsServer) + }) + resp, err = m.trMoveToExistingSubAdminOperationsServer.Do(req) + case "MoveToExistingSubUserOperationsClient": + initServer(&m.trMu, &m.trMoveToExistingSubUserOperationsServer, func() *MoveToExistingSubUserOperationsServerTransport { + return NewMoveToExistingSubUserOperationsServerTransport(&m.srv.MoveToExistingSubUserOperationsServer) + }) + resp, err = m.trMoveToExistingSubUserOperationsServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to MoveToExistingSubServerTransport +var moveToExistingSubServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/fake/zz_movetoexistingsubadminoperations_server.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/fake/zz_movetoexistingsubadminoperations_server.go new file mode 100644 index 000000000000..bae3b6809ce4 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/fake/zz_movetoexistingsubadminoperations_server.go @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "coreclientlocationmoveexistingsubclientgroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// MoveToExistingSubAdminOperationsServer is a fake server for instances of the coreclientlocationmoveexistingsubclientgroup.MoveToExistingSubAdminOperationsClient type. +type MoveToExistingSubAdminOperationsServer struct { + // DeleteUser is the fake for method MoveToExistingSubAdminOperationsClient.DeleteUser + // HTTP status codes to indicate success: http.StatusNoContent + DeleteUser func(ctx context.Context, options *coreclientlocationmoveexistingsubclientgroup.MoveToExistingSubAdminOperationsClientDeleteUserOptions) (resp azfake.Responder[coreclientlocationmoveexistingsubclientgroup.MoveToExistingSubAdminOperationsClientDeleteUserResponse], errResp azfake.ErrorResponder) + + // GetAdminInfo is the fake for method MoveToExistingSubAdminOperationsClient.GetAdminInfo + // HTTP status codes to indicate success: http.StatusNoContent + GetAdminInfo func(ctx context.Context, options *coreclientlocationmoveexistingsubclientgroup.MoveToExistingSubAdminOperationsClientGetAdminInfoOptions) (resp azfake.Responder[coreclientlocationmoveexistingsubclientgroup.MoveToExistingSubAdminOperationsClientGetAdminInfoResponse], errResp azfake.ErrorResponder) +} + +// NewMoveToExistingSubAdminOperationsServerTransport creates a new instance of MoveToExistingSubAdminOperationsServerTransport with the provided implementation. +// The returned MoveToExistingSubAdminOperationsServerTransport instance is connected to an instance of coreclientlocationmoveexistingsubclientgroup.MoveToExistingSubAdminOperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewMoveToExistingSubAdminOperationsServerTransport(srv *MoveToExistingSubAdminOperationsServer) *MoveToExistingSubAdminOperationsServerTransport { + return &MoveToExistingSubAdminOperationsServerTransport{srv: srv} +} + +// MoveToExistingSubAdminOperationsServerTransport connects instances of coreclientlocationmoveexistingsubclientgroup.MoveToExistingSubAdminOperationsClient to instances of MoveToExistingSubAdminOperationsServer. +// Don't use this type directly, use NewMoveToExistingSubAdminOperationsServerTransport instead. +type MoveToExistingSubAdminOperationsServerTransport struct { + srv *MoveToExistingSubAdminOperationsServer +} + +// Do implements the policy.Transporter interface for MoveToExistingSubAdminOperationsServerTransport. +func (m *MoveToExistingSubAdminOperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToMethodFake(req, method) +} + +func (m *MoveToExistingSubAdminOperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if moveToExistingSubAdminOperationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = moveToExistingSubAdminOperationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "MoveToExistingSubAdminOperationsClient.DeleteUser": + res.resp, res.err = m.dispatchDeleteUser(req) + case "MoveToExistingSubAdminOperationsClient.GetAdminInfo": + res.resp, res.err = m.dispatchGetAdminInfo(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *MoveToExistingSubAdminOperationsServerTransport) dispatchDeleteUser(req *http.Request) (*http.Response, error) { + if m.srv.DeleteUser == nil { + return nil, &nonRetriableError{errors.New("fake for method DeleteUser not implemented")} + } + respr, errRespr := m.srv.DeleteUser(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *MoveToExistingSubAdminOperationsServerTransport) dispatchGetAdminInfo(req *http.Request) (*http.Response, error) { + if m.srv.GetAdminInfo == nil { + return nil, &nonRetriableError{errors.New("fake for method GetAdminInfo not implemented")} + } + respr, errRespr := m.srv.GetAdminInfo(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to MoveToExistingSubAdminOperationsServerTransport +var moveToExistingSubAdminOperationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/fake/zz_movetoexistingsubuseroperations_server.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/fake/zz_movetoexistingsubuseroperations_server.go new file mode 100644 index 000000000000..263912dfe407 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/fake/zz_movetoexistingsubuseroperations_server.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "coreclientlocationmoveexistingsubclientgroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// MoveToExistingSubUserOperationsServer is a fake server for instances of the coreclientlocationmoveexistingsubclientgroup.MoveToExistingSubUserOperationsClient type. +type MoveToExistingSubUserOperationsServer struct { + // GetUser is the fake for method MoveToExistingSubUserOperationsClient.GetUser + // HTTP status codes to indicate success: http.StatusNoContent + GetUser func(ctx context.Context, options *coreclientlocationmoveexistingsubclientgroup.MoveToExistingSubUserOperationsClientGetUserOptions) (resp azfake.Responder[coreclientlocationmoveexistingsubclientgroup.MoveToExistingSubUserOperationsClientGetUserResponse], errResp azfake.ErrorResponder) +} + +// NewMoveToExistingSubUserOperationsServerTransport creates a new instance of MoveToExistingSubUserOperationsServerTransport with the provided implementation. +// The returned MoveToExistingSubUserOperationsServerTransport instance is connected to an instance of coreclientlocationmoveexistingsubclientgroup.MoveToExistingSubUserOperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewMoveToExistingSubUserOperationsServerTransport(srv *MoveToExistingSubUserOperationsServer) *MoveToExistingSubUserOperationsServerTransport { + return &MoveToExistingSubUserOperationsServerTransport{srv: srv} +} + +// MoveToExistingSubUserOperationsServerTransport connects instances of coreclientlocationmoveexistingsubclientgroup.MoveToExistingSubUserOperationsClient to instances of MoveToExistingSubUserOperationsServer. +// Don't use this type directly, use NewMoveToExistingSubUserOperationsServerTransport instead. +type MoveToExistingSubUserOperationsServerTransport struct { + srv *MoveToExistingSubUserOperationsServer +} + +// Do implements the policy.Transporter interface for MoveToExistingSubUserOperationsServerTransport. +func (m *MoveToExistingSubUserOperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToMethodFake(req, method) +} + +func (m *MoveToExistingSubUserOperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if moveToExistingSubUserOperationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = moveToExistingSubUserOperationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "MoveToExistingSubUserOperationsClient.GetUser": + res.resp, res.err = m.dispatchGetUser(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *MoveToExistingSubUserOperationsServerTransport) dispatchGetUser(req *http.Request) (*http.Response, error) { + if m.srv.GetUser == nil { + return nil, &nonRetriableError{errors.New("fake for method GetUser not implemented")} + } + respr, errRespr := m.srv.GetUser(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to MoveToExistingSubUserOperationsServerTransport +var moveToExistingSubUserOperationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/go.mod b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/go.mod new file mode 100644 index 000000000000..88f4c8c5442d --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/go.mod @@ -0,0 +1,17 @@ +module coreclientlocationmoveexistingsubclientgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/go.sum b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/movetoexistingsub_client_test.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/movetoexistingsub_client_test.go new file mode 100644 index 000000000000..3cce46d1d522 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/movetoexistingsub_client_test.go @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package coreclientlocationmoveexistingsubclientgroup + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestMoveToExistingSubClients(t *testing.T) { + client, err := NewMoveToExistingSubClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + + adminClient := client.NewMoveToExistingSubAdminOperationsClient() + _, err = adminClient.GetAdminInfo(context.Background(), nil) + require.NoError(t, err) + + _, err = adminClient.DeleteUser(context.Background(), nil) + require.NoError(t, err) + + userClient := client.NewMoveToExistingSubUserOperationsClient() + _, err = userClient.GetUser(context.Background(), nil) + require.NoError(t, err) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/testdata/_metadata.json b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/zz_movetoexistingsub_client.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/zz_movetoexistingsub_client.go new file mode 100644 index 000000000000..c428b4679235 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/zz_movetoexistingsub_client.go @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coreclientlocationmoveexistingsubclientgroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// MoveToExistingSubClient - Test for @clientLocation decorator - moving operations between clients +// Don't use this type directly, use NewMoveToExistingSubClientWithNoCredential() instead. +type MoveToExistingSubClient struct { + internal *azcore.Client + endpoint string +} + +// MoveToExistingSubClientOptions contains the optional values for creating a [MoveToExistingSubClient]. +type MoveToExistingSubClientOptions struct { + azcore.ClientOptions +} + +// NewMoveToExistingSubClientWithNoCredential creates a new instance of MoveToExistingSubClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewMoveToExistingSubClientWithNoCredential(endpoint string, options *MoveToExistingSubClientOptions) (*MoveToExistingSubClient, error) { + if options == nil { + options = &MoveToExistingSubClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &MoveToExistingSubClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewMoveToExistingSubAdminOperationsClient creates a new instance of [MoveToExistingSubAdminOperationsClient]. +func (client *MoveToExistingSubClient) NewMoveToExistingSubAdminOperationsClient() *MoveToExistingSubAdminOperationsClient { + return &MoveToExistingSubAdminOperationsClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewMoveToExistingSubUserOperationsClient creates a new instance of [MoveToExistingSubUserOperationsClient]. +func (client *MoveToExistingSubClient) NewMoveToExistingSubUserOperationsClient() *MoveToExistingSubUserOperationsClient { + return &MoveToExistingSubUserOperationsClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/zz_movetoexistingsubadminoperations_client.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/zz_movetoexistingsubadminoperations_client.go new file mode 100644 index 000000000000..7c4ded3b762b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/zz_movetoexistingsubadminoperations_client.go @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coreclientlocationmoveexistingsubclientgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// MoveToExistingSubAdminOperationsClient contains the methods for the MoveToExistingSubAdminOperations group. +// Don't use this type directly, use [MoveToExistingSubClient.NewMoveToExistingSubAdminOperationsClient] instead. +type MoveToExistingSubAdminOperationsClient struct { + internal *azcore.Client + endpoint string +} + +// DeleteUser - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MoveToExistingSubAdminOperationsClientDeleteUserOptions contains the optional parameters for the MoveToExistingSubAdminOperationsClient.DeleteUser +// method. +func (client *MoveToExistingSubAdminOperationsClient) DeleteUser(ctx context.Context, options *MoveToExistingSubAdminOperationsClientDeleteUserOptions) (MoveToExistingSubAdminOperationsClientDeleteUserResponse, error) { + var err error + const operationName = "MoveToExistingSubAdminOperationsClient.DeleteUser" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteUserCreateRequest(ctx, options) + if err != nil { + return MoveToExistingSubAdminOperationsClientDeleteUserResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MoveToExistingSubAdminOperationsClientDeleteUserResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MoveToExistingSubAdminOperationsClientDeleteUserResponse{}, err + } + return MoveToExistingSubAdminOperationsClientDeleteUserResponse{}, nil +} + +// deleteUserCreateRequest creates the DeleteUser request. +func (client *MoveToExistingSubAdminOperationsClient) deleteUserCreateRequest(ctx context.Context, _ *MoveToExistingSubAdminOperationsClientDeleteUserOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-location/move-to-existing-sub-client/user" + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// GetAdminInfo - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MoveToExistingSubAdminOperationsClientGetAdminInfoOptions contains the optional parameters for the MoveToExistingSubAdminOperationsClient.GetAdminInfo +// method. +func (client *MoveToExistingSubAdminOperationsClient) GetAdminInfo(ctx context.Context, options *MoveToExistingSubAdminOperationsClientGetAdminInfoOptions) (MoveToExistingSubAdminOperationsClientGetAdminInfoResponse, error) { + var err error + const operationName = "MoveToExistingSubAdminOperationsClient.GetAdminInfo" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getAdminInfoCreateRequest(ctx, options) + if err != nil { + return MoveToExistingSubAdminOperationsClientGetAdminInfoResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MoveToExistingSubAdminOperationsClientGetAdminInfoResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MoveToExistingSubAdminOperationsClientGetAdminInfoResponse{}, err + } + return MoveToExistingSubAdminOperationsClientGetAdminInfoResponse{}, nil +} + +// getAdminInfoCreateRequest creates the GetAdminInfo request. +func (client *MoveToExistingSubAdminOperationsClient) getAdminInfoCreateRequest(ctx context.Context, _ *MoveToExistingSubAdminOperationsClientGetAdminInfoOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-location/move-to-existing-sub-client/admin" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/zz_movetoexistingsubuseroperations_client.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/zz_movetoexistingsubuseroperations_client.go new file mode 100644 index 000000000000..9b8522d3545a --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/zz_movetoexistingsubuseroperations_client.go @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coreclientlocationmoveexistingsubclientgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// MoveToExistingSubUserOperationsClient contains the methods for the MoveToExistingSubUserOperations group. +// Don't use this type directly, use [MoveToExistingSubClient.NewMoveToExistingSubUserOperationsClient] instead. +type MoveToExistingSubUserOperationsClient struct { + internal *azcore.Client + endpoint string +} + +// GetUser - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MoveToExistingSubUserOperationsClientGetUserOptions contains the optional parameters for the MoveToExistingSubUserOperationsClient.GetUser +// method. +func (client *MoveToExistingSubUserOperationsClient) GetUser(ctx context.Context, options *MoveToExistingSubUserOperationsClientGetUserOptions) (MoveToExistingSubUserOperationsClientGetUserResponse, error) { + var err error + const operationName = "MoveToExistingSubUserOperationsClient.GetUser" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getUserCreateRequest(ctx, options) + if err != nil { + return MoveToExistingSubUserOperationsClientGetUserResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MoveToExistingSubUserOperationsClientGetUserResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MoveToExistingSubUserOperationsClientGetUserResponse{}, err + } + return MoveToExistingSubUserOperationsClientGetUserResponse{}, nil +} + +// getUserCreateRequest creates the GetUser request. +func (client *MoveToExistingSubUserOperationsClient) getUserCreateRequest(ctx context.Context, _ *MoveToExistingSubUserOperationsClientGetUserOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-location/move-to-existing-sub-client/user" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/zz_options.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/zz_options.go new file mode 100644 index 000000000000..28aeb53024cc --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/zz_options.go @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coreclientlocationmoveexistingsubclientgroup + +// MoveToExistingSubAdminOperationsClientDeleteUserOptions contains the optional parameters for the MoveToExistingSubAdminOperationsClient.DeleteUser +// method. +type MoveToExistingSubAdminOperationsClientDeleteUserOptions struct { + // placeholder for future optional parameters +} + +// MoveToExistingSubAdminOperationsClientGetAdminInfoOptions contains the optional parameters for the MoveToExistingSubAdminOperationsClient.GetAdminInfo +// method. +type MoveToExistingSubAdminOperationsClientGetAdminInfoOptions struct { + // placeholder for future optional parameters +} + +// MoveToExistingSubUserOperationsClientGetUserOptions contains the optional parameters for the MoveToExistingSubUserOperationsClient.GetUser +// method. +type MoveToExistingSubUserOperationsClientGetUserOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/zz_responses.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/zz_responses.go new file mode 100644 index 000000000000..408f428b3818 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/zz_responses.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coreclientlocationmoveexistingsubclientgroup + +// MoveToExistingSubAdminOperationsClientDeleteUserResponse contains the response from method MoveToExistingSubAdminOperationsClient.DeleteUser. +type MoveToExistingSubAdminOperationsClientDeleteUserResponse struct { + // placeholder for future response values +} + +// MoveToExistingSubAdminOperationsClientGetAdminInfoResponse contains the response from method MoveToExistingSubAdminOperationsClient.GetAdminInfo. +type MoveToExistingSubAdminOperationsClientGetAdminInfoResponse struct { + // placeholder for future response values +} + +// MoveToExistingSubUserOperationsClientGetUserResponse contains the response from method MoveToExistingSubUserOperationsClient.GetUser. +type MoveToExistingSubUserOperationsClientGetUserResponse struct { + // placeholder for future response values +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/zz_version.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/zz_version.go new file mode 100644 index 000000000000..67b5ec63a6d3 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoveexistingsubclientgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package coreclientlocationmoveexistingsubclientgroup + +const ( + moduleName = "coreclientlocationmoveexistingsubclientgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/LICENSE.txt b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/fake/zz_internal.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/fake/zz_movemethodparameterto_server.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/fake/zz_movemethodparameterto_server.go new file mode 100644 index 000000000000..e74e27cc8df9 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/fake/zz_movemethodparameterto_server.go @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// MoveMethodParameterToServer is a fake server for instances of the coreclientlocationmovemethodparametertoclientgroup.MoveMethodParameterToClient type. +type MoveMethodParameterToServer struct { + // MoveMethodParameterToBlobOperationsServer contains the fakes for client MoveMethodParameterToBlobOperationsClient + MoveMethodParameterToBlobOperationsServer MoveMethodParameterToBlobOperationsServer +} + +// NewMoveMethodParameterToServerTransport creates a new instance of MoveMethodParameterToServerTransport with the provided implementation. +// The returned MoveMethodParameterToServerTransport instance is connected to an instance of coreclientlocationmovemethodparametertoclientgroup.MoveMethodParameterToClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewMoveMethodParameterToServerTransport(srv *MoveMethodParameterToServer) *MoveMethodParameterToServerTransport { + return &MoveMethodParameterToServerTransport{srv: srv} +} + +// MoveMethodParameterToServerTransport connects instances of coreclientlocationmovemethodparametertoclientgroup.MoveMethodParameterToClient to instances of MoveMethodParameterToServer. +// Don't use this type directly, use NewMoveMethodParameterToServerTransport instead. +type MoveMethodParameterToServerTransport struct { + srv *MoveMethodParameterToServer + trMu sync.Mutex + trMoveMethodParameterToBlobOperationsServer *MoveMethodParameterToBlobOperationsServerTransport +} + +// Do implements the policy.Transporter interface for MoveMethodParameterToServerTransport. +func (m *MoveMethodParameterToServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (m *MoveMethodParameterToServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "MoveMethodParameterToBlobOperationsClient": + initServer(&m.trMu, &m.trMoveMethodParameterToBlobOperationsServer, func() *MoveMethodParameterToBlobOperationsServerTransport { + return NewMoveMethodParameterToBlobOperationsServerTransport(&m.srv.MoveMethodParameterToBlobOperationsServer) + }) + resp, err = m.trMoveMethodParameterToBlobOperationsServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to MoveMethodParameterToServerTransport +var moveMethodParameterToServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/fake/zz_movemethodparametertobloboperations_server.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/fake/zz_movemethodparametertobloboperations_server.go new file mode 100644 index 000000000000..d18c718c6cef --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/fake/zz_movemethodparametertobloboperations_server.go @@ -0,0 +1,102 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "coreclientlocationmovemethodparametertoclientgroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// MoveMethodParameterToBlobOperationsServer is a fake server for instances of the coreclientlocationmovemethodparametertoclientgroup.MoveMethodParameterToBlobOperationsClient type. +type MoveMethodParameterToBlobOperationsServer struct { + // GetBlob is the fake for method MoveMethodParameterToBlobOperationsClient.GetBlob + // HTTP status codes to indicate success: http.StatusOK + GetBlob func(ctx context.Context, containerParam string, blob string, options *coreclientlocationmovemethodparametertoclientgroup.MoveMethodParameterToBlobOperationsClientGetBlobOptions) (resp azfake.Responder[coreclientlocationmovemethodparametertoclientgroup.MoveMethodParameterToBlobOperationsClientGetBlobResponse], errResp azfake.ErrorResponder) +} + +// NewMoveMethodParameterToBlobOperationsServerTransport creates a new instance of MoveMethodParameterToBlobOperationsServerTransport with the provided implementation. +// The returned MoveMethodParameterToBlobOperationsServerTransport instance is connected to an instance of coreclientlocationmovemethodparametertoclientgroup.MoveMethodParameterToBlobOperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewMoveMethodParameterToBlobOperationsServerTransport(srv *MoveMethodParameterToBlobOperationsServer) *MoveMethodParameterToBlobOperationsServerTransport { + return &MoveMethodParameterToBlobOperationsServerTransport{srv: srv} +} + +// MoveMethodParameterToBlobOperationsServerTransport connects instances of coreclientlocationmovemethodparametertoclientgroup.MoveMethodParameterToBlobOperationsClient to instances of MoveMethodParameterToBlobOperationsServer. +// Don't use this type directly, use NewMoveMethodParameterToBlobOperationsServerTransport instead. +type MoveMethodParameterToBlobOperationsServerTransport struct { + srv *MoveMethodParameterToBlobOperationsServer +} + +// Do implements the policy.Transporter interface for MoveMethodParameterToBlobOperationsServerTransport. +func (m *MoveMethodParameterToBlobOperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToMethodFake(req, method) +} + +func (m *MoveMethodParameterToBlobOperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if moveMethodParameterToBlobOperationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = moveMethodParameterToBlobOperationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "MoveMethodParameterToBlobOperationsClient.GetBlob": + res.resp, res.err = m.dispatchGetBlob(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *MoveMethodParameterToBlobOperationsServerTransport) dispatchGetBlob(req *http.Request) (*http.Response, error) { + if m.srv.GetBlob == nil { + return nil, &nonRetriableError{errors.New("fake for method GetBlob not implemented")} + } + qp := req.URL.Query() + respr, errRespr := m.srv.GetBlob(req.Context(), qp.Get("container"), qp.Get("blob"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Blob, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to MoveMethodParameterToBlobOperationsServerTransport +var moveMethodParameterToBlobOperationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/go.mod b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/go.mod new file mode 100644 index 000000000000..b8ad812f91c6 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/go.mod @@ -0,0 +1,17 @@ +module coreclientlocationmovemethodparametertoclientgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/go.sum b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/movemethodparameterto_client_test.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/movemethodparameterto_client_test.go new file mode 100644 index 000000000000..53a292adbc28 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/movemethodparameterto_client_test.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package coreclientlocationmovemethodparametertoclientgroup + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestMoveMethodParameterToBlobOperations_GetBlob(t *testing.T) { + client, err := NewMoveMethodParameterToClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + + blobClient := client.NewMoveMethodParameterToBlobOperationsClient() + blobClient.storageAccount = "testaccount" + + resp, err := blobClient.GetBlob(context.Background(), "testcontainer", "testblob.txt", nil) + require.NoError(t, err) + + require.NotNil(t, resp.ID) + require.Equal(t, "blob-001", *resp.ID) + require.NotNil(t, resp.Name) + require.Equal(t, "testblob.txt", *resp.Name) + require.NotNil(t, resp.Path) + require.Equal(t, "/testcontainer/testblob.txt", *resp.Path) + require.NotNil(t, resp.Size) + require.Equal(t, int32(1024), *resp.Size) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/testdata/_metadata.json b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_models.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_models.go new file mode 100644 index 000000000000..cea7b5343d7b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_models.go @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coreclientlocationmovemethodparametertoclientgroup + +type Blob struct { + // REQUIRED + ID *string + + // REQUIRED + Name *string + + // REQUIRED + Path *string + + // REQUIRED + Size *int32 +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_models_serde.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_models_serde.go new file mode 100644 index 000000000000..ad126c13de52 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_models_serde.go @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coreclientlocationmovemethodparametertoclientgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type Blob. +func (b Blob) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", b.ID) + populate(objectMap, "name", b.Name) + populate(objectMap, "path", b.Path) + populate(objectMap, "size", b.Size) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Blob. +func (b *Blob) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &b.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &b.Name) + delete(rawMsg, key) + case "path": + err = unpopulate(val, "Path", &b.Path) + delete(rawMsg, key) + case "size": + err = unpopulate(val, "Size", &b.Size) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_movemethodparameterto_client.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_movemethodparameterto_client.go new file mode 100644 index 000000000000..5d1eb901299f --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_movemethodparameterto_client.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coreclientlocationmovemethodparametertoclientgroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// MoveMethodParameterToClient - Test for @clientLocation decorator - moving operations between clients +// Don't use this type directly, use NewMoveMethodParameterToClientWithNoCredential() instead. +type MoveMethodParameterToClient struct { + internal *azcore.Client + endpoint string +} + +// MoveMethodParameterToClientOptions contains the optional values for creating a [MoveMethodParameterToClient]. +type MoveMethodParameterToClientOptions struct { + azcore.ClientOptions +} + +// NewMoveMethodParameterToClientWithNoCredential creates a new instance of MoveMethodParameterToClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewMoveMethodParameterToClientWithNoCredential(endpoint string, options *MoveMethodParameterToClientOptions) (*MoveMethodParameterToClient, error) { + if options == nil { + options = &MoveMethodParameterToClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &MoveMethodParameterToClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewMoveMethodParameterToBlobOperationsClient creates a new instance of [MoveMethodParameterToBlobOperationsClient]. +func (client *MoveMethodParameterToClient) NewMoveMethodParameterToBlobOperationsClient() *MoveMethodParameterToBlobOperationsClient { + return &MoveMethodParameterToBlobOperationsClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_movemethodparametertobloboperations_client.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_movemethodparametertobloboperations_client.go new file mode 100644 index 000000000000..7d5853cf9828 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_movemethodparametertobloboperations_client.go @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coreclientlocationmovemethodparametertoclientgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// MoveMethodParameterToBlobOperationsClient contains the methods for the MoveMethodParameterToBlobOperations group. +// Don't use this type directly, use [MoveMethodParameterToClient.NewMoveMethodParameterToBlobOperationsClient] instead. +type MoveMethodParameterToBlobOperationsClient struct { + internal *azcore.Client + endpoint string + storageAccount string +} + +// GetBlob - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MoveMethodParameterToBlobOperationsClientGetBlobOptions contains the optional parameters for the MoveMethodParameterToBlobOperationsClient.GetBlob +// method. +func (client *MoveMethodParameterToBlobOperationsClient) GetBlob(ctx context.Context, containerParam string, blob string, options *MoveMethodParameterToBlobOperationsClientGetBlobOptions) (MoveMethodParameterToBlobOperationsClientGetBlobResponse, error) { + var err error + const operationName = "MoveMethodParameterToBlobOperationsClient.GetBlob" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getBlobCreateRequest(ctx, containerParam, blob, options) + if err != nil { + return MoveMethodParameterToBlobOperationsClientGetBlobResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MoveMethodParameterToBlobOperationsClientGetBlobResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return MoveMethodParameterToBlobOperationsClientGetBlobResponse{}, err + } + resp, err := client.getBlobHandleResponse(httpResp) + return resp, err +} + +// getBlobCreateRequest creates the GetBlob request. +func (client *MoveMethodParameterToBlobOperationsClient) getBlobCreateRequest(ctx context.Context, containerParam string, blob string, _ *MoveMethodParameterToBlobOperationsClientGetBlobOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-location/move-method-parameter-to-client/blob" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("blob", blob) + reqQP.Set("container", containerParam) + reqQP.Set("storageAccount", client.storageAccount) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getBlobHandleResponse handles the GetBlob response. +func (client *MoveMethodParameterToBlobOperationsClient) getBlobHandleResponse(resp *http.Response) (MoveMethodParameterToBlobOperationsClientGetBlobResponse, error) { + result := MoveMethodParameterToBlobOperationsClientGetBlobResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Blob); err != nil { + return MoveMethodParameterToBlobOperationsClientGetBlobResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_options.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_options.go new file mode 100644 index 000000000000..e16ef1d3924e --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_options.go @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coreclientlocationmovemethodparametertoclientgroup + +// MoveMethodParameterToBlobOperationsClientGetBlobOptions contains the optional parameters for the MoveMethodParameterToBlobOperationsClient.GetBlob +// method. +type MoveMethodParameterToBlobOperationsClientGetBlobOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_responses.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_responses.go new file mode 100644 index 000000000000..569143e8cff6 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_responses.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coreclientlocationmovemethodparametertoclientgroup + +// MoveMethodParameterToBlobOperationsClientGetBlobResponse contains the response from method MoveMethodParameterToBlobOperationsClient.GetBlob. +type MoveMethodParameterToBlobOperationsClientGetBlobResponse struct { + Blob +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_version.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_version.go new file mode 100644 index 000000000000..708dec9d5489 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovemethodparametertoclientgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package coreclientlocationmovemethodparametertoclientgroup + +const ( + moduleName = "coreclientlocationmovemethodparametertoclientgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/LICENSE.txt b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/fake/zz_internal.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/fake/zz_movetonewsub_server.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/fake/zz_movetonewsub_server.go new file mode 100644 index 000000000000..6a849eea9d2b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/fake/zz_movetonewsub_server.go @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// MoveToNewSubServer is a fake server for instances of the coreclientlocationmovenewsubclientgroup.MoveToNewSubClient type. +type MoveToNewSubServer struct { + // MoveToNewSubArchiveOperationsServer contains the fakes for client MoveToNewSubArchiveOperationsClient + MoveToNewSubArchiveOperationsServer MoveToNewSubArchiveOperationsServer + + // MoveToNewSubProductOperationsServer contains the fakes for client MoveToNewSubProductOperationsClient + MoveToNewSubProductOperationsServer MoveToNewSubProductOperationsServer +} + +// NewMoveToNewSubServerTransport creates a new instance of MoveToNewSubServerTransport with the provided implementation. +// The returned MoveToNewSubServerTransport instance is connected to an instance of coreclientlocationmovenewsubclientgroup.MoveToNewSubClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewMoveToNewSubServerTransport(srv *MoveToNewSubServer) *MoveToNewSubServerTransport { + return &MoveToNewSubServerTransport{srv: srv} +} + +// MoveToNewSubServerTransport connects instances of coreclientlocationmovenewsubclientgroup.MoveToNewSubClient to instances of MoveToNewSubServer. +// Don't use this type directly, use NewMoveToNewSubServerTransport instead. +type MoveToNewSubServerTransport struct { + srv *MoveToNewSubServer + trMu sync.Mutex + trMoveToNewSubArchiveOperationsServer *MoveToNewSubArchiveOperationsServerTransport + trMoveToNewSubProductOperationsServer *MoveToNewSubProductOperationsServerTransport +} + +// Do implements the policy.Transporter interface for MoveToNewSubServerTransport. +func (m *MoveToNewSubServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (m *MoveToNewSubServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "MoveToNewSubArchiveOperationsClient": + initServer(&m.trMu, &m.trMoveToNewSubArchiveOperationsServer, func() *MoveToNewSubArchiveOperationsServerTransport { + return NewMoveToNewSubArchiveOperationsServerTransport(&m.srv.MoveToNewSubArchiveOperationsServer) + }) + resp, err = m.trMoveToNewSubArchiveOperationsServer.Do(req) + case "MoveToNewSubProductOperationsClient": + initServer(&m.trMu, &m.trMoveToNewSubProductOperationsServer, func() *MoveToNewSubProductOperationsServerTransport { + return NewMoveToNewSubProductOperationsServerTransport(&m.srv.MoveToNewSubProductOperationsServer) + }) + resp, err = m.trMoveToNewSubProductOperationsServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to MoveToNewSubServerTransport +var moveToNewSubServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/fake/zz_movetonewsubarchiveoperations_server.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/fake/zz_movetonewsubarchiveoperations_server.go new file mode 100644 index 000000000000..e94eb5aeb087 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/fake/zz_movetonewsubarchiveoperations_server.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "coreclientlocationmovenewsubclientgroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// MoveToNewSubArchiveOperationsServer is a fake server for instances of the coreclientlocationmovenewsubclientgroup.MoveToNewSubArchiveOperationsClient type. +type MoveToNewSubArchiveOperationsServer struct { + // ArchiveProduct is the fake for method MoveToNewSubArchiveOperationsClient.ArchiveProduct + // HTTP status codes to indicate success: http.StatusNoContent + ArchiveProduct func(ctx context.Context, options *coreclientlocationmovenewsubclientgroup.MoveToNewSubArchiveOperationsClientArchiveProductOptions) (resp azfake.Responder[coreclientlocationmovenewsubclientgroup.MoveToNewSubArchiveOperationsClientArchiveProductResponse], errResp azfake.ErrorResponder) +} + +// NewMoveToNewSubArchiveOperationsServerTransport creates a new instance of MoveToNewSubArchiveOperationsServerTransport with the provided implementation. +// The returned MoveToNewSubArchiveOperationsServerTransport instance is connected to an instance of coreclientlocationmovenewsubclientgroup.MoveToNewSubArchiveOperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewMoveToNewSubArchiveOperationsServerTransport(srv *MoveToNewSubArchiveOperationsServer) *MoveToNewSubArchiveOperationsServerTransport { + return &MoveToNewSubArchiveOperationsServerTransport{srv: srv} +} + +// MoveToNewSubArchiveOperationsServerTransport connects instances of coreclientlocationmovenewsubclientgroup.MoveToNewSubArchiveOperationsClient to instances of MoveToNewSubArchiveOperationsServer. +// Don't use this type directly, use NewMoveToNewSubArchiveOperationsServerTransport instead. +type MoveToNewSubArchiveOperationsServerTransport struct { + srv *MoveToNewSubArchiveOperationsServer +} + +// Do implements the policy.Transporter interface for MoveToNewSubArchiveOperationsServerTransport. +func (m *MoveToNewSubArchiveOperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToMethodFake(req, method) +} + +func (m *MoveToNewSubArchiveOperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if moveToNewSubArchiveOperationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = moveToNewSubArchiveOperationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "MoveToNewSubArchiveOperationsClient.ArchiveProduct": + res.resp, res.err = m.dispatchArchiveProduct(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *MoveToNewSubArchiveOperationsServerTransport) dispatchArchiveProduct(req *http.Request) (*http.Response, error) { + if m.srv.ArchiveProduct == nil { + return nil, &nonRetriableError{errors.New("fake for method ArchiveProduct not implemented")} + } + respr, errRespr := m.srv.ArchiveProduct(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to MoveToNewSubArchiveOperationsServerTransport +var moveToNewSubArchiveOperationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/fake/zz_movetonewsubproductoperations_server.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/fake/zz_movetonewsubproductoperations_server.go new file mode 100644 index 000000000000..b6d48d7f42e8 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/fake/zz_movetonewsubproductoperations_server.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "coreclientlocationmovenewsubclientgroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// MoveToNewSubProductOperationsServer is a fake server for instances of the coreclientlocationmovenewsubclientgroup.MoveToNewSubProductOperationsClient type. +type MoveToNewSubProductOperationsServer struct { + // ListProducts is the fake for method MoveToNewSubProductOperationsClient.ListProducts + // HTTP status codes to indicate success: http.StatusNoContent + ListProducts func(ctx context.Context, options *coreclientlocationmovenewsubclientgroup.MoveToNewSubProductOperationsClientListProductsOptions) (resp azfake.Responder[coreclientlocationmovenewsubclientgroup.MoveToNewSubProductOperationsClientListProductsResponse], errResp azfake.ErrorResponder) +} + +// NewMoveToNewSubProductOperationsServerTransport creates a new instance of MoveToNewSubProductOperationsServerTransport with the provided implementation. +// The returned MoveToNewSubProductOperationsServerTransport instance is connected to an instance of coreclientlocationmovenewsubclientgroup.MoveToNewSubProductOperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewMoveToNewSubProductOperationsServerTransport(srv *MoveToNewSubProductOperationsServer) *MoveToNewSubProductOperationsServerTransport { + return &MoveToNewSubProductOperationsServerTransport{srv: srv} +} + +// MoveToNewSubProductOperationsServerTransport connects instances of coreclientlocationmovenewsubclientgroup.MoveToNewSubProductOperationsClient to instances of MoveToNewSubProductOperationsServer. +// Don't use this type directly, use NewMoveToNewSubProductOperationsServerTransport instead. +type MoveToNewSubProductOperationsServerTransport struct { + srv *MoveToNewSubProductOperationsServer +} + +// Do implements the policy.Transporter interface for MoveToNewSubProductOperationsServerTransport. +func (m *MoveToNewSubProductOperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToMethodFake(req, method) +} + +func (m *MoveToNewSubProductOperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if moveToNewSubProductOperationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = moveToNewSubProductOperationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "MoveToNewSubProductOperationsClient.ListProducts": + res.resp, res.err = m.dispatchListProducts(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *MoveToNewSubProductOperationsServerTransport) dispatchListProducts(req *http.Request) (*http.Response, error) { + if m.srv.ListProducts == nil { + return nil, &nonRetriableError{errors.New("fake for method ListProducts not implemented")} + } + respr, errRespr := m.srv.ListProducts(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to MoveToNewSubProductOperationsServerTransport +var moveToNewSubProductOperationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/go.mod b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/go.mod new file mode 100644 index 000000000000..8570edc7b1c4 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/go.mod @@ -0,0 +1,17 @@ +module coreclientlocationmovenewsubclientgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/go.sum b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/movetonewsub_client_test.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/movetonewsub_client_test.go new file mode 100644 index 000000000000..e7dbbd0116cc --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/movetonewsub_client_test.go @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package coreclientlocationmovenewsubclientgroup + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestMoveToNewSubClients(t *testing.T) { + client, err := NewMoveToNewSubClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + + archiveClient := client.NewMoveToNewSubArchiveOperationsClient() + _, err = archiveClient.ArchiveProduct(context.Background(), nil) + require.NoError(t, err) + + productClient := client.NewMoveToNewSubProductOperationsClient() + _, err = productClient.ListProducts(context.Background(), nil) + require.NoError(t, err) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/testdata/_metadata.json b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/zz_movetonewsub_client.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/zz_movetonewsub_client.go new file mode 100644 index 000000000000..f60ce6b3ddd0 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/zz_movetonewsub_client.go @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coreclientlocationmovenewsubclientgroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// MoveToNewSubClient - Test for @clientLocation decorator - moving operations between clients +// Don't use this type directly, use NewMoveToNewSubClientWithNoCredential() instead. +type MoveToNewSubClient struct { + internal *azcore.Client + endpoint string +} + +// MoveToNewSubClientOptions contains the optional values for creating a [MoveToNewSubClient]. +type MoveToNewSubClientOptions struct { + azcore.ClientOptions +} + +// NewMoveToNewSubClientWithNoCredential creates a new instance of MoveToNewSubClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewMoveToNewSubClientWithNoCredential(endpoint string, options *MoveToNewSubClientOptions) (*MoveToNewSubClient, error) { + if options == nil { + options = &MoveToNewSubClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &MoveToNewSubClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewMoveToNewSubArchiveOperationsClient creates a new instance of [MoveToNewSubArchiveOperationsClient]. +func (client *MoveToNewSubClient) NewMoveToNewSubArchiveOperationsClient() *MoveToNewSubArchiveOperationsClient { + return &MoveToNewSubArchiveOperationsClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewMoveToNewSubProductOperationsClient creates a new instance of [MoveToNewSubProductOperationsClient]. +func (client *MoveToNewSubClient) NewMoveToNewSubProductOperationsClient() *MoveToNewSubProductOperationsClient { + return &MoveToNewSubProductOperationsClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/zz_movetonewsubarchiveoperations_client.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/zz_movetonewsubarchiveoperations_client.go new file mode 100644 index 000000000000..f922026670c1 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/zz_movetonewsubarchiveoperations_client.go @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coreclientlocationmovenewsubclientgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// MoveToNewSubArchiveOperationsClient contains the methods for the MoveToNewSubArchiveOperations group. +// Don't use this type directly, use [MoveToNewSubClient.NewMoveToNewSubArchiveOperationsClient] instead. +type MoveToNewSubArchiveOperationsClient struct { + internal *azcore.Client + endpoint string +} + +// ArchiveProduct - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MoveToNewSubArchiveOperationsClientArchiveProductOptions contains the optional parameters for the MoveToNewSubArchiveOperationsClient.ArchiveProduct +// method. +func (client *MoveToNewSubArchiveOperationsClient) ArchiveProduct(ctx context.Context, options *MoveToNewSubArchiveOperationsClientArchiveProductOptions) (MoveToNewSubArchiveOperationsClientArchiveProductResponse, error) { + var err error + const operationName = "MoveToNewSubArchiveOperationsClient.ArchiveProduct" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.archiveProductCreateRequest(ctx, options) + if err != nil { + return MoveToNewSubArchiveOperationsClientArchiveProductResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MoveToNewSubArchiveOperationsClientArchiveProductResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MoveToNewSubArchiveOperationsClientArchiveProductResponse{}, err + } + return MoveToNewSubArchiveOperationsClientArchiveProductResponse{}, nil +} + +// archiveProductCreateRequest creates the ArchiveProduct request. +func (client *MoveToNewSubArchiveOperationsClient) archiveProductCreateRequest(ctx context.Context, _ *MoveToNewSubArchiveOperationsClientArchiveProductOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-location/move-to-new-sub-client/products/archive" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/zz_movetonewsubproductoperations_client.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/zz_movetonewsubproductoperations_client.go new file mode 100644 index 000000000000..96ffd77776be --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/zz_movetonewsubproductoperations_client.go @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coreclientlocationmovenewsubclientgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// MoveToNewSubProductOperationsClient contains the methods for the MoveToNewSubProductOperations group. +// Don't use this type directly, use [MoveToNewSubClient.NewMoveToNewSubProductOperationsClient] instead. +type MoveToNewSubProductOperationsClient struct { + internal *azcore.Client + endpoint string +} + +// ListProducts - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MoveToNewSubProductOperationsClientListProductsOptions contains the optional parameters for the MoveToNewSubProductOperationsClient.ListProducts +// method. +func (client *MoveToNewSubProductOperationsClient) ListProducts(ctx context.Context, options *MoveToNewSubProductOperationsClientListProductsOptions) (MoveToNewSubProductOperationsClientListProductsResponse, error) { + var err error + const operationName = "MoveToNewSubProductOperationsClient.ListProducts" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listProductsCreateRequest(ctx, options) + if err != nil { + return MoveToNewSubProductOperationsClientListProductsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MoveToNewSubProductOperationsClientListProductsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MoveToNewSubProductOperationsClientListProductsResponse{}, err + } + return MoveToNewSubProductOperationsClientListProductsResponse{}, nil +} + +// listProductsCreateRequest creates the ListProducts request. +func (client *MoveToNewSubProductOperationsClient) listProductsCreateRequest(ctx context.Context, _ *MoveToNewSubProductOperationsClientListProductsOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-location/move-to-new-sub-client/products" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/zz_options.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/zz_options.go new file mode 100644 index 000000000000..9e770a2583cc --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/zz_options.go @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coreclientlocationmovenewsubclientgroup + +// MoveToNewSubArchiveOperationsClientArchiveProductOptions contains the optional parameters for the MoveToNewSubArchiveOperationsClient.ArchiveProduct +// method. +type MoveToNewSubArchiveOperationsClientArchiveProductOptions struct { + // placeholder for future optional parameters +} + +// MoveToNewSubProductOperationsClientListProductsOptions contains the optional parameters for the MoveToNewSubProductOperationsClient.ListProducts +// method. +type MoveToNewSubProductOperationsClientListProductsOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/zz_responses.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/zz_responses.go new file mode 100644 index 000000000000..c3564636e578 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/zz_responses.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coreclientlocationmovenewsubclientgroup + +// MoveToNewSubArchiveOperationsClientArchiveProductResponse contains the response from method MoveToNewSubArchiveOperationsClient.ArchiveProduct. +type MoveToNewSubArchiveOperationsClientArchiveProductResponse struct { + // placeholder for future response values +} + +// MoveToNewSubProductOperationsClientListProductsResponse contains the response from method MoveToNewSubProductOperationsClient.ListProducts. +type MoveToNewSubProductOperationsClientListProductsResponse struct { + // placeholder for future response values +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/zz_version.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/zz_version.go new file mode 100644 index 000000000000..70a4d09d7b7e --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmovenewsubclientgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package coreclientlocationmovenewsubclientgroup + +const ( + moduleName = "coreclientlocationmovenewsubclientgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/LICENSE.txt b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/fake/zz_internal.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/fake/zz_movetoroot_server.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/fake/zz_movetoroot_server.go new file mode 100644 index 000000000000..73b6ce2b8fbd --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/fake/zz_movetoroot_server.go @@ -0,0 +1,128 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "coreclientlocationmoverootclientgroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "strings" + "sync" +) + +// MoveToRootServer is a fake server for instances of the coreclientlocationmoverootclientgroup.MoveToRootClient type. +type MoveToRootServer struct { + // MoveToRootResourceOperationsServer contains the fakes for client MoveToRootResourceOperationsClient + MoveToRootResourceOperationsServer MoveToRootResourceOperationsServer + + // GetHealthStatus is the fake for method MoveToRootClient.GetHealthStatus + // HTTP status codes to indicate success: http.StatusNoContent + GetHealthStatus func(ctx context.Context, options *coreclientlocationmoverootclientgroup.MoveToRootClientGetHealthStatusOptions) (resp azfake.Responder[coreclientlocationmoverootclientgroup.MoveToRootClientGetHealthStatusResponse], errResp azfake.ErrorResponder) +} + +// NewMoveToRootServerTransport creates a new instance of MoveToRootServerTransport with the provided implementation. +// The returned MoveToRootServerTransport instance is connected to an instance of coreclientlocationmoverootclientgroup.MoveToRootClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewMoveToRootServerTransport(srv *MoveToRootServer) *MoveToRootServerTransport { + return &MoveToRootServerTransport{srv: srv} +} + +// MoveToRootServerTransport connects instances of coreclientlocationmoverootclientgroup.MoveToRootClient to instances of MoveToRootServer. +// Don't use this type directly, use NewMoveToRootServerTransport instead. +type MoveToRootServerTransport struct { + srv *MoveToRootServer + trMu sync.Mutex + trMoveToRootResourceOperationsServer *MoveToRootResourceOperationsServerTransport +} + +// Do implements the policy.Transporter interface for MoveToRootServerTransport. +func (m *MoveToRootServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + if client := method[:strings.Index(method, ".")]; client != "MoveToRootClient" { + return m.dispatchToClientFake(req, client) + } + return m.dispatchToMethodFake(req, method) +} + +func (m *MoveToRootServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "MoveToRootResourceOperationsClient": + initServer(&m.trMu, &m.trMoveToRootResourceOperationsServer, func() *MoveToRootResourceOperationsServerTransport { + return NewMoveToRootResourceOperationsServerTransport(&m.srv.MoveToRootResourceOperationsServer) + }) + resp, err = m.trMoveToRootResourceOperationsServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +func (m *MoveToRootServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if moveToRootServerTransportInterceptor != nil { + res.resp, res.err, intercepted = moveToRootServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "MoveToRootClient.GetHealthStatus": + res.resp, res.err = m.dispatchGetHealthStatus(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *MoveToRootServerTransport) dispatchGetHealthStatus(req *http.Request) (*http.Response, error) { + if m.srv.GetHealthStatus == nil { + return nil, &nonRetriableError{errors.New("fake for method GetHealthStatus not implemented")} + } + respr, errRespr := m.srv.GetHealthStatus(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to MoveToRootServerTransport +var moveToRootServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/fake/zz_movetorootresourceoperations_server.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/fake/zz_movetorootresourceoperations_server.go new file mode 100644 index 000000000000..83ec00ee5f73 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/fake/zz_movetorootresourceoperations_server.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "coreclientlocationmoverootclientgroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// MoveToRootResourceOperationsServer is a fake server for instances of the coreclientlocationmoverootclientgroup.MoveToRootResourceOperationsClient type. +type MoveToRootResourceOperationsServer struct { + // GetResource is the fake for method MoveToRootResourceOperationsClient.GetResource + // HTTP status codes to indicate success: http.StatusNoContent + GetResource func(ctx context.Context, options *coreclientlocationmoverootclientgroup.MoveToRootResourceOperationsClientGetResourceOptions) (resp azfake.Responder[coreclientlocationmoverootclientgroup.MoveToRootResourceOperationsClientGetResourceResponse], errResp azfake.ErrorResponder) +} + +// NewMoveToRootResourceOperationsServerTransport creates a new instance of MoveToRootResourceOperationsServerTransport with the provided implementation. +// The returned MoveToRootResourceOperationsServerTransport instance is connected to an instance of coreclientlocationmoverootclientgroup.MoveToRootResourceOperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewMoveToRootResourceOperationsServerTransport(srv *MoveToRootResourceOperationsServer) *MoveToRootResourceOperationsServerTransport { + return &MoveToRootResourceOperationsServerTransport{srv: srv} +} + +// MoveToRootResourceOperationsServerTransport connects instances of coreclientlocationmoverootclientgroup.MoveToRootResourceOperationsClient to instances of MoveToRootResourceOperationsServer. +// Don't use this type directly, use NewMoveToRootResourceOperationsServerTransport instead. +type MoveToRootResourceOperationsServerTransport struct { + srv *MoveToRootResourceOperationsServer +} + +// Do implements the policy.Transporter interface for MoveToRootResourceOperationsServerTransport. +func (m *MoveToRootResourceOperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToMethodFake(req, method) +} + +func (m *MoveToRootResourceOperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if moveToRootResourceOperationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = moveToRootResourceOperationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "MoveToRootResourceOperationsClient.GetResource": + res.resp, res.err = m.dispatchGetResource(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *MoveToRootResourceOperationsServerTransport) dispatchGetResource(req *http.Request) (*http.Response, error) { + if m.srv.GetResource == nil { + return nil, &nonRetriableError{errors.New("fake for method GetResource not implemented")} + } + respr, errRespr := m.srv.GetResource(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to MoveToRootResourceOperationsServerTransport +var moveToRootResourceOperationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/go.mod b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/go.mod new file mode 100644 index 000000000000..bdd65675082a --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/go.mod @@ -0,0 +1,17 @@ +module coreclientlocationmoverootclientgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/go.sum b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/movetoroot_client_test.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/movetoroot_client_test.go new file mode 100644 index 000000000000..8185957fc587 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/movetoroot_client_test.go @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package coreclientlocationmoverootclientgroup + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestMoveToRootClients(t *testing.T) { + client, err := NewMoveToRootClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + + _, err = client.GetHealthStatus(context.Background(), nil) + require.NoError(t, err) + + resourceClient := client.NewMoveToRootResourceOperationsClient() + _, err = resourceClient.GetResource(context.Background(), nil) + require.NoError(t, err) +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/testdata/_metadata.json b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/zz_movetoroot_client.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/zz_movetoroot_client.go new file mode 100644 index 000000000000..ba77fcea4f5c --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/zz_movetoroot_client.go @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coreclientlocationmoverootclientgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// MoveToRootClient - Test for @clientLocation decorator - moving operations between clients +// Don't use this type directly, use NewMoveToRootClientWithNoCredential() instead. +type MoveToRootClient struct { + internal *azcore.Client + endpoint string +} + +// MoveToRootClientOptions contains the optional values for creating a [MoveToRootClient]. +type MoveToRootClientOptions struct { + azcore.ClientOptions +} + +// NewMoveToRootClientWithNoCredential creates a new instance of MoveToRootClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewMoveToRootClientWithNoCredential(endpoint string, options *MoveToRootClientOptions) (*MoveToRootClient, error) { + if options == nil { + options = &MoveToRootClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &MoveToRootClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewMoveToRootResourceOperationsClient creates a new instance of [MoveToRootResourceOperationsClient]. +func (client *MoveToRootClient) NewMoveToRootResourceOperationsClient() *MoveToRootResourceOperationsClient { + return &MoveToRootResourceOperationsClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// GetHealthStatus - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MoveToRootClientGetHealthStatusOptions contains the optional parameters for the MoveToRootClient.GetHealthStatus +// method. +func (client *MoveToRootClient) GetHealthStatus(ctx context.Context, options *MoveToRootClientGetHealthStatusOptions) (MoveToRootClientGetHealthStatusResponse, error) { + var err error + const operationName = "MoveToRootClient.GetHealthStatus" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getHealthStatusCreateRequest(ctx, options) + if err != nil { + return MoveToRootClientGetHealthStatusResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MoveToRootClientGetHealthStatusResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MoveToRootClientGetHealthStatusResponse{}, err + } + return MoveToRootClientGetHealthStatusResponse{}, nil +} + +// getHealthStatusCreateRequest creates the GetHealthStatus request. +func (client *MoveToRootClient) getHealthStatusCreateRequest(ctx context.Context, _ *MoveToRootClientGetHealthStatusOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-location/move-to-root-client/health" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/zz_movetorootresourceoperations_client.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/zz_movetorootresourceoperations_client.go new file mode 100644 index 000000000000..c58c691d0fe7 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/zz_movetorootresourceoperations_client.go @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coreclientlocationmoverootclientgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// MoveToRootResourceOperationsClient contains the methods for the MoveToRootResourceOperations group. +// Don't use this type directly, use [MoveToRootClient.NewMoveToRootResourceOperationsClient] instead. +type MoveToRootResourceOperationsClient struct { + internal *azcore.Client + endpoint string +} + +// GetResource - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MoveToRootResourceOperationsClientGetResourceOptions contains the optional parameters for the MoveToRootResourceOperationsClient.GetResource +// method. +func (client *MoveToRootResourceOperationsClient) GetResource(ctx context.Context, options *MoveToRootResourceOperationsClientGetResourceOptions) (MoveToRootResourceOperationsClientGetResourceResponse, error) { + var err error + const operationName = "MoveToRootResourceOperationsClient.GetResource" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getResourceCreateRequest(ctx, options) + if err != nil { + return MoveToRootResourceOperationsClientGetResourceResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MoveToRootResourceOperationsClientGetResourceResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MoveToRootResourceOperationsClientGetResourceResponse{}, err + } + return MoveToRootResourceOperationsClientGetResourceResponse{}, nil +} + +// getResourceCreateRequest creates the GetResource request. +func (client *MoveToRootResourceOperationsClient) getResourceCreateRequest(ctx context.Context, _ *MoveToRootResourceOperationsClientGetResourceOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-location/move-to-root-client/resource" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/zz_options.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/zz_options.go new file mode 100644 index 000000000000..4ffff1f6c7ea --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/zz_options.go @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coreclientlocationmoverootclientgroup + +// MoveToRootClientGetHealthStatusOptions contains the optional parameters for the MoveToRootClient.GetHealthStatus method. +type MoveToRootClientGetHealthStatusOptions struct { + // placeholder for future optional parameters +} + +// MoveToRootResourceOperationsClientGetResourceOptions contains the optional parameters for the MoveToRootResourceOperationsClient.GetResource +// method. +type MoveToRootResourceOperationsClientGetResourceOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/zz_responses.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/zz_responses.go new file mode 100644 index 000000000000..3f498972d55b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/zz_responses.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coreclientlocationmoverootclientgroup + +// MoveToRootClientGetHealthStatusResponse contains the response from method MoveToRootClient.GetHealthStatus. +type MoveToRootClientGetHealthStatusResponse struct { + // placeholder for future response values +} + +// MoveToRootResourceOperationsClientGetResourceResponse contains the response from method MoveToRootResourceOperationsClient.GetResource. +type MoveToRootResourceOperationsClientGetResourceResponse struct { + // placeholder for future response values +} diff --git a/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/zz_version.go b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/zz_version.go new file mode 100644 index 000000000000..4219ca4d6027 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/client-location/coreclientlocationmoverootclientgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package coreclientlocationmoverootclientgroup + +const ( + moduleName = "coreclientlocationmoverootclientgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/client-generator-core/coreusagegroup/LICENSE.txt b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/client-generator-core/coreusagegroup/fake/zz_internal.go b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/azure-http-specs/azure/client-generator-core/coreusagegroup/fake/zz_usage_server.go b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/fake/zz_usage_server.go new file mode 100644 index 000000000000..e3e2805e7d10 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/fake/zz_usage_server.go @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// UsageServer is a fake server for instances of the coreusagegroup.UsageClient type. +type UsageServer struct { + // UsageModelInOperationServer contains the fakes for client UsageModelInOperationClient + UsageModelInOperationServer UsageModelInOperationServer + + // UsageNamespaceUsageServer contains the fakes for client UsageNamespaceUsageClient + UsageNamespaceUsageServer UsageNamespaceUsageServer +} + +// NewUsageServerTransport creates a new instance of UsageServerTransport with the provided implementation. +// The returned UsageServerTransport instance is connected to an instance of coreusagegroup.UsageClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewUsageServerTransport(srv *UsageServer) *UsageServerTransport { + return &UsageServerTransport{srv: srv} +} + +// UsageServerTransport connects instances of coreusagegroup.UsageClient to instances of UsageServer. +// Don't use this type directly, use NewUsageServerTransport instead. +type UsageServerTransport struct { + srv *UsageServer + trMu sync.Mutex + trUsageModelInOperationServer *UsageModelInOperationServerTransport + trUsageNamespaceUsageServer *UsageNamespaceUsageServerTransport +} + +// Do implements the policy.Transporter interface for UsageServerTransport. +func (u *UsageServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return u.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (u *UsageServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "UsageModelInOperationClient": + initServer(&u.trMu, &u.trUsageModelInOperationServer, func() *UsageModelInOperationServerTransport { + return NewUsageModelInOperationServerTransport(&u.srv.UsageModelInOperationServer) + }) + resp, err = u.trUsageModelInOperationServer.Do(req) + case "UsageNamespaceUsageClient": + initServer(&u.trMu, &u.trUsageNamespaceUsageServer, func() *UsageNamespaceUsageServerTransport { + return NewUsageNamespaceUsageServerTransport(&u.srv.UsageNamespaceUsageServer) + }) + resp, err = u.trUsageNamespaceUsageServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to UsageServerTransport +var usageServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/coreusagegroup/fake/zz_usagemodelinoperation_server.go b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/fake/zz_usagemodelinoperation_server.go new file mode 100644 index 000000000000..26c8642ffebb --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/fake/zz_usagemodelinoperation_server.go @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "coreusagegroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// UsageModelInOperationServer is a fake server for instances of the coreusagegroup.UsageModelInOperationClient type. +type UsageModelInOperationServer struct { + // InputToInputOutput is the fake for method UsageModelInOperationClient.InputToInputOutput + // HTTP status codes to indicate success: http.StatusNoContent + InputToInputOutput func(ctx context.Context, body coreusagegroup.InputModel, options *coreusagegroup.UsageModelInOperationClientInputToInputOutputOptions) (resp azfake.Responder[coreusagegroup.UsageModelInOperationClientInputToInputOutputResponse], errResp azfake.ErrorResponder) + + // ModelInReadOnlyProperty is the fake for method UsageModelInOperationClient.ModelInReadOnlyProperty + // HTTP status codes to indicate success: http.StatusOK + ModelInReadOnlyProperty func(ctx context.Context, body coreusagegroup.RoundTripModel, options *coreusagegroup.UsageModelInOperationClientModelInReadOnlyPropertyOptions) (resp azfake.Responder[coreusagegroup.UsageModelInOperationClientModelInReadOnlyPropertyResponse], errResp azfake.ErrorResponder) + + // OrphanModelSerializable is the fake for method UsageModelInOperationClient.OrphanModelSerializable + // HTTP status codes to indicate success: http.StatusNoContent + OrphanModelSerializable func(ctx context.Context, body any, options *coreusagegroup.UsageModelInOperationClientOrphanModelSerializableOptions) (resp azfake.Responder[coreusagegroup.UsageModelInOperationClientOrphanModelSerializableResponse], errResp azfake.ErrorResponder) + + // OutputToInputOutput is the fake for method UsageModelInOperationClient.OutputToInputOutput + // HTTP status codes to indicate success: http.StatusOK + OutputToInputOutput func(ctx context.Context, options *coreusagegroup.UsageModelInOperationClientOutputToInputOutputOptions) (resp azfake.Responder[coreusagegroup.UsageModelInOperationClientOutputToInputOutputResponse], errResp azfake.ErrorResponder) +} + +// NewUsageModelInOperationServerTransport creates a new instance of UsageModelInOperationServerTransport with the provided implementation. +// The returned UsageModelInOperationServerTransport instance is connected to an instance of coreusagegroup.UsageModelInOperationClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewUsageModelInOperationServerTransport(srv *UsageModelInOperationServer) *UsageModelInOperationServerTransport { + return &UsageModelInOperationServerTransport{srv: srv} +} + +// UsageModelInOperationServerTransport connects instances of coreusagegroup.UsageModelInOperationClient to instances of UsageModelInOperationServer. +// Don't use this type directly, use NewUsageModelInOperationServerTransport instead. +type UsageModelInOperationServerTransport struct { + srv *UsageModelInOperationServer +} + +// Do implements the policy.Transporter interface for UsageModelInOperationServerTransport. +func (u *UsageModelInOperationServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return u.dispatchToMethodFake(req, method) +} + +func (u *UsageModelInOperationServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if usageModelInOperationServerTransportInterceptor != nil { + res.resp, res.err, intercepted = usageModelInOperationServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "UsageModelInOperationClient.InputToInputOutput": + res.resp, res.err = u.dispatchInputToInputOutput(req) + case "UsageModelInOperationClient.ModelInReadOnlyProperty": + res.resp, res.err = u.dispatchModelInReadOnlyProperty(req) + case "UsageModelInOperationClient.OrphanModelSerializable": + res.resp, res.err = u.dispatchOrphanModelSerializable(req) + case "UsageModelInOperationClient.OutputToInputOutput": + res.resp, res.err = u.dispatchOutputToInputOutput(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (u *UsageModelInOperationServerTransport) dispatchInputToInputOutput(req *http.Request) (*http.Response, error) { + if u.srv.InputToInputOutput == nil { + return nil, &nonRetriableError{errors.New("fake for method InputToInputOutput not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[coreusagegroup.InputModel](req) + if err != nil { + return nil, err + } + respr, errRespr := u.srv.InputToInputOutput(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (u *UsageModelInOperationServerTransport) dispatchModelInReadOnlyProperty(req *http.Request) (*http.Response, error) { + if u.srv.ModelInReadOnlyProperty == nil { + return nil, &nonRetriableError{errors.New("fake for method ModelInReadOnlyProperty not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[coreusagegroup.RoundTripModel](req) + if err != nil { + return nil, err + } + respr, errRespr := u.srv.ModelInReadOnlyProperty(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RoundTripModel, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (u *UsageModelInOperationServerTransport) dispatchOrphanModelSerializable(req *http.Request) (*http.Response, error) { + if u.srv.OrphanModelSerializable == nil { + return nil, &nonRetriableError{errors.New("fake for method OrphanModelSerializable not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[any](req) + if err != nil { + return nil, err + } + respr, errRespr := u.srv.OrphanModelSerializable(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (u *UsageModelInOperationServerTransport) dispatchOutputToInputOutput(req *http.Request) (*http.Response, error) { + if u.srv.OutputToInputOutput == nil { + return nil, &nonRetriableError{errors.New("fake for method OutputToInputOutput not implemented")} + } + respr, errRespr := u.srv.OutputToInputOutput(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).OutputModel, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to UsageModelInOperationServerTransport +var usageModelInOperationServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/coreusagegroup/fake/zz_usagenamespaceusage_server.go b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/fake/zz_usagenamespaceusage_server.go new file mode 100644 index 000000000000..bf9ce109db93 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/fake/zz_usagenamespaceusage_server.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "coreusagegroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// UsageNamespaceUsageServer is a fake server for instances of the coreusagegroup.UsageNamespaceUsageClient type. +type UsageNamespaceUsageServer struct { + // NamespaceModelSerializable is the fake for method UsageNamespaceUsageClient.NamespaceModelSerializable + // HTTP status codes to indicate success: http.StatusNoContent + NamespaceModelSerializable func(ctx context.Context, body any, options *coreusagegroup.UsageNamespaceUsageClientNamespaceModelSerializableOptions) (resp azfake.Responder[coreusagegroup.UsageNamespaceUsageClientNamespaceModelSerializableResponse], errResp azfake.ErrorResponder) +} + +// NewUsageNamespaceUsageServerTransport creates a new instance of UsageNamespaceUsageServerTransport with the provided implementation. +// The returned UsageNamespaceUsageServerTransport instance is connected to an instance of coreusagegroup.UsageNamespaceUsageClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewUsageNamespaceUsageServerTransport(srv *UsageNamespaceUsageServer) *UsageNamespaceUsageServerTransport { + return &UsageNamespaceUsageServerTransport{srv: srv} +} + +// UsageNamespaceUsageServerTransport connects instances of coreusagegroup.UsageNamespaceUsageClient to instances of UsageNamespaceUsageServer. +// Don't use this type directly, use NewUsageNamespaceUsageServerTransport instead. +type UsageNamespaceUsageServerTransport struct { + srv *UsageNamespaceUsageServer +} + +// Do implements the policy.Transporter interface for UsageNamespaceUsageServerTransport. +func (u *UsageNamespaceUsageServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return u.dispatchToMethodFake(req, method) +} + +func (u *UsageNamespaceUsageServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if usageNamespaceUsageServerTransportInterceptor != nil { + res.resp, res.err, intercepted = usageNamespaceUsageServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "UsageNamespaceUsageClient.NamespaceModelSerializable": + res.resp, res.err = u.dispatchNamespaceModelSerializable(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (u *UsageNamespaceUsageServerTransport) dispatchNamespaceModelSerializable(req *http.Request) (*http.Response, error) { + if u.srv.NamespaceModelSerializable == nil { + return nil, &nonRetriableError{errors.New("fake for method NamespaceModelSerializable not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[any](req) + if err != nil { + return nil, err + } + respr, errRespr := u.srv.NamespaceModelSerializable(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to UsageNamespaceUsageServerTransport +var usageNamespaceUsageServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/coreusagegroup/go.mod b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/go.mod new file mode 100644 index 000000000000..eed01b46f3ee --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/go.mod @@ -0,0 +1,17 @@ +module coreusagegroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/client-generator-core/coreusagegroup/go.sum b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/client-generator-core/coreusagegroup/modelinoperation_client_test.go b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/modelinoperation_client_test.go new file mode 100644 index 000000000000..e94dd3c6bf0e --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/modelinoperation_client_test.go @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package coreusagegroup_test + +import ( + "context" + "coreusagegroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestModelInOperationClient_InputToInputOutput(t *testing.T) { + client, err := coreusagegroup.NewUsageClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewUsageModelInOperationClient().InputToInputOutput(context.Background(), coreusagegroup.InputModel{ + Name: to.Ptr("Madge"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelInOperationClient_OutputToInputOutput(t *testing.T) { + client, err := coreusagegroup.NewUsageClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewUsageModelInOperationClient().OutputToInputOutput(context.Background(), nil) + require.NoError(t, err) + require.Equal(t, coreusagegroup.OutputModel{ + Name: to.Ptr("Madge"), + }, resp.OutputModel) +} + +func TestModelInOperationClient_ModelInReadOnlyProperty(t *testing.T) { + client, err := coreusagegroup.NewUsageClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewUsageModelInOperationClient().ModelInReadOnlyProperty(context.Background(), coreusagegroup.RoundTripModel{}, nil) + require.NoError(t, err) + require.NotNil(t, resp) + require.Equal(t, "Madge", *resp.Result.Name) +} + +func TestModelInOperationClient_OrphanModelSerializable(t *testing.T) { + client, err := coreusagegroup.NewUsageClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewUsageModelInOperationClient().OrphanModelSerializable( + context.Background(), + coreusagegroup.OrphanModel{ + ModelName: to.Ptr("name"), + Description: to.Ptr("desc"), + }, + &coreusagegroup.UsageModelInOperationClientOrphanModelSerializableOptions{}, + ) + require.NoError(t, err) + require.NotNil(t, resp) +} diff --git a/test/azure-http-specs/azure/client-generator-core/coreusagegroup/testdata/_metadata.json b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_models.go b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_models.go new file mode 100644 index 000000000000..a4f918cef39d --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_models.go @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coreusagegroup + +// InputModel - Usage additive to roundtrip. +type InputModel struct { + // REQUIRED + Name *string +} + +type NamespaceModel struct { + // REQUIRED + Name *string +} + +type NestedNamespaceModel struct { + // REQUIRED + Value *string +} + +// OrphanModel - Not used anywhere, but access is override to public so still need to be generated and exported with serialization. +type OrphanModel struct { + // REQUIRED + Description *string + + // REQUIRED + ModelName *string +} + +// OutputModel - Usage additive to roundtrip. +type OutputModel struct { + // REQUIRED + Name *string +} + +type ResultModel struct { + // REQUIRED + Name *string +} + +type RoundTripModel struct { + // READ-ONLY + Result *ResultModel +} diff --git a/test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_models_serde.go b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_models_serde.go new file mode 100644 index 000000000000..c12d9f044f41 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_models_serde.go @@ -0,0 +1,225 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coreusagegroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type InputModel. +func (i InputModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", i.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InputModel. +func (i *InputModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &i.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NamespaceModel. +func (n NamespaceModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", n.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NamespaceModel. +func (n *NamespaceModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &n.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NestedNamespaceModel. +func (n NestedNamespaceModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", n.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NestedNamespaceModel. +func (n *NestedNamespaceModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &n.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OrphanModel. +func (o OrphanModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "desc", o.Description) + populate(objectMap, "name", o.ModelName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OrphanModel. +func (o *OrphanModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "desc": + err = unpopulate(val, "Description", &o.Description) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "ModelName", &o.ModelName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OutputModel. +func (o OutputModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", o.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OutputModel. +func (o *OutputModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResultModel. +func (r ResultModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", r.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResultModel. +func (r *ResultModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RoundTripModel. +func (r RoundTripModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "result", r.Result) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RoundTripModel. +func (r *RoundTripModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "result": + err = unpopulate(val, "Result", &r.Result) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_options.go b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_options.go new file mode 100644 index 000000000000..4a3c314db8a4 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_options.go @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coreusagegroup + +// UsageModelInOperationClientInputToInputOutputOptions contains the optional parameters for the UsageModelInOperationClient.InputToInputOutput +// method. +type UsageModelInOperationClientInputToInputOutputOptions struct { + // placeholder for future optional parameters +} + +// UsageModelInOperationClientModelInReadOnlyPropertyOptions contains the optional parameters for the UsageModelInOperationClient.ModelInReadOnlyProperty +// method. +type UsageModelInOperationClientModelInReadOnlyPropertyOptions struct { + // placeholder for future optional parameters +} + +// UsageModelInOperationClientOrphanModelSerializableOptions contains the optional parameters for the UsageModelInOperationClient.OrphanModelSerializable +// method. +type UsageModelInOperationClientOrphanModelSerializableOptions struct { + // placeholder for future optional parameters +} + +// UsageModelInOperationClientOutputToInputOutputOptions contains the optional parameters for the UsageModelInOperationClient.OutputToInputOutput +// method. +type UsageModelInOperationClientOutputToInputOutputOptions struct { + // placeholder for future optional parameters +} + +// UsageNamespaceUsageClientNamespaceModelSerializableOptions contains the optional parameters for the UsageNamespaceUsageClient.NamespaceModelSerializable +// method. +type UsageNamespaceUsageClientNamespaceModelSerializableOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_responses.go b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_responses.go new file mode 100644 index 000000000000..a20d3e21ef71 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_responses.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coreusagegroup + +// UsageModelInOperationClientInputToInputOutputResponse contains the response from method UsageModelInOperationClient.InputToInputOutput. +type UsageModelInOperationClientInputToInputOutputResponse struct { + // placeholder for future response values +} + +// UsageModelInOperationClientModelInReadOnlyPropertyResponse contains the response from method UsageModelInOperationClient.ModelInReadOnlyProperty. +type UsageModelInOperationClientModelInReadOnlyPropertyResponse struct { + RoundTripModel +} + +// UsageModelInOperationClientOrphanModelSerializableResponse contains the response from method UsageModelInOperationClient.OrphanModelSerializable. +type UsageModelInOperationClientOrphanModelSerializableResponse struct { + // placeholder for future response values +} + +// UsageModelInOperationClientOutputToInputOutputResponse contains the response from method UsageModelInOperationClient.OutputToInputOutput. +type UsageModelInOperationClientOutputToInputOutputResponse struct { + // Usage additive to roundtrip. + OutputModel +} + +// UsageNamespaceUsageClientNamespaceModelSerializableResponse contains the response from method UsageNamespaceUsageClient.NamespaceModelSerializable. +type UsageNamespaceUsageClientNamespaceModelSerializableResponse struct { + // placeholder for future response values +} diff --git a/test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_usage_client.go b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_usage_client.go new file mode 100644 index 000000000000..26abdcd08f5f --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_usage_client.go @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coreusagegroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// UsageClient - Test for internal decorator. +// Don't use this type directly, use NewUsageClientWithNoCredential() instead. +type UsageClient struct { + internal *azcore.Client + endpoint string +} + +// UsageClientOptions contains the optional values for creating a [UsageClient]. +type UsageClientOptions struct { + azcore.ClientOptions +} + +// NewUsageClientWithNoCredential creates a new instance of UsageClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewUsageClientWithNoCredential(endpoint string, options *UsageClientOptions) (*UsageClient, error) { + if options == nil { + options = &UsageClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &UsageClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewUsageModelInOperationClient creates a new instance of [UsageModelInOperationClient]. +func (client *UsageClient) NewUsageModelInOperationClient() *UsageModelInOperationClient { + return &UsageModelInOperationClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewUsageNamespaceUsageClient creates a new instance of [UsageNamespaceUsageClient]. +func (client *UsageClient) NewUsageNamespaceUsageClient() *UsageNamespaceUsageClient { + return &UsageNamespaceUsageClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_usagemodelinoperation_client.go b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_usagemodelinoperation_client.go new file mode 100644 index 000000000000..07c63d079062 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_usagemodelinoperation_client.go @@ -0,0 +1,224 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coreusagegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// UsageModelInOperationClient contains the methods for the UsageModelInOperation group. +// Don't use this type directly, use [UsageClient.NewUsageModelInOperationClient] instead. +type UsageModelInOperationClient struct { + internal *azcore.Client + endpoint string +} + +// InputToInputOutput - Expected body parameter: +// ```json +// { +// "name": "Madge" +// } +// ``` +// If the operation fails it returns an *azcore.ResponseError type. +// - options - UsageModelInOperationClientInputToInputOutputOptions contains the optional parameters for the UsageModelInOperationClient.InputToInputOutput +// method. +func (client *UsageModelInOperationClient) InputToInputOutput(ctx context.Context, body InputModel, options *UsageModelInOperationClientInputToInputOutputOptions) (UsageModelInOperationClientInputToInputOutputResponse, error) { + var err error + const operationName = "UsageModelInOperationClient.InputToInputOutput" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.inputToInputOutputCreateRequest(ctx, body, options) + if err != nil { + return UsageModelInOperationClientInputToInputOutputResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return UsageModelInOperationClientInputToInputOutputResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return UsageModelInOperationClientInputToInputOutputResponse{}, err + } + return UsageModelInOperationClientInputToInputOutputResponse{}, nil +} + +// inputToInputOutputCreateRequest creates the InputToInputOutput request. +func (client *UsageModelInOperationClient) inputToInputOutputCreateRequest(ctx context.Context, body InputModel, _ *UsageModelInOperationClientInputToInputOutputOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/usage/inputToInputOutput" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// ModelInReadOnlyProperty - "ResultModel" should be usage=output, as it is read-only and does not exist in request body. +// Expected body parameter: +// ```json +// { +// } +// ``` +// Expected response body: +// ```json +// { +// "result": { +// "name": "Madge" +// } +// } +// ``` +// If the operation fails it returns an *azcore.ResponseError type. +// - options - UsageModelInOperationClientModelInReadOnlyPropertyOptions contains the optional parameters for the UsageModelInOperationClient.ModelInReadOnlyProperty +// method. +func (client *UsageModelInOperationClient) ModelInReadOnlyProperty(ctx context.Context, body RoundTripModel, options *UsageModelInOperationClientModelInReadOnlyPropertyOptions) (UsageModelInOperationClientModelInReadOnlyPropertyResponse, error) { + var err error + const operationName = "UsageModelInOperationClient.ModelInReadOnlyProperty" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.modelInReadOnlyPropertyCreateRequest(ctx, body, options) + if err != nil { + return UsageModelInOperationClientModelInReadOnlyPropertyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return UsageModelInOperationClientModelInReadOnlyPropertyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return UsageModelInOperationClientModelInReadOnlyPropertyResponse{}, err + } + resp, err := client.modelInReadOnlyPropertyHandleResponse(httpResp) + return resp, err +} + +// modelInReadOnlyPropertyCreateRequest creates the ModelInReadOnlyProperty request. +func (client *UsageModelInOperationClient) modelInReadOnlyPropertyCreateRequest(ctx context.Context, body RoundTripModel, _ *UsageModelInOperationClientModelInReadOnlyPropertyOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/usage/modelInReadOnlyProperty" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// modelInReadOnlyPropertyHandleResponse handles the ModelInReadOnlyProperty response. +func (client *UsageModelInOperationClient) modelInReadOnlyPropertyHandleResponse(resp *http.Response) (UsageModelInOperationClientModelInReadOnlyPropertyResponse, error) { + result := UsageModelInOperationClientModelInReadOnlyPropertyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RoundTripModel); err != nil { + return UsageModelInOperationClientModelInReadOnlyPropertyResponse{}, err + } + return result, nil +} + +// OrphanModelSerializable - Serialize the 'OrphanModel' as request body. +// Expected body parameter: +// ```json +// { +// "name": "name", +// "desc": "desc" +// } +// ``` +// If the operation fails it returns an *azcore.ResponseError type. +// - options - UsageModelInOperationClientOrphanModelSerializableOptions contains the optional parameters for the UsageModelInOperationClient.OrphanModelSerializable +// method. +func (client *UsageModelInOperationClient) OrphanModelSerializable(ctx context.Context, body any, options *UsageModelInOperationClientOrphanModelSerializableOptions) (UsageModelInOperationClientOrphanModelSerializableResponse, error) { + var err error + const operationName = "UsageModelInOperationClient.OrphanModelSerializable" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.orphanModelSerializableCreateRequest(ctx, body, options) + if err != nil { + return UsageModelInOperationClientOrphanModelSerializableResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return UsageModelInOperationClientOrphanModelSerializableResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return UsageModelInOperationClientOrphanModelSerializableResponse{}, err + } + return UsageModelInOperationClientOrphanModelSerializableResponse{}, nil +} + +// orphanModelSerializableCreateRequest creates the OrphanModelSerializable request. +func (client *UsageModelInOperationClient) orphanModelSerializableCreateRequest(ctx context.Context, body any, _ *UsageModelInOperationClientOrphanModelSerializableOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/usage/orphanModelSerializable" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// OutputToInputOutput - Expected response body: +// ```json +// { +// "name": "Madge" +// } +// ``` +// If the operation fails it returns an *azcore.ResponseError type. +// - options - UsageModelInOperationClientOutputToInputOutputOptions contains the optional parameters for the UsageModelInOperationClient.OutputToInputOutput +// method. +func (client *UsageModelInOperationClient) OutputToInputOutput(ctx context.Context, options *UsageModelInOperationClientOutputToInputOutputOptions) (UsageModelInOperationClientOutputToInputOutputResponse, error) { + var err error + const operationName = "UsageModelInOperationClient.OutputToInputOutput" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.outputToInputOutputCreateRequest(ctx, options) + if err != nil { + return UsageModelInOperationClientOutputToInputOutputResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return UsageModelInOperationClientOutputToInputOutputResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return UsageModelInOperationClientOutputToInputOutputResponse{}, err + } + resp, err := client.outputToInputOutputHandleResponse(httpResp) + return resp, err +} + +// outputToInputOutputCreateRequest creates the OutputToInputOutput request. +func (client *UsageModelInOperationClient) outputToInputOutputCreateRequest(ctx context.Context, _ *UsageModelInOperationClientOutputToInputOutputOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/usage/outputToInputOutput" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// outputToInputOutputHandleResponse handles the OutputToInputOutput response. +func (client *UsageModelInOperationClient) outputToInputOutputHandleResponse(resp *http.Response) (UsageModelInOperationClientOutputToInputOutputResponse, error) { + result := UsageModelInOperationClientOutputToInputOutputResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OutputModel); err != nil { + return UsageModelInOperationClientOutputToInputOutputResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_usagenamespaceusage_client.go b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_usagenamespaceusage_client.go new file mode 100644 index 000000000000..63f4510c3b17 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_usagenamespaceusage_client.go @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coreusagegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// UsageNamespaceUsageClient contains the methods for the UsageNamespaceUsage group. +// Don't use this type directly, use [UsageClient.NewUsageNamespaceUsageClient] instead. +type UsageNamespaceUsageClient struct { + internal *azcore.Client + endpoint string +} + +// NamespaceModelSerializable - Serialize the 'NamespaceModel' as request body. +// Expected body parameter: +// ```json +// { +// "name": "test" +// } +// ``` +// If the operation fails it returns an *azcore.ResponseError type. +// - options - UsageNamespaceUsageClientNamespaceModelSerializableOptions contains the optional parameters for the UsageNamespaceUsageClient.NamespaceModelSerializable +// method. +func (client *UsageNamespaceUsageClient) NamespaceModelSerializable(ctx context.Context, body any, options *UsageNamespaceUsageClientNamespaceModelSerializableOptions) (UsageNamespaceUsageClientNamespaceModelSerializableResponse, error) { + var err error + const operationName = "UsageNamespaceUsageClient.NamespaceModelSerializable" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.namespaceModelSerializableCreateRequest(ctx, body, options) + if err != nil { + return UsageNamespaceUsageClientNamespaceModelSerializableResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return UsageNamespaceUsageClientNamespaceModelSerializableResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return UsageNamespaceUsageClientNamespaceModelSerializableResponse{}, err + } + return UsageNamespaceUsageClientNamespaceModelSerializableResponse{}, nil +} + +// namespaceModelSerializableCreateRequest creates the NamespaceModelSerializable request. +func (client *UsageNamespaceUsageClient) namespaceModelSerializableCreateRequest(ctx context.Context, body any, _ *UsageNamespaceUsageClientNamespaceModelSerializableOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/usage/namespaceModelSerializable" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_version.go b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_version.go new file mode 100644 index 000000000000..9e5eeb0fe0ac --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/coreusagegroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package coreusagegroup + +const ( + moduleName = "coreusagegroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/LICENSE.txt b/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/clientdefaultvalue_client_test.go b/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/clientdefaultvalue_client_test.go new file mode 100644 index 000000000000..163c5ba2d1aa --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/clientdefaultvalue_client_test.go @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package defaultvaluegroup_test + +import ( + "context" + "defaultvaluegroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestClientDefaultValueClient_GetHeaderParameter(t *testing.T) { + client, err := defaultvaluegroup.NewClientDefaultValueClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.GetHeaderParameter(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp) +} + +func TestClientDefaultValueClient_GetOperationParameter(t *testing.T) { + client, err := defaultvaluegroup.NewClientDefaultValueClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.GetOperationParameter(context.Background(), "test", nil) + require.NoError(t, err) + require.NotNil(t, resp) +} + +func TestClientDefaultValueClient_GetPathParameter(t *testing.T) { + client, err := defaultvaluegroup.NewClientDefaultValueClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.GetPathParameter(context.Background(), "segment2", nil) + require.NoError(t, err) + require.NotNil(t, resp) +} + +func TestClientDefaultValueClient_PutModelProperty(t *testing.T) { + t.Skip("https://github.com/Azure/typespec-azure/issues/4295") + client, err := defaultvaluegroup.NewClientDefaultValueClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.PutModelProperty(context.Background(), defaultvaluegroup.ModelWithDefaultValues{ + Name: to.Ptr("test"), + }, nil) + require.NoError(t, err) + require.Equal(t, defaultvaluegroup.ModelWithDefaultValues{ + Name: to.Ptr("test"), + Timeout: to.Ptr(int32(30)), + Tier: to.Ptr("standard"), + Retry: to.Ptr(true), + }, resp.ModelWithDefaultValues) +} diff --git a/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/fake/zz_clientdefaultvalue_server.go b/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/fake/zz_clientdefaultvalue_server.go new file mode 100644 index 000000000000..f0032a837dfa --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/fake/zz_clientdefaultvalue_server.go @@ -0,0 +1,232 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "defaultvaluegroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" + "strconv" +) + +// ClientDefaultValueServer is a fake server for instances of the defaultvaluegroup.ClientDefaultValueClient type. +type ClientDefaultValueServer struct { + // GetHeaderParameter is the fake for method ClientDefaultValueClient.GetHeaderParameter + // HTTP status codes to indicate success: http.StatusNoContent + GetHeaderParameter func(ctx context.Context, options *defaultvaluegroup.ClientDefaultValueClientGetHeaderParameterOptions) (resp azfake.Responder[defaultvaluegroup.ClientDefaultValueClientGetHeaderParameterResponse], errResp azfake.ErrorResponder) + + // GetOperationParameter is the fake for method ClientDefaultValueClient.GetOperationParameter + // HTTP status codes to indicate success: http.StatusNoContent + GetOperationParameter func(ctx context.Context, name string, options *defaultvaluegroup.ClientDefaultValueClientGetOperationParameterOptions) (resp azfake.Responder[defaultvaluegroup.ClientDefaultValueClientGetOperationParameterResponse], errResp azfake.ErrorResponder) + + // GetPathParameter is the fake for method ClientDefaultValueClient.GetPathParameter + // HTTP status codes to indicate success: http.StatusNoContent + GetPathParameter func(ctx context.Context, segment2 string, options *defaultvaluegroup.ClientDefaultValueClientGetPathParameterOptions) (resp azfake.Responder[defaultvaluegroup.ClientDefaultValueClientGetPathParameterResponse], errResp azfake.ErrorResponder) + + // PutModelProperty is the fake for method ClientDefaultValueClient.PutModelProperty + // HTTP status codes to indicate success: http.StatusOK + PutModelProperty func(ctx context.Context, body defaultvaluegroup.ModelWithDefaultValues, options *defaultvaluegroup.ClientDefaultValueClientPutModelPropertyOptions) (resp azfake.Responder[defaultvaluegroup.ClientDefaultValueClientPutModelPropertyResponse], errResp azfake.ErrorResponder) +} + +// NewClientDefaultValueServerTransport creates a new instance of ClientDefaultValueServerTransport with the provided implementation. +// The returned ClientDefaultValueServerTransport instance is connected to an instance of defaultvaluegroup.ClientDefaultValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewClientDefaultValueServerTransport(srv *ClientDefaultValueServer) *ClientDefaultValueServerTransport { + return &ClientDefaultValueServerTransport{srv: srv} +} + +// ClientDefaultValueServerTransport connects instances of defaultvaluegroup.ClientDefaultValueClient to instances of ClientDefaultValueServer. +// Don't use this type directly, use NewClientDefaultValueServerTransport instead. +type ClientDefaultValueServerTransport struct { + srv *ClientDefaultValueServer +} + +// Do implements the policy.Transporter interface for ClientDefaultValueServerTransport. +func (c *ClientDefaultValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *ClientDefaultValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if clientDefaultValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = clientDefaultValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ClientDefaultValueClient.GetHeaderParameter": + res.resp, res.err = c.dispatchGetHeaderParameter(req) + case "ClientDefaultValueClient.GetOperationParameter": + res.resp, res.err = c.dispatchGetOperationParameter(req) + case "ClientDefaultValueClient.GetPathParameter": + res.resp, res.err = c.dispatchGetPathParameter(req) + case "ClientDefaultValueClient.PutModelProperty": + res.resp, res.err = c.dispatchPutModelProperty(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *ClientDefaultValueServerTransport) dispatchGetHeaderParameter(req *http.Request) (*http.Response, error) { + if c.srv.GetHeaderParameter == nil { + return nil, &nonRetriableError{errors.New("fake for method GetHeaderParameter not implemented")} + } + acceptParam := getOptional(getHeaderValue(req.Header, "Accept")) + customHeaderParam := getOptional(getHeaderValue(req.Header, "x-custom-header")) + var options *defaultvaluegroup.ClientDefaultValueClientGetHeaderParameterOptions + if acceptParam != nil || customHeaderParam != nil { + options = &defaultvaluegroup.ClientDefaultValueClientGetHeaderParameterOptions{ + Accept: acceptParam, + CustomHeader: customHeaderParam, + } + } + respr, errRespr := c.srv.GetHeaderParameter(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *ClientDefaultValueServerTransport) dispatchGetOperationParameter(req *http.Request) (*http.Response, error) { + if c.srv.GetOperationParameter == nil { + return nil, &nonRetriableError{errors.New("fake for method GetOperationParameter not implemented")} + } + qp := req.URL.Query() + pageSizeParam, err := parseOptional(qp.Get("pageSize"), func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + formatParam := getOptional(qp.Get("format")) + var options *defaultvaluegroup.ClientDefaultValueClientGetOperationParameterOptions + if pageSizeParam != nil || formatParam != nil { + options = &defaultvaluegroup.ClientDefaultValueClientGetOperationParameterOptions{ + PageSize: pageSizeParam, + Format: formatParam, + } + } + respr, errRespr := c.srv.GetOperationParameter(req.Context(), qp.Get("name"), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *ClientDefaultValueServerTransport) dispatchGetPathParameter(req *http.Request) (*http.Response, error) { + if c.srv.GetPathParameter == nil { + return nil, &nonRetriableError{errors.New("fake for method GetPathParameter not implemented")} + } + const regexStr = `/azure/client-generator-core/client-default-value/path-parameter/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + segment1Unescaped, err := url.PathUnescape(matches[regex.SubexpIndex("segment1")]) + if err != nil { + return nil, err + } + segment1Param := getOptional(segment1Unescaped) + segment2Param, err := url.PathUnescape(matches[regex.SubexpIndex("segment2")]) + if err != nil { + return nil, err + } + var options *defaultvaluegroup.ClientDefaultValueClientGetPathParameterOptions + if segment1Param != nil { + options = &defaultvaluegroup.ClientDefaultValueClientGetPathParameterOptions{ + Segment1: segment1Param, + } + } + respr, errRespr := c.srv.GetPathParameter(req.Context(), segment2Param, options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *ClientDefaultValueServerTransport) dispatchPutModelProperty(req *http.Request) (*http.Response, error) { + if c.srv.PutModelProperty == nil { + return nil, &nonRetriableError{errors.New("fake for method PutModelProperty not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[defaultvaluegroup.ModelWithDefaultValues](req) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.PutModelProperty(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ModelWithDefaultValues, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ClientDefaultValueServerTransport +var clientDefaultValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/fake/zz_internal.go b/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/fake/zz_internal.go new file mode 100644 index 000000000000..ea412051f8be --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/fake/zz_internal.go @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "reflect" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getHeaderValue(h http.Header, k string) string { + v := h[k] + if len(v) == 0 { + return "" + } + return v[0] +} + +func getOptional[T any](v T) *T { + if reflect.ValueOf(v).IsZero() { + return nil + } + return &v +} + +func parseOptional[T any](v string, parse func(v string) (T, error)) (*T, error) { + if v == "" { + return nil, nil + } + t, err := parse(v) + if err != nil { + return nil, err + } + return &t, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/go.mod b/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/go.mod new file mode 100644 index 000000000000..7ee3192b7cb7 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/go.mod @@ -0,0 +1,17 @@ +module defaultvaluegroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/go.sum b/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/testdata/_metadata.json b/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/zz_clientdefaultvalue_client.go b/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/zz_clientdefaultvalue_client.go new file mode 100644 index 000000000000..b8403aa242a3 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/zz_clientdefaultvalue_client.go @@ -0,0 +1,234 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package defaultvaluegroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" +) + +// ClientDefaultValueClient - Test for `@clientDefaultValue` decorator. +// Don't use this type directly, use NewClientDefaultValueClientWithNoCredential() instead. +type ClientDefaultValueClient struct { + internal *azcore.Client + endpoint string +} + +// ClientDefaultValueClientOptions contains the optional values for creating a [ClientDefaultValueClient]. +type ClientDefaultValueClientOptions struct { + azcore.ClientOptions +} + +// NewClientDefaultValueClientWithNoCredential creates a new instance of ClientDefaultValueClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewClientDefaultValueClientWithNoCredential(endpoint string, options *ClientDefaultValueClientOptions) (*ClientDefaultValueClient, error) { + if options == nil { + options = &ClientDefaultValueClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &ClientDefaultValueClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// GetHeaderParameter - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientDefaultValueClientGetHeaderParameterOptions contains the optional parameters for the ClientDefaultValueClient.GetHeaderParameter +// method. +func (client *ClientDefaultValueClient) GetHeaderParameter(ctx context.Context, options *ClientDefaultValueClientGetHeaderParameterOptions) (ClientDefaultValueClientGetHeaderParameterResponse, error) { + var err error + const operationName = "ClientDefaultValueClient.GetHeaderParameter" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getHeaderParameterCreateRequest(ctx, options) + if err != nil { + return ClientDefaultValueClientGetHeaderParameterResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientDefaultValueClientGetHeaderParameterResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ClientDefaultValueClientGetHeaderParameterResponse{}, err + } + return ClientDefaultValueClientGetHeaderParameterResponse{}, nil +} + +// getHeaderParameterCreateRequest creates the GetHeaderParameter request. +func (client *ClientDefaultValueClient) getHeaderParameterCreateRequest(ctx context.Context, options *ClientDefaultValueClientGetHeaderParameterOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-default-value/header-parameter" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + acceptDefault := "application/json;odata.metadata=none" + if options != nil && options.Accept != nil { + acceptDefault = *options.Accept + } + req.Raw().Header["Accept"] = []string{acceptDefault} + customHeaderDefault := "default-value" + if options != nil && options.CustomHeader != nil { + customHeaderDefault = *options.CustomHeader + } + req.Raw().Header["x-custom-header"] = []string{customHeaderDefault} + return req, nil +} + +// GetOperationParameter - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientDefaultValueClientGetOperationParameterOptions contains the optional parameters for the ClientDefaultValueClient.GetOperationParameter +// method. +func (client *ClientDefaultValueClient) GetOperationParameter(ctx context.Context, name string, options *ClientDefaultValueClientGetOperationParameterOptions) (ClientDefaultValueClientGetOperationParameterResponse, error) { + var err error + const operationName = "ClientDefaultValueClient.GetOperationParameter" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getOperationParameterCreateRequest(ctx, name, options) + if err != nil { + return ClientDefaultValueClientGetOperationParameterResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientDefaultValueClientGetOperationParameterResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ClientDefaultValueClientGetOperationParameterResponse{}, err + } + return ClientDefaultValueClientGetOperationParameterResponse{}, nil +} + +// getOperationParameterCreateRequest creates the GetOperationParameter request. +func (client *ClientDefaultValueClient) getOperationParameterCreateRequest(ctx context.Context, name string, options *ClientDefaultValueClientGetOperationParameterOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-default-value/operation-parameter" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + formatDefault := "json" + if options != nil && options.Format != nil { + formatDefault = *options.Format + } + reqQP.Set("format", formatDefault) + reqQP.Set("name", name) + pageSizeDefault := int32(10) + if options != nil && options.PageSize != nil { + pageSizeDefault = *options.PageSize + } + reqQP.Set("pageSize", strconv.FormatInt(int64(pageSizeDefault), 10)) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// GetPathParameter - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientDefaultValueClientGetPathParameterOptions contains the optional parameters for the ClientDefaultValueClient.GetPathParameter +// method. +func (client *ClientDefaultValueClient) GetPathParameter(ctx context.Context, segment2 string, options *ClientDefaultValueClientGetPathParameterOptions) (ClientDefaultValueClientGetPathParameterResponse, error) { + var err error + const operationName = "ClientDefaultValueClient.GetPathParameter" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getPathParameterCreateRequest(ctx, segment2, options) + if err != nil { + return ClientDefaultValueClientGetPathParameterResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientDefaultValueClientGetPathParameterResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ClientDefaultValueClientGetPathParameterResponse{}, err + } + return ClientDefaultValueClientGetPathParameterResponse{}, nil +} + +// getPathParameterCreateRequest creates the GetPathParameter request. +func (client *ClientDefaultValueClient) getPathParameterCreateRequest(ctx context.Context, segment2 string, options *ClientDefaultValueClientGetPathParameterOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-default-value/path-parameter/{segment1}/{segment2}" + segment1Default := "default-segment1" + if options != nil && options.Segment1 != nil { + segment1Default = *options.Segment1 + } + urlPath = strings.ReplaceAll(urlPath, "{segment1}", url.PathEscape(segment1Default)) + if segment2 == "" { + return nil, errors.New("parameter segment2 cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{segment2}", url.PathEscape(segment2)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// PutModelProperty - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientDefaultValueClientPutModelPropertyOptions contains the optional parameters for the ClientDefaultValueClient.PutModelProperty +// method. +func (client *ClientDefaultValueClient) PutModelProperty(ctx context.Context, body ModelWithDefaultValues, options *ClientDefaultValueClientPutModelPropertyOptions) (ClientDefaultValueClientPutModelPropertyResponse, error) { + var err error + const operationName = "ClientDefaultValueClient.PutModelProperty" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putModelPropertyCreateRequest(ctx, body, options) + if err != nil { + return ClientDefaultValueClientPutModelPropertyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientDefaultValueClientPutModelPropertyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientDefaultValueClientPutModelPropertyResponse{}, err + } + resp, err := client.putModelPropertyHandleResponse(httpResp) + return resp, err +} + +// putModelPropertyCreateRequest creates the PutModelProperty request. +func (client *ClientDefaultValueClient) putModelPropertyCreateRequest(ctx context.Context, body ModelWithDefaultValues, _ *ClientDefaultValueClientPutModelPropertyOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/client-default-value/model-property" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// putModelPropertyHandleResponse handles the PutModelProperty response. +func (client *ClientDefaultValueClient) putModelPropertyHandleResponse(resp *http.Response) (ClientDefaultValueClientPutModelPropertyResponse, error) { + result := ClientDefaultValueClientPutModelPropertyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ModelWithDefaultValues); err != nil { + return ClientDefaultValueClientPutModelPropertyResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/zz_models.go b/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/zz_models.go new file mode 100644 index 000000000000..4e243045567b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/zz_models.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package defaultvaluegroup + +// ModelWithDefaultValues - Model with client default values on properties. +type ModelWithDefaultValues struct { + // REQUIRED; Name property with no default value. + Name *string + + // Retry property with client default value of true. + Retry *bool + + // Tier property with client default value of 'standard'. + Tier *string + + // Timeout property with client default value of 30. + Timeout *int32 +} diff --git a/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/zz_models_serde.go b/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/zz_models_serde.go new file mode 100644 index 000000000000..65aaf533d815 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/zz_models_serde.go @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package defaultvaluegroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type ModelWithDefaultValues. +func (m ModelWithDefaultValues) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", m.Name) + if m.Retry == nil { + m.Retry = to.Ptr(true) + } + populate(objectMap, "retry", m.Retry) + if m.Tier == nil { + m.Tier = to.Ptr("standard") + } + populate(objectMap, "tier", m.Tier) + if m.Timeout == nil { + m.Timeout = to.Ptr(int32(30)) + } + populate(objectMap, "timeout", m.Timeout) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ModelWithDefaultValues. +func (m *ModelWithDefaultValues) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &m.Name) + delete(rawMsg, key) + case "retry": + err = unpopulate(val, "Retry", &m.Retry) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &m.Tier) + delete(rawMsg, key) + case "timeout": + err = unpopulate(val, "Timeout", &m.Timeout) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/zz_options.go b/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/zz_options.go new file mode 100644 index 000000000000..7adbc20092ea --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/zz_options.go @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package defaultvaluegroup + +// ClientDefaultValueClientGetHeaderParameterOptions contains the optional parameters for the ClientDefaultValueClient.GetHeaderParameter +// method. +type ClientDefaultValueClientGetHeaderParameterOptions struct { + // The default value is "application/json;odata.metadata=none". + Accept *string + + // The default value is "default-value". + CustomHeader *string +} + +// ClientDefaultValueClientGetOperationParameterOptions contains the optional parameters for the ClientDefaultValueClient.GetOperationParameter +// method. +type ClientDefaultValueClientGetOperationParameterOptions struct { + // The default value is "json". + Format *string + + // The default value is 10. + PageSize *int32 +} + +// ClientDefaultValueClientGetPathParameterOptions contains the optional parameters for the ClientDefaultValueClient.GetPathParameter +// method. +type ClientDefaultValueClientGetPathParameterOptions struct { + // The default value is "default-segment1". + Segment1 *string +} + +// ClientDefaultValueClientPutModelPropertyOptions contains the optional parameters for the ClientDefaultValueClient.PutModelProperty +// method. +type ClientDefaultValueClientPutModelPropertyOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/zz_responses.go b/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/zz_responses.go new file mode 100644 index 000000000000..d0cd01b75aa3 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/zz_responses.go @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package defaultvaluegroup + +// ClientDefaultValueClientGetHeaderParameterResponse contains the response from method ClientDefaultValueClient.GetHeaderParameter. +type ClientDefaultValueClientGetHeaderParameterResponse struct { + // placeholder for future response values +} + +// ClientDefaultValueClientGetOperationParameterResponse contains the response from method ClientDefaultValueClient.GetOperationParameter. +type ClientDefaultValueClientGetOperationParameterResponse struct { + // placeholder for future response values +} + +// ClientDefaultValueClientGetPathParameterResponse contains the response from method ClientDefaultValueClient.GetPathParameter. +type ClientDefaultValueClientGetPathParameterResponse struct { + // placeholder for future response values +} + +// ClientDefaultValueClientPutModelPropertyResponse contains the response from method ClientDefaultValueClient.PutModelProperty. +type ClientDefaultValueClientPutModelPropertyResponse struct { + // Model with client default values on properties. + ModelWithDefaultValues +} diff --git a/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/zz_version.go b/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/zz_version.go new file mode 100644 index 000000000000..3496e4d19212 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/defaultvaluegroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package defaultvaluegroup + +const ( + moduleName = "defaultvaluegroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/client-generator-core/emptystringgroup/LICENSE.txt b/test/azure-http-specs/azure/client-generator-core/emptystringgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/emptystringgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/client-generator-core/emptystringgroup/deserializeemptystringasnull_client_test.go b/test/azure-http-specs/azure/client-generator-core/emptystringgroup/deserializeemptystringasnull_client_test.go new file mode 100644 index 000000000000..25e17d5a9dfd --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/emptystringgroup/deserializeemptystringasnull_client_test.go @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package emptystringgroup + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestDeserializeEmptyStringAsNullClient_Get(t *testing.T) { + client, err := NewDeserializeEmptyStringAsNullClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.Get(context.Background(), nil) + require.NoError(t, err) + require.Nil(t, resp.SampleURL) +} diff --git a/test/azure-http-specs/azure/client-generator-core/emptystringgroup/fake/zz_deserializeemptystringasnull_server.go b/test/azure-http-specs/azure/client-generator-core/emptystringgroup/fake/zz_deserializeemptystringasnull_server.go new file mode 100644 index 000000000000..c22783553b02 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/emptystringgroup/fake/zz_deserializeemptystringasnull_server.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "emptystringgroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// DeserializeEmptyStringAsNullServer is a fake server for instances of the emptystringgroup.DeserializeEmptyStringAsNullClient type. +type DeserializeEmptyStringAsNullServer struct { + // Get is the fake for method DeserializeEmptyStringAsNullClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *emptystringgroup.DeserializeEmptyStringAsNullClientGetOptions) (resp azfake.Responder[emptystringgroup.DeserializeEmptyStringAsNullClientGetResponse], errResp azfake.ErrorResponder) +} + +// NewDeserializeEmptyStringAsNullServerTransport creates a new instance of DeserializeEmptyStringAsNullServerTransport with the provided implementation. +// The returned DeserializeEmptyStringAsNullServerTransport instance is connected to an instance of emptystringgroup.DeserializeEmptyStringAsNullClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDeserializeEmptyStringAsNullServerTransport(srv *DeserializeEmptyStringAsNullServer) *DeserializeEmptyStringAsNullServerTransport { + return &DeserializeEmptyStringAsNullServerTransport{srv: srv} +} + +// DeserializeEmptyStringAsNullServerTransport connects instances of emptystringgroup.DeserializeEmptyStringAsNullClient to instances of DeserializeEmptyStringAsNullServer. +// Don't use this type directly, use NewDeserializeEmptyStringAsNullServerTransport instead. +type DeserializeEmptyStringAsNullServerTransport struct { + srv *DeserializeEmptyStringAsNullServer +} + +// Do implements the policy.Transporter interface for DeserializeEmptyStringAsNullServerTransport. +func (d *DeserializeEmptyStringAsNullServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DeserializeEmptyStringAsNullServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if deserializeEmptyStringAsNullServerTransportInterceptor != nil { + res.resp, res.err, intercepted = deserializeEmptyStringAsNullServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DeserializeEmptyStringAsNullClient.Get": + res.resp, res.err = d.dispatchGet(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DeserializeEmptyStringAsNullServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := d.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ResponseModel, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DeserializeEmptyStringAsNullServerTransport +var deserializeEmptyStringAsNullServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/emptystringgroup/fake/zz_internal.go b/test/azure-http-specs/azure/client-generator-core/emptystringgroup/fake/zz_internal.go new file mode 100644 index 000000000000..705f81eacafe --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/emptystringgroup/fake/zz_internal.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import "net/http" + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} diff --git a/test/azure-http-specs/azure/client-generator-core/emptystringgroup/go.mod b/test/azure-http-specs/azure/client-generator-core/emptystringgroup/go.mod new file mode 100644 index 000000000000..35151c2f8493 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/emptystringgroup/go.mod @@ -0,0 +1,17 @@ +module emptystringgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/client-generator-core/emptystringgroup/go.sum b/test/azure-http-specs/azure/client-generator-core/emptystringgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/emptystringgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/client-generator-core/emptystringgroup/testdata/_metadata.json b/test/azure-http-specs/azure/client-generator-core/emptystringgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/emptystringgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/client-generator-core/emptystringgroup/zz_deserializeemptystringasnull_client.go b/test/azure-http-specs/azure/client-generator-core/emptystringgroup/zz_deserializeemptystringasnull_client.go new file mode 100644 index 000000000000..7135ab202c0f --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/emptystringgroup/zz_deserializeemptystringasnull_client.go @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package emptystringgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// DeserializeEmptyStringAsNullClient - Test decorator @deserializeEmptyStringAsNull. +// Don't use this type directly, use NewDeserializeEmptyStringAsNullClientWithNoCredential() instead. +type DeserializeEmptyStringAsNullClient struct { + internal *azcore.Client + endpoint string +} + +// DeserializeEmptyStringAsNullClientOptions contains the optional values for creating a [DeserializeEmptyStringAsNullClient]. +type DeserializeEmptyStringAsNullClientOptions struct { + azcore.ClientOptions +} + +// NewDeserializeEmptyStringAsNullClientWithNoCredential creates a new instance of DeserializeEmptyStringAsNullClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewDeserializeEmptyStringAsNullClientWithNoCredential(endpoint string, options *DeserializeEmptyStringAsNullClientOptions) (*DeserializeEmptyStringAsNullClient, error) { + if options == nil { + options = &DeserializeEmptyStringAsNullClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &DeserializeEmptyStringAsNullClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DeserializeEmptyStringAsNullClientGetOptions contains the optional parameters for the DeserializeEmptyStringAsNullClient.Get +// method. +func (client *DeserializeEmptyStringAsNullClient) Get(ctx context.Context, options *DeserializeEmptyStringAsNullClientGetOptions) (DeserializeEmptyStringAsNullClientGetResponse, error) { + var err error + const operationName = "DeserializeEmptyStringAsNullClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return DeserializeEmptyStringAsNullClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DeserializeEmptyStringAsNullClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DeserializeEmptyStringAsNullClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DeserializeEmptyStringAsNullClient) getCreateRequest(ctx context.Context, _ *DeserializeEmptyStringAsNullClientGetOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/deserialize-empty-string-as-null/responseModel" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DeserializeEmptyStringAsNullClient) getHandleResponse(resp *http.Response) (DeserializeEmptyStringAsNullClientGetResponse, error) { + result := DeserializeEmptyStringAsNullClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ResponseModel); err != nil { + return DeserializeEmptyStringAsNullClientGetResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/emptystringgroup/zz_models.go b/test/azure-http-specs/azure/client-generator-core/emptystringgroup/zz_models.go new file mode 100644 index 000000000000..9d7beb105311 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/emptystringgroup/zz_models.go @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package emptystringgroup + +// ResponseModel - This is a Model contains a string-like property of type url. +type ResponseModel struct { + // REQUIRED + SampleURL *string +} diff --git a/test/azure-http-specs/azure/client-generator-core/emptystringgroup/zz_models_serde.go b/test/azure-http-specs/azure/client-generator-core/emptystringgroup/zz_models_serde.go new file mode 100644 index 000000000000..8f4e7a0dd084 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/emptystringgroup/zz_models_serde.go @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package emptystringgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type ResponseModel. +func (r ResponseModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "sampleUrl", r.SampleURL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResponseModel. +func (r *ResponseModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "sampleUrl": + if string(val) != `""` { + err = unpopulate(val, "SampleURL", &r.SampleURL) + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/emptystringgroup/zz_options.go b/test/azure-http-specs/azure/client-generator-core/emptystringgroup/zz_options.go new file mode 100644 index 000000000000..3929b565f102 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/emptystringgroup/zz_options.go @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package emptystringgroup + +// DeserializeEmptyStringAsNullClientGetOptions contains the optional parameters for the DeserializeEmptyStringAsNullClient.Get +// method. +type DeserializeEmptyStringAsNullClientGetOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/azure/client-generator-core/emptystringgroup/zz_responses.go b/test/azure-http-specs/azure/client-generator-core/emptystringgroup/zz_responses.go new file mode 100644 index 000000000000..2d1e9de5238e --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/emptystringgroup/zz_responses.go @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package emptystringgroup + +// DeserializeEmptyStringAsNullClientGetResponse contains the response from method DeserializeEmptyStringAsNullClient.Get. +type DeserializeEmptyStringAsNullClientGetResponse struct { + // This is a Model contains a string-like property of type url. + ResponseModel +} diff --git a/test/azure-http-specs/azure/client-generator-core/emptystringgroup/zz_version.go b/test/azure-http-specs/azure/client-generator-core/emptystringgroup/zz_version.go new file mode 100644 index 000000000000..92bab391015c --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/emptystringgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package emptystringgroup + +const ( + moduleName = "emptystringgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/client-generator-core/flattengroup/LICENSE.txt b/test/azure-http-specs/azure/client-generator-core/flattengroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/flattengroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/client-generator-core/flattengroup/fake/zz_flattenproperty_server.go b/test/azure-http-specs/azure/client-generator-core/flattengroup/fake/zz_flattenproperty_server.go new file mode 100644 index 000000000000..d8ae335a920e --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/flattengroup/fake/zz_flattenproperty_server.go @@ -0,0 +1,192 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "flattengroup" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// FlattenPropertyServer is a fake server for instances of the flattengroup.FlattenPropertyClient type. +type FlattenPropertyServer struct { + // PutFlattenModel is the fake for method FlattenPropertyClient.PutFlattenModel + // HTTP status codes to indicate success: http.StatusOK + PutFlattenModel func(ctx context.Context, input flattengroup.FlattenModel, options *flattengroup.FlattenPropertyClientPutFlattenModelOptions) (resp azfake.Responder[flattengroup.FlattenPropertyClientPutFlattenModelResponse], errResp azfake.ErrorResponder) + + // PutFlattenReadOnlyModel is the fake for method FlattenPropertyClient.PutFlattenReadOnlyModel + // HTTP status codes to indicate success: http.StatusOK + PutFlattenReadOnlyModel func(ctx context.Context, body flattengroup.Solution, options *flattengroup.FlattenPropertyClientPutFlattenReadOnlyModelOptions) (resp azfake.Responder[flattengroup.FlattenPropertyClientPutFlattenReadOnlyModelResponse], errResp azfake.ErrorResponder) + + // PutFlattenUnknownModel is the fake for method FlattenPropertyClient.PutFlattenUnknownModel + // HTTP status codes to indicate success: http.StatusOK + PutFlattenUnknownModel func(ctx context.Context, input flattengroup.FlattenUnknownModel, options *flattengroup.FlattenPropertyClientPutFlattenUnknownModelOptions) (resp azfake.Responder[flattengroup.FlattenPropertyClientPutFlattenUnknownModelResponse], errResp azfake.ErrorResponder) + + // PutNestedFlattenModel is the fake for method FlattenPropertyClient.PutNestedFlattenModel + // HTTP status codes to indicate success: http.StatusOK + PutNestedFlattenModel func(ctx context.Context, input flattengroup.NestedFlattenModel, options *flattengroup.FlattenPropertyClientPutNestedFlattenModelOptions) (resp azfake.Responder[flattengroup.FlattenPropertyClientPutNestedFlattenModelResponse], errResp azfake.ErrorResponder) +} + +// NewFlattenPropertyServerTransport creates a new instance of FlattenPropertyServerTransport with the provided implementation. +// The returned FlattenPropertyServerTransport instance is connected to an instance of flattengroup.FlattenPropertyClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewFlattenPropertyServerTransport(srv *FlattenPropertyServer) *FlattenPropertyServerTransport { + return &FlattenPropertyServerTransport{srv: srv} +} + +// FlattenPropertyServerTransport connects instances of flattengroup.FlattenPropertyClient to instances of FlattenPropertyServer. +// Don't use this type directly, use NewFlattenPropertyServerTransport instead. +type FlattenPropertyServerTransport struct { + srv *FlattenPropertyServer +} + +// Do implements the policy.Transporter interface for FlattenPropertyServerTransport. +func (f *FlattenPropertyServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return f.dispatchToMethodFake(req, method) +} + +func (f *FlattenPropertyServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if flattenPropertyServerTransportInterceptor != nil { + res.resp, res.err, intercepted = flattenPropertyServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "FlattenPropertyClient.PutFlattenModel": + res.resp, res.err = f.dispatchPutFlattenModel(req) + case "FlattenPropertyClient.PutFlattenReadOnlyModel": + res.resp, res.err = f.dispatchPutFlattenReadOnlyModel(req) + case "FlattenPropertyClient.PutFlattenUnknownModel": + res.resp, res.err = f.dispatchPutFlattenUnknownModel(req) + case "FlattenPropertyClient.PutNestedFlattenModel": + res.resp, res.err = f.dispatchPutNestedFlattenModel(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (f *FlattenPropertyServerTransport) dispatchPutFlattenModel(req *http.Request) (*http.Response, error) { + if f.srv.PutFlattenModel == nil { + return nil, &nonRetriableError{errors.New("fake for method PutFlattenModel not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[flattengroup.FlattenModel](req) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.PutFlattenModel(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).FlattenModel, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (f *FlattenPropertyServerTransport) dispatchPutFlattenReadOnlyModel(req *http.Request) (*http.Response, error) { + if f.srv.PutFlattenReadOnlyModel == nil { + return nil, &nonRetriableError{errors.New("fake for method PutFlattenReadOnlyModel not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[flattengroup.Solution](req) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.PutFlattenReadOnlyModel(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Solution, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (f *FlattenPropertyServerTransport) dispatchPutFlattenUnknownModel(req *http.Request) (*http.Response, error) { + if f.srv.PutFlattenUnknownModel == nil { + return nil, &nonRetriableError{errors.New("fake for method PutFlattenUnknownModel not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[flattengroup.FlattenUnknownModel](req) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.PutFlattenUnknownModel(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).FlattenUnknownModel, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (f *FlattenPropertyServerTransport) dispatchPutNestedFlattenModel(req *http.Request) (*http.Response, error) { + if f.srv.PutNestedFlattenModel == nil { + return nil, &nonRetriableError{errors.New("fake for method PutNestedFlattenModel not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[flattengroup.NestedFlattenModel](req) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.PutNestedFlattenModel(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).NestedFlattenModel, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to FlattenPropertyServerTransport +var flattenPropertyServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/flattengroup/fake/zz_internal.go b/test/azure-http-specs/azure/client-generator-core/flattengroup/fake/zz_internal.go new file mode 100644 index 000000000000..705f81eacafe --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/flattengroup/fake/zz_internal.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import "net/http" + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} diff --git a/test/azure-http-specs/azure/client-generator-core/flattengroup/flattenproperty_client_test.go b/test/azure-http-specs/azure/client-generator-core/flattengroup/flattenproperty_client_test.go new file mode 100644 index 000000000000..a9fd2d96efed --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/flattengroup/flattenproperty_client_test.go @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package flattengroup_test + +import ( + "context" + "flattengroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestFlattenPropertyClient_PutFlattenModel(t *testing.T) { + client, err := flattengroup.NewFlattenPropertyClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.PutFlattenModel(context.Background(), flattengroup.FlattenModel{ + Name: to.Ptr("foo"), + Properties: &flattengroup.ChildModel{ + Description: to.Ptr("bar"), + Age: to.Ptr[int32](10), + }, + }, nil) + require.NoError(t, err) + require.Equal(t, flattengroup.FlattenModel{ + Name: to.Ptr("test"), + Properties: &flattengroup.ChildModel{ + Description: to.Ptr("test"), + Age: to.Ptr[int32](1), + }, + }, resp.FlattenModel) +} + +func TestFlattenPropertyClient_PutNestedFlattenModel(t *testing.T) { + client, err := flattengroup.NewFlattenPropertyClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.PutNestedFlattenModel(context.Background(), flattengroup.NestedFlattenModel{ + Name: to.Ptr("foo"), + Properties: &flattengroup.ChildFlattenModel{ + Summary: to.Ptr("bar"), + Properties: &flattengroup.ChildModel{ + Description: to.Ptr("test"), + Age: to.Ptr[int32](10), + }, + }, + }, nil) + require.NoError(t, err) + require.Equal(t, flattengroup.NestedFlattenModel{ + Name: to.Ptr("test"), + Properties: &flattengroup.ChildFlattenModel{ + Summary: to.Ptr("test"), + Properties: &flattengroup.ChildModel{ + Description: to.Ptr("foo"), + Age: to.Ptr[int32](1), + }, + }, + }, resp.NestedFlattenModel) +} + +func TestFlattenPropertyClient_PutFlattenUnknownModel(t *testing.T) { + client, err := flattengroup.NewFlattenPropertyClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.PutFlattenUnknownModel(context.Background(), flattengroup.FlattenUnknownModel{ + Name: to.Ptr("foo"), + }, nil) + require.NoError(t, err) + require.Equal(t, to.Ptr("test"), resp.Name) + props, ok := resp.Properties.(map[string]any) + require.True(t, ok) + require.Equal(t, "value1", props["key1"]) + require.Equal(t, "value2", props["key2"]) +} + +func TestFlattenPropertyClient_PutFlattenReadOnlyModel(t *testing.T) { + client, err := flattengroup.NewFlattenPropertyClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.PutFlattenReadOnlyModel(context.Background(), flattengroup.Solution{ + Name: to.Ptr("foo"), + }, nil) + require.NoError(t, err) + require.Equal(t, to.Ptr("foo"), resp.Name) + require.NotNil(t, resp.Properties) + require.Equal(t, to.Ptr("solution1"), resp.Properties.SolutionID) + require.Equal(t, to.Ptr("Solution Title"), resp.Properties.Title) + require.Equal(t, to.Ptr("Solution Content"), resp.Properties.Content) +} diff --git a/test/azure-http-specs/azure/client-generator-core/flattengroup/go.mod b/test/azure-http-specs/azure/client-generator-core/flattengroup/go.mod new file mode 100644 index 000000000000..a8cd02121195 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/flattengroup/go.mod @@ -0,0 +1,17 @@ +module flattengroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/client-generator-core/flattengroup/go.sum b/test/azure-http-specs/azure/client-generator-core/flattengroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/flattengroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/client-generator-core/flattengroup/testdata/_metadata.json b/test/azure-http-specs/azure/client-generator-core/flattengroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/flattengroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/client-generator-core/flattengroup/zz_flattenproperty_client.go b/test/azure-http-specs/azure/client-generator-core/flattengroup/zz_flattenproperty_client.go new file mode 100644 index 000000000000..573c99bed5f9 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/flattengroup/zz_flattenproperty_client.go @@ -0,0 +1,243 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package flattengroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// FlattenPropertyClient - Illustrates the model flatten cases. +// Don't use this type directly, use NewFlattenPropertyClientWithNoCredential() instead. +type FlattenPropertyClient struct { + internal *azcore.Client + endpoint string +} + +// FlattenPropertyClientOptions contains the optional values for creating a [FlattenPropertyClient]. +type FlattenPropertyClientOptions struct { + azcore.ClientOptions +} + +// NewFlattenPropertyClientWithNoCredential creates a new instance of FlattenPropertyClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewFlattenPropertyClientWithNoCredential(endpoint string, options *FlattenPropertyClientOptions) (*FlattenPropertyClient, error) { + if options == nil { + options = &FlattenPropertyClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &FlattenPropertyClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// PutFlattenModel - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - FlattenPropertyClientPutFlattenModelOptions contains the optional parameters for the FlattenPropertyClient.PutFlattenModel +// method. +func (client *FlattenPropertyClient) PutFlattenModel(ctx context.Context, input FlattenModel, options *FlattenPropertyClientPutFlattenModelOptions) (FlattenPropertyClientPutFlattenModelResponse, error) { + var err error + const operationName = "FlattenPropertyClient.PutFlattenModel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putFlattenModelCreateRequest(ctx, input, options) + if err != nil { + return FlattenPropertyClientPutFlattenModelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FlattenPropertyClientPutFlattenModelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FlattenPropertyClientPutFlattenModelResponse{}, err + } + resp, err := client.putFlattenModelHandleResponse(httpResp) + return resp, err +} + +// putFlattenModelCreateRequest creates the PutFlattenModel request. +func (client *FlattenPropertyClient) putFlattenModelCreateRequest(ctx context.Context, input FlattenModel, _ *FlattenPropertyClientPutFlattenModelOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/flatten-property/flattenModel" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, input); err != nil { + return nil, err + } + return req, nil +} + +// putFlattenModelHandleResponse handles the PutFlattenModel response. +func (client *FlattenPropertyClient) putFlattenModelHandleResponse(resp *http.Response) (FlattenPropertyClientPutFlattenModelResponse, error) { + result := FlattenPropertyClientPutFlattenModelResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FlattenModel); err != nil { + return FlattenPropertyClientPutFlattenModelResponse{}, err + } + return result, nil +} + +// PutFlattenReadOnlyModel - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - FlattenPropertyClientPutFlattenReadOnlyModelOptions contains the optional parameters for the FlattenPropertyClient.PutFlattenReadOnlyModel +// method. +func (client *FlattenPropertyClient) PutFlattenReadOnlyModel(ctx context.Context, body Solution, options *FlattenPropertyClientPutFlattenReadOnlyModelOptions) (FlattenPropertyClientPutFlattenReadOnlyModelResponse, error) { + var err error + const operationName = "FlattenPropertyClient.PutFlattenReadOnlyModel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putFlattenReadOnlyModelCreateRequest(ctx, body, options) + if err != nil { + return FlattenPropertyClientPutFlattenReadOnlyModelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FlattenPropertyClientPutFlattenReadOnlyModelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FlattenPropertyClientPutFlattenReadOnlyModelResponse{}, err + } + resp, err := client.putFlattenReadOnlyModelHandleResponse(httpResp) + return resp, err +} + +// putFlattenReadOnlyModelCreateRequest creates the PutFlattenReadOnlyModel request. +func (client *FlattenPropertyClient) putFlattenReadOnlyModelCreateRequest(ctx context.Context, body Solution, _ *FlattenPropertyClientPutFlattenReadOnlyModelOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/flatten-property/flattenReadOnlyModel" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// putFlattenReadOnlyModelHandleResponse handles the PutFlattenReadOnlyModel response. +func (client *FlattenPropertyClient) putFlattenReadOnlyModelHandleResponse(resp *http.Response) (FlattenPropertyClientPutFlattenReadOnlyModelResponse, error) { + result := FlattenPropertyClientPutFlattenReadOnlyModelResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Solution); err != nil { + return FlattenPropertyClientPutFlattenReadOnlyModelResponse{}, err + } + return result, nil +} + +// PutFlattenUnknownModel - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - FlattenPropertyClientPutFlattenUnknownModelOptions contains the optional parameters for the FlattenPropertyClient.PutFlattenUnknownModel +// method. +func (client *FlattenPropertyClient) PutFlattenUnknownModel(ctx context.Context, input FlattenUnknownModel, options *FlattenPropertyClientPutFlattenUnknownModelOptions) (FlattenPropertyClientPutFlattenUnknownModelResponse, error) { + var err error + const operationName = "FlattenPropertyClient.PutFlattenUnknownModel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putFlattenUnknownModelCreateRequest(ctx, input, options) + if err != nil { + return FlattenPropertyClientPutFlattenUnknownModelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FlattenPropertyClientPutFlattenUnknownModelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FlattenPropertyClientPutFlattenUnknownModelResponse{}, err + } + resp, err := client.putFlattenUnknownModelHandleResponse(httpResp) + return resp, err +} + +// putFlattenUnknownModelCreateRequest creates the PutFlattenUnknownModel request. +func (client *FlattenPropertyClient) putFlattenUnknownModelCreateRequest(ctx context.Context, input FlattenUnknownModel, _ *FlattenPropertyClientPutFlattenUnknownModelOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/flatten-property/flattenUnknownModel" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, input); err != nil { + return nil, err + } + return req, nil +} + +// putFlattenUnknownModelHandleResponse handles the PutFlattenUnknownModel response. +func (client *FlattenPropertyClient) putFlattenUnknownModelHandleResponse(resp *http.Response) (FlattenPropertyClientPutFlattenUnknownModelResponse, error) { + result := FlattenPropertyClientPutFlattenUnknownModelResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FlattenUnknownModel); err != nil { + return FlattenPropertyClientPutFlattenUnknownModelResponse{}, err + } + return result, nil +} + +// PutNestedFlattenModel - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - FlattenPropertyClientPutNestedFlattenModelOptions contains the optional parameters for the FlattenPropertyClient.PutNestedFlattenModel +// method. +func (client *FlattenPropertyClient) PutNestedFlattenModel(ctx context.Context, input NestedFlattenModel, options *FlattenPropertyClientPutNestedFlattenModelOptions) (FlattenPropertyClientPutNestedFlattenModelResponse, error) { + var err error + const operationName = "FlattenPropertyClient.PutNestedFlattenModel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putNestedFlattenModelCreateRequest(ctx, input, options) + if err != nil { + return FlattenPropertyClientPutNestedFlattenModelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FlattenPropertyClientPutNestedFlattenModelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FlattenPropertyClientPutNestedFlattenModelResponse{}, err + } + resp, err := client.putNestedFlattenModelHandleResponse(httpResp) + return resp, err +} + +// putNestedFlattenModelCreateRequest creates the PutNestedFlattenModel request. +func (client *FlattenPropertyClient) putNestedFlattenModelCreateRequest(ctx context.Context, input NestedFlattenModel, _ *FlattenPropertyClientPutNestedFlattenModelOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/flatten-property/nestedFlattenModel" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, input); err != nil { + return nil, err + } + return req, nil +} + +// putNestedFlattenModelHandleResponse handles the PutNestedFlattenModel response. +func (client *FlattenPropertyClient) putNestedFlattenModelHandleResponse(resp *http.Response) (FlattenPropertyClientPutNestedFlattenModelResponse, error) { + result := FlattenPropertyClientPutNestedFlattenModelResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.NestedFlattenModel); err != nil { + return FlattenPropertyClientPutNestedFlattenModelResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/flattengroup/zz_models.go b/test/azure-http-specs/azure/client-generator-core/flattengroup/zz_models.go new file mode 100644 index 000000000000..3e93c081f397 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/flattengroup/zz_models.go @@ -0,0 +1,67 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package flattengroup + +// ChildFlattenModel - This is the child model to be flattened. And it has flattened property as well. +type ChildFlattenModel struct { + // REQUIRED + Properties *ChildModel + + // REQUIRED + Summary *string +} + +// ChildModel - This is the child model to be flattened. +type ChildModel struct { + // REQUIRED + Age *int32 + + // REQUIRED + Description *string +} + +// FlattenModel - This is the model with one level of flattening. +type FlattenModel struct { + // REQUIRED + Name *string + + // REQUIRED + Properties *ChildModel +} + +// FlattenUnknownModel - This is the model with unknown type properties to be flattened. +type FlattenUnknownModel struct { + // REQUIRED + Name *string + Properties any +} + +// NestedFlattenModel - This is the model with two levels of flattening. +type NestedFlattenModel struct { + // REQUIRED + Name *string + + // REQUIRED + Properties *ChildFlattenModel +} + +// Solution - This is the model with flattened properties that are all read-only. +type Solution struct { + // REQUIRED + Name *string + Properties *SolutionProperties +} + +// SolutionProperties - This is the model with all read-only properties to be flattened. +type SolutionProperties struct { + // READ-ONLY + Content *string + + // READ-ONLY + SolutionID *string + + // READ-ONLY + Title *string +} diff --git a/test/azure-http-specs/azure/client-generator-core/flattengroup/zz_models_serde.go b/test/azure-http-specs/azure/client-generator-core/flattengroup/zz_models_serde.go new file mode 100644 index 000000000000..36724fd485ed --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/flattengroup/zz_models_serde.go @@ -0,0 +1,263 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package flattengroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type ChildFlattenModel. +func (c ChildFlattenModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "summary", c.Summary) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ChildFlattenModel. +func (c *ChildFlattenModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + case "summary": + err = unpopulate(val, "Summary", &c.Summary) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ChildModel. +func (c ChildModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "age", c.Age) + populate(objectMap, "description", c.Description) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ChildModel. +func (c *ChildModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "age": + err = unpopulate(val, "Age", &c.Age) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &c.Description) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FlattenModel. +func (f FlattenModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", f.Name) + populate(objectMap, "properties", f.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FlattenModel. +func (f *FlattenModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &f.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &f.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FlattenUnknownModel. +func (f FlattenUnknownModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", f.Name) + populateAny(objectMap, "properties", f.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FlattenUnknownModel. +func (f *FlattenUnknownModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &f.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &f.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NestedFlattenModel. +func (n NestedFlattenModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", n.Name) + populate(objectMap, "properties", n.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NestedFlattenModel. +func (n *NestedFlattenModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &n.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &n.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Solution. +func (s Solution) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Solution. +func (s *Solution) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SolutionProperties. +func (s SolutionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "content", s.Content) + populate(objectMap, "solutionId", s.SolutionID) + populate(objectMap, "title", s.Title) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SolutionProperties. +func (s *SolutionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "content": + err = unpopulate(val, "Content", &s.Content) + delete(rawMsg, key) + case "solutionId": + err = unpopulate(val, "SolutionID", &s.SolutionID) + delete(rawMsg, key) + case "title": + err = unpopulate(val, "Title", &s.Title) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateAny(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/flattengroup/zz_options.go b/test/azure-http-specs/azure/client-generator-core/flattengroup/zz_options.go new file mode 100644 index 000000000000..61334a4c3cee --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/flattengroup/zz_options.go @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package flattengroup + +// FlattenPropertyClientPutFlattenModelOptions contains the optional parameters for the FlattenPropertyClient.PutFlattenModel +// method. +type FlattenPropertyClientPutFlattenModelOptions struct { + // placeholder for future optional parameters +} + +// FlattenPropertyClientPutFlattenReadOnlyModelOptions contains the optional parameters for the FlattenPropertyClient.PutFlattenReadOnlyModel +// method. +type FlattenPropertyClientPutFlattenReadOnlyModelOptions struct { + // placeholder for future optional parameters +} + +// FlattenPropertyClientPutFlattenUnknownModelOptions contains the optional parameters for the FlattenPropertyClient.PutFlattenUnknownModel +// method. +type FlattenPropertyClientPutFlattenUnknownModelOptions struct { + // placeholder for future optional parameters +} + +// FlattenPropertyClientPutNestedFlattenModelOptions contains the optional parameters for the FlattenPropertyClient.PutNestedFlattenModel +// method. +type FlattenPropertyClientPutNestedFlattenModelOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/azure/client-generator-core/flattengroup/zz_responses.go b/test/azure-http-specs/azure/client-generator-core/flattengroup/zz_responses.go new file mode 100644 index 000000000000..73816559e25f --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/flattengroup/zz_responses.go @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package flattengroup + +// FlattenPropertyClientPutFlattenModelResponse contains the response from method FlattenPropertyClient.PutFlattenModel. +type FlattenPropertyClientPutFlattenModelResponse struct { + // This is the model with one level of flattening. + FlattenModel +} + +// FlattenPropertyClientPutFlattenReadOnlyModelResponse contains the response from method FlattenPropertyClient.PutFlattenReadOnlyModel. +type FlattenPropertyClientPutFlattenReadOnlyModelResponse struct { + // This is the model with flattened properties that are all read-only. + Solution +} + +// FlattenPropertyClientPutFlattenUnknownModelResponse contains the response from method FlattenPropertyClient.PutFlattenUnknownModel. +type FlattenPropertyClientPutFlattenUnknownModelResponse struct { + // This is the model with unknown type properties to be flattened. + FlattenUnknownModel +} + +// FlattenPropertyClientPutNestedFlattenModelResponse contains the response from method FlattenPropertyClient.PutNestedFlattenModel. +type FlattenPropertyClientPutNestedFlattenModelResponse struct { + // This is the model with two levels of flattening. + NestedFlattenModel +} diff --git a/test/azure-http-specs/azure/client-generator-core/flattengroup/zz_version.go b/test/azure-http-specs/azure/client-generator-core/flattengroup/zz_version.go new file mode 100644 index 000000000000..1584918785a8 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/flattengroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package flattengroup + +const ( + moduleName = "flattengroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/client-generator-core/hierarchygroup/LICENSE.txt b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/client-generator-core/hierarchygroup/fake/zz_hierarchybuilding_server.go b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/fake/zz_hierarchybuilding_server.go new file mode 100644 index 000000000000..2bae32268375 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/fake/zz_hierarchybuilding_server.go @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// HierarchyBuildingServer is a fake server for instances of the hierarchygroup.HierarchyBuildingClient type. +type HierarchyBuildingServer struct { + // HierarchyBuildingAnimalOperationsServer contains the fakes for client HierarchyBuildingAnimalOperationsClient + HierarchyBuildingAnimalOperationsServer HierarchyBuildingAnimalOperationsServer + + // HierarchyBuildingDogOperationsServer contains the fakes for client HierarchyBuildingDogOperationsClient + HierarchyBuildingDogOperationsServer HierarchyBuildingDogOperationsServer + + // HierarchyBuildingPetOperationsServer contains the fakes for client HierarchyBuildingPetOperationsClient + HierarchyBuildingPetOperationsServer HierarchyBuildingPetOperationsServer +} + +// NewHierarchyBuildingServerTransport creates a new instance of HierarchyBuildingServerTransport with the provided implementation. +// The returned HierarchyBuildingServerTransport instance is connected to an instance of hierarchygroup.HierarchyBuildingClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewHierarchyBuildingServerTransport(srv *HierarchyBuildingServer) *HierarchyBuildingServerTransport { + return &HierarchyBuildingServerTransport{srv: srv} +} + +// HierarchyBuildingServerTransport connects instances of hierarchygroup.HierarchyBuildingClient to instances of HierarchyBuildingServer. +// Don't use this type directly, use NewHierarchyBuildingServerTransport instead. +type HierarchyBuildingServerTransport struct { + srv *HierarchyBuildingServer + trMu sync.Mutex + trHierarchyBuildingAnimalOperationsServer *HierarchyBuildingAnimalOperationsServerTransport + trHierarchyBuildingDogOperationsServer *HierarchyBuildingDogOperationsServerTransport + trHierarchyBuildingPetOperationsServer *HierarchyBuildingPetOperationsServerTransport +} + +// Do implements the policy.Transporter interface for HierarchyBuildingServerTransport. +func (h *HierarchyBuildingServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return h.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (h *HierarchyBuildingServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "HierarchyBuildingAnimalOperationsClient": + initServer(&h.trMu, &h.trHierarchyBuildingAnimalOperationsServer, func() *HierarchyBuildingAnimalOperationsServerTransport { + return NewHierarchyBuildingAnimalOperationsServerTransport(&h.srv.HierarchyBuildingAnimalOperationsServer) + }) + resp, err = h.trHierarchyBuildingAnimalOperationsServer.Do(req) + case "HierarchyBuildingDogOperationsClient": + initServer(&h.trMu, &h.trHierarchyBuildingDogOperationsServer, func() *HierarchyBuildingDogOperationsServerTransport { + return NewHierarchyBuildingDogOperationsServerTransport(&h.srv.HierarchyBuildingDogOperationsServer) + }) + resp, err = h.trHierarchyBuildingDogOperationsServer.Do(req) + case "HierarchyBuildingPetOperationsClient": + initServer(&h.trMu, &h.trHierarchyBuildingPetOperationsServer, func() *HierarchyBuildingPetOperationsServerTransport { + return NewHierarchyBuildingPetOperationsServerTransport(&h.srv.HierarchyBuildingPetOperationsServer) + }) + resp, err = h.trHierarchyBuildingPetOperationsServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to HierarchyBuildingServerTransport +var hierarchyBuildingServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/hierarchygroup/fake/zz_hierarchybuildinganimaloperations_server.go b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/fake/zz_hierarchybuildinganimaloperations_server.go new file mode 100644 index 000000000000..7f664e60542f --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/fake/zz_hierarchybuildinganimaloperations_server.go @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "hierarchygroup" + "net/http" + "slices" +) + +// HierarchyBuildingAnimalOperationsServer is a fake server for instances of the hierarchygroup.HierarchyBuildingAnimalOperationsClient type. +type HierarchyBuildingAnimalOperationsServer struct { + // UpdateDogAsAnimal is the fake for method HierarchyBuildingAnimalOperationsClient.UpdateDogAsAnimal + // HTTP status codes to indicate success: http.StatusOK + UpdateDogAsAnimal func(ctx context.Context, animal hierarchygroup.AnimalClassification, options *hierarchygroup.HierarchyBuildingAnimalOperationsClientUpdateDogAsAnimalOptions) (resp azfake.Responder[hierarchygroup.HierarchyBuildingAnimalOperationsClientUpdateDogAsAnimalResponse], errResp azfake.ErrorResponder) + + // UpdatePetAsAnimal is the fake for method HierarchyBuildingAnimalOperationsClient.UpdatePetAsAnimal + // HTTP status codes to indicate success: http.StatusOK + UpdatePetAsAnimal func(ctx context.Context, animal hierarchygroup.AnimalClassification, options *hierarchygroup.HierarchyBuildingAnimalOperationsClientUpdatePetAsAnimalOptions) (resp azfake.Responder[hierarchygroup.HierarchyBuildingAnimalOperationsClientUpdatePetAsAnimalResponse], errResp azfake.ErrorResponder) +} + +// NewHierarchyBuildingAnimalOperationsServerTransport creates a new instance of HierarchyBuildingAnimalOperationsServerTransport with the provided implementation. +// The returned HierarchyBuildingAnimalOperationsServerTransport instance is connected to an instance of hierarchygroup.HierarchyBuildingAnimalOperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewHierarchyBuildingAnimalOperationsServerTransport(srv *HierarchyBuildingAnimalOperationsServer) *HierarchyBuildingAnimalOperationsServerTransport { + return &HierarchyBuildingAnimalOperationsServerTransport{srv: srv} +} + +// HierarchyBuildingAnimalOperationsServerTransport connects instances of hierarchygroup.HierarchyBuildingAnimalOperationsClient to instances of HierarchyBuildingAnimalOperationsServer. +// Don't use this type directly, use NewHierarchyBuildingAnimalOperationsServerTransport instead. +type HierarchyBuildingAnimalOperationsServerTransport struct { + srv *HierarchyBuildingAnimalOperationsServer +} + +// Do implements the policy.Transporter interface for HierarchyBuildingAnimalOperationsServerTransport. +func (h *HierarchyBuildingAnimalOperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return h.dispatchToMethodFake(req, method) +} + +func (h *HierarchyBuildingAnimalOperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if hierarchyBuildingAnimalOperationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = hierarchyBuildingAnimalOperationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "HierarchyBuildingAnimalOperationsClient.UpdateDogAsAnimal": + res.resp, res.err = h.dispatchUpdateDogAsAnimal(req) + case "HierarchyBuildingAnimalOperationsClient.UpdatePetAsAnimal": + res.resp, res.err = h.dispatchUpdatePetAsAnimal(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (h *HierarchyBuildingAnimalOperationsServerTransport) dispatchUpdateDogAsAnimal(req *http.Request) (*http.Response, error) { + if h.srv.UpdateDogAsAnimal == nil { + return nil, &nonRetriableError{errors.New("fake for method UpdateDogAsAnimal not implemented")} + } + raw, err := readRequestBody(req) + if err != nil { + return nil, err + } + body, err := unmarshalAnimalClassification(raw) + if err != nil { + return nil, err + } + respr, errRespr := h.srv.UpdateDogAsAnimal(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).AnimalClassification, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (h *HierarchyBuildingAnimalOperationsServerTransport) dispatchUpdatePetAsAnimal(req *http.Request) (*http.Response, error) { + if h.srv.UpdatePetAsAnimal == nil { + return nil, &nonRetriableError{errors.New("fake for method UpdatePetAsAnimal not implemented")} + } + raw, err := readRequestBody(req) + if err != nil { + return nil, err + } + body, err := unmarshalAnimalClassification(raw) + if err != nil { + return nil, err + } + respr, errRespr := h.srv.UpdatePetAsAnimal(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).AnimalClassification, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to HierarchyBuildingAnimalOperationsServerTransport +var hierarchyBuildingAnimalOperationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/hierarchygroup/fake/zz_hierarchybuildingdogoperations_server.go b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/fake/zz_hierarchybuildingdogoperations_server.go new file mode 100644 index 000000000000..13a460bb92fa --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/fake/zz_hierarchybuildingdogoperations_server.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "hierarchygroup" + "net/http" + "slices" +) + +// HierarchyBuildingDogOperationsServer is a fake server for instances of the hierarchygroup.HierarchyBuildingDogOperationsClient type. +type HierarchyBuildingDogOperationsServer struct { + // UpdateDogAsDog is the fake for method HierarchyBuildingDogOperationsClient.UpdateDogAsDog + // HTTP status codes to indicate success: http.StatusOK + UpdateDogAsDog func(ctx context.Context, dog hierarchygroup.Dog, options *hierarchygroup.HierarchyBuildingDogOperationsClientUpdateDogAsDogOptions) (resp azfake.Responder[hierarchygroup.HierarchyBuildingDogOperationsClientUpdateDogAsDogResponse], errResp azfake.ErrorResponder) +} + +// NewHierarchyBuildingDogOperationsServerTransport creates a new instance of HierarchyBuildingDogOperationsServerTransport with the provided implementation. +// The returned HierarchyBuildingDogOperationsServerTransport instance is connected to an instance of hierarchygroup.HierarchyBuildingDogOperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewHierarchyBuildingDogOperationsServerTransport(srv *HierarchyBuildingDogOperationsServer) *HierarchyBuildingDogOperationsServerTransport { + return &HierarchyBuildingDogOperationsServerTransport{srv: srv} +} + +// HierarchyBuildingDogOperationsServerTransport connects instances of hierarchygroup.HierarchyBuildingDogOperationsClient to instances of HierarchyBuildingDogOperationsServer. +// Don't use this type directly, use NewHierarchyBuildingDogOperationsServerTransport instead. +type HierarchyBuildingDogOperationsServerTransport struct { + srv *HierarchyBuildingDogOperationsServer +} + +// Do implements the policy.Transporter interface for HierarchyBuildingDogOperationsServerTransport. +func (h *HierarchyBuildingDogOperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return h.dispatchToMethodFake(req, method) +} + +func (h *HierarchyBuildingDogOperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if hierarchyBuildingDogOperationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = hierarchyBuildingDogOperationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "HierarchyBuildingDogOperationsClient.UpdateDogAsDog": + res.resp, res.err = h.dispatchUpdateDogAsDog(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (h *HierarchyBuildingDogOperationsServerTransport) dispatchUpdateDogAsDog(req *http.Request) (*http.Response, error) { + if h.srv.UpdateDogAsDog == nil { + return nil, &nonRetriableError{errors.New("fake for method UpdateDogAsDog not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[hierarchygroup.Dog](req) + if err != nil { + return nil, err + } + respr, errRespr := h.srv.UpdateDogAsDog(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Dog, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to HierarchyBuildingDogOperationsServerTransport +var hierarchyBuildingDogOperationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/hierarchygroup/fake/zz_hierarchybuildingpetoperations_server.go b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/fake/zz_hierarchybuildingpetoperations_server.go new file mode 100644 index 000000000000..a9dcd93134f8 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/fake/zz_hierarchybuildingpetoperations_server.go @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "hierarchygroup" + "net/http" + "slices" +) + +// HierarchyBuildingPetOperationsServer is a fake server for instances of the hierarchygroup.HierarchyBuildingPetOperationsClient type. +type HierarchyBuildingPetOperationsServer struct { + // UpdateDogAsPet is the fake for method HierarchyBuildingPetOperationsClient.UpdateDogAsPet + // HTTP status codes to indicate success: http.StatusOK + UpdateDogAsPet func(ctx context.Context, pet hierarchygroup.PetClassification, options *hierarchygroup.HierarchyBuildingPetOperationsClientUpdateDogAsPetOptions) (resp azfake.Responder[hierarchygroup.HierarchyBuildingPetOperationsClientUpdateDogAsPetResponse], errResp azfake.ErrorResponder) + + // UpdatePetAsPet is the fake for method HierarchyBuildingPetOperationsClient.UpdatePetAsPet + // HTTP status codes to indicate success: http.StatusOK + UpdatePetAsPet func(ctx context.Context, pet hierarchygroup.PetClassification, options *hierarchygroup.HierarchyBuildingPetOperationsClientUpdatePetAsPetOptions) (resp azfake.Responder[hierarchygroup.HierarchyBuildingPetOperationsClientUpdatePetAsPetResponse], errResp azfake.ErrorResponder) +} + +// NewHierarchyBuildingPetOperationsServerTransport creates a new instance of HierarchyBuildingPetOperationsServerTransport with the provided implementation. +// The returned HierarchyBuildingPetOperationsServerTransport instance is connected to an instance of hierarchygroup.HierarchyBuildingPetOperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewHierarchyBuildingPetOperationsServerTransport(srv *HierarchyBuildingPetOperationsServer) *HierarchyBuildingPetOperationsServerTransport { + return &HierarchyBuildingPetOperationsServerTransport{srv: srv} +} + +// HierarchyBuildingPetOperationsServerTransport connects instances of hierarchygroup.HierarchyBuildingPetOperationsClient to instances of HierarchyBuildingPetOperationsServer. +// Don't use this type directly, use NewHierarchyBuildingPetOperationsServerTransport instead. +type HierarchyBuildingPetOperationsServerTransport struct { + srv *HierarchyBuildingPetOperationsServer +} + +// Do implements the policy.Transporter interface for HierarchyBuildingPetOperationsServerTransport. +func (h *HierarchyBuildingPetOperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return h.dispatchToMethodFake(req, method) +} + +func (h *HierarchyBuildingPetOperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if hierarchyBuildingPetOperationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = hierarchyBuildingPetOperationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "HierarchyBuildingPetOperationsClient.UpdateDogAsPet": + res.resp, res.err = h.dispatchUpdateDogAsPet(req) + case "HierarchyBuildingPetOperationsClient.UpdatePetAsPet": + res.resp, res.err = h.dispatchUpdatePetAsPet(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (h *HierarchyBuildingPetOperationsServerTransport) dispatchUpdateDogAsPet(req *http.Request) (*http.Response, error) { + if h.srv.UpdateDogAsPet == nil { + return nil, &nonRetriableError{errors.New("fake for method UpdateDogAsPet not implemented")} + } + raw, err := readRequestBody(req) + if err != nil { + return nil, err + } + body, err := unmarshalPetClassification(raw) + if err != nil { + return nil, err + } + respr, errRespr := h.srv.UpdateDogAsPet(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).PetClassification, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (h *HierarchyBuildingPetOperationsServerTransport) dispatchUpdatePetAsPet(req *http.Request) (*http.Response, error) { + if h.srv.UpdatePetAsPet == nil { + return nil, &nonRetriableError{errors.New("fake for method UpdatePetAsPet not implemented")} + } + raw, err := readRequestBody(req) + if err != nil { + return nil, err + } + body, err := unmarshalPetClassification(raw) + if err != nil { + return nil, err + } + respr, errRespr := h.srv.UpdatePetAsPet(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).PetClassification, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to HierarchyBuildingPetOperationsServerTransport +var hierarchyBuildingPetOperationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/hierarchygroup/fake/zz_internal.go b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/fake/zz_internal.go new file mode 100644 index 000000000000..24f0ba71db24 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/fake/zz_internal.go @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "io" + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func readRequestBody(req *http.Request) ([]byte, error) { + if req.Body == nil { + return nil, nil + } + body, err := io.ReadAll(req.Body) + if err != nil { + return nil, err + } + req.Body.Close() + return body, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/hierarchygroup/fake/zz_polymorphic_helpers.go b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/fake/zz_polymorphic_helpers.go new file mode 100644 index 000000000000..78978314336d --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/fake/zz_polymorphic_helpers.go @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "encoding/json" + "hierarchygroup" +) + +func unmarshalAnimalClassification(rawMsg json.RawMessage) (hierarchygroup.AnimalClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b hierarchygroup.AnimalClassification + switch m["kind"] { + case "dog": + b = &hierarchygroup.Dog{} + case "pet": + b = &hierarchygroup.Pet{} + default: + b = &hierarchygroup.Animal{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} + +func unmarshalPetClassification(rawMsg json.RawMessage) (hierarchygroup.PetClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b hierarchygroup.PetClassification + switch m["kind"] { + case "dog": + b = &hierarchygroup.Dog{} + default: + b = &hierarchygroup.Pet{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/hierarchygroup/go.mod b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/go.mod new file mode 100644 index 000000000000..9358219301d4 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/go.mod @@ -0,0 +1,17 @@ +module hierarchygroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/client-generator-core/hierarchygroup/go.sum b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/client-generator-core/hierarchygroup/hierarchy_client_test.go b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/hierarchy_client_test.go new file mode 100644 index 000000000000..224f1d1f431c --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/hierarchy_client_test.go @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package hierarchygroup_test + +import ( + "context" + "hierarchygroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestHierarchyBuildingClient_UpdatePetAsAnimal(t *testing.T) { + client, err := hierarchygroup.NewHierarchyBuildingClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + animalClient := client.NewHierarchyBuildingAnimalOperationsClient() + + resp, err := animalClient.UpdatePetAsAnimal(context.Background(), &hierarchygroup.Pet{ + Kind: to.Ptr("pet"), + Name: to.Ptr("Buddy"), + Trained: to.Ptr(true), + }, nil) + require.NoError(t, err) + require.Equal(t, &hierarchygroup.Pet{ + Kind: to.Ptr("pet"), + Name: to.Ptr("Buddy"), + Trained: to.Ptr(true), + }, resp.AnimalClassification) +} + +func TestHierarchyBuildingClient_UpdateDogAsAnimal(t *testing.T) { + client, err := hierarchygroup.NewHierarchyBuildingClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + animalClient := client.NewHierarchyBuildingAnimalOperationsClient() + + resp, err := animalClient.UpdateDogAsAnimal(context.Background(), &hierarchygroup.Dog{ + Kind: to.Ptr("dog"), + Name: to.Ptr("Rex"), + Trained: to.Ptr(true), + Breed: to.Ptr("German Shepherd"), + }, nil) + require.NoError(t, err) + require.Equal(t, &hierarchygroup.Dog{ + Kind: to.Ptr("dog"), + Name: to.Ptr("Rex"), + Trained: to.Ptr(true), + Breed: to.Ptr("German Shepherd"), + }, resp.AnimalClassification) +} + +func TestHierarchyBuildingClient_UpdateDogAsPet(t *testing.T) { + client, err := hierarchygroup.NewHierarchyBuildingClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + petClient := client.NewHierarchyBuildingPetOperationsClient() + + resp, err := petClient.UpdateDogAsPet(context.Background(), &hierarchygroup.Dog{ + Kind: to.Ptr("dog"), + Name: to.Ptr("Rex"), + Trained: to.Ptr(true), + Breed: to.Ptr("German Shepherd"), + }, nil) + require.NoError(t, err) + require.Equal(t, &hierarchygroup.Dog{ + Kind: to.Ptr("dog"), + Name: to.Ptr("Rex"), + Trained: to.Ptr(true), + Breed: to.Ptr("German Shepherd"), + }, resp.PetClassification) +} + +func TestHierarchyBuildingClient_UpdatePetAsPet(t *testing.T) { + client, err := hierarchygroup.NewHierarchyBuildingClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + petClient := client.NewHierarchyBuildingPetOperationsClient() + + resp, err := petClient.UpdatePetAsPet(context.Background(), &hierarchygroup.Pet{ + Kind: to.Ptr("pet"), + Name: to.Ptr("Buddy"), + Trained: to.Ptr(true), + }, nil) + require.NoError(t, err) + require.Equal(t, &hierarchygroup.Pet{ + Kind: to.Ptr("pet"), + Name: to.Ptr("Buddy"), + Trained: to.Ptr(true), + }, resp.PetClassification) +} + +func TestHierarchyBuildingClient_UpdateDogAsDog(t *testing.T) { + client, err := hierarchygroup.NewHierarchyBuildingClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + dogClient := client.NewHierarchyBuildingDogOperationsClient() + + resp, err := dogClient.UpdateDogAsDog(context.Background(), hierarchygroup.Dog{ + Kind: to.Ptr("dog"), + Name: to.Ptr("Rex"), + Trained: to.Ptr(true), + Breed: to.Ptr("German Shepherd"), + }, nil) + require.NoError(t, err) + require.Equal(t, hierarchygroup.Dog{ + Kind: to.Ptr("dog"), + Name: to.Ptr("Rex"), + Trained: to.Ptr(true), + Breed: to.Ptr("German Shepherd"), + }, resp.Dog) +} diff --git a/test/azure-http-specs/azure/client-generator-core/hierarchygroup/testdata/_metadata.json b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_hierarchybuilding_client.go b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_hierarchybuilding_client.go new file mode 100644 index 000000000000..f9063b317968 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_hierarchybuilding_client.go @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package hierarchygroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// HierarchyBuildingClient - Test for @hierarchyBuilding decorator. +// Don't use this type directly, use NewHierarchyBuildingClientWithNoCredential() instead. +type HierarchyBuildingClient struct { + internal *azcore.Client + endpoint string +} + +// HierarchyBuildingClientOptions contains the optional values for creating a [HierarchyBuildingClient]. +type HierarchyBuildingClientOptions struct { + azcore.ClientOptions +} + +// NewHierarchyBuildingClientWithNoCredential creates a new instance of HierarchyBuildingClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewHierarchyBuildingClientWithNoCredential(endpoint string, options *HierarchyBuildingClientOptions) (*HierarchyBuildingClient, error) { + if options == nil { + options = &HierarchyBuildingClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &HierarchyBuildingClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewHierarchyBuildingAnimalOperationsClient creates a new instance of [HierarchyBuildingAnimalOperationsClient]. +func (client *HierarchyBuildingClient) NewHierarchyBuildingAnimalOperationsClient() *HierarchyBuildingAnimalOperationsClient { + return &HierarchyBuildingAnimalOperationsClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewHierarchyBuildingDogOperationsClient creates a new instance of [HierarchyBuildingDogOperationsClient]. +func (client *HierarchyBuildingClient) NewHierarchyBuildingDogOperationsClient() *HierarchyBuildingDogOperationsClient { + return &HierarchyBuildingDogOperationsClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewHierarchyBuildingPetOperationsClient creates a new instance of [HierarchyBuildingPetOperationsClient]. +func (client *HierarchyBuildingClient) NewHierarchyBuildingPetOperationsClient() *HierarchyBuildingPetOperationsClient { + return &HierarchyBuildingPetOperationsClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_hierarchybuildinganimaloperations_client.go b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_hierarchybuildinganimaloperations_client.go new file mode 100644 index 000000000000..ddefcf695156 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_hierarchybuildinganimaloperations_client.go @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package hierarchygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// HierarchyBuildingAnimalOperationsClient contains the methods for the HierarchyBuildingAnimalOperations group. +// Don't use this type directly, use [HierarchyBuildingClient.NewHierarchyBuildingAnimalOperationsClient] instead. +type HierarchyBuildingAnimalOperationsClient struct { + internal *azcore.Client + endpoint string +} + +// UpdateDogAsAnimal - Update a dog as an animal +// If the operation fails it returns an *azcore.ResponseError type. +// - options - HierarchyBuildingAnimalOperationsClientUpdateDogAsAnimalOptions contains the optional parameters for the HierarchyBuildingAnimalOperationsClient.UpdateDogAsAnimal +// method. +func (client *HierarchyBuildingAnimalOperationsClient) UpdateDogAsAnimal(ctx context.Context, animal AnimalClassification, options *HierarchyBuildingAnimalOperationsClientUpdateDogAsAnimalOptions) (HierarchyBuildingAnimalOperationsClientUpdateDogAsAnimalResponse, error) { + var err error + const operationName = "HierarchyBuildingAnimalOperationsClient.UpdateDogAsAnimal" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateDogAsAnimalCreateRequest(ctx, animal, options) + if err != nil { + return HierarchyBuildingAnimalOperationsClientUpdateDogAsAnimalResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return HierarchyBuildingAnimalOperationsClientUpdateDogAsAnimalResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return HierarchyBuildingAnimalOperationsClientUpdateDogAsAnimalResponse{}, err + } + resp, err := client.updateDogAsAnimalHandleResponse(httpResp) + return resp, err +} + +// updateDogAsAnimalCreateRequest creates the UpdateDogAsAnimal request. +func (client *HierarchyBuildingAnimalOperationsClient) updateDogAsAnimalCreateRequest(ctx context.Context, animal AnimalClassification, _ *HierarchyBuildingAnimalOperationsClientUpdateDogAsAnimalOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/hierarchy-building/dog/as-animal" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, animal); err != nil { + return nil, err + } + return req, nil +} + +// updateDogAsAnimalHandleResponse handles the UpdateDogAsAnimal response. +func (client *HierarchyBuildingAnimalOperationsClient) updateDogAsAnimalHandleResponse(resp *http.Response) (HierarchyBuildingAnimalOperationsClientUpdateDogAsAnimalResponse, error) { + result := HierarchyBuildingAnimalOperationsClientUpdateDogAsAnimalResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result); err != nil { + return HierarchyBuildingAnimalOperationsClientUpdateDogAsAnimalResponse{}, err + } + return result, nil +} + +// UpdatePetAsAnimal - Update a pet as an animal +// If the operation fails it returns an *azcore.ResponseError type. +// - options - HierarchyBuildingAnimalOperationsClientUpdatePetAsAnimalOptions contains the optional parameters for the HierarchyBuildingAnimalOperationsClient.UpdatePetAsAnimal +// method. +func (client *HierarchyBuildingAnimalOperationsClient) UpdatePetAsAnimal(ctx context.Context, animal AnimalClassification, options *HierarchyBuildingAnimalOperationsClientUpdatePetAsAnimalOptions) (HierarchyBuildingAnimalOperationsClientUpdatePetAsAnimalResponse, error) { + var err error + const operationName = "HierarchyBuildingAnimalOperationsClient.UpdatePetAsAnimal" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updatePetAsAnimalCreateRequest(ctx, animal, options) + if err != nil { + return HierarchyBuildingAnimalOperationsClientUpdatePetAsAnimalResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return HierarchyBuildingAnimalOperationsClientUpdatePetAsAnimalResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return HierarchyBuildingAnimalOperationsClientUpdatePetAsAnimalResponse{}, err + } + resp, err := client.updatePetAsAnimalHandleResponse(httpResp) + return resp, err +} + +// updatePetAsAnimalCreateRequest creates the UpdatePetAsAnimal request. +func (client *HierarchyBuildingAnimalOperationsClient) updatePetAsAnimalCreateRequest(ctx context.Context, animal AnimalClassification, _ *HierarchyBuildingAnimalOperationsClientUpdatePetAsAnimalOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/hierarchy-building/pet/as-animal" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, animal); err != nil { + return nil, err + } + return req, nil +} + +// updatePetAsAnimalHandleResponse handles the UpdatePetAsAnimal response. +func (client *HierarchyBuildingAnimalOperationsClient) updatePetAsAnimalHandleResponse(resp *http.Response) (HierarchyBuildingAnimalOperationsClientUpdatePetAsAnimalResponse, error) { + result := HierarchyBuildingAnimalOperationsClientUpdatePetAsAnimalResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result); err != nil { + return HierarchyBuildingAnimalOperationsClientUpdatePetAsAnimalResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_hierarchybuildingdogoperations_client.go b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_hierarchybuildingdogoperations_client.go new file mode 100644 index 000000000000..c61c6020c7ab --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_hierarchybuildingdogoperations_client.go @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package hierarchygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// HierarchyBuildingDogOperationsClient contains the methods for the HierarchyBuildingDogOperations group. +// Don't use this type directly, use [HierarchyBuildingClient.NewHierarchyBuildingDogOperationsClient] instead. +type HierarchyBuildingDogOperationsClient struct { + internal *azcore.Client + endpoint string +} + +// UpdateDogAsDog - Update a dog as a dog +// If the operation fails it returns an *azcore.ResponseError type. +// - options - HierarchyBuildingDogOperationsClientUpdateDogAsDogOptions contains the optional parameters for the HierarchyBuildingDogOperationsClient.UpdateDogAsDog +// method. +func (client *HierarchyBuildingDogOperationsClient) UpdateDogAsDog(ctx context.Context, dog Dog, options *HierarchyBuildingDogOperationsClientUpdateDogAsDogOptions) (HierarchyBuildingDogOperationsClientUpdateDogAsDogResponse, error) { + var err error + const operationName = "HierarchyBuildingDogOperationsClient.UpdateDogAsDog" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateDogAsDogCreateRequest(ctx, dog, options) + if err != nil { + return HierarchyBuildingDogOperationsClientUpdateDogAsDogResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return HierarchyBuildingDogOperationsClientUpdateDogAsDogResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return HierarchyBuildingDogOperationsClientUpdateDogAsDogResponse{}, err + } + resp, err := client.updateDogAsDogHandleResponse(httpResp) + return resp, err +} + +// updateDogAsDogCreateRequest creates the UpdateDogAsDog request. +func (client *HierarchyBuildingDogOperationsClient) updateDogAsDogCreateRequest(ctx context.Context, dog Dog, _ *HierarchyBuildingDogOperationsClientUpdateDogAsDogOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/hierarchy-building/dog/as-dog" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, dog); err != nil { + return nil, err + } + return req, nil +} + +// updateDogAsDogHandleResponse handles the UpdateDogAsDog response. +func (client *HierarchyBuildingDogOperationsClient) updateDogAsDogHandleResponse(resp *http.Response) (HierarchyBuildingDogOperationsClientUpdateDogAsDogResponse, error) { + result := HierarchyBuildingDogOperationsClientUpdateDogAsDogResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Dog); err != nil { + return HierarchyBuildingDogOperationsClientUpdateDogAsDogResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_hierarchybuildingpetoperations_client.go b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_hierarchybuildingpetoperations_client.go new file mode 100644 index 000000000000..f6495c2d8735 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_hierarchybuildingpetoperations_client.go @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package hierarchygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// HierarchyBuildingPetOperationsClient contains the methods for the HierarchyBuildingPetOperations group. +// Don't use this type directly, use [HierarchyBuildingClient.NewHierarchyBuildingPetOperationsClient] instead. +type HierarchyBuildingPetOperationsClient struct { + internal *azcore.Client + endpoint string +} + +// UpdateDogAsPet - Update a dog as a pet +// If the operation fails it returns an *azcore.ResponseError type. +// - options - HierarchyBuildingPetOperationsClientUpdateDogAsPetOptions contains the optional parameters for the HierarchyBuildingPetOperationsClient.UpdateDogAsPet +// method. +func (client *HierarchyBuildingPetOperationsClient) UpdateDogAsPet(ctx context.Context, pet PetClassification, options *HierarchyBuildingPetOperationsClientUpdateDogAsPetOptions) (HierarchyBuildingPetOperationsClientUpdateDogAsPetResponse, error) { + var err error + const operationName = "HierarchyBuildingPetOperationsClient.UpdateDogAsPet" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateDogAsPetCreateRequest(ctx, pet, options) + if err != nil { + return HierarchyBuildingPetOperationsClientUpdateDogAsPetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return HierarchyBuildingPetOperationsClientUpdateDogAsPetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return HierarchyBuildingPetOperationsClientUpdateDogAsPetResponse{}, err + } + resp, err := client.updateDogAsPetHandleResponse(httpResp) + return resp, err +} + +// updateDogAsPetCreateRequest creates the UpdateDogAsPet request. +func (client *HierarchyBuildingPetOperationsClient) updateDogAsPetCreateRequest(ctx context.Context, pet PetClassification, _ *HierarchyBuildingPetOperationsClientUpdateDogAsPetOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/hierarchy-building/dog/as-pet" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, pet); err != nil { + return nil, err + } + return req, nil +} + +// updateDogAsPetHandleResponse handles the UpdateDogAsPet response. +func (client *HierarchyBuildingPetOperationsClient) updateDogAsPetHandleResponse(resp *http.Response) (HierarchyBuildingPetOperationsClientUpdateDogAsPetResponse, error) { + result := HierarchyBuildingPetOperationsClientUpdateDogAsPetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result); err != nil { + return HierarchyBuildingPetOperationsClientUpdateDogAsPetResponse{}, err + } + return result, nil +} + +// UpdatePetAsPet - Update a pet as a pet +// If the operation fails it returns an *azcore.ResponseError type. +// - options - HierarchyBuildingPetOperationsClientUpdatePetAsPetOptions contains the optional parameters for the HierarchyBuildingPetOperationsClient.UpdatePetAsPet +// method. +func (client *HierarchyBuildingPetOperationsClient) UpdatePetAsPet(ctx context.Context, pet PetClassification, options *HierarchyBuildingPetOperationsClientUpdatePetAsPetOptions) (HierarchyBuildingPetOperationsClientUpdatePetAsPetResponse, error) { + var err error + const operationName = "HierarchyBuildingPetOperationsClient.UpdatePetAsPet" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updatePetAsPetCreateRequest(ctx, pet, options) + if err != nil { + return HierarchyBuildingPetOperationsClientUpdatePetAsPetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return HierarchyBuildingPetOperationsClientUpdatePetAsPetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return HierarchyBuildingPetOperationsClientUpdatePetAsPetResponse{}, err + } + resp, err := client.updatePetAsPetHandleResponse(httpResp) + return resp, err +} + +// updatePetAsPetCreateRequest creates the UpdatePetAsPet request. +func (client *HierarchyBuildingPetOperationsClient) updatePetAsPetCreateRequest(ctx context.Context, pet PetClassification, _ *HierarchyBuildingPetOperationsClientUpdatePetAsPetOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/hierarchy-building/pet/as-pet" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, pet); err != nil { + return nil, err + } + return req, nil +} + +// updatePetAsPetHandleResponse handles the UpdatePetAsPet response. +func (client *HierarchyBuildingPetOperationsClient) updatePetAsPetHandleResponse(resp *http.Response) (HierarchyBuildingPetOperationsClientUpdatePetAsPetResponse, error) { + result := HierarchyBuildingPetOperationsClientUpdatePetAsPetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result); err != nil { + return HierarchyBuildingPetOperationsClientUpdatePetAsPetResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_interfaces.go b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_interfaces.go new file mode 100644 index 000000000000..984333b3b382 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_interfaces.go @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package hierarchygroup + +// AnimalClassification provides polymorphic access to related types. +// Call the interface's GetAnimal() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *Animal, *Dog, *Pet +type AnimalClassification interface { + // GetAnimal returns the Animal content of the underlying type. + GetAnimal() *Animal +} + +// PetClassification provides polymorphic access to related types. +// Call the interface's GetPet() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *Dog, *Pet +type PetClassification interface { + AnimalClassification + // GetPet returns the Pet content of the underlying type. + GetPet() *Pet +} diff --git a/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_models.go b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_models.go new file mode 100644 index 000000000000..c06dfe3f630f --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_models.go @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package hierarchygroup + +type Animal struct { + // REQUIRED; The kind of animal + Kind *string + + // REQUIRED; Name of the animal + Name *string +} + +// GetAnimal implements the AnimalClassification interface for type Animal. +func (a *Animal) GetAnimal() *Animal { return a } + +type Dog struct { + // REQUIRED; The breed of the dog + Breed *string + + // CONSTANT; Field has constant value "dog", any specified value is ignored. + Kind *string + + // REQUIRED; Name of the animal + Name *string + + // REQUIRED; Whether the pet is trained + Trained *bool +} + +// GetAnimal implements the AnimalClassification interface for type Dog. +func (d *Dog) GetAnimal() *Animal { + return &Animal{ + Kind: d.Kind, + Name: d.Name, + } +} + +// GetPet implements the PetClassification interface for type Dog. +func (d *Dog) GetPet() *Pet { + return &Pet{ + Kind: d.Kind, + Name: d.Name, + Trained: d.Trained, + } +} + +type Pet struct { + // CONSTANT; Field has constant value "pet", any specified value is ignored. + Kind *string + + // REQUIRED; Name of the animal + Name *string + + // REQUIRED; Whether the pet is trained + Trained *bool +} + +// GetAnimal implements the AnimalClassification interface for type Pet. +func (p *Pet) GetAnimal() *Animal { + return &Animal{ + Kind: p.Kind, + Name: p.Name, + } +} + +// GetPet implements the PetClassification interface for type Pet. +func (p *Pet) GetPet() *Pet { return p } diff --git a/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_models_serde.go b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_models_serde.go new file mode 100644 index 000000000000..2275dc3fd190 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_models_serde.go @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package hierarchygroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type Animal. +func (a Animal) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "kind", a.Kind) + populate(objectMap, "name", a.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Animal. +func (a *Animal) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &a.Kind) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Dog. +func (d Dog) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "breed", d.Breed) + objectMap["kind"] = "dog" + populate(objectMap, "name", d.Name) + populate(objectMap, "trained", d.Trained) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Dog. +func (d *Dog) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "breed": + err = unpopulate(val, "Breed", &d.Breed) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &d.Kind) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "trained": + err = unpopulate(val, "Trained", &d.Trained) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Pet. +func (p Pet) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["kind"] = "pet" + populate(objectMap, "name", p.Name) + populate(objectMap, "trained", p.Trained) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Pet. +func (p *Pet) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &p.Kind) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "trained": + err = unpopulate(val, "Trained", &p.Trained) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_options.go b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_options.go new file mode 100644 index 000000000000..1211334a0ee1 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_options.go @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package hierarchygroup + +// HierarchyBuildingAnimalOperationsClientUpdateDogAsAnimalOptions contains the optional parameters for the HierarchyBuildingAnimalOperationsClient.UpdateDogAsAnimal +// method. +type HierarchyBuildingAnimalOperationsClientUpdateDogAsAnimalOptions struct { + // placeholder for future optional parameters +} + +// HierarchyBuildingAnimalOperationsClientUpdatePetAsAnimalOptions contains the optional parameters for the HierarchyBuildingAnimalOperationsClient.UpdatePetAsAnimal +// method. +type HierarchyBuildingAnimalOperationsClientUpdatePetAsAnimalOptions struct { + // placeholder for future optional parameters +} + +// HierarchyBuildingDogOperationsClientUpdateDogAsDogOptions contains the optional parameters for the HierarchyBuildingDogOperationsClient.UpdateDogAsDog +// method. +type HierarchyBuildingDogOperationsClientUpdateDogAsDogOptions struct { + // placeholder for future optional parameters +} + +// HierarchyBuildingPetOperationsClientUpdateDogAsPetOptions contains the optional parameters for the HierarchyBuildingPetOperationsClient.UpdateDogAsPet +// method. +type HierarchyBuildingPetOperationsClientUpdateDogAsPetOptions struct { + // placeholder for future optional parameters +} + +// HierarchyBuildingPetOperationsClientUpdatePetAsPetOptions contains the optional parameters for the HierarchyBuildingPetOperationsClient.UpdatePetAsPet +// method. +type HierarchyBuildingPetOperationsClientUpdatePetAsPetOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_polymorphic_helpers.go b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_polymorphic_helpers.go new file mode 100644 index 000000000000..fcc5e099ff25 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_polymorphic_helpers.go @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package hierarchygroup + +import "encoding/json" + +func unmarshalAnimalClassification(rawMsg json.RawMessage) (AnimalClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b AnimalClassification + switch m["kind"] { + case "dog": + b = &Dog{} + case "pet": + b = &Pet{} + default: + b = &Animal{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} + +func unmarshalPetClassification(rawMsg json.RawMessage) (PetClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b PetClassification + switch m["kind"] { + case "dog": + b = &Dog{} + default: + b = &Pet{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_responses.go b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_responses.go new file mode 100644 index 000000000000..c98764529bfc --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_responses.go @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package hierarchygroup + +// HierarchyBuildingAnimalOperationsClientUpdateDogAsAnimalResponse contains the response from method HierarchyBuildingAnimalOperationsClient.UpdateDogAsAnimal. +type HierarchyBuildingAnimalOperationsClientUpdateDogAsAnimalResponse struct { + AnimalClassification +} + +// HierarchyBuildingAnimalOperationsClientUpdatePetAsAnimalResponse contains the response from method HierarchyBuildingAnimalOperationsClient.UpdatePetAsAnimal. +type HierarchyBuildingAnimalOperationsClientUpdatePetAsAnimalResponse struct { + AnimalClassification +} + +// HierarchyBuildingDogOperationsClientUpdateDogAsDogResponse contains the response from method HierarchyBuildingDogOperationsClient.UpdateDogAsDog. +type HierarchyBuildingDogOperationsClientUpdateDogAsDogResponse struct { + Dog +} + +// HierarchyBuildingPetOperationsClientUpdateDogAsPetResponse contains the response from method HierarchyBuildingPetOperationsClient.UpdateDogAsPet. +type HierarchyBuildingPetOperationsClientUpdateDogAsPetResponse struct { + PetClassification +} + +// HierarchyBuildingPetOperationsClientUpdatePetAsPetResponse contains the response from method HierarchyBuildingPetOperationsClient.UpdatePetAsPet. +type HierarchyBuildingPetOperationsClientUpdatePetAsPetResponse struct { + PetClassification +} diff --git a/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_responses_serde.go b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_responses_serde.go new file mode 100644 index 000000000000..29769f9b6bec --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_responses_serde.go @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package hierarchygroup + +// UnmarshalJSON implements the json.Unmarshaller interface for type HierarchyBuildingAnimalOperationsClientUpdateDogAsAnimalResponse. +func (h *HierarchyBuildingAnimalOperationsClientUpdateDogAsAnimalResponse) UnmarshalJSON(data []byte) error { + res, err := unmarshalAnimalClassification(data) + if err != nil { + return err + } + h.AnimalClassification = res + return nil +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HierarchyBuildingAnimalOperationsClientUpdatePetAsAnimalResponse. +func (h *HierarchyBuildingAnimalOperationsClientUpdatePetAsAnimalResponse) UnmarshalJSON(data []byte) error { + res, err := unmarshalAnimalClassification(data) + if err != nil { + return err + } + h.AnimalClassification = res + return nil +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HierarchyBuildingPetOperationsClientUpdateDogAsPetResponse. +func (h *HierarchyBuildingPetOperationsClientUpdateDogAsPetResponse) UnmarshalJSON(data []byte) error { + res, err := unmarshalPetClassification(data) + if err != nil { + return err + } + h.PetClassification = res + return nil +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HierarchyBuildingPetOperationsClientUpdatePetAsPetResponse. +func (h *HierarchyBuildingPetOperationsClientUpdatePetAsPetResponse) UnmarshalJSON(data []byte) error { + res, err := unmarshalPetClassification(data) + if err != nil { + return err + } + h.PetClassification = res + return nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_version.go b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_version.go new file mode 100644 index 000000000000..75b627e98ba8 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/hierarchygroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package hierarchygroup + +const ( + moduleName = "hierarchygroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/LICENSE.txt b/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/fake/zz_internal.go b/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/fake/zz_internal.go new file mode 100644 index 000000000000..2f8b4aafab8d --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/fake/zz_internal.go @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/fake/zz_nextlinkverb_server.go b/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/fake/zz_nextlinkverb_server.go new file mode 100644 index 000000000000..05c8f8566c4e --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/fake/zz_nextlinkverb_server.go @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "nextlinkverbgroup" + "slices" +) + +// NextLinkVerbServer is a fake server for instances of the nextlinkverbgroup.NextLinkVerbClient type. +type NextLinkVerbServer struct { + // NewListItemsPager is the fake for method NextLinkVerbClient.NewListItemsPager + // HTTP status codes to indicate success: http.StatusOK + NewListItemsPager func(options *nextlinkverbgroup.NextLinkVerbClientListItemsOptions) (resp azfake.PagerResponder[nextlinkverbgroup.NextLinkVerbClientListItemsResponse]) +} + +// NewNextLinkVerbServerTransport creates a new instance of NextLinkVerbServerTransport with the provided implementation. +// The returned NextLinkVerbServerTransport instance is connected to an instance of nextlinkverbgroup.NextLinkVerbClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewNextLinkVerbServerTransport(srv *NextLinkVerbServer) *NextLinkVerbServerTransport { + return &NextLinkVerbServerTransport{ + srv: srv, + newListItemsPager: newTracker[azfake.PagerResponder[nextlinkverbgroup.NextLinkVerbClientListItemsResponse]](), + } +} + +// NextLinkVerbServerTransport connects instances of nextlinkverbgroup.NextLinkVerbClient to instances of NextLinkVerbServer. +// Don't use this type directly, use NewNextLinkVerbServerTransport instead. +type NextLinkVerbServerTransport struct { + srv *NextLinkVerbServer + newListItemsPager *tracker[azfake.PagerResponder[nextlinkverbgroup.NextLinkVerbClientListItemsResponse]] +} + +// Do implements the policy.Transporter interface for NextLinkVerbServerTransport. +func (n *NextLinkVerbServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return n.dispatchToMethodFake(req, method) +} + +func (n *NextLinkVerbServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if nextLinkVerbServerTransportInterceptor != nil { + res.resp, res.err, intercepted = nextLinkVerbServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "NextLinkVerbClient.NewListItemsPager": + res.resp, res.err = n.dispatchNewListItemsPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (n *NextLinkVerbServerTransport) dispatchNewListItemsPager(req *http.Request) (*http.Response, error) { + if n.srv.NewListItemsPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListItemsPager not implemented")} + } + newListItemsPager := n.newListItemsPager.get(req) + if newListItemsPager == nil { + resp := n.srv.NewListItemsPager(nil) + newListItemsPager = &resp + n.newListItemsPager.add(req, newListItemsPager) + server.PagerResponderInjectNextLinks(newListItemsPager, req, func(page *nextlinkverbgroup.NextLinkVerbClientListItemsResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListItemsPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + n.newListItemsPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListItemsPager) { + n.newListItemsPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to NextLinkVerbServerTransport +var nextLinkVerbServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/go.mod b/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/go.mod new file mode 100644 index 000000000000..79682cc37dbc --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/go.mod @@ -0,0 +1,17 @@ +module nextlinkverbgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/go.sum b/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/nextlinkverb_client_test.go b/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/nextlinkverb_client_test.go new file mode 100644 index 000000000000..ef348b763616 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/nextlinkverb_client_test.go @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package nextlinkverbgroup_test + +import ( + "context" + "nextlinkverbgroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestNewListItemsPager(t *testing.T) { + client, err := nextlinkverbgroup.NewNextLinkVerbClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + pager := client.NewListItemsPager(nil) + pageCount := 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + pageCount++ + switch pageCount { + case 1: + require.Len(t, page.Items, 1) + require.Equal(t, nextlinkverbgroup.Test{ID: to.Ptr("test1")}, page.Items[0]) + require.NotNil(t, page.NextLink) + case 2: + require.Len(t, page.Items, 1) + require.Equal(t, nextlinkverbgroup.Test{ID: to.Ptr("test2")}, page.Items[0]) + require.Nil(t, page.NextLink) + default: + t.Fatalf("unexpected page number %d", pageCount) + } + } + require.EqualValues(t, 2, pageCount) +} diff --git a/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/testdata/_metadata.json b/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/zz_models.go b/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/zz_models.go new file mode 100644 index 000000000000..f21145462495 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/zz_models.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nextlinkverbgroup + +// ListTestResult - Paged response model. +type ListTestResult struct { + // REQUIRED; List of items. + Items []Test + + // Link to fetch more items. + NextLink *string +} + +// Test model. +type Test struct { + // REQUIRED; The id of the test. + ID *string +} diff --git a/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/zz_models_serde.go b/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/zz_models_serde.go new file mode 100644 index 000000000000..632ad6004868 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/zz_models_serde.go @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nextlinkverbgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type ListTestResult. +func (l ListTestResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "items", l.Items) + populate(objectMap, "nextLink", l.NextLink) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ListTestResult. +func (l *ListTestResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "items": + err = unpopulate(val, "Items", &l.Items) + delete(rawMsg, key) + case "nextLink": + err = unpopulate(val, "NextLink", &l.NextLink) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Test. +func (t Test) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", t.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Test. +func (t *Test) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &t.ID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/zz_nextlinkverb_client.go b/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/zz_nextlinkverb_client.go new file mode 100644 index 000000000000..15387fce8e69 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/zz_nextlinkverb_client.go @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nextlinkverbgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// NextLinkVerbClient - Test for @nextLinkVerb decorator. +// Don't use this type directly, use NewNextLinkVerbClientWithNoCredential() instead. +type NextLinkVerbClient struct { + internal *azcore.Client + endpoint string +} + +// NextLinkVerbClientOptions contains the optional values for creating a [NextLinkVerbClient]. +type NextLinkVerbClientOptions struct { + azcore.ClientOptions +} + +// NewNextLinkVerbClientWithNoCredential creates a new instance of NextLinkVerbClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewNextLinkVerbClientWithNoCredential(endpoint string, options *NextLinkVerbClientOptions) (*NextLinkVerbClient, error) { + if options == nil { + options = &NextLinkVerbClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &NextLinkVerbClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// - options - NextLinkVerbClientListItemsOptions contains the optional parameters for the NextLinkVerbClient.NewListItemsPager +// method. +func (client *NextLinkVerbClient) NewListItemsPager(options *NextLinkVerbClientListItemsOptions) *runtime.Pager[NextLinkVerbClientListItemsResponse] { + return runtime.NewPager(runtime.PagingHandler[NextLinkVerbClientListItemsResponse]{ + More: func(page NextLinkVerbClientListItemsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *NextLinkVerbClientListItemsResponse) (NextLinkVerbClientListItemsResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "NextLinkVerbClient.NewListItemsPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listItemsCreateRequest(ctx, options) + }, &runtime.FetcherForNextLinkOptions{ + HTTPVerb: http.MethodPost, + }) + if err != nil { + return NextLinkVerbClientListItemsResponse{}, err + } + return client.listItemsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listItemsCreateRequest creates the ListItems request. +func (client *NextLinkVerbClient) listItemsCreateRequest(ctx context.Context, _ *NextLinkVerbClientListItemsOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/next-link-verb/items" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listItemsHandleResponse handles the ListItems response. +func (client *NextLinkVerbClient) listItemsHandleResponse(resp *http.Response) (NextLinkVerbClientListItemsResponse, error) { + result := NextLinkVerbClientListItemsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListTestResult); err != nil { + return NextLinkVerbClientListItemsResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/zz_options.go b/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/zz_options.go new file mode 100644 index 000000000000..a5fe3e017023 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/zz_options.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nextlinkverbgroup + +// NextLinkVerbClientListItemsOptions contains the optional parameters for the NextLinkVerbClient.NewListItemsPager method. +type NextLinkVerbClientListItemsOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/zz_responses.go b/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/zz_responses.go new file mode 100644 index 000000000000..d0dd4a511315 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/zz_responses.go @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nextlinkverbgroup + +// NextLinkVerbClientListItemsResponse contains the response from method NextLinkVerbClient.NewListItemsPager. +type NextLinkVerbClientListItemsResponse struct { + // Paged response model. + ListTestResult +} diff --git a/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/zz_version.go b/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/zz_version.go new file mode 100644 index 000000000000..c72d89c2c435 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/nextlinkverbgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package nextlinkverbgroup + +const ( + moduleName = "nextlinkverbgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/client-generator-core/overridegroup/LICENSE.txt b/test/azure-http-specs/azure/client-generator-core/overridegroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/overridegroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/client-generator-core/overridegroup/fake/zz_internal.go b/test/azure-http-specs/azure/client-generator-core/overridegroup/fake/zz_internal.go new file mode 100644 index 000000000000..35b717171f62 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/overridegroup/fake/zz_internal.go @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "reflect" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getOptional[T any](v T) *T { + if reflect.ValueOf(v).IsZero() { + return nil + } + return &v +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/azure-http-specs/azure/client-generator-core/overridegroup/fake/zz_override_server.go b/test/azure-http-specs/azure/client-generator-core/overridegroup/fake/zz_override_server.go new file mode 100644 index 000000000000..5371b939eed7 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/overridegroup/fake/zz_override_server.go @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// OverrideServer is a fake server for instances of the overridegroup.OverrideClient type. +type OverrideServer struct { + // OverrideGroupParametersServer contains the fakes for client OverrideGroupParametersClient + OverrideGroupParametersServer OverrideGroupParametersServer + + // OverrideRemoveOptionalParameterServer contains the fakes for client OverrideRemoveOptionalParameterClient + OverrideRemoveOptionalParameterServer OverrideRemoveOptionalParameterServer + + // OverrideReorderParametersServer contains the fakes for client OverrideReorderParametersClient + OverrideReorderParametersServer OverrideReorderParametersServer + + // OverrideRequireOptionalParameterServer contains the fakes for client OverrideRequireOptionalParameterClient + OverrideRequireOptionalParameterServer OverrideRequireOptionalParameterServer +} + +// NewOverrideServerTransport creates a new instance of OverrideServerTransport with the provided implementation. +// The returned OverrideServerTransport instance is connected to an instance of overridegroup.OverrideClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOverrideServerTransport(srv *OverrideServer) *OverrideServerTransport { + return &OverrideServerTransport{srv: srv} +} + +// OverrideServerTransport connects instances of overridegroup.OverrideClient to instances of OverrideServer. +// Don't use this type directly, use NewOverrideServerTransport instead. +type OverrideServerTransport struct { + srv *OverrideServer + trMu sync.Mutex + trOverrideGroupParametersServer *OverrideGroupParametersServerTransport + trOverrideRemoveOptionalParameterServer *OverrideRemoveOptionalParameterServerTransport + trOverrideReorderParametersServer *OverrideReorderParametersServerTransport + trOverrideRequireOptionalParameterServer *OverrideRequireOptionalParameterServerTransport +} + +// Do implements the policy.Transporter interface for OverrideServerTransport. +func (o *OverrideServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (o *OverrideServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "OverrideGroupParametersClient": + initServer(&o.trMu, &o.trOverrideGroupParametersServer, func() *OverrideGroupParametersServerTransport { + return NewOverrideGroupParametersServerTransport(&o.srv.OverrideGroupParametersServer) + }) + resp, err = o.trOverrideGroupParametersServer.Do(req) + case "OverrideRemoveOptionalParameterClient": + initServer(&o.trMu, &o.trOverrideRemoveOptionalParameterServer, func() *OverrideRemoveOptionalParameterServerTransport { + return NewOverrideRemoveOptionalParameterServerTransport(&o.srv.OverrideRemoveOptionalParameterServer) + }) + resp, err = o.trOverrideRemoveOptionalParameterServer.Do(req) + case "OverrideReorderParametersClient": + initServer(&o.trMu, &o.trOverrideReorderParametersServer, func() *OverrideReorderParametersServerTransport { + return NewOverrideReorderParametersServerTransport(&o.srv.OverrideReorderParametersServer) + }) + resp, err = o.trOverrideReorderParametersServer.Do(req) + case "OverrideRequireOptionalParameterClient": + initServer(&o.trMu, &o.trOverrideRequireOptionalParameterServer, func() *OverrideRequireOptionalParameterServerTransport { + return NewOverrideRequireOptionalParameterServerTransport(&o.srv.OverrideRequireOptionalParameterServer) + }) + resp, err = o.trOverrideRequireOptionalParameterServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to OverrideServerTransport +var overrideServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/overridegroup/fake/zz_overridegroupparameters_server.go b/test/azure-http-specs/azure/client-generator-core/overridegroup/fake/zz_overridegroupparameters_server.go new file mode 100644 index 000000000000..b5139672a553 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/overridegroup/fake/zz_overridegroupparameters_server.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "overridegroup" + "slices" +) + +// OverrideGroupParametersServer is a fake server for instances of the overridegroup.OverrideGroupParametersClient type. +type OverrideGroupParametersServer struct { + // Group is the fake for method OverrideGroupParametersClient.Group + // HTTP status codes to indicate success: http.StatusNoContent + Group func(ctx context.Context, options overridegroup.GroupParametersOptions, opts *overridegroup.OverrideGroupParametersClientGroupOptions) (resp azfake.Responder[overridegroup.OverrideGroupParametersClientGroupResponse], errResp azfake.ErrorResponder) +} + +// NewOverrideGroupParametersServerTransport creates a new instance of OverrideGroupParametersServerTransport with the provided implementation. +// The returned OverrideGroupParametersServerTransport instance is connected to an instance of overridegroup.OverrideGroupParametersClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOverrideGroupParametersServerTransport(srv *OverrideGroupParametersServer) *OverrideGroupParametersServerTransport { + return &OverrideGroupParametersServerTransport{srv: srv} +} + +// OverrideGroupParametersServerTransport connects instances of overridegroup.OverrideGroupParametersClient to instances of OverrideGroupParametersServer. +// Don't use this type directly, use NewOverrideGroupParametersServerTransport instead. +type OverrideGroupParametersServerTransport struct { + srv *OverrideGroupParametersServer +} + +// Do implements the policy.Transporter interface for OverrideGroupParametersServerTransport. +func (o *OverrideGroupParametersServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OverrideGroupParametersServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if overrideGroupParametersServerTransportInterceptor != nil { + res.resp, res.err, intercepted = overrideGroupParametersServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OverrideGroupParametersClient.Group": + res.resp, res.err = o.dispatchGroup(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OverrideGroupParametersServerTransport) dispatchGroup(req *http.Request) (*http.Response, error) { + if o.srv.Group == nil { + return nil, &nonRetriableError{errors.New("fake for method Group not implemented")} + } + qp := req.URL.Query() + options := overridegroup.GroupParametersOptions{ + Param1: qp.Get("param1"), + Param2: qp.Get("param2"), + } + respr, errRespr := o.srv.Group(req.Context(), options, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OverrideGroupParametersServerTransport +var overrideGroupParametersServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/overridegroup/fake/zz_overrideremoveoptionalparameter_server.go b/test/azure-http-specs/azure/client-generator-core/overridegroup/fake/zz_overrideremoveoptionalparameter_server.go new file mode 100644 index 000000000000..02dea3f16cc9 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/overridegroup/fake/zz_overrideremoveoptionalparameter_server.go @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "overridegroup" + "regexp" + "slices" +) + +// OverrideRemoveOptionalParameterServer is a fake server for instances of the overridegroup.OverrideRemoveOptionalParameterClient type. +type OverrideRemoveOptionalParameterServer struct { + // RemoveOptional is the fake for method OverrideRemoveOptionalParameterClient.RemoveOptional + // HTTP status codes to indicate success: http.StatusNoContent + RemoveOptional func(ctx context.Context, param1 string, options *overridegroup.OverrideRemoveOptionalParameterClientRemoveOptionalOptions) (resp azfake.Responder[overridegroup.OverrideRemoveOptionalParameterClientRemoveOptionalResponse], errResp azfake.ErrorResponder) +} + +// NewOverrideRemoveOptionalParameterServerTransport creates a new instance of OverrideRemoveOptionalParameterServerTransport with the provided implementation. +// The returned OverrideRemoveOptionalParameterServerTransport instance is connected to an instance of overridegroup.OverrideRemoveOptionalParameterClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOverrideRemoveOptionalParameterServerTransport(srv *OverrideRemoveOptionalParameterServer) *OverrideRemoveOptionalParameterServerTransport { + return &OverrideRemoveOptionalParameterServerTransport{srv: srv} +} + +// OverrideRemoveOptionalParameterServerTransport connects instances of overridegroup.OverrideRemoveOptionalParameterClient to instances of OverrideRemoveOptionalParameterServer. +// Don't use this type directly, use NewOverrideRemoveOptionalParameterServerTransport instead. +type OverrideRemoveOptionalParameterServerTransport struct { + srv *OverrideRemoveOptionalParameterServer +} + +// Do implements the policy.Transporter interface for OverrideRemoveOptionalParameterServerTransport. +func (o *OverrideRemoveOptionalParameterServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OverrideRemoveOptionalParameterServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if overrideRemoveOptionalParameterServerTransportInterceptor != nil { + res.resp, res.err, intercepted = overrideRemoveOptionalParameterServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OverrideRemoveOptionalParameterClient.RemoveOptional": + res.resp, res.err = o.dispatchRemoveOptional(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OverrideRemoveOptionalParameterServerTransport) dispatchRemoveOptional(req *http.Request) (*http.Response, error) { + if o.srv.RemoveOptional == nil { + return nil, &nonRetriableError{errors.New("fake for method RemoveOptional not implemented")} + } + const regexStr = `/azure/client-generator-core/override/remove-optional/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + param1Param, err := url.PathUnescape(matches[regex.SubexpIndex("param1")]) + if err != nil { + return nil, err + } + param2Param := getOptional(qp.Get("param2")) + var options *overridegroup.OverrideRemoveOptionalParameterClientRemoveOptionalOptions + if param2Param != nil { + options = &overridegroup.OverrideRemoveOptionalParameterClientRemoveOptionalOptions{ + Param2: param2Param, + } + } + respr, errRespr := o.srv.RemoveOptional(req.Context(), param1Param, options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OverrideRemoveOptionalParameterServerTransport +var overrideRemoveOptionalParameterServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/overridegroup/fake/zz_overridereorderparameters_server.go b/test/azure-http-specs/azure/client-generator-core/overridegroup/fake/zz_overridereorderparameters_server.go new file mode 100644 index 000000000000..1a636bc5f7de --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/overridegroup/fake/zz_overridereorderparameters_server.go @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "overridegroup" + "regexp" + "slices" +) + +// OverrideReorderParametersServer is a fake server for instances of the overridegroup.OverrideReorderParametersClient type. +type OverrideReorderParametersServer struct { + // Reorder is the fake for method OverrideReorderParametersClient.Reorder + // HTTP status codes to indicate success: http.StatusNoContent + Reorder func(ctx context.Context, param1 string, param2 string, options *overridegroup.OverrideReorderParametersClientReorderOptions) (resp azfake.Responder[overridegroup.OverrideReorderParametersClientReorderResponse], errResp azfake.ErrorResponder) +} + +// NewOverrideReorderParametersServerTransport creates a new instance of OverrideReorderParametersServerTransport with the provided implementation. +// The returned OverrideReorderParametersServerTransport instance is connected to an instance of overridegroup.OverrideReorderParametersClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOverrideReorderParametersServerTransport(srv *OverrideReorderParametersServer) *OverrideReorderParametersServerTransport { + return &OverrideReorderParametersServerTransport{srv: srv} +} + +// OverrideReorderParametersServerTransport connects instances of overridegroup.OverrideReorderParametersClient to instances of OverrideReorderParametersServer. +// Don't use this type directly, use NewOverrideReorderParametersServerTransport instead. +type OverrideReorderParametersServerTransport struct { + srv *OverrideReorderParametersServer +} + +// Do implements the policy.Transporter interface for OverrideReorderParametersServerTransport. +func (o *OverrideReorderParametersServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OverrideReorderParametersServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if overrideReorderParametersServerTransportInterceptor != nil { + res.resp, res.err, intercepted = overrideReorderParametersServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OverrideReorderParametersClient.Reorder": + res.resp, res.err = o.dispatchReorder(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OverrideReorderParametersServerTransport) dispatchReorder(req *http.Request) (*http.Response, error) { + if o.srv.Reorder == nil { + return nil, &nonRetriableError{errors.New("fake for method Reorder not implemented")} + } + const regexStr = `/azure/client-generator-core/override/reorder/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + param1Param, err := url.PathUnescape(matches[regex.SubexpIndex("param1")]) + if err != nil { + return nil, err + } + param2Param, err := url.PathUnescape(matches[regex.SubexpIndex("param2")]) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.Reorder(req.Context(), param1Param, param2Param, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OverrideReorderParametersServerTransport +var overrideReorderParametersServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/overridegroup/fake/zz_overriderequireoptionalparameter_server.go b/test/azure-http-specs/azure/client-generator-core/overridegroup/fake/zz_overriderequireoptionalparameter_server.go new file mode 100644 index 000000000000..e66e7058a016 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/overridegroup/fake/zz_overriderequireoptionalparameter_server.go @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "overridegroup" + "regexp" + "slices" +) + +// OverrideRequireOptionalParameterServer is a fake server for instances of the overridegroup.OverrideRequireOptionalParameterClient type. +type OverrideRequireOptionalParameterServer struct { + // RequireOptional is the fake for method OverrideRequireOptionalParameterClient.RequireOptional + // HTTP status codes to indicate success: http.StatusNoContent + RequireOptional func(ctx context.Context, param1 string, param2 string, options *overridegroup.OverrideRequireOptionalParameterClientRequireOptionalOptions) (resp azfake.Responder[overridegroup.OverrideRequireOptionalParameterClientRequireOptionalResponse], errResp azfake.ErrorResponder) +} + +// NewOverrideRequireOptionalParameterServerTransport creates a new instance of OverrideRequireOptionalParameterServerTransport with the provided implementation. +// The returned OverrideRequireOptionalParameterServerTransport instance is connected to an instance of overridegroup.OverrideRequireOptionalParameterClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOverrideRequireOptionalParameterServerTransport(srv *OverrideRequireOptionalParameterServer) *OverrideRequireOptionalParameterServerTransport { + return &OverrideRequireOptionalParameterServerTransport{srv: srv} +} + +// OverrideRequireOptionalParameterServerTransport connects instances of overridegroup.OverrideRequireOptionalParameterClient to instances of OverrideRequireOptionalParameterServer. +// Don't use this type directly, use NewOverrideRequireOptionalParameterServerTransport instead. +type OverrideRequireOptionalParameterServerTransport struct { + srv *OverrideRequireOptionalParameterServer +} + +// Do implements the policy.Transporter interface for OverrideRequireOptionalParameterServerTransport. +func (o *OverrideRequireOptionalParameterServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OverrideRequireOptionalParameterServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if overrideRequireOptionalParameterServerTransportInterceptor != nil { + res.resp, res.err, intercepted = overrideRequireOptionalParameterServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OverrideRequireOptionalParameterClient.RequireOptional": + res.resp, res.err = o.dispatchRequireOptional(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OverrideRequireOptionalParameterServerTransport) dispatchRequireOptional(req *http.Request) (*http.Response, error) { + if o.srv.RequireOptional == nil { + return nil, &nonRetriableError{errors.New("fake for method RequireOptional not implemented")} + } + const regexStr = `/azure/client-generator-core/override/require-optional/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + param1Param, err := url.PathUnescape(matches[regex.SubexpIndex("param1")]) + if err != nil { + return nil, err + } + param2Param, err := url.PathUnescape(matches[regex.SubexpIndex("param2")]) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.RequireOptional(req.Context(), param1Param, param2Param, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OverrideRequireOptionalParameterServerTransport +var overrideRequireOptionalParameterServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/client-generator-core/overridegroup/go.mod b/test/azure-http-specs/azure/client-generator-core/overridegroup/go.mod new file mode 100644 index 000000000000..85c4361ad22e --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/overridegroup/go.mod @@ -0,0 +1,17 @@ +module overridegroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/client-generator-core/overridegroup/go.sum b/test/azure-http-specs/azure/client-generator-core/overridegroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/overridegroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/client-generator-core/overridegroup/overridegroupparameters_client_test.go b/test/azure-http-specs/azure/client-generator-core/overridegroup/overridegroupparameters_client_test.go new file mode 100644 index 000000000000..7c9c3ea841c8 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/overridegroup/overridegroupparameters_client_test.go @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package overridegroup_test + +import ( + "context" + "overridegroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestOverrideGroupParametersClient_Group(t *testing.T) { + client, err := overridegroup.NewOverrideClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOverrideGroupParametersClient().Group(context.Background(), overridegroup.GroupParametersOptions{ + Param1: "param1", + Param2: "param2", + }, &overridegroup.OverrideGroupParametersClientGroupOptions{}) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/azure/client-generator-core/overridegroup/overrideremoveoptionalparameter_test.go b/test/azure-http-specs/azure/client-generator-core/overridegroup/overrideremoveoptionalparameter_test.go new file mode 100644 index 000000000000..5dac228742bc --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/overridegroup/overrideremoveoptionalparameter_test.go @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package overridegroup_test + +import ( + "context" + "overridegroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestOverrideRemoveOptionalParametersClient_Group(t *testing.T) { + client, err := overridegroup.NewOverrideClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOverrideRemoveOptionalParameterClient().RemoveOptional(context.Background(), "param1", &overridegroup.OverrideRemoveOptionalParameterClientRemoveOptionalOptions{to.Ptr("param2")}) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/azure/client-generator-core/overridegroup/overridereorderparameters_client_test.go b/test/azure-http-specs/azure/client-generator-core/overridegroup/overridereorderparameters_client_test.go new file mode 100644 index 000000000000..d1acd3ced83b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/overridegroup/overridereorderparameters_client_test.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package overridegroup_test + +import ( + "context" + "overridegroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestOverrideReorderParametersClient_Reorder(t *testing.T) { + client, err := overridegroup.NewOverrideClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOverrideReorderParametersClient().Reorder(context.Background(), "param1", "param2", &overridegroup.OverrideReorderParametersClientReorderOptions{}) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/azure/client-generator-core/overridegroup/overriderequireoptionalparameter_test.go b/test/azure-http-specs/azure/client-generator-core/overridegroup/overriderequireoptionalparameter_test.go new file mode 100644 index 000000000000..0ba50eb1f75b --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/overridegroup/overriderequireoptionalparameter_test.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package overridegroup_test + +import ( + "context" + "overridegroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestOverrideRequireOptionalParametersClient_Group(t *testing.T) { + client, err := overridegroup.NewOverrideClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOverrideRequireOptionalParameterClient().RequireOptional(context.Background(), "param1", "param2", &overridegroup.OverrideRequireOptionalParameterClientRequireOptionalOptions{}) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/azure/client-generator-core/overridegroup/testdata/_metadata.json b/test/azure-http-specs/azure/client-generator-core/overridegroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/overridegroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/client-generator-core/overridegroup/zz_options.go b/test/azure-http-specs/azure/client-generator-core/overridegroup/zz_options.go new file mode 100644 index 000000000000..f0a0c0de26b7 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/overridegroup/zz_options.go @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package overridegroup + +// GroupParametersOptions contains a group of parameters for the OverrideGroupParametersClient.Group method. +type GroupParametersOptions struct { + Param1 string + Param2 string +} + +// OverrideGroupParametersClientGroupOptions contains the optional parameters for the OverrideGroupParametersClient.Group +// method. +type OverrideGroupParametersClientGroupOptions struct { + // placeholder for future optional parameters +} + +// OverrideRemoveOptionalParameterClientRemoveOptionalOptions contains the optional parameters for the OverrideRemoveOptionalParameterClient.RemoveOptional +// method. +type OverrideRemoveOptionalParameterClientRemoveOptionalOptions struct { + Param2 *string +} + +// OverrideReorderParametersClientReorderOptions contains the optional parameters for the OverrideReorderParametersClient.Reorder +// method. +type OverrideReorderParametersClientReorderOptions struct { + // placeholder for future optional parameters +} + +// OverrideRequireOptionalParameterClientRequireOptionalOptions contains the optional parameters for the OverrideRequireOptionalParameterClient.RequireOptional +// method. +type OverrideRequireOptionalParameterClientRequireOptionalOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/azure/client-generator-core/overridegroup/zz_override_client.go b/test/azure-http-specs/azure/client-generator-core/overridegroup/zz_override_client.go new file mode 100644 index 000000000000..e74875fa1ebd --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/overridegroup/zz_override_client.go @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package overridegroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// OverrideClient - Test scenarios for client override behavior. +// Don't use this type directly, use NewOverrideClientWithNoCredential() instead. +type OverrideClient struct { + internal *azcore.Client + endpoint string +} + +// OverrideClientOptions contains the optional values for creating a [OverrideClient]. +type OverrideClientOptions struct { + azcore.ClientOptions +} + +// NewOverrideClientWithNoCredential creates a new instance of OverrideClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewOverrideClientWithNoCredential(endpoint string, options *OverrideClientOptions) (*OverrideClient, error) { + if options == nil { + options = &OverrideClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &OverrideClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewOverrideGroupParametersClient creates a new instance of [OverrideGroupParametersClient]. +func (client *OverrideClient) NewOverrideGroupParametersClient() *OverrideGroupParametersClient { + return &OverrideGroupParametersClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewOverrideRemoveOptionalParameterClient creates a new instance of [OverrideRemoveOptionalParameterClient]. +func (client *OverrideClient) NewOverrideRemoveOptionalParameterClient() *OverrideRemoveOptionalParameterClient { + return &OverrideRemoveOptionalParameterClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewOverrideReorderParametersClient creates a new instance of [OverrideReorderParametersClient]. +func (client *OverrideClient) NewOverrideReorderParametersClient() *OverrideReorderParametersClient { + return &OverrideReorderParametersClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewOverrideRequireOptionalParameterClient creates a new instance of [OverrideRequireOptionalParameterClient]. +func (client *OverrideClient) NewOverrideRequireOptionalParameterClient() *OverrideRequireOptionalParameterClient { + return &OverrideRequireOptionalParameterClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/azure-http-specs/azure/client-generator-core/overridegroup/zz_overridegroupparameters_client.go b/test/azure-http-specs/azure/client-generator-core/overridegroup/zz_overridegroupparameters_client.go new file mode 100644 index 000000000000..9abd64dc9f47 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/overridegroup/zz_overridegroupparameters_client.go @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package overridegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// OverrideGroupParametersClient contains the methods for the OverrideGroupParameters group. +// Don't use this type directly, use [OverrideClient.NewOverrideGroupParametersClient] instead. +type OverrideGroupParametersClient struct { + internal *azcore.Client + endpoint string +} + +// Group - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - GroupParametersOptions contains a group of parameters for the OverrideGroupParametersClient.Group method. +// - opts - OverrideGroupParametersClientGroupOptions contains the optional parameters for the OverrideGroupParametersClient.Group +// method. +func (client *OverrideGroupParametersClient) Group(ctx context.Context, options GroupParametersOptions, opts *OverrideGroupParametersClientGroupOptions) (OverrideGroupParametersClientGroupResponse, error) { + var err error + const operationName = "OverrideGroupParametersClient.Group" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.groupCreateRequest(ctx, options, opts) + if err != nil { + return OverrideGroupParametersClientGroupResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OverrideGroupParametersClientGroupResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OverrideGroupParametersClientGroupResponse{}, err + } + return OverrideGroupParametersClientGroupResponse{}, nil +} + +// groupCreateRequest creates the Group request. +func (client *OverrideGroupParametersClient) groupCreateRequest(ctx context.Context, options GroupParametersOptions, _ *OverrideGroupParametersClientGroupOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/override/group" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("param1", options.Param1) + reqQP.Set("param2", options.Param2) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/overridegroup/zz_overrideremoveoptionalparameter_client.go b/test/azure-http-specs/azure/client-generator-core/overridegroup/zz_overrideremoveoptionalparameter_client.go new file mode 100644 index 000000000000..393e05678d5d --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/overridegroup/zz_overrideremoveoptionalparameter_client.go @@ -0,0 +1,67 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package overridegroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// OverrideRemoveOptionalParameterClient contains the methods for the OverrideRemoveOptionalParameter group. +// Don't use this type directly, use [OverrideClient.NewOverrideRemoveOptionalParameterClient] instead. +type OverrideRemoveOptionalParameterClient struct { + internal *azcore.Client + endpoint string +} + +// RemoveOptional - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OverrideRemoveOptionalParameterClientRemoveOptionalOptions contains the optional parameters for the OverrideRemoveOptionalParameterClient.RemoveOptional +// method. +func (client *OverrideRemoveOptionalParameterClient) RemoveOptional(ctx context.Context, param1 string, options *OverrideRemoveOptionalParameterClientRemoveOptionalOptions) (OverrideRemoveOptionalParameterClientRemoveOptionalResponse, error) { + var err error + const operationName = "OverrideRemoveOptionalParameterClient.RemoveOptional" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.removeOptionalCreateRequest(ctx, param1, options) + if err != nil { + return OverrideRemoveOptionalParameterClientRemoveOptionalResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OverrideRemoveOptionalParameterClientRemoveOptionalResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OverrideRemoveOptionalParameterClientRemoveOptionalResponse{}, err + } + return OverrideRemoveOptionalParameterClientRemoveOptionalResponse{}, nil +} + +// removeOptionalCreateRequest creates the RemoveOptional request. +func (client *OverrideRemoveOptionalParameterClient) removeOptionalCreateRequest(ctx context.Context, param1 string, options *OverrideRemoveOptionalParameterClientRemoveOptionalOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/override/remove-optional/{param1}" + if param1 == "" { + return nil, errors.New("parameter param1 cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{param1}", url.PathEscape(param1)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Param2 != nil { + reqQP.Set("param2", *options.Param2) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/overridegroup/zz_overridereorderparameters_client.go b/test/azure-http-specs/azure/client-generator-core/overridegroup/zz_overridereorderparameters_client.go new file mode 100644 index 000000000000..2c8593e26452 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/overridegroup/zz_overridereorderparameters_client.go @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package overridegroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// OverrideReorderParametersClient contains the methods for the OverrideReorderParameters group. +// Don't use this type directly, use [OverrideClient.NewOverrideReorderParametersClient] instead. +type OverrideReorderParametersClient struct { + internal *azcore.Client + endpoint string +} + +// Reorder - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OverrideReorderParametersClientReorderOptions contains the optional parameters for the OverrideReorderParametersClient.Reorder +// method. +func (client *OverrideReorderParametersClient) Reorder(ctx context.Context, param1 string, param2 string, options *OverrideReorderParametersClientReorderOptions) (OverrideReorderParametersClientReorderResponse, error) { + var err error + const operationName = "OverrideReorderParametersClient.Reorder" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.reorderCreateRequest(ctx, param1, param2, options) + if err != nil { + return OverrideReorderParametersClientReorderResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OverrideReorderParametersClientReorderResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OverrideReorderParametersClientReorderResponse{}, err + } + return OverrideReorderParametersClientReorderResponse{}, nil +} + +// reorderCreateRequest creates the Reorder request. +func (client *OverrideReorderParametersClient) reorderCreateRequest(ctx context.Context, param1 string, param2 string, _ *OverrideReorderParametersClientReorderOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/override/reorder/{param2}/{param1}" + if param1 == "" { + return nil, errors.New("parameter param1 cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{param1}", url.PathEscape(param1)) + if param2 == "" { + return nil, errors.New("parameter param2 cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{param2}", url.PathEscape(param2)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/overridegroup/zz_overriderequireoptionalparameter_client.go b/test/azure-http-specs/azure/client-generator-core/overridegroup/zz_overriderequireoptionalparameter_client.go new file mode 100644 index 000000000000..a0b6191b98ba --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/overridegroup/zz_overriderequireoptionalparameter_client.go @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package overridegroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// OverrideRequireOptionalParameterClient contains the methods for the OverrideRequireOptionalParameter group. +// Don't use this type directly, use [OverrideClient.NewOverrideRequireOptionalParameterClient] instead. +type OverrideRequireOptionalParameterClient struct { + internal *azcore.Client + endpoint string +} + +// RequireOptional - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OverrideRequireOptionalParameterClientRequireOptionalOptions contains the optional parameters for the OverrideRequireOptionalParameterClient.RequireOptional +// method. +func (client *OverrideRequireOptionalParameterClient) RequireOptional(ctx context.Context, param1 string, param2 string, options *OverrideRequireOptionalParameterClientRequireOptionalOptions) (OverrideRequireOptionalParameterClientRequireOptionalResponse, error) { + var err error + const operationName = "OverrideRequireOptionalParameterClient.RequireOptional" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.requireOptionalCreateRequest(ctx, param1, param2, options) + if err != nil { + return OverrideRequireOptionalParameterClientRequireOptionalResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OverrideRequireOptionalParameterClientRequireOptionalResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OverrideRequireOptionalParameterClientRequireOptionalResponse{}, err + } + return OverrideRequireOptionalParameterClientRequireOptionalResponse{}, nil +} + +// requireOptionalCreateRequest creates the RequireOptional request. +func (client *OverrideRequireOptionalParameterClient) requireOptionalCreateRequest(ctx context.Context, param1 string, param2 string, _ *OverrideRequireOptionalParameterClientRequireOptionalOptions) (*policy.Request, error) { + urlPath := "/azure/client-generator-core/override/require-optional/{param1}/{param2}" + if param1 == "" { + return nil, errors.New("parameter param1 cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{param1}", url.PathEscape(param1)) + if param2 == "" { + return nil, errors.New("parameter param2 cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{param2}", url.PathEscape(param2)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/azure/client-generator-core/overridegroup/zz_responses.go b/test/azure-http-specs/azure/client-generator-core/overridegroup/zz_responses.go new file mode 100644 index 000000000000..faebbf608807 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/overridegroup/zz_responses.go @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package overridegroup + +// OverrideGroupParametersClientGroupResponse contains the response from method OverrideGroupParametersClient.Group. +type OverrideGroupParametersClientGroupResponse struct { + // placeholder for future response values +} + +// OverrideRemoveOptionalParameterClientRemoveOptionalResponse contains the response from method OverrideRemoveOptionalParameterClient.RemoveOptional. +type OverrideRemoveOptionalParameterClientRemoveOptionalResponse struct { + // placeholder for future response values +} + +// OverrideReorderParametersClientReorderResponse contains the response from method OverrideReorderParametersClient.Reorder. +type OverrideReorderParametersClientReorderResponse struct { + // placeholder for future response values +} + +// OverrideRequireOptionalParameterClientRequireOptionalResponse contains the response from method OverrideRequireOptionalParameterClient.RequireOptional. +type OverrideRequireOptionalParameterClientRequireOptionalResponse struct { + // placeholder for future response values +} diff --git a/test/azure-http-specs/azure/client-generator-core/overridegroup/zz_version.go b/test/azure-http-specs/azure/client-generator-core/overridegroup/zz_version.go new file mode 100644 index 000000000000..0cd498ab1b25 --- /dev/null +++ b/test/azure-http-specs/azure/client-generator-core/overridegroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package overridegroup + +const ( + moduleName = "overridegroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/core/azurepagegroup/LICENSE.txt b/test/azure-http-specs/azure/core/azurepagegroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/core/azurepagegroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/core/azurepagegroup/custom_client_test.go b/test/azure-http-specs/azure/core/azurepagegroup/custom_client_test.go new file mode 100644 index 000000000000..9b8dfac4fef4 --- /dev/null +++ b/test/azure-http-specs/azure/core/azurepagegroup/custom_client_test.go @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package azurepagegroup_test + +import ( + "azurepagegroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestPageClient_NewListWithCustomPageModelPager(t *testing.T) { + client, err := azurepagegroup.NewPageClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + pager := client.NewListWithCustomPageModelPager(nil) + pages := 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + require.EqualValues(t, []*azurepagegroup.User{ + { + ID: to.Ptr[int32](1), + Name: to.Ptr("Madge"), + Etag: to.Ptr[azcore.ETag]("11bdc430-65e8-45ad-81d9-8ffa60d55b59"), + }, + }, page.Items) + pages++ + } + require.EqualValues(t, 1, pages) +} + +func TestPageClient_NewListWithPagePager(t *testing.T) { + client, err := azurepagegroup.NewPageClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + pager := client.NewListWithPagePager(nil) + pages := 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + require.EqualValues(t, []*azurepagegroup.User{ + { + ID: to.Ptr[int32](1), + Name: to.Ptr("Madge"), + Etag: to.Ptr[azcore.ETag]("11bdc430-65e8-45ad-81d9-8ffa60d55b59"), + }, + }, page.Value) + pages++ + } + require.EqualValues(t, 1, pages) +} + +func TestPageClient_NewListWithParametersPager(t *testing.T) { + client, err := azurepagegroup.NewPageClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + pager := client.NewListWithParametersPager(azurepagegroup.ListItemInputBody{ + InputName: to.Ptr("Madge"), + }, &azurepagegroup.PageClientListWithParametersOptions{ + Another: to.Ptr(azurepagegroup.ListItemInputExtensibleEnumSecond), + }) + pages := 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + require.EqualValues(t, []*azurepagegroup.User{ + { + ID: to.Ptr[int32](1), + Name: to.Ptr("Madge"), + Etag: to.Ptr[azcore.ETag]("11bdc430-65e8-45ad-81d9-8ffa60d55b59"), + }, + }, page.Value) + pages++ + } + require.EqualValues(t, 1, pages) +} + +/*func TestPageClient_NewWithParameterizedNextLinkPager(t *testing.T) { + client, err := azurepagegroup.NewPageClient("http://localhost:3000", nil) + require.NoError(t, err) + pager := client.NewWithParameterizedNextLinkPager("name", &azurepagegroup.PageClientWithParameterizedNextLinkOptions{ + IncludePending: to.Ptr(true), + }) + pages := 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + pages++ + switch pages { + case 1: + require.EqualValues(t, []*azurepagegroup.User{ + { + ID: to.Ptr[int32](1), + Name: to.Ptr("User1"), + }, + }, page.Values) + case 2: + require.EqualValues(t, []*azurepagegroup.User{ + { + ID: to.Ptr[int32](2), + Name: to.Ptr("User2"), + }, + }, page.Values) + default: + t.Fatalf("unexpected page number %d", pages) + } + } + require.EqualValues(t, 2, pages) +}*/ + +// TODO: runtime.FetcherForNextLink doesn't support relative next link URLs +/*func TestPageClient_NewWithRelativeNextLinkPager(t *testing.T) { + client, err := azurepagegroup.NewPageClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + pager := client.NewWithRelativeNextLinkPager(nil) + pages := 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + pages++ + switch pages { + case 1: + require.EqualValues(t, []*azurepagegroup.User{ + { + ID: to.Ptr[int32](1), + Name: to.Ptr("User1"), + Etag: to.Ptr[azcore.ETag]("11bdc430-65e8-45ad-81d9-8ffa60d55b59"), + }, + }, page.Value) + case 2: + require.EqualValues(t, []*azurepagegroup.User{ + { + ID: to.Ptr[int32](2), + Name: to.Ptr("User2"), + Etag: to.Ptr[azcore.ETag]("11bdc430-65e8-45ad-81d9-8ffa60d55b59"), + }, + }, page.Value) + default: + t.Fatalf("unexpected page number %d", pages) + } + } + require.EqualValues(t, 2, pages) +}*/ diff --git a/test/azure-http-specs/azure/core/azurepagegroup/fake/zz_internal.go b/test/azure-http-specs/azure/core/azurepagegroup/fake/zz_internal.go new file mode 100644 index 000000000000..a5a90f7ae323 --- /dev/null +++ b/test/azure-http-specs/azure/core/azurepagegroup/fake/zz_internal.go @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "reflect" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getOptional[T any](v T) *T { + if reflect.ValueOf(v).IsZero() { + return nil + } + return &v +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/azure-http-specs/azure/core/azurepagegroup/fake/zz_page_server.go b/test/azure-http-specs/azure/core/azurepagegroup/fake/zz_page_server.go new file mode 100644 index 000000000000..18329a0817d9 --- /dev/null +++ b/test/azure-http-specs/azure/core/azurepagegroup/fake/zz_page_server.go @@ -0,0 +1,257 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "azurepagegroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "slices" + "strings" + "sync" +) + +// PageServer is a fake server for instances of the azurepagegroup.PageClient type. +type PageServer struct { + // PageTwoModelsAsPageItemServer contains the fakes for client PageTwoModelsAsPageItemClient + PageTwoModelsAsPageItemServer PageTwoModelsAsPageItemServer + + // NewListWithCustomPageModelPager is the fake for method PageClient.NewListWithCustomPageModelPager + // HTTP status codes to indicate success: http.StatusOK + NewListWithCustomPageModelPager func(options *azurepagegroup.PageClientListWithCustomPageModelOptions) (resp azfake.PagerResponder[azurepagegroup.PageClientListWithCustomPageModelResponse]) + + // NewListWithPagePager is the fake for method PageClient.NewListWithPagePager + // HTTP status codes to indicate success: http.StatusOK + NewListWithPagePager func(options *azurepagegroup.PageClientListWithPageOptions) (resp azfake.PagerResponder[azurepagegroup.PageClientListWithPageResponse]) + + // NewListWithParametersPager is the fake for method PageClient.NewListWithParametersPager + // HTTP status codes to indicate success: http.StatusOK + NewListWithParametersPager func(bodyInput azurepagegroup.ListItemInputBody, options *azurepagegroup.PageClientListWithParametersOptions) (resp azfake.PagerResponder[azurepagegroup.PageClientListWithParametersResponse]) + + // NewWithRelativeNextLinkPager is the fake for method PageClient.NewWithRelativeNextLinkPager + // HTTP status codes to indicate success: http.StatusOK + NewWithRelativeNextLinkPager func(options *azurepagegroup.PageClientWithRelativeNextLinkOptions) (resp azfake.PagerResponder[azurepagegroup.PageClientWithRelativeNextLinkResponse]) +} + +// NewPageServerTransport creates a new instance of PageServerTransport with the provided implementation. +// The returned PageServerTransport instance is connected to an instance of azurepagegroup.PageClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewPageServerTransport(srv *PageServer) *PageServerTransport { + return &PageServerTransport{ + srv: srv, + newListWithCustomPageModelPager: newTracker[azfake.PagerResponder[azurepagegroup.PageClientListWithCustomPageModelResponse]](), + newListWithPagePager: newTracker[azfake.PagerResponder[azurepagegroup.PageClientListWithPageResponse]](), + newListWithParametersPager: newTracker[azfake.PagerResponder[azurepagegroup.PageClientListWithParametersResponse]](), + newWithRelativeNextLinkPager: newTracker[azfake.PagerResponder[azurepagegroup.PageClientWithRelativeNextLinkResponse]](), + } +} + +// PageServerTransport connects instances of azurepagegroup.PageClient to instances of PageServer. +// Don't use this type directly, use NewPageServerTransport instead. +type PageServerTransport struct { + srv *PageServer + trMu sync.Mutex + trPageTwoModelsAsPageItemServer *PageTwoModelsAsPageItemServerTransport + newListWithCustomPageModelPager *tracker[azfake.PagerResponder[azurepagegroup.PageClientListWithCustomPageModelResponse]] + newListWithPagePager *tracker[azfake.PagerResponder[azurepagegroup.PageClientListWithPageResponse]] + newListWithParametersPager *tracker[azfake.PagerResponder[azurepagegroup.PageClientListWithParametersResponse]] + newWithRelativeNextLinkPager *tracker[azfake.PagerResponder[azurepagegroup.PageClientWithRelativeNextLinkResponse]] +} + +// Do implements the policy.Transporter interface for PageServerTransport. +func (p *PageServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + if client := method[:strings.Index(method, ".")]; client != "PageClient" { + return p.dispatchToClientFake(req, client) + } + return p.dispatchToMethodFake(req, method) +} + +func (p *PageServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "PageTwoModelsAsPageItemClient": + initServer(&p.trMu, &p.trPageTwoModelsAsPageItemServer, func() *PageTwoModelsAsPageItemServerTransport { + return NewPageTwoModelsAsPageItemServerTransport(&p.srv.PageTwoModelsAsPageItemServer) + }) + resp, err = p.trPageTwoModelsAsPageItemServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +func (p *PageServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if pageServerTransportInterceptor != nil { + res.resp, res.err, intercepted = pageServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "PageClient.NewListWithCustomPageModelPager": + res.resp, res.err = p.dispatchNewListWithCustomPageModelPager(req) + case "PageClient.NewListWithPagePager": + res.resp, res.err = p.dispatchNewListWithPagePager(req) + case "PageClient.NewListWithParametersPager": + res.resp, res.err = p.dispatchNewListWithParametersPager(req) + case "PageClient.NewWithRelativeNextLinkPager": + res.resp, res.err = p.dispatchNewWithRelativeNextLinkPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (p *PageServerTransport) dispatchNewListWithCustomPageModelPager(req *http.Request) (*http.Response, error) { + if p.srv.NewListWithCustomPageModelPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListWithCustomPageModelPager not implemented")} + } + newListWithCustomPageModelPager := p.newListWithCustomPageModelPager.get(req) + if newListWithCustomPageModelPager == nil { + resp := p.srv.NewListWithCustomPageModelPager(nil) + newListWithCustomPageModelPager = &resp + p.newListWithCustomPageModelPager.add(req, newListWithCustomPageModelPager) + server.PagerResponderInjectNextLinks(newListWithCustomPageModelPager, req, func(page *azurepagegroup.PageClientListWithCustomPageModelResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListWithCustomPageModelPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newListWithCustomPageModelPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListWithCustomPageModelPager) { + p.newListWithCustomPageModelPager.remove(req) + } + return resp, nil +} + +func (p *PageServerTransport) dispatchNewListWithPagePager(req *http.Request) (*http.Response, error) { + if p.srv.NewListWithPagePager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListWithPagePager not implemented")} + } + newListWithPagePager := p.newListWithPagePager.get(req) + if newListWithPagePager == nil { + resp := p.srv.NewListWithPagePager(nil) + newListWithPagePager = &resp + p.newListWithPagePager.add(req, newListWithPagePager) + server.PagerResponderInjectNextLinks(newListWithPagePager, req, func(page *azurepagegroup.PageClientListWithPageResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListWithPagePager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newListWithPagePager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListWithPagePager) { + p.newListWithPagePager.remove(req) + } + return resp, nil +} + +func (p *PageServerTransport) dispatchNewListWithParametersPager(req *http.Request) (*http.Response, error) { + if p.srv.NewListWithParametersPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListWithParametersPager not implemented")} + } + newListWithParametersPager := p.newListWithParametersPager.get(req) + if newListWithParametersPager == nil { + qp := req.URL.Query() + body, err := server.UnmarshalRequestAsJSON[azurepagegroup.ListItemInputBody](req) + if err != nil { + return nil, err + } + anotherParam := getOptional(azurepagegroup.ListItemInputExtensibleEnum(qp.Get("another"))) + var options *azurepagegroup.PageClientListWithParametersOptions + if anotherParam != nil { + options = &azurepagegroup.PageClientListWithParametersOptions{ + Another: anotherParam, + } + } + resp := p.srv.NewListWithParametersPager(body, options) + newListWithParametersPager = &resp + p.newListWithParametersPager.add(req, newListWithParametersPager) + server.PagerResponderInjectNextLinks(newListWithParametersPager, req, func(page *azurepagegroup.PageClientListWithParametersResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListWithParametersPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newListWithParametersPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListWithParametersPager) { + p.newListWithParametersPager.remove(req) + } + return resp, nil +} + +func (p *PageServerTransport) dispatchNewWithRelativeNextLinkPager(req *http.Request) (*http.Response, error) { + if p.srv.NewWithRelativeNextLinkPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewWithRelativeNextLinkPager not implemented")} + } + newWithRelativeNextLinkPager := p.newWithRelativeNextLinkPager.get(req) + if newWithRelativeNextLinkPager == nil { + resp := p.srv.NewWithRelativeNextLinkPager(nil) + newWithRelativeNextLinkPager = &resp + p.newWithRelativeNextLinkPager.add(req, newWithRelativeNextLinkPager) + server.PagerResponderInjectNextLinks(newWithRelativeNextLinkPager, req, func(page *azurepagegroup.PageClientWithRelativeNextLinkResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newWithRelativeNextLinkPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newWithRelativeNextLinkPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newWithRelativeNextLinkPager) { + p.newWithRelativeNextLinkPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to PageServerTransport +var pageServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/core/azurepagegroup/fake/zz_pagetwomodelsaspageitem_server.go b/test/azure-http-specs/azure/core/azurepagegroup/fake/zz_pagetwomodelsaspageitem_server.go new file mode 100644 index 000000000000..6b9aad644534 --- /dev/null +++ b/test/azure-http-specs/azure/core/azurepagegroup/fake/zz_pagetwomodelsaspageitem_server.go @@ -0,0 +1,148 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "azurepagegroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "slices" +) + +// PageTwoModelsAsPageItemServer is a fake server for instances of the azurepagegroup.PageTwoModelsAsPageItemClient type. +type PageTwoModelsAsPageItemServer struct { + // NewListFirstItemPager is the fake for method PageTwoModelsAsPageItemClient.NewListFirstItemPager + // HTTP status codes to indicate success: http.StatusOK + NewListFirstItemPager func(options *azurepagegroup.PageTwoModelsAsPageItemClientListFirstItemOptions) (resp azfake.PagerResponder[azurepagegroup.PageTwoModelsAsPageItemClientListFirstItemResponse]) + + // NewListSecondItemPager is the fake for method PageTwoModelsAsPageItemClient.NewListSecondItemPager + // HTTP status codes to indicate success: http.StatusOK + NewListSecondItemPager func(options *azurepagegroup.PageTwoModelsAsPageItemClientListSecondItemOptions) (resp azfake.PagerResponder[azurepagegroup.PageTwoModelsAsPageItemClientListSecondItemResponse]) +} + +// NewPageTwoModelsAsPageItemServerTransport creates a new instance of PageTwoModelsAsPageItemServerTransport with the provided implementation. +// The returned PageTwoModelsAsPageItemServerTransport instance is connected to an instance of azurepagegroup.PageTwoModelsAsPageItemClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewPageTwoModelsAsPageItemServerTransport(srv *PageTwoModelsAsPageItemServer) *PageTwoModelsAsPageItemServerTransport { + return &PageTwoModelsAsPageItemServerTransport{ + srv: srv, + newListFirstItemPager: newTracker[azfake.PagerResponder[azurepagegroup.PageTwoModelsAsPageItemClientListFirstItemResponse]](), + newListSecondItemPager: newTracker[azfake.PagerResponder[azurepagegroup.PageTwoModelsAsPageItemClientListSecondItemResponse]](), + } +} + +// PageTwoModelsAsPageItemServerTransport connects instances of azurepagegroup.PageTwoModelsAsPageItemClient to instances of PageTwoModelsAsPageItemServer. +// Don't use this type directly, use NewPageTwoModelsAsPageItemServerTransport instead. +type PageTwoModelsAsPageItemServerTransport struct { + srv *PageTwoModelsAsPageItemServer + newListFirstItemPager *tracker[azfake.PagerResponder[azurepagegroup.PageTwoModelsAsPageItemClientListFirstItemResponse]] + newListSecondItemPager *tracker[azfake.PagerResponder[azurepagegroup.PageTwoModelsAsPageItemClientListSecondItemResponse]] +} + +// Do implements the policy.Transporter interface for PageTwoModelsAsPageItemServerTransport. +func (p *PageTwoModelsAsPageItemServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return p.dispatchToMethodFake(req, method) +} + +func (p *PageTwoModelsAsPageItemServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if pageTwoModelsAsPageItemServerTransportInterceptor != nil { + res.resp, res.err, intercepted = pageTwoModelsAsPageItemServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "PageTwoModelsAsPageItemClient.NewListFirstItemPager": + res.resp, res.err = p.dispatchNewListFirstItemPager(req) + case "PageTwoModelsAsPageItemClient.NewListSecondItemPager": + res.resp, res.err = p.dispatchNewListSecondItemPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (p *PageTwoModelsAsPageItemServerTransport) dispatchNewListFirstItemPager(req *http.Request) (*http.Response, error) { + if p.srv.NewListFirstItemPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListFirstItemPager not implemented")} + } + newListFirstItemPager := p.newListFirstItemPager.get(req) + if newListFirstItemPager == nil { + resp := p.srv.NewListFirstItemPager(nil) + newListFirstItemPager = &resp + p.newListFirstItemPager.add(req, newListFirstItemPager) + server.PagerResponderInjectNextLinks(newListFirstItemPager, req, func(page *azurepagegroup.PageTwoModelsAsPageItemClientListFirstItemResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListFirstItemPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newListFirstItemPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListFirstItemPager) { + p.newListFirstItemPager.remove(req) + } + return resp, nil +} + +func (p *PageTwoModelsAsPageItemServerTransport) dispatchNewListSecondItemPager(req *http.Request) (*http.Response, error) { + if p.srv.NewListSecondItemPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListSecondItemPager not implemented")} + } + newListSecondItemPager := p.newListSecondItemPager.get(req) + if newListSecondItemPager == nil { + resp := p.srv.NewListSecondItemPager(nil) + newListSecondItemPager = &resp + p.newListSecondItemPager.add(req, newListSecondItemPager) + server.PagerResponderInjectNextLinks(newListSecondItemPager, req, func(page *azurepagegroup.PageTwoModelsAsPageItemClientListSecondItemResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListSecondItemPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newListSecondItemPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListSecondItemPager) { + p.newListSecondItemPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to PageTwoModelsAsPageItemServerTransport +var pageTwoModelsAsPageItemServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/core/azurepagegroup/go.mod b/test/azure-http-specs/azure/core/azurepagegroup/go.mod new file mode 100644 index 000000000000..ea1c4e24ab38 --- /dev/null +++ b/test/azure-http-specs/azure/core/azurepagegroup/go.mod @@ -0,0 +1,17 @@ +module azurepagegroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/core/azurepagegroup/go.sum b/test/azure-http-specs/azure/core/azurepagegroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/core/azurepagegroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/core/azurepagegroup/testdata/_metadata.json b/test/azure-http-specs/azure/core/azurepagegroup/testdata/_metadata.json new file mode 100644 index 000000000000..231b346ceca1 --- /dev/null +++ b/test/azure-http-specs/azure/core/azurepagegroup/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "_Specs_.Azure.Core.Page": "2022-12-01-preview" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/core/azurepagegroup/twomodelsaspageitem_client_test.go b/test/azure-http-specs/azure/core/azurepagegroup/twomodelsaspageitem_client_test.go new file mode 100644 index 000000000000..0390afa7d728 --- /dev/null +++ b/test/azure-http-specs/azure/core/azurepagegroup/twomodelsaspageitem_client_test.go @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package azurepagegroup_test + +import ( + "azurepagegroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestTwoModelsAsPageItemClient_NewListFirstItemPager(t *testing.T) { + client, err := azurepagegroup.NewPageClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + pager := client.NewPageTwoModelsAsPageItemClient().NewListFirstItemPager(nil) + pages := 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + require.EqualValues(t, []*azurepagegroup.FirstItem{ + { + ID: to.Ptr[int32](1), + }, + }, page.Value) + pages++ + } + require.EqualValues(t, 1, pages) +} + +func TestTwoModelsAsPageItemClient_NewListSecondItemPager(t *testing.T) { + client, err := azurepagegroup.NewPageClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + pager := client.NewPageTwoModelsAsPageItemClient().NewListSecondItemPager(nil) + pages := 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + require.EqualValues(t, []*azurepagegroup.SecondItem{ + { + Name: to.Ptr("Madge"), + }, + }, page.Value) + pages++ + } + require.EqualValues(t, 1, pages) +} diff --git a/test/azure-http-specs/azure/core/azurepagegroup/zz_constants.go b/test/azure-http-specs/azure/core/azurepagegroup/zz_constants.go new file mode 100644 index 000000000000..f64c012a124a --- /dev/null +++ b/test/azure-http-specs/azure/core/azurepagegroup/zz_constants.go @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azurepagegroup + +const ( + version20221201Preview string = "2022-12-01-preview" +) + +// ListItemInputExtensibleEnum - An extensible enum input parameter. +type ListItemInputExtensibleEnum string + +const ( + // ListItemInputExtensibleEnumFirst - The first enum value. + ListItemInputExtensibleEnumFirst ListItemInputExtensibleEnum = "First" + // ListItemInputExtensibleEnumSecond - The second enum value. + ListItemInputExtensibleEnumSecond ListItemInputExtensibleEnum = "Second" +) + +// PossibleListItemInputExtensibleEnumValues returns the possible values for the ListItemInputExtensibleEnum const type. +func PossibleListItemInputExtensibleEnumValues() []ListItemInputExtensibleEnum { + return []ListItemInputExtensibleEnum{ + ListItemInputExtensibleEnumFirst, + ListItemInputExtensibleEnumSecond, + } +} diff --git a/test/azure-http-specs/azure/core/azurepagegroup/zz_models.go b/test/azure-http-specs/azure/core/azurepagegroup/zz_models.go new file mode 100644 index 000000000000..b7ca8b35c99f --- /dev/null +++ b/test/azure-http-specs/azure/core/azurepagegroup/zz_models.go @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azurepagegroup + +import "github.com/Azure/azure-sdk-for-go/sdk/azcore" + +// FirstItem - First item. +type FirstItem struct { + // READ-ONLY; The id of the item. + ID *int32 +} + +// ListItemInputBody - The body of the input. +type ListItemInputBody struct { + // REQUIRED; The name of the input. + InputName *string +} + +// PagedFirstItem - Paged collection of FirstItem items +type PagedFirstItem struct { + // REQUIRED; The FirstItem items on this page + Value []*FirstItem + + // The link to the next page of items + NextLink *string +} + +// PagedSecondItem - Paged collection of SecondItem items +type PagedSecondItem struct { + // REQUIRED; The SecondItem items on this page + Value []*SecondItem + + // The link to the next page of items + NextLink *string +} + +// PagedUser - Paged collection of User items +type PagedUser struct { + // REQUIRED; The User items on this page + Value []*User + + // The link to the next page of items + NextLink *string +} + +// SecondItem - Second item. +type SecondItem struct { + // READ-ONLY; The name of the item. + Name *string +} + +// User - Details about a user. +type User struct { + // REQUIRED; The user's name. + Name *string + + // The user's order list + Orders []*UserOrder + + // READ-ONLY; The entity tag for this resource. + Etag *azcore.ETag + + // READ-ONLY; The user's id. + ID *int32 +} + +type UserListResults struct { + // REQUIRED; List of items. + Items []*User + + // Link to fetch more items. + NextLink *string +} + +// UserOrder for testing list with expand. +type UserOrder struct { + // REQUIRED; The user's order detail + Detail *string + + // REQUIRED; The user's id. + UserID *int32 + + // READ-ONLY; The user's id. + ID *int32 +} diff --git a/test/azure-http-specs/azure/core/azurepagegroup/zz_models_serde.go b/test/azure-http-specs/azure/core/azurepagegroup/zz_models_serde.go new file mode 100644 index 000000000000..1b0f7a141389 --- /dev/null +++ b/test/azure-http-specs/azure/core/azurepagegroup/zz_models_serde.go @@ -0,0 +1,311 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azurepagegroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type FirstItem. +func (f FirstItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", f.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirstItem. +func (f *FirstItem) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &f.ID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ListItemInputBody. +func (l ListItemInputBody) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "inputName", l.InputName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ListItemInputBody. +func (l *ListItemInputBody) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "inputName": + err = unpopulate(val, "InputName", &l.InputName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PagedFirstItem. +func (p PagedFirstItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", p.NextLink) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PagedFirstItem. +func (p *PagedFirstItem) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &p.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PagedSecondItem. +func (p PagedSecondItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", p.NextLink) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PagedSecondItem. +func (p *PagedSecondItem) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &p.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PagedUser. +func (p PagedUser) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", p.NextLink) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PagedUser. +func (p *PagedUser) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &p.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SecondItem. +func (s SecondItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", s.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecondItem. +func (s *SecondItem) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type User. +func (u User) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", u.Etag) + populate(objectMap, "id", u.ID) + populate(objectMap, "name", u.Name) + populate(objectMap, "orders", u.Orders) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type User. +func (u *User) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &u.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &u.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &u.Name) + delete(rawMsg, key) + case "orders": + err = unpopulate(val, "Orders", &u.Orders) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserListResults. +func (u UserListResults) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "items", u.Items) + populate(objectMap, "nextLink", u.NextLink) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserListResults. +func (u *UserListResults) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "items": + err = unpopulate(val, "Items", &u.Items) + delete(rawMsg, key) + case "nextLink": + err = unpopulate(val, "NextLink", &u.NextLink) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserOrder. +func (u UserOrder) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "detail", u.Detail) + populate(objectMap, "id", u.ID) + populate(objectMap, "userId", u.UserID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserOrder. +func (u *UserOrder) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "detail": + err = unpopulate(val, "Detail", &u.Detail) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &u.ID) + delete(rawMsg, key) + case "userId": + err = unpopulate(val, "UserID", &u.UserID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/azure-http-specs/azure/core/azurepagegroup/zz_options.go b/test/azure-http-specs/azure/core/azurepagegroup/zz_options.go new file mode 100644 index 000000000000..f69664d33311 --- /dev/null +++ b/test/azure-http-specs/azure/core/azurepagegroup/zz_options.go @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azurepagegroup + +// PageClientListWithCustomPageModelOptions contains the optional parameters for the PageClient.NewListWithCustomPageModelPager +// method. +type PageClientListWithCustomPageModelOptions struct { + // placeholder for future optional parameters +} + +// PageClientListWithPageOptions contains the optional parameters for the PageClient.NewListWithPagePager method. +type PageClientListWithPageOptions struct { + // placeholder for future optional parameters +} + +// PageClientListWithParametersOptions contains the optional parameters for the PageClient.NewListWithParametersPager method. +type PageClientListWithParametersOptions struct { + // Another query parameter. + Another *ListItemInputExtensibleEnum +} + +// PageClientWithRelativeNextLinkOptions contains the optional parameters for the PageClient.NewWithRelativeNextLinkPager +// method. +type PageClientWithRelativeNextLinkOptions struct { + // placeholder for future optional parameters +} + +// PageTwoModelsAsPageItemClientListFirstItemOptions contains the optional parameters for the PageTwoModelsAsPageItemClient.NewListFirstItemPager +// method. +type PageTwoModelsAsPageItemClientListFirstItemOptions struct { + // placeholder for future optional parameters +} + +// PageTwoModelsAsPageItemClientListSecondItemOptions contains the optional parameters for the PageTwoModelsAsPageItemClient.NewListSecondItemPager +// method. +type PageTwoModelsAsPageItemClientListSecondItemOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/azure/core/azurepagegroup/zz_page_client.go b/test/azure-http-specs/azure/core/azurepagegroup/zz_page_client.go new file mode 100644 index 000000000000..29ddee0ada13 --- /dev/null +++ b/test/azure-http-specs/azure/core/azurepagegroup/zz_page_client.go @@ -0,0 +1,259 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azurepagegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// PageClient - Illustrates bodies templated with Azure Core with paging support +// Don't use this type directly, use NewPageClientWithNoCredential() instead. +// +// Generated from API version 2022-12-01-preview +type PageClient struct { + internal *azcore.Client + endpoint string +} + +// PageClientOptions contains the optional values for creating a [PageClient]. +type PageClientOptions struct { + azcore.ClientOptions +} + +// NewPageClientWithNoCredential creates a new instance of PageClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewPageClientWithNoCredential(endpoint string, options *PageClientOptions) (*PageClient, error) { + if options == nil { + options = &PageClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{ + APIVersion: runtime.APIVersionOptions{ + Name: "api-version", + Location: runtime.APIVersionLocationQueryParam, + }, + }, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &PageClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewPageTwoModelsAsPageItemClient creates a new instance of [PageTwoModelsAsPageItemClient]. +func (client *PageClient) NewPageTwoModelsAsPageItemClient() *PageTwoModelsAsPageItemClient { + return &PageTwoModelsAsPageItemClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewListWithCustomPageModelPager - List with custom page model. +// - options - PageClientListWithCustomPageModelOptions contains the optional parameters for the PageClient.NewListWithCustomPageModelPager +// method. +func (client *PageClient) NewListWithCustomPageModelPager(options *PageClientListWithCustomPageModelOptions) *runtime.Pager[PageClientListWithCustomPageModelResponse] { + return runtime.NewPager(runtime.PagingHandler[PageClientListWithCustomPageModelResponse]{ + More: func(page PageClientListWithCustomPageModelResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PageClientListWithCustomPageModelResponse) (PageClientListWithCustomPageModelResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PageClient.NewListWithCustomPageModelPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listWithCustomPageModelCreateRequest(ctx, options) + }, nil) + if err != nil { + return PageClientListWithCustomPageModelResponse{}, err + } + return client.listWithCustomPageModelHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listWithCustomPageModelCreateRequest creates the ListWithCustomPageModel request. +func (client *PageClient) listWithCustomPageModelCreateRequest(ctx context.Context, _ *PageClientListWithCustomPageModelOptions) (*policy.Request, error) { + urlPath := "/azure/core/page/custom-page" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20221201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listWithCustomPageModelHandleResponse handles the ListWithCustomPageModel response. +func (client *PageClient) listWithCustomPageModelHandleResponse(resp *http.Response) (PageClientListWithCustomPageModelResponse, error) { + result := PageClientListWithCustomPageModelResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.UserListResults); err != nil { + return PageClientListWithCustomPageModelResponse{}, err + } + return result, nil +} + +// NewListWithPagePager - List with Azure.Core.Page<>. +// - options - PageClientListWithPageOptions contains the optional parameters for the PageClient.NewListWithPagePager method. +func (client *PageClient) NewListWithPagePager(options *PageClientListWithPageOptions) *runtime.Pager[PageClientListWithPageResponse] { + return runtime.NewPager(runtime.PagingHandler[PageClientListWithPageResponse]{ + More: func(page PageClientListWithPageResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PageClientListWithPageResponse) (PageClientListWithPageResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PageClient.NewListWithPagePager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listWithPageCreateRequest(ctx, options) + }, nil) + if err != nil { + return PageClientListWithPageResponse{}, err + } + return client.listWithPageHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listWithPageCreateRequest creates the ListWithPage request. +func (client *PageClient) listWithPageCreateRequest(ctx context.Context, _ *PageClientListWithPageOptions) (*policy.Request, error) { + urlPath := "/azure/core/page/page" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20221201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listWithPageHandleResponse handles the ListWithPage response. +func (client *PageClient) listWithPageHandleResponse(resp *http.Response) (PageClientListWithPageResponse, error) { + result := PageClientListWithPageResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PagedUser); err != nil { + return PageClientListWithPageResponse{}, err + } + return result, nil +} + +// NewListWithParametersPager - List with extensible enum parameter Azure.Core.Page<>. +// - bodyInput - The body of the input. +// - options - PageClientListWithParametersOptions contains the optional parameters for the PageClient.NewListWithParametersPager +// method. +func (client *PageClient) NewListWithParametersPager(bodyInput ListItemInputBody, options *PageClientListWithParametersOptions) *runtime.Pager[PageClientListWithParametersResponse] { + return runtime.NewPager(runtime.PagingHandler[PageClientListWithParametersResponse]{ + More: func(page PageClientListWithParametersResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PageClientListWithParametersResponse) (PageClientListWithParametersResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PageClient.NewListWithParametersPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listWithParametersCreateRequest(ctx, bodyInput, options) + }, nil) + if err != nil { + return PageClientListWithParametersResponse{}, err + } + return client.listWithParametersHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listWithParametersCreateRequest creates the ListWithParameters request. +func (client *PageClient) listWithParametersCreateRequest(ctx context.Context, bodyInput ListItemInputBody, options *PageClientListWithParametersOptions) (*policy.Request, error) { + urlPath := "/azure/core/page/parameters" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Another != nil { + reqQP.Set("another", string(*options.Another)) + } + reqQP.Set("api-version", version20221201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, bodyInput); err != nil { + return nil, err + } + return req, nil +} + +// listWithParametersHandleResponse handles the ListWithParameters response. +func (client *PageClient) listWithParametersHandleResponse(resp *http.Response) (PageClientListWithParametersResponse, error) { + result := PageClientListWithParametersResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PagedUser); err != nil { + return PageClientListWithParametersResponse{}, err + } + return result, nil +} + +// NewWithRelativeNextLinkPager - List with relative nextLink URL that requires endpoint resolution. +// - options - PageClientWithRelativeNextLinkOptions contains the optional parameters for the PageClient.NewWithRelativeNextLinkPager +// method. +func (client *PageClient) NewWithRelativeNextLinkPager(options *PageClientWithRelativeNextLinkOptions) *runtime.Pager[PageClientWithRelativeNextLinkResponse] { + return runtime.NewPager(runtime.PagingHandler[PageClientWithRelativeNextLinkResponse]{ + More: func(page PageClientWithRelativeNextLinkResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PageClientWithRelativeNextLinkResponse) (PageClientWithRelativeNextLinkResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PageClient.NewWithRelativeNextLinkPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.withRelativeNextLinkCreateRequest(ctx, options) + }, nil) + if err != nil { + return PageClientWithRelativeNextLinkResponse{}, err + } + return client.withRelativeNextLinkHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// withRelativeNextLinkCreateRequest creates the WithRelativeNextLink request. +func (client *PageClient) withRelativeNextLinkCreateRequest(ctx context.Context, _ *PageClientWithRelativeNextLinkOptions) (*policy.Request, error) { + urlPath := "/azure/core/page/with-relative-next-link" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// withRelativeNextLinkHandleResponse handles the WithRelativeNextLink response. +func (client *PageClient) withRelativeNextLinkHandleResponse(resp *http.Response) (PageClientWithRelativeNextLinkResponse, error) { + result := PageClientWithRelativeNextLinkResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PagedUser); err != nil { + return PageClientWithRelativeNextLinkResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/core/azurepagegroup/zz_pagetwomodelsaspageitem_client.go b/test/azure-http-specs/azure/core/azurepagegroup/zz_pagetwomodelsaspageitem_client.go new file mode 100644 index 000000000000..c96dd714d0bf --- /dev/null +++ b/test/azure-http-specs/azure/core/azurepagegroup/zz_pagetwomodelsaspageitem_client.go @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azurepagegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// PageTwoModelsAsPageItemClient contains the methods for the PageTwoModelsAsPageItem group. +// Don't use this type directly, use [PageClient.NewPageTwoModelsAsPageItemClient] instead. +// +// Generated from API version 2022-12-01-preview +type PageTwoModelsAsPageItemClient struct { + internal *azcore.Client + endpoint string +} + +// NewListFirstItemPager - Two operations with two different page item types should be successfully generated. Should generate +// model for FirstItem. +// - options - PageTwoModelsAsPageItemClientListFirstItemOptions contains the optional parameters for the PageTwoModelsAsPageItemClient.NewListFirstItemPager +// method. +func (client *PageTwoModelsAsPageItemClient) NewListFirstItemPager(options *PageTwoModelsAsPageItemClientListFirstItemOptions) *runtime.Pager[PageTwoModelsAsPageItemClientListFirstItemResponse] { + return runtime.NewPager(runtime.PagingHandler[PageTwoModelsAsPageItemClientListFirstItemResponse]{ + More: func(page PageTwoModelsAsPageItemClientListFirstItemResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PageTwoModelsAsPageItemClientListFirstItemResponse) (PageTwoModelsAsPageItemClientListFirstItemResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PageTwoModelsAsPageItemClient.NewListFirstItemPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listFirstItemCreateRequest(ctx, options) + }, nil) + if err != nil { + return PageTwoModelsAsPageItemClientListFirstItemResponse{}, err + } + return client.listFirstItemHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listFirstItemCreateRequest creates the ListFirstItem request. +func (client *PageTwoModelsAsPageItemClient) listFirstItemCreateRequest(ctx context.Context, _ *PageTwoModelsAsPageItemClientListFirstItemOptions) (*policy.Request, error) { + urlPath := "/azure/core/page/first-item" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20221201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listFirstItemHandleResponse handles the ListFirstItem response. +func (client *PageTwoModelsAsPageItemClient) listFirstItemHandleResponse(resp *http.Response) (PageTwoModelsAsPageItemClientListFirstItemResponse, error) { + result := PageTwoModelsAsPageItemClientListFirstItemResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PagedFirstItem); err != nil { + return PageTwoModelsAsPageItemClientListFirstItemResponse{}, err + } + return result, nil +} + +// NewListSecondItemPager - Two operations with two different page item types should be successfully generated. Should generate +// model for SecondItem. +// - options - PageTwoModelsAsPageItemClientListSecondItemOptions contains the optional parameters for the PageTwoModelsAsPageItemClient.NewListSecondItemPager +// method. +func (client *PageTwoModelsAsPageItemClient) NewListSecondItemPager(options *PageTwoModelsAsPageItemClientListSecondItemOptions) *runtime.Pager[PageTwoModelsAsPageItemClientListSecondItemResponse] { + return runtime.NewPager(runtime.PagingHandler[PageTwoModelsAsPageItemClientListSecondItemResponse]{ + More: func(page PageTwoModelsAsPageItemClientListSecondItemResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PageTwoModelsAsPageItemClientListSecondItemResponse) (PageTwoModelsAsPageItemClientListSecondItemResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PageTwoModelsAsPageItemClient.NewListSecondItemPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listSecondItemCreateRequest(ctx, options) + }, nil) + if err != nil { + return PageTwoModelsAsPageItemClientListSecondItemResponse{}, err + } + return client.listSecondItemHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listSecondItemCreateRequest creates the ListSecondItem request. +func (client *PageTwoModelsAsPageItemClient) listSecondItemCreateRequest(ctx context.Context, _ *PageTwoModelsAsPageItemClientListSecondItemOptions) (*policy.Request, error) { + urlPath := "/azure/core/page/second-item" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20221201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listSecondItemHandleResponse handles the ListSecondItem response. +func (client *PageTwoModelsAsPageItemClient) listSecondItemHandleResponse(resp *http.Response) (PageTwoModelsAsPageItemClientListSecondItemResponse, error) { + result := PageTwoModelsAsPageItemClientListSecondItemResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PagedSecondItem); err != nil { + return PageTwoModelsAsPageItemClientListSecondItemResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/core/azurepagegroup/zz_responses.go b/test/azure-http-specs/azure/core/azurepagegroup/zz_responses.go new file mode 100644 index 000000000000..4622119d2458 --- /dev/null +++ b/test/azure-http-specs/azure/core/azurepagegroup/zz_responses.go @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azurepagegroup + +// PageClientListWithCustomPageModelResponse contains the response from method PageClient.NewListWithCustomPageModelPager. +type PageClientListWithCustomPageModelResponse struct { + UserListResults +} + +// PageClientListWithPageResponse contains the response from method PageClient.NewListWithPagePager. +type PageClientListWithPageResponse struct { + // Paged collection of User items + PagedUser +} + +// PageClientListWithParametersResponse contains the response from method PageClient.NewListWithParametersPager. +type PageClientListWithParametersResponse struct { + // Paged collection of User items + PagedUser +} + +// PageClientWithRelativeNextLinkResponse contains the response from method PageClient.NewWithRelativeNextLinkPager. +type PageClientWithRelativeNextLinkResponse struct { + // Paged collection of User items + PagedUser +} + +// PageTwoModelsAsPageItemClientListFirstItemResponse contains the response from method PageTwoModelsAsPageItemClient.NewListFirstItemPager. +type PageTwoModelsAsPageItemClientListFirstItemResponse struct { + // Paged collection of FirstItem items + PagedFirstItem +} + +// PageTwoModelsAsPageItemClientListSecondItemResponse contains the response from method PageTwoModelsAsPageItemClient.NewListSecondItemPager. +type PageTwoModelsAsPageItemClientListSecondItemResponse struct { + // Paged collection of SecondItem items + PagedSecondItem +} diff --git a/test/azure-http-specs/azure/core/azurepagegroup/zz_version.go b/test/azure-http-specs/azure/core/azurepagegroup/zz_version.go new file mode 100644 index 000000000000..ef4315d80dd1 --- /dev/null +++ b/test/azure-http-specs/azure/core/azurepagegroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package azurepagegroup + +const ( + moduleName = "azurepagegroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/core/basicgroup/LICENSE.txt b/test/azure-http-specs/azure/core/basicgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/core/basicgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/core/basicgroup/basic_client_test.go b/test/azure-http-specs/azure/core/basicgroup/basic_client_test.go new file mode 100644 index 000000000000..725cbd1e0893 --- /dev/null +++ b/test/azure-http-specs/azure/core/basicgroup/basic_client_test.go @@ -0,0 +1,139 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package basicgroup_test + +import ( + "basicgroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestBasicClient_CreateOrReplace(t *testing.T) { + client, err := basicgroup.NewBasicClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.CreateOrReplace(context.Background(), 1, basicgroup.User{ + Name: to.Ptr("Madge"), + }, nil) + require.NoError(t, err) + require.EqualValues(t, basicgroup.User{ + Etag: to.Ptr[azcore.ETag]("11bdc430-65e8-45ad-81d9-8ffa60d55b59"), + ID: to.Ptr[int32](1), + Name: to.Ptr("Madge"), + }, resp.User) +} + +func TestBasicClient_CreateOrUpdate(t *testing.T) { + client, err := basicgroup.NewBasicClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.CreateOrUpdate(context.Background(), 1, basicgroup.User{ + Name: to.Ptr("Madge"), + }, nil) + require.NoError(t, err) + require.EqualValues(t, basicgroup.User{ + Etag: to.Ptr[azcore.ETag]("11bdc430-65e8-45ad-81d9-8ffa60d55b59"), + ID: to.Ptr[int32](1), + Name: to.Ptr("Madge"), + }, resp.User) +} + +func TestBasicClient_Delete(t *testing.T) { + client, err := basicgroup.NewBasicClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.Delete(context.Background(), 1, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestBasicClient_Export(t *testing.T) { + client, err := basicgroup.NewBasicClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.Export(context.Background(), 1, "json", nil) + require.NoError(t, err) + require.EqualValues(t, basicgroup.User{ + Etag: to.Ptr[azcore.ETag]("11bdc430-65e8-45ad-81d9-8ffa60d55b59"), + ID: to.Ptr[int32](1), + Name: to.Ptr("Madge"), + }, resp.User) +} + +func TestBasicClient_ExportAllUsers(t *testing.T) { + client, err := basicgroup.NewBasicClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.ExportAllUsers(context.Background(), "json", nil) + require.NoError(t, err) + require.EqualValues(t, []*basicgroup.User{ + { + Etag: to.Ptr[azcore.ETag]("11bdc430-65e8-45ad-81d9-8ffa60d55b59"), + ID: to.Ptr[int32](1), + Name: to.Ptr("Madge"), + }, + { + Etag: to.Ptr[azcore.ETag]("22bdc430-65e8-45ad-81d9-8ffa60d55b59"), + ID: to.Ptr[int32](2), + Name: to.Ptr("John"), + }, + }, resp.Users) +} + +func TestBasicClient_Get(t *testing.T) { + client, err := basicgroup.NewBasicClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.Get(context.Background(), 1, nil) + require.NoError(t, err) + require.EqualValues(t, basicgroup.User{ + Etag: to.Ptr[azcore.ETag]("11bdc430-65e8-45ad-81d9-8ffa60d55b59"), + ID: to.Ptr[int32](1), + Name: to.Ptr("Madge"), + }, resp.User) +} + +func TestBasicClient_NewListPager(t *testing.T) { + client, err := basicgroup.NewBasicClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + pager := client.NewListPager(&basicgroup.BasicClientListOptions{ + Top: to.Ptr[int32](5), + Skip: to.Ptr[int32](10), + Orderby: []string{"id"}, + Filter: to.Ptr("id lt 10"), + Select: []string{"id", "orders", "etag"}, + Expand: []string{"orders"}, + }) + pages := 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + require.EqualValues(t, []*basicgroup.User{ + { + ID: to.Ptr[int32](1), + Name: to.Ptr("Madge"), + Etag: to.Ptr[azcore.ETag]("11bdc430-65e8-45ad-81d9-8ffa60d55b59"), + Orders: []*basicgroup.UserOrder{ + { + ID: to.Ptr[int32](1), + UserID: to.Ptr[int32](1), + Detail: to.Ptr("a recorder"), + }, + }, + }, + { + ID: to.Ptr[int32](2), + Name: to.Ptr("John"), + Etag: to.Ptr[azcore.ETag]("11bdc430-65e8-45ad-81d9-8ffa60d55b5a"), + Orders: []*basicgroup.UserOrder{ + { + ID: to.Ptr[int32](2), + UserID: to.Ptr[int32](2), + Detail: to.Ptr("a TV"), + }, + }, + }, + }, page.Value) + pages++ + } + require.EqualValues(t, 1, pages) +} diff --git a/test/azure-http-specs/azure/core/basicgroup/fake/zz_basic_server.go b/test/azure-http-specs/azure/core/basicgroup/fake/zz_basic_server.go new file mode 100644 index 000000000000..5399898852a6 --- /dev/null +++ b/test/azure-http-specs/azure/core/basicgroup/fake/zz_basic_server.go @@ -0,0 +1,421 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "basicgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" + "strconv" +) + +// BasicServer is a fake server for instances of the basicgroup.BasicClient type. +type BasicServer struct { + // CreateOrReplace is the fake for method BasicClient.CreateOrReplace + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrReplace func(ctx context.Context, id int32, resource basicgroup.User, options *basicgroup.BasicClientCreateOrReplaceOptions) (resp azfake.Responder[basicgroup.BasicClientCreateOrReplaceResponse], errResp azfake.ErrorResponder) + + // CreateOrUpdate is the fake for method BasicClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, id int32, resource basicgroup.User, options *basicgroup.BasicClientCreateOrUpdateOptions) (resp azfake.Responder[basicgroup.BasicClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method BasicClient.Delete + // HTTP status codes to indicate success: http.StatusNoContent + Delete func(ctx context.Context, id int32, options *basicgroup.BasicClientDeleteOptions) (resp azfake.Responder[basicgroup.BasicClientDeleteResponse], errResp azfake.ErrorResponder) + + // Export is the fake for method BasicClient.Export + // HTTP status codes to indicate success: http.StatusOK + Export func(ctx context.Context, id int32, formatParam string, options *basicgroup.BasicClientExportOptions) (resp azfake.Responder[basicgroup.BasicClientExportResponse], errResp azfake.ErrorResponder) + + // ExportAllUsers is the fake for method BasicClient.ExportAllUsers + // HTTP status codes to indicate success: http.StatusOK + ExportAllUsers func(ctx context.Context, formatParam string, options *basicgroup.BasicClientExportAllUsersOptions) (resp azfake.Responder[basicgroup.BasicClientExportAllUsersResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method BasicClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, id int32, options *basicgroup.BasicClientGetOptions) (resp azfake.Responder[basicgroup.BasicClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method BasicClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *basicgroup.BasicClientListOptions) (resp azfake.PagerResponder[basicgroup.BasicClientListResponse]) +} + +// NewBasicServerTransport creates a new instance of BasicServerTransport with the provided implementation. +// The returned BasicServerTransport instance is connected to an instance of basicgroup.BasicClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewBasicServerTransport(srv *BasicServer) *BasicServerTransport { + return &BasicServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[basicgroup.BasicClientListResponse]](), + } +} + +// BasicServerTransport connects instances of basicgroup.BasicClient to instances of BasicServer. +// Don't use this type directly, use NewBasicServerTransport instead. +type BasicServerTransport struct { + srv *BasicServer + newListPager *tracker[azfake.PagerResponder[basicgroup.BasicClientListResponse]] +} + +// Do implements the policy.Transporter interface for BasicServerTransport. +func (b *BasicServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return b.dispatchToMethodFake(req, method) +} + +func (b *BasicServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if basicServerTransportInterceptor != nil { + res.resp, res.err, intercepted = basicServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "BasicClient.CreateOrReplace": + res.resp, res.err = b.dispatchCreateOrReplace(req) + case "BasicClient.CreateOrUpdate": + res.resp, res.err = b.dispatchCreateOrUpdate(req) + case "BasicClient.Delete": + res.resp, res.err = b.dispatchDelete(req) + case "BasicClient.Export": + res.resp, res.err = b.dispatchExport(req) + case "BasicClient.ExportAllUsers": + res.resp, res.err = b.dispatchExportAllUsers(req) + case "BasicClient.Get": + res.resp, res.err = b.dispatchGet(req) + case "BasicClient.NewListPager": + res.resp, res.err = b.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (b *BasicServerTransport) dispatchCreateOrReplace(req *http.Request) (*http.Response, error) { + if b.srv.CreateOrReplace == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrReplace not implemented")} + } + const regexStr = `/azure/core/basic/users/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[basicgroup.User](req) + if err != nil { + return nil, err + } + idUnescaped, err := url.PathUnescape(matches[regex.SubexpIndex("id")]) + if err != nil { + return nil, err + } + idParam, err := parseWithCast(idUnescaped, func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.CreateOrReplace(req.Context(), idParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).User, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BasicServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if b.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/azure/core/basic/users/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[basicgroup.User](req) + if err != nil { + return nil, err + } + idUnescaped, err := url.PathUnescape(matches[regex.SubexpIndex("id")]) + if err != nil { + return nil, err + } + idParam, err := parseWithCast(idUnescaped, func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.CreateOrUpdate(req.Context(), idParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).User, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BasicServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if b.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/azure/core/basic/users/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + idUnescaped, err := url.PathUnescape(matches[regex.SubexpIndex("id")]) + if err != nil { + return nil, err + } + idParam, err := parseWithCast(idUnescaped, func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.Delete(req.Context(), idParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BasicServerTransport) dispatchExport(req *http.Request) (*http.Response, error) { + if b.srv.Export == nil { + return nil, &nonRetriableError{errors.New("fake for method Export not implemented")} + } + const regexStr = `/azure/core/basic/users/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+):export` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + idUnescaped, err := url.PathUnescape(matches[regex.SubexpIndex("id")]) + if err != nil { + return nil, err + } + idParam, err := parseWithCast(idUnescaped, func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.Export(req.Context(), idParam, qp.Get("format"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).User, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BasicServerTransport) dispatchExportAllUsers(req *http.Request) (*http.Response, error) { + if b.srv.ExportAllUsers == nil { + return nil, &nonRetriableError{errors.New("fake for method ExportAllUsers not implemented")} + } + qp := req.URL.Query() + respr, errRespr := b.srv.ExportAllUsers(req.Context(), qp.Get("format"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).UserList, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BasicServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if b.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/azure/core/basic/users/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + idUnescaped, err := url.PathUnescape(matches[regex.SubexpIndex("id")]) + if err != nil { + return nil, err + } + idParam, err := parseWithCast(idUnescaped, func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.Get(req.Context(), idParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).User, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BasicServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if b.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := b.newListPager.get(req) + if newListPager == nil { + qp := req.URL.Query() + topParam, err := parseOptional(qp.Get("top"), func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + skipParam, err := parseOptional(qp.Get("skip"), func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + maxpagesizeParam, err := parseOptional(qp.Get("maxpagesize"), func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + filterParam := getOptional(qp.Get("filter")) + var options *basicgroup.BasicClientListOptions + if topParam != nil || skipParam != nil || maxpagesizeParam != nil || len(qp["orderby"]) > 0 || filterParam != nil || len(qp["select"]) > 0 || len(qp["expand"]) > 0 { + options = &basicgroup.BasicClientListOptions{ + Top: topParam, + Skip: skipParam, + Maxpagesize: maxpagesizeParam, + Orderby: qp["orderby"], + Filter: filterParam, + Select: qp["select"], + Expand: qp["expand"], + } + } + resp := b.srv.NewListPager(options) + newListPager = &resp + b.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *basicgroup.BasicClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + b.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + b.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to BasicServerTransport +var basicServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/core/basicgroup/fake/zz_internal.go b/test/azure-http-specs/azure/core/basicgroup/fake/zz_internal.go new file mode 100644 index 000000000000..f343eec4bc92 --- /dev/null +++ b/test/azure-http-specs/azure/core/basicgroup/fake/zz_internal.go @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "reflect" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getOptional[T any](v T) *T { + if reflect.ValueOf(v).IsZero() { + return nil + } + return &v +} + +func parseOptional[T any](v string, parse func(v string) (T, error)) (*T, error) { + if v == "" { + return nil, nil + } + t, err := parse(v) + if err != nil { + return nil, err + } + return &t, nil +} + +func parseWithCast[T any](v string, parse func(v string) (T, error)) (T, error) { + t, err := parse(v) + if err != nil { + return *new(T), err + } + return t, err +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/azure-http-specs/azure/core/basicgroup/go.mod b/test/azure-http-specs/azure/core/basicgroup/go.mod new file mode 100644 index 000000000000..83ee43e290a6 --- /dev/null +++ b/test/azure-http-specs/azure/core/basicgroup/go.mod @@ -0,0 +1,17 @@ +module basicgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/core/basicgroup/go.sum b/test/azure-http-specs/azure/core/basicgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/core/basicgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/core/basicgroup/testdata/_metadata.json b/test/azure-http-specs/azure/core/basicgroup/testdata/_metadata.json new file mode 100644 index 000000000000..f161a919212f --- /dev/null +++ b/test/azure-http-specs/azure/core/basicgroup/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "_Specs_.Azure.Core.Basic": "2022-12-01-preview" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/core/basicgroup/zz_basic_client.go b/test/azure-http-specs/azure/core/basicgroup/zz_basic_client.go new file mode 100644 index 000000000000..1074c7a4ceb2 --- /dev/null +++ b/test/azure-http-specs/azure/core/basicgroup/zz_basic_client.go @@ -0,0 +1,443 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package basicgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" +) + +// BasicClient - Illustrates bodies templated with Azure Core +// Don't use this type directly, use NewBasicClientWithNoCredential() instead. +// +// Generated from API version 2022-12-01-preview +type BasicClient struct { + internal *azcore.Client + endpoint string +} + +// BasicClientOptions contains the optional values for creating a [BasicClient]. +type BasicClientOptions struct { + azcore.ClientOptions +} + +// NewBasicClientWithNoCredential creates a new instance of BasicClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewBasicClientWithNoCredential(endpoint string, options *BasicClientOptions) (*BasicClient, error) { + if options == nil { + options = &BasicClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{ + APIVersion: runtime.APIVersionOptions{ + Name: "api-version", + Location: runtime.APIVersionLocationQueryParam, + }, + }, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &BasicClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// CreateOrReplace - Adds a user or replaces a user's fields. +// +// Creates or replaces a User +// If the operation fails it returns an *azcore.ResponseError type. +// - id - The user's id. +// - resource - The resource instance. +// - options - BasicClientCreateOrReplaceOptions contains the optional parameters for the BasicClient.CreateOrReplace method. +func (client *BasicClient) CreateOrReplace(ctx context.Context, id int32, resource User, options *BasicClientCreateOrReplaceOptions) (BasicClientCreateOrReplaceResponse, error) { + var err error + const operationName = "BasicClient.CreateOrReplace" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrReplaceCreateRequest(ctx, id, resource, options) + if err != nil { + return BasicClientCreateOrReplaceResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BasicClientCreateOrReplaceResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return BasicClientCreateOrReplaceResponse{}, err + } + resp, err := client.createOrReplaceHandleResponse(httpResp) + return resp, err +} + +// createOrReplaceCreateRequest creates the CreateOrReplace request. +func (client *BasicClient) createOrReplaceCreateRequest(ctx context.Context, id int32, resource User, _ *BasicClientCreateOrReplaceOptions) (*policy.Request, error) { + urlPath := "/azure/core/basic/users/{id}" + urlPath = strings.ReplaceAll(urlPath, "{id}", url.PathEscape(strconv.FormatInt(int64(id), 10))) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20221201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// createOrReplaceHandleResponse handles the CreateOrReplace response. +func (client *BasicClient) createOrReplaceHandleResponse(resp *http.Response) (BasicClientCreateOrReplaceResponse, error) { + result := BasicClientCreateOrReplaceResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.User); err != nil { + return BasicClientCreateOrReplaceResponse{}, err + } + return result, nil +} + +// CreateOrUpdate - Adds a user or updates a user's fields. +// +// Creates or updates a User +// If the operation fails it returns an *azcore.ResponseError type. +// - id - The user's id. +// - resource - The resource instance. +// - options - BasicClientCreateOrUpdateOptions contains the optional parameters for the BasicClient.CreateOrUpdate method. +func (client *BasicClient) CreateOrUpdate(ctx context.Context, id int32, resource User, options *BasicClientCreateOrUpdateOptions) (BasicClientCreateOrUpdateResponse, error) { + var err error + const operationName = "BasicClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, id, resource, options) + if err != nil { + return BasicClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BasicClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return BasicClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *BasicClient) createOrUpdateCreateRequest(ctx context.Context, id int32, resource User, _ *BasicClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/azure/core/basic/users/{id}" + urlPath = strings.ReplaceAll(urlPath, "{id}", url.PathEscape(strconv.FormatInt(int64(id), 10))) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20221201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/merge-patch+json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *BasicClient) createOrUpdateHandleResponse(resp *http.Response) (BasicClientCreateOrUpdateResponse, error) { + result := BasicClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.User); err != nil { + return BasicClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Deletes a user. +// +// Deletes a User +// If the operation fails it returns an *azcore.ResponseError type. +// - id - The user's id. +// - options - BasicClientDeleteOptions contains the optional parameters for the BasicClient.Delete method. +func (client *BasicClient) Delete(ctx context.Context, id int32, options *BasicClientDeleteOptions) (BasicClientDeleteResponse, error) { + var err error + const operationName = "BasicClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, id, options) + if err != nil { + return BasicClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BasicClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return BasicClientDeleteResponse{}, err + } + return BasicClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *BasicClient) deleteCreateRequest(ctx context.Context, id int32, _ *BasicClientDeleteOptions) (*policy.Request, error) { + urlPath := "/azure/core/basic/users/{id}" + urlPath = strings.ReplaceAll(urlPath, "{id}", url.PathEscape(strconv.FormatInt(int64(id), 10))) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20221201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Export - Exports a user. +// +// Exports a User +// If the operation fails it returns an *azcore.ResponseError type. +// - id - The user's id. +// - formatParam - The format of the data. +// - options - BasicClientExportOptions contains the optional parameters for the BasicClient.Export method. +func (client *BasicClient) Export(ctx context.Context, id int32, formatParam string, options *BasicClientExportOptions) (BasicClientExportResponse, error) { + var err error + const operationName = "BasicClient.Export" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.exportCreateRequest(ctx, id, formatParam, options) + if err != nil { + return BasicClientExportResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BasicClientExportResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BasicClientExportResponse{}, err + } + resp, err := client.exportHandleResponse(httpResp) + return resp, err +} + +// exportCreateRequest creates the Export request. +func (client *BasicClient) exportCreateRequest(ctx context.Context, id int32, formatParam string, _ *BasicClientExportOptions) (*policy.Request, error) { + urlPath := "/azure/core/basic/users/{id}:export" + urlPath = strings.ReplaceAll(urlPath, "{id}", url.PathEscape(strconv.FormatInt(int64(id), 10))) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20221201Preview) + reqQP.Set("format", formatParam) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// exportHandleResponse handles the Export response. +func (client *BasicClient) exportHandleResponse(resp *http.Response) (BasicClientExportResponse, error) { + result := BasicClientExportResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.User); err != nil { + return BasicClientExportResponse{}, err + } + return result, nil +} + +// ExportAllUsers - Exports all users. +// +// Exports all users +// If the operation fails it returns an *azcore.ResponseError type. +// - formatParam - The format of the data. +// - options - BasicClientExportAllUsersOptions contains the optional parameters for the BasicClient.ExportAllUsers method. +func (client *BasicClient) ExportAllUsers(ctx context.Context, formatParam string, options *BasicClientExportAllUsersOptions) (BasicClientExportAllUsersResponse, error) { + var err error + const operationName = "BasicClient.ExportAllUsers" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.exportAllUsersCreateRequest(ctx, formatParam, options) + if err != nil { + return BasicClientExportAllUsersResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BasicClientExportAllUsersResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BasicClientExportAllUsersResponse{}, err + } + resp, err := client.exportAllUsersHandleResponse(httpResp) + return resp, err +} + +// exportAllUsersCreateRequest creates the ExportAllUsers request. +func (client *BasicClient) exportAllUsersCreateRequest(ctx context.Context, formatParam string, _ *BasicClientExportAllUsersOptions) (*policy.Request, error) { + urlPath := "/azure/core/basic/users:exportallusers" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20221201Preview) + reqQP.Set("format", formatParam) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// exportAllUsersHandleResponse handles the ExportAllUsers response. +func (client *BasicClient) exportAllUsersHandleResponse(resp *http.Response) (BasicClientExportAllUsersResponse, error) { + result := BasicClientExportAllUsersResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.UserList); err != nil { + return BasicClientExportAllUsersResponse{}, err + } + return result, nil +} + +// Get - Gets a user. +// +// Gets a User +// If the operation fails it returns an *azcore.ResponseError type. +// - id - The user's id. +// - options - BasicClientGetOptions contains the optional parameters for the BasicClient.Get method. +func (client *BasicClient) Get(ctx context.Context, id int32, options *BasicClientGetOptions) (BasicClientGetResponse, error) { + var err error + const operationName = "BasicClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, id, options) + if err != nil { + return BasicClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BasicClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BasicClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *BasicClient) getCreateRequest(ctx context.Context, id int32, _ *BasicClientGetOptions) (*policy.Request, error) { + urlPath := "/azure/core/basic/users/{id}" + urlPath = strings.ReplaceAll(urlPath, "{id}", url.PathEscape(strconv.FormatInt(int64(id), 10))) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20221201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *BasicClient) getHandleResponse(resp *http.Response) (BasicClientGetResponse, error) { + result := BasicClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.User); err != nil { + return BasicClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all users. +// +// Lists all Users +// - options - BasicClientListOptions contains the optional parameters for the BasicClient.NewListPager method. +func (client *BasicClient) NewListPager(options *BasicClientListOptions) *runtime.Pager[BasicClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[BasicClientListResponse]{ + More: func(page BasicClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *BasicClientListResponse) (BasicClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "BasicClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return BasicClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *BasicClient) listCreateRequest(ctx context.Context, options *BasicClientListOptions) (*policy.Request, error) { + urlPath := "/azure/core/basic/users" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20221201Preview) + if options != nil && options.Expand != nil { + for _, qv := range options.Expand { + reqQP.Add("expand", qv) + } + } + if options != nil && options.Filter != nil { + reqQP.Set("filter", *options.Filter) + } + if options != nil && options.Maxpagesize != nil { + reqQP.Set("maxpagesize", strconv.FormatInt(int64(*options.Maxpagesize), 10)) + } + if options != nil && options.Orderby != nil { + for _, qv := range options.Orderby { + reqQP.Add("orderby", qv) + } + } + if options != nil && options.Select != nil { + for _, qv := range options.Select { + reqQP.Add("select", qv) + } + } + if options != nil && options.Skip != nil { + reqQP.Set("skip", strconv.FormatInt(int64(*options.Skip), 10)) + } + if options != nil && options.Top != nil { + reqQP.Set("top", strconv.FormatInt(int64(*options.Top), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *BasicClient) listHandleResponse(resp *http.Response) (BasicClientListResponse, error) { + result := BasicClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PagedUser); err != nil { + return BasicClientListResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/core/basicgroup/zz_constants.go b/test/azure-http-specs/azure/core/basicgroup/zz_constants.go new file mode 100644 index 000000000000..4bcbac354c30 --- /dev/null +++ b/test/azure-http-specs/azure/core/basicgroup/zz_constants.go @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package basicgroup + +const ( + version20221201Preview string = "2022-12-01-preview" +) diff --git a/test/azure-http-specs/azure/core/basicgroup/zz_models.go b/test/azure-http-specs/azure/core/basicgroup/zz_models.go new file mode 100644 index 000000000000..5c68ab67ac8f --- /dev/null +++ b/test/azure-http-specs/azure/core/basicgroup/zz_models.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package basicgroup + +import "github.com/Azure/azure-sdk-for-go/sdk/azcore" + +// PagedUser - Paged collection of User items +type PagedUser struct { + // REQUIRED; The User items on this page + Value []*User + + // The link to the next page of items + NextLink *string +} + +// User - Details about a user. +type User struct { + // REQUIRED; The user's name. + Name *string + + // The user's order list + Orders []*UserOrder + + // READ-ONLY; The entity tag for this resource. + Etag *azcore.ETag + + // READ-ONLY; The user's id. + ID *int32 +} + +type UserList struct { + // REQUIRED + Users []*User +} + +// UserOrder for testing list with expand. +type UserOrder struct { + // REQUIRED; The user's order detail + Detail *string + + // REQUIRED; The user's id. + UserID *int32 + + // READ-ONLY; The user's id. + ID *int32 +} diff --git a/test/azure-http-specs/azure/core/basicgroup/zz_models_serde.go b/test/azure-http-specs/azure/core/basicgroup/zz_models_serde.go new file mode 100644 index 000000000000..23ca9427e807 --- /dev/null +++ b/test/azure-http-specs/azure/core/basicgroup/zz_models_serde.go @@ -0,0 +1,164 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package basicgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type PagedUser. +func (p PagedUser) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", p.NextLink) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PagedUser. +func (p *PagedUser) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &p.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type User. +func (u User) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", u.Etag) + populate(objectMap, "id", u.ID) + populate(objectMap, "name", u.Name) + populate(objectMap, "orders", u.Orders) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type User. +func (u *User) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &u.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &u.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &u.Name) + delete(rawMsg, key) + case "orders": + err = unpopulate(val, "Orders", &u.Orders) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserList. +func (u UserList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "users", u.Users) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserList. +func (u *UserList) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "users": + err = unpopulate(val, "Users", &u.Users) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserOrder. +func (u UserOrder) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "detail", u.Detail) + populate(objectMap, "id", u.ID) + populate(objectMap, "userId", u.UserID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserOrder. +func (u *UserOrder) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "detail": + err = unpopulate(val, "Detail", &u.Detail) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &u.ID) + delete(rawMsg, key) + case "userId": + err = unpopulate(val, "UserID", &u.UserID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/azure-http-specs/azure/core/basicgroup/zz_options.go b/test/azure-http-specs/azure/core/basicgroup/zz_options.go new file mode 100644 index 000000000000..4966f75d661d --- /dev/null +++ b/test/azure-http-specs/azure/core/basicgroup/zz_options.go @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package basicgroup + +// BasicClientCreateOrReplaceOptions contains the optional parameters for the BasicClient.CreateOrReplace method. +type BasicClientCreateOrReplaceOptions struct { + // placeholder for future optional parameters +} + +// BasicClientCreateOrUpdateOptions contains the optional parameters for the BasicClient.CreateOrUpdate method. +type BasicClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// BasicClientDeleteOptions contains the optional parameters for the BasicClient.Delete method. +type BasicClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// BasicClientExportAllUsersOptions contains the optional parameters for the BasicClient.ExportAllUsers method. +type BasicClientExportAllUsersOptions struct { + // placeholder for future optional parameters +} + +// BasicClientExportOptions contains the optional parameters for the BasicClient.Export method. +type BasicClientExportOptions struct { + // placeholder for future optional parameters +} + +// BasicClientGetOptions contains the optional parameters for the BasicClient.Get method. +type BasicClientGetOptions struct { + // placeholder for future optional parameters +} + +// BasicClientListOptions contains the optional parameters for the BasicClient.NewListPager method. +type BasicClientListOptions struct { + // Expand the indicated resources into the response. + Expand []string + + // Filter the result list using the given expression. + Filter *string + + // The maximum number of result items per page. + Maxpagesize *int32 + + // Expressions that specify the order of returned results. + Orderby []string + + // Select the specified fields to be included in the response. + Select []string + + // The number of result items to skip. + Skip *int32 + + // The number of result items to return. + Top *int32 +} diff --git a/test/azure-http-specs/azure/core/basicgroup/zz_responses.go b/test/azure-http-specs/azure/core/basicgroup/zz_responses.go new file mode 100644 index 000000000000..eb6944001683 --- /dev/null +++ b/test/azure-http-specs/azure/core/basicgroup/zz_responses.go @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package basicgroup + +// BasicClientCreateOrReplaceResponse contains the response from method BasicClient.CreateOrReplace. +type BasicClientCreateOrReplaceResponse struct { + // Details about a user. + User +} + +// BasicClientCreateOrUpdateResponse contains the response from method BasicClient.CreateOrUpdate. +type BasicClientCreateOrUpdateResponse struct { + // Details about a user. + User +} + +// BasicClientDeleteResponse contains the response from method BasicClient.Delete. +type BasicClientDeleteResponse struct { + // placeholder for future response values +} + +// BasicClientExportAllUsersResponse contains the response from method BasicClient.ExportAllUsers. +type BasicClientExportAllUsersResponse struct { + UserList +} + +// BasicClientExportResponse contains the response from method BasicClient.Export. +type BasicClientExportResponse struct { + // Details about a user. + User +} + +// BasicClientGetResponse contains the response from method BasicClient.Get. +type BasicClientGetResponse struct { + // Details about a user. + User +} + +// BasicClientListResponse contains the response from method BasicClient.NewListPager. +type BasicClientListResponse struct { + // Paged collection of User items + PagedUser +} diff --git a/test/azure-http-specs/azure/core/basicgroup/zz_version.go b/test/azure-http-specs/azure/core/basicgroup/zz_version.go new file mode 100644 index 000000000000..32569edc7dd1 --- /dev/null +++ b/test/azure-http-specs/azure/core/basicgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package basicgroup + +const ( + moduleName = "basicgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/core/coremodelgroup/LICENSE.txt b/test/azure-http-specs/azure/core/coremodelgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/core/coremodelgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/core/coremodelgroup/fake/zz_internal.go b/test/azure-http-specs/azure/core/coremodelgroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/azure-http-specs/azure/core/coremodelgroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/azure-http-specs/azure/core/coremodelgroup/fake/zz_model_server.go b/test/azure-http-specs/azure/core/coremodelgroup/fake/zz_model_server.go new file mode 100644 index 000000000000..c4b595d73384 --- /dev/null +++ b/test/azure-http-specs/azure/core/coremodelgroup/fake/zz_model_server.go @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ModelServer is a fake server for instances of the coremodelgroup.ModelClient type. +type ModelServer struct { + // ModelAzureCoreEmbeddingVectorServer contains the fakes for client ModelAzureCoreEmbeddingVectorClient + ModelAzureCoreEmbeddingVectorServer ModelAzureCoreEmbeddingVectorServer +} + +// NewModelServerTransport creates a new instance of ModelServerTransport with the provided implementation. +// The returned ModelServerTransport instance is connected to an instance of coremodelgroup.ModelClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewModelServerTransport(srv *ModelServer) *ModelServerTransport { + return &ModelServerTransport{srv: srv} +} + +// ModelServerTransport connects instances of coremodelgroup.ModelClient to instances of ModelServer. +// Don't use this type directly, use NewModelServerTransport instead. +type ModelServerTransport struct { + srv *ModelServer + trMu sync.Mutex + trModelAzureCoreEmbeddingVectorServer *ModelAzureCoreEmbeddingVectorServerTransport +} + +// Do implements the policy.Transporter interface for ModelServerTransport. +func (m *ModelServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (m *ModelServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "ModelAzureCoreEmbeddingVectorClient": + initServer(&m.trMu, &m.trModelAzureCoreEmbeddingVectorServer, func() *ModelAzureCoreEmbeddingVectorServerTransport { + return NewModelAzureCoreEmbeddingVectorServerTransport(&m.srv.ModelAzureCoreEmbeddingVectorServer) + }) + resp, err = m.trModelAzureCoreEmbeddingVectorServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to ModelServerTransport +var modelServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/core/coremodelgroup/fake/zz_modelazurecoreembeddingvector_server.go b/test/azure-http-specs/azure/core/coremodelgroup/fake/zz_modelazurecoreembeddingvector_server.go new file mode 100644 index 000000000000..d7c677f1a537 --- /dev/null +++ b/test/azure-http-specs/azure/core/coremodelgroup/fake/zz_modelazurecoreembeddingvector_server.go @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "coremodelgroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// ModelAzureCoreEmbeddingVectorServer is a fake server for instances of the coremodelgroup.ModelAzureCoreEmbeddingVectorClient type. +type ModelAzureCoreEmbeddingVectorServer struct { + // Get is the fake for method ModelAzureCoreEmbeddingVectorClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *coremodelgroup.ModelAzureCoreEmbeddingVectorClientGetOptions) (resp azfake.Responder[coremodelgroup.ModelAzureCoreEmbeddingVectorClientGetResponse], errResp azfake.ErrorResponder) + + // Post is the fake for method ModelAzureCoreEmbeddingVectorClient.Post + // HTTP status codes to indicate success: http.StatusOK + Post func(ctx context.Context, body coremodelgroup.AzureEmbeddingModel, options *coremodelgroup.ModelAzureCoreEmbeddingVectorClientPostOptions) (resp azfake.Responder[coremodelgroup.ModelAzureCoreEmbeddingVectorClientPostResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ModelAzureCoreEmbeddingVectorClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body []*int32, options *coremodelgroup.ModelAzureCoreEmbeddingVectorClientPutOptions) (resp azfake.Responder[coremodelgroup.ModelAzureCoreEmbeddingVectorClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewModelAzureCoreEmbeddingVectorServerTransport creates a new instance of ModelAzureCoreEmbeddingVectorServerTransport with the provided implementation. +// The returned ModelAzureCoreEmbeddingVectorServerTransport instance is connected to an instance of coremodelgroup.ModelAzureCoreEmbeddingVectorClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewModelAzureCoreEmbeddingVectorServerTransport(srv *ModelAzureCoreEmbeddingVectorServer) *ModelAzureCoreEmbeddingVectorServerTransport { + return &ModelAzureCoreEmbeddingVectorServerTransport{srv: srv} +} + +// ModelAzureCoreEmbeddingVectorServerTransport connects instances of coremodelgroup.ModelAzureCoreEmbeddingVectorClient to instances of ModelAzureCoreEmbeddingVectorServer. +// Don't use this type directly, use NewModelAzureCoreEmbeddingVectorServerTransport instead. +type ModelAzureCoreEmbeddingVectorServerTransport struct { + srv *ModelAzureCoreEmbeddingVectorServer +} + +// Do implements the policy.Transporter interface for ModelAzureCoreEmbeddingVectorServerTransport. +func (m *ModelAzureCoreEmbeddingVectorServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToMethodFake(req, method) +} + +func (m *ModelAzureCoreEmbeddingVectorServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if modelAzureCoreEmbeddingVectorServerTransportInterceptor != nil { + res.resp, res.err, intercepted = modelAzureCoreEmbeddingVectorServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ModelAzureCoreEmbeddingVectorClient.Get": + res.resp, res.err = m.dispatchGet(req) + case "ModelAzureCoreEmbeddingVectorClient.Post": + res.resp, res.err = m.dispatchPost(req) + case "ModelAzureCoreEmbeddingVectorClient.Put": + res.resp, res.err = m.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *ModelAzureCoreEmbeddingVectorServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if m.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := m.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Int32Array, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *ModelAzureCoreEmbeddingVectorServerTransport) dispatchPost(req *http.Request) (*http.Response, error) { + if m.srv.Post == nil { + return nil, &nonRetriableError{errors.New("fake for method Post not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[coremodelgroup.AzureEmbeddingModel](req) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.Post(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).AzureEmbeddingModel, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *ModelAzureCoreEmbeddingVectorServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if m.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[[]*int32](req) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ModelAzureCoreEmbeddingVectorServerTransport +var modelAzureCoreEmbeddingVectorServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/core/coremodelgroup/go.mod b/test/azure-http-specs/azure/core/coremodelgroup/go.mod new file mode 100644 index 000000000000..2db7d34848b6 --- /dev/null +++ b/test/azure-http-specs/azure/core/coremodelgroup/go.mod @@ -0,0 +1,17 @@ +module coremodelgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/core/coremodelgroup/go.sum b/test/azure-http-specs/azure/core/coremodelgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/core/coremodelgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/core/coremodelgroup/modelazurecoreembeddingvector_client_test.go b/test/azure-http-specs/azure/core/coremodelgroup/modelazurecoreembeddingvector_client_test.go new file mode 100644 index 000000000000..9258efcbcd1e --- /dev/null +++ b/test/azure-http-specs/azure/core/coremodelgroup/modelazurecoreembeddingvector_client_test.go @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package coremodelgroup_test + +import ( + "context" + "coremodelgroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestModelAzureCoreEmbeddingVectorClient_Get(t *testing.T) { + input := []*int32{to.Ptr(int32(0)), to.Ptr(int32(1)), to.Ptr(int32(2)), to.Ptr(int32(3)), to.Ptr(int32(4))} + client, err := coremodelgroup.NewModelClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + + resp, err := client.NewModelAzureCoreEmbeddingVectorClient().Get(context.Background(), nil) + require.NoError(t, err) + require.Equal(t, input, resp.Int32Array) +} + +func TestModelAzureCoreEmbeddingVectorClient_Post(t *testing.T) { + input := coremodelgroup.AzureEmbeddingModel{Embedding: []*int32{to.Ptr(int32(0)), to.Ptr(int32(1)), to.Ptr(int32(2)), to.Ptr(int32(3)), to.Ptr(int32(4))}} + client, err := coremodelgroup.NewModelClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewModelAzureCoreEmbeddingVectorClient().Post(context.Background(), input, nil) + require.NoError(t, err) + require.NotNil(t, resp) + expected := coremodelgroup.AzureEmbeddingModel{Embedding: []*int32{to.Ptr(int32(5)), to.Ptr(int32(6)), to.Ptr(int32(7)), to.Ptr(int32(8)), to.Ptr(int32(9))}} + require.Equal(t, expected, resp.AzureEmbeddingModel) +} + +func TestModelAzureCoreEmbeddingVectorClient_Put(t *testing.T) { + input := []*int32{to.Ptr(int32(0)), to.Ptr(int32(1)), to.Ptr(int32(2)), to.Ptr(int32(3)), to.Ptr(int32(4))} + client, err := coremodelgroup.NewModelClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewModelAzureCoreEmbeddingVectorClient().Put(context.Background(), input, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/azure/core/coremodelgroup/testdata/_metadata.json b/test/azure-http-specs/azure/core/coremodelgroup/testdata/_metadata.json new file mode 100644 index 000000000000..9d587f411059 --- /dev/null +++ b/test/azure-http-specs/azure/core/coremodelgroup/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "_Specs_.Azure.Core.Model": "2022-12-01-preview" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/core/coremodelgroup/zz_model_client.go b/test/azure-http-specs/azure/core/coremodelgroup/zz_model_client.go new file mode 100644 index 000000000000..14359db8ffaa --- /dev/null +++ b/test/azure-http-specs/azure/core/coremodelgroup/zz_model_client.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coremodelgroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// ModelClient contains the methods for the Model group. +// Don't use this type directly, use NewModelClientWithNoCredential() instead. +type ModelClient struct { + internal *azcore.Client + endpoint string +} + +// ModelClientOptions contains the optional values for creating a [ModelClient]. +type ModelClientOptions struct { + azcore.ClientOptions +} + +// NewModelClientWithNoCredential creates a new instance of ModelClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewModelClientWithNoCredential(endpoint string, options *ModelClientOptions) (*ModelClient, error) { + if options == nil { + options = &ModelClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &ModelClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewModelAzureCoreEmbeddingVectorClient creates a new instance of [ModelAzureCoreEmbeddingVectorClient]. +func (client *ModelClient) NewModelAzureCoreEmbeddingVectorClient() *ModelAzureCoreEmbeddingVectorClient { + return &ModelAzureCoreEmbeddingVectorClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/azure-http-specs/azure/core/coremodelgroup/zz_modelazurecoreembeddingvector_client.go b/test/azure-http-specs/azure/core/coremodelgroup/zz_modelazurecoreembeddingvector_client.go new file mode 100644 index 000000000000..c39d9684dbbc --- /dev/null +++ b/test/azure-http-specs/azure/core/coremodelgroup/zz_modelazurecoreembeddingvector_client.go @@ -0,0 +1,157 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coremodelgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ModelAzureCoreEmbeddingVectorClient contains the methods for the ModelAzureCoreEmbeddingVector group. +// Don't use this type directly, use [ModelClient.NewModelAzureCoreEmbeddingVectorClient] instead. +type ModelAzureCoreEmbeddingVectorClient struct { + internal *azcore.Client + endpoint string +} + +// Get - get an embedding vector +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ModelAzureCoreEmbeddingVectorClientGetOptions contains the optional parameters for the ModelAzureCoreEmbeddingVectorClient.Get +// method. +func (client *ModelAzureCoreEmbeddingVectorClient) Get(ctx context.Context, options *ModelAzureCoreEmbeddingVectorClientGetOptions) (ModelAzureCoreEmbeddingVectorClientGetResponse, error) { + var err error + const operationName = "ModelAzureCoreEmbeddingVectorClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ModelAzureCoreEmbeddingVectorClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ModelAzureCoreEmbeddingVectorClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ModelAzureCoreEmbeddingVectorClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ModelAzureCoreEmbeddingVectorClient) getCreateRequest(ctx context.Context, _ *ModelAzureCoreEmbeddingVectorClientGetOptions) (*policy.Request, error) { + urlPath := "/azure/core/model/embeddingVector" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ModelAzureCoreEmbeddingVectorClient) getHandleResponse(resp *http.Response) (ModelAzureCoreEmbeddingVectorClientGetResponse, error) { + result := ModelAzureCoreEmbeddingVectorClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Int32Array); err != nil { + return ModelAzureCoreEmbeddingVectorClientGetResponse{}, err + } + return result, nil +} + +// Post - post a model which has an embeddingVector property +// If the operation fails it returns an *azcore.ResponseError type. +// - body - _ +// - options - ModelAzureCoreEmbeddingVectorClientPostOptions contains the optional parameters for the ModelAzureCoreEmbeddingVectorClient.Post +// method. +func (client *ModelAzureCoreEmbeddingVectorClient) Post(ctx context.Context, body AzureEmbeddingModel, options *ModelAzureCoreEmbeddingVectorClientPostOptions) (ModelAzureCoreEmbeddingVectorClientPostResponse, error) { + var err error + const operationName = "ModelAzureCoreEmbeddingVectorClient.Post" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.postCreateRequest(ctx, body, options) + if err != nil { + return ModelAzureCoreEmbeddingVectorClientPostResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ModelAzureCoreEmbeddingVectorClientPostResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ModelAzureCoreEmbeddingVectorClientPostResponse{}, err + } + resp, err := client.postHandleResponse(httpResp) + return resp, err +} + +// postCreateRequest creates the Post request. +func (client *ModelAzureCoreEmbeddingVectorClient) postCreateRequest(ctx context.Context, body AzureEmbeddingModel, _ *ModelAzureCoreEmbeddingVectorClientPostOptions) (*policy.Request, error) { + urlPath := "/azure/core/model/embeddingVector" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// postHandleResponse handles the Post response. +func (client *ModelAzureCoreEmbeddingVectorClient) postHandleResponse(resp *http.Response) (ModelAzureCoreEmbeddingVectorClientPostResponse, error) { + result := ModelAzureCoreEmbeddingVectorClientPostResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AzureEmbeddingModel); err != nil { + return ModelAzureCoreEmbeddingVectorClientPostResponse{}, err + } + return result, nil +} + +// Put - put an embedding vector +// If the operation fails it returns an *azcore.ResponseError type. +// - body - _ +// - options - ModelAzureCoreEmbeddingVectorClientPutOptions contains the optional parameters for the ModelAzureCoreEmbeddingVectorClient.Put +// method. +func (client *ModelAzureCoreEmbeddingVectorClient) Put(ctx context.Context, body []*int32, options *ModelAzureCoreEmbeddingVectorClientPutOptions) (ModelAzureCoreEmbeddingVectorClientPutResponse, error) { + var err error + const operationName = "ModelAzureCoreEmbeddingVectorClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ModelAzureCoreEmbeddingVectorClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ModelAzureCoreEmbeddingVectorClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ModelAzureCoreEmbeddingVectorClientPutResponse{}, err + } + return ModelAzureCoreEmbeddingVectorClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ModelAzureCoreEmbeddingVectorClient) putCreateRequest(ctx context.Context, body []*int32, _ *ModelAzureCoreEmbeddingVectorClientPutOptions) (*policy.Request, error) { + urlPath := "/azure/core/model/embeddingVector" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/azure/core/coremodelgroup/zz_models.go b/test/azure-http-specs/azure/core/coremodelgroup/zz_models.go new file mode 100644 index 000000000000..9e03ed928b50 --- /dev/null +++ b/test/azure-http-specs/azure/core/coremodelgroup/zz_models.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coremodelgroup + +type AzureEmbeddingModel struct { + // REQUIRED + Embedding []*int32 +} diff --git a/test/azure-http-specs/azure/core/coremodelgroup/zz_models_serde.go b/test/azure-http-specs/azure/core/coremodelgroup/zz_models_serde.go new file mode 100644 index 000000000000..d7411cab3d4b --- /dev/null +++ b/test/azure-http-specs/azure/core/coremodelgroup/zz_models_serde.go @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coremodelgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type AzureEmbeddingModel. +func (a AzureEmbeddingModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "embedding", a.Embedding) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureEmbeddingModel. +func (a *AzureEmbeddingModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "embedding": + err = unpopulate(val, "Embedding", &a.Embedding) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/azure-http-specs/azure/core/coremodelgroup/zz_options.go b/test/azure-http-specs/azure/core/coremodelgroup/zz_options.go new file mode 100644 index 000000000000..d6e0887f31de --- /dev/null +++ b/test/azure-http-specs/azure/core/coremodelgroup/zz_options.go @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coremodelgroup + +// ModelAzureCoreEmbeddingVectorClientGetOptions contains the optional parameters for the ModelAzureCoreEmbeddingVectorClient.Get +// method. +type ModelAzureCoreEmbeddingVectorClientGetOptions struct { + // placeholder for future optional parameters +} + +// ModelAzureCoreEmbeddingVectorClientPostOptions contains the optional parameters for the ModelAzureCoreEmbeddingVectorClient.Post +// method. +type ModelAzureCoreEmbeddingVectorClientPostOptions struct { + // placeholder for future optional parameters +} + +// ModelAzureCoreEmbeddingVectorClientPutOptions contains the optional parameters for the ModelAzureCoreEmbeddingVectorClient.Put +// method. +type ModelAzureCoreEmbeddingVectorClientPutOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/azure/core/coremodelgroup/zz_responses.go b/test/azure-http-specs/azure/core/coremodelgroup/zz_responses.go new file mode 100644 index 000000000000..97c3eaab7acf --- /dev/null +++ b/test/azure-http-specs/azure/core/coremodelgroup/zz_responses.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package coremodelgroup + +// ModelAzureCoreEmbeddingVectorClientGetResponse contains the response from method ModelAzureCoreEmbeddingVectorClient.Get. +type ModelAzureCoreEmbeddingVectorClientGetResponse struct { + Int32Array []*int32 +} + +// ModelAzureCoreEmbeddingVectorClientPostResponse contains the response from method ModelAzureCoreEmbeddingVectorClient.Post. +type ModelAzureCoreEmbeddingVectorClientPostResponse struct { + AzureEmbeddingModel +} + +// ModelAzureCoreEmbeddingVectorClientPutResponse contains the response from method ModelAzureCoreEmbeddingVectorClient.Put. +type ModelAzureCoreEmbeddingVectorClientPutResponse struct { + // placeholder for future response values +} diff --git a/test/azure-http-specs/azure/core/coremodelgroup/zz_version.go b/test/azure-http-specs/azure/core/coremodelgroup/zz_version.go new file mode 100644 index 000000000000..d85c111adb0a --- /dev/null +++ b/test/azure-http-specs/azure/core/coremodelgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package coremodelgroup + +const ( + moduleName = "coremodelgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/core/corescalargroup/LICENSE.txt b/test/azure-http-specs/azure/core/corescalargroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/core/corescalargroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/core/corescalargroup/azurelocationscalar_client_test.go b/test/azure-http-specs/azure/core/corescalargroup/azurelocationscalar_client_test.go new file mode 100644 index 000000000000..da4af6a52be6 --- /dev/null +++ b/test/azure-http-specs/azure/core/corescalargroup/azurelocationscalar_client_test.go @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package corescalargroup_test + +import ( + "context" + "corescalargroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestAzureLocationScalarClient_Get(t *testing.T) { + client, err := corescalargroup.NewScalarClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewScalarAzureLocationScalarClient().Get(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, "eastus", *resp.Value) +} + +func TestAzureLocationScalarClient_Header(t *testing.T) { + client, err := corescalargroup.NewScalarClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewScalarAzureLocationScalarClient().Header(context.Background(), "eastus", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestAzureLocationScalarClient_Post(t *testing.T) { + client, err := corescalargroup.NewScalarClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewScalarAzureLocationScalarClient().Post(context.Background(), corescalargroup.AzureLocationModel{ + Location: to.Ptr("eastus"), + }, nil) + require.NoError(t, err) + require.NotNil(t, resp.Location) + require.EqualValues(t, "eastus", *resp.Location) +} + +func TestAzureLocationScalarClient_Put(t *testing.T) { + client, err := corescalargroup.NewScalarClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewScalarAzureLocationScalarClient().Put(context.Background(), "eastus", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestAzureLocationScalarClient_Query(t *testing.T) { + client, err := corescalargroup.NewScalarClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewScalarAzureLocationScalarClient().Query(context.Background(), "eastus", nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/azure/core/corescalargroup/fake/zz_internal.go b/test/azure-http-specs/azure/core/corescalargroup/fake/zz_internal.go new file mode 100644 index 000000000000..df56a9f6266b --- /dev/null +++ b/test/azure-http-specs/azure/core/corescalargroup/fake/zz_internal.go @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getHeaderValue(h http.Header, k string) string { + v := h[k] + if len(v) == 0 { + return "" + } + return v[0] +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/azure-http-specs/azure/core/corescalargroup/fake/zz_scalar_server.go b/test/azure-http-specs/azure/core/corescalargroup/fake/zz_scalar_server.go new file mode 100644 index 000000000000..273a763b1102 --- /dev/null +++ b/test/azure-http-specs/azure/core/corescalargroup/fake/zz_scalar_server.go @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ScalarServer is a fake server for instances of the corescalargroup.ScalarClient type. +type ScalarServer struct { + // ScalarAzureLocationScalarServer contains the fakes for client ScalarAzureLocationScalarClient + ScalarAzureLocationScalarServer ScalarAzureLocationScalarServer +} + +// NewScalarServerTransport creates a new instance of ScalarServerTransport with the provided implementation. +// The returned ScalarServerTransport instance is connected to an instance of corescalargroup.ScalarClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewScalarServerTransport(srv *ScalarServer) *ScalarServerTransport { + return &ScalarServerTransport{srv: srv} +} + +// ScalarServerTransport connects instances of corescalargroup.ScalarClient to instances of ScalarServer. +// Don't use this type directly, use NewScalarServerTransport instead. +type ScalarServerTransport struct { + srv *ScalarServer + trMu sync.Mutex + trScalarAzureLocationScalarServer *ScalarAzureLocationScalarServerTransport +} + +// Do implements the policy.Transporter interface for ScalarServerTransport. +func (s *ScalarServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (s *ScalarServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "ScalarAzureLocationScalarClient": + initServer(&s.trMu, &s.trScalarAzureLocationScalarServer, func() *ScalarAzureLocationScalarServerTransport { + return NewScalarAzureLocationScalarServerTransport(&s.srv.ScalarAzureLocationScalarServer) + }) + resp, err = s.trScalarAzureLocationScalarServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to ScalarServerTransport +var scalarServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/core/corescalargroup/fake/zz_scalarazurelocationscalar_server.go b/test/azure-http-specs/azure/core/corescalargroup/fake/zz_scalarazurelocationscalar_server.go new file mode 100644 index 000000000000..ba3b8cc583d4 --- /dev/null +++ b/test/azure-http-specs/azure/core/corescalargroup/fake/zz_scalarazurelocationscalar_server.go @@ -0,0 +1,210 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "corescalargroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// ScalarAzureLocationScalarServer is a fake server for instances of the corescalargroup.ScalarAzureLocationScalarClient type. +type ScalarAzureLocationScalarServer struct { + // Get is the fake for method ScalarAzureLocationScalarClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *corescalargroup.ScalarAzureLocationScalarClientGetOptions) (resp azfake.Responder[corescalargroup.ScalarAzureLocationScalarClientGetResponse], errResp azfake.ErrorResponder) + + // Header is the fake for method ScalarAzureLocationScalarClient.Header + // HTTP status codes to indicate success: http.StatusNoContent + Header func(ctx context.Context, region string, options *corescalargroup.ScalarAzureLocationScalarClientHeaderOptions) (resp azfake.Responder[corescalargroup.ScalarAzureLocationScalarClientHeaderResponse], errResp azfake.ErrorResponder) + + // Post is the fake for method ScalarAzureLocationScalarClient.Post + // HTTP status codes to indicate success: http.StatusOK + Post func(ctx context.Context, body corescalargroup.AzureLocationModel, options *corescalargroup.ScalarAzureLocationScalarClientPostOptions) (resp azfake.Responder[corescalargroup.ScalarAzureLocationScalarClientPostResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ScalarAzureLocationScalarClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body string, options *corescalargroup.ScalarAzureLocationScalarClientPutOptions) (resp azfake.Responder[corescalargroup.ScalarAzureLocationScalarClientPutResponse], errResp azfake.ErrorResponder) + + // Query is the fake for method ScalarAzureLocationScalarClient.Query + // HTTP status codes to indicate success: http.StatusNoContent + Query func(ctx context.Context, region string, options *corescalargroup.ScalarAzureLocationScalarClientQueryOptions) (resp azfake.Responder[corescalargroup.ScalarAzureLocationScalarClientQueryResponse], errResp azfake.ErrorResponder) +} + +// NewScalarAzureLocationScalarServerTransport creates a new instance of ScalarAzureLocationScalarServerTransport with the provided implementation. +// The returned ScalarAzureLocationScalarServerTransport instance is connected to an instance of corescalargroup.ScalarAzureLocationScalarClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewScalarAzureLocationScalarServerTransport(srv *ScalarAzureLocationScalarServer) *ScalarAzureLocationScalarServerTransport { + return &ScalarAzureLocationScalarServerTransport{srv: srv} +} + +// ScalarAzureLocationScalarServerTransport connects instances of corescalargroup.ScalarAzureLocationScalarClient to instances of ScalarAzureLocationScalarServer. +// Don't use this type directly, use NewScalarAzureLocationScalarServerTransport instead. +type ScalarAzureLocationScalarServerTransport struct { + srv *ScalarAzureLocationScalarServer +} + +// Do implements the policy.Transporter interface for ScalarAzureLocationScalarServerTransport. +func (s *ScalarAzureLocationScalarServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ScalarAzureLocationScalarServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if scalarAzureLocationScalarServerTransportInterceptor != nil { + res.resp, res.err, intercepted = scalarAzureLocationScalarServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ScalarAzureLocationScalarClient.Get": + res.resp, res.err = s.dispatchGet(req) + case "ScalarAzureLocationScalarClient.Header": + res.resp, res.err = s.dispatchHeader(req) + case "ScalarAzureLocationScalarClient.Post": + res.resp, res.err = s.dispatchPost(req) + case "ScalarAzureLocationScalarClient.Put": + res.resp, res.err = s.dispatchPut(req) + case "ScalarAzureLocationScalarClient.Query": + res.resp, res.err = s.dispatchQuery(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ScalarAzureLocationScalarServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if s.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := s.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Value, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScalarAzureLocationScalarServerTransport) dispatchHeader(req *http.Request) (*http.Response, error) { + if s.srv.Header == nil { + return nil, &nonRetriableError{errors.New("fake for method Header not implemented")} + } + respr, errRespr := s.srv.Header(req.Context(), getHeaderValue(req.Header, "region"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScalarAzureLocationScalarServerTransport) dispatchPost(req *http.Request) (*http.Response, error) { + if s.srv.Post == nil { + return nil, &nonRetriableError{errors.New("fake for method Post not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[corescalargroup.AzureLocationModel](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Post(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).AzureLocationModel, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScalarAzureLocationScalarServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if s.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[string](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScalarAzureLocationScalarServerTransport) dispatchQuery(req *http.Request) (*http.Response, error) { + if s.srv.Query == nil { + return nil, &nonRetriableError{errors.New("fake for method Query not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.Query(req.Context(), qp.Get("region"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ScalarAzureLocationScalarServerTransport +var scalarAzureLocationScalarServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/core/corescalargroup/go.mod b/test/azure-http-specs/azure/core/corescalargroup/go.mod new file mode 100644 index 000000000000..434ccf138efd --- /dev/null +++ b/test/azure-http-specs/azure/core/corescalargroup/go.mod @@ -0,0 +1,17 @@ +module corescalargroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/core/corescalargroup/go.sum b/test/azure-http-specs/azure/core/corescalargroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/core/corescalargroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/core/corescalargroup/testdata/_metadata.json b/test/azure-http-specs/azure/core/corescalargroup/testdata/_metadata.json new file mode 100644 index 000000000000..97e50b4cea8d --- /dev/null +++ b/test/azure-http-specs/azure/core/corescalargroup/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "_Specs_.Azure.Core.Scalar": "2022-12-01-preview" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/core/corescalargroup/zz_models.go b/test/azure-http-specs/azure/core/corescalargroup/zz_models.go new file mode 100644 index 000000000000..4943b105998c --- /dev/null +++ b/test/azure-http-specs/azure/core/corescalargroup/zz_models.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package corescalargroup + +type AzureLocationModel struct { + // REQUIRED + Location *string +} diff --git a/test/azure-http-specs/azure/core/corescalargroup/zz_models_serde.go b/test/azure-http-specs/azure/core/corescalargroup/zz_models_serde.go new file mode 100644 index 000000000000..c7a43e440658 --- /dev/null +++ b/test/azure-http-specs/azure/core/corescalargroup/zz_models_serde.go @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package corescalargroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type AzureLocationModel. +func (a AzureLocationModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "location", a.Location) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureLocationModel. +func (a *AzureLocationModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "location": + err = unpopulate(val, "Location", &a.Location) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/azure-http-specs/azure/core/corescalargroup/zz_options.go b/test/azure-http-specs/azure/core/corescalargroup/zz_options.go new file mode 100644 index 000000000000..c113e807fb86 --- /dev/null +++ b/test/azure-http-specs/azure/core/corescalargroup/zz_options.go @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package corescalargroup + +// ScalarAzureLocationScalarClientGetOptions contains the optional parameters for the ScalarAzureLocationScalarClient.Get +// method. +type ScalarAzureLocationScalarClientGetOptions struct { + // placeholder for future optional parameters +} + +// ScalarAzureLocationScalarClientHeaderOptions contains the optional parameters for the ScalarAzureLocationScalarClient.Header +// method. +type ScalarAzureLocationScalarClientHeaderOptions struct { + // placeholder for future optional parameters +} + +// ScalarAzureLocationScalarClientPostOptions contains the optional parameters for the ScalarAzureLocationScalarClient.Post +// method. +type ScalarAzureLocationScalarClientPostOptions struct { + // placeholder for future optional parameters +} + +// ScalarAzureLocationScalarClientPutOptions contains the optional parameters for the ScalarAzureLocationScalarClient.Put +// method. +type ScalarAzureLocationScalarClientPutOptions struct { + // placeholder for future optional parameters +} + +// ScalarAzureLocationScalarClientQueryOptions contains the optional parameters for the ScalarAzureLocationScalarClient.Query +// method. +type ScalarAzureLocationScalarClientQueryOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/azure/core/corescalargroup/zz_responses.go b/test/azure-http-specs/azure/core/corescalargroup/zz_responses.go new file mode 100644 index 000000000000..2c994512de49 --- /dev/null +++ b/test/azure-http-specs/azure/core/corescalargroup/zz_responses.go @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package corescalargroup + +// ScalarAzureLocationScalarClientGetResponse contains the response from method ScalarAzureLocationScalarClient.Get. +type ScalarAzureLocationScalarClientGetResponse struct { + Value *string +} + +// ScalarAzureLocationScalarClientHeaderResponse contains the response from method ScalarAzureLocationScalarClient.Header. +type ScalarAzureLocationScalarClientHeaderResponse struct { + // placeholder for future response values +} + +// ScalarAzureLocationScalarClientPostResponse contains the response from method ScalarAzureLocationScalarClient.Post. +type ScalarAzureLocationScalarClientPostResponse struct { + AzureLocationModel +} + +// ScalarAzureLocationScalarClientPutResponse contains the response from method ScalarAzureLocationScalarClient.Put. +type ScalarAzureLocationScalarClientPutResponse struct { + // placeholder for future response values +} + +// ScalarAzureLocationScalarClientQueryResponse contains the response from method ScalarAzureLocationScalarClient.Query. +type ScalarAzureLocationScalarClientQueryResponse struct { + // placeholder for future response values +} diff --git a/test/azure-http-specs/azure/core/corescalargroup/zz_scalar_client.go b/test/azure-http-specs/azure/core/corescalargroup/zz_scalar_client.go new file mode 100644 index 000000000000..b2d3efe8d944 --- /dev/null +++ b/test/azure-http-specs/azure/core/corescalargroup/zz_scalar_client.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package corescalargroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// ScalarClient contains the methods for the Scalar group. +// Don't use this type directly, use NewScalarClientWithNoCredential() instead. +type ScalarClient struct { + internal *azcore.Client + endpoint string +} + +// ScalarClientOptions contains the optional values for creating a [ScalarClient]. +type ScalarClientOptions struct { + azcore.ClientOptions +} + +// NewScalarClientWithNoCredential creates a new instance of ScalarClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewScalarClientWithNoCredential(endpoint string, options *ScalarClientOptions) (*ScalarClient, error) { + if options == nil { + options = &ScalarClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &ScalarClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewScalarAzureLocationScalarClient creates a new instance of [ScalarAzureLocationScalarClient]. +func (client *ScalarClient) NewScalarAzureLocationScalarClient() *ScalarAzureLocationScalarClient { + return &ScalarAzureLocationScalarClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/azure-http-specs/azure/core/corescalargroup/zz_scalarazurelocationscalar_client.go b/test/azure-http-specs/azure/core/corescalargroup/zz_scalarazurelocationscalar_client.go new file mode 100644 index 000000000000..1e40a9864758 --- /dev/null +++ b/test/azure-http-specs/azure/core/corescalargroup/zz_scalarazurelocationscalar_client.go @@ -0,0 +1,234 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package corescalargroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// ScalarAzureLocationScalarClient contains the methods for the ScalarAzureLocationScalar group. +// Don't use this type directly, use [ScalarClient.NewScalarAzureLocationScalarClient] instead. +type ScalarAzureLocationScalarClient struct { + internal *azcore.Client + endpoint string +} + +// Get - get azureLocation value +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ScalarAzureLocationScalarClientGetOptions contains the optional parameters for the ScalarAzureLocationScalarClient.Get +// method. +func (client *ScalarAzureLocationScalarClient) Get(ctx context.Context, options *ScalarAzureLocationScalarClientGetOptions) (ScalarAzureLocationScalarClientGetResponse, error) { + var err error + const operationName = "ScalarAzureLocationScalarClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ScalarAzureLocationScalarClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScalarAzureLocationScalarClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScalarAzureLocationScalarClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ScalarAzureLocationScalarClient) getCreateRequest(ctx context.Context, _ *ScalarAzureLocationScalarClientGetOptions) (*policy.Request, error) { + urlPath := "/azure/core/scalar/azureLocation" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ScalarAzureLocationScalarClient) getHandleResponse(resp *http.Response) (ScalarAzureLocationScalarClientGetResponse, error) { + result := ScalarAzureLocationScalarClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Value); err != nil { + return ScalarAzureLocationScalarClientGetResponse{}, err + } + return result, nil +} + +// Header - azureLocation value header +// If the operation fails it returns an *azcore.ResponseError type. +// - region - _ +// - options - ScalarAzureLocationScalarClientHeaderOptions contains the optional parameters for the ScalarAzureLocationScalarClient.Header +// method. +func (client *ScalarAzureLocationScalarClient) Header(ctx context.Context, region string, options *ScalarAzureLocationScalarClientHeaderOptions) (ScalarAzureLocationScalarClientHeaderResponse, error) { + var err error + const operationName = "ScalarAzureLocationScalarClient.Header" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.headerCreateRequest(ctx, region, options) + if err != nil { + return ScalarAzureLocationScalarClientHeaderResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScalarAzureLocationScalarClientHeaderResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ScalarAzureLocationScalarClientHeaderResponse{}, err + } + return ScalarAzureLocationScalarClientHeaderResponse{}, nil +} + +// headerCreateRequest creates the Header request. +func (client *ScalarAzureLocationScalarClient) headerCreateRequest(ctx context.Context, region string, _ *ScalarAzureLocationScalarClientHeaderOptions) (*policy.Request, error) { + urlPath := "/azure/core/scalar/azureLocation/header" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["region"] = []string{region} + return req, nil +} + +// Post - post a model which has azureLocation property +// If the operation fails it returns an *azcore.ResponseError type. +// - body - _ +// - options - ScalarAzureLocationScalarClientPostOptions contains the optional parameters for the ScalarAzureLocationScalarClient.Post +// method. +func (client *ScalarAzureLocationScalarClient) Post(ctx context.Context, body AzureLocationModel, options *ScalarAzureLocationScalarClientPostOptions) (ScalarAzureLocationScalarClientPostResponse, error) { + var err error + const operationName = "ScalarAzureLocationScalarClient.Post" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.postCreateRequest(ctx, body, options) + if err != nil { + return ScalarAzureLocationScalarClientPostResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScalarAzureLocationScalarClientPostResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScalarAzureLocationScalarClientPostResponse{}, err + } + resp, err := client.postHandleResponse(httpResp) + return resp, err +} + +// postCreateRequest creates the Post request. +func (client *ScalarAzureLocationScalarClient) postCreateRequest(ctx context.Context, body AzureLocationModel, _ *ScalarAzureLocationScalarClientPostOptions) (*policy.Request, error) { + urlPath := "/azure/core/scalar/azureLocation" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// postHandleResponse handles the Post response. +func (client *ScalarAzureLocationScalarClient) postHandleResponse(resp *http.Response) (ScalarAzureLocationScalarClientPostResponse, error) { + result := ScalarAzureLocationScalarClientPostResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AzureLocationModel); err != nil { + return ScalarAzureLocationScalarClientPostResponse{}, err + } + return result, nil +} + +// Put - put azureLocation value +// If the operation fails it returns an *azcore.ResponseError type. +// - body - _ +// - options - ScalarAzureLocationScalarClientPutOptions contains the optional parameters for the ScalarAzureLocationScalarClient.Put +// method. +func (client *ScalarAzureLocationScalarClient) Put(ctx context.Context, body string, options *ScalarAzureLocationScalarClientPutOptions) (ScalarAzureLocationScalarClientPutResponse, error) { + var err error + const operationName = "ScalarAzureLocationScalarClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ScalarAzureLocationScalarClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScalarAzureLocationScalarClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ScalarAzureLocationScalarClientPutResponse{}, err + } + return ScalarAzureLocationScalarClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ScalarAzureLocationScalarClient) putCreateRequest(ctx context.Context, body string, _ *ScalarAzureLocationScalarClientPutOptions) (*policy.Request, error) { + urlPath := "/azure/core/scalar/azureLocation" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// Query - azureLocation value query +// If the operation fails it returns an *azcore.ResponseError type. +// - region - _ +// - options - ScalarAzureLocationScalarClientQueryOptions contains the optional parameters for the ScalarAzureLocationScalarClient.Query +// method. +func (client *ScalarAzureLocationScalarClient) Query(ctx context.Context, region string, options *ScalarAzureLocationScalarClientQueryOptions) (ScalarAzureLocationScalarClientQueryResponse, error) { + var err error + const operationName = "ScalarAzureLocationScalarClient.Query" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.queryCreateRequest(ctx, region, options) + if err != nil { + return ScalarAzureLocationScalarClientQueryResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScalarAzureLocationScalarClientQueryResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ScalarAzureLocationScalarClientQueryResponse{}, err + } + return ScalarAzureLocationScalarClientQueryResponse{}, nil +} + +// queryCreateRequest creates the Query request. +func (client *ScalarAzureLocationScalarClient) queryCreateRequest(ctx context.Context, region string, _ *ScalarAzureLocationScalarClientQueryOptions) (*policy.Request, error) { + urlPath := "/azure/core/scalar/azureLocation/query" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("region", region) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/azure-http-specs/azure/core/corescalargroup/zz_version.go b/test/azure-http-specs/azure/core/corescalargroup/zz_version.go new file mode 100644 index 000000000000..0f02e48ee9f1 --- /dev/null +++ b/test/azure-http-specs/azure/core/corescalargroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package corescalargroup + +const ( + moduleName = "corescalargroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/core/lro/lrorpcgroup/LICENSE.txt b/test/azure-http-specs/azure/core/lro/lrorpcgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrorpcgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/core/lro/lrorpcgroup/fake/zz_internal.go b/test/azure-http-specs/azure/core/lro/lrorpcgroup/fake/zz_internal.go new file mode 100644 index 000000000000..2f8b4aafab8d --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrorpcgroup/fake/zz_internal.go @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/azure-http-specs/azure/core/lro/lrorpcgroup/fake/zz_rpc_server.go b/test/azure-http-specs/azure/core/lro/lrorpcgroup/fake/zz_rpc_server.go new file mode 100644 index 000000000000..192c78a615fc --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrorpcgroup/fake/zz_rpc_server.go @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "lrorpcgroup" + "net/http" + "slices" +) + +// RPCServer is a fake server for instances of the lrorpcgroup.RPCClient type. +type RPCServer struct { + // BeginLongRunningRPC is the fake for method RPCClient.BeginLongRunningRPC + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginLongRunningRPC func(ctx context.Context, body lrorpcgroup.GenerationOptions, options *lrorpcgroup.RPCClientBeginLongRunningRPCOptions) (resp azfake.PollerResponder[lrorpcgroup.RPCClientLongRunningRPCResponse], errResp azfake.ErrorResponder) +} + +// NewRPCServerTransport creates a new instance of RPCServerTransport with the provided implementation. +// The returned RPCServerTransport instance is connected to an instance of lrorpcgroup.RPCClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewRPCServerTransport(srv *RPCServer) *RPCServerTransport { + return &RPCServerTransport{ + srv: srv, + beginLongRunningRPC: newTracker[azfake.PollerResponder[lrorpcgroup.RPCClientLongRunningRPCResponse]](), + } +} + +// RPCServerTransport connects instances of lrorpcgroup.RPCClient to instances of RPCServer. +// Don't use this type directly, use NewRPCServerTransport instead. +type RPCServerTransport struct { + srv *RPCServer + beginLongRunningRPC *tracker[azfake.PollerResponder[lrorpcgroup.RPCClientLongRunningRPCResponse]] +} + +// Do implements the policy.Transporter interface for RPCServerTransport. +func (r *RPCServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return r.dispatchToMethodFake(req, method) +} + +func (r *RPCServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if rpcServerTransportInterceptor != nil { + res.resp, res.err, intercepted = rpcServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "RPCClient.BeginLongRunningRPC": + res.resp, res.err = r.dispatchBeginLongRunningRPC(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (r *RPCServerTransport) dispatchBeginLongRunningRPC(req *http.Request) (*http.Response, error) { + if r.srv.BeginLongRunningRPC == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginLongRunningRPC not implemented")} + } + beginLongRunningRPC := r.beginLongRunningRPC.get(req) + if beginLongRunningRPC == nil { + body, err := server.UnmarshalRequestAsJSON[lrorpcgroup.GenerationOptions](req) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.BeginLongRunningRPC(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginLongRunningRPC = &respr + r.beginLongRunningRPC.add(req, beginLongRunningRPC) + } + + resp, err := server.PollerResponderNext(beginLongRunningRPC, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + r.beginLongRunningRPC.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginLongRunningRPC) { + r.beginLongRunningRPC.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to RPCServerTransport +var rpcServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/core/lro/lrorpcgroup/go.mod b/test/azure-http-specs/azure/core/lro/lrorpcgroup/go.mod new file mode 100644 index 000000000000..f4a408f68fcb --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrorpcgroup/go.mod @@ -0,0 +1,17 @@ +module lrorpcgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/core/lro/lrorpcgroup/go.sum b/test/azure-http-specs/azure/core/lro/lrorpcgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrorpcgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/core/lro/lrorpcgroup/rcp_client_test.go b/test/azure-http-specs/azure/core/lro/lrorpcgroup/rcp_client_test.go new file mode 100644 index 000000000000..20620bec12b5 --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrorpcgroup/rcp_client_test.go @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package lrorpcgroup_test + +import ( + "context" + "lrorpcgroup" + "net/http" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +type apiVersionPolicy struct { + apiVersion string +} + +func (a *apiVersionPolicy) Do(req *policy.Request) (*http.Response, error) { + rawQP := req.Raw().URL.Query() + rawQP.Set("api-version", a.apiVersion) + req.Raw().URL.RawQuery = rawQP.Encode() + return req.Next() +} + +func TestRpcClient_BeginLongRunningRPC(t *testing.T) { + client, err := lrorpcgroup.NewRPCClientWithNoCredential("http://localhost:3000", &lrorpcgroup.RPCClientOptions{ + azcore.ClientOptions{ + PerCallPolicies: []policy.Policy{&apiVersionPolicy{apiVersion: "2022-12-01-preview"}}, + }, + }) + require.NoError(t, err) + poller, err := client.BeginLongRunningRPC(context.Background(), lrorpcgroup.GenerationOptions{ + Prompt: to.Ptr("text"), + }, nil) + require.NoError(t, err) + resp, err := poller.PollUntilDone(context.Background(), &runtime.PollUntilDoneOptions{ + Frequency: time.Second, + }) + require.NoError(t, err) + require.Equal(t, lrorpcgroup.GenerationResult{ + Data: to.Ptr("text data"), + }, resp.GenerationResult) +} diff --git a/test/azure-http-specs/azure/core/lro/lrorpcgroup/testdata/_metadata.json b/test/azure-http-specs/azure/core/lro/lrorpcgroup/testdata/_metadata.json new file mode 100644 index 000000000000..83ad302ea5b1 --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrorpcgroup/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "_Specs_.Azure.Core.Lro.Rpc": "2022-12-01-preview" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_constants.go b/test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_constants.go new file mode 100644 index 000000000000..fca7f401fe16 --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_constants.go @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package lrorpcgroup + +const ( + version20221201Preview string = "2022-12-01-preview" +) diff --git a/test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_models.go b/test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_models.go new file mode 100644 index 000000000000..eba6856f43b2 --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_models.go @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package lrorpcgroup + +// GenerationOptions - Options for the generation. +type GenerationOptions struct { + // REQUIRED; Prompt. + Prompt *string +} + +// GenerationResult - Result of the generation. +type GenerationResult struct { + // REQUIRED; The data. + Data *string +} diff --git a/test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_models_serde.go b/test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_models_serde.go new file mode 100644 index 000000000000..d487dc41502a --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_models_serde.go @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package lrorpcgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type GenerationOptions. +func (g GenerationOptions) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "prompt", g.Prompt) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GenerationOptions. +func (g *GenerationOptions) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "prompt": + err = unpopulate(val, "Prompt", &g.Prompt) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type GenerationResult. +func (g GenerationResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "data", g.Data) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GenerationResult. +func (g *GenerationResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "data": + err = unpopulate(val, "Data", &g.Data) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_options.go b/test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_options.go new file mode 100644 index 000000000000..33cecdd32b12 --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_options.go @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package lrorpcgroup + +// RPCClientBeginLongRunningRPCOptions contains the optional parameters for the RPCClient.BeginLongRunningRPC method. +type RPCClientBeginLongRunningRPCOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} diff --git a/test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_responses.go b/test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_responses.go new file mode 100644 index 000000000000..5466d570b0ed --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_responses.go @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package lrorpcgroup + +// RPCClientLongRunningRPCResponse contains the response from method RPCClient.BeginLongRunningRPC. +type RPCClientLongRunningRPCResponse struct { + // Result of the generation. + GenerationResult +} diff --git a/test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_rpc_client.go b/test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_rpc_client.go new file mode 100644 index 000000000000..2de5759131c2 --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_rpc_client.go @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package lrorpcgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// RPCClient - Illustrates bodies templated with Azure Core with long-running RPC operation +// Don't use this type directly, use NewRPCClientWithNoCredential() instead. +// +// Generated from API version 2022-12-01-preview +type RPCClient struct { + internal *azcore.Client + endpoint string +} + +// RPCClientOptions contains the optional values for creating a [RPCClient]. +type RPCClientOptions struct { + azcore.ClientOptions +} + +// NewRPCClientWithNoCredential creates a new instance of RPCClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewRPCClientWithNoCredential(endpoint string, options *RPCClientOptions) (*RPCClient, error) { + if options == nil { + options = &RPCClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{ + APIVersion: runtime.APIVersionOptions{ + Name: "api-version", + Location: runtime.APIVersionLocationQueryParam, + }, + }, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &RPCClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// BeginLongRunningRPC - Generate data. +// +// Generate data. +// If the operation fails it returns an *azcore.ResponseError type. +// - body - The body parameter. +// - options - RPCClientBeginLongRunningRPCOptions contains the optional parameters for the RPCClient.BeginLongRunningRPC method. +func (client *RPCClient) BeginLongRunningRPC(ctx context.Context, body GenerationOptions, options *RPCClientBeginLongRunningRPCOptions) (*runtime.Poller[RPCClientLongRunningRPCResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.longRunningRPC(ctx, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RPCClientLongRunningRPCResponse]{ + OperationLocationResultPath: "result", + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RPCClientLongRunningRPCResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// LongRunningRPC - Generate data. +// +// Generate data. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *RPCClient) longRunningRPC(ctx context.Context, body GenerationOptions, options *RPCClientBeginLongRunningRPCOptions) (*http.Response, error) { + var err error + const operationName = "RPCClient.BeginLongRunningRPC" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.longRunningRPCCreateRequest(ctx, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// longRunningRPCCreateRequest creates the LongRunningRPC request. +func (client *RPCClient) longRunningRPCCreateRequest(ctx context.Context, body GenerationOptions, _ *RPCClientBeginLongRunningRPCOptions) (*policy.Request, error) { + urlPath := "/azure/core/lro/rpc/generations:submit" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20221201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_version.go b/test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_version.go new file mode 100644 index 000000000000..afb7082f93a4 --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrorpcgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package lrorpcgroup + +const ( + moduleName = "lrorpcgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/core/lro/lrostdgroup/LICENSE.txt b/test/azure-http-specs/azure/core/lro/lrostdgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrostdgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/core/lro/lrostdgroup/fake/zz_internal.go b/test/azure-http-specs/azure/core/lro/lrostdgroup/fake/zz_internal.go new file mode 100644 index 000000000000..2f8b4aafab8d --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrostdgroup/fake/zz_internal.go @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/azure-http-specs/azure/core/lro/lrostdgroup/fake/zz_standard_server.go b/test/azure-http-specs/azure/core/lro/lrostdgroup/fake/zz_standard_server.go new file mode 100644 index 000000000000..654a43416f31 --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrostdgroup/fake/zz_standard_server.go @@ -0,0 +1,229 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "lrostdgroup" + "net/http" + "net/url" + "regexp" + "slices" +) + +// StandardServer is a fake server for instances of the lrostdgroup.StandardClient type. +type StandardServer struct { + // BeginCreateOrReplace is the fake for method StandardClient.BeginCreateOrReplace + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrReplace func(ctx context.Context, name string, resource lrostdgroup.User, options *lrostdgroup.StandardClientBeginCreateOrReplaceOptions) (resp azfake.PollerResponder[lrostdgroup.StandardClientCreateOrReplaceResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method StandardClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, name string, options *lrostdgroup.StandardClientBeginDeleteOptions) (resp azfake.PollerResponder[lrostdgroup.StandardClientDeleteResponse], errResp azfake.ErrorResponder) + + // BeginExport is the fake for method StandardClient.BeginExport + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginExport func(ctx context.Context, name string, formatParam string, options *lrostdgroup.StandardClientBeginExportOptions) (resp azfake.PollerResponder[lrostdgroup.StandardClientExportResponse], errResp azfake.ErrorResponder) +} + +// NewStandardServerTransport creates a new instance of StandardServerTransport with the provided implementation. +// The returned StandardServerTransport instance is connected to an instance of lrostdgroup.StandardClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewStandardServerTransport(srv *StandardServer) *StandardServerTransport { + return &StandardServerTransport{ + srv: srv, + beginCreateOrReplace: newTracker[azfake.PollerResponder[lrostdgroup.StandardClientCreateOrReplaceResponse]](), + beginDelete: newTracker[azfake.PollerResponder[lrostdgroup.StandardClientDeleteResponse]](), + beginExport: newTracker[azfake.PollerResponder[lrostdgroup.StandardClientExportResponse]](), + } +} + +// StandardServerTransport connects instances of lrostdgroup.StandardClient to instances of StandardServer. +// Don't use this type directly, use NewStandardServerTransport instead. +type StandardServerTransport struct { + srv *StandardServer + beginCreateOrReplace *tracker[azfake.PollerResponder[lrostdgroup.StandardClientCreateOrReplaceResponse]] + beginDelete *tracker[azfake.PollerResponder[lrostdgroup.StandardClientDeleteResponse]] + beginExport *tracker[azfake.PollerResponder[lrostdgroup.StandardClientExportResponse]] +} + +// Do implements the policy.Transporter interface for StandardServerTransport. +func (s *StandardServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *StandardServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if standardServerTransportInterceptor != nil { + res.resp, res.err, intercepted = standardServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "StandardClient.BeginCreateOrReplace": + res.resp, res.err = s.dispatchBeginCreateOrReplace(req) + case "StandardClient.BeginDelete": + res.resp, res.err = s.dispatchBeginDelete(req) + case "StandardClient.BeginExport": + res.resp, res.err = s.dispatchBeginExport(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *StandardServerTransport) dispatchBeginCreateOrReplace(req *http.Request) (*http.Response, error) { + if s.srv.BeginCreateOrReplace == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrReplace not implemented")} + } + beginCreateOrReplace := s.beginCreateOrReplace.get(req) + if beginCreateOrReplace == nil { + const regexStr = `/azure/core/lro/standard/users/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[lrostdgroup.User](req) + if err != nil { + return nil, err + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("name")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.BeginCreateOrReplace(req.Context(), nameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrReplace = &respr + s.beginCreateOrReplace.add(req, beginCreateOrReplace) + } + + resp, err := server.PollerResponderNext(beginCreateOrReplace, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + s.beginCreateOrReplace.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrReplace) { + s.beginCreateOrReplace.remove(req) + } + + return resp, nil +} + +func (s *StandardServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if s.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := s.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/azure/core/lro/standard/users/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("name")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.BeginDelete(req.Context(), nameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + s.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + s.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + s.beginDelete.remove(req) + } + + return resp, nil +} + +func (s *StandardServerTransport) dispatchBeginExport(req *http.Request) (*http.Response, error) { + if s.srv.BeginExport == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginExport not implemented")} + } + beginExport := s.beginExport.get(req) + if beginExport == nil { + const regexStr = `/azure/core/lro/standard/users/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+):export` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("name")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.BeginExport(req.Context(), nameParam, qp.Get("format"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginExport = &respr + s.beginExport.add(req, beginExport) + } + + resp, err := server.PollerResponderNext(beginExport, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + s.beginExport.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginExport) { + s.beginExport.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to StandardServerTransport +var standardServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/core/lro/lrostdgroup/go.mod b/test/azure-http-specs/azure/core/lro/lrostdgroup/go.mod new file mode 100644 index 000000000000..d17dc26a9667 --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrostdgroup/go.mod @@ -0,0 +1,17 @@ +module lrostdgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/core/lro/lrostdgroup/go.sum b/test/azure-http-specs/azure/core/lro/lrostdgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrostdgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/core/lro/lrostdgroup/standard_client_test.go b/test/azure-http-specs/azure/core/lro/lrostdgroup/standard_client_test.go new file mode 100644 index 000000000000..fed283f2c691 --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrostdgroup/standard_client_test.go @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package lrostdgroup_test + +import ( + "context" + "lrostdgroup" + "net/http" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +type apiVersionPolicy struct { + apiVersion string +} + +func (a *apiVersionPolicy) Do(req *policy.Request) (*http.Response, error) { + rawQP := req.Raw().URL.Query() + rawQP.Set("api-version", a.apiVersion) + req.Raw().URL.RawQuery = rawQP.Encode() + return req.Next() +} + +func TestStandardClient_BeginCreateOrReplace(t *testing.T) { + client, err := lrostdgroup.NewStandardClientWithNoCredential("http://localhost:3000", &lrostdgroup.StandardClientOptions{ + azcore.ClientOptions{ + PerCallPolicies: []policy.Policy{&apiVersionPolicy{apiVersion: "2022-12-01-preview"}}, + }, + }) + require.NoError(t, err) + poller, err := client.BeginCreateOrReplace(context.Background(), "madge", lrostdgroup.User{ + Role: to.Ptr("contributor"), + }, nil) + require.NoError(t, err) + resp, err := poller.PollUntilDone(context.Background(), &runtime.PollUntilDoneOptions{ + Frequency: time.Second, + }) + require.NoError(t, err) + require.Equal(t, lrostdgroup.User{ + Name: to.Ptr("madge"), + Role: to.Ptr("contributor"), + }, resp.User) +} + +func TestStandardClient_BeginDelete(t *testing.T) { + client, err := lrostdgroup.NewStandardClientWithNoCredential("http://localhost:3000", &lrostdgroup.StandardClientOptions{ + azcore.ClientOptions{ + PerCallPolicies: []policy.Policy{&apiVersionPolicy{apiVersion: "2022-12-01-preview"}}, + }, + }) + require.NoError(t, err) + poller, err := client.BeginDelete(context.Background(), "madge", nil) + require.NoError(t, err) + resp, err := poller.PollUntilDone(context.Background(), &runtime.PollUntilDoneOptions{ + Frequency: time.Second, + }) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestStandardClient_BeginExport(t *testing.T) { + client, err := lrostdgroup.NewStandardClientWithNoCredential("http://localhost:3000", &lrostdgroup.StandardClientOptions{ + azcore.ClientOptions{ + PerCallPolicies: []policy.Policy{&apiVersionPolicy{apiVersion: "2022-12-01-preview"}}, + }, + }) + require.NoError(t, err) + poller, err := client.BeginExport(context.Background(), "madge", "json", nil) + require.NoError(t, err) + resp, err := poller.PollUntilDone(context.Background(), &runtime.PollUntilDoneOptions{ + Frequency: time.Second, + }) + require.NoError(t, err) + require.Equal(t, lrostdgroup.ExportedUser{ + Name: to.Ptr("madge"), + ResourceURI: to.Ptr("/users/madge"), + }, resp.ExportedUser) +} diff --git a/test/azure-http-specs/azure/core/lro/lrostdgroup/testdata/_metadata.json b/test/azure-http-specs/azure/core/lro/lrostdgroup/testdata/_metadata.json new file mode 100644 index 000000000000..4bd0cf399b23 --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrostdgroup/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "_Specs_.Azure.Core.Lro.Standard": "2022-12-01-preview" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/core/lro/lrostdgroup/zz_constants.go b/test/azure-http-specs/azure/core/lro/lrostdgroup/zz_constants.go new file mode 100644 index 000000000000..a970a5c9e5fb --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrostdgroup/zz_constants.go @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package lrostdgroup + +const ( + version20221201Preview string = "2022-12-01-preview" +) diff --git a/test/azure-http-specs/azure/core/lro/lrostdgroup/zz_models.go b/test/azure-http-specs/azure/core/lro/lrostdgroup/zz_models.go new file mode 100644 index 000000000000..3415037d9a9d --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrostdgroup/zz_models.go @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package lrostdgroup + +// ExportedUser - The exported user data. +type ExportedUser struct { + // REQUIRED; The name of user. + Name *string + + // REQUIRED; The exported URI. + ResourceURI *string +} + +// User - Details about a user. +type User struct { + // REQUIRED; The role of user + Role *string + + // READ-ONLY; The name of user. + Name *string +} diff --git a/test/azure-http-specs/azure/core/lro/lrostdgroup/zz_models_serde.go b/test/azure-http-specs/azure/core/lro/lrostdgroup/zz_models_serde.go new file mode 100644 index 000000000000..6638d767dd27 --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrostdgroup/zz_models_serde.go @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package lrostdgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type ExportedUser. +func (e ExportedUser) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", e.Name) + populate(objectMap, "resourceUri", e.ResourceURI) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExportedUser. +func (e *ExportedUser) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &e.Name) + delete(rawMsg, key) + case "resourceUri": + err = unpopulate(val, "ResourceURI", &e.ResourceURI) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type User. +func (u User) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", u.Name) + populate(objectMap, "role", u.Role) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type User. +func (u *User) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &u.Name) + delete(rawMsg, key) + case "role": + err = unpopulate(val, "Role", &u.Role) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/azure-http-specs/azure/core/lro/lrostdgroup/zz_options.go b/test/azure-http-specs/azure/core/lro/lrostdgroup/zz_options.go new file mode 100644 index 000000000000..d7f62b63a67a --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrostdgroup/zz_options.go @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package lrostdgroup + +// StandardClientBeginCreateOrReplaceOptions contains the optional parameters for the StandardClient.BeginCreateOrReplace +// method. +type StandardClientBeginCreateOrReplaceOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// StandardClientBeginDeleteOptions contains the optional parameters for the StandardClient.BeginDelete method. +type StandardClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// StandardClientBeginExportOptions contains the optional parameters for the StandardClient.BeginExport method. +type StandardClientBeginExportOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} diff --git a/test/azure-http-specs/azure/core/lro/lrostdgroup/zz_responses.go b/test/azure-http-specs/azure/core/lro/lrostdgroup/zz_responses.go new file mode 100644 index 000000000000..d35424d018de --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrostdgroup/zz_responses.go @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package lrostdgroup + +// StandardClientCreateOrReplaceResponse contains the response from method StandardClient.BeginCreateOrReplace. +type StandardClientCreateOrReplaceResponse struct { + // Details about a user. + User +} + +// StandardClientDeleteResponse contains the response from method StandardClient.BeginDelete. +type StandardClientDeleteResponse struct { + // placeholder for future response values +} + +// StandardClientExportResponse contains the response from method StandardClient.BeginExport. +type StandardClientExportResponse struct { + // The exported user data. + ExportedUser +} diff --git a/test/azure-http-specs/azure/core/lro/lrostdgroup/zz_standard_client.go b/test/azure-http-specs/azure/core/lro/lrostdgroup/zz_standard_client.go new file mode 100644 index 000000000000..11084f8fafcd --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrostdgroup/zz_standard_client.go @@ -0,0 +1,260 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package lrostdgroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// StandardClient - Illustrates bodies templated with Azure Core with long-running operation +// Don't use this type directly, use NewStandardClientWithNoCredential() instead. +// +// Generated from API version 2022-12-01-preview +type StandardClient struct { + internal *azcore.Client + endpoint string +} + +// StandardClientOptions contains the optional values for creating a [StandardClient]. +type StandardClientOptions struct { + azcore.ClientOptions +} + +// NewStandardClientWithNoCredential creates a new instance of StandardClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewStandardClientWithNoCredential(endpoint string, options *StandardClientOptions) (*StandardClient, error) { + if options == nil { + options = &StandardClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{ + APIVersion: runtime.APIVersionOptions{ + Name: "api-version", + Location: runtime.APIVersionLocationQueryParam, + }, + }, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &StandardClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// BeginCreateOrReplace - Adds a user or replaces a user's fields. +// +// Creates or replaces a User +// If the operation fails it returns an *azcore.ResponseError type. +// - name - The name of user. +// - resource - The resource instance. +// - options - StandardClientBeginCreateOrReplaceOptions contains the optional parameters for the StandardClient.BeginCreateOrReplace +// method. +func (client *StandardClient) BeginCreateOrReplace(ctx context.Context, name string, resource User, options *StandardClientBeginCreateOrReplaceOptions) (*runtime.Poller[StandardClientCreateOrReplaceResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrReplace(ctx, name, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[StandardClientCreateOrReplaceResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[StandardClientCreateOrReplaceResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrReplace - Adds a user or replaces a user's fields. +// +// Creates or replaces a User +// If the operation fails it returns an *azcore.ResponseError type. +func (client *StandardClient) createOrReplace(ctx context.Context, name string, resource User, options *StandardClientBeginCreateOrReplaceOptions) (*http.Response, error) { + var err error + const operationName = "StandardClient.BeginCreateOrReplace" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrReplaceCreateRequest(ctx, name, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrReplaceCreateRequest creates the CreateOrReplace request. +func (client *StandardClient) createOrReplaceCreateRequest(ctx context.Context, name string, resource User, _ *StandardClientBeginCreateOrReplaceOptions) (*policy.Request, error) { + urlPath := "/azure/core/lro/standard/users/{name}" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20221201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a user. +// +// Deletes a User +// If the operation fails it returns an *azcore.ResponseError type. +// - name - The name of user. +// - options - StandardClientBeginDeleteOptions contains the optional parameters for the StandardClient.BeginDelete method. +func (client *StandardClient) BeginDelete(ctx context.Context, name string, options *StandardClientBeginDeleteOptions) (*runtime.Poller[StandardClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, name, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[StandardClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[StandardClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a user. +// +// Deletes a User +// If the operation fails it returns an *azcore.ResponseError type. +func (client *StandardClient) deleteOperation(ctx context.Context, name string, options *StandardClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "StandardClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, name, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *StandardClient) deleteCreateRequest(ctx context.Context, name string, _ *StandardClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/azure/core/lro/standard/users/{name}" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20221201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginExport - Exports a user. +// +// Exports a User +// If the operation fails it returns an *azcore.ResponseError type. +// - name - The name of user. +// - formatParam - The format of the data. +// - options - StandardClientBeginExportOptions contains the optional parameters for the StandardClient.BeginExport method. +func (client *StandardClient) BeginExport(ctx context.Context, name string, formatParam string, options *StandardClientBeginExportOptions) (*runtime.Poller[StandardClientExportResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.export(ctx, name, formatParam, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[StandardClientExportResponse]{ + OperationLocationResultPath: "result", + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[StandardClientExportResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Export - Exports a user. +// +// Exports a User +// If the operation fails it returns an *azcore.ResponseError type. +func (client *StandardClient) export(ctx context.Context, name string, formatParam string, options *StandardClientBeginExportOptions) (*http.Response, error) { + var err error + const operationName = "StandardClient.BeginExport" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.exportCreateRequest(ctx, name, formatParam, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// exportCreateRequest creates the Export request. +func (client *StandardClient) exportCreateRequest(ctx context.Context, name string, formatParam string, _ *StandardClientBeginExportOptions) (*policy.Request, error) { + urlPath := "/azure/core/lro/standard/users/{name}:export" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20221201Preview) + reqQP.Set("format", formatParam) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} diff --git a/test/azure-http-specs/azure/core/lro/lrostdgroup/zz_version.go b/test/azure-http-specs/azure/core/lro/lrostdgroup/zz_version.go new file mode 100644 index 000000000000..6924518fb45f --- /dev/null +++ b/test/azure-http-specs/azure/core/lro/lrostdgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package lrostdgroup + +const ( + moduleName = "lrostdgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/core/traitsgroup/LICENSE.txt b/test/azure-http-specs/azure/core/traitsgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/core/traitsgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/core/traitsgroup/fake/zz_internal.go b/test/azure-http-specs/azure/core/traitsgroup/fake/zz_internal.go new file mode 100644 index 000000000000..f9fb1169359a --- /dev/null +++ b/test/azure-http-specs/azure/core/traitsgroup/fake/zz_internal.go @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "reflect" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getHeaderValue(h http.Header, k string) string { + v := h[k] + if len(v) == 0 { + return "" + } + return v[0] +} + +func getOptional[T any](v T) *T { + if reflect.ValueOf(v).IsZero() { + return nil + } + return &v +} + +func parseOptional[T any](v string, parse func(v string) (T, error)) (*T, error) { + if v == "" { + return nil, nil + } + t, err := parse(v) + if err != nil { + return nil, err + } + return &t, nil +} + +func parseWithCast[T any](v string, parse func(v string) (T, error)) (T, error) { + t, err := parse(v) + if err != nil { + return *new(T), err + } + return t, err +} diff --git a/test/azure-http-specs/azure/core/traitsgroup/fake/zz_traits_server.go b/test/azure-http-specs/azure/core/traitsgroup/fake/zz_traits_server.go new file mode 100644 index 000000000000..08ec649c624e --- /dev/null +++ b/test/azure-http-specs/azure/core/traitsgroup/fake/zz_traits_server.go @@ -0,0 +1,219 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" + "strconv" + "time" + "traitsgroup" +) + +// TraitsServer is a fake server for instances of the traitsgroup.TraitsClient type. +type TraitsServer struct { + // RepeatableAction is the fake for method TraitsClient.RepeatableAction + // HTTP status codes to indicate success: http.StatusOK + RepeatableAction func(ctx context.Context, id int32, body traitsgroup.UserActionParam, options *traitsgroup.TraitsClientRepeatableActionOptions) (resp azfake.Responder[traitsgroup.TraitsClientRepeatableActionResponse], errResp azfake.ErrorResponder) + + // SmokeTest is the fake for method TraitsClient.SmokeTest + // HTTP status codes to indicate success: http.StatusOK + SmokeTest func(ctx context.Context, id int32, foo string, options *traitsgroup.TraitsClientSmokeTestOptions) (resp azfake.Responder[traitsgroup.TraitsClientSmokeTestResponse], errResp azfake.ErrorResponder) +} + +// NewTraitsServerTransport creates a new instance of TraitsServerTransport with the provided implementation. +// The returned TraitsServerTransport instance is connected to an instance of traitsgroup.TraitsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewTraitsServerTransport(srv *TraitsServer) *TraitsServerTransport { + return &TraitsServerTransport{srv: srv} +} + +// TraitsServerTransport connects instances of traitsgroup.TraitsClient to instances of TraitsServer. +// Don't use this type directly, use NewTraitsServerTransport instead. +type TraitsServerTransport struct { + srv *TraitsServer +} + +// Do implements the policy.Transporter interface for TraitsServerTransport. +func (t *TraitsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return t.dispatchToMethodFake(req, method) +} + +func (t *TraitsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if traitsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = traitsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "TraitsClient.RepeatableAction": + res.resp, res.err = t.dispatchRepeatableAction(req) + case "TraitsClient.SmokeTest": + res.resp, res.err = t.dispatchSmokeTest(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (t *TraitsServerTransport) dispatchRepeatableAction(req *http.Request) (*http.Response, error) { + if t.srv.RepeatableAction == nil { + return nil, &nonRetriableError{errors.New("fake for method RepeatableAction not implemented")} + } + const regexStr = `/azure/core/traits/user/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+):repeatableAction` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[traitsgroup.UserActionParam](req) + if err != nil { + return nil, err + } + idUnescaped, err := url.PathUnescape(matches[regex.SubexpIndex("id")]) + if err != nil { + return nil, err + } + idParam, err := parseWithCast(idUnescaped, func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + repeatabilityRequestIDParam := getOptional(getHeaderValue(req.Header, "Repeatability-Request-ID")) + repeatabilityFirstSentParam, err := parseOptional(getHeaderValue(req.Header, "Repeatability-First-Sent"), func(v string) (time.Time, error) { return time.Parse(time.RFC1123, v) }) + if err != nil { + return nil, err + } + var options *traitsgroup.TraitsClientRepeatableActionOptions + if repeatabilityRequestIDParam != nil || repeatabilityFirstSentParam != nil { + options = &traitsgroup.TraitsClientRepeatableActionOptions{ + RepeatabilityRequestID: repeatabilityRequestIDParam, + RepeatabilityFirstSent: repeatabilityFirstSentParam, + } + } + respr, errRespr := t.srv.RepeatableAction(req.Context(), idParam, body, options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).UserActionResponse, req) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).RepeatabilityResult; val != nil { + resp.Header.Set("Repeatability-Result", string(*val)) + } + return resp, nil +} + +func (t *TraitsServerTransport) dispatchSmokeTest(req *http.Request) (*http.Response, error) { + if t.srv.SmokeTest == nil { + return nil, &nonRetriableError{errors.New("fake for method SmokeTest not implemented")} + } + const regexStr = `/azure/core/traits/user/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + idUnescaped, err := url.PathUnescape(matches[regex.SubexpIndex("id")]) + if err != nil { + return nil, err + } + idParam, err := parseWithCast(idUnescaped, func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + ifMatchParam := getOptional(getHeaderValue(req.Header, "If-Match")) + ifNoneMatchParam := getOptional(getHeaderValue(req.Header, "If-None-Match")) + ifUnmodifiedSinceParam, err := parseOptional(getHeaderValue(req.Header, "If-Unmodified-Since"), func(v string) (time.Time, error) { return time.Parse(time.RFC1123, v) }) + if err != nil { + return nil, err + } + ifModifiedSinceParam, err := parseOptional(getHeaderValue(req.Header, "If-Modified-Since"), func(v string) (time.Time, error) { return time.Parse(time.RFC1123, v) }) + if err != nil { + return nil, err + } + clientRequestIDParam := getOptional(getHeaderValue(req.Header, "x-ms-client-request-id")) + var options *traitsgroup.TraitsClientSmokeTestOptions + if ifMatchParam != nil || ifNoneMatchParam != nil || ifUnmodifiedSinceParam != nil || ifModifiedSinceParam != nil || clientRequestIDParam != nil { + options = &traitsgroup.TraitsClientSmokeTestOptions{ + IfMatch: ifMatchParam, + IfNoneMatch: ifNoneMatchParam, + IfUnmodifiedSince: ifUnmodifiedSinceParam, + IfModifiedSince: ifModifiedSinceParam, + ClientRequestID: clientRequestIDParam, + } + } + respr, errRespr := t.srv.SmokeTest(req.Context(), idParam, getHeaderValue(req.Header, "foo"), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).User, req) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).Bar; val != nil { + resp.Header.Set("bar", *val) + } + if val := server.GetResponse(respr).ClientRequestID; val != nil { + resp.Header.Set("x-ms-client-request-id", *val) + } + if val := server.GetResponse(respr).EtagHeader; val != nil { + resp.Header.Set("ETag", *val) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to TraitsServerTransport +var traitsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/core/traitsgroup/go.mod b/test/azure-http-specs/azure/core/traitsgroup/go.mod new file mode 100644 index 000000000000..915045bd192f --- /dev/null +++ b/test/azure-http-specs/azure/core/traitsgroup/go.mod @@ -0,0 +1,17 @@ +module traitsgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/core/traitsgroup/go.sum b/test/azure-http-specs/azure/core/traitsgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/core/traitsgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/core/traitsgroup/testdata/_metadata.json b/test/azure-http-specs/azure/core/traitsgroup/testdata/_metadata.json new file mode 100644 index 000000000000..50d5013b33eb --- /dev/null +++ b/test/azure-http-specs/azure/core/traitsgroup/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "_Specs_.Azure.Core.Traits": "2022-12-01-preview" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/core/traitsgroup/traits_client_test.go b/test/azure-http-specs/azure/core/traitsgroup/traits_client_test.go new file mode 100644 index 000000000000..066e5a56a59b --- /dev/null +++ b/test/azure-http-specs/azure/core/traitsgroup/traits_client_test.go @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package traitsgroup_test + +import ( + "context" + "testing" + "time" + "traitsgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestTraitsClient_RepeatableAction(t *testing.T) { + client, err := traitsgroup.NewTraitsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + require.NotNil(t, client) + resp, err := client.RepeatableAction(context.Background(), 1, traitsgroup.UserActionParam{ + UserActionValue: to.Ptr("test"), + }, &traitsgroup.TraitsClientRepeatableActionOptions{ + RepeatabilityFirstSent: to.Ptr(time.Date(2023, time.November, 27, 11, 58, 0, 0, time.UTC)), + RepeatabilityRequestID: to.Ptr("86aede1f-96fa-4e7f-b1e1-bf8a947cb804"), + }) + require.NoError(t, err) + require.NotNil(t, resp.UserActionResult) + require.Equal(t, "test", *resp.UserActionResult) +} + +func TestTraitsClient_SmokeTest(t *testing.T) { + client, err := traitsgroup.NewTraitsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + require.NotNil(t, client) + require.NoError(t, err) + const id = int32(1) + resp, err := client.SmokeTest(context.Background(), id, "123", &traitsgroup.TraitsClientSmokeTestOptions{ + IfMatch: to.Ptr("\"valid\""), + IfNoneMatch: to.Ptr("\"invalid\""), + IfModifiedSince: to.Ptr(time.Date(2021, time.August, 26, 14, 38, 0, 0, time.UTC)), + IfUnmodifiedSince: to.Ptr(time.Date(2022, time.August, 26, 14, 38, 0, 0, time.UTC)), + ClientRequestID: to.Ptr("86aede1f-96fa-4e7f-b1e1-bf8a947cb804"), + }) + require.NoError(t, err) + require.NotNil(t, resp.ID) + require.NotNil(t, resp.Name) + require.Equal(t, id, *resp.ID) + require.Equal(t, "Madge", *resp.Name) +} diff --git a/test/azure-http-specs/azure/core/traitsgroup/zz_constants.go b/test/azure-http-specs/azure/core/traitsgroup/zz_constants.go new file mode 100644 index 000000000000..d78dee2f85e2 --- /dev/null +++ b/test/azure-http-specs/azure/core/traitsgroup/zz_constants.go @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package traitsgroup + +const ( + version20221201Preview string = "2022-12-01-preview" +) + +// RepeatabilityResult - Repeatability Result header options +type RepeatabilityResult string + +const ( + // RepeatabilityResultAccepted - If the request was accepted and the server guarantees that the server state reflects a single + // execution of the operation. + RepeatabilityResultAccepted RepeatabilityResult = "accepted" + // RepeatabilityResultRejected - If the request was rejected because the combination of Repeatability-First-Sent and Repeatability-Request-ID + // were invalid + // or because the Repeatability-First-Sent value was outside the range of values held by the server. + RepeatabilityResultRejected RepeatabilityResult = "rejected" +) + +// PossibleRepeatabilityResultValues returns the possible values for the RepeatabilityResult const type. +func PossibleRepeatabilityResultValues() []RepeatabilityResult { + return []RepeatabilityResult{ + RepeatabilityResultAccepted, + RepeatabilityResultRejected, + } +} diff --git a/test/azure-http-specs/azure/core/traitsgroup/zz_models.go b/test/azure-http-specs/azure/core/traitsgroup/zz_models.go new file mode 100644 index 000000000000..8bdece4da3cd --- /dev/null +++ b/test/azure-http-specs/azure/core/traitsgroup/zz_models.go @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package traitsgroup + +// User - Sample Model +type User struct { + // The user's name. + Name *string + + // READ-ONLY; The user's id. + ID *int32 +} + +// UserActionParam - User action param +type UserActionParam struct { + // REQUIRED; User action value. + UserActionValue *string +} + +// UserActionResponse - User action response +type UserActionResponse struct { + // REQUIRED; User action result. + UserActionResult *string +} diff --git a/test/azure-http-specs/azure/core/traitsgroup/zz_models_serde.go b/test/azure-http-specs/azure/core/traitsgroup/zz_models_serde.go new file mode 100644 index 000000000000..7d40c2d722bc --- /dev/null +++ b/test/azure-http-specs/azure/core/traitsgroup/zz_models_serde.go @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package traitsgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type User. +func (u User) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", u.ID) + populate(objectMap, "name", u.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type User. +func (u *User) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &u.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &u.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserActionParam. +func (u UserActionParam) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "userActionValue", u.UserActionValue) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserActionParam. +func (u *UserActionParam) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "userActionValue": + err = unpopulate(val, "UserActionValue", &u.UserActionValue) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserActionResponse. +func (u UserActionResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "userActionResult", u.UserActionResult) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserActionResponse. +func (u *UserActionResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "userActionResult": + err = unpopulate(val, "UserActionResult", &u.UserActionResult) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/azure-http-specs/azure/core/traitsgroup/zz_options.go b/test/azure-http-specs/azure/core/traitsgroup/zz_options.go new file mode 100644 index 000000000000..d2f58b29c256 --- /dev/null +++ b/test/azure-http-specs/azure/core/traitsgroup/zz_options.go @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package traitsgroup + +import "time" + +// TraitsClientRepeatableActionOptions contains the optional parameters for the TraitsClient.RepeatableAction method. +type TraitsClientRepeatableActionOptions struct { + // Specifies the date and time at which the request was first created. + RepeatabilityFirstSent *time.Time + + // An opaque, globally-unique, client-generated string identifier for the request. + RepeatabilityRequestID *string +} + +// TraitsClientSmokeTestOptions contains the optional parameters for the TraitsClient.SmokeTest method. +type TraitsClientSmokeTestOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The request should only proceed if an entity matches this string. + IfMatch *string + + // The request should only proceed if the entity was modified after this time. + IfModifiedSince *time.Time + + // The request should only proceed if no entity matches this string. + IfNoneMatch *string + + // The request should only proceed if the entity was not modified after this time. + IfUnmodifiedSince *time.Time +} diff --git a/test/azure-http-specs/azure/core/traitsgroup/zz_responses.go b/test/azure-http-specs/azure/core/traitsgroup/zz_responses.go new file mode 100644 index 000000000000..555d77fc90d6 --- /dev/null +++ b/test/azure-http-specs/azure/core/traitsgroup/zz_responses.go @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package traitsgroup + +// TraitsClientRepeatableActionResponse contains the response from method TraitsClient.RepeatableAction. +type TraitsClientRepeatableActionResponse struct { + // User action response + UserActionResponse + + // Indicates whether the repeatable request was accepted or rejected. + RepeatabilityResult *RepeatabilityResult +} + +// TraitsClientSmokeTestResponse contains the response from method TraitsClient.SmokeTest. +type TraitsClientSmokeTestResponse struct { + // Sample Model + User + Bar *string + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The entity tag for the response. + EtagHeader *string +} diff --git a/test/azure-http-specs/azure/core/traitsgroup/zz_traits_client.go b/test/azure-http-specs/azure/core/traitsgroup/zz_traits_client.go new file mode 100644 index 000000000000..e2250bfba999 --- /dev/null +++ b/test/azure-http-specs/azure/core/traitsgroup/zz_traits_client.go @@ -0,0 +1,194 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package traitsgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "net/http" + "net/url" + "strconv" + "strings" +) + +// TraitsClient - Illustrates Azure Core operation customizations by traits +// Don't use this type directly, use NewTraitsClientWithNoCredential() instead. +// +// Generated from API version 2022-12-01-preview +type TraitsClient struct { + internal *azcore.Client + endpoint string +} + +// TraitsClientOptions contains the optional values for creating a [TraitsClient]. +type TraitsClientOptions struct { + azcore.ClientOptions +} + +// NewTraitsClientWithNoCredential creates a new instance of TraitsClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewTraitsClientWithNoCredential(endpoint string, options *TraitsClientOptions) (*TraitsClient, error) { + if options == nil { + options = &TraitsClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{ + APIVersion: runtime.APIVersionOptions{ + Name: "api-version", + Location: runtime.APIVersionLocationQueryParam, + }, + }, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &TraitsClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// RepeatableAction - Test for repeatable requests +// If the operation fails it returns an *azcore.ResponseError type. +// - id - The user's id. +// - body - The body parameter. +// - options - TraitsClientRepeatableActionOptions contains the optional parameters for the TraitsClient.RepeatableAction method. +func (client *TraitsClient) RepeatableAction(ctx context.Context, id int32, body UserActionParam, options *TraitsClientRepeatableActionOptions) (TraitsClientRepeatableActionResponse, error) { + var err error + const operationName = "TraitsClient.RepeatableAction" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.repeatableActionCreateRequest(ctx, id, body, options) + if err != nil { + return TraitsClientRepeatableActionResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TraitsClientRepeatableActionResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return TraitsClientRepeatableActionResponse{}, err + } + resp, err := client.repeatableActionHandleResponse(httpResp) + return resp, err +} + +// repeatableActionCreateRequest creates the RepeatableAction request. +func (client *TraitsClient) repeatableActionCreateRequest(ctx context.Context, id int32, body UserActionParam, options *TraitsClientRepeatableActionOptions) (*policy.Request, error) { + urlPath := "/azure/core/traits/user/{id}:repeatableAction" + urlPath = strings.ReplaceAll(urlPath, "{id}", url.PathEscape(strconv.FormatInt(int64(id), 10))) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20221201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.RepeatabilityFirstSent != nil { + req.Raw().Header["Repeatability-First-Sent"] = []string{datetime.RFC7231(*options.RepeatabilityFirstSent).String()} + } + if options != nil && options.RepeatabilityRequestID != nil { + req.Raw().Header["Repeatability-Request-ID"] = []string{*options.RepeatabilityRequestID} + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// repeatableActionHandleResponse handles the RepeatableAction response. +func (client *TraitsClient) repeatableActionHandleResponse(resp *http.Response) (TraitsClientRepeatableActionResponse, error) { + result := TraitsClientRepeatableActionResponse{} + if val := resp.Header.Get("Repeatability-Result"); val != "" { + result.RepeatabilityResult = (*RepeatabilityResult)(&val) + } + if err := runtime.UnmarshalAsJSON(resp, &result.UserActionResponse); err != nil { + return TraitsClientRepeatableActionResponse{}, err + } + return result, nil +} + +// SmokeTest - Get a resource, sending and receiving headers. +// If the operation fails it returns an *azcore.ResponseError type. +// - id - The user's id. +// - foo - header in request +// - options - TraitsClientSmokeTestOptions contains the optional parameters for the TraitsClient.SmokeTest method. +func (client *TraitsClient) SmokeTest(ctx context.Context, id int32, foo string, options *TraitsClientSmokeTestOptions) (TraitsClientSmokeTestResponse, error) { + var err error + const operationName = "TraitsClient.SmokeTest" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.smokeTestCreateRequest(ctx, id, foo, options) + if err != nil { + return TraitsClientSmokeTestResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TraitsClientSmokeTestResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return TraitsClientSmokeTestResponse{}, err + } + resp, err := client.smokeTestHandleResponse(httpResp) + return resp, err +} + +// smokeTestCreateRequest creates the SmokeTest request. +func (client *TraitsClient) smokeTestCreateRequest(ctx context.Context, id int32, foo string, options *TraitsClientSmokeTestOptions) (*policy.Request, error) { + urlPath := "/azure/core/traits/user/{id}" + urlPath = strings.ReplaceAll(urlPath, "{id}", url.PathEscape(strconv.FormatInt(int64(id), 10))) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20221201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + req.Raw().Header["foo"] = []string{foo} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + return req, nil +} + +// smokeTestHandleResponse handles the SmokeTest response. +func (client *TraitsClient) smokeTestHandleResponse(resp *http.Response) (TraitsClientSmokeTestResponse, error) { + result := TraitsClientSmokeTestResponse{} + if val := resp.Header.Get("bar"); val != "" { + result.Bar = &val + } + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.EtagHeader = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.User); err != nil { + return TraitsClientSmokeTestResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/core/traitsgroup/zz_version.go b/test/azure-http-specs/azure/core/traitsgroup/zz_version.go new file mode 100644 index 000000000000..95fdae89d247 --- /dev/null +++ b/test/azure-http-specs/azure/core/traitsgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package traitsgroup + +const ( + moduleName = "traitsgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/encode/encodedurationgroup/LICENSE.txt b/test/azure-http-specs/azure/encode/encodedurationgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/encode/encodedurationgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/encode/encodedurationgroup/duration_client_test.go b/test/azure-http-specs/azure/encode/encodedurationgroup/duration_client_test.go new file mode 100644 index 000000000000..f1e11b3d4077 --- /dev/null +++ b/test/azure-http-specs/azure/encode/encodedurationgroup/duration_client_test.go @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package encodedurationgroup + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestDurationClient_DurationConstant(t *testing.T) { + client, err := NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + input := "1.02:59:59.5000000" + body := DurationModel{ + Input: &input, + } + result, err := client.DurationConstant(context.Background(), body, nil) + require.NoError(t, err) + require.Equal(t, DurationClientDurationConstantResponse{}, result) +} diff --git a/test/azure-http-specs/azure/encode/encodedurationgroup/fake/zz_duration_server.go b/test/azure-http-specs/azure/encode/encodedurationgroup/fake/zz_duration_server.go new file mode 100644 index 000000000000..afde2c0a4d49 --- /dev/null +++ b/test/azure-http-specs/azure/encode/encodedurationgroup/fake/zz_duration_server.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "encodedurationgroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// DurationServer is a fake server for instances of the encodedurationgroup.DurationClient type. +type DurationServer struct { + // DurationConstant is the fake for method DurationClient.DurationConstant + // HTTP status codes to indicate success: http.StatusNoContent + DurationConstant func(ctx context.Context, body encodedurationgroup.DurationModel, options *encodedurationgroup.DurationClientDurationConstantOptions) (resp azfake.Responder[encodedurationgroup.DurationClientDurationConstantResponse], errResp azfake.ErrorResponder) +} + +// NewDurationServerTransport creates a new instance of DurationServerTransport with the provided implementation. +// The returned DurationServerTransport instance is connected to an instance of encodedurationgroup.DurationClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDurationServerTransport(srv *DurationServer) *DurationServerTransport { + return &DurationServerTransport{srv: srv} +} + +// DurationServerTransport connects instances of encodedurationgroup.DurationClient to instances of DurationServer. +// Don't use this type directly, use NewDurationServerTransport instead. +type DurationServerTransport struct { + srv *DurationServer +} + +// Do implements the policy.Transporter interface for DurationServerTransport. +func (d *DurationServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DurationServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if durationServerTransportInterceptor != nil { + res.resp, res.err, intercepted = durationServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DurationClient.DurationConstant": + res.resp, res.err = d.dispatchDurationConstant(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DurationServerTransport) dispatchDurationConstant(req *http.Request) (*http.Response, error) { + if d.srv.DurationConstant == nil { + return nil, &nonRetriableError{errors.New("fake for method DurationConstant not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[encodedurationgroup.DurationModel](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.DurationConstant(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DurationServerTransport +var durationServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/encode/encodedurationgroup/fake/zz_internal.go b/test/azure-http-specs/azure/encode/encodedurationgroup/fake/zz_internal.go new file mode 100644 index 000000000000..705f81eacafe --- /dev/null +++ b/test/azure-http-specs/azure/encode/encodedurationgroup/fake/zz_internal.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import "net/http" + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} diff --git a/test/azure-http-specs/azure/encode/encodedurationgroup/go.mod b/test/azure-http-specs/azure/encode/encodedurationgroup/go.mod new file mode 100644 index 000000000000..82875ae2fdc3 --- /dev/null +++ b/test/azure-http-specs/azure/encode/encodedurationgroup/go.mod @@ -0,0 +1,17 @@ +module encodedurationgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/encode/encodedurationgroup/go.sum b/test/azure-http-specs/azure/encode/encodedurationgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/encode/encodedurationgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/encode/encodedurationgroup/testdata/_metadata.json b/test/azure-http-specs/azure/encode/encodedurationgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/azure-http-specs/azure/encode/encodedurationgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/encode/encodedurationgroup/zz_duration_client.go b/test/azure-http-specs/azure/encode/encodedurationgroup/zz_duration_client.go new file mode 100644 index 000000000000..fa0bf6515e5e --- /dev/null +++ b/test/azure-http-specs/azure/encode/encodedurationgroup/zz_duration_client.go @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package encodedurationgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// DurationClient - Test for azure related encode decorator. +// Don't use this type directly, use NewDurationClientWithNoCredential() instead. +type DurationClient struct { + internal *azcore.Client + endpoint string +} + +// DurationClientOptions contains the optional values for creating a [DurationClient]. +type DurationClientOptions struct { + azcore.ClientOptions +} + +// NewDurationClientWithNoCredential creates a new instance of DurationClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewDurationClientWithNoCredential(endpoint string, options *DurationClientOptions) (*DurationClient, error) { + if options == nil { + options = &DurationClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &DurationClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// DurationConstant - Test duration with azure specific encoding. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationClientDurationConstantOptions contains the optional parameters for the DurationClient.DurationConstant +// method. +func (client *DurationClient) DurationConstant(ctx context.Context, body DurationModel, options *DurationClientDurationConstantOptions) (DurationClientDurationConstantResponse, error) { + var err error + const operationName = "DurationClient.DurationConstant" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.durationConstantCreateRequest(ctx, body, options) + if err != nil { + return DurationClientDurationConstantResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationClientDurationConstantResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationClientDurationConstantResponse{}, err + } + return DurationClientDurationConstantResponse{}, nil +} + +// durationConstantCreateRequest creates the DurationConstant request. +func (client *DurationClient) durationConstantCreateRequest(ctx context.Context, body DurationModel, _ *DurationClientDurationConstantOptions) (*policy.Request, error) { + urlPath := "/azure/encode/duration/duration-constant" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/azure/encode/encodedurationgroup/zz_models.go b/test/azure-http-specs/azure/encode/encodedurationgroup/zz_models.go new file mode 100644 index 000000000000..8f76599272a6 --- /dev/null +++ b/test/azure-http-specs/azure/encode/encodedurationgroup/zz_models.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package encodedurationgroup + +type DurationModel struct { + // REQUIRED + Input *string +} diff --git a/test/azure-http-specs/azure/encode/encodedurationgroup/zz_models_serde.go b/test/azure-http-specs/azure/encode/encodedurationgroup/zz_models_serde.go new file mode 100644 index 000000000000..fbd732709d4b --- /dev/null +++ b/test/azure-http-specs/azure/encode/encodedurationgroup/zz_models_serde.go @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package encodedurationgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type DurationModel. +func (d DurationModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "input", d.Input) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DurationModel. +func (d *DurationModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "input": + err = unpopulate(val, "Input", &d.Input) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/azure-http-specs/azure/encode/encodedurationgroup/zz_options.go b/test/azure-http-specs/azure/encode/encodedurationgroup/zz_options.go new file mode 100644 index 000000000000..a9c34f2c59e3 --- /dev/null +++ b/test/azure-http-specs/azure/encode/encodedurationgroup/zz_options.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package encodedurationgroup + +// DurationClientDurationConstantOptions contains the optional parameters for the DurationClient.DurationConstant method. +type DurationClientDurationConstantOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/azure/encode/encodedurationgroup/zz_responses.go b/test/azure-http-specs/azure/encode/encodedurationgroup/zz_responses.go new file mode 100644 index 000000000000..f38679d95329 --- /dev/null +++ b/test/azure-http-specs/azure/encode/encodedurationgroup/zz_responses.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package encodedurationgroup + +// DurationClientDurationConstantResponse contains the response from method DurationClient.DurationConstant. +type DurationClientDurationConstantResponse struct { + // placeholder for future response values +} diff --git a/test/azure-http-specs/azure/encode/encodedurationgroup/zz_version.go b/test/azure-http-specs/azure/encode/encodedurationgroup/zz_version.go new file mode 100644 index 000000000000..7880ef1e7023 --- /dev/null +++ b/test/azure-http-specs/azure/encode/encodedurationgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package encodedurationgroup + +const ( + moduleName = "encodedurationgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/example/examplebasicgroup/LICENSE.txt b/test/azure-http-specs/azure/example/examplebasicgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/example/examplebasicgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/example/examplebasicgroup/basicserviceoperationgroup_client_test.go b/test/azure-http-specs/azure/example/examplebasicgroup/basicserviceoperationgroup_client_test.go new file mode 100644 index 000000000000..236a70f67dbe --- /dev/null +++ b/test/azure-http-specs/azure/example/examplebasicgroup/basicserviceoperationgroup_client_test.go @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package examplebasicgroup_test + +import ( + "context" + "examplebasicgroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestBasicServiceOperationGroupClient_Basic_Success(t *testing.T) { + client, err := examplebasicgroup.NewAzureExampleClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + reqBody := examplebasicgroup.ActionRequest{ + StringProperty: to.Ptr("text"), + ModelProperty: &examplebasicgroup.Model{ + Int32Property: to.Ptr(int32(1)), + Float32Property: to.Ptr(float32(1.5)), + EnumProperty: to.Ptr(examplebasicgroup.EnumEnumValue1), + }, + ArrayProperty: []*string{to.Ptr("item")}, + RecordProperty: map[string]*string{ + "record": to.Ptr("value"), + }, + } + _, err = client.BasicAction(context.Background(), "query", "header", reqBody, nil) + require.NoError(t, err) +} diff --git a/test/azure-http-specs/azure/example/examplebasicgroup/fake/zz_azureexample_server.go b/test/azure-http-specs/azure/example/examplebasicgroup/fake/zz_azureexample_server.go new file mode 100644 index 000000000000..d7e595f09dae --- /dev/null +++ b/test/azure-http-specs/azure/example/examplebasicgroup/fake/zz_azureexample_server.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "examplebasicgroup" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// AzureExampleServer is a fake server for instances of the examplebasicgroup.AzureExampleClient type. +type AzureExampleServer struct { + // BasicAction is the fake for method AzureExampleClient.BasicAction + // HTTP status codes to indicate success: http.StatusOK + BasicAction func(ctx context.Context, queryParam string, headerParam string, body examplebasicgroup.ActionRequest, options *examplebasicgroup.AzureExampleClientBasicActionOptions) (resp azfake.Responder[examplebasicgroup.AzureExampleClientBasicActionResponse], errResp azfake.ErrorResponder) +} + +// NewAzureExampleServerTransport creates a new instance of AzureExampleServerTransport with the provided implementation. +// The returned AzureExampleServerTransport instance is connected to an instance of examplebasicgroup.AzureExampleClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAzureExampleServerTransport(srv *AzureExampleServer) *AzureExampleServerTransport { + return &AzureExampleServerTransport{srv: srv} +} + +// AzureExampleServerTransport connects instances of examplebasicgroup.AzureExampleClient to instances of AzureExampleServer. +// Don't use this type directly, use NewAzureExampleServerTransport instead. +type AzureExampleServerTransport struct { + srv *AzureExampleServer +} + +// Do implements the policy.Transporter interface for AzureExampleServerTransport. +func (a *AzureExampleServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *AzureExampleServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if azureExampleServerTransportInterceptor != nil { + res.resp, res.err, intercepted = azureExampleServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "AzureExampleClient.BasicAction": + res.resp, res.err = a.dispatchBasicAction(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *AzureExampleServerTransport) dispatchBasicAction(req *http.Request) (*http.Response, error) { + if a.srv.BasicAction == nil { + return nil, &nonRetriableError{errors.New("fake for method BasicAction not implemented")} + } + qp := req.URL.Query() + body, err := server.UnmarshalRequestAsJSON[examplebasicgroup.ActionRequest](req) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BasicAction(req.Context(), qp.Get("query-param"), getHeaderValue(req.Header, "header-param"), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ActionResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to AzureExampleServerTransport +var azureExampleServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/example/examplebasicgroup/fake/zz_internal.go b/test/azure-http-specs/azure/example/examplebasicgroup/fake/zz_internal.go new file mode 100644 index 000000000000..6a51e841a656 --- /dev/null +++ b/test/azure-http-specs/azure/example/examplebasicgroup/fake/zz_internal.go @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import "net/http" + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getHeaderValue(h http.Header, k string) string { + v := h[k] + if len(v) == 0 { + return "" + } + return v[0] +} diff --git a/test/azure-http-specs/azure/example/examplebasicgroup/go.mod b/test/azure-http-specs/azure/example/examplebasicgroup/go.mod new file mode 100644 index 000000000000..0df80c24d6a8 --- /dev/null +++ b/test/azure-http-specs/azure/example/examplebasicgroup/go.mod @@ -0,0 +1,17 @@ +module examplebasicgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/example/examplebasicgroup/go.sum b/test/azure-http-specs/azure/example/examplebasicgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/example/examplebasicgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/example/examplebasicgroup/testdata/_metadata.json b/test/azure-http-specs/azure/example/examplebasicgroup/testdata/_metadata.json new file mode 100644 index 000000000000..ec01c80564c8 --- /dev/null +++ b/test/azure-http-specs/azure/example/examplebasicgroup/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "_Specs_.Azure.Example.Basic": "2022-12-01-preview" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/example/examplebasicgroup/zz_azureexample_client.go b/test/azure-http-specs/azure/example/examplebasicgroup/zz_azureexample_client.go new file mode 100644 index 000000000000..a928f6d4ac0f --- /dev/null +++ b/test/azure-http-specs/azure/example/examplebasicgroup/zz_azureexample_client.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package examplebasicgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// AzureExampleClient contains the methods for the AzureExample group. +// Don't use this type directly, use NewAzureExampleClientWithNoCredential() instead. +// +// Generated from API version 2022-12-01-preview +type AzureExampleClient struct { + internal *azcore.Client + endpoint string +} + +// AzureExampleClientOptions contains the optional values for creating a [AzureExampleClient]. +type AzureExampleClientOptions struct { + azcore.ClientOptions +} + +// NewAzureExampleClientWithNoCredential creates a new instance of AzureExampleClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewAzureExampleClientWithNoCredential(endpoint string, options *AzureExampleClientOptions) (*AzureExampleClient, error) { + if options == nil { + options = &AzureExampleClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{ + APIVersion: runtime.APIVersionOptions{ + Name: "api-version", + Location: runtime.APIVersionLocationQueryParam, + }, + }, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &AzureExampleClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// BasicAction - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - AzureExampleClientBasicActionOptions contains the optional parameters for the AzureExampleClient.BasicAction +// method. +func (client *AzureExampleClient) BasicAction(ctx context.Context, queryParam string, headerParam string, body ActionRequest, options *AzureExampleClientBasicActionOptions) (AzureExampleClientBasicActionResponse, error) { + var err error + const operationName = "AzureExampleClient.BasicAction" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.basicActionCreateRequest(ctx, queryParam, headerParam, body, options) + if err != nil { + return AzureExampleClientBasicActionResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AzureExampleClientBasicActionResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AzureExampleClientBasicActionResponse{}, err + } + resp, err := client.basicActionHandleResponse(httpResp) + return resp, err +} + +// basicActionCreateRequest creates the BasicAction request. +func (client *AzureExampleClient) basicActionCreateRequest(ctx context.Context, queryParam string, headerParam string, body ActionRequest, _ *AzureExampleClientBasicActionOptions) (*policy.Request, error) { + urlPath := "/azure/example/basic/basic" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20221201Preview) + reqQP.Set("query-param", queryParam) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["header-param"] = []string{headerParam} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// basicActionHandleResponse handles the BasicAction response. +func (client *AzureExampleClient) basicActionHandleResponse(resp *http.Response) (AzureExampleClientBasicActionResponse, error) { + result := AzureExampleClientBasicActionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ActionResponse); err != nil { + return AzureExampleClientBasicActionResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/example/examplebasicgroup/zz_constants.go b/test/azure-http-specs/azure/example/examplebasicgroup/zz_constants.go new file mode 100644 index 000000000000..9a1e5929d226 --- /dev/null +++ b/test/azure-http-specs/azure/example/examplebasicgroup/zz_constants.go @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package examplebasicgroup + +const ( + version20221201Preview string = "2022-12-01-preview" +) + +type Enum string + +const ( + EnumEnumValue1 Enum = "EnumValue1" +) + +// PossibleEnumValues returns the possible values for the Enum const type. +func PossibleEnumValues() []Enum { + return []Enum{ + EnumEnumValue1, + } +} diff --git a/test/azure-http-specs/azure/example/examplebasicgroup/zz_models.go b/test/azure-http-specs/azure/example/examplebasicgroup/zz_models.go new file mode 100644 index 000000000000..376ff36555fb --- /dev/null +++ b/test/azure-http-specs/azure/example/examplebasicgroup/zz_models.go @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package examplebasicgroup + +type ActionRequest struct { + // REQUIRED + StringProperty *string + ArrayProperty []*string + ModelProperty *Model + RecordProperty map[string]*string +} + +type ActionResponse struct { + // REQUIRED + StringProperty *string + ArrayProperty []*string + ModelProperty *Model + RecordProperty map[string]*string +} + +type Model struct { + EnumProperty *Enum + Float32Property *float32 + Int32Property *int32 +} diff --git a/test/azure-http-specs/azure/example/examplebasicgroup/zz_models_serde.go b/test/azure-http-specs/azure/example/examplebasicgroup/zz_models_serde.go new file mode 100644 index 000000000000..f1c0c6e5e88f --- /dev/null +++ b/test/azure-http-specs/azure/example/examplebasicgroup/zz_models_serde.go @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package examplebasicgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type ActionRequest. +func (a ActionRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "arrayProperty", a.ArrayProperty) + populate(objectMap, "modelProperty", a.ModelProperty) + populate(objectMap, "recordProperty", a.RecordProperty) + populate(objectMap, "stringProperty", a.StringProperty) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ActionRequest. +func (a *ActionRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "arrayProperty": + err = unpopulate(val, "ArrayProperty", &a.ArrayProperty) + delete(rawMsg, key) + case "modelProperty": + err = unpopulate(val, "ModelProperty", &a.ModelProperty) + delete(rawMsg, key) + case "recordProperty": + err = unpopulate(val, "RecordProperty", &a.RecordProperty) + delete(rawMsg, key) + case "stringProperty": + err = unpopulate(val, "StringProperty", &a.StringProperty) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ActionResponse. +func (a ActionResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "arrayProperty", a.ArrayProperty) + populate(objectMap, "modelProperty", a.ModelProperty) + populate(objectMap, "recordProperty", a.RecordProperty) + populate(objectMap, "stringProperty", a.StringProperty) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ActionResponse. +func (a *ActionResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "arrayProperty": + err = unpopulate(val, "ArrayProperty", &a.ArrayProperty) + delete(rawMsg, key) + case "modelProperty": + err = unpopulate(val, "ModelProperty", &a.ModelProperty) + delete(rawMsg, key) + case "recordProperty": + err = unpopulate(val, "RecordProperty", &a.RecordProperty) + delete(rawMsg, key) + case "stringProperty": + err = unpopulate(val, "StringProperty", &a.StringProperty) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Model. +func (m Model) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enumProperty", m.EnumProperty) + populate(objectMap, "float32Property", m.Float32Property) + populate(objectMap, "int32Property", m.Int32Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Model. +func (m *Model) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "enumProperty": + err = unpopulate(val, "EnumProperty", &m.EnumProperty) + delete(rawMsg, key) + case "float32Property": + err = unpopulate(val, "Float32Property", &m.Float32Property) + delete(rawMsg, key) + case "int32Property": + err = unpopulate(val, "Int32Property", &m.Int32Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/azure-http-specs/azure/example/examplebasicgroup/zz_options.go b/test/azure-http-specs/azure/example/examplebasicgroup/zz_options.go new file mode 100644 index 000000000000..0408aef581f9 --- /dev/null +++ b/test/azure-http-specs/azure/example/examplebasicgroup/zz_options.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package examplebasicgroup + +// AzureExampleClientBasicActionOptions contains the optional parameters for the AzureExampleClient.BasicAction method. +type AzureExampleClientBasicActionOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/azure/example/examplebasicgroup/zz_responses.go b/test/azure-http-specs/azure/example/examplebasicgroup/zz_responses.go new file mode 100644 index 000000000000..8fbf35cb903a --- /dev/null +++ b/test/azure-http-specs/azure/example/examplebasicgroup/zz_responses.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package examplebasicgroup + +// AzureExampleClientBasicActionResponse contains the response from method AzureExampleClient.BasicAction. +type AzureExampleClientBasicActionResponse struct { + ActionResponse +} diff --git a/test/azure-http-specs/azure/example/examplebasicgroup/zz_version.go b/test/azure-http-specs/azure/example/examplebasicgroup/zz_version.go new file mode 100644 index 000000000000..729aedbb2791 --- /dev/null +++ b/test/azure-http-specs/azure/example/examplebasicgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package examplebasicgroup + +const ( + moduleName = "examplebasicgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/payload/pageablegroup/LICENSE.txt b/test/azure-http-specs/azure/payload/pageablegroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/payload/pageablegroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/payload/pageablegroup/fake/zz_internal.go b/test/azure-http-specs/azure/payload/pageablegroup/fake/zz_internal.go new file mode 100644 index 000000000000..c6cbd9a6db98 --- /dev/null +++ b/test/azure-http-specs/azure/payload/pageablegroup/fake/zz_internal.go @@ -0,0 +1,67 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func parseOptional[T any](v string, parse func(v string) (T, error)) (*T, error) { + if v == "" { + return nil, nil + } + t, err := parse(v) + if err != nil { + return nil, err + } + return &t, nil +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/azure-http-specs/azure/payload/pageablegroup/fake/zz_pageable_server.go b/test/azure-http-specs/azure/payload/pageablegroup/fake/zz_pageable_server.go new file mode 100644 index 000000000000..da5104f532f7 --- /dev/null +++ b/test/azure-http-specs/azure/payload/pageablegroup/fake/zz_pageable_server.go @@ -0,0 +1,131 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "pageablegroup" + "slices" + "strconv" +) + +// PageableServer is a fake server for instances of the pageablegroup.PageableClient type. +type PageableServer struct { + // NewListPager is the fake for method PageableClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *pageablegroup.PageableClientListOptions) (resp azfake.PagerResponder[pageablegroup.PageableClientListResponse]) +} + +// NewPageableServerTransport creates a new instance of PageableServerTransport with the provided implementation. +// The returned PageableServerTransport instance is connected to an instance of pageablegroup.PageableClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewPageableServerTransport(srv *PageableServer) *PageableServerTransport { + return &PageableServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[pageablegroup.PageableClientListResponse]](), + } +} + +// PageableServerTransport connects instances of pageablegroup.PageableClient to instances of PageableServer. +// Don't use this type directly, use NewPageableServerTransport instead. +type PageableServerTransport struct { + srv *PageableServer + newListPager *tracker[azfake.PagerResponder[pageablegroup.PageableClientListResponse]] +} + +// Do implements the policy.Transporter interface for PageableServerTransport. +func (p *PageableServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return p.dispatchToMethodFake(req, method) +} + +func (p *PageableServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if pageableServerTransportInterceptor != nil { + res.resp, res.err, intercepted = pageableServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "PageableClient.NewListPager": + res.resp, res.err = p.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (p *PageableServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if p.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := p.newListPager.get(req) + if newListPager == nil { + qp := req.URL.Query() + maxpagesizeParam, err := parseOptional(qp.Get("maxpagesize"), func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + var options *pageablegroup.PageableClientListOptions + if maxpagesizeParam != nil { + options = &pageablegroup.PageableClientListOptions{ + Maxpagesize: maxpagesizeParam, + } + } + resp := p.srv.NewListPager(options) + newListPager = &resp + p.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *pageablegroup.PageableClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + p.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to PageableServerTransport +var pageableServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/payload/pageablegroup/go.mod b/test/azure-http-specs/azure/payload/pageablegroup/go.mod new file mode 100644 index 000000000000..b853b413cda0 --- /dev/null +++ b/test/azure-http-specs/azure/payload/pageablegroup/go.mod @@ -0,0 +1,17 @@ +module pageablegroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/payload/pageablegroup/go.sum b/test/azure-http-specs/azure/payload/pageablegroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/payload/pageablegroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/payload/pageablegroup/pageable_client_test.go b/test/azure-http-specs/azure/payload/pageablegroup/pageable_client_test.go new file mode 100644 index 000000000000..1c21afec656a --- /dev/null +++ b/test/azure-http-specs/azure/payload/pageablegroup/pageable_client_test.go @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package pageablegroup_test + +import ( + "context" + "pageablegroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestPageableClientNewListPager(t *testing.T) { + client, err := pageablegroup.NewPageableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + pager := client.NewListPager(&pageablegroup.PageableClientListOptions{ + Maxpagesize: to.Ptr[int32](3), + }) + pageCount := 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + pageCount++ + switch pageCount { + case 1: + require.Len(t, page.Value, 3) + require.NotNil(t, page.NextLink) + case 2: + require.Len(t, page.Value, 1) + require.Nil(t, page.NextLink) + default: + t.Fatalf("unexpected page number %d", pageCount) + } + } + require.EqualValues(t, 2, pageCount) +} diff --git a/test/azure-http-specs/azure/payload/pageablegroup/testdata/_metadata.json b/test/azure-http-specs/azure/payload/pageablegroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/azure-http-specs/azure/payload/pageablegroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/payload/pageablegroup/zz_models.go b/test/azure-http-specs/azure/payload/pageablegroup/zz_models.go new file mode 100644 index 000000000000..c1cf9a35b467 --- /dev/null +++ b/test/azure-http-specs/azure/payload/pageablegroup/zz_models.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package pageablegroup + +// PagedUser - Paged collection of User items +type PagedUser struct { + // REQUIRED; The User items on this page + Value []*User + + // The link to the next page of items + NextLink *string +} + +// User model +type User struct { + // REQUIRED; User name + Name *string +} diff --git a/test/azure-http-specs/azure/payload/pageablegroup/zz_models_serde.go b/test/azure-http-specs/azure/payload/pageablegroup/zz_models_serde.go new file mode 100644 index 000000000000..00b179e6d1b2 --- /dev/null +++ b/test/azure-http-specs/azure/payload/pageablegroup/zz_models_serde.go @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package pageablegroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type PagedUser. +func (p PagedUser) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", p.NextLink) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PagedUser. +func (p *PagedUser) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &p.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type User. +func (u User) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", u.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type User. +func (u *User) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &u.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/azure-http-specs/azure/payload/pageablegroup/zz_options.go b/test/azure-http-specs/azure/payload/pageablegroup/zz_options.go new file mode 100644 index 000000000000..4dfa9c9e8616 --- /dev/null +++ b/test/azure-http-specs/azure/payload/pageablegroup/zz_options.go @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package pageablegroup + +// PageableClientListOptions contains the optional parameters for the PageableClient.NewListPager method. +type PageableClientListOptions struct { + // The maximum number of result items per page. + Maxpagesize *int32 +} diff --git a/test/azure-http-specs/azure/payload/pageablegroup/zz_pageable_client.go b/test/azure-http-specs/azure/payload/pageablegroup/zz_pageable_client.go new file mode 100644 index 000000000000..7e8e3b02c5cd --- /dev/null +++ b/test/azure-http-specs/azure/payload/pageablegroup/zz_pageable_client.go @@ -0,0 +1,95 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package pageablegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strconv" + "strings" +) + +// PageableClient - Test describing pageable. +// Don't use this type directly, use NewPageableClientWithNoCredential() instead. +type PageableClient struct { + internal *azcore.Client + endpoint string +} + +// PageableClientOptions contains the optional values for creating a [PageableClient]. +type PageableClientOptions struct { + azcore.ClientOptions +} + +// NewPageableClientWithNoCredential creates a new instance of PageableClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewPageableClientWithNoCredential(endpoint string, options *PageableClientOptions) (*PageableClient, error) { + if options == nil { + options = &PageableClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &PageableClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewListPager - List users +// - options - PageableClientListOptions contains the optional parameters for the PageableClient.NewListPager method. +func (client *PageableClient) NewListPager(options *PageableClientListOptions) *runtime.Pager[PageableClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[PageableClientListResponse]{ + More: func(page PageableClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PageableClientListResponse) (PageableClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PageableClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return PageableClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *PageableClient) listCreateRequest(ctx context.Context, options *PageableClientListOptions) (*policy.Request, error) { + urlPath := "/azure/payload/pageable" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Maxpagesize != nil { + reqQP.Set("maxpagesize", strconv.FormatInt(int64(*options.Maxpagesize), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *PageableClient) listHandleResponse(resp *http.Response) (PageableClientListResponse, error) { + result := PageableClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PagedUser); err != nil { + return PageableClientListResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/payload/pageablegroup/zz_responses.go b/test/azure-http-specs/azure/payload/pageablegroup/zz_responses.go new file mode 100644 index 000000000000..bcf568072116 --- /dev/null +++ b/test/azure-http-specs/azure/payload/pageablegroup/zz_responses.go @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package pageablegroup + +// PageableClientListResponse contains the response from method PageableClient.NewListPager. +type PageableClientListResponse struct { + // Paged collection of User items + PagedUser +} diff --git a/test/azure-http-specs/azure/payload/pageablegroup/zz_version.go b/test/azure-http-specs/azure/payload/pageablegroup/zz_version.go new file mode 100644 index 000000000000..893c5de20824 --- /dev/null +++ b/test/azure-http-specs/azure/payload/pageablegroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package pageablegroup + +const ( + moduleName = "pageablegroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/LICENSE.txt b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/disk_client_test.go b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/disk_client_test.go new file mode 100644 index 000000000000..468dc2c3e02f --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/disk_client_test.go @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package armmultipleservicegroup_test + +import ( + "armmultipleservicegroup" + "fmt" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +var ( + validDiskResource = armmultipleservicegroup.Disk{ + ID: to.Ptr(fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/disks/disk1", subscriptionIdExpected, resourceGroupExpected)), + Name: to.Ptr("disk1"), + Type: to.Ptr("Microsoft.Compute/disks"), + Location: to.Ptr(locationExpected), + Properties: &armmultipleservicegroup.DiskProperties{ + ProvisioningState: to.Ptr(armmultipleservicegroup.ResourceProvisioningStateSucceeded), + }, + } +) + +func TestDiskClient_Get(t *testing.T) { + diskClientGetResponse, err := clientFactory.NewDisksClient().Get(ctx, resourceGroupExpected, "disk1", nil) + require.NoError(t, err) + require.Equal(t, *validDiskResource.ID, *diskClientGetResponse.ID) + require.Equal(t, *validDiskResource.Name, *diskClientGetResponse.Name) + require.Equal(t, *validDiskResource.Type, *diskClientGetResponse.Type) + require.Equal(t, *validDiskResource.Location, *diskClientGetResponse.Location) + require.Equal(t, *validDiskResource.Properties.ProvisioningState, *diskClientGetResponse.Properties.ProvisioningState) +} + +func TestDiskClient_CreateOrUpdate(t *testing.T) { + poller, err := clientFactory.NewDisksClient().BeginCreateOrUpdate(ctx, resourceGroupExpected, "disk1", armmultipleservicegroup.Disk{ + Location: validDiskResource.Location, + Properties: &armmultipleservicegroup.DiskProperties{}, + }, nil) + require.NoError(t, err) + + diskClientCreateOrUpdateResponse, err := poller.PollUntilDone(ctx, nil) + require.NoError(t, err) + require.Equal(t, *validDiskResource.ID, *diskClientCreateOrUpdateResponse.ID) + require.Equal(t, *validDiskResource.Name, *diskClientCreateOrUpdateResponse.Name) + require.Equal(t, *validDiskResource.Type, *diskClientCreateOrUpdateResponse.Type) + require.Equal(t, *validDiskResource.Location, *diskClientCreateOrUpdateResponse.Location) + require.Equal(t, *validDiskResource.Properties.ProvisioningState, *diskClientCreateOrUpdateResponse.Properties.ProvisioningState) +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/fake/zz_disks_server.go b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/fake/zz_disks_server.go new file mode 100644 index 000000000000..c714c2ba507b --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/fake/zz_disks_server.go @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armmultipleservicegroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// DisksServer is a fake server for instances of the armmultipleservicegroup.DisksClient type. +type DisksServer struct { + // BeginCreateOrUpdate is the fake for method DisksClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, diskName string, resource armmultipleservicegroup.Disk, options *armmultipleservicegroup.DisksClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armmultipleservicegroup.DisksClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method DisksClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, diskName string, options *armmultipleservicegroup.DisksClientGetOptions) (resp azfake.Responder[armmultipleservicegroup.DisksClientGetResponse], errResp azfake.ErrorResponder) +} + +// NewDisksServerTransport creates a new instance of DisksServerTransport with the provided implementation. +// The returned DisksServerTransport instance is connected to an instance of armmultipleservicegroup.DisksClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDisksServerTransport(srv *DisksServer) *DisksServerTransport { + return &DisksServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armmultipleservicegroup.DisksClientCreateOrUpdateResponse]](), + } +} + +// DisksServerTransport connects instances of armmultipleservicegroup.DisksClient to instances of DisksServer. +// Don't use this type directly, use NewDisksServerTransport instead. +type DisksServerTransport struct { + srv *DisksServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armmultipleservicegroup.DisksClientCreateOrUpdateResponse]] +} + +// Do implements the policy.Transporter interface for DisksServerTransport. +func (d *DisksServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DisksServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if disksServerTransportInterceptor != nil { + res.resp, res.err, intercepted = disksServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DisksClient.BeginCreateOrUpdate": + res.resp, res.err = d.dispatchBeginCreateOrUpdate(req) + case "DisksClient.Get": + res.resp, res.err = d.dispatchGet(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DisksServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if d.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := d.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Compute/disks/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armmultipleservicegroup.Disk](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + diskNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("diskName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, diskNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + d.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + d.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + d.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (d *DisksServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Compute/disks/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + diskNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("diskName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Get(req.Context(), resourceGroupNameParam, diskNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Disk, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DisksServerTransport +var disksServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/fake/zz_internal.go b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/fake/zz_internal.go new file mode 100644 index 000000000000..590b4d743e97 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/fake/zz_internal.go @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/fake/zz_server_factory.go b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/fake/zz_server_factory.go new file mode 100644 index 000000000000..d9277db3a6be --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/fake/zz_server_factory.go @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armmultipleservicegroup.ClientFactory type. +type ServerFactory struct { + // DisksServer contains the fakes for client DisksClient + DisksServer DisksServer + + // VirtualMachinesServer contains the fakes for client VirtualMachinesClient + VirtualMachinesServer VirtualMachinesServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armmultipleservicegroup.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of armmultipleservicegroup.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trDisksServer *DisksServerTransport + trVirtualMachinesServer *VirtualMachinesServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "DisksClient": + initServer(&s.trMu, &s.trDisksServer, func() *DisksServerTransport { return NewDisksServerTransport(&s.srv.DisksServer) }) + resp, err = s.trDisksServer.Do(req) + case "VirtualMachinesClient": + initServer(&s.trMu, &s.trVirtualMachinesServer, func() *VirtualMachinesServerTransport { + return NewVirtualMachinesServerTransport(&s.srv.VirtualMachinesServer) + }) + resp, err = s.trVirtualMachinesServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/fake/zz_virtualmachines_server.go b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/fake/zz_virtualmachines_server.go new file mode 100644 index 000000000000..66bbb18832ab --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/fake/zz_virtualmachines_server.go @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armmultipleservicegroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// VirtualMachinesServer is a fake server for instances of the armmultipleservicegroup.VirtualMachinesClient type. +type VirtualMachinesServer struct { + // BeginCreateOrUpdate is the fake for method VirtualMachinesClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, vmName string, resource armmultipleservicegroup.VirtualMachine, options *armmultipleservicegroup.VirtualMachinesClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armmultipleservicegroup.VirtualMachinesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method VirtualMachinesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, vmName string, options *armmultipleservicegroup.VirtualMachinesClientGetOptions) (resp azfake.Responder[armmultipleservicegroup.VirtualMachinesClientGetResponse], errResp azfake.ErrorResponder) +} + +// NewVirtualMachinesServerTransport creates a new instance of VirtualMachinesServerTransport with the provided implementation. +// The returned VirtualMachinesServerTransport instance is connected to an instance of armmultipleservicegroup.VirtualMachinesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewVirtualMachinesServerTransport(srv *VirtualMachinesServer) *VirtualMachinesServerTransport { + return &VirtualMachinesServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armmultipleservicegroup.VirtualMachinesClientCreateOrUpdateResponse]](), + } +} + +// VirtualMachinesServerTransport connects instances of armmultipleservicegroup.VirtualMachinesClient to instances of VirtualMachinesServer. +// Don't use this type directly, use NewVirtualMachinesServerTransport instead. +type VirtualMachinesServerTransport struct { + srv *VirtualMachinesServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armmultipleservicegroup.VirtualMachinesClientCreateOrUpdateResponse]] +} + +// Do implements the policy.Transporter interface for VirtualMachinesServerTransport. +func (v *VirtualMachinesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *VirtualMachinesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if virtualMachinesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = virtualMachinesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "VirtualMachinesClient.BeginCreateOrUpdate": + res.resp, res.err = v.dispatchBeginCreateOrUpdate(req) + case "VirtualMachinesClient.Get": + res.resp, res.err = v.dispatchGet(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *VirtualMachinesServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if v.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := v.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Compute/virtualMachines/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armmultipleservicegroup.VirtualMachine](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + vmNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("vmName")]) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, vmNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + v.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + v.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + v.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (v *VirtualMachinesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Compute/virtualMachines/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + vmNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("vmName")]) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Get(req.Context(), resourceGroupNameParam, vmNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).VirtualMachine, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to VirtualMachinesServerTransport +var virtualMachinesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/go.mod b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/go.mod new file mode 100644 index 000000000000..5eb231d7faff --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/go.mod @@ -0,0 +1,17 @@ +module armmultipleservicegroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/go.sum b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/testdata/_metadata.json b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/testdata/_metadata.json new file mode 100644 index 000000000000..5d6b45007a74 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/testdata/_metadata.json @@ -0,0 +1,7 @@ +{ + "apiVersions": { + "Azure.ResourceManager.MultiService.Compute": "2025-04-01", + "Azure.ResourceManager.MultiService.ComputeDisk": "2025-01-02" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/utils_test.go b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/utils_test.go new file mode 100644 index 000000000000..3124d3aa0322 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/utils_test.go @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package armmultipleservicegroup_test + +import ( + "armmultipleservicegroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" +) + +var ( + ctx context.Context + clientFactory *armmultipleservicegroup.ClientFactory + + subscriptionIdExpected = "00000000-0000-0000-0000-000000000000" + locationExpected = "eastus" + resourceGroupExpected = "test-rg" +) + +func TestMain(m *testing.M) { + ctx = context.Background() + clientFactory, _ = armmultipleservicegroup.NewClientFactory(subscriptionIdExpected, &azfake.TokenCredential{}, &arm.ClientOptions{ + ClientOptions: azcore.ClientOptions{ + Cloud: cloud.Configuration{ + Services: map[cloud.ServiceName]cloud.ServiceConfiguration{ + cloud.ResourceManager: { + Audience: "fake_audience", + Endpoint: "http://localhost:3000", + }, + }, + }, + InsecureAllowCredentialWithHTTP: true, + }, + }) + + m.Run() +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/virtual_machine_client_test.go b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/virtual_machine_client_test.go new file mode 100644 index 000000000000..d4c2bdc30640 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/virtual_machine_client_test.go @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package armmultipleservicegroup_test + +import ( + "armmultipleservicegroup" + "fmt" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +var ( + validVirtualMachineResource = armmultipleservicegroup.VirtualMachine{ + ID: to.Ptr(fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/virtualMachines/vm1", subscriptionIdExpected, resourceGroupExpected)), + Name: to.Ptr("vm1"), + Type: to.Ptr("Microsoft.Compute/virtualMachines"), + Location: to.Ptr(locationExpected), + Properties: &armmultipleservicegroup.VirtualMachineProperties{ + ProvisioningState: to.Ptr(armmultipleservicegroup.ResourceProvisioningStateSucceeded), + }, + } +) + +func TestVirtualMachineClient_Get(t *testing.T) { + virtualMachineClientGetResponse, err := clientFactory.NewVirtualMachinesClient().Get(ctx, resourceGroupExpected, "vm1", nil) + require.NoError(t, err) + require.Equal(t, *validVirtualMachineResource.ID, *virtualMachineClientGetResponse.ID) + require.Equal(t, *validVirtualMachineResource.Name, *virtualMachineClientGetResponse.Name) + require.Equal(t, *validVirtualMachineResource.Type, *virtualMachineClientGetResponse.Type) + require.Equal(t, *validVirtualMachineResource.Location, *virtualMachineClientGetResponse.Location) + require.Equal(t, *validVirtualMachineResource.Properties.ProvisioningState, *virtualMachineClientGetResponse.Properties.ProvisioningState) +} + +func TestVirtualMachineClient_CreateOrUpdate(t *testing.T) { + poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, resourceGroupExpected, "vm1", armmultipleservicegroup.VirtualMachine{ + Location: validVirtualMachineResource.Location, + Properties: &armmultipleservicegroup.VirtualMachineProperties{}, + }, nil) + require.NoError(t, err) + + virtualMachineClientCreateOrUpdateResponse, err := poller.PollUntilDone(ctx, nil) + require.NoError(t, err) + require.Equal(t, *validVirtualMachineResource.ID, *virtualMachineClientCreateOrUpdateResponse.ID) + require.Equal(t, *validVirtualMachineResource.Name, *virtualMachineClientCreateOrUpdateResponse.Name) + require.Equal(t, *validVirtualMachineResource.Type, *virtualMachineClientCreateOrUpdateResponse.Type) + require.Equal(t, *validVirtualMachineResource.Location, *virtualMachineClientCreateOrUpdateResponse.Location) + require.Equal(t, *validVirtualMachineResource.Properties.ProvisioningState, *virtualMachineClientCreateOrUpdateResponse.Properties.ProvisioningState) +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_client_factory.go b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_client_factory.go new file mode 100644 index 000000000000..2aa8d1daba25 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_client_factory.go @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmultipleservicegroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + subscriptionID string + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, + internal: internal, + }, nil +} + +// NewDisksClient creates a new instance of DisksClient. +func (c *ClientFactory) NewDisksClient() *DisksClient { + return &DisksClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewVirtualMachinesClient creates a new instance of VirtualMachinesClient. +func (c *ClientFactory) NewVirtualMachinesClient() *VirtualMachinesClient { + return &VirtualMachinesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_constants.go b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_constants.go new file mode 100644 index 000000000000..4e03defec06f --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_constants.go @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmultipleservicegroup + +const ( + version20250102 string = "2025-01-02" + version20250401 string = "2025-04-01" +) + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// ResourceProvisioningState - The provisioning state of a resource type. +type ResourceProvisioningState string + +const ( + // ResourceProvisioningStateCanceled - Resource creation was canceled. + ResourceProvisioningStateCanceled ResourceProvisioningState = "Canceled" + // ResourceProvisioningStateFailed - Resource creation failed. + ResourceProvisioningStateFailed ResourceProvisioningState = "Failed" + // ResourceProvisioningStateSucceeded - Resource has been created. + ResourceProvisioningStateSucceeded ResourceProvisioningState = "Succeeded" +) + +// PossibleResourceProvisioningStateValues returns the possible values for the ResourceProvisioningState const type. +func PossibleResourceProvisioningStateValues() []ResourceProvisioningState { + return []ResourceProvisioningState{ + ResourceProvisioningStateCanceled, + ResourceProvisioningStateFailed, + ResourceProvisioningStateSucceeded, + } +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_disks_client.go b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_disks_client.go new file mode 100644 index 000000000000..6f0a47b71f86 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_disks_client.go @@ -0,0 +1,181 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmultipleservicegroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// DisksClient contains the methods for the Disks group. +// Don't use this type directly, use NewDisksClient() instead. +// +// Generated from API version 2025-01-02 +type DisksClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDisksClient creates a new instance of DisksClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewDisksClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DisksClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DisksClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a disk. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - diskName - The name of the Disk +// - resource - Resource create parameters. +// - options - DisksClientBeginCreateOrUpdateOptions contains the optional parameters for the DisksClient.BeginCreateOrUpdate +// method. +func (client *DisksClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, diskName string, resource Disk, options *DisksClientBeginCreateOrUpdateOptions) (*runtime.Poller[DisksClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, diskName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DisksClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DisksClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a disk. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *DisksClient) createOrUpdate(ctx context.Context, resourceGroupName string, diskName string, resource Disk, options *DisksClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "DisksClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, diskName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *DisksClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, diskName string, resource Disk, _ *DisksClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks/{diskName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if diskName == "" { + return nil, errors.New("parameter diskName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{diskName}", url.PathEscape(diskName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250102) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// Get - Gets information about a disk. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - diskName - The name of the Disk +// - options - DisksClientGetOptions contains the optional parameters for the DisksClient.Get method. +func (client *DisksClient) Get(ctx context.Context, resourceGroupName string, diskName string, options *DisksClientGetOptions) (DisksClientGetResponse, error) { + var err error + const operationName = "DisksClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, diskName, options) + if err != nil { + return DisksClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DisksClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DisksClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DisksClient) getCreateRequest(ctx context.Context, resourceGroupName string, diskName string, _ *DisksClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/disks/{diskName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if diskName == "" { + return nil, errors.New("parameter diskName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{diskName}", url.PathEscape(diskName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250102) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DisksClient) getHandleResponse(resp *http.Response) (DisksClientGetResponse, error) { + result := DisksClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Disk); err != nil { + return DisksClientGetResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_models.go b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_models.go new file mode 100644 index 000000000000..cd896805ec2d --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_models.go @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmultipleservicegroup + +import "time" + +// Disk resource. +type Disk struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *DiskProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// DiskProperties - Disk resource properties. +type DiskProperties struct { + // READ-ONLY + ProvisioningState *ResourceProvisioningState +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time + + // The identity that created the resource. + CreatedBy *string + + // The type of identity that created the resource. + CreatedByType *CreatedByType + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time + + // The identity that last modified the resource. + LastModifiedBy *string + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType +} + +// VirtualMachine - Describes a Virtual Machine. +type VirtualMachine struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *VirtualMachineProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +type VirtualMachineProperties struct { + // READ-ONLY + ProvisioningState *ResourceProvisioningState +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_models_serde.go b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_models_serde.go new file mode 100644 index 000000000000..8388cd5d58e1 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_models_serde.go @@ -0,0 +1,265 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmultipleservicegroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type Disk. +func (d Disk) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", d.ID) + populate(objectMap, "location", d.Location) + populate(objectMap, "name", d.Name) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "systemData", d.SystemData) + populate(objectMap, "tags", d.Tags) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Disk. +func (d *Disk) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &d.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &d.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &d.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &d.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &d.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DiskProperties. +func (d DiskProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", d.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiskProperties. +func (d *DiskProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &d.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateTime[datetime.RFC3339](objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateTime[datetime.RFC3339](val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateTime[datetime.RFC3339](val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualMachine. +func (v VirtualMachine) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", v.ID) + populate(objectMap, "location", v.Location) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "systemData", v.SystemData) + populate(objectMap, "tags", v.Tags) + populate(objectMap, "type", v.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachine. +func (v *VirtualMachine) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &v.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &v.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &v.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &v.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &v.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &v.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &v.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualMachineProperties. +func (v VirtualMachineProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", v.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineProperties. +func (v *VirtualMachineProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_options.go b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_options.go new file mode 100644 index 000000000000..5be982659d6e --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_options.go @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmultipleservicegroup + +// DisksClientBeginCreateOrUpdateOptions contains the optional parameters for the DisksClient.BeginCreateOrUpdate method. +type DisksClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// DisksClientGetOptions contains the optional parameters for the DisksClient.Get method. +type DisksClientGetOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachinesClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualMachinesClient.BeginCreateOrUpdate +// method. +type VirtualMachinesClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// VirtualMachinesClientGetOptions contains the optional parameters for the VirtualMachinesClient.Get method. +type VirtualMachinesClientGetOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_responses.go b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_responses.go new file mode 100644 index 000000000000..0072057dc5a1 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_responses.go @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmultipleservicegroup + +// DisksClientCreateOrUpdateResponse contains the response from method DisksClient.BeginCreateOrUpdate. +type DisksClientCreateOrUpdateResponse struct { + // Disk resource. + Disk +} + +// DisksClientGetResponse contains the response from method DisksClient.Get. +type DisksClientGetResponse struct { + // Disk resource. + Disk +} + +// VirtualMachinesClientCreateOrUpdateResponse contains the response from method VirtualMachinesClient.BeginCreateOrUpdate. +type VirtualMachinesClientCreateOrUpdateResponse struct { + // Describes a Virtual Machine. + VirtualMachine +} + +// VirtualMachinesClientGetResponse contains the response from method VirtualMachinesClient.Get. +type VirtualMachinesClientGetResponse struct { + // Describes a Virtual Machine. + VirtualMachine +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_version.go b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_version.go new file mode 100644 index 000000000000..59bdb820bb61 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package armmultipleservicegroup + +const ( + moduleName = "armmultipleservicegroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_virtualmachines_client.go b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_virtualmachines_client.go new file mode 100644 index 000000000000..c6f36105e855 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultipleservicegroup/zz_virtualmachines_client.go @@ -0,0 +1,183 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmultipleservicegroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// VirtualMachinesClient contains the methods for the VirtualMachines group. +// Don't use this type directly, use NewVirtualMachinesClient() instead. +// +// Generated from API version 2025-04-01 +type VirtualMachinesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualMachinesClient creates a new instance of VirtualMachinesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewVirtualMachinesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualMachinesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualMachinesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - The operation to create or update a virtual machine. Please note some properties can be set only +// during virtual machine creation. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - vmName - The name of the VirtualMachine +// - resource - Resource create parameters. +// - options - VirtualMachinesClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualMachinesClient.BeginCreateOrUpdate +// method. +func (client *VirtualMachinesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, vmName string, resource VirtualMachine, options *VirtualMachinesClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualMachinesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, vmName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachinesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachinesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - The operation to create or update a virtual machine. Please note some properties can be set only during +// virtual machine creation. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *VirtualMachinesClient) createOrUpdate(ctx context.Context, resourceGroupName string, vmName string, resource VirtualMachine, options *VirtualMachinesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachinesClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, vmName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *VirtualMachinesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, vmName string, resource VirtualMachine, _ *VirtualMachinesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250401) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// Get - Retrieves information about the model view or the instance view of a virtual machine. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - vmName - The name of the VirtualMachine +// - options - VirtualMachinesClientGetOptions contains the optional parameters for the VirtualMachinesClient.Get method. +func (client *VirtualMachinesClient) Get(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientGetOptions) (VirtualMachinesClientGetResponse, error) { + var err error + const operationName = "VirtualMachinesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, vmName, options) + if err != nil { + return VirtualMachinesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachinesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachinesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualMachinesClient) getCreateRequest(ctx context.Context, resourceGroupName string, vmName string, _ *VirtualMachinesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250401) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VirtualMachinesClient) getHandleResponse(resp *http.Response) (VirtualMachinesClientGetResponse, error) { + result := VirtualMachinesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachine); err != nil { + return VirtualMachinesClientGetResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/LICENSE.txt b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/fake/zz_internal.go b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/fake/zz_internal.go new file mode 100644 index 000000000000..590b4d743e97 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/fake/zz_internal.go @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/fake/zz_server_factory.go b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/fake/zz_server_factory.go new file mode 100644 index 000000000000..97f664f8b9fa --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/fake/zz_server_factory.go @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armmultisharedmodelsgroup.ClientFactory type. +type ServerFactory struct { + // StorageAccountsServer contains the fakes for client StorageAccountsClient + StorageAccountsServer StorageAccountsServer + + // VirtualMachinesServer contains the fakes for client VirtualMachinesClient + VirtualMachinesServer VirtualMachinesServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armmultisharedmodelsgroup.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of armmultisharedmodelsgroup.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trStorageAccountsServer *StorageAccountsServerTransport + trVirtualMachinesServer *VirtualMachinesServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "StorageAccountsClient": + initServer(&s.trMu, &s.trStorageAccountsServer, func() *StorageAccountsServerTransport { + return NewStorageAccountsServerTransport(&s.srv.StorageAccountsServer) + }) + resp, err = s.trStorageAccountsServer.Do(req) + case "VirtualMachinesClient": + initServer(&s.trMu, &s.trVirtualMachinesServer, func() *VirtualMachinesServerTransport { + return NewVirtualMachinesServerTransport(&s.srv.VirtualMachinesServer) + }) + resp, err = s.trVirtualMachinesServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/fake/zz_storageaccounts_server.go b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/fake/zz_storageaccounts_server.go new file mode 100644 index 000000000000..f74d637a533b --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/fake/zz_storageaccounts_server.go @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armmultisharedmodelsgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// StorageAccountsServer is a fake server for instances of the armmultisharedmodelsgroup.StorageAccountsClient type. +type StorageAccountsServer struct { + // BeginCreateOrUpdate is the fake for method StorageAccountsClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, accountName string, resource armmultisharedmodelsgroup.StorageAccount, options *armmultisharedmodelsgroup.StorageAccountsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armmultisharedmodelsgroup.StorageAccountsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method StorageAccountsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, accountName string, options *armmultisharedmodelsgroup.StorageAccountsClientGetOptions) (resp azfake.Responder[armmultisharedmodelsgroup.StorageAccountsClientGetResponse], errResp azfake.ErrorResponder) +} + +// NewStorageAccountsServerTransport creates a new instance of StorageAccountsServerTransport with the provided implementation. +// The returned StorageAccountsServerTransport instance is connected to an instance of armmultisharedmodelsgroup.StorageAccountsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewStorageAccountsServerTransport(srv *StorageAccountsServer) *StorageAccountsServerTransport { + return &StorageAccountsServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armmultisharedmodelsgroup.StorageAccountsClientCreateOrUpdateResponse]](), + } +} + +// StorageAccountsServerTransport connects instances of armmultisharedmodelsgroup.StorageAccountsClient to instances of StorageAccountsServer. +// Don't use this type directly, use NewStorageAccountsServerTransport instead. +type StorageAccountsServerTransport struct { + srv *StorageAccountsServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armmultisharedmodelsgroup.StorageAccountsClientCreateOrUpdateResponse]] +} + +// Do implements the policy.Transporter interface for StorageAccountsServerTransport. +func (s *StorageAccountsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *StorageAccountsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if storageAccountsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = storageAccountsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "StorageAccountsClient.BeginCreateOrUpdate": + res.resp, res.err = s.dispatchBeginCreateOrUpdate(req) + case "StorageAccountsClient.Get": + res.resp, res.err = s.dispatchGet(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *StorageAccountsServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if s.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := s.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Storage/storageAccounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armmultisharedmodelsgroup.StorageAccount](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, accountNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + s.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + s.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + s.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (s *StorageAccountsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if s.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Storage/storageAccounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Get(req.Context(), resourceGroupNameParam, accountNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).StorageAccount, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to StorageAccountsServerTransport +var storageAccountsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/fake/zz_virtualmachines_server.go b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/fake/zz_virtualmachines_server.go new file mode 100644 index 000000000000..e610edab257e --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/fake/zz_virtualmachines_server.go @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armmultisharedmodelsgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// VirtualMachinesServer is a fake server for instances of the armmultisharedmodelsgroup.VirtualMachinesClient type. +type VirtualMachinesServer struct { + // BeginCreateOrUpdate is the fake for method VirtualMachinesClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, vmName string, resource armmultisharedmodelsgroup.VirtualMachine, options *armmultisharedmodelsgroup.VirtualMachinesClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armmultisharedmodelsgroup.VirtualMachinesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method VirtualMachinesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, vmName string, options *armmultisharedmodelsgroup.VirtualMachinesClientGetOptions) (resp azfake.Responder[armmultisharedmodelsgroup.VirtualMachinesClientGetResponse], errResp azfake.ErrorResponder) +} + +// NewVirtualMachinesServerTransport creates a new instance of VirtualMachinesServerTransport with the provided implementation. +// The returned VirtualMachinesServerTransport instance is connected to an instance of armmultisharedmodelsgroup.VirtualMachinesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewVirtualMachinesServerTransport(srv *VirtualMachinesServer) *VirtualMachinesServerTransport { + return &VirtualMachinesServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armmultisharedmodelsgroup.VirtualMachinesClientCreateOrUpdateResponse]](), + } +} + +// VirtualMachinesServerTransport connects instances of armmultisharedmodelsgroup.VirtualMachinesClient to instances of VirtualMachinesServer. +// Don't use this type directly, use NewVirtualMachinesServerTransport instead. +type VirtualMachinesServerTransport struct { + srv *VirtualMachinesServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armmultisharedmodelsgroup.VirtualMachinesClientCreateOrUpdateResponse]] +} + +// Do implements the policy.Transporter interface for VirtualMachinesServerTransport. +func (v *VirtualMachinesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *VirtualMachinesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if virtualMachinesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = virtualMachinesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "VirtualMachinesClient.BeginCreateOrUpdate": + res.resp, res.err = v.dispatchBeginCreateOrUpdate(req) + case "VirtualMachinesClient.Get": + res.resp, res.err = v.dispatchGet(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *VirtualMachinesServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if v.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := v.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Compute/virtualMachinesShared/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armmultisharedmodelsgroup.VirtualMachine](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + vmNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("vmName")]) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, vmNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + v.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + v.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + v.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (v *VirtualMachinesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Compute/virtualMachinesShared/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + vmNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("vmName")]) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Get(req.Context(), resourceGroupNameParam, vmNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).VirtualMachine, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to VirtualMachinesServerTransport +var virtualMachinesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/go.mod b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/go.mod new file mode 100644 index 000000000000..227502cc7788 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/go.mod @@ -0,0 +1,17 @@ +module armmultisharedmodelsgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/go.sum b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/storage_accounts_client_test.go b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/storage_accounts_client_test.go new file mode 100644 index 000000000000..eaba9703b3f4 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/storage_accounts_client_test.go @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package armmultisharedmodelsgroup_test + +import ( + "armmultisharedmodelsgroup" + "fmt" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +var ( + validStorageAccountResource = armmultisharedmodelsgroup.StorageAccount{ + ID: to.Ptr(fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Storage/storageAccounts/account1", subscriptionIDExpected, resourceGroupExpected)), + Name: to.Ptr("account1"), + Type: to.Ptr("Microsoft.Storage/storageAccounts"), + Location: to.Ptr("westus"), + Properties: &armmultisharedmodelsgroup.StorageAccountProperties{ + ProvisioningState: to.Ptr(armmultisharedmodelsgroup.ResourceProvisioningStateSucceeded), + Metadata: &armmultisharedmodelsgroup.SharedMetadata{ + CreatedBy: to.Ptr("admin@example.com"), + Tags: map[string]*string{"department": to.Ptr("engineering")}, + }, + }, + } +) + +func TestStorageAccountsClient_Get(t *testing.T) { + resp, err := clientFactory.NewStorageAccountsClient().Get(ctx, resourceGroupExpected, "account1", nil) + require.NoError(t, err) + require.Equal(t, *validStorageAccountResource.ID, *resp.ID) + require.Equal(t, *validStorageAccountResource.Name, *resp.Name) + require.Equal(t, *validStorageAccountResource.Type, *resp.Type) + require.Equal(t, *validStorageAccountResource.Location, *resp.Location) + require.Equal(t, *validStorageAccountResource.Properties.ProvisioningState, *resp.Properties.ProvisioningState) + require.NotNil(t, resp.Properties.Metadata) + require.Equal(t, *validStorageAccountResource.Properties.Metadata.CreatedBy, *resp.Properties.Metadata.CreatedBy) + require.Equal(t, *validStorageAccountResource.Properties.Metadata.Tags["department"], *resp.Properties.Metadata.Tags["department"]) +} + +func TestStorageAccountsClient_CreateOrUpdate(t *testing.T) { + poller, err := clientFactory.NewStorageAccountsClient().BeginCreateOrUpdate(ctx, resourceGroupExpected, "account1", armmultisharedmodelsgroup.StorageAccount{ + Location: to.Ptr("westus"), + Properties: &armmultisharedmodelsgroup.StorageAccountProperties{ + Metadata: &armmultisharedmodelsgroup.SharedMetadata{ + CreatedBy: to.Ptr("admin@example.com"), + Tags: map[string]*string{"department": to.Ptr("engineering")}, + }, + }, + }, nil) + require.NoError(t, err) + + resp, err := poller.PollUntilDone(ctx, nil) + require.NoError(t, err) + require.Equal(t, *validStorageAccountResource.ID, *resp.ID) + require.Equal(t, *validStorageAccountResource.Name, *resp.Name) + require.Equal(t, *validStorageAccountResource.Type, *resp.Type) + require.Equal(t, *validStorageAccountResource.Location, *resp.Location) + require.Equal(t, *validStorageAccountResource.Properties.ProvisioningState, *resp.Properties.ProvisioningState) +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/testdata/_metadata.json b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/testdata/_metadata.json new file mode 100644 index 000000000000..c87d973f87da --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/testdata/_metadata.json @@ -0,0 +1,7 @@ +{ + "apiVersions": { + "Azure.ResourceManager.MultiServiceSharedModels.Compute": "2025-05-01", + "Azure.ResourceManager.MultiServiceSharedModels.Storage": "2025-02-01" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/utils_test.go b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/utils_test.go new file mode 100644 index 000000000000..b1eef92cf355 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/utils_test.go @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package armmultisharedmodelsgroup_test + +import ( + "armmultisharedmodelsgroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" +) + +var ( + ctx context.Context + clientFactory *armmultisharedmodelsgroup.ClientFactory + + subscriptionIDExpected = "00000000-0000-0000-0000-000000000000" + resourceGroupExpected = "test-rg" +) + +func TestMain(m *testing.M) { + ctx = context.Background() + clientFactory, _ = armmultisharedmodelsgroup.NewClientFactory(subscriptionIDExpected, &azfake.TokenCredential{}, &arm.ClientOptions{ + ClientOptions: azcore.ClientOptions{ + Cloud: cloud.Configuration{ + Services: map[cloud.ServiceName]cloud.ServiceConfiguration{ + cloud.ResourceManager: { + Audience: "fake_audience", + Endpoint: "http://localhost:3000", + }, + }, + }, + InsecureAllowCredentialWithHTTP: true, + }, + }) + + m.Run() +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/virtual_machines_client_test.go b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/virtual_machines_client_test.go new file mode 100644 index 000000000000..87ac2cd68b58 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/virtual_machines_client_test.go @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package armmultisharedmodelsgroup_test + +import ( + "armmultisharedmodelsgroup" + "fmt" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +var ( + validVirtualMachineResource = armmultisharedmodelsgroup.VirtualMachine{ + ID: to.Ptr(fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/virtualMachinesShared/vm-shared1", subscriptionIDExpected, resourceGroupExpected)), + Name: to.Ptr("vm-shared1"), + Type: to.Ptr("Microsoft.Compute/virtualMachinesShared"), + Location: to.Ptr("eastus"), + Properties: &armmultisharedmodelsgroup.VirtualMachineProperties{ + ProvisioningState: to.Ptr(armmultisharedmodelsgroup.ResourceProvisioningStateSucceeded), + Metadata: &armmultisharedmodelsgroup.SharedMetadata{ + CreatedBy: to.Ptr("user@example.com"), + Tags: map[string]*string{"environment": to.Ptr("production")}, + }, + }, + } +) + +func TestVirtualMachinesClient_Get(t *testing.T) { + resp, err := clientFactory.NewVirtualMachinesClient().Get(ctx, resourceGroupExpected, "vm-shared1", nil) + require.NoError(t, err) + require.Equal(t, *validVirtualMachineResource.ID, *resp.ID) + require.Equal(t, *validVirtualMachineResource.Name, *resp.Name) + require.Equal(t, *validVirtualMachineResource.Type, *resp.Type) + require.Equal(t, *validVirtualMachineResource.Location, *resp.Location) + require.Equal(t, *validVirtualMachineResource.Properties.ProvisioningState, *resp.Properties.ProvisioningState) + require.NotNil(t, resp.Properties.Metadata) + require.Equal(t, *validVirtualMachineResource.Properties.Metadata.CreatedBy, *resp.Properties.Metadata.CreatedBy) + require.Equal(t, *validVirtualMachineResource.Properties.Metadata.Tags["environment"], *resp.Properties.Metadata.Tags["environment"]) +} + +func TestVirtualMachinesClient_CreateOrUpdate(t *testing.T) { + poller, err := clientFactory.NewVirtualMachinesClient().BeginCreateOrUpdate(ctx, resourceGroupExpected, "vm-shared1", armmultisharedmodelsgroup.VirtualMachine{ + Location: to.Ptr("eastus"), + Properties: &armmultisharedmodelsgroup.VirtualMachineProperties{ + Metadata: &armmultisharedmodelsgroup.SharedMetadata{ + CreatedBy: to.Ptr("user@example.com"), + Tags: map[string]*string{"environment": to.Ptr("production")}, + }, + }, + }, nil) + require.NoError(t, err) + + resp, err := poller.PollUntilDone(ctx, nil) + require.NoError(t, err) + require.Equal(t, *validVirtualMachineResource.ID, *resp.ID) + require.Equal(t, *validVirtualMachineResource.Name, *resp.Name) + require.Equal(t, *validVirtualMachineResource.Type, *resp.Type) + require.Equal(t, *validVirtualMachineResource.Location, *resp.Location) + require.Equal(t, *validVirtualMachineResource.Properties.ProvisioningState, *resp.Properties.ProvisioningState) +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_client_factory.go b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_client_factory.go new file mode 100644 index 000000000000..0d32c859e3e5 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_client_factory.go @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmultisharedmodelsgroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + subscriptionID string + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, + internal: internal, + }, nil +} + +// NewStorageAccountsClient creates a new instance of StorageAccountsClient. +func (c *ClientFactory) NewStorageAccountsClient() *StorageAccountsClient { + return &StorageAccountsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewVirtualMachinesClient creates a new instance of VirtualMachinesClient. +func (c *ClientFactory) NewVirtualMachinesClient() *VirtualMachinesClient { + return &VirtualMachinesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_constants.go b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_constants.go new file mode 100644 index 000000000000..9bfb1b6cfd27 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_constants.go @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmultisharedmodelsgroup + +const ( + version20250201 string = "2025-02-01" + version20250501 string = "2025-05-01" +) + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// ResourceProvisioningState - The provisioning state of a resource type. +type ResourceProvisioningState string + +const ( + // ResourceProvisioningStateCanceled - Resource creation was canceled. + ResourceProvisioningStateCanceled ResourceProvisioningState = "Canceled" + // ResourceProvisioningStateFailed - Resource creation failed. + ResourceProvisioningStateFailed ResourceProvisioningState = "Failed" + // ResourceProvisioningStateSucceeded - Resource has been created. + ResourceProvisioningStateSucceeded ResourceProvisioningState = "Succeeded" +) + +// PossibleResourceProvisioningStateValues returns the possible values for the ResourceProvisioningState const type. +func PossibleResourceProvisioningStateValues() []ResourceProvisioningState { + return []ResourceProvisioningState{ + ResourceProvisioningStateCanceled, + ResourceProvisioningStateFailed, + ResourceProvisioningStateSucceeded, + } +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_models.go b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_models.go new file mode 100644 index 000000000000..8457c7d7c0a2 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_models.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmultisharedmodelsgroup + +import "time" + +// SharedMetadata - Common metadata shared across multiple services. +type SharedMetadata struct { + // Creation timestamp of the resource. + CreatedAt *time.Time + + // Creator of the resource. + CreatedBy *string + + // Tags associated with the resource. + Tags map[string]*string +} + +// StorageAccount - Storage account resource. +type StorageAccount struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *StorageAccountProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// StorageAccountProperties - Storage account properties. +type StorageAccountProperties struct { + // Shared metadata for the storage account. + Metadata *SharedMetadata + + // READ-ONLY + ProvisioningState *ResourceProvisioningState +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time + + // The identity that created the resource. + CreatedBy *string + + // The type of identity that created the resource. + CreatedByType *CreatedByType + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time + + // The identity that last modified the resource. + LastModifiedBy *string + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType +} + +// VirtualMachine - Describes a Virtual Machine. +type VirtualMachine struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *VirtualMachineProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +type VirtualMachineProperties struct { + // Shared metadata for the virtual machine. + Metadata *SharedMetadata + + // READ-ONLY + ProvisioningState *ResourceProvisioningState +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_models_serde.go b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_models_serde.go new file mode 100644 index 000000000000..129ea2d514d7 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_models_serde.go @@ -0,0 +1,308 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmultisharedmodelsgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type SharedMetadata. +func (s SharedMetadata) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "tags", s.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SharedMetadata. +func (s *SharedMetadata) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateTime[datetime.RFC3339](val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &s.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type StorageAccount. +func (s StorageAccount) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + populate(objectMap, "location", s.Location) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "systemData", s.SystemData) + populate(objectMap, "tags", s.Tags) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StorageAccount. +func (s *StorageAccount) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &s.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &s.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &s.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type StorageAccountProperties. +func (s StorageAccountProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "metadata", s.Metadata) + populate(objectMap, "provisioningState", s.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StorageAccountProperties. +func (s *StorageAccountProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "metadata": + err = unpopulate(val, "Metadata", &s.Metadata) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateTime[datetime.RFC3339](objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateTime[datetime.RFC3339](val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateTime[datetime.RFC3339](val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualMachine. +func (v VirtualMachine) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", v.ID) + populate(objectMap, "location", v.Location) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "systemData", v.SystemData) + populate(objectMap, "tags", v.Tags) + populate(objectMap, "type", v.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachine. +func (v *VirtualMachine) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &v.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &v.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &v.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &v.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &v.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &v.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &v.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualMachineProperties. +func (v VirtualMachineProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "metadata", v.Metadata) + populate(objectMap, "provisioningState", v.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineProperties. +func (v *VirtualMachineProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "metadata": + err = unpopulate(val, "Metadata", &v.Metadata) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_options.go b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_options.go new file mode 100644 index 000000000000..e07489d3ba80 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_options.go @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmultisharedmodelsgroup + +// StorageAccountsClientBeginCreateOrUpdateOptions contains the optional parameters for the StorageAccountsClient.BeginCreateOrUpdate +// method. +type StorageAccountsClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// StorageAccountsClientGetOptions contains the optional parameters for the StorageAccountsClient.Get method. +type StorageAccountsClientGetOptions struct { + // placeholder for future optional parameters +} + +// VirtualMachinesClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualMachinesClient.BeginCreateOrUpdate +// method. +type VirtualMachinesClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// VirtualMachinesClientGetOptions contains the optional parameters for the VirtualMachinesClient.Get method. +type VirtualMachinesClientGetOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_responses.go b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_responses.go new file mode 100644 index 000000000000..561f8770d48e --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_responses.go @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmultisharedmodelsgroup + +// StorageAccountsClientCreateOrUpdateResponse contains the response from method StorageAccountsClient.BeginCreateOrUpdate. +type StorageAccountsClientCreateOrUpdateResponse struct { + // Storage account resource. + StorageAccount +} + +// StorageAccountsClientGetResponse contains the response from method StorageAccountsClient.Get. +type StorageAccountsClientGetResponse struct { + // Storage account resource. + StorageAccount +} + +// VirtualMachinesClientCreateOrUpdateResponse contains the response from method VirtualMachinesClient.BeginCreateOrUpdate. +type VirtualMachinesClientCreateOrUpdateResponse struct { + // Describes a Virtual Machine. + VirtualMachine +} + +// VirtualMachinesClientGetResponse contains the response from method VirtualMachinesClient.Get. +type VirtualMachinesClientGetResponse struct { + // Describes a Virtual Machine. + VirtualMachine +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_storageaccounts_client.go b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_storageaccounts_client.go new file mode 100644 index 000000000000..681419407b86 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_storageaccounts_client.go @@ -0,0 +1,181 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmultisharedmodelsgroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// StorageAccountsClient contains the methods for the StorageAccounts group. +// Don't use this type directly, use NewStorageAccountsClient() instead. +// +// Generated from API version 2025-02-01 +type StorageAccountsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewStorageAccountsClient creates a new instance of StorageAccountsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewStorageAccountsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*StorageAccountsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &StorageAccountsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates a storage account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of the StorageAccount +// - resource - Resource create parameters. +// - options - StorageAccountsClientBeginCreateOrUpdateOptions contains the optional parameters for the StorageAccountsClient.BeginCreateOrUpdate +// method. +func (client *StorageAccountsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, resource StorageAccount, options *StorageAccountsClientBeginCreateOrUpdateOptions) (*runtime.Poller[StorageAccountsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, accountName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[StorageAccountsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[StorageAccountsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates a storage account. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *StorageAccountsClient) createOrUpdate(ctx context.Context, resourceGroupName string, accountName string, resource StorageAccount, options *StorageAccountsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "StorageAccountsClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *StorageAccountsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, resource StorageAccount, _ *StorageAccountsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250201) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// Get - Gets information about a storage account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of the StorageAccount +// - options - StorageAccountsClientGetOptions contains the optional parameters for the StorageAccountsClient.Get method. +func (client *StorageAccountsClient) Get(ctx context.Context, resourceGroupName string, accountName string, options *StorageAccountsClientGetOptions) (StorageAccountsClientGetResponse, error) { + var err error + const operationName = "StorageAccountsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return StorageAccountsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return StorageAccountsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return StorageAccountsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *StorageAccountsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, _ *StorageAccountsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250201) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *StorageAccountsClient) getHandleResponse(resp *http.Response) (StorageAccountsClientGetResponse, error) { + result := StorageAccountsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.StorageAccount); err != nil { + return StorageAccountsClientGetResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_version.go b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_version.go new file mode 100644 index 000000000000..73aa24935ef4 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package armmultisharedmodelsgroup + +const ( + moduleName = "armmultisharedmodelsgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_virtualmachines_client.go b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_virtualmachines_client.go new file mode 100644 index 000000000000..9357e49a16f3 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/armmultisharedmodelsgroup/zz_virtualmachines_client.go @@ -0,0 +1,183 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmultisharedmodelsgroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// VirtualMachinesClient contains the methods for the VirtualMachines group. +// Don't use this type directly, use NewVirtualMachinesClient() instead. +// +// Generated from API version 2025-05-01 +type VirtualMachinesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualMachinesClient creates a new instance of VirtualMachinesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewVirtualMachinesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualMachinesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualMachinesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - The operation to create or update a virtual machine. Please note some properties can be set only +// during virtual machine creation. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - vmName - The name of the VirtualMachine +// - resource - Resource create parameters. +// - options - VirtualMachinesClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualMachinesClient.BeginCreateOrUpdate +// method. +func (client *VirtualMachinesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, vmName string, resource VirtualMachine, options *VirtualMachinesClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualMachinesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, vmName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualMachinesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualMachinesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - The operation to create or update a virtual machine. Please note some properties can be set only during +// virtual machine creation. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *VirtualMachinesClient) createOrUpdate(ctx context.Context, resourceGroupName string, vmName string, resource VirtualMachine, options *VirtualMachinesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualMachinesClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, vmName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *VirtualMachinesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, vmName string, resource VirtualMachine, _ *VirtualMachinesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachinesShared/{vmName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// Get - Retrieves information about the model view or the instance view of a virtual machine. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - vmName - The name of the VirtualMachine +// - options - VirtualMachinesClientGetOptions contains the optional parameters for the VirtualMachinesClient.Get method. +func (client *VirtualMachinesClient) Get(ctx context.Context, resourceGroupName string, vmName string, options *VirtualMachinesClientGetOptions) (VirtualMachinesClientGetResponse, error) { + var err error + const operationName = "VirtualMachinesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, vmName, options) + if err != nil { + return VirtualMachinesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualMachinesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualMachinesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualMachinesClient) getCreateRequest(ctx context.Context, resourceGroupName string, vmName string, _ *VirtualMachinesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachinesShared/{vmName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if vmName == "" { + return nil, errors.New("parameter vmName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{vmName}", url.PathEscape(vmName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VirtualMachinesClient) getHandleResponse(resp *http.Response) (VirtualMachinesClientGetResponse, error) { + result := VirtualMachinesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualMachine); err != nil { + return VirtualMachinesClientGetResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/commonpropsgroup/LICENSE.txt b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/resource-manager/commonpropsgroup/error_client_test.go b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/error_client_test.go new file mode 100644 index 000000000000..b7f4b24702a3 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/error_client_test.go @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package commonpropsgroup_test + +import ( + "commonpropsgroup" + "net/http" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestErrorClient_CreateForUserDefinedError(t *testing.T) { + resp, err := clientFactory.NewErrorClient().CreateForUserDefinedError(ctx, resourceGroupExpected, "confidential", commonpropsgroup.ConfidentialResource{ + Location: to.Ptr("eastus"), + Properties: &commonpropsgroup.ConfidentialResourceProperties{ + Username: to.Ptr("00"), + }, + }, nil) + require.Error(t, err) + require.NotNil(t, resp) + var respErr *azcore.ResponseError + require.ErrorAs(t, err, &respErr) + require.EqualValues(t, http.StatusBadRequest, respErr.StatusCode) + require.Zero(t, resp) + bodyBytes := make([]byte, respErr.RawResponse.ContentLength) + _, readErr := respErr.RawResponse.Body.Read(bodyBytes) + require.NoError(t, readErr) + bodyString := string(bodyBytes) + require.Contains(t, bodyString, "Username should not contain only numbers.") +} + +func TestErrorClient_GetForPredefinedError(t *testing.T) { + resp, err := clientFactory.NewErrorClient().GetForPredefinedError(ctx, resourceGroupExpected, "confidential", nil) + require.Error(t, err) + require.NotNil(t, resp) + var respErr *azcore.ResponseError + require.ErrorAs(t, err, &respErr) + require.EqualValues(t, http.StatusNotFound, respErr.StatusCode) + require.Zero(t, resp) + bodyBytes := make([]byte, respErr.RawResponse.ContentLength) + _, readErr := respErr.RawResponse.Body.Read(bodyBytes) + require.NoError(t, readErr) + bodyString := string(bodyBytes) + require.Contains(t, bodyString, "The Resource 'Azure.ResourceManager.CommonProperties/confidentialResources/confidential' under resource group 'test-rg' was not found.") +} diff --git a/test/azure-http-specs/azure/resource-manager/commonpropsgroup/fake/zz_armresourceidentifiers_server.go b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/fake/zz_armresourceidentifiers_server.go new file mode 100644 index 000000000000..7a5224aff6e6 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/fake/zz_armresourceidentifiers_server.go @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "commonpropsgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// ArmResourceIdentifiersServer is a fake server for instances of the commonpropsgroup.ArmResourceIdentifiersClient type. +type ArmResourceIdentifiersServer struct { + // CreateOrReplace is the fake for method ArmResourceIdentifiersClient.CreateOrReplace + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrReplace func(ctx context.Context, resourceGroupName string, armResourceIdentifierResourceName string, resource commonpropsgroup.ArmResourceIdentifierResource, options *commonpropsgroup.ArmResourceIdentifiersClientCreateOrReplaceOptions) (resp azfake.Responder[commonpropsgroup.ArmResourceIdentifiersClientCreateOrReplaceResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method ArmResourceIdentifiersClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, armResourceIdentifierResourceName string, options *commonpropsgroup.ArmResourceIdentifiersClientGetOptions) (resp azfake.Responder[commonpropsgroup.ArmResourceIdentifiersClientGetResponse], errResp azfake.ErrorResponder) +} + +// NewArmResourceIdentifiersServerTransport creates a new instance of ArmResourceIdentifiersServerTransport with the provided implementation. +// The returned ArmResourceIdentifiersServerTransport instance is connected to an instance of commonpropsgroup.ArmResourceIdentifiersClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewArmResourceIdentifiersServerTransport(srv *ArmResourceIdentifiersServer) *ArmResourceIdentifiersServerTransport { + return &ArmResourceIdentifiersServerTransport{srv: srv} +} + +// ArmResourceIdentifiersServerTransport connects instances of commonpropsgroup.ArmResourceIdentifiersClient to instances of ArmResourceIdentifiersServer. +// Don't use this type directly, use NewArmResourceIdentifiersServerTransport instead. +type ArmResourceIdentifiersServerTransport struct { + srv *ArmResourceIdentifiersServer +} + +// Do implements the policy.Transporter interface for ArmResourceIdentifiersServerTransport. +func (a *ArmResourceIdentifiersServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *ArmResourceIdentifiersServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if armResourceIdentifiersServerTransportInterceptor != nil { + res.resp, res.err, intercepted = armResourceIdentifiersServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ArmResourceIdentifiersClient.CreateOrReplace": + res.resp, res.err = a.dispatchCreateOrReplace(req) + case "ArmResourceIdentifiersClient.Get": + res.resp, res.err = a.dispatchGet(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *ArmResourceIdentifiersServerTransport) dispatchCreateOrReplace(req *http.Request) (*http.Response, error) { + if a.srv.CreateOrReplace == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrReplace not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.CommonProperties/armResourceIdentifierResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[commonpropsgroup.ArmResourceIdentifierResource](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + armResourceIdentifierResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("armResourceIdentifierResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.CreateOrReplace(req.Context(), resourceGroupNameParam, armResourceIdentifierResourceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ArmResourceIdentifierResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *ArmResourceIdentifiersServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.CommonProperties/armResourceIdentifierResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + armResourceIdentifierResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("armResourceIdentifierResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Get(req.Context(), resourceGroupNameParam, armResourceIdentifierResourceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ArmResourceIdentifierResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ArmResourceIdentifiersServerTransport +var armResourceIdentifiersServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/resource-manager/commonpropsgroup/fake/zz_error_server.go b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/fake/zz_error_server.go new file mode 100644 index 000000000000..fbf311f2154a --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/fake/zz_error_server.go @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "commonpropsgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// ErrorServer is a fake server for instances of the commonpropsgroup.ErrorClient type. +type ErrorServer struct { + // CreateForUserDefinedError is the fake for method ErrorClient.CreateForUserDefinedError + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateForUserDefinedError func(ctx context.Context, resourceGroupName string, confidentialResourceName string, resource commonpropsgroup.ConfidentialResource, options *commonpropsgroup.ErrorClientCreateForUserDefinedErrorOptions) (resp azfake.Responder[commonpropsgroup.ErrorClientCreateForUserDefinedErrorResponse], errResp azfake.ErrorResponder) + + // GetForPredefinedError is the fake for method ErrorClient.GetForPredefinedError + // HTTP status codes to indicate success: http.StatusOK + GetForPredefinedError func(ctx context.Context, resourceGroupName string, confidentialResourceName string, options *commonpropsgroup.ErrorClientGetForPredefinedErrorOptions) (resp azfake.Responder[commonpropsgroup.ErrorClientGetForPredefinedErrorResponse], errResp azfake.ErrorResponder) +} + +// NewErrorServerTransport creates a new instance of ErrorServerTransport with the provided implementation. +// The returned ErrorServerTransport instance is connected to an instance of commonpropsgroup.ErrorClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewErrorServerTransport(srv *ErrorServer) *ErrorServerTransport { + return &ErrorServerTransport{srv: srv} +} + +// ErrorServerTransport connects instances of commonpropsgroup.ErrorClient to instances of ErrorServer. +// Don't use this type directly, use NewErrorServerTransport instead. +type ErrorServerTransport struct { + srv *ErrorServer +} + +// Do implements the policy.Transporter interface for ErrorServerTransport. +func (e *ErrorServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return e.dispatchToMethodFake(req, method) +} + +func (e *ErrorServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if errorServerTransportInterceptor != nil { + res.resp, res.err, intercepted = errorServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ErrorClient.CreateForUserDefinedError": + res.resp, res.err = e.dispatchCreateForUserDefinedError(req) + case "ErrorClient.GetForPredefinedError": + res.resp, res.err = e.dispatchGetForPredefinedError(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (e *ErrorServerTransport) dispatchCreateForUserDefinedError(req *http.Request) (*http.Response, error) { + if e.srv.CreateForUserDefinedError == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateForUserDefinedError not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.CommonProperties/confidentialResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[commonpropsgroup.ConfidentialResource](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + confidentialResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("confidentialResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.CreateForUserDefinedError(req.Context(), resourceGroupNameParam, confidentialResourceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ConfidentialResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *ErrorServerTransport) dispatchGetForPredefinedError(req *http.Request) (*http.Response, error) { + if e.srv.GetForPredefinedError == nil { + return nil, &nonRetriableError{errors.New("fake for method GetForPredefinedError not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.CommonProperties/confidentialResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + confidentialResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("confidentialResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.GetForPredefinedError(req.Context(), resourceGroupNameParam, confidentialResourceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ConfidentialResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ErrorServerTransport +var errorServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/resource-manager/commonpropsgroup/fake/zz_internal.go b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/azure-http-specs/azure/resource-manager/commonpropsgroup/fake/zz_managedidentity_server.go b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/fake/zz_managedidentity_server.go new file mode 100644 index 000000000000..1f1a63e664c6 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/fake/zz_managedidentity_server.go @@ -0,0 +1,203 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "commonpropsgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// ManagedIdentityServer is a fake server for instances of the commonpropsgroup.ManagedIdentityClient type. +type ManagedIdentityServer struct { + // CreateWithSystemAssigned is the fake for method ManagedIdentityClient.CreateWithSystemAssigned + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateWithSystemAssigned func(ctx context.Context, resourceGroupName string, managedIdentityTrackedResourceName string, resource commonpropsgroup.ManagedIdentityTrackedResource, options *commonpropsgroup.ManagedIdentityClientCreateWithSystemAssignedOptions) (resp azfake.Responder[commonpropsgroup.ManagedIdentityClientCreateWithSystemAssignedResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method ManagedIdentityClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, managedIdentityTrackedResourceName string, options *commonpropsgroup.ManagedIdentityClientGetOptions) (resp azfake.Responder[commonpropsgroup.ManagedIdentityClientGetResponse], errResp azfake.ErrorResponder) + + // UpdateWithUserAssignedAndSystemAssigned is the fake for method ManagedIdentityClient.UpdateWithUserAssignedAndSystemAssigned + // HTTP status codes to indicate success: http.StatusOK + UpdateWithUserAssignedAndSystemAssigned func(ctx context.Context, resourceGroupName string, managedIdentityTrackedResourceName string, properties commonpropsgroup.ManagedIdentityTrackedResource, options *commonpropsgroup.ManagedIdentityClientUpdateWithUserAssignedAndSystemAssignedOptions) (resp azfake.Responder[commonpropsgroup.ManagedIdentityClientUpdateWithUserAssignedAndSystemAssignedResponse], errResp azfake.ErrorResponder) +} + +// NewManagedIdentityServerTransport creates a new instance of ManagedIdentityServerTransport with the provided implementation. +// The returned ManagedIdentityServerTransport instance is connected to an instance of commonpropsgroup.ManagedIdentityClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewManagedIdentityServerTransport(srv *ManagedIdentityServer) *ManagedIdentityServerTransport { + return &ManagedIdentityServerTransport{srv: srv} +} + +// ManagedIdentityServerTransport connects instances of commonpropsgroup.ManagedIdentityClient to instances of ManagedIdentityServer. +// Don't use this type directly, use NewManagedIdentityServerTransport instead. +type ManagedIdentityServerTransport struct { + srv *ManagedIdentityServer +} + +// Do implements the policy.Transporter interface for ManagedIdentityServerTransport. +func (m *ManagedIdentityServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToMethodFake(req, method) +} + +func (m *ManagedIdentityServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if managedIdentityServerTransportInterceptor != nil { + res.resp, res.err, intercepted = managedIdentityServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ManagedIdentityClient.CreateWithSystemAssigned": + res.resp, res.err = m.dispatchCreateWithSystemAssigned(req) + case "ManagedIdentityClient.Get": + res.resp, res.err = m.dispatchGet(req) + case "ManagedIdentityClient.UpdateWithUserAssignedAndSystemAssigned": + res.resp, res.err = m.dispatchUpdateWithUserAssignedAndSystemAssigned(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *ManagedIdentityServerTransport) dispatchCreateWithSystemAssigned(req *http.Request) (*http.Response, error) { + if m.srv.CreateWithSystemAssigned == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateWithSystemAssigned not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.CommonProperties/managedIdentityTrackedResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[commonpropsgroup.ManagedIdentityTrackedResource](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + managedIdentityTrackedResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managedIdentityTrackedResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.CreateWithSystemAssigned(req.Context(), resourceGroupNameParam, managedIdentityTrackedResourceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ManagedIdentityTrackedResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *ManagedIdentityServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if m.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.CommonProperties/managedIdentityTrackedResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + managedIdentityTrackedResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managedIdentityTrackedResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.Get(req.Context(), resourceGroupNameParam, managedIdentityTrackedResourceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ManagedIdentityTrackedResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *ManagedIdentityServerTransport) dispatchUpdateWithUserAssignedAndSystemAssigned(req *http.Request) (*http.Response, error) { + if m.srv.UpdateWithUserAssignedAndSystemAssigned == nil { + return nil, &nonRetriableError{errors.New("fake for method UpdateWithUserAssignedAndSystemAssigned not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.CommonProperties/managedIdentityTrackedResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[commonpropsgroup.ManagedIdentityTrackedResource](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + managedIdentityTrackedResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managedIdentityTrackedResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.UpdateWithUserAssignedAndSystemAssigned(req.Context(), resourceGroupNameParam, managedIdentityTrackedResourceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ManagedIdentityTrackedResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ManagedIdentityServerTransport +var managedIdentityServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/resource-manager/commonpropsgroup/fake/zz_server_factory.go b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/fake/zz_server_factory.go new file mode 100644 index 000000000000..3629952458e8 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/fake/zz_server_factory.go @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the commonpropsgroup.ClientFactory type. +type ServerFactory struct { + // ArmResourceIdentifiersServer contains the fakes for client ArmResourceIdentifiersClient + ArmResourceIdentifiersServer ArmResourceIdentifiersServer + + // ErrorServer contains the fakes for client ErrorClient + ErrorServer ErrorServer + + // ManagedIdentityServer contains the fakes for client ManagedIdentityClient + ManagedIdentityServer ManagedIdentityServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of commonpropsgroup.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of commonpropsgroup.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trArmResourceIdentifiersServer *ArmResourceIdentifiersServerTransport + trErrorServer *ErrorServerTransport + trManagedIdentityServer *ManagedIdentityServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "ArmResourceIdentifiersClient": + initServer(&s.trMu, &s.trArmResourceIdentifiersServer, func() *ArmResourceIdentifiersServerTransport { + return NewArmResourceIdentifiersServerTransport(&s.srv.ArmResourceIdentifiersServer) + }) + resp, err = s.trArmResourceIdentifiersServer.Do(req) + case "ErrorClient": + initServer(&s.trMu, &s.trErrorServer, func() *ErrorServerTransport { return NewErrorServerTransport(&s.srv.ErrorServer) }) + resp, err = s.trErrorServer.Do(req) + case "ManagedIdentityClient": + initServer(&s.trMu, &s.trManagedIdentityServer, func() *ManagedIdentityServerTransport { + return NewManagedIdentityServerTransport(&s.srv.ManagedIdentityServer) + }) + resp, err = s.trManagedIdentityServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/commonpropsgroup/go.mod b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/go.mod new file mode 100644 index 000000000000..45e05c4b3189 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/go.mod @@ -0,0 +1,17 @@ +module commonpropsgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/resource-manager/commonpropsgroup/go.sum b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/resource-manager/commonpropsgroup/managedidentity_client_test.go b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/managedidentity_client_test.go new file mode 100644 index 000000000000..e88739b84fa9 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/managedidentity_client_test.go @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package commonpropsgroup_test + +import ( + "commonpropsgroup" + "fmt" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +var ( + validSystemAssignedManagedIdentityResource = commonpropsgroup.ManagedIdentityTrackedResource{ + ID: to.Ptr(fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Azure.ResourceManager.CommonProperties/managedIdentityTrackedResources/identity", subscriptionIdExpected, resourceGroupExpected)), + Location: to.Ptr(locationExpected), + Tags: map[string]*string{ + "tagKey1": to.Ptr("tagValue1"), + }, + Identity: &commonpropsgroup.ManagedServiceIdentity{ + Type: to.Ptr(commonpropsgroup.ManagedServiceIdentityType(identityTypeSystemAssigendExpected)), + PrincipalID: to.Ptr(principalIdExpected), + TenantID: to.Ptr(tenantIdExpected), + }, + Properties: &commonpropsgroup.ManagedIdentityTrackedResourceProperties{ + ProvisioningState: to.Ptr("Succeeded"), + }, + } + + validUserAssignedAndSystemAssignedManagedIdentityResource = commonpropsgroup.ManagedIdentityTrackedResource{ + ID: to.Ptr(fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Azure.ResourceManager.CommonProperties/managedIdentityTrackedResources/identity", subscriptionIdExpected, resourceGroupExpected)), + Location: to.Ptr(locationExpected), + Tags: map[string]*string{ + "tagKey1": to.Ptr("tagValue1"), + }, + Identity: &commonpropsgroup.ManagedServiceIdentity{ + Type: to.Ptr(commonpropsgroup.ManagedServiceIdentityType(identityTypeSystemUserAssignedExpected)), + UserAssignedIdentities: map[string]*commonpropsgroup.UserAssignedIdentity{ + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": { + PrincipalID: to.Ptr(principalIdExpected), + ClientID: to.Ptr(clientIdExpected), + }, + }, + PrincipalID: to.Ptr(principalIdExpected), + TenantID: to.Ptr(tenantIdExpected), + }, + Properties: &commonpropsgroup.ManagedIdentityTrackedResourceProperties{ + ProvisioningState: to.Ptr("Succeeded"), + }, + } +) + +func TestManagedIdentityTrackedResourcesClient_Get(t *testing.T) { + managedIdentityTrackedResourcesClientGetResponse, err := clientFactory.NewManagedIdentityClient().Get(ctx, resourceGroupExpected, "identity", nil) + require.NoError(t, err) + require.Equal(t, *validSystemAssignedManagedIdentityResource.ID, *managedIdentityTrackedResourcesClientGetResponse.ID) + require.Equal(t, *validSystemAssignedManagedIdentityResource.Location, *managedIdentityTrackedResourcesClientGetResponse.Location) + require.Equal(t, *validSystemAssignedManagedIdentityResource.Identity.Type, *managedIdentityTrackedResourcesClientGetResponse.Identity.Type) + require.Equal(t, *validSystemAssignedManagedIdentityResource.Identity.PrincipalID, *managedIdentityTrackedResourcesClientGetResponse.Identity.PrincipalID) + require.Equal(t, *validSystemAssignedManagedIdentityResource.Identity.TenantID, *managedIdentityTrackedResourcesClientGetResponse.Identity.TenantID) + require.Equal(t, validSystemAssignedManagedIdentityResource.Tags, managedIdentityTrackedResourcesClientGetResponse.Tags) + require.Equal(t, *validSystemAssignedManagedIdentityResource.Properties.ProvisioningState, *managedIdentityTrackedResourcesClientGetResponse.Properties.ProvisioningState) +} + +func TestManagedIdentityTrackedResourcesClient_CreateWithSystemAssigned(t *testing.T) { + managedIdentityTrackedResourcesClientCreateWithSystemAssignedResponse, err := clientFactory.NewManagedIdentityClient().CreateWithSystemAssigned( + ctx, + resourceGroupExpected, + "identity", + commonpropsgroup.ManagedIdentityTrackedResource{ + Location: to.Ptr(locationExpected), + Identity: &commonpropsgroup.ManagedServiceIdentity{ + Type: to.Ptr(commonpropsgroup.ManagedServiceIdentityTypeSystemAssigned), + }, + }, + nil, + ) + require.NoError(t, err) + require.Equal(t, *validSystemAssignedManagedIdentityResource.ID, *managedIdentityTrackedResourcesClientCreateWithSystemAssignedResponse.ID) + require.Equal(t, *validSystemAssignedManagedIdentityResource.Location, *managedIdentityTrackedResourcesClientCreateWithSystemAssignedResponse.Location) + require.Equal(t, *validSystemAssignedManagedIdentityResource.Identity.Type, *managedIdentityTrackedResourcesClientCreateWithSystemAssignedResponse.Identity.Type) + require.Equal(t, *validSystemAssignedManagedIdentityResource.Identity.PrincipalID, *managedIdentityTrackedResourcesClientCreateWithSystemAssignedResponse.Identity.PrincipalID) + require.Equal(t, *validSystemAssignedManagedIdentityResource.Identity.TenantID, *managedIdentityTrackedResourcesClientCreateWithSystemAssignedResponse.Identity.TenantID) + require.Equal(t, validSystemAssignedManagedIdentityResource.Tags, managedIdentityTrackedResourcesClientCreateWithSystemAssignedResponse.Tags) + require.Equal(t, *validSystemAssignedManagedIdentityResource.Properties, *managedIdentityTrackedResourcesClientCreateWithSystemAssignedResponse.Properties) +} + +func TestManagedIdentityTrackedResourcesClient_UpdateWithUserAssignedAndSystemAssigned(t *testing.T) { + managedIdentityTrackedResourcesClientUpdateWithUserAssignedAndSystemAssignedResponse, err := clientFactory.NewManagedIdentityClient().UpdateWithUserAssignedAndSystemAssigned( + ctx, + resourceGroupExpected, + "identity", + commonpropsgroup.ManagedIdentityTrackedResource{ + Location: to.Ptr(locationExpected), + Identity: &commonpropsgroup.ManagedServiceIdentity{ + Type: to.Ptr(commonpropsgroup.ManagedServiceIdentityTypeSystemAssignedUserAssigned), + UserAssignedIdentities: map[string]*commonpropsgroup.UserAssignedIdentity{ + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id1": {}, + }, + }, + }, + nil, + ) + require.NoError(t, err) + require.Equal(t, *validUserAssignedAndSystemAssignedManagedIdentityResource.ID, *managedIdentityTrackedResourcesClientUpdateWithUserAssignedAndSystemAssignedResponse.ID) + require.Equal(t, *validUserAssignedAndSystemAssignedManagedIdentityResource.Location, *managedIdentityTrackedResourcesClientUpdateWithUserAssignedAndSystemAssignedResponse.Location) + require.Equal(t, *validUserAssignedAndSystemAssignedManagedIdentityResource.Identity, *managedIdentityTrackedResourcesClientUpdateWithUserAssignedAndSystemAssignedResponse.Identity) + require.Equal(t, validUserAssignedAndSystemAssignedManagedIdentityResource.Tags, managedIdentityTrackedResourcesClientUpdateWithUserAssignedAndSystemAssignedResponse.Tags) + require.Equal(t, *validUserAssignedAndSystemAssignedManagedIdentityResource.Properties, *managedIdentityTrackedResourcesClientUpdateWithUserAssignedAndSystemAssignedResponse.Properties) +} diff --git a/test/azure-http-specs/azure/resource-manager/commonpropsgroup/testdata/_metadata.json b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/testdata/_metadata.json new file mode 100644 index 000000000000..0f18cdea5cb8 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Azure.ResourceManager.CommonProperties": "2023-12-01-preview" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/resource-manager/commonpropsgroup/utils_test.go b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/utils_test.go new file mode 100644 index 000000000000..d3ecfd757c85 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/utils_test.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package commonpropsgroup_test + +import ( + "commonpropsgroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" +) + +var ( + ctx context.Context + clientFactory *commonpropsgroup.ClientFactory + + subscriptionIdExpected = "00000000-0000-0000-0000-000000000000" + principalIdExpected = "00000000-0000-0000-0000-000000000000" + tenantIdExpected = "00000000-0000-0000-0000-000000000000" + clientIdExpected = "00000000-0000-0000-0000-000000000000" + locationExpected = "eastus" + resourceGroupExpected = "test-rg" + identityTypeSystemAssigendExpected = "SystemAssigned" + identityTypeSystemUserAssignedExpected = "SystemAssigned,UserAssigned" +) + +func TestMain(m *testing.M) { + ctx = context.Background() + clientFactory, _ = commonpropsgroup.NewClientFactory(subscriptionIdExpected, &azfake.TokenCredential{}, &arm.ClientOptions{ + ClientOptions: azcore.ClientOptions{ + Cloud: cloud.Configuration{ + Services: map[cloud.ServiceName]cloud.ServiceConfiguration{ + cloud.ResourceManager: { + Audience: "fake_audience", + Endpoint: "http://localhost:3000", + }, + }, + }, + InsecureAllowCredentialWithHTTP: true, + }, + }) + + m.Run() +} diff --git a/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_armresourceidentifiers_client.go b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_armresourceidentifiers_client.go new file mode 100644 index 000000000000..d5f122bfdf2d --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_armresourceidentifiers_client.go @@ -0,0 +1,173 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package commonpropsgroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ArmResourceIdentifiersClient contains the methods for the ArmResourceIdentifiers group. +// Don't use this type directly, use NewArmResourceIdentifiersClient() instead. +// +// Generated from API version 2023-12-01-preview +type ArmResourceIdentifiersClient struct { + internal *arm.Client + subscriptionID string +} + +// NewArmResourceIdentifiersClient creates a new instance of ArmResourceIdentifiersClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewArmResourceIdentifiersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ArmResourceIdentifiersClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ArmResourceIdentifiersClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrReplace - Create a ArmResourceIdentifierResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - armResourceIdentifierResourceName - arm resource name for path +// - resource - Resource create parameters. +// - options - ArmResourceIdentifiersClientCreateOrReplaceOptions contains the optional parameters for the ArmResourceIdentifiersClient.CreateOrReplace +// method. +func (client *ArmResourceIdentifiersClient) CreateOrReplace(ctx context.Context, resourceGroupName string, armResourceIdentifierResourceName string, resource ArmResourceIdentifierResource, options *ArmResourceIdentifiersClientCreateOrReplaceOptions) (ArmResourceIdentifiersClientCreateOrReplaceResponse, error) { + var err error + const operationName = "ArmResourceIdentifiersClient.CreateOrReplace" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrReplaceCreateRequest(ctx, resourceGroupName, armResourceIdentifierResourceName, resource, options) + if err != nil { + return ArmResourceIdentifiersClientCreateOrReplaceResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArmResourceIdentifiersClientCreateOrReplaceResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return ArmResourceIdentifiersClientCreateOrReplaceResponse{}, err + } + resp, err := client.createOrReplaceHandleResponse(httpResp) + return resp, err +} + +// createOrReplaceCreateRequest creates the CreateOrReplace request. +func (client *ArmResourceIdentifiersClient) createOrReplaceCreateRequest(ctx context.Context, resourceGroupName string, armResourceIdentifierResourceName string, resource ArmResourceIdentifierResource, _ *ArmResourceIdentifiersClientCreateOrReplaceOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.CommonProperties/armResourceIdentifierResources/{armResourceIdentifierResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if armResourceIdentifierResourceName == "" { + return nil, errors.New("parameter armResourceIdentifierResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{armResourceIdentifierResourceName}", url.PathEscape(armResourceIdentifierResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// createOrReplaceHandleResponse handles the CreateOrReplace response. +func (client *ArmResourceIdentifiersClient) createOrReplaceHandleResponse(resp *http.Response) (ArmResourceIdentifiersClientCreateOrReplaceResponse, error) { + result := ArmResourceIdentifiersClientCreateOrReplaceResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ArmResourceIdentifierResource); err != nil { + return ArmResourceIdentifiersClientCreateOrReplaceResponse{}, err + } + return result, nil +} + +// Get - Get a ArmResourceIdentifierResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - armResourceIdentifierResourceName - arm resource name for path +// - options - ArmResourceIdentifiersClientGetOptions contains the optional parameters for the ArmResourceIdentifiersClient.Get +// method. +func (client *ArmResourceIdentifiersClient) Get(ctx context.Context, resourceGroupName string, armResourceIdentifierResourceName string, options *ArmResourceIdentifiersClientGetOptions) (ArmResourceIdentifiersClientGetResponse, error) { + var err error + const operationName = "ArmResourceIdentifiersClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, armResourceIdentifierResourceName, options) + if err != nil { + return ArmResourceIdentifiersClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArmResourceIdentifiersClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ArmResourceIdentifiersClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ArmResourceIdentifiersClient) getCreateRequest(ctx context.Context, resourceGroupName string, armResourceIdentifierResourceName string, _ *ArmResourceIdentifiersClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.CommonProperties/armResourceIdentifierResources/{armResourceIdentifierResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if armResourceIdentifierResourceName == "" { + return nil, errors.New("parameter armResourceIdentifierResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{armResourceIdentifierResourceName}", url.PathEscape(armResourceIdentifierResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ArmResourceIdentifiersClient) getHandleResponse(resp *http.Response) (ArmResourceIdentifiersClientGetResponse, error) { + result := ArmResourceIdentifiersClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ArmResourceIdentifierResource); err != nil { + return ArmResourceIdentifiersClientGetResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_client_factory.go b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_client_factory.go new file mode 100644 index 000000000000..75ee5459c27d --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_client_factory.go @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package commonpropsgroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + subscriptionID string + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, + internal: internal, + }, nil +} + +// NewArmResourceIdentifiersClient creates a new instance of ArmResourceIdentifiersClient. +func (c *ClientFactory) NewArmResourceIdentifiersClient() *ArmResourceIdentifiersClient { + return &ArmResourceIdentifiersClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewErrorClient creates a new instance of ErrorClient. +func (c *ClientFactory) NewErrorClient() *ErrorClient { + return &ErrorClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewManagedIdentityClient creates a new instance of ManagedIdentityClient. +func (c *ClientFactory) NewManagedIdentityClient() *ManagedIdentityClient { + return &ManagedIdentityClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} diff --git a/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_constants.go b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_constants.go new file mode 100644 index 000000000000..8d3a8e633d6a --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_constants.go @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package commonpropsgroup + +const ( + version20231201Preview string = "2023-12-01-preview" +) + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// ManagedServiceIdentityType - Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). +type ManagedServiceIdentityType string + +const ( + // ManagedServiceIdentityTypeNone - No managed identity. + ManagedServiceIdentityTypeNone ManagedServiceIdentityType = "None" + // ManagedServiceIdentityTypeSystemAssigned - System assigned managed identity. + ManagedServiceIdentityTypeSystemAssigned ManagedServiceIdentityType = "SystemAssigned" + // ManagedServiceIdentityTypeSystemAssignedUserAssigned - System and user assigned managed identity. + ManagedServiceIdentityTypeSystemAssignedUserAssigned ManagedServiceIdentityType = "SystemAssigned,UserAssigned" + // ManagedServiceIdentityTypeUserAssigned - User assigned managed identity. + ManagedServiceIdentityTypeUserAssigned ManagedServiceIdentityType = "UserAssigned" +) + +// PossibleManagedServiceIdentityTypeValues returns the possible values for the ManagedServiceIdentityType const type. +func PossibleManagedServiceIdentityTypeValues() []ManagedServiceIdentityType { + return []ManagedServiceIdentityType{ + ManagedServiceIdentityTypeNone, + ManagedServiceIdentityTypeSystemAssigned, + ManagedServiceIdentityTypeSystemAssignedUserAssigned, + ManagedServiceIdentityTypeUserAssigned, + } +} + +// ResourceProvisioningState - The provisioning state of a resource type. +type ResourceProvisioningState string + +const ( + // ResourceProvisioningStateCanceled - Resource creation was canceled. + ResourceProvisioningStateCanceled ResourceProvisioningState = "Canceled" + // ResourceProvisioningStateFailed - Resource creation failed. + ResourceProvisioningStateFailed ResourceProvisioningState = "Failed" + // ResourceProvisioningStateSucceeded - Resource has been created. + ResourceProvisioningStateSucceeded ResourceProvisioningState = "Succeeded" +) + +// PossibleResourceProvisioningStateValues returns the possible values for the ResourceProvisioningState const type. +func PossibleResourceProvisioningStateValues() []ResourceProvisioningState { + return []ResourceProvisioningState{ + ResourceProvisioningStateCanceled, + ResourceProvisioningStateFailed, + ResourceProvisioningStateSucceeded, + } +} diff --git a/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_error_client.go b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_error_client.go new file mode 100644 index 000000000000..b27c4b4816b8 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_error_client.go @@ -0,0 +1,173 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package commonpropsgroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ErrorClient contains the methods for the Error group. +// Don't use this type directly, use NewErrorClient() instead. +// +// Generated from API version 2023-12-01-preview +type ErrorClient struct { + internal *arm.Client + subscriptionID string +} + +// NewErrorClient creates a new instance of ErrorClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewErrorClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ErrorClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ErrorClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateForUserDefinedError - Create a ConfidentialResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - confidentialResourceName - The name of the ConfidentialResource +// - resource - Resource create parameters. +// - options - ErrorClientCreateForUserDefinedErrorOptions contains the optional parameters for the ErrorClient.CreateForUserDefinedError +// method. +func (client *ErrorClient) CreateForUserDefinedError(ctx context.Context, resourceGroupName string, confidentialResourceName string, resource ConfidentialResource, options *ErrorClientCreateForUserDefinedErrorOptions) (ErrorClientCreateForUserDefinedErrorResponse, error) { + var err error + const operationName = "ErrorClient.CreateForUserDefinedError" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createForUserDefinedErrorCreateRequest(ctx, resourceGroupName, confidentialResourceName, resource, options) + if err != nil { + return ErrorClientCreateForUserDefinedErrorResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ErrorClientCreateForUserDefinedErrorResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return ErrorClientCreateForUserDefinedErrorResponse{}, err + } + resp, err := client.createForUserDefinedErrorHandleResponse(httpResp) + return resp, err +} + +// createForUserDefinedErrorCreateRequest creates the CreateForUserDefinedError request. +func (client *ErrorClient) createForUserDefinedErrorCreateRequest(ctx context.Context, resourceGroupName string, confidentialResourceName string, resource ConfidentialResource, _ *ErrorClientCreateForUserDefinedErrorOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.CommonProperties/confidentialResources/{confidentialResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if confidentialResourceName == "" { + return nil, errors.New("parameter confidentialResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{confidentialResourceName}", url.PathEscape(confidentialResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// createForUserDefinedErrorHandleResponse handles the CreateForUserDefinedError response. +func (client *ErrorClient) createForUserDefinedErrorHandleResponse(resp *http.Response) (ErrorClientCreateForUserDefinedErrorResponse, error) { + result := ErrorClientCreateForUserDefinedErrorResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ConfidentialResource); err != nil { + return ErrorClientCreateForUserDefinedErrorResponse{}, err + } + return result, nil +} + +// GetForPredefinedError - Get a ConfidentialResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - confidentialResourceName - The name of the ConfidentialResource +// - options - ErrorClientGetForPredefinedErrorOptions contains the optional parameters for the ErrorClient.GetForPredefinedError +// method. +func (client *ErrorClient) GetForPredefinedError(ctx context.Context, resourceGroupName string, confidentialResourceName string, options *ErrorClientGetForPredefinedErrorOptions) (ErrorClientGetForPredefinedErrorResponse, error) { + var err error + const operationName = "ErrorClient.GetForPredefinedError" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getForPredefinedErrorCreateRequest(ctx, resourceGroupName, confidentialResourceName, options) + if err != nil { + return ErrorClientGetForPredefinedErrorResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ErrorClientGetForPredefinedErrorResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ErrorClientGetForPredefinedErrorResponse{}, err + } + resp, err := client.getForPredefinedErrorHandleResponse(httpResp) + return resp, err +} + +// getForPredefinedErrorCreateRequest creates the GetForPredefinedError request. +func (client *ErrorClient) getForPredefinedErrorCreateRequest(ctx context.Context, resourceGroupName string, confidentialResourceName string, _ *ErrorClientGetForPredefinedErrorOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.CommonProperties/confidentialResources/{confidentialResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if confidentialResourceName == "" { + return nil, errors.New("parameter confidentialResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{confidentialResourceName}", url.PathEscape(confidentialResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getForPredefinedErrorHandleResponse handles the GetForPredefinedError response. +func (client *ErrorClient) getForPredefinedErrorHandleResponse(resp *http.Response) (ErrorClientGetForPredefinedErrorResponse, error) { + result := ErrorClientGetForPredefinedErrorResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ConfidentialResource); err != nil { + return ErrorClientGetForPredefinedErrorResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_managedidentity_client.go b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_managedidentity_client.go new file mode 100644 index 000000000000..368030cda12f --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_managedidentity_client.go @@ -0,0 +1,240 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package commonpropsgroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ManagedIdentityClient contains the methods for the ManagedIdentity group. +// Don't use this type directly, use NewManagedIdentityClient() instead. +// +// Generated from API version 2023-12-01-preview +type ManagedIdentityClient struct { + internal *arm.Client + subscriptionID string +} + +// NewManagedIdentityClient creates a new instance of ManagedIdentityClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewManagedIdentityClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ManagedIdentityClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ManagedIdentityClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateWithSystemAssigned - Create a ManagedIdentityTrackedResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - managedIdentityTrackedResourceName - arm resource name for path +// - resource - Resource create parameters. +// - options - ManagedIdentityClientCreateWithSystemAssignedOptions contains the optional parameters for the ManagedIdentityClient.CreateWithSystemAssigned +// method. +func (client *ManagedIdentityClient) CreateWithSystemAssigned(ctx context.Context, resourceGroupName string, managedIdentityTrackedResourceName string, resource ManagedIdentityTrackedResource, options *ManagedIdentityClientCreateWithSystemAssignedOptions) (ManagedIdentityClientCreateWithSystemAssignedResponse, error) { + var err error + const operationName = "ManagedIdentityClient.CreateWithSystemAssigned" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createWithSystemAssignedCreateRequest(ctx, resourceGroupName, managedIdentityTrackedResourceName, resource, options) + if err != nil { + return ManagedIdentityClientCreateWithSystemAssignedResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagedIdentityClientCreateWithSystemAssignedResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return ManagedIdentityClientCreateWithSystemAssignedResponse{}, err + } + resp, err := client.createWithSystemAssignedHandleResponse(httpResp) + return resp, err +} + +// createWithSystemAssignedCreateRequest creates the CreateWithSystemAssigned request. +func (client *ManagedIdentityClient) createWithSystemAssignedCreateRequest(ctx context.Context, resourceGroupName string, managedIdentityTrackedResourceName string, resource ManagedIdentityTrackedResource, _ *ManagedIdentityClientCreateWithSystemAssignedOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.CommonProperties/managedIdentityTrackedResources/{managedIdentityTrackedResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if managedIdentityTrackedResourceName == "" { + return nil, errors.New("parameter managedIdentityTrackedResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{managedIdentityTrackedResourceName}", url.PathEscape(managedIdentityTrackedResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// createWithSystemAssignedHandleResponse handles the CreateWithSystemAssigned response. +func (client *ManagedIdentityClient) createWithSystemAssignedHandleResponse(resp *http.Response) (ManagedIdentityClientCreateWithSystemAssignedResponse, error) { + result := ManagedIdentityClientCreateWithSystemAssignedResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagedIdentityTrackedResource); err != nil { + return ManagedIdentityClientCreateWithSystemAssignedResponse{}, err + } + return result, nil +} + +// Get - Get a ManagedIdentityTrackedResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - managedIdentityTrackedResourceName - arm resource name for path +// - options - ManagedIdentityClientGetOptions contains the optional parameters for the ManagedIdentityClient.Get method. +func (client *ManagedIdentityClient) Get(ctx context.Context, resourceGroupName string, managedIdentityTrackedResourceName string, options *ManagedIdentityClientGetOptions) (ManagedIdentityClientGetResponse, error) { + var err error + const operationName = "ManagedIdentityClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, managedIdentityTrackedResourceName, options) + if err != nil { + return ManagedIdentityClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagedIdentityClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ManagedIdentityClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ManagedIdentityClient) getCreateRequest(ctx context.Context, resourceGroupName string, managedIdentityTrackedResourceName string, _ *ManagedIdentityClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.CommonProperties/managedIdentityTrackedResources/{managedIdentityTrackedResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if managedIdentityTrackedResourceName == "" { + return nil, errors.New("parameter managedIdentityTrackedResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{managedIdentityTrackedResourceName}", url.PathEscape(managedIdentityTrackedResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ManagedIdentityClient) getHandleResponse(resp *http.Response) (ManagedIdentityClientGetResponse, error) { + result := ManagedIdentityClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagedIdentityTrackedResource); err != nil { + return ManagedIdentityClientGetResponse{}, err + } + return result, nil +} + +// UpdateWithUserAssignedAndSystemAssigned - Update a ManagedIdentityTrackedResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - managedIdentityTrackedResourceName - arm resource name for path +// - properties - The resource properties to be updated. +// - options - ManagedIdentityClientUpdateWithUserAssignedAndSystemAssignedOptions contains the optional parameters for the +// ManagedIdentityClient.UpdateWithUserAssignedAndSystemAssigned method. +func (client *ManagedIdentityClient) UpdateWithUserAssignedAndSystemAssigned(ctx context.Context, resourceGroupName string, managedIdentityTrackedResourceName string, properties ManagedIdentityTrackedResource, options *ManagedIdentityClientUpdateWithUserAssignedAndSystemAssignedOptions) (ManagedIdentityClientUpdateWithUserAssignedAndSystemAssignedResponse, error) { + var err error + const operationName = "ManagedIdentityClient.UpdateWithUserAssignedAndSystemAssigned" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateWithUserAssignedAndSystemAssignedCreateRequest(ctx, resourceGroupName, managedIdentityTrackedResourceName, properties, options) + if err != nil { + return ManagedIdentityClientUpdateWithUserAssignedAndSystemAssignedResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagedIdentityClientUpdateWithUserAssignedAndSystemAssignedResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ManagedIdentityClientUpdateWithUserAssignedAndSystemAssignedResponse{}, err + } + resp, err := client.updateWithUserAssignedAndSystemAssignedHandleResponse(httpResp) + return resp, err +} + +// updateWithUserAssignedAndSystemAssignedCreateRequest creates the UpdateWithUserAssignedAndSystemAssigned request. +func (client *ManagedIdentityClient) updateWithUserAssignedAndSystemAssignedCreateRequest(ctx context.Context, resourceGroupName string, managedIdentityTrackedResourceName string, properties ManagedIdentityTrackedResource, _ *ManagedIdentityClientUpdateWithUserAssignedAndSystemAssignedOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.CommonProperties/managedIdentityTrackedResources/{managedIdentityTrackedResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if managedIdentityTrackedResourceName == "" { + return nil, errors.New("parameter managedIdentityTrackedResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{managedIdentityTrackedResourceName}", url.PathEscape(managedIdentityTrackedResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} + +// updateWithUserAssignedAndSystemAssignedHandleResponse handles the UpdateWithUserAssignedAndSystemAssigned response. +func (client *ManagedIdentityClient) updateWithUserAssignedAndSystemAssignedHandleResponse(resp *http.Response) (ManagedIdentityClientUpdateWithUserAssignedAndSystemAssignedResponse, error) { + result := ManagedIdentityClientUpdateWithUserAssignedAndSystemAssignedResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagedIdentityTrackedResource); err != nil { + return ManagedIdentityClientUpdateWithUserAssignedAndSystemAssignedResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_models.go b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_models.go new file mode 100644 index 000000000000..218c4242cdbf --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_models.go @@ -0,0 +1,163 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package commonpropsgroup + +import "time" + +// ArmResourceIdentifierResource - Concrete tracked resource types can be created by aliasing this type using a specific property +// type. +type ArmResourceIdentifierResource struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *ArmResourceIdentifierResourceProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ArmResourceIdentifierResourceProperties - ArmResourceIdentifier Resource Properties. +type ArmResourceIdentifierResourceProperties struct { + // REQUIRED; An ARM resource identifier with all scopes. + ArmIDWithAllScopes *string + + // REQUIRED; An ARM resource identifier with type only. + ArmIDWithType *string + + // REQUIRED; An ARM resource identifier with type and scopes. + ArmIDWithTypeAndScope *string + + // REQUIRED; A basic ARM resource identifier without type or scopes. + SimpleArmID *string + + // READ-ONLY; The status of the last operation. + ProvisioningState *ResourceProvisioningState +} + +// ConfidentialResource - Concrete tracked resource types can be created by aliasing this type using a specific property type. +type ConfidentialResource struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *ConfidentialResourceProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ConfidentialResourceProperties - Confidential Resource Properties. +type ConfidentialResourceProperties struct { + // REQUIRED + Username *string + + // READ-ONLY; The status of the last operation. + ProvisioningState *string +} + +// ManagedIdentityTrackedResource - Concrete tracked resource types can be created by aliasing this type using a specific +// property type. +type ManagedIdentityTrackedResource struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The managed service identities assigned to this resource. + Identity *ManagedServiceIdentity + + // The resource-specific properties for this resource. + Properties *ManagedIdentityTrackedResourceProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ManagedIdentityTrackedResourceProperties - Managed Identity Arm Resource Properties. +type ManagedIdentityTrackedResourceProperties struct { + // READ-ONLY; The status of the last operation. + ProvisioningState *string +} + +// ManagedServiceIdentity - Managed service identity (system assigned and/or user assigned identities) +type ManagedServiceIdentity struct { + // REQUIRED; The type of managed identity assigned to this resource. + Type *ManagedServiceIdentityType + + // The identities assigned to this resource by the user. + UserAssignedIdentities map[string]*UserAssignedIdentity + + // READ-ONLY; The service principal ID of the system assigned identity. This property will only be provided for a system assigned + // identity. + PrincipalID *string + + // READ-ONLY; The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + TenantID *string +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time + + // The identity that created the resource. + CreatedBy *string + + // The type of identity that created the resource. + CreatedByType *CreatedByType + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time + + // The identity that last modified the resource. + LastModifiedBy *string + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType +} + +// UserAssignedIdentity - User assigned identity properties +type UserAssignedIdentity struct { + // READ-ONLY; The client ID of the assigned identity. + ClientID *string + + // READ-ONLY; The principal ID of the assigned identity. + PrincipalID *string +} diff --git a/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_models_serde.go b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_models_serde.go new file mode 100644 index 000000000000..ab1e4cb2b68b --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_models_serde.go @@ -0,0 +1,437 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package commonpropsgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type ArmResourceIdentifierResource. +func (a ArmResourceIdentifierResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "location", a.Location) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "tags", a.Tags) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ArmResourceIdentifierResource. +func (a *ArmResourceIdentifierResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &a.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &a.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &a.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ArmResourceIdentifierResourceProperties. +func (a ArmResourceIdentifierResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "armIdWithAllScopes", a.ArmIDWithAllScopes) + populate(objectMap, "armIdWithType", a.ArmIDWithType) + populate(objectMap, "armIdWithTypeAndScope", a.ArmIDWithTypeAndScope) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "simpleArmId", a.SimpleArmID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ArmResourceIdentifierResourceProperties. +func (a *ArmResourceIdentifierResourceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "armIdWithAllScopes": + err = unpopulate(val, "ArmIDWithAllScopes", &a.ArmIDWithAllScopes) + delete(rawMsg, key) + case "armIdWithType": + err = unpopulate(val, "ArmIDWithType", &a.ArmIDWithType) + delete(rawMsg, key) + case "armIdWithTypeAndScope": + err = unpopulate(val, "ArmIDWithTypeAndScope", &a.ArmIDWithTypeAndScope) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "simpleArmId": + err = unpopulate(val, "SimpleArmID", &a.SimpleArmID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConfidentialResource. +func (c ConfidentialResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", c.ID) + populate(objectMap, "location", c.Location) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "systemData", c.SystemData) + populate(objectMap, "tags", c.Tags) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConfidentialResource. +func (c *ConfidentialResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &c.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &c.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &c.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConfidentialResourceProperties. +func (c ConfidentialResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", c.ProvisioningState) + populate(objectMap, "username", c.Username) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConfidentialResourceProperties. +func (c *ConfidentialResourceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &c.ProvisioningState) + delete(rawMsg, key) + case "username": + err = unpopulate(val, "Username", &c.Username) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedIdentityTrackedResource. +func (m ManagedIdentityTrackedResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", m.ID) + populate(objectMap, "identity", m.Identity) + populate(objectMap, "location", m.Location) + populate(objectMap, "name", m.Name) + populate(objectMap, "properties", m.Properties) + populate(objectMap, "systemData", m.SystemData) + populate(objectMap, "tags", m.Tags) + populate(objectMap, "type", m.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedIdentityTrackedResource. +func (m *ManagedIdentityTrackedResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &m.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &m.Identity) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &m.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &m.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &m.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &m.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &m.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedIdentityTrackedResourceProperties. +func (m ManagedIdentityTrackedResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", m.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedIdentityTrackedResourceProperties. +func (m *ManagedIdentityTrackedResourceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &m.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedServiceIdentity. +func (m ManagedServiceIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "principalId", m.PrincipalID) + populate(objectMap, "tenantId", m.TenantID) + populate(objectMap, "type", m.Type) + populate(objectMap, "userAssignedIdentities", m.UserAssignedIdentities) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedServiceIdentity. +func (m *ManagedServiceIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "principalId": + err = unpopulate(val, "PrincipalID", &m.PrincipalID) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &m.TenantID) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + case "userAssignedIdentities": + err = unpopulate(val, "UserAssignedIdentities", &m.UserAssignedIdentities) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateTime[datetime.RFC3339](objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateTime[datetime.RFC3339](val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateTime[datetime.RFC3339](val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserAssignedIdentity. +func (u UserAssignedIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clientId", u.ClientID) + populate(objectMap, "principalId", u.PrincipalID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserAssignedIdentity. +func (u *UserAssignedIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "clientId": + err = unpopulate(val, "ClientID", &u.ClientID) + delete(rawMsg, key) + case "principalId": + err = unpopulate(val, "PrincipalID", &u.PrincipalID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_options.go b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_options.go new file mode 100644 index 000000000000..92dca07030d3 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_options.go @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package commonpropsgroup + +// ArmResourceIdentifiersClientCreateOrReplaceOptions contains the optional parameters for the ArmResourceIdentifiersClient.CreateOrReplace +// method. +type ArmResourceIdentifiersClientCreateOrReplaceOptions struct { + // placeholder for future optional parameters +} + +// ArmResourceIdentifiersClientGetOptions contains the optional parameters for the ArmResourceIdentifiersClient.Get method. +type ArmResourceIdentifiersClientGetOptions struct { + // placeholder for future optional parameters +} + +// ErrorClientCreateForUserDefinedErrorOptions contains the optional parameters for the ErrorClient.CreateForUserDefinedError +// method. +type ErrorClientCreateForUserDefinedErrorOptions struct { + // placeholder for future optional parameters +} + +// ErrorClientGetForPredefinedErrorOptions contains the optional parameters for the ErrorClient.GetForPredefinedError method. +type ErrorClientGetForPredefinedErrorOptions struct { + // placeholder for future optional parameters +} + +// ManagedIdentityClientCreateWithSystemAssignedOptions contains the optional parameters for the ManagedIdentityClient.CreateWithSystemAssigned +// method. +type ManagedIdentityClientCreateWithSystemAssignedOptions struct { + // placeholder for future optional parameters +} + +// ManagedIdentityClientGetOptions contains the optional parameters for the ManagedIdentityClient.Get method. +type ManagedIdentityClientGetOptions struct { + // placeholder for future optional parameters +} + +// ManagedIdentityClientUpdateWithUserAssignedAndSystemAssignedOptions contains the optional parameters for the ManagedIdentityClient.UpdateWithUserAssignedAndSystemAssigned +// method. +type ManagedIdentityClientUpdateWithUserAssignedAndSystemAssignedOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_responses.go b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_responses.go new file mode 100644 index 000000000000..71cffe81e5ba --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_responses.go @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package commonpropsgroup + +// ArmResourceIdentifiersClientCreateOrReplaceResponse contains the response from method ArmResourceIdentifiersClient.CreateOrReplace. +type ArmResourceIdentifiersClientCreateOrReplaceResponse struct { + // Concrete tracked resource types can be created by aliasing this type using a specific property type. + ArmResourceIdentifierResource +} + +// ArmResourceIdentifiersClientGetResponse contains the response from method ArmResourceIdentifiersClient.Get. +type ArmResourceIdentifiersClientGetResponse struct { + // Concrete tracked resource types can be created by aliasing this type using a specific property type. + ArmResourceIdentifierResource +} + +// ErrorClientCreateForUserDefinedErrorResponse contains the response from method ErrorClient.CreateForUserDefinedError. +type ErrorClientCreateForUserDefinedErrorResponse struct { + // Concrete tracked resource types can be created by aliasing this type using a specific property type. + ConfidentialResource +} + +// ErrorClientGetForPredefinedErrorResponse contains the response from method ErrorClient.GetForPredefinedError. +type ErrorClientGetForPredefinedErrorResponse struct { + // Concrete tracked resource types can be created by aliasing this type using a specific property type. + ConfidentialResource +} + +// ManagedIdentityClientCreateWithSystemAssignedResponse contains the response from method ManagedIdentityClient.CreateWithSystemAssigned. +type ManagedIdentityClientCreateWithSystemAssignedResponse struct { + // Concrete tracked resource types can be created by aliasing this type using a specific property type. + ManagedIdentityTrackedResource +} + +// ManagedIdentityClientGetResponse contains the response from method ManagedIdentityClient.Get. +type ManagedIdentityClientGetResponse struct { + // Concrete tracked resource types can be created by aliasing this type using a specific property type. + ManagedIdentityTrackedResource +} + +// ManagedIdentityClientUpdateWithUserAssignedAndSystemAssignedResponse contains the response from method ManagedIdentityClient.UpdateWithUserAssignedAndSystemAssigned. +type ManagedIdentityClientUpdateWithUserAssignedAndSystemAssignedResponse struct { + // Concrete tracked resource types can be created by aliasing this type using a specific property type. + ManagedIdentityTrackedResource +} diff --git a/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_version.go b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_version.go new file mode 100644 index 000000000000..29bef9b03945 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/commonpropsgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package commonpropsgroup + +const ( + moduleName = "commonpropsgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/resource-manager/largeheadergroup/LICENSE.txt b/test/azure-http-specs/azure/resource-manager/largeheadergroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/largeheadergroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/resource-manager/largeheadergroup/fake/zz_internal.go b/test/azure-http-specs/azure/resource-manager/largeheadergroup/fake/zz_internal.go new file mode 100644 index 000000000000..590b4d743e97 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/largeheadergroup/fake/zz_internal.go @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/azure-http-specs/azure/resource-manager/largeheadergroup/fake/zz_largeheaders_server.go b/test/azure-http-specs/azure/resource-manager/largeheadergroup/fake/zz_largeheaders_server.go new file mode 100644 index 000000000000..241858b6de87 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/largeheadergroup/fake/zz_largeheaders_server.go @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "largeheadergroup" + "net/http" + "net/url" + "regexp" + "slices" +) + +// LargeHeadersServer is a fake server for instances of the largeheadergroup.LargeHeadersClient type. +type LargeHeadersServer struct { + // BeginTwo6K is the fake for method LargeHeadersClient.BeginTwo6K + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginTwo6K func(ctx context.Context, resourceGroupName string, largeHeaderName string, options *largeheadergroup.LargeHeadersClientBeginTwo6KOptions) (resp azfake.PollerResponder[largeheadergroup.LargeHeadersClientTwo6KResponse], errResp azfake.ErrorResponder) +} + +// NewLargeHeadersServerTransport creates a new instance of LargeHeadersServerTransport with the provided implementation. +// The returned LargeHeadersServerTransport instance is connected to an instance of largeheadergroup.LargeHeadersClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewLargeHeadersServerTransport(srv *LargeHeadersServer) *LargeHeadersServerTransport { + return &LargeHeadersServerTransport{ + srv: srv, + beginTwo6K: newTracker[azfake.PollerResponder[largeheadergroup.LargeHeadersClientTwo6KResponse]](), + } +} + +// LargeHeadersServerTransport connects instances of largeheadergroup.LargeHeadersClient to instances of LargeHeadersServer. +// Don't use this type directly, use NewLargeHeadersServerTransport instead. +type LargeHeadersServerTransport struct { + srv *LargeHeadersServer + beginTwo6K *tracker[azfake.PollerResponder[largeheadergroup.LargeHeadersClientTwo6KResponse]] +} + +// Do implements the policy.Transporter interface for LargeHeadersServerTransport. +func (l *LargeHeadersServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return l.dispatchToMethodFake(req, method) +} + +func (l *LargeHeadersServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if largeHeadersServerTransportInterceptor != nil { + res.resp, res.err, intercepted = largeHeadersServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "LargeHeadersClient.BeginTwo6K": + res.resp, res.err = l.dispatchBeginTwo6K(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (l *LargeHeadersServerTransport) dispatchBeginTwo6K(req *http.Request) (*http.Response, error) { + if l.srv.BeginTwo6K == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginTwo6K not implemented")} + } + beginTwo6K := l.beginTwo6K.get(req) + if beginTwo6K == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.LargeHeader/largeHeaders/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/two6k` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + largeHeaderNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("largeHeaderName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.BeginTwo6K(req.Context(), resourceGroupNameParam, largeHeaderNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginTwo6K = &respr + l.beginTwo6K.add(req, beginTwo6K) + } + + resp, err := server.PollerResponderNext(beginTwo6K, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + l.beginTwo6K.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginTwo6K) { + l.beginTwo6K.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to LargeHeadersServerTransport +var largeHeadersServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/resource-manager/largeheadergroup/fake/zz_server_factory.go b/test/azure-http-specs/azure/resource-manager/largeheadergroup/fake/zz_server_factory.go new file mode 100644 index 000000000000..9c97fe84f337 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/largeheadergroup/fake/zz_server_factory.go @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the largeheadergroup.ClientFactory type. +type ServerFactory struct { + // LargeHeadersServer contains the fakes for client LargeHeadersClient + LargeHeadersServer LargeHeadersServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of largeheadergroup.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of largeheadergroup.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trLargeHeadersServer *LargeHeadersServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "LargeHeadersClient": + initServer(&s.trMu, &s.trLargeHeadersServer, func() *LargeHeadersServerTransport { return NewLargeHeadersServerTransport(&s.srv.LargeHeadersServer) }) + resp, err = s.trLargeHeadersServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/largeheadergroup/go.mod b/test/azure-http-specs/azure/resource-manager/largeheadergroup/go.mod new file mode 100644 index 000000000000..790c51f617b8 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/largeheadergroup/go.mod @@ -0,0 +1,17 @@ +module largeheadergroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/resource-manager/largeheadergroup/go.sum b/test/azure-http-specs/azure/resource-manager/largeheadergroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/largeheadergroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/resource-manager/largeheadergroup/largeheaders_client_test.go b/test/azure-http-specs/azure/resource-manager/largeheadergroup/largeheaders_client_test.go new file mode 100644 index 000000000000..bd7da7553538 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/largeheadergroup/largeheaders_client_test.go @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package largeheadergroup_test + +import ( + "context" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/stretchr/testify/require" +) + +func TestNewLargeHeadersClient_BeginTwo6K(t *testing.T) { + client := clientFactory.NewLargeHeadersClient() + poller, err := client.BeginTwo6K(context.Background(), resourceGroupExpected, "header1", nil) + require.NoError(t, err) + require.NotNil(t, poller) + resp, err := poller.PollUntilDone(context.Background(), &runtime.PollUntilDoneOptions{Frequency: time.Second}) + require.NoError(t, err) + require.NotNil(t, resp) + require.NotNil(t, resp.Succeeded) + require.True(t, *resp.Succeeded) +} diff --git a/test/azure-http-specs/azure/resource-manager/largeheadergroup/testdata/_metadata.json b/test/azure-http-specs/azure/resource-manager/largeheadergroup/testdata/_metadata.json new file mode 100644 index 000000000000..10beb095fc9a --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/largeheadergroup/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Azure.ResourceManager.LargeHeader": "2023-12-01-preview" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/resource-manager/largeheadergroup/utils_test.go b/test/azure-http-specs/azure/resource-manager/largeheadergroup/utils_test.go new file mode 100644 index 000000000000..ec0fb930ea6f --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/largeheadergroup/utils_test.go @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package largeheadergroup_test + +import ( + "context" + "largeheadergroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" +) + +var ( + ctx context.Context + clientFactory *largeheadergroup.ClientFactory + + subscriptionIdExpected = "00000000-0000-0000-0000-000000000000" + resourceGroupExpected = "test-rg" +) + +func TestMain(m *testing.M) { + ctx = context.Background() + clientFactory, _ = largeheadergroup.NewClientFactory(subscriptionIdExpected, &azfake.TokenCredential{}, &arm.ClientOptions{ + ClientOptions: azcore.ClientOptions{ + Cloud: cloud.Configuration{ + Services: map[cloud.ServiceName]cloud.ServiceConfiguration{ + cloud.ResourceManager: { + Audience: "fake_audience", + Endpoint: "http://localhost:3000", + }, + }, + }, + InsecureAllowCredentialWithHTTP: true, + }, + }) + + m.Run() +} diff --git a/test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_client_factory.go b/test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_client_factory.go new file mode 100644 index 000000000000..046e27f82ba2 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_client_factory.go @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package largeheadergroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + subscriptionID string + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, + internal: internal, + }, nil +} + +// NewLargeHeadersClient creates a new instance of LargeHeadersClient. +func (c *ClientFactory) NewLargeHeadersClient() *LargeHeadersClient { + return &LargeHeadersClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} diff --git a/test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_constants.go b/test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_constants.go new file mode 100644 index 000000000000..8dae2bc107c1 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_constants.go @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package largeheadergroup + +const ( + version20231201Preview string = "2023-12-01-preview" +) diff --git a/test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_largeheaders_client.go b/test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_largeheaders_client.go new file mode 100644 index 000000000000..fe14c921eb11 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_largeheaders_client.go @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package largeheadergroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// LargeHeadersClient contains the methods for the LargeHeaders group. +// Don't use this type directly, use NewLargeHeadersClient() instead. +// +// Generated from API version 2023-12-01-preview +type LargeHeadersClient struct { + internal *arm.Client + subscriptionID string +} + +// NewLargeHeadersClient creates a new instance of LargeHeadersClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewLargeHeadersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*LargeHeadersClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &LargeHeadersClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginTwo6K - A long-running resource action. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - largeHeaderName - The name of the LargeHeader +// - options - LargeHeadersClientBeginTwo6KOptions contains the optional parameters for the LargeHeadersClient.BeginTwo6K method. +func (client *LargeHeadersClient) BeginTwo6K(ctx context.Context, resourceGroupName string, largeHeaderName string, options *LargeHeadersClientBeginTwo6KOptions) (*runtime.Poller[LargeHeadersClientTwo6KResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.two6K(ctx, resourceGroupName, largeHeaderName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[LargeHeadersClientTwo6KResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[LargeHeadersClientTwo6KResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Two6K - A long-running resource action. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *LargeHeadersClient) two6K(ctx context.Context, resourceGroupName string, largeHeaderName string, options *LargeHeadersClientBeginTwo6KOptions) (*http.Response, error) { + var err error + const operationName = "LargeHeadersClient.BeginTwo6K" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.two6KCreateRequest(ctx, resourceGroupName, largeHeaderName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// two6KCreateRequest creates the Two6K request. +func (client *LargeHeadersClient) two6KCreateRequest(ctx context.Context, resourceGroupName string, largeHeaderName string, _ *LargeHeadersClientBeginTwo6KOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.LargeHeader/largeHeaders/{largeHeaderName}/two6k" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if largeHeaderName == "" { + return nil, errors.New("parameter largeHeaderName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{largeHeaderName}", url.PathEscape(largeHeaderName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_models.go b/test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_models.go new file mode 100644 index 000000000000..3132aa11661d --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_models.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package largeheadergroup + +type CancelResult struct { + // REQUIRED + Succeeded *bool +} diff --git a/test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_models_serde.go b/test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_models_serde.go new file mode 100644 index 000000000000..26d142ffdc03 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_models_serde.go @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package largeheadergroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type CancelResult. +func (c CancelResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "succeeded", c.Succeeded) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CancelResult. +func (c *CancelResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "succeeded": + err = unpopulate(val, "Succeeded", &c.Succeeded) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_options.go b/test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_options.go new file mode 100644 index 000000000000..2a36232c1256 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_options.go @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package largeheadergroup + +// LargeHeadersClientBeginTwo6KOptions contains the optional parameters for the LargeHeadersClient.BeginTwo6K method. +type LargeHeadersClientBeginTwo6KOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} diff --git a/test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_responses.go b/test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_responses.go new file mode 100644 index 000000000000..d1d17359f03e --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_responses.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package largeheadergroup + +// LargeHeadersClientTwo6KResponse contains the response from method LargeHeadersClient.BeginTwo6K. +type LargeHeadersClientTwo6KResponse struct { + CancelResult +} diff --git a/test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_version.go b/test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_version.go new file mode 100644 index 000000000000..9fbf1b9938c3 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/largeheadergroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package largeheadergroup + +const ( + moduleName = "largeheadergroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/LICENSE.txt b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_internal.go b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_internal.go new file mode 100644 index 000000000000..590b4d743e97 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_internal.go @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_operations_server.go b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_operations_server.go new file mode 100644 index 000000000000..3b6e530296e1 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_operations_server.go @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "methodsubscriptionidgroup" + "net/http" + "slices" +) + +// OperationsServer is a fake server for instances of the methodsubscriptionidgroup.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *methodsubscriptionidgroup.OperationsClientListOptions) (resp azfake.PagerResponder[methodsubscriptionidgroup.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of methodsubscriptionidgroup.OperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOperationsServerTransport(srv *OperationsServer) *OperationsServerTransport { + return &OperationsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[methodsubscriptionidgroup.OperationsClientListResponse]](), + } +} + +// OperationsServerTransport connects instances of methodsubscriptionidgroup.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[methodsubscriptionidgroup.OperationsClientListResponse]] +} + +// Do implements the policy.Transporter interface for OperationsServerTransport. +func (o *OperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if operationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = operationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OperationsClient.NewListPager": + res.resp, res.err = o.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OperationsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := o.newListPager.get(req) + if newListPager == nil { + resp := o.srv.NewListPager(nil) + newListPager = &resp + o.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *methodsubscriptionidgroup.OperationsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + o.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + o.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OperationsServerTransport +var operationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_resourcegroupresourceoperations_server.go b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_resourcegroupresourceoperations_server.go new file mode 100644 index 000000000000..623bd55ae847 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_resourcegroupresourceoperations_server.go @@ -0,0 +1,199 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "methodsubscriptionidgroup" + "net/http" + "net/url" + "regexp" + "slices" +) + +// ResourceGroupResourceOperationsServer is a fake server for instances of the methodsubscriptionidgroup.ResourceGroupResourceOperationsClient type. +type ResourceGroupResourceOperationsServer struct { + // Delete is the fake for method ResourceGroupResourceOperationsClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceGroupName string, resourceGroupResourceName string, options *methodsubscriptionidgroup.ResourceGroupResourceOperationsClientDeleteOptions) (resp azfake.Responder[methodsubscriptionidgroup.ResourceGroupResourceOperationsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method ResourceGroupResourceOperationsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, resourceGroupResourceName string, options *methodsubscriptionidgroup.ResourceGroupResourceOperationsClientGetOptions) (resp azfake.Responder[methodsubscriptionidgroup.ResourceGroupResourceOperationsClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ResourceGroupResourceOperationsClient.Put + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + Put func(ctx context.Context, resourceGroupName string, resourceGroupResourceName string, resource methodsubscriptionidgroup.ResourceGroupResource, options *methodsubscriptionidgroup.ResourceGroupResourceOperationsClientPutOptions) (resp azfake.Responder[methodsubscriptionidgroup.ResourceGroupResourceOperationsClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewResourceGroupResourceOperationsServerTransport creates a new instance of ResourceGroupResourceOperationsServerTransport with the provided implementation. +// The returned ResourceGroupResourceOperationsServerTransport instance is connected to an instance of methodsubscriptionidgroup.ResourceGroupResourceOperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewResourceGroupResourceOperationsServerTransport(srv *ResourceGroupResourceOperationsServer) *ResourceGroupResourceOperationsServerTransport { + return &ResourceGroupResourceOperationsServerTransport{srv: srv} +} + +// ResourceGroupResourceOperationsServerTransport connects instances of methodsubscriptionidgroup.ResourceGroupResourceOperationsClient to instances of ResourceGroupResourceOperationsServer. +// Don't use this type directly, use NewResourceGroupResourceOperationsServerTransport instead. +type ResourceGroupResourceOperationsServerTransport struct { + srv *ResourceGroupResourceOperationsServer +} + +// Do implements the policy.Transporter interface for ResourceGroupResourceOperationsServerTransport. +func (r *ResourceGroupResourceOperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return r.dispatchToMethodFake(req, method) +} + +func (r *ResourceGroupResourceOperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if resourceGroupResourceOperationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = resourceGroupResourceOperationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ResourceGroupResourceOperationsClient.Delete": + res.resp, res.err = r.dispatchDelete(req) + case "ResourceGroupResourceOperationsClient.Get": + res.resp, res.err = r.dispatchGet(req) + case "ResourceGroupResourceOperationsClient.Put": + res.resp, res.err = r.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (r *ResourceGroupResourceOperationsServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if r.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.MethodSubscriptionId/resourceGroupResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resourceGroupResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.Delete(req.Context(), resourceGroupNameParam, resourceGroupResourceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (r *ResourceGroupResourceOperationsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if r.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.MethodSubscriptionId/resourceGroupResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resourceGroupResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.Get(req.Context(), resourceGroupNameParam, resourceGroupResourceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ResourceGroupResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (r *ResourceGroupResourceOperationsServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if r.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.MethodSubscriptionId/resourceGroupResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[methodsubscriptionidgroup.ResourceGroupResource](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resourceGroupResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.Put(req.Context(), resourceGroupNameParam, resourceGroupResourceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ResourceGroupResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ResourceGroupResourceOperationsServerTransport +var resourceGroupResourceOperationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_server_factory.go b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_server_factory.go new file mode 100644 index 000000000000..5a1378e7d592 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_server_factory.go @@ -0,0 +1,100 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the methodsubscriptionidgroup.ClientFactory type. +type ServerFactory struct { + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer + + // ResourceGroupResourceOperationsServer contains the fakes for client ResourceGroupResourceOperationsClient + ResourceGroupResourceOperationsServer ResourceGroupResourceOperationsServer + + // SubscriptionResource1OperationsServer contains the fakes for client SubscriptionResource1OperationsClient + SubscriptionResource1OperationsServer SubscriptionResource1OperationsServer + + // SubscriptionResource2OperationsServer contains the fakes for client SubscriptionResource2OperationsClient + SubscriptionResource2OperationsServer SubscriptionResource2OperationsServer + + // SubscriptionResourceOperationsServer contains the fakes for client SubscriptionResourceOperationsClient + SubscriptionResourceOperationsServer SubscriptionResourceOperationsServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of methodsubscriptionidgroup.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of methodsubscriptionidgroup.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trOperationsServer *OperationsServerTransport + trResourceGroupResourceOperationsServer *ResourceGroupResourceOperationsServerTransport + trSubscriptionResource1OperationsServer *SubscriptionResource1OperationsServerTransport + trSubscriptionResource2OperationsServer *SubscriptionResource2OperationsServerTransport + trSubscriptionResourceOperationsServer *SubscriptionResourceOperationsServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "OperationsClient": + initServer(&s.trMu, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + resp, err = s.trOperationsServer.Do(req) + case "ResourceGroupResourceOperationsClient": + initServer(&s.trMu, &s.trResourceGroupResourceOperationsServer, func() *ResourceGroupResourceOperationsServerTransport { + return NewResourceGroupResourceOperationsServerTransport(&s.srv.ResourceGroupResourceOperationsServer) + }) + resp, err = s.trResourceGroupResourceOperationsServer.Do(req) + case "SubscriptionResource1OperationsClient": + initServer(&s.trMu, &s.trSubscriptionResource1OperationsServer, func() *SubscriptionResource1OperationsServerTransport { + return NewSubscriptionResource1OperationsServerTransport(&s.srv.SubscriptionResource1OperationsServer) + }) + resp, err = s.trSubscriptionResource1OperationsServer.Do(req) + case "SubscriptionResource2OperationsClient": + initServer(&s.trMu, &s.trSubscriptionResource2OperationsServer, func() *SubscriptionResource2OperationsServerTransport { + return NewSubscriptionResource2OperationsServerTransport(&s.srv.SubscriptionResource2OperationsServer) + }) + resp, err = s.trSubscriptionResource2OperationsServer.Do(req) + case "SubscriptionResourceOperationsClient": + initServer(&s.trMu, &s.trSubscriptionResourceOperationsServer, func() *SubscriptionResourceOperationsServerTransport { + return NewSubscriptionResourceOperationsServerTransport(&s.srv.SubscriptionResourceOperationsServer) + }) + resp, err = s.trSubscriptionResourceOperationsServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_subscriptionresource1operations_server.go b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_subscriptionresource1operations_server.go new file mode 100644 index 000000000000..1db9c5feca66 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_subscriptionresource1operations_server.go @@ -0,0 +1,199 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "methodsubscriptionidgroup" + "net/http" + "net/url" + "regexp" + "slices" +) + +// SubscriptionResource1OperationsServer is a fake server for instances of the methodsubscriptionidgroup.SubscriptionResource1OperationsClient type. +type SubscriptionResource1OperationsServer struct { + // Delete is the fake for method SubscriptionResource1OperationsClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, subscriptionID string, subscriptionResource1Name string, options *methodsubscriptionidgroup.SubscriptionResource1OperationsClientDeleteOptions) (resp azfake.Responder[methodsubscriptionidgroup.SubscriptionResource1OperationsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method SubscriptionResource1OperationsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, subscriptionID string, subscriptionResource1Name string, options *methodsubscriptionidgroup.SubscriptionResource1OperationsClientGetOptions) (resp azfake.Responder[methodsubscriptionidgroup.SubscriptionResource1OperationsClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method SubscriptionResource1OperationsClient.Put + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + Put func(ctx context.Context, subscriptionID string, subscriptionResource1Name string, resource methodsubscriptionidgroup.SubscriptionResource1, options *methodsubscriptionidgroup.SubscriptionResource1OperationsClientPutOptions) (resp azfake.Responder[methodsubscriptionidgroup.SubscriptionResource1OperationsClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewSubscriptionResource1OperationsServerTransport creates a new instance of SubscriptionResource1OperationsServerTransport with the provided implementation. +// The returned SubscriptionResource1OperationsServerTransport instance is connected to an instance of methodsubscriptionidgroup.SubscriptionResource1OperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSubscriptionResource1OperationsServerTransport(srv *SubscriptionResource1OperationsServer) *SubscriptionResource1OperationsServerTransport { + return &SubscriptionResource1OperationsServerTransport{srv: srv} +} + +// SubscriptionResource1OperationsServerTransport connects instances of methodsubscriptionidgroup.SubscriptionResource1OperationsClient to instances of SubscriptionResource1OperationsServer. +// Don't use this type directly, use NewSubscriptionResource1OperationsServerTransport instead. +type SubscriptionResource1OperationsServerTransport struct { + srv *SubscriptionResource1OperationsServer +} + +// Do implements the policy.Transporter interface for SubscriptionResource1OperationsServerTransport. +func (s *SubscriptionResource1OperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *SubscriptionResource1OperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if subscriptionResource1OperationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = subscriptionResource1OperationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SubscriptionResource1OperationsClient.Delete": + res.resp, res.err = s.dispatchDelete(req) + case "SubscriptionResource1OperationsClient.Get": + res.resp, res.err = s.dispatchGet(req) + case "SubscriptionResource1OperationsClient.Put": + res.resp, res.err = s.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *SubscriptionResource1OperationsServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if s.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.MethodSubscriptionId/subscriptionResource1s/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + subscriptionIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionId")]) + if err != nil { + return nil, err + } + subscriptionResource1NameParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionResource1Name")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Delete(req.Context(), subscriptionIDParam, subscriptionResource1NameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SubscriptionResource1OperationsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if s.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.MethodSubscriptionId/subscriptionResource1s/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + subscriptionIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionId")]) + if err != nil { + return nil, err + } + subscriptionResource1NameParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionResource1Name")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Get(req.Context(), subscriptionIDParam, subscriptionResource1NameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).SubscriptionResource1, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SubscriptionResource1OperationsServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if s.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.MethodSubscriptionId/subscriptionResource1s/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[methodsubscriptionidgroup.SubscriptionResource1](req) + if err != nil { + return nil, err + } + subscriptionIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionId")]) + if err != nil { + return nil, err + } + subscriptionResource1NameParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionResource1Name")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Put(req.Context(), subscriptionIDParam, subscriptionResource1NameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).SubscriptionResource1, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SubscriptionResource1OperationsServerTransport +var subscriptionResource1OperationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_subscriptionresource2operations_server.go b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_subscriptionresource2operations_server.go new file mode 100644 index 000000000000..1a7c8029c7f2 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_subscriptionresource2operations_server.go @@ -0,0 +1,199 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "methodsubscriptionidgroup" + "net/http" + "net/url" + "regexp" + "slices" +) + +// SubscriptionResource2OperationsServer is a fake server for instances of the methodsubscriptionidgroup.SubscriptionResource2OperationsClient type. +type SubscriptionResource2OperationsServer struct { + // Delete is the fake for method SubscriptionResource2OperationsClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, subscriptionID string, subscriptionResource2Name string, options *methodsubscriptionidgroup.SubscriptionResource2OperationsClientDeleteOptions) (resp azfake.Responder[methodsubscriptionidgroup.SubscriptionResource2OperationsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method SubscriptionResource2OperationsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, subscriptionID string, subscriptionResource2Name string, options *methodsubscriptionidgroup.SubscriptionResource2OperationsClientGetOptions) (resp azfake.Responder[methodsubscriptionidgroup.SubscriptionResource2OperationsClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method SubscriptionResource2OperationsClient.Put + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + Put func(ctx context.Context, subscriptionID string, subscriptionResource2Name string, resource methodsubscriptionidgroup.SubscriptionResource2, options *methodsubscriptionidgroup.SubscriptionResource2OperationsClientPutOptions) (resp azfake.Responder[methodsubscriptionidgroup.SubscriptionResource2OperationsClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewSubscriptionResource2OperationsServerTransport creates a new instance of SubscriptionResource2OperationsServerTransport with the provided implementation. +// The returned SubscriptionResource2OperationsServerTransport instance is connected to an instance of methodsubscriptionidgroup.SubscriptionResource2OperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSubscriptionResource2OperationsServerTransport(srv *SubscriptionResource2OperationsServer) *SubscriptionResource2OperationsServerTransport { + return &SubscriptionResource2OperationsServerTransport{srv: srv} +} + +// SubscriptionResource2OperationsServerTransport connects instances of methodsubscriptionidgroup.SubscriptionResource2OperationsClient to instances of SubscriptionResource2OperationsServer. +// Don't use this type directly, use NewSubscriptionResource2OperationsServerTransport instead. +type SubscriptionResource2OperationsServerTransport struct { + srv *SubscriptionResource2OperationsServer +} + +// Do implements the policy.Transporter interface for SubscriptionResource2OperationsServerTransport. +func (s *SubscriptionResource2OperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *SubscriptionResource2OperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if subscriptionResource2OperationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = subscriptionResource2OperationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SubscriptionResource2OperationsClient.Delete": + res.resp, res.err = s.dispatchDelete(req) + case "SubscriptionResource2OperationsClient.Get": + res.resp, res.err = s.dispatchGet(req) + case "SubscriptionResource2OperationsClient.Put": + res.resp, res.err = s.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *SubscriptionResource2OperationsServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if s.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.MethodSubscriptionId/subscriptionResource2s/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + subscriptionIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionId")]) + if err != nil { + return nil, err + } + subscriptionResource2NameParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionResource2Name")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Delete(req.Context(), subscriptionIDParam, subscriptionResource2NameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SubscriptionResource2OperationsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if s.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.MethodSubscriptionId/subscriptionResource2s/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + subscriptionIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionId")]) + if err != nil { + return nil, err + } + subscriptionResource2NameParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionResource2Name")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Get(req.Context(), subscriptionIDParam, subscriptionResource2NameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).SubscriptionResource2, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SubscriptionResource2OperationsServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if s.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.MethodSubscriptionId/subscriptionResource2s/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[methodsubscriptionidgroup.SubscriptionResource2](req) + if err != nil { + return nil, err + } + subscriptionIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionId")]) + if err != nil { + return nil, err + } + subscriptionResource2NameParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionResource2Name")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Put(req.Context(), subscriptionIDParam, subscriptionResource2NameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).SubscriptionResource2, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SubscriptionResource2OperationsServerTransport +var subscriptionResource2OperationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_subscriptionresourceoperations_server.go b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_subscriptionresourceoperations_server.go new file mode 100644 index 000000000000..6f5ea6d16663 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/fake/zz_subscriptionresourceoperations_server.go @@ -0,0 +1,199 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "methodsubscriptionidgroup" + "net/http" + "net/url" + "regexp" + "slices" +) + +// SubscriptionResourceOperationsServer is a fake server for instances of the methodsubscriptionidgroup.SubscriptionResourceOperationsClient type. +type SubscriptionResourceOperationsServer struct { + // Delete is the fake for method SubscriptionResourceOperationsClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, subscriptionID string, subscriptionResourceName string, options *methodsubscriptionidgroup.SubscriptionResourceOperationsClientDeleteOptions) (resp azfake.Responder[methodsubscriptionidgroup.SubscriptionResourceOperationsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method SubscriptionResourceOperationsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, subscriptionID string, subscriptionResourceName string, options *methodsubscriptionidgroup.SubscriptionResourceOperationsClientGetOptions) (resp azfake.Responder[methodsubscriptionidgroup.SubscriptionResourceOperationsClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method SubscriptionResourceOperationsClient.Put + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + Put func(ctx context.Context, subscriptionID string, subscriptionResourceName string, resource methodsubscriptionidgroup.SubscriptionResource, options *methodsubscriptionidgroup.SubscriptionResourceOperationsClientPutOptions) (resp azfake.Responder[methodsubscriptionidgroup.SubscriptionResourceOperationsClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewSubscriptionResourceOperationsServerTransport creates a new instance of SubscriptionResourceOperationsServerTransport with the provided implementation. +// The returned SubscriptionResourceOperationsServerTransport instance is connected to an instance of methodsubscriptionidgroup.SubscriptionResourceOperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSubscriptionResourceOperationsServerTransport(srv *SubscriptionResourceOperationsServer) *SubscriptionResourceOperationsServerTransport { + return &SubscriptionResourceOperationsServerTransport{srv: srv} +} + +// SubscriptionResourceOperationsServerTransport connects instances of methodsubscriptionidgroup.SubscriptionResourceOperationsClient to instances of SubscriptionResourceOperationsServer. +// Don't use this type directly, use NewSubscriptionResourceOperationsServerTransport instead. +type SubscriptionResourceOperationsServerTransport struct { + srv *SubscriptionResourceOperationsServer +} + +// Do implements the policy.Transporter interface for SubscriptionResourceOperationsServerTransport. +func (s *SubscriptionResourceOperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *SubscriptionResourceOperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if subscriptionResourceOperationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = subscriptionResourceOperationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SubscriptionResourceOperationsClient.Delete": + res.resp, res.err = s.dispatchDelete(req) + case "SubscriptionResourceOperationsClient.Get": + res.resp, res.err = s.dispatchGet(req) + case "SubscriptionResourceOperationsClient.Put": + res.resp, res.err = s.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *SubscriptionResourceOperationsServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if s.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.MethodSubscriptionId/subscriptionResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + subscriptionIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionId")]) + if err != nil { + return nil, err + } + subscriptionResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Delete(req.Context(), subscriptionIDParam, subscriptionResourceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SubscriptionResourceOperationsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if s.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.MethodSubscriptionId/subscriptionResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + subscriptionIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionId")]) + if err != nil { + return nil, err + } + subscriptionResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Get(req.Context(), subscriptionIDParam, subscriptionResourceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).SubscriptionResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SubscriptionResourceOperationsServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if s.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.MethodSubscriptionId/subscriptionResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[methodsubscriptionidgroup.SubscriptionResource](req) + if err != nil { + return nil, err + } + subscriptionIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionId")]) + if err != nil { + return nil, err + } + subscriptionResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("subscriptionResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Put(req.Context(), subscriptionIDParam, subscriptionResourceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).SubscriptionResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SubscriptionResourceOperationsServerTransport +var subscriptionResourceOperationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/go.mod b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/go.mod new file mode 100644 index 000000000000..71cdb28904ab --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/go.mod @@ -0,0 +1,17 @@ +module methodsubscriptionidgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/go.sum b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/operations_client_test.go b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/operations_client_test.go new file mode 100644 index 000000000000..23685b50a757 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/operations_client_test.go @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package methodsubscriptionidgroup_test + +import ( + "context" + "methodsubscriptionidgroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestOperationsClient_NewListPager(t *testing.T) { + pager := clientFactory.NewOperationsClient().NewListPager(nil) + require.NotNil(t, pager) + validOperation := methodsubscriptionidgroup.Operation{ + Name: to.Ptr("Azure.ResourceManager.MethodSubscriptionId/services/read"), + IsDataAction: to.Ptr(false), + Display: &methodsubscriptionidgroup.OperationDisplay{ + Provider: to.Ptr("Azure.ResourceManager.MethodSubscriptionId"), + Resource: to.Ptr("services"), + Operation: to.Ptr("Lists services"), + Description: to.Ptr("Lists registered services"), + }, + } + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + require.NotNil(t, page) + require.NotEmpty(t, page.Value) + for _, op := range page.Value { + require.Equal(t, validOperation, *op) + } + } +} diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/resourcegroupresourceoperations_client_test.go b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/resourcegroupresourceoperations_client_test.go new file mode 100644 index 000000000000..fc32a039b54e --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/resourcegroupresourceoperations_client_test.go @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package methodsubscriptionidgroup_test + +import ( + "context" + "fmt" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" + + "methodsubscriptionidgroup" +) + +var validResource = methodsubscriptionidgroup.ResourceGroupResource{ + ID: to.Ptr(fmt.Sprintf("/subscriptions/%s/resourceGroups/test-rg/providers/Azure.ResourceManager.MethodSubscriptionId/resourceGroupResources/rg-resource", subscriptionIdExpected)), + Location: to.Ptr("eastus"), + Name: to.Ptr("rg-resource"), + Properties: &methodsubscriptionidgroup.ResourceGroupResourceProperties{ + ProvisioningState: to.Ptr(methodsubscriptionidgroup.ResourceProvisioningState("Succeeded")), + ResourceGroupSetting: to.Ptr(string("test-setting")), + }, + SystemData: &methodsubscriptionidgroup.SystemData{ + CreatedAt: to.Ptr(parseTime("2023-01-01T00:00:00.000Z")), + CreatedBy: to.Ptr(string("AzureSDK")), + CreatedByType: to.Ptr(methodsubscriptionidgroup.CreatedByType("User")), + LastModifiedAt: to.Ptr(parseTime("2023-01-01T00:00:00.000Z")), + LastModifiedBy: to.Ptr(string("AzureSDK")), + LastModifiedByType: to.Ptr(methodsubscriptionidgroup.CreatedByType("User")), + }, + Type: to.Ptr("Azure.ResourceManager.MethodSubscriptionId/resourceGroupResources"), +} + +func TestResourceGroupResourceOperationsClient_Delete(t *testing.T) { + delResp, err := clientFactory.NewResourceGroupResourceOperationsClient().Delete(context.Background(), "test-rg", "rg-resource", nil) + require.NoError(t, err) + require.Zero(t, delResp) +} + +func TestResourceGroupResourceOperationsClient_Put(t *testing.T) { + var reqResource = methodsubscriptionidgroup.ResourceGroupResource{ + Location: to.Ptr("eastus"), + Properties: &methodsubscriptionidgroup.ResourceGroupResourceProperties{ + ResourceGroupSetting: to.Ptr(string("test-setting")), + }, + } + putResp, err := clientFactory.NewResourceGroupResourceOperationsClient().Put(context.Background(), "test-rg", "rg-resource", reqResource, nil) + require.NoError(t, err) + require.NotNil(t, putResp) + require.Equal(t, validResource, putResp.ResourceGroupResource) +} + +func TestResourceGroupResourceOperationsClient_Get(t *testing.T) { + getResp, err := clientFactory.NewResourceGroupResourceOperationsClient().Get(context.Background(), "test-rg", "rg-resource", nil) + require.NoError(t, err) + require.NotNil(t, getResp) + require.Equal(t, validResource, getResp.ResourceGroupResource) +} diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/subscriptionresource1operations_client_test.go b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/subscriptionresource1operations_client_test.go new file mode 100644 index 000000000000..8ffb260c473a --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/subscriptionresource1operations_client_test.go @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package methodsubscriptionidgroup_test + +import ( + "context" + "fmt" + "log" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" + + "methodsubscriptionidgroup" +) + +// parseTime parses an RFC3339 time string and panics if parsing fails. +func parseTime(value string) time.Time { + t, err := time.Parse(time.RFC3339, value) + if err != nil { + log.Fatalf("failed to parse time: %v", err) + } + return t +} + +var validResource1 = methodsubscriptionidgroup.SubscriptionResource1{ + ID: to.Ptr(fmt.Sprintf(`/subscriptions/%s/providers/Azure.ResourceManager.MethodSubscriptionId/subscriptionResource1s/sub-resource-1`, subscriptionIdExpected)), + Name: to.Ptr("sub-resource-1"), + Type: to.Ptr("Azure.ResourceManager.MethodSubscriptionId/subscriptionResource1s"), + Properties: &methodsubscriptionidgroup.SubscriptionResource1Properties{ + ProvisioningState: to.Ptr(methodsubscriptionidgroup.ResourceProvisioningState("Succeeded")), + Description: to.Ptr(string("Valid subscription resource 1")), + }, + SystemData: &methodsubscriptionidgroup.SystemData{ + CreatedBy: to.Ptr(string("AzureSDK")), + CreatedByType: to.Ptr(methodsubscriptionidgroup.CreatedByType("User")), + CreatedAt: to.Ptr(parseTime("2023-01-01T00:00:00.000Z")), + LastModifiedBy: to.Ptr(string("AzureSDK")), + LastModifiedAt: to.Ptr(parseTime("2023-01-01T00:00:00.000Z")), + LastModifiedByType: to.Ptr(methodsubscriptionidgroup.CreatedByType("User")), + }, +} + +func TestSubscriptionResource1OperationsClient_Delete(t *testing.T) { + delResp, err := clientFactory.NewSubscriptionResource1OperationsClient().Delete(context.Background(), subscriptionIdExpected, "sub-resource-1", nil) + require.NoError(t, err) + require.Zero(t, delResp) +} + +func TestSubscriptionResource1OperationsClient_Put(t *testing.T) { + var validResource = methodsubscriptionidgroup.SubscriptionResource1{ + Properties: &methodsubscriptionidgroup.SubscriptionResource1Properties{ + Description: to.Ptr(string("Valid subscription resource 1")), + }, + } + putResp, err := clientFactory.NewSubscriptionResource1OperationsClient().Put(context.Background(), subscriptionIdExpected, "sub-resource-1", validResource, nil) + require.NoError(t, err) + require.NotNil(t, putResp) + require.Equal(t, validResource1, putResp.SubscriptionResource1) +} + +func TestSubscriptionResource1OperationsClient_Get(t *testing.T) { + getResp, err := clientFactory.NewSubscriptionResource1OperationsClient().Get(context.Background(), subscriptionIdExpected, "sub-resource-1", nil) + require.NoError(t, err) + require.NotNil(t, getResp) + require.Equal(t, validResource1, getResp.SubscriptionResource1) +} diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/subscriptionresource2operations_client_test.go b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/subscriptionresource2operations_client_test.go new file mode 100644 index 000000000000..f5f5849e6e50 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/subscriptionresource2operations_client_test.go @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package methodsubscriptionidgroup_test + +import ( + "context" + "fmt" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" + + "methodsubscriptionidgroup" +) + +var validResource2 = methodsubscriptionidgroup.SubscriptionResource2{ + ID: to.Ptr(fmt.Sprintf(`/subscriptions/%s/providers/Azure.ResourceManager.MethodSubscriptionId/subscriptionResource2s/sub-resource-2`, subscriptionIdExpected)), + Name: to.Ptr("sub-resource-2"), + Type: to.Ptr("Azure.ResourceManager.MethodSubscriptionId/subscriptionResource2s"), + Properties: &methodsubscriptionidgroup.SubscriptionResource2Properties{ + ProvisioningState: to.Ptr(methodsubscriptionidgroup.ResourceProvisioningState("Succeeded")), + ConfigValue: to.Ptr(string("test-config")), + }, + SystemData: &methodsubscriptionidgroup.SystemData{ + CreatedBy: to.Ptr(string("AzureSDK")), + CreatedByType: to.Ptr(methodsubscriptionidgroup.CreatedByType("User")), + CreatedAt: to.Ptr(parseTime("2023-01-01T00:00:00.000Z")), + LastModifiedBy: to.Ptr(string("AzureSDK")), + LastModifiedAt: to.Ptr(parseTime("2023-01-01T00:00:00.000Z")), + LastModifiedByType: to.Ptr(methodsubscriptionidgroup.CreatedByType("User")), + }, +} + +func TestSubscriptionResource2OperationsClient_Delete(t *testing.T) { + delResp, err := clientFactory.NewSubscriptionResource2OperationsClient().Delete(context.Background(), subscriptionIdExpected, "sub-resource-2", nil) + require.NoError(t, err) + require.Zero(t, delResp) +} + +func TestSubscriptionResource2OperationsClient_Put(t *testing.T) { + var validResource = methodsubscriptionidgroup.SubscriptionResource2{ + Properties: &methodsubscriptionidgroup.SubscriptionResource2Properties{ + ConfigValue: to.Ptr(string("test-config")), + }, + } + putResp, err := clientFactory.NewSubscriptionResource2OperationsClient().Put(context.Background(), subscriptionIdExpected, "sub-resource-2", validResource, nil) + require.NoError(t, err) + require.NotNil(t, putResp) + require.Equal(t, validResource2, putResp.SubscriptionResource2) +} + +func TestSubscriptionResource2OperationsClient_Get(t *testing.T) { + getResp, err := clientFactory.NewSubscriptionResource2OperationsClient().Get(context.Background(), subscriptionIdExpected, "sub-resource-2", nil) + require.NoError(t, err) + require.NotNil(t, getResp) + require.Equal(t, validResource2, getResp.SubscriptionResource2) +} diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/subscriptionresourceoperations_client_test.go b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/subscriptionresourceoperations_client_test.go new file mode 100644 index 000000000000..154b940a7c4e --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/subscriptionresourceoperations_client_test.go @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package methodsubscriptionidgroup_test + +import ( + "context" + "fmt" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" + + "methodsubscriptionidgroup" +) + +var validMixedSubscriptionResource = methodsubscriptionidgroup.SubscriptionResource{ + ID: to.Ptr(fmt.Sprintf("/subscriptions/%s/providers/Azure.ResourceManager.MethodSubscriptionId/subscriptionResources/sub-resource", subscriptionIdExpected)), + Name: to.Ptr("sub-resource"), + Properties: &methodsubscriptionidgroup.SubscriptionResourceProperties{ + ProvisioningState: to.Ptr(methodsubscriptionidgroup.ResourceProvisioningState("Succeeded")), + SubscriptionSetting: to.Ptr(string("test-sub-setting")), + }, + SystemData: &methodsubscriptionidgroup.SystemData{ + CreatedAt: to.Ptr(parseTime("2023-01-01T00:00:00.000Z")), + CreatedBy: to.Ptr(string("AzureSDK")), + CreatedByType: to.Ptr(methodsubscriptionidgroup.CreatedByType("User")), + LastModifiedAt: to.Ptr(parseTime("2023-01-01T00:00:00.000Z")), + LastModifiedBy: to.Ptr(string("AzureSDK")), + LastModifiedByType: to.Ptr(methodsubscriptionidgroup.CreatedByType("User")), + }, + Type: to.Ptr("Azure.ResourceManager.MethodSubscriptionId/subscriptionResources"), +} + +func TestSubscriptionResourceOperationsClient_Delete(t *testing.T) { + delResp, err := clientFactory.NewSubscriptionResourceOperationsClient().Delete(context.Background(), subscriptionIdExpected, "sub-resource", nil) + require.NoError(t, err) + require.Zero(t, delResp) +} + +func TestSubscriptionResourceOperationsClient_Put(t *testing.T) { + var validResource = methodsubscriptionidgroup.SubscriptionResource{ + Properties: &methodsubscriptionidgroup.SubscriptionResourceProperties{ + SubscriptionSetting: to.Ptr(string("test-sub-setting")), + }, + } + putResp, err := clientFactory.NewSubscriptionResourceOperationsClient().Put(context.Background(), subscriptionIdExpected, "sub-resource", validResource, nil) + require.NoError(t, err) + require.NotNil(t, putResp) + require.Equal(t, validMixedSubscriptionResource, putResp.SubscriptionResource) +} + +func TestSubscriptionResourceOperationsClient_Get(t *testing.T) { + getResp, err := clientFactory.NewSubscriptionResourceOperationsClient().Get(context.Background(), subscriptionIdExpected, "sub-resource", nil) + require.NoError(t, err) + require.NotNil(t, getResp) + require.Equal(t, validMixedSubscriptionResource, getResp.SubscriptionResource) +} diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/testdata/_metadata.json b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/testdata/_metadata.json new file mode 100644 index 000000000000..50bad3726870 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Azure.ResourceManager.MethodSubscriptionId": "2023-12-01-preview" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/utils_test.go b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/utils_test.go new file mode 100644 index 000000000000..0f6cc5c0c582 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/utils_test.go @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package methodsubscriptionidgroup_test + +import ( + "context" + "methodsubscriptionidgroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" +) + +var ( + ctx context.Context + clientFactory *methodsubscriptionidgroup.ClientFactory + + subscriptionIdExpected = "00000000-0000-0000-0000-000000000000" +) + +func TestMain(m *testing.M) { + ctx = context.Background() + clientFactory, _ = methodsubscriptionidgroup.NewClientFactory(subscriptionIdExpected, &azfake.TokenCredential{}, &arm.ClientOptions{ + ClientOptions: azcore.ClientOptions{ + Cloud: cloud.Configuration{ + Services: map[cloud.ServiceName]cloud.ServiceConfiguration{ + cloud.ResourceManager: { + Audience: "fake_audience", + Endpoint: "http://localhost:3000", + }, + }, + }, + InsecureAllowCredentialWithHTTP: true, + }, + }) + + m.Run() +} diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_client_factory.go b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_client_factory.go new file mode 100644 index 000000000000..5ad4a9729864 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_client_factory.go @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package methodsubscriptionidgroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + subscriptionID string + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, + internal: internal, + }, nil +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: c.internal, + } +} + +// NewResourceGroupResourceOperationsClient creates a new instance of ResourceGroupResourceOperationsClient. +func (c *ClientFactory) NewResourceGroupResourceOperationsClient() *ResourceGroupResourceOperationsClient { + return &ResourceGroupResourceOperationsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewSubscriptionResource1OperationsClient creates a new instance of SubscriptionResource1OperationsClient. +func (c *ClientFactory) NewSubscriptionResource1OperationsClient() *SubscriptionResource1OperationsClient { + return &SubscriptionResource1OperationsClient{ + internal: c.internal, + } +} + +// NewSubscriptionResource2OperationsClient creates a new instance of SubscriptionResource2OperationsClient. +func (c *ClientFactory) NewSubscriptionResource2OperationsClient() *SubscriptionResource2OperationsClient { + return &SubscriptionResource2OperationsClient{ + internal: c.internal, + } +} + +// NewSubscriptionResourceOperationsClient creates a new instance of SubscriptionResourceOperationsClient. +func (c *ClientFactory) NewSubscriptionResourceOperationsClient() *SubscriptionResourceOperationsClient { + return &SubscriptionResourceOperationsClient{ + internal: c.internal, + } +} diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_constants.go b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_constants.go new file mode 100644 index 000000000000..a6223e59d792 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_constants.go @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package methodsubscriptionidgroup + +const ( + version20231201Preview string = "2023-12-01-preview" +) + +// ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +type ActionType string + +const ( + // ActionTypeInternal - Actions are for internal-only APIs. + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// Origin - The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default +// value is "user,system" +type Origin string + +const ( + // OriginSystem - Indicates the operation is initiated by a system. + OriginSystem Origin = "system" + // OriginUser - Indicates the operation is initiated by a user. + OriginUser Origin = "user" + // OriginUserSystem - Indicates the operation is initiated by a user or system. + OriginUserSystem Origin = "user,system" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginSystem, + OriginUser, + OriginUserSystem, + } +} + +// ResourceProvisioningState - The provisioning state of a resource type. +type ResourceProvisioningState string + +const ( + // ResourceProvisioningStateCanceled - Resource creation was canceled. + ResourceProvisioningStateCanceled ResourceProvisioningState = "Canceled" + // ResourceProvisioningStateFailed - Resource creation failed. + ResourceProvisioningStateFailed ResourceProvisioningState = "Failed" + // ResourceProvisioningStateSucceeded - Resource has been created. + ResourceProvisioningStateSucceeded ResourceProvisioningState = "Succeeded" +) + +// PossibleResourceProvisioningStateValues returns the possible values for the ResourceProvisioningState const type. +func PossibleResourceProvisioningStateValues() []ResourceProvisioningState { + return []ResourceProvisioningState{ + ResourceProvisioningStateCanceled, + ResourceProvisioningStateFailed, + ResourceProvisioningStateSucceeded, + } +} diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_models.go b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_models.go new file mode 100644 index 000000000000..fceed3e95fbb --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_models.go @@ -0,0 +1,194 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package methodsubscriptionidgroup + +import "time" + +// Operation - REST API Operation +// +// Details of a REST API operation, returned from the Resource Provider Operations API +type Operation struct { + // Localized display information for this particular operation. + Display *OperationDisplay + + // READ-ONLY; Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + ActionType *ActionType + + // READ-ONLY; Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure + // Resource Manager/control-plane operations. + IsDataAction *bool + + // READ-ONLY; The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + // "Microsoft.Compute/virtualMachines/capture/action" + Name *string + + // READ-ONLY; The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default + // value is "user,system" + Origin *Origin +} + +// OperationDisplay - Localized display information for an operation. +type OperationDisplay struct { + // READ-ONLY; The short, localized friendly description of the operation; suitable for tool tips and detailed views. + Description *string + + // READ-ONLY; The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual + // Machine", "Restart Virtual Machine". + Operation *string + + // READ-ONLY; The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft + // Compute". + Provider *string + + // READ-ONLY; The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job + // Schedule Collections". + Resource *string +} + +// OperationListResult - A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to +// get the next set of results. +type OperationListResult struct { + // REQUIRED; The Operation items on this page + Value []*Operation + + // The link to the next page of items + NextLink *string +} + +// ResourceGroupResource - Concrete tracked resource types can be created by aliasing this type using a specific property +// type. +type ResourceGroupResource struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *ResourceGroupResourceProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ResourceGroupResourceProperties - Properties of resource group resource. +type ResourceGroupResourceProperties struct { + // The resource group-scoped setting. + ResourceGroupSetting *string + + // READ-ONLY; The status of the last operation. + ProvisioningState *ResourceProvisioningState +} + +// SubscriptionResource - Concrete proxy resource types can be created by aliasing this type using a specific property type. +type SubscriptionResource struct { + // The resource-specific properties for this resource. + Properties *SubscriptionResourceProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// SubscriptionResource1 - Concrete proxy resource types can be created by aliasing this type using a specific property type. +type SubscriptionResource1 struct { + // The resource-specific properties for this resource. + Properties *SubscriptionResource1Properties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// SubscriptionResource1Properties - Properties of subscription resource 1. +type SubscriptionResource1Properties struct { + // The description of the resource. + Description *string + + // READ-ONLY; The status of the last operation. + ProvisioningState *ResourceProvisioningState +} + +// SubscriptionResource2 - Concrete proxy resource types can be created by aliasing this type using a specific property type. +type SubscriptionResource2 struct { + // The resource-specific properties for this resource. + Properties *SubscriptionResource2Properties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// SubscriptionResource2Properties - Properties of subscription resource 2. +type SubscriptionResource2Properties struct { + // The configuration value. + ConfigValue *string + + // READ-ONLY; The status of the last operation. + ProvisioningState *ResourceProvisioningState +} + +// SubscriptionResourceProperties - Properties of subscription resource. +type SubscriptionResourceProperties struct { + // The subscription-scoped setting. + SubscriptionSetting *string + + // READ-ONLY; The status of the last operation. + ProvisioningState *ResourceProvisioningState +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time + + // The identity that created the resource. + CreatedBy *string + + // The type of identity that created the resource. + CreatedByType *CreatedByType + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time + + // The identity that last modified the resource. + LastModifiedBy *string + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType +} diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_models_serde.go b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_models_serde.go new file mode 100644 index 000000000000..d2b3938b9eea --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_models_serde.go @@ -0,0 +1,526 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package methodsubscriptionidgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type Operation. +func (o Operation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionType", o.ActionType) + populate(objectMap, "display", o.Display) + populate(objectMap, "isDataAction", o.IsDataAction) + populate(objectMap, "name", o.Name) + populate(objectMap, "origin", o.Origin) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Operation. +func (o *Operation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionType": + err = unpopulate(val, "ActionType", &o.ActionType) + delete(rawMsg, key) + case "display": + err = unpopulate(val, "Display", &o.Display) + delete(rawMsg, key) + case "isDataAction": + err = unpopulate(val, "IsDataAction", &o.IsDataAction) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "origin": + err = unpopulate(val, "Origin", &o.Origin) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationDisplay. +func (o OperationDisplay) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", o.Description) + populate(objectMap, "operation", o.Operation) + populate(objectMap, "provider", o.Provider) + populate(objectMap, "resource", o.Resource) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationDisplay. +func (o *OperationDisplay) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &o.Description) + delete(rawMsg, key) + case "operation": + err = unpopulate(val, "Operation", &o.Operation) + delete(rawMsg, key) + case "provider": + err = unpopulate(val, "Provider", &o.Provider) + delete(rawMsg, key) + case "resource": + err = unpopulate(val, "Resource", &o.Resource) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationListResult. +func (o *OperationListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &o.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceGroupResource. +func (r ResourceGroupResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", r.ID) + populate(objectMap, "location", r.Location) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "systemData", r.SystemData) + populate(objectMap, "tags", r.Tags) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceGroupResource. +func (r *ResourceGroupResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &r.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &r.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &r.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &r.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceGroupResourceProperties. +func (r ResourceGroupResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", r.ProvisioningState) + populate(objectMap, "resourceGroupSetting", r.ResourceGroupSetting) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceGroupResourceProperties. +func (r *ResourceGroupResourceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &r.ProvisioningState) + delete(rawMsg, key) + case "resourceGroupSetting": + err = unpopulate(val, "ResourceGroupSetting", &r.ResourceGroupSetting) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SubscriptionResource. +func (s SubscriptionResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "systemData", s.SystemData) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SubscriptionResource. +func (s *SubscriptionResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &s.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SubscriptionResource1. +func (s SubscriptionResource1) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "systemData", s.SystemData) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SubscriptionResource1. +func (s *SubscriptionResource1) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &s.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SubscriptionResource1Properties. +func (s SubscriptionResource1Properties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", s.Description) + populate(objectMap, "provisioningState", s.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SubscriptionResource1Properties. +func (s *SubscriptionResource1Properties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &s.Description) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SubscriptionResource2. +func (s SubscriptionResource2) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "systemData", s.SystemData) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SubscriptionResource2. +func (s *SubscriptionResource2) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &s.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SubscriptionResource2Properties. +func (s SubscriptionResource2Properties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "configValue", s.ConfigValue) + populate(objectMap, "provisioningState", s.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SubscriptionResource2Properties. +func (s *SubscriptionResource2Properties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "configValue": + err = unpopulate(val, "ConfigValue", &s.ConfigValue) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SubscriptionResourceProperties. +func (s SubscriptionResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "subscriptionSetting", s.SubscriptionSetting) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SubscriptionResourceProperties. +func (s *SubscriptionResourceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + case "subscriptionSetting": + err = unpopulate(val, "SubscriptionSetting", &s.SubscriptionSetting) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateTime[datetime.RFC3339](objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateTime[datetime.RFC3339](val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateTime[datetime.RFC3339](val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_operations_client.go b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_operations_client.go new file mode 100644 index 000000000000..4479effa74a2 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_operations_client.go @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package methodsubscriptionidgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +// +// Generated from API version 2023-12-01-preview +type OperationsClient struct { + internal *arm.Client +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*OperationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OperationsClient{ + internal: cl, + } + return client, nil +} + +// NewListPager - List the operations for the provider +// - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ + More: func(page OperationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OperationsClientListResponse) (OperationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OperationsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return OperationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, _ *OperationsClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Azure.ResourceManager.MethodSubscriptionId/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsClientListResponse, error) { + result := OperationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsClientListResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_options.go b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_options.go new file mode 100644 index 000000000000..3ad663248c91 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_options.go @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package methodsubscriptionidgroup + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} + +// ResourceGroupResourceOperationsClientDeleteOptions contains the optional parameters for the ResourceGroupResourceOperationsClient.Delete +// method. +type ResourceGroupResourceOperationsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// ResourceGroupResourceOperationsClientGetOptions contains the optional parameters for the ResourceGroupResourceOperationsClient.Get +// method. +type ResourceGroupResourceOperationsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ResourceGroupResourceOperationsClientPutOptions contains the optional parameters for the ResourceGroupResourceOperationsClient.Put +// method. +type ResourceGroupResourceOperationsClientPutOptions struct { + // placeholder for future optional parameters +} + +// SubscriptionResource1OperationsClientDeleteOptions contains the optional parameters for the SubscriptionResource1OperationsClient.Delete +// method. +type SubscriptionResource1OperationsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// SubscriptionResource1OperationsClientGetOptions contains the optional parameters for the SubscriptionResource1OperationsClient.Get +// method. +type SubscriptionResource1OperationsClientGetOptions struct { + // placeholder for future optional parameters +} + +// SubscriptionResource1OperationsClientPutOptions contains the optional parameters for the SubscriptionResource1OperationsClient.Put +// method. +type SubscriptionResource1OperationsClientPutOptions struct { + // placeholder for future optional parameters +} + +// SubscriptionResource2OperationsClientDeleteOptions contains the optional parameters for the SubscriptionResource2OperationsClient.Delete +// method. +type SubscriptionResource2OperationsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// SubscriptionResource2OperationsClientGetOptions contains the optional parameters for the SubscriptionResource2OperationsClient.Get +// method. +type SubscriptionResource2OperationsClientGetOptions struct { + // placeholder for future optional parameters +} + +// SubscriptionResource2OperationsClientPutOptions contains the optional parameters for the SubscriptionResource2OperationsClient.Put +// method. +type SubscriptionResource2OperationsClientPutOptions struct { + // placeholder for future optional parameters +} + +// SubscriptionResourceOperationsClientDeleteOptions contains the optional parameters for the SubscriptionResourceOperationsClient.Delete +// method. +type SubscriptionResourceOperationsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// SubscriptionResourceOperationsClientGetOptions contains the optional parameters for the SubscriptionResourceOperationsClient.Get +// method. +type SubscriptionResourceOperationsClientGetOptions struct { + // placeholder for future optional parameters +} + +// SubscriptionResourceOperationsClientPutOptions contains the optional parameters for the SubscriptionResourceOperationsClient.Put +// method. +type SubscriptionResourceOperationsClientPutOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_resourcegroupresourceoperations_client.go b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_resourcegroupresourceoperations_client.go new file mode 100644 index 000000000000..8e62c628c0f0 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_resourcegroupresourceoperations_client.go @@ -0,0 +1,225 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package methodsubscriptionidgroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ResourceGroupResourceOperationsClient contains the methods for the ResourceGroupResourceOperations group. +// Don't use this type directly, use NewResourceGroupResourceOperationsClient() instead. +// +// Generated from API version 2023-12-01-preview +type ResourceGroupResourceOperationsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewResourceGroupResourceOperationsClient creates a new instance of ResourceGroupResourceOperationsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewResourceGroupResourceOperationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ResourceGroupResourceOperationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ResourceGroupResourceOperationsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Delete - Delete a ResourceGroupResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - resourceGroupResourceName - The name of the ResourceGroupResource +// - options - ResourceGroupResourceOperationsClientDeleteOptions contains the optional parameters for the ResourceGroupResourceOperationsClient.Delete +// method. +func (client *ResourceGroupResourceOperationsClient) Delete(ctx context.Context, resourceGroupName string, resourceGroupResourceName string, options *ResourceGroupResourceOperationsClientDeleteOptions) (ResourceGroupResourceOperationsClientDeleteResponse, error) { + var err error + const operationName = "ResourceGroupResourceOperationsClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, resourceGroupResourceName, options) + if err != nil { + return ResourceGroupResourceOperationsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ResourceGroupResourceOperationsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ResourceGroupResourceOperationsClientDeleteResponse{}, err + } + return ResourceGroupResourceOperationsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ResourceGroupResourceOperationsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, resourceGroupResourceName string, _ *ResourceGroupResourceOperationsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.MethodSubscriptionId/resourceGroupResources/{resourceGroupResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if resourceGroupResourceName == "" { + return nil, errors.New("parameter resourceGroupResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupResourceName}", url.PathEscape(resourceGroupResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a ResourceGroupResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - resourceGroupResourceName - The name of the ResourceGroupResource +// - options - ResourceGroupResourceOperationsClientGetOptions contains the optional parameters for the ResourceGroupResourceOperationsClient.Get +// method. +func (client *ResourceGroupResourceOperationsClient) Get(ctx context.Context, resourceGroupName string, resourceGroupResourceName string, options *ResourceGroupResourceOperationsClientGetOptions) (ResourceGroupResourceOperationsClientGetResponse, error) { + var err error + const operationName = "ResourceGroupResourceOperationsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, resourceGroupResourceName, options) + if err != nil { + return ResourceGroupResourceOperationsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ResourceGroupResourceOperationsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ResourceGroupResourceOperationsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ResourceGroupResourceOperationsClient) getCreateRequest(ctx context.Context, resourceGroupName string, resourceGroupResourceName string, _ *ResourceGroupResourceOperationsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.MethodSubscriptionId/resourceGroupResources/{resourceGroupResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if resourceGroupResourceName == "" { + return nil, errors.New("parameter resourceGroupResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupResourceName}", url.PathEscape(resourceGroupResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ResourceGroupResourceOperationsClient) getHandleResponse(resp *http.Response) (ResourceGroupResourceOperationsClientGetResponse, error) { + result := ResourceGroupResourceOperationsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ResourceGroupResource); err != nil { + return ResourceGroupResourceOperationsClientGetResponse{}, err + } + return result, nil +} + +// Put - Create a ResourceGroupResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - resourceGroupResourceName - The name of the ResourceGroupResource +// - resource - Resource create parameters. +// - options - ResourceGroupResourceOperationsClientPutOptions contains the optional parameters for the ResourceGroupResourceOperationsClient.Put +// method. +func (client *ResourceGroupResourceOperationsClient) Put(ctx context.Context, resourceGroupName string, resourceGroupResourceName string, resource ResourceGroupResource, options *ResourceGroupResourceOperationsClientPutOptions) (ResourceGroupResourceOperationsClientPutResponse, error) { + var err error + const operationName = "ResourceGroupResourceOperationsClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, resourceGroupName, resourceGroupResourceName, resource, options) + if err != nil { + return ResourceGroupResourceOperationsClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ResourceGroupResourceOperationsClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return ResourceGroupResourceOperationsClientPutResponse{}, err + } + resp, err := client.putHandleResponse(httpResp) + return resp, err +} + +// putCreateRequest creates the Put request. +func (client *ResourceGroupResourceOperationsClient) putCreateRequest(ctx context.Context, resourceGroupName string, resourceGroupResourceName string, resource ResourceGroupResource, _ *ResourceGroupResourceOperationsClientPutOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.MethodSubscriptionId/resourceGroupResources/{resourceGroupResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if resourceGroupResourceName == "" { + return nil, errors.New("parameter resourceGroupResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupResourceName}", url.PathEscape(resourceGroupResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// putHandleResponse handles the Put response. +func (client *ResourceGroupResourceOperationsClient) putHandleResponse(resp *http.Response) (ResourceGroupResourceOperationsClientPutResponse, error) { + result := ResourceGroupResourceOperationsClientPutResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ResourceGroupResource); err != nil { + return ResourceGroupResourceOperationsClientPutResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_responses.go b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_responses.go new file mode 100644 index 000000000000..b48f79e12f3a --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_responses.go @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package methodsubscriptionidgroup + +// OperationsClientListResponse contains the response from method OperationsClient.NewListPager. +type OperationsClientListResponse struct { + // A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. + OperationListResult +} + +// ResourceGroupResourceOperationsClientDeleteResponse contains the response from method ResourceGroupResourceOperationsClient.Delete. +type ResourceGroupResourceOperationsClientDeleteResponse struct { + // placeholder for future response values +} + +// ResourceGroupResourceOperationsClientGetResponse contains the response from method ResourceGroupResourceOperationsClient.Get. +type ResourceGroupResourceOperationsClientGetResponse struct { + // Concrete tracked resource types can be created by aliasing this type using a specific property type. + ResourceGroupResource +} + +// ResourceGroupResourceOperationsClientPutResponse contains the response from method ResourceGroupResourceOperationsClient.Put. +type ResourceGroupResourceOperationsClientPutResponse struct { + // Concrete tracked resource types can be created by aliasing this type using a specific property type. + ResourceGroupResource +} + +// SubscriptionResource1OperationsClientDeleteResponse contains the response from method SubscriptionResource1OperationsClient.Delete. +type SubscriptionResource1OperationsClientDeleteResponse struct { + // placeholder for future response values +} + +// SubscriptionResource1OperationsClientGetResponse contains the response from method SubscriptionResource1OperationsClient.Get. +type SubscriptionResource1OperationsClientGetResponse struct { + // Concrete proxy resource types can be created by aliasing this type using a specific property type. + SubscriptionResource1 +} + +// SubscriptionResource1OperationsClientPutResponse contains the response from method SubscriptionResource1OperationsClient.Put. +type SubscriptionResource1OperationsClientPutResponse struct { + // Concrete proxy resource types can be created by aliasing this type using a specific property type. + SubscriptionResource1 +} + +// SubscriptionResource2OperationsClientDeleteResponse contains the response from method SubscriptionResource2OperationsClient.Delete. +type SubscriptionResource2OperationsClientDeleteResponse struct { + // placeholder for future response values +} + +// SubscriptionResource2OperationsClientGetResponse contains the response from method SubscriptionResource2OperationsClient.Get. +type SubscriptionResource2OperationsClientGetResponse struct { + // Concrete proxy resource types can be created by aliasing this type using a specific property type. + SubscriptionResource2 +} + +// SubscriptionResource2OperationsClientPutResponse contains the response from method SubscriptionResource2OperationsClient.Put. +type SubscriptionResource2OperationsClientPutResponse struct { + // Concrete proxy resource types can be created by aliasing this type using a specific property type. + SubscriptionResource2 +} + +// SubscriptionResourceOperationsClientDeleteResponse contains the response from method SubscriptionResourceOperationsClient.Delete. +type SubscriptionResourceOperationsClientDeleteResponse struct { + // placeholder for future response values +} + +// SubscriptionResourceOperationsClientGetResponse contains the response from method SubscriptionResourceOperationsClient.Get. +type SubscriptionResourceOperationsClientGetResponse struct { + // Concrete proxy resource types can be created by aliasing this type using a specific property type. + SubscriptionResource +} + +// SubscriptionResourceOperationsClientPutResponse contains the response from method SubscriptionResourceOperationsClient.Put. +type SubscriptionResourceOperationsClientPutResponse struct { + // Concrete proxy resource types can be created by aliasing this type using a specific property type. + SubscriptionResource +} diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_subscriptionresource1operations_client.go b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_subscriptionresource1operations_client.go new file mode 100644 index 000000000000..eace0e3cc3da --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_subscriptionresource1operations_client.go @@ -0,0 +1,210 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package methodsubscriptionidgroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// SubscriptionResource1OperationsClient contains the methods for the SubscriptionResource1Operations group. +// Don't use this type directly, use NewSubscriptionResource1OperationsClient() instead. +// +// Generated from API version 2023-12-01-preview +type SubscriptionResource1OperationsClient struct { + internal *arm.Client +} + +// NewSubscriptionResource1OperationsClient creates a new instance of SubscriptionResource1OperationsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewSubscriptionResource1OperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*SubscriptionResource1OperationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SubscriptionResource1OperationsClient{ + internal: cl, + } + return client, nil +} + +// Delete - Delete a SubscriptionResource1 +// If the operation fails it returns an *azcore.ResponseError type. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - subscriptionResource1Name - The name of the SubscriptionResource1 +// - options - SubscriptionResource1OperationsClientDeleteOptions contains the optional parameters for the SubscriptionResource1OperationsClient.Delete +// method. +func (client *SubscriptionResource1OperationsClient) Delete(ctx context.Context, subscriptionID string, subscriptionResource1Name string, options *SubscriptionResource1OperationsClientDeleteOptions) (SubscriptionResource1OperationsClientDeleteResponse, error) { + var err error + const operationName = "SubscriptionResource1OperationsClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, subscriptionID, subscriptionResource1Name, options) + if err != nil { + return SubscriptionResource1OperationsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SubscriptionResource1OperationsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SubscriptionResource1OperationsClientDeleteResponse{}, err + } + return SubscriptionResource1OperationsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *SubscriptionResource1OperationsClient) deleteCreateRequest(ctx context.Context, subscriptionID string, subscriptionResource1Name string, _ *SubscriptionResource1OperationsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Azure.ResourceManager.MethodSubscriptionId/subscriptionResource1s/{subscriptionResource1Name}" + if subscriptionID == "" { + return nil, errors.New("parameter subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(subscriptionID)) + if subscriptionResource1Name == "" { + return nil, errors.New("parameter subscriptionResource1Name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionResource1Name}", url.PathEscape(subscriptionResource1Name)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a SubscriptionResource1 +// If the operation fails it returns an *azcore.ResponseError type. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - subscriptionResource1Name - The name of the SubscriptionResource1 +// - options - SubscriptionResource1OperationsClientGetOptions contains the optional parameters for the SubscriptionResource1OperationsClient.Get +// method. +func (client *SubscriptionResource1OperationsClient) Get(ctx context.Context, subscriptionID string, subscriptionResource1Name string, options *SubscriptionResource1OperationsClientGetOptions) (SubscriptionResource1OperationsClientGetResponse, error) { + var err error + const operationName = "SubscriptionResource1OperationsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, subscriptionID, subscriptionResource1Name, options) + if err != nil { + return SubscriptionResource1OperationsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SubscriptionResource1OperationsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SubscriptionResource1OperationsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *SubscriptionResource1OperationsClient) getCreateRequest(ctx context.Context, subscriptionID string, subscriptionResource1Name string, _ *SubscriptionResource1OperationsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Azure.ResourceManager.MethodSubscriptionId/subscriptionResource1s/{subscriptionResource1Name}" + if subscriptionID == "" { + return nil, errors.New("parameter subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(subscriptionID)) + if subscriptionResource1Name == "" { + return nil, errors.New("parameter subscriptionResource1Name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionResource1Name}", url.PathEscape(subscriptionResource1Name)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *SubscriptionResource1OperationsClient) getHandleResponse(resp *http.Response) (SubscriptionResource1OperationsClientGetResponse, error) { + result := SubscriptionResource1OperationsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SubscriptionResource1); err != nil { + return SubscriptionResource1OperationsClientGetResponse{}, err + } + return result, nil +} + +// Put - Create a SubscriptionResource1 +// If the operation fails it returns an *azcore.ResponseError type. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - subscriptionResource1Name - The name of the SubscriptionResource1 +// - resource - Resource create parameters. +// - options - SubscriptionResource1OperationsClientPutOptions contains the optional parameters for the SubscriptionResource1OperationsClient.Put +// method. +func (client *SubscriptionResource1OperationsClient) Put(ctx context.Context, subscriptionID string, subscriptionResource1Name string, resource SubscriptionResource1, options *SubscriptionResource1OperationsClientPutOptions) (SubscriptionResource1OperationsClientPutResponse, error) { + var err error + const operationName = "SubscriptionResource1OperationsClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, subscriptionID, subscriptionResource1Name, resource, options) + if err != nil { + return SubscriptionResource1OperationsClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SubscriptionResource1OperationsClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return SubscriptionResource1OperationsClientPutResponse{}, err + } + resp, err := client.putHandleResponse(httpResp) + return resp, err +} + +// putCreateRequest creates the Put request. +func (client *SubscriptionResource1OperationsClient) putCreateRequest(ctx context.Context, subscriptionID string, subscriptionResource1Name string, resource SubscriptionResource1, _ *SubscriptionResource1OperationsClientPutOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Azure.ResourceManager.MethodSubscriptionId/subscriptionResource1s/{subscriptionResource1Name}" + if subscriptionID == "" { + return nil, errors.New("parameter subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(subscriptionID)) + if subscriptionResource1Name == "" { + return nil, errors.New("parameter subscriptionResource1Name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionResource1Name}", url.PathEscape(subscriptionResource1Name)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// putHandleResponse handles the Put response. +func (client *SubscriptionResource1OperationsClient) putHandleResponse(resp *http.Response) (SubscriptionResource1OperationsClientPutResponse, error) { + result := SubscriptionResource1OperationsClientPutResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SubscriptionResource1); err != nil { + return SubscriptionResource1OperationsClientPutResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_subscriptionresource2operations_client.go b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_subscriptionresource2operations_client.go new file mode 100644 index 000000000000..20df3e66e3fb --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_subscriptionresource2operations_client.go @@ -0,0 +1,210 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package methodsubscriptionidgroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// SubscriptionResource2OperationsClient contains the methods for the SubscriptionResource2Operations group. +// Don't use this type directly, use NewSubscriptionResource2OperationsClient() instead. +// +// Generated from API version 2023-12-01-preview +type SubscriptionResource2OperationsClient struct { + internal *arm.Client +} + +// NewSubscriptionResource2OperationsClient creates a new instance of SubscriptionResource2OperationsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewSubscriptionResource2OperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*SubscriptionResource2OperationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SubscriptionResource2OperationsClient{ + internal: cl, + } + return client, nil +} + +// Delete - Delete a SubscriptionResource2 +// If the operation fails it returns an *azcore.ResponseError type. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - subscriptionResource2Name - The name of the SubscriptionResource2 +// - options - SubscriptionResource2OperationsClientDeleteOptions contains the optional parameters for the SubscriptionResource2OperationsClient.Delete +// method. +func (client *SubscriptionResource2OperationsClient) Delete(ctx context.Context, subscriptionID string, subscriptionResource2Name string, options *SubscriptionResource2OperationsClientDeleteOptions) (SubscriptionResource2OperationsClientDeleteResponse, error) { + var err error + const operationName = "SubscriptionResource2OperationsClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, subscriptionID, subscriptionResource2Name, options) + if err != nil { + return SubscriptionResource2OperationsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SubscriptionResource2OperationsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SubscriptionResource2OperationsClientDeleteResponse{}, err + } + return SubscriptionResource2OperationsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *SubscriptionResource2OperationsClient) deleteCreateRequest(ctx context.Context, subscriptionID string, subscriptionResource2Name string, _ *SubscriptionResource2OperationsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Azure.ResourceManager.MethodSubscriptionId/subscriptionResource2s/{subscriptionResource2Name}" + if subscriptionID == "" { + return nil, errors.New("parameter subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(subscriptionID)) + if subscriptionResource2Name == "" { + return nil, errors.New("parameter subscriptionResource2Name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionResource2Name}", url.PathEscape(subscriptionResource2Name)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a SubscriptionResource2 +// If the operation fails it returns an *azcore.ResponseError type. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - subscriptionResource2Name - The name of the SubscriptionResource2 +// - options - SubscriptionResource2OperationsClientGetOptions contains the optional parameters for the SubscriptionResource2OperationsClient.Get +// method. +func (client *SubscriptionResource2OperationsClient) Get(ctx context.Context, subscriptionID string, subscriptionResource2Name string, options *SubscriptionResource2OperationsClientGetOptions) (SubscriptionResource2OperationsClientGetResponse, error) { + var err error + const operationName = "SubscriptionResource2OperationsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, subscriptionID, subscriptionResource2Name, options) + if err != nil { + return SubscriptionResource2OperationsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SubscriptionResource2OperationsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SubscriptionResource2OperationsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *SubscriptionResource2OperationsClient) getCreateRequest(ctx context.Context, subscriptionID string, subscriptionResource2Name string, _ *SubscriptionResource2OperationsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Azure.ResourceManager.MethodSubscriptionId/subscriptionResource2s/{subscriptionResource2Name}" + if subscriptionID == "" { + return nil, errors.New("parameter subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(subscriptionID)) + if subscriptionResource2Name == "" { + return nil, errors.New("parameter subscriptionResource2Name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionResource2Name}", url.PathEscape(subscriptionResource2Name)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *SubscriptionResource2OperationsClient) getHandleResponse(resp *http.Response) (SubscriptionResource2OperationsClientGetResponse, error) { + result := SubscriptionResource2OperationsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SubscriptionResource2); err != nil { + return SubscriptionResource2OperationsClientGetResponse{}, err + } + return result, nil +} + +// Put - Create a SubscriptionResource2 +// If the operation fails it returns an *azcore.ResponseError type. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - subscriptionResource2Name - The name of the SubscriptionResource2 +// - resource - Resource create parameters. +// - options - SubscriptionResource2OperationsClientPutOptions contains the optional parameters for the SubscriptionResource2OperationsClient.Put +// method. +func (client *SubscriptionResource2OperationsClient) Put(ctx context.Context, subscriptionID string, subscriptionResource2Name string, resource SubscriptionResource2, options *SubscriptionResource2OperationsClientPutOptions) (SubscriptionResource2OperationsClientPutResponse, error) { + var err error + const operationName = "SubscriptionResource2OperationsClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, subscriptionID, subscriptionResource2Name, resource, options) + if err != nil { + return SubscriptionResource2OperationsClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SubscriptionResource2OperationsClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return SubscriptionResource2OperationsClientPutResponse{}, err + } + resp, err := client.putHandleResponse(httpResp) + return resp, err +} + +// putCreateRequest creates the Put request. +func (client *SubscriptionResource2OperationsClient) putCreateRequest(ctx context.Context, subscriptionID string, subscriptionResource2Name string, resource SubscriptionResource2, _ *SubscriptionResource2OperationsClientPutOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Azure.ResourceManager.MethodSubscriptionId/subscriptionResource2s/{subscriptionResource2Name}" + if subscriptionID == "" { + return nil, errors.New("parameter subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(subscriptionID)) + if subscriptionResource2Name == "" { + return nil, errors.New("parameter subscriptionResource2Name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionResource2Name}", url.PathEscape(subscriptionResource2Name)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// putHandleResponse handles the Put response. +func (client *SubscriptionResource2OperationsClient) putHandleResponse(resp *http.Response) (SubscriptionResource2OperationsClientPutResponse, error) { + result := SubscriptionResource2OperationsClientPutResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SubscriptionResource2); err != nil { + return SubscriptionResource2OperationsClientPutResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_subscriptionresourceoperations_client.go b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_subscriptionresourceoperations_client.go new file mode 100644 index 000000000000..9434b1b27318 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_subscriptionresourceoperations_client.go @@ -0,0 +1,210 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package methodsubscriptionidgroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// SubscriptionResourceOperationsClient contains the methods for the SubscriptionResourceOperations group. +// Don't use this type directly, use NewSubscriptionResourceOperationsClient() instead. +// +// Generated from API version 2023-12-01-preview +type SubscriptionResourceOperationsClient struct { + internal *arm.Client +} + +// NewSubscriptionResourceOperationsClient creates a new instance of SubscriptionResourceOperationsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewSubscriptionResourceOperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*SubscriptionResourceOperationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SubscriptionResourceOperationsClient{ + internal: cl, + } + return client, nil +} + +// Delete - Delete a SubscriptionResource +// If the operation fails it returns an *azcore.ResponseError type. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - subscriptionResourceName - The name of the SubscriptionResource +// - options - SubscriptionResourceOperationsClientDeleteOptions contains the optional parameters for the SubscriptionResourceOperationsClient.Delete +// method. +func (client *SubscriptionResourceOperationsClient) Delete(ctx context.Context, subscriptionID string, subscriptionResourceName string, options *SubscriptionResourceOperationsClientDeleteOptions) (SubscriptionResourceOperationsClientDeleteResponse, error) { + var err error + const operationName = "SubscriptionResourceOperationsClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, subscriptionID, subscriptionResourceName, options) + if err != nil { + return SubscriptionResourceOperationsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SubscriptionResourceOperationsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SubscriptionResourceOperationsClientDeleteResponse{}, err + } + return SubscriptionResourceOperationsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *SubscriptionResourceOperationsClient) deleteCreateRequest(ctx context.Context, subscriptionID string, subscriptionResourceName string, _ *SubscriptionResourceOperationsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Azure.ResourceManager.MethodSubscriptionId/subscriptionResources/{subscriptionResourceName}" + if subscriptionID == "" { + return nil, errors.New("parameter subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(subscriptionID)) + if subscriptionResourceName == "" { + return nil, errors.New("parameter subscriptionResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionResourceName}", url.PathEscape(subscriptionResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a SubscriptionResource +// If the operation fails it returns an *azcore.ResponseError type. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - subscriptionResourceName - The name of the SubscriptionResource +// - options - SubscriptionResourceOperationsClientGetOptions contains the optional parameters for the SubscriptionResourceOperationsClient.Get +// method. +func (client *SubscriptionResourceOperationsClient) Get(ctx context.Context, subscriptionID string, subscriptionResourceName string, options *SubscriptionResourceOperationsClientGetOptions) (SubscriptionResourceOperationsClientGetResponse, error) { + var err error + const operationName = "SubscriptionResourceOperationsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, subscriptionID, subscriptionResourceName, options) + if err != nil { + return SubscriptionResourceOperationsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SubscriptionResourceOperationsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SubscriptionResourceOperationsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *SubscriptionResourceOperationsClient) getCreateRequest(ctx context.Context, subscriptionID string, subscriptionResourceName string, _ *SubscriptionResourceOperationsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Azure.ResourceManager.MethodSubscriptionId/subscriptionResources/{subscriptionResourceName}" + if subscriptionID == "" { + return nil, errors.New("parameter subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(subscriptionID)) + if subscriptionResourceName == "" { + return nil, errors.New("parameter subscriptionResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionResourceName}", url.PathEscape(subscriptionResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *SubscriptionResourceOperationsClient) getHandleResponse(resp *http.Response) (SubscriptionResourceOperationsClientGetResponse, error) { + result := SubscriptionResourceOperationsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SubscriptionResource); err != nil { + return SubscriptionResourceOperationsClientGetResponse{}, err + } + return result, nil +} + +// Put - Create a SubscriptionResource +// If the operation fails it returns an *azcore.ResponseError type. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - subscriptionResourceName - The name of the SubscriptionResource +// - resource - Resource create parameters. +// - options - SubscriptionResourceOperationsClientPutOptions contains the optional parameters for the SubscriptionResourceOperationsClient.Put +// method. +func (client *SubscriptionResourceOperationsClient) Put(ctx context.Context, subscriptionID string, subscriptionResourceName string, resource SubscriptionResource, options *SubscriptionResourceOperationsClientPutOptions) (SubscriptionResourceOperationsClientPutResponse, error) { + var err error + const operationName = "SubscriptionResourceOperationsClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, subscriptionID, subscriptionResourceName, resource, options) + if err != nil { + return SubscriptionResourceOperationsClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SubscriptionResourceOperationsClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return SubscriptionResourceOperationsClientPutResponse{}, err + } + resp, err := client.putHandleResponse(httpResp) + return resp, err +} + +// putCreateRequest creates the Put request. +func (client *SubscriptionResourceOperationsClient) putCreateRequest(ctx context.Context, subscriptionID string, subscriptionResourceName string, resource SubscriptionResource, _ *SubscriptionResourceOperationsClientPutOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Azure.ResourceManager.MethodSubscriptionId/subscriptionResources/{subscriptionResourceName}" + if subscriptionID == "" { + return nil, errors.New("parameter subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(subscriptionID)) + if subscriptionResourceName == "" { + return nil, errors.New("parameter subscriptionResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionResourceName}", url.PathEscape(subscriptionResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// putHandleResponse handles the Put response. +func (client *SubscriptionResourceOperationsClient) putHandleResponse(resp *http.Response) (SubscriptionResourceOperationsClientPutResponse, error) { + result := SubscriptionResourceOperationsClientPutResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SubscriptionResource); err != nil { + return SubscriptionResourceOperationsClientPutResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_version.go b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_version.go new file mode 100644 index 000000000000..ea0539b3355e --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/methodsubscriptionidgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package methodsubscriptionidgroup + +const ( + moduleName = "methodsubscriptionidgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/resource-manager/nonresourcegroup/LICENSE.txt b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/resource-manager/nonresourcegroup/fake/zz_internal.go b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/azure-http-specs/azure/resource-manager/nonresourcegroup/fake/zz_nonresourceoperations_server.go b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/fake/zz_nonresourceoperations_server.go new file mode 100644 index 000000000000..1dd5e9b01e7f --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/fake/zz_nonresourceoperations_server.go @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "nonresourcegroup" + "regexp" + "slices" +) + +// NonResourceOperationsServer is a fake server for instances of the nonresourcegroup.NonResourceOperationsClient type. +type NonResourceOperationsServer struct { + // Create is the fake for method NonResourceOperationsClient.Create + // HTTP status codes to indicate success: http.StatusOK + Create func(ctx context.Context, location string, parameter string, body nonresourcegroup.NonResource, options *nonresourcegroup.NonResourceOperationsClientCreateOptions) (resp azfake.Responder[nonresourcegroup.NonResourceOperationsClientCreateResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method NonResourceOperationsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, location string, parameter string, options *nonresourcegroup.NonResourceOperationsClientGetOptions) (resp azfake.Responder[nonresourcegroup.NonResourceOperationsClientGetResponse], errResp azfake.ErrorResponder) +} + +// NewNonResourceOperationsServerTransport creates a new instance of NonResourceOperationsServerTransport with the provided implementation. +// The returned NonResourceOperationsServerTransport instance is connected to an instance of nonresourcegroup.NonResourceOperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewNonResourceOperationsServerTransport(srv *NonResourceOperationsServer) *NonResourceOperationsServerTransport { + return &NonResourceOperationsServerTransport{srv: srv} +} + +// NonResourceOperationsServerTransport connects instances of nonresourcegroup.NonResourceOperationsClient to instances of NonResourceOperationsServer. +// Don't use this type directly, use NewNonResourceOperationsServerTransport instead. +type NonResourceOperationsServerTransport struct { + srv *NonResourceOperationsServer +} + +// Do implements the policy.Transporter interface for NonResourceOperationsServerTransport. +func (n *NonResourceOperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return n.dispatchToMethodFake(req, method) +} + +func (n *NonResourceOperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if nonResourceOperationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = nonResourceOperationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "NonResourceOperationsClient.Create": + res.resp, res.err = n.dispatchCreate(req) + case "NonResourceOperationsClient.Get": + res.resp, res.err = n.dispatchGet(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (n *NonResourceOperationsServerTransport) dispatchCreate(req *http.Request) (*http.Response, error) { + if n.srv.Create == nil { + return nil, &nonRetriableError{errors.New("fake for method Create not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.NonResource/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/otherParameters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[nonresourcegroup.NonResource](req) + if err != nil { + return nil, err + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + parameterParam, err := url.PathUnescape(matches[regex.SubexpIndex("parameter")]) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.Create(req.Context(), locationParam, parameterParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).NonResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NonResourceOperationsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if n.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.NonResource/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/otherParameters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + parameterParam, err := url.PathUnescape(matches[regex.SubexpIndex("parameter")]) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.Get(req.Context(), locationParam, parameterParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).NonResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to NonResourceOperationsServerTransport +var nonResourceOperationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/resource-manager/nonresourcegroup/fake/zz_server_factory.go b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/fake/zz_server_factory.go new file mode 100644 index 000000000000..f6e1d33066ed --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/fake/zz_server_factory.go @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the nonresourcegroup.ClientFactory type. +type ServerFactory struct { + // NonResourceOperationsServer contains the fakes for client NonResourceOperationsClient + NonResourceOperationsServer NonResourceOperationsServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of nonresourcegroup.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of nonresourcegroup.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trNonResourceOperationsServer *NonResourceOperationsServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "NonResourceOperationsClient": + initServer(&s.trMu, &s.trNonResourceOperationsServer, func() *NonResourceOperationsServerTransport { + return NewNonResourceOperationsServerTransport(&s.srv.NonResourceOperationsServer) + }) + resp, err = s.trNonResourceOperationsServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/nonresourcegroup/go.mod b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/go.mod new file mode 100644 index 000000000000..eb30f13bfe00 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/go.mod @@ -0,0 +1,17 @@ +module nonresourcegroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/resource-manager/nonresourcegroup/go.sum b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/resource-manager/nonresourcegroup/nonresourceoperations_client_test.go b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/nonresourceoperations_client_test.go new file mode 100644 index 000000000000..728ec3fc6321 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/nonresourceoperations_client_test.go @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package nonresourcegroup + +import ( + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestNewNonResourceOperationsClient_Create(t *testing.T) { + body := NonResource{ + ID: to.Ptr("id"), + Name: to.Ptr("hello"), + Type: to.Ptr("nonResource"), + } + + resp, err := clientFactory.NewNonResourceOperationsClient().Create(ctx, locationExpected, "hello", body, nil) + require.NoError(t, err) + require.Equal(t, resp.ID, to.Ptr("id")) + require.Equal(t, resp.Name, to.Ptr("hello")) + require.Equal(t, resp.Type, to.Ptr("nonResource")) +} + +func TestNewNonResourceOperationsClient_Get(t *testing.T) { + resp, err := clientFactory.NewNonResourceOperationsClient().Get(ctx, locationExpected, "hello", nil) + require.NoError(t, err) + require.Equal(t, resp.ID, to.Ptr("id")) + require.Equal(t, resp.Name, to.Ptr("hello")) + require.Equal(t, resp.Type, to.Ptr("nonResource")) +} diff --git a/test/azure-http-specs/azure/resource-manager/nonresourcegroup/testdata/_metadata.json b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/testdata/_metadata.json new file mode 100644 index 000000000000..989376212e0f --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Azure.ResourceManager.NonResource": "2023-12-01-preview" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/resource-manager/nonresourcegroup/utils_test.go b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/utils_test.go new file mode 100644 index 000000000000..6061c3b9fab0 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/utils_test.go @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package nonresourcegroup + +import ( + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" +) + +var ( + ctx context.Context + clientFactory *ClientFactory + + subscriptionIdExpected = "00000000-0000-0000-0000-000000000000" + locationExpected = "eastus" +) + +func TestMain(m *testing.M) { + ctx = context.Background() + clientFactory, _ = NewClientFactory(subscriptionIdExpected, &azfake.TokenCredential{}, &arm.ClientOptions{ + ClientOptions: azcore.ClientOptions{ + Cloud: cloud.Configuration{ + Services: map[cloud.ServiceName]cloud.ServiceConfiguration{ + cloud.ResourceManager: { + Audience: "fake_audience", + Endpoint: "http://localhost:3000", + }, + }, + }, + InsecureAllowCredentialWithHTTP: true, + }, + }) + + m.Run() +} diff --git a/test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_client_factory.go b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_client_factory.go new file mode 100644 index 000000000000..5e1f579ef104 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_client_factory.go @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nonresourcegroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + subscriptionID string + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, + internal: internal, + }, nil +} + +// NewNonResourceOperationsClient creates a new instance of NonResourceOperationsClient. +func (c *ClientFactory) NewNonResourceOperationsClient() *NonResourceOperationsClient { + return &NonResourceOperationsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} diff --git a/test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_constants.go b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_constants.go new file mode 100644 index 000000000000..08942944850a --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_constants.go @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nonresourcegroup + +const ( + version20231201Preview string = "2023-12-01-preview" +) diff --git a/test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_models.go b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_models.go new file mode 100644 index 000000000000..701950119ff0 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_models.go @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nonresourcegroup + +// NonResource - Though this model has `id`, `name`, `type` properties, it is not a resource as it doesn't extends `Resource`. +type NonResource struct { + // An id. + ID *string + + // A name. + Name *string + + // A type. + Type *string +} diff --git a/test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_models_serde.go b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_models_serde.go new file mode 100644 index 000000000000..d48b8c8e5980 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_models_serde.go @@ -0,0 +1,67 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nonresourcegroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type NonResource. +func (n NonResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", n.ID) + populate(objectMap, "name", n.Name) + populate(objectMap, "type", n.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NonResource. +func (n *NonResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &n.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &n.Name) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &n.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_nonresourceoperations_client.go b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_nonresourceoperations_client.go new file mode 100644 index 000000000000..1ff5ae6472e3 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_nonresourceoperations_client.go @@ -0,0 +1,173 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nonresourcegroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// NonResourceOperationsClient - Operations on non resource model should not be marked as `@armResourceOperations`. +// Don't use this type directly, use NewNonResourceOperationsClient() instead. +// +// Generated from API version 2023-12-01-preview +type NonResourceOperationsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewNonResourceOperationsClient creates a new instance of NonResourceOperationsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewNonResourceOperationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*NonResourceOperationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &NonResourceOperationsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Create - +// If the operation fails it returns an *azcore.ResponseError type. +// - location - The location parameter. +// - parameter - Another parameter. +// - body - The request body. +// - options - NonResourceOperationsClientCreateOptions contains the optional parameters for the NonResourceOperationsClient.Create +// method. +func (client *NonResourceOperationsClient) Create(ctx context.Context, location string, parameter string, body NonResource, options *NonResourceOperationsClientCreateOptions) (NonResourceOperationsClientCreateResponse, error) { + var err error + const operationName = "NonResourceOperationsClient.Create" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, location, parameter, body, options) + if err != nil { + return NonResourceOperationsClientCreateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NonResourceOperationsClientCreateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NonResourceOperationsClientCreateResponse{}, err + } + resp, err := client.createHandleResponse(httpResp) + return resp, err +} + +// createCreateRequest creates the Create request. +func (client *NonResourceOperationsClient) createCreateRequest(ctx context.Context, location string, parameter string, body NonResource, _ *NonResourceOperationsClientCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.NonResource/locations/{location}/otherParameters/{parameter}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if parameter == "" { + return nil, errors.New("parameter parameter cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{parameter}", url.PathEscape(parameter)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// createHandleResponse handles the Create response. +func (client *NonResourceOperationsClient) createHandleResponse(resp *http.Response) (NonResourceOperationsClientCreateResponse, error) { + result := NonResourceOperationsClientCreateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.NonResource); err != nil { + return NonResourceOperationsClientCreateResponse{}, err + } + return result, nil +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - location - The location parameter. +// - parameter - Another parameter. +// - options - NonResourceOperationsClientGetOptions contains the optional parameters for the NonResourceOperationsClient.Get +// method. +func (client *NonResourceOperationsClient) Get(ctx context.Context, location string, parameter string, options *NonResourceOperationsClientGetOptions) (NonResourceOperationsClientGetResponse, error) { + var err error + const operationName = "NonResourceOperationsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, location, parameter, options) + if err != nil { + return NonResourceOperationsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NonResourceOperationsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NonResourceOperationsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *NonResourceOperationsClient) getCreateRequest(ctx context.Context, location string, parameter string, _ *NonResourceOperationsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.NonResource/locations/{location}/otherParameters/{parameter}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if parameter == "" { + return nil, errors.New("parameter parameter cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{parameter}", url.PathEscape(parameter)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *NonResourceOperationsClient) getHandleResponse(resp *http.Response) (NonResourceOperationsClientGetResponse, error) { + result := NonResourceOperationsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.NonResource); err != nil { + return NonResourceOperationsClientGetResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_options.go b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_options.go new file mode 100644 index 000000000000..11ea0818bad4 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_options.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nonresourcegroup + +// NonResourceOperationsClientCreateOptions contains the optional parameters for the NonResourceOperationsClient.Create method. +type NonResourceOperationsClientCreateOptions struct { + // placeholder for future optional parameters +} + +// NonResourceOperationsClientGetOptions contains the optional parameters for the NonResourceOperationsClient.Get method. +type NonResourceOperationsClientGetOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_responses.go b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_responses.go new file mode 100644 index 000000000000..a287cae96261 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_responses.go @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nonresourcegroup + +// NonResourceOperationsClientCreateResponse contains the response from method NonResourceOperationsClient.Create. +type NonResourceOperationsClientCreateResponse struct { + // Though this model has `id`, `name`, `type` properties, it is not a resource as it doesn't extends `Resource`. + NonResource +} + +// NonResourceOperationsClientGetResponse contains the response from method NonResourceOperationsClient.Get. +type NonResourceOperationsClientGetResponse struct { + // Though this model has `id`, `name`, `type` properties, it is not a resource as it doesn't extends `Resource`. + NonResource +} diff --git a/test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_version.go b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_version.go new file mode 100644 index 000000000000..e620ddb04ab3 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/nonresourcegroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package nonresourcegroup + +const ( + moduleName = "nonresourcegroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/resource-manager/resources/LICENSE.txt b/test/azure-http-specs/azure/resource-manager/resources/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/resource-manager/resources/extensionsresources_client_test.go b/test/azure-http-specs/azure/resource-manager/resources/extensionsresources_client_test.go new file mode 100644 index 000000000000..d62ae75ef765 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/extensionsresources_client_test.go @@ -0,0 +1,435 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package resources_test + +import ( + "context" + "resources" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestExtensionsResourcesClient_BeginCreateOrUpdate(t *testing.T) { + poller, err := clientFactory.NewExtensionsResourcesClient().BeginCreateOrUpdate(context.Background(), "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg", "extension", resources.ExtensionsResource{ + Properties: &resources.ExtensionsResourceProperties{ + Description: to.Ptr("valid"), + }, + }, nil) + require.NoError(t, err) + resp, err := poller.PollUntilDone(context.Background(), &runtime.PollUntilDoneOptions{ + Frequency: 1 * time.Second, + }) + require.NoError(t, err) + require.Equal(t, resources.ExtensionsResource{ + Properties: &resources.ExtensionsResourceProperties{ + Description: to.Ptr("valid"), + ProvisioningState: to.Ptr(resources.ProvisioningStateSucceeded), + }, + Name: to.Ptr("extension"), + ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Azure.ResourceManager.Resources/extensionsResources/extension"), + SystemData: &resources.SystemData{ + CreatedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + CreatedBy: to.Ptr("AzureSDK"), + CreatedByType: to.Ptr(resources.CreatedByTypeUser), + LastModifiedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + LastModifiedBy: to.Ptr("AzureSDK"), + LastModifiedByType: to.Ptr(resources.CreatedByTypeUser), + }, + Type: to.Ptr("Azure.ResourceManager.Resources/extensionsResources"), + }, resp.ExtensionsResource) + + poller2, err := clientFactory.NewExtensionsResourcesClient().BeginCreateOrUpdate(context.Background(), "/subscriptions/00000000-0000-0000-0000-000000000000", "extension", resources.ExtensionsResource{ + Properties: &resources.ExtensionsResourceProperties{ + Description: to.Ptr("valid"), + }, + }, nil) + require.NoError(t, err) + resp, err = poller2.PollUntilDone(context.Background(), &runtime.PollUntilDoneOptions{ + Frequency: 1 * time.Second, + }) + require.NoError(t, err) + require.Equal(t, resources.ExtensionsResource{ + Properties: &resources.ExtensionsResourceProperties{ + Description: to.Ptr("valid"), + ProvisioningState: to.Ptr(resources.ProvisioningStateSucceeded), + }, + Name: to.Ptr("extension"), + ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/providers/Azure.ResourceManager.Resources/extensionsResources/extension"), + SystemData: &resources.SystemData{ + CreatedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + CreatedBy: to.Ptr("AzureSDK"), + CreatedByType: to.Ptr(resources.CreatedByTypeUser), + LastModifiedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + LastModifiedBy: to.Ptr("AzureSDK"), + LastModifiedByType: to.Ptr(resources.CreatedByTypeUser), + }, + Type: to.Ptr("Azure.ResourceManager.Resources/extensionsResources"), + }, resp.ExtensionsResource) + + poller3, err := clientFactory.NewExtensionsResourcesClient().BeginCreateOrUpdate(context.Background(), "/", "extension", resources.ExtensionsResource{ + Properties: &resources.ExtensionsResourceProperties{ + Description: to.Ptr("valid"), + }, + }, nil) + require.NoError(t, err) + resp, err = poller3.PollUntilDone(context.Background(), &runtime.PollUntilDoneOptions{ + Frequency: 1 * time.Second, + }) + require.NoError(t, err) + require.Equal(t, resources.ExtensionsResource{ + Properties: &resources.ExtensionsResourceProperties{ + Description: to.Ptr("valid"), + ProvisioningState: to.Ptr(resources.ProvisioningStateSucceeded), + }, + Name: to.Ptr("extension"), + ID: to.Ptr("/providers/Azure.ResourceManager.Resources/extensionsResources/extension"), + SystemData: &resources.SystemData{ + CreatedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + CreatedBy: to.Ptr("AzureSDK"), + CreatedByType: to.Ptr(resources.CreatedByTypeUser), + LastModifiedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + LastModifiedBy: to.Ptr("AzureSDK"), + LastModifiedByType: to.Ptr(resources.CreatedByTypeUser), + }, + Type: to.Ptr("Azure.ResourceManager.Resources/extensionsResources"), + }, resp.ExtensionsResource) + + poller4, err := clientFactory.NewExtensionsResourcesClient().BeginCreateOrUpdate(context.Background(), "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Azure.ResourceManager.Resources/topLevelTrackedResources/top", "extension", resources.ExtensionsResource{ + Properties: &resources.ExtensionsResourceProperties{ + Description: to.Ptr("valid"), + }, + }, nil) + require.NoError(t, err) + resp, err = poller4.PollUntilDone(context.Background(), &runtime.PollUntilDoneOptions{ + Frequency: 1 * time.Second, + }) + require.NoError(t, err) + require.Equal(t, resources.ExtensionsResource{ + Properties: &resources.ExtensionsResourceProperties{ + Description: to.Ptr("valid"), + ProvisioningState: to.Ptr(resources.ProvisioningStateSucceeded), + }, + Name: to.Ptr("extension"), + ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Azure.ResourceManager.Resources/topLevelTrackedResources/top/providers/Azure.ResourceManager.Resources/extensionsResources/extension"), + SystemData: &resources.SystemData{ + CreatedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + CreatedBy: to.Ptr("AzureSDK"), + CreatedByType: to.Ptr(resources.CreatedByTypeUser), + LastModifiedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + LastModifiedBy: to.Ptr("AzureSDK"), + LastModifiedByType: to.Ptr(resources.CreatedByTypeUser), + }, + Type: to.Ptr("Azure.ResourceManager.Resources/extensionsResources"), + }, resp.ExtensionsResource) + +} + +func TestExtensionsResourcesClient_Delete(t *testing.T) { + resp, err := clientFactory.NewExtensionsResourcesClient().Delete(context.Background(), "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg", "extension", nil) + require.NoError(t, err) + require.Zero(t, resp) + resp, err = clientFactory.NewExtensionsResourcesClient().Delete(context.Background(), "/subscriptions/00000000-0000-0000-0000-000000000000", "extension", nil) + require.NoError(t, err) + require.Zero(t, resp) + resp, err = clientFactory.NewExtensionsResourcesClient().Delete(context.Background(), "/", "extension", nil) + require.NoError(t, err) + require.Zero(t, resp) + resp, err = clientFactory.NewExtensionsResourcesClient().Delete(context.Background(), "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Azure.ResourceManager.Resources/topLevelTrackedResources/top", "extension", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestExtensionsResourcesClient_Get(t *testing.T) { + resp, err := clientFactory.NewExtensionsResourcesClient().Get(context.Background(), "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg", "extension", nil) + require.NoError(t, err) + require.Equal(t, resources.ExtensionsResource{ + Properties: &resources.ExtensionsResourceProperties{ + Description: to.Ptr("valid"), + ProvisioningState: to.Ptr(resources.ProvisioningStateSucceeded), + }, + Name: to.Ptr("extension"), + ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Azure.ResourceManager.Resources/extensionsResources/extension"), + SystemData: &resources.SystemData{ + CreatedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + CreatedBy: to.Ptr("AzureSDK"), + CreatedByType: to.Ptr(resources.CreatedByTypeUser), + LastModifiedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + LastModifiedBy: to.Ptr("AzureSDK"), + LastModifiedByType: to.Ptr(resources.CreatedByTypeUser), + }, + Type: to.Ptr("Azure.ResourceManager.Resources/extensionsResources"), + }, resp.ExtensionsResource) + + resp, err = clientFactory.NewExtensionsResourcesClient().Get(context.Background(), "/subscriptions/00000000-0000-0000-0000-000000000000", "extension", nil) + require.NoError(t, err) + require.Equal(t, resources.ExtensionsResource{ + Properties: &resources.ExtensionsResourceProperties{ + Description: to.Ptr("valid"), + ProvisioningState: to.Ptr(resources.ProvisioningStateSucceeded), + }, + Name: to.Ptr("extension"), + ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/providers/Azure.ResourceManager.Resources/extensionsResources/extension"), + SystemData: &resources.SystemData{ + CreatedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + CreatedBy: to.Ptr("AzureSDK"), + CreatedByType: to.Ptr(resources.CreatedByTypeUser), + LastModifiedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + LastModifiedBy: to.Ptr("AzureSDK"), + LastModifiedByType: to.Ptr(resources.CreatedByTypeUser), + }, + Type: to.Ptr("Azure.ResourceManager.Resources/extensionsResources"), + }, resp.ExtensionsResource) + + resp, err = clientFactory.NewExtensionsResourcesClient().Get(context.Background(), "/", "extension", nil) + require.NoError(t, err) + require.Equal(t, resources.ExtensionsResource{ + Properties: &resources.ExtensionsResourceProperties{ + Description: to.Ptr("valid"), + ProvisioningState: to.Ptr(resources.ProvisioningStateSucceeded), + }, + Name: to.Ptr("extension"), + ID: to.Ptr("/providers/Azure.ResourceManager.Resources/extensionsResources/extension"), + SystemData: &resources.SystemData{ + CreatedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + CreatedBy: to.Ptr("AzureSDK"), + CreatedByType: to.Ptr(resources.CreatedByTypeUser), + LastModifiedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + LastModifiedBy: to.Ptr("AzureSDK"), + LastModifiedByType: to.Ptr(resources.CreatedByTypeUser), + }, + Type: to.Ptr("Azure.ResourceManager.Resources/extensionsResources"), + }, resp.ExtensionsResource) + + resp, err = clientFactory.NewExtensionsResourcesClient().Get(context.Background(), "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Azure.ResourceManager.Resources/topLevelTrackedResources/top", "extension", nil) + require.NoError(t, err) + require.Equal(t, resources.ExtensionsResource{ + Properties: &resources.ExtensionsResourceProperties{ + Description: to.Ptr("valid"), + ProvisioningState: to.Ptr(resources.ProvisioningStateSucceeded), + }, + Name: to.Ptr("extension"), + ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Azure.ResourceManager.Resources/topLevelTrackedResources/top/providers/Azure.ResourceManager.Resources/extensionsResources/extension"), + SystemData: &resources.SystemData{ + CreatedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + CreatedBy: to.Ptr("AzureSDK"), + CreatedByType: to.Ptr(resources.CreatedByTypeUser), + LastModifiedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + LastModifiedBy: to.Ptr("AzureSDK"), + LastModifiedByType: to.Ptr(resources.CreatedByTypeUser), + }, + Type: to.Ptr("Azure.ResourceManager.Resources/extensionsResources"), + }, resp.ExtensionsResource) +} + +func TestExtensionsResourcesClient_NewListByScopePager(t *testing.T) { + pager := clientFactory.NewExtensionsResourcesClient().NewListByScopePager("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg", nil) + pageCount := 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + require.Len(t, page.Value, 1) + require.Equal(t, &resources.ExtensionsResource{ + Properties: &resources.ExtensionsResourceProperties{ + Description: to.Ptr("valid"), + ProvisioningState: to.Ptr(resources.ProvisioningStateSucceeded), + }, + Name: to.Ptr("extension"), + ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Azure.ResourceManager.Resources/extensionsResources/extension"), + SystemData: &resources.SystemData{ + CreatedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + CreatedBy: to.Ptr("AzureSDK"), + CreatedByType: to.Ptr(resources.CreatedByTypeUser), + LastModifiedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + LastModifiedBy: to.Ptr("AzureSDK"), + LastModifiedByType: to.Ptr(resources.CreatedByTypeUser), + }, + Type: to.Ptr("Azure.ResourceManager.Resources/extensionsResources"), + }, page.Value[0]) + pageCount++ + } + require.EqualValues(t, 1, pageCount) + + pager = clientFactory.NewExtensionsResourcesClient().NewListByScopePager("/subscriptions/00000000-0000-0000-0000-000000000000", nil) + pageCount = 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + require.Len(t, page.Value, 1) + require.Equal(t, &resources.ExtensionsResource{ + Properties: &resources.ExtensionsResourceProperties{ + Description: to.Ptr("valid"), + ProvisioningState: to.Ptr(resources.ProvisioningStateSucceeded), + }, + Name: to.Ptr("extension"), + ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/providers/Azure.ResourceManager.Resources/extensionsResources/extension"), + SystemData: &resources.SystemData{ + CreatedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + CreatedBy: to.Ptr("AzureSDK"), + CreatedByType: to.Ptr(resources.CreatedByTypeUser), + LastModifiedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + LastModifiedBy: to.Ptr("AzureSDK"), + LastModifiedByType: to.Ptr(resources.CreatedByTypeUser), + }, + Type: to.Ptr("Azure.ResourceManager.Resources/extensionsResources"), + }, page.Value[0]) + pageCount++ + } + require.EqualValues(t, 1, pageCount) + + pager = clientFactory.NewExtensionsResourcesClient().NewListByScopePager("/", nil) + pageCount = 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + require.Len(t, page.Value, 1) + require.Equal(t, &resources.ExtensionsResource{ + Properties: &resources.ExtensionsResourceProperties{ + Description: to.Ptr("valid"), + ProvisioningState: to.Ptr(resources.ProvisioningStateSucceeded), + }, + Name: to.Ptr("extension"), + ID: to.Ptr("/providers/Azure.ResourceManager.Resources/extensionsResources/extension"), + SystemData: &resources.SystemData{ + CreatedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + CreatedBy: to.Ptr("AzureSDK"), + CreatedByType: to.Ptr(resources.CreatedByTypeUser), + LastModifiedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + LastModifiedBy: to.Ptr("AzureSDK"), + LastModifiedByType: to.Ptr(resources.CreatedByTypeUser), + }, + Type: to.Ptr("Azure.ResourceManager.Resources/extensionsResources"), + }, page.Value[0]) + pageCount++ + } + require.EqualValues(t, 1, pageCount) + + pager = clientFactory.NewExtensionsResourcesClient().NewListByScopePager("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Azure.ResourceManager.Resources/topLevelTrackedResources/top", nil) + pageCount = 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + require.Len(t, page.Value, 1) + require.Equal(t, &resources.ExtensionsResource{ + Properties: &resources.ExtensionsResourceProperties{ + Description: to.Ptr("valid"), + ProvisioningState: to.Ptr(resources.ProvisioningStateSucceeded), + }, + Name: to.Ptr("extension"), + ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Azure.ResourceManager.Resources/topLevelTrackedResources/top/providers/Azure.ResourceManager.Resources/extensionsResources/extension"), + SystemData: &resources.SystemData{ + CreatedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + CreatedBy: to.Ptr("AzureSDK"), + CreatedByType: to.Ptr(resources.CreatedByTypeUser), + LastModifiedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + LastModifiedBy: to.Ptr("AzureSDK"), + LastModifiedByType: to.Ptr(resources.CreatedByTypeUser), + }, + Type: to.Ptr("Azure.ResourceManager.Resources/extensionsResources"), + }, page.Value[0]) + pageCount++ + } + require.EqualValues(t, 1, pageCount) +} + +func TestExtensionsResourcesClient_Update(t *testing.T) { + resp, err := clientFactory.NewExtensionsResourcesClient().Update(context.Background(), "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg", "extension", resources.ExtensionsResource{ + Properties: &resources.ExtensionsResourceProperties{ + Description: to.Ptr("valid2"), + }, + }, nil) + require.NoError(t, err) + require.Equal(t, resources.ExtensionsResource{ + Properties: &resources.ExtensionsResourceProperties{ + Description: to.Ptr("valid2"), + ProvisioningState: to.Ptr(resources.ProvisioningStateSucceeded), + }, + Name: to.Ptr("extension"), + ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Azure.ResourceManager.Resources/extensionsResources/extension"), + SystemData: &resources.SystemData{ + CreatedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + CreatedBy: to.Ptr("AzureSDK"), + CreatedByType: to.Ptr(resources.CreatedByTypeUser), + LastModifiedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + LastModifiedBy: to.Ptr("AzureSDK"), + LastModifiedByType: to.Ptr(resources.CreatedByTypeUser), + }, + Type: to.Ptr("Azure.ResourceManager.Resources/extensionsResources"), + }, resp.ExtensionsResource) + + resp, err = clientFactory.NewExtensionsResourcesClient().Update(context.Background(), "/subscriptions/00000000-0000-0000-0000-000000000000", "extension", resources.ExtensionsResource{ + Properties: &resources.ExtensionsResourceProperties{ + Description: to.Ptr("valid2"), + }, + }, nil) + require.NoError(t, err) + require.Equal(t, resources.ExtensionsResource{ + Properties: &resources.ExtensionsResourceProperties{ + Description: to.Ptr("valid2"), + ProvisioningState: to.Ptr(resources.ProvisioningStateSucceeded), + }, + Name: to.Ptr("extension"), + ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/providers/Azure.ResourceManager.Resources/extensionsResources/extension"), + SystemData: &resources.SystemData{ + CreatedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + CreatedBy: to.Ptr("AzureSDK"), + CreatedByType: to.Ptr(resources.CreatedByTypeUser), + LastModifiedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + LastModifiedBy: to.Ptr("AzureSDK"), + LastModifiedByType: to.Ptr(resources.CreatedByTypeUser), + }, + Type: to.Ptr("Azure.ResourceManager.Resources/extensionsResources"), + }, resp.ExtensionsResource) + + resp, err = clientFactory.NewExtensionsResourcesClient().Update(context.Background(), "/", "extension", resources.ExtensionsResource{ + Properties: &resources.ExtensionsResourceProperties{ + Description: to.Ptr("valid2"), + }, + }, nil) + require.NoError(t, err) + require.Equal(t, resources.ExtensionsResource{ + Properties: &resources.ExtensionsResourceProperties{ + Description: to.Ptr("valid2"), + ProvisioningState: to.Ptr(resources.ProvisioningStateSucceeded), + }, + Name: to.Ptr("extension"), + ID: to.Ptr("/providers/Azure.ResourceManager.Resources/extensionsResources/extension"), + SystemData: &resources.SystemData{ + CreatedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + CreatedBy: to.Ptr("AzureSDK"), + CreatedByType: to.Ptr(resources.CreatedByTypeUser), + LastModifiedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + LastModifiedBy: to.Ptr("AzureSDK"), + LastModifiedByType: to.Ptr(resources.CreatedByTypeUser), + }, + Type: to.Ptr("Azure.ResourceManager.Resources/extensionsResources"), + }, resp.ExtensionsResource) + + resp, err = clientFactory.NewExtensionsResourcesClient().Update(context.Background(), "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Azure.ResourceManager.Resources/topLevelTrackedResources/top", "extension", resources.ExtensionsResource{ + Properties: &resources.ExtensionsResourceProperties{ + Description: to.Ptr("valid2"), + }, + }, nil) + require.NoError(t, err) + require.Equal(t, resources.ExtensionsResource{ + Properties: &resources.ExtensionsResourceProperties{ + Description: to.Ptr("valid2"), + ProvisioningState: to.Ptr(resources.ProvisioningStateSucceeded), + }, + Name: to.Ptr("extension"), + ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Azure.ResourceManager.Resources/topLevelTrackedResources/top/providers/Azure.ResourceManager.Resources/extensionsResources/extension"), + SystemData: &resources.SystemData{ + CreatedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + CreatedBy: to.Ptr("AzureSDK"), + CreatedByType: to.Ptr(resources.CreatedByTypeUser), + LastModifiedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + LastModifiedBy: to.Ptr("AzureSDK"), + LastModifiedByType: to.Ptr(resources.CreatedByTypeUser), + }, + Type: to.Ptr("Azure.ResourceManager.Resources/extensionsResources"), + }, resp.ExtensionsResource) +} diff --git a/test/azure-http-specs/azure/resource-manager/resources/fake/zz_extensionsresources_server.go b/test/azure-http-specs/azure/resource-manager/resources/fake/zz_extensionsresources_server.go new file mode 100644 index 000000000000..f3546cff7f52 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/fake/zz_extensionsresources_server.go @@ -0,0 +1,303 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "resources" + "slices" +) + +// ExtensionsResourcesServer is a fake server for instances of the resources.ExtensionsResourcesClient type. +type ExtensionsResourcesServer struct { + // BeginCreateOrUpdate is the fake for method ExtensionsResourcesClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceURI string, extensionsResourceName string, resource resources.ExtensionsResource, options *resources.ExtensionsResourcesClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[resources.ExtensionsResourcesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method ExtensionsResourcesClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceURI string, extensionsResourceName string, options *resources.ExtensionsResourcesClientDeleteOptions) (resp azfake.Responder[resources.ExtensionsResourcesClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method ExtensionsResourcesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceURI string, extensionsResourceName string, options *resources.ExtensionsResourcesClientGetOptions) (resp azfake.Responder[resources.ExtensionsResourcesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByScopePager is the fake for method ExtensionsResourcesClient.NewListByScopePager + // HTTP status codes to indicate success: http.StatusOK + NewListByScopePager func(resourceURI string, options *resources.ExtensionsResourcesClientListByScopeOptions) (resp azfake.PagerResponder[resources.ExtensionsResourcesClientListByScopeResponse]) + + // Update is the fake for method ExtensionsResourcesClient.Update + // HTTP status codes to indicate success: http.StatusOK + Update func(ctx context.Context, resourceURI string, extensionsResourceName string, properties resources.ExtensionsResource, options *resources.ExtensionsResourcesClientUpdateOptions) (resp azfake.Responder[resources.ExtensionsResourcesClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewExtensionsResourcesServerTransport creates a new instance of ExtensionsResourcesServerTransport with the provided implementation. +// The returned ExtensionsResourcesServerTransport instance is connected to an instance of resources.ExtensionsResourcesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewExtensionsResourcesServerTransport(srv *ExtensionsResourcesServer) *ExtensionsResourcesServerTransport { + return &ExtensionsResourcesServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[resources.ExtensionsResourcesClientCreateOrUpdateResponse]](), + newListByScopePager: newTracker[azfake.PagerResponder[resources.ExtensionsResourcesClientListByScopeResponse]](), + } +} + +// ExtensionsResourcesServerTransport connects instances of resources.ExtensionsResourcesClient to instances of ExtensionsResourcesServer. +// Don't use this type directly, use NewExtensionsResourcesServerTransport instead. +type ExtensionsResourcesServerTransport struct { + srv *ExtensionsResourcesServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[resources.ExtensionsResourcesClientCreateOrUpdateResponse]] + newListByScopePager *tracker[azfake.PagerResponder[resources.ExtensionsResourcesClientListByScopeResponse]] +} + +// Do implements the policy.Transporter interface for ExtensionsResourcesServerTransport. +func (e *ExtensionsResourcesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return e.dispatchToMethodFake(req, method) +} + +func (e *ExtensionsResourcesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if extensionsResourcesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = extensionsResourcesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ExtensionsResourcesClient.BeginCreateOrUpdate": + res.resp, res.err = e.dispatchBeginCreateOrUpdate(req) + case "ExtensionsResourcesClient.Delete": + res.resp, res.err = e.dispatchDelete(req) + case "ExtensionsResourcesClient.Get": + res.resp, res.err = e.dispatchGet(req) + case "ExtensionsResourcesClient.NewListByScopePager": + res.resp, res.err = e.dispatchNewListByScopePager(req) + case "ExtensionsResourcesClient.Update": + res.resp, res.err = e.dispatchUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (e *ExtensionsResourcesServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if e.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := e.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.Resources/extensionsResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[resources.ExtensionsResource](req) + if err != nil { + return nil, err + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + extensionsResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("extensionsResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.BeginCreateOrUpdate(req.Context(), resourceURIParam, extensionsResourceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + e.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + e.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + e.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (e *ExtensionsResourcesServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if e.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.Resources/extensionsResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + extensionsResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("extensionsResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.Delete(req.Context(), resourceURIParam, extensionsResourceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *ExtensionsResourcesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if e.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.Resources/extensionsResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + extensionsResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("extensionsResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.Get(req.Context(), resourceURIParam, extensionsResourceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ExtensionsResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *ExtensionsResourcesServerTransport) dispatchNewListByScopePager(req *http.Request) (*http.Response, error) { + if e.srv.NewListByScopePager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByScopePager not implemented")} + } + newListByScopePager := e.newListByScopePager.get(req) + if newListByScopePager == nil { + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.Resources/extensionsResources` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + resp := e.srv.NewListByScopePager(resourceURIParam, nil) + newListByScopePager = &resp + e.newListByScopePager.add(req, newListByScopePager) + server.PagerResponderInjectNextLinks(newListByScopePager, req, func(page *resources.ExtensionsResourcesClientListByScopeResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByScopePager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + e.newListByScopePager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByScopePager) { + e.newListByScopePager.remove(req) + } + return resp, nil +} + +func (e *ExtensionsResourcesServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) { + if e.srv.Update == nil { + return nil, &nonRetriableError{errors.New("fake for method Update not implemented")} + } + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.Resources/extensionsResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[resources.ExtensionsResource](req) + if err != nil { + return nil, err + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + extensionsResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("extensionsResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.Update(req.Context(), resourceURIParam, extensionsResourceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ExtensionsResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ExtensionsResourcesServerTransport +var extensionsResourcesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/resource-manager/resources/fake/zz_internal.go b/test/azure-http-specs/azure/resource-manager/resources/fake/zz_internal.go new file mode 100644 index 000000000000..590b4d743e97 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/fake/zz_internal.go @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/azure-http-specs/azure/resource-manager/resources/fake/zz_locationresources_server.go b/test/azure-http-specs/azure/resource-manager/resources/fake/zz_locationresources_server.go new file mode 100644 index 000000000000..883de7f72699 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/fake/zz_locationresources_server.go @@ -0,0 +1,290 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "resources" + "slices" +) + +// LocationResourcesServer is a fake server for instances of the resources.LocationResourcesClient type. +type LocationResourcesServer struct { + // CreateOrUpdate is the fake for method LocationResourcesClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, location string, locationResourceName string, resource resources.LocationResource, options *resources.LocationResourcesClientCreateOrUpdateOptions) (resp azfake.Responder[resources.LocationResourcesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method LocationResourcesClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, location string, locationResourceName string, options *resources.LocationResourcesClientDeleteOptions) (resp azfake.Responder[resources.LocationResourcesClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method LocationResourcesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, location string, locationResourceName string, options *resources.LocationResourcesClientGetOptions) (resp azfake.Responder[resources.LocationResourcesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByLocationPager is the fake for method LocationResourcesClient.NewListByLocationPager + // HTTP status codes to indicate success: http.StatusOK + NewListByLocationPager func(location string, options *resources.LocationResourcesClientListByLocationOptions) (resp azfake.PagerResponder[resources.LocationResourcesClientListByLocationResponse]) + + // Update is the fake for method LocationResourcesClient.Update + // HTTP status codes to indicate success: http.StatusOK + Update func(ctx context.Context, location string, locationResourceName string, properties resources.LocationResource, options *resources.LocationResourcesClientUpdateOptions) (resp azfake.Responder[resources.LocationResourcesClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewLocationResourcesServerTransport creates a new instance of LocationResourcesServerTransport with the provided implementation. +// The returned LocationResourcesServerTransport instance is connected to an instance of resources.LocationResourcesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewLocationResourcesServerTransport(srv *LocationResourcesServer) *LocationResourcesServerTransport { + return &LocationResourcesServerTransport{ + srv: srv, + newListByLocationPager: newTracker[azfake.PagerResponder[resources.LocationResourcesClientListByLocationResponse]](), + } +} + +// LocationResourcesServerTransport connects instances of resources.LocationResourcesClient to instances of LocationResourcesServer. +// Don't use this type directly, use NewLocationResourcesServerTransport instead. +type LocationResourcesServerTransport struct { + srv *LocationResourcesServer + newListByLocationPager *tracker[azfake.PagerResponder[resources.LocationResourcesClientListByLocationResponse]] +} + +// Do implements the policy.Transporter interface for LocationResourcesServerTransport. +func (l *LocationResourcesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return l.dispatchToMethodFake(req, method) +} + +func (l *LocationResourcesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if locationResourcesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = locationResourcesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "LocationResourcesClient.CreateOrUpdate": + res.resp, res.err = l.dispatchCreateOrUpdate(req) + case "LocationResourcesClient.Delete": + res.resp, res.err = l.dispatchDelete(req) + case "LocationResourcesClient.Get": + res.resp, res.err = l.dispatchGet(req) + case "LocationResourcesClient.NewListByLocationPager": + res.resp, res.err = l.dispatchNewListByLocationPager(req) + case "LocationResourcesClient.Update": + res.resp, res.err = l.dispatchUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (l *LocationResourcesServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if l.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.Resources/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/locationResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[resources.LocationResource](req) + if err != nil { + return nil, err + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + locationResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("locationResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.CreateOrUpdate(req.Context(), locationParam, locationResourceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).LocationResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (l *LocationResourcesServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if l.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.Resources/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/locationResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + locationResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("locationResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.Delete(req.Context(), locationParam, locationResourceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (l *LocationResourcesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if l.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.Resources/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/locationResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + locationResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("locationResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.Get(req.Context(), locationParam, locationResourceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).LocationResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (l *LocationResourcesServerTransport) dispatchNewListByLocationPager(req *http.Request) (*http.Response, error) { + if l.srv.NewListByLocationPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByLocationPager not implemented")} + } + newListByLocationPager := l.newListByLocationPager.get(req) + if newListByLocationPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.Resources/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/locationResources` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + resp := l.srv.NewListByLocationPager(locationParam, nil) + newListByLocationPager = &resp + l.newListByLocationPager.add(req, newListByLocationPager) + server.PagerResponderInjectNextLinks(newListByLocationPager, req, func(page *resources.LocationResourcesClientListByLocationResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByLocationPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + l.newListByLocationPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByLocationPager) { + l.newListByLocationPager.remove(req) + } + return resp, nil +} + +func (l *LocationResourcesServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) { + if l.srv.Update == nil { + return nil, &nonRetriableError{errors.New("fake for method Update not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.Resources/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/locationResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[resources.LocationResource](req) + if err != nil { + return nil, err + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + locationResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("locationResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.Update(req.Context(), locationParam, locationResourceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).LocationResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to LocationResourcesServerTransport +var locationResourcesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/resource-manager/resources/fake/zz_nested_server.go b/test/azure-http-specs/azure/resource-manager/resources/fake/zz_nested_server.go new file mode 100644 index 000000000000..6d2d8dc88aa7 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/fake/zz_nested_server.go @@ -0,0 +1,349 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "resources" + "slices" +) + +// NestedServer is a fake server for instances of the resources.NestedClient type. +type NestedServer struct { + // BeginCreateOrReplace is the fake for method NestedClient.BeginCreateOrReplace + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrReplace func(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, nextedProxyResourceName string, resource resources.NestedProxyResource, options *resources.NestedClientBeginCreateOrReplaceOptions) (resp azfake.PollerResponder[resources.NestedClientCreateOrReplaceResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method NestedClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, nextedProxyResourceName string, options *resources.NestedClientBeginDeleteOptions) (resp azfake.PollerResponder[resources.NestedClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method NestedClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, nextedProxyResourceName string, options *resources.NestedClientGetOptions) (resp azfake.Responder[resources.NestedClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByTopLevelTrackedResourcePager is the fake for method NestedClient.NewListByTopLevelTrackedResourcePager + // HTTP status codes to indicate success: http.StatusOK + NewListByTopLevelTrackedResourcePager func(resourceGroupName string, topLevelTrackedResourceName string, options *resources.NestedClientListByTopLevelTrackedResourceOptions) (resp azfake.PagerResponder[resources.NestedClientListByTopLevelTrackedResourceResponse]) + + // BeginUpdate is the fake for method NestedClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, nextedProxyResourceName string, properties resources.NestedProxyResource, options *resources.NestedClientBeginUpdateOptions) (resp azfake.PollerResponder[resources.NestedClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewNestedServerTransport creates a new instance of NestedServerTransport with the provided implementation. +// The returned NestedServerTransport instance is connected to an instance of resources.NestedClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewNestedServerTransport(srv *NestedServer) *NestedServerTransport { + return &NestedServerTransport{ + srv: srv, + beginCreateOrReplace: newTracker[azfake.PollerResponder[resources.NestedClientCreateOrReplaceResponse]](), + beginDelete: newTracker[azfake.PollerResponder[resources.NestedClientDeleteResponse]](), + newListByTopLevelTrackedResourcePager: newTracker[azfake.PagerResponder[resources.NestedClientListByTopLevelTrackedResourceResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[resources.NestedClientUpdateResponse]](), + } +} + +// NestedServerTransport connects instances of resources.NestedClient to instances of NestedServer. +// Don't use this type directly, use NewNestedServerTransport instead. +type NestedServerTransport struct { + srv *NestedServer + beginCreateOrReplace *tracker[azfake.PollerResponder[resources.NestedClientCreateOrReplaceResponse]] + beginDelete *tracker[azfake.PollerResponder[resources.NestedClientDeleteResponse]] + newListByTopLevelTrackedResourcePager *tracker[azfake.PagerResponder[resources.NestedClientListByTopLevelTrackedResourceResponse]] + beginUpdate *tracker[azfake.PollerResponder[resources.NestedClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for NestedServerTransport. +func (n *NestedServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return n.dispatchToMethodFake(req, method) +} + +func (n *NestedServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if nestedServerTransportInterceptor != nil { + res.resp, res.err, intercepted = nestedServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "NestedClient.BeginCreateOrReplace": + res.resp, res.err = n.dispatchBeginCreateOrReplace(req) + case "NestedClient.BeginDelete": + res.resp, res.err = n.dispatchBeginDelete(req) + case "NestedClient.Get": + res.resp, res.err = n.dispatchGet(req) + case "NestedClient.NewListByTopLevelTrackedResourcePager": + res.resp, res.err = n.dispatchNewListByTopLevelTrackedResourcePager(req) + case "NestedClient.BeginUpdate": + res.resp, res.err = n.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (n *NestedServerTransport) dispatchBeginCreateOrReplace(req *http.Request) (*http.Response, error) { + if n.srv.BeginCreateOrReplace == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrReplace not implemented")} + } + beginCreateOrReplace := n.beginCreateOrReplace.get(req) + if beginCreateOrReplace == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.Resources/topLevelTrackedResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/nestedProxyResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[resources.NestedProxyResource](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + topLevelTrackedResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("topLevelTrackedResourceName")]) + if err != nil { + return nil, err + } + nextedProxyResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("nextedProxyResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.BeginCreateOrReplace(req.Context(), resourceGroupNameParam, topLevelTrackedResourceNameParam, nextedProxyResourceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrReplace = &respr + n.beginCreateOrReplace.add(req, beginCreateOrReplace) + } + + resp, err := server.PollerResponderNext(beginCreateOrReplace, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + n.beginCreateOrReplace.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrReplace) { + n.beginCreateOrReplace.remove(req) + } + + return resp, nil +} + +func (n *NestedServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if n.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := n.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.Resources/topLevelTrackedResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/nestedProxyResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + topLevelTrackedResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("topLevelTrackedResourceName")]) + if err != nil { + return nil, err + } + nextedProxyResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("nextedProxyResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.BeginDelete(req.Context(), resourceGroupNameParam, topLevelTrackedResourceNameParam, nextedProxyResourceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + n.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + n.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + n.beginDelete.remove(req) + } + + return resp, nil +} + +func (n *NestedServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if n.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.Resources/topLevelTrackedResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/nestedProxyResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + topLevelTrackedResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("topLevelTrackedResourceName")]) + if err != nil { + return nil, err + } + nextedProxyResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("nextedProxyResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.Get(req.Context(), resourceGroupNameParam, topLevelTrackedResourceNameParam, nextedProxyResourceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).NestedProxyResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NestedServerTransport) dispatchNewListByTopLevelTrackedResourcePager(req *http.Request) (*http.Response, error) { + if n.srv.NewListByTopLevelTrackedResourcePager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByTopLevelTrackedResourcePager not implemented")} + } + newListByTopLevelTrackedResourcePager := n.newListByTopLevelTrackedResourcePager.get(req) + if newListByTopLevelTrackedResourcePager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.Resources/topLevelTrackedResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/nestedProxyResources` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + topLevelTrackedResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("topLevelTrackedResourceName")]) + if err != nil { + return nil, err + } + resp := n.srv.NewListByTopLevelTrackedResourcePager(resourceGroupNameParam, topLevelTrackedResourceNameParam, nil) + newListByTopLevelTrackedResourcePager = &resp + n.newListByTopLevelTrackedResourcePager.add(req, newListByTopLevelTrackedResourcePager) + server.PagerResponderInjectNextLinks(newListByTopLevelTrackedResourcePager, req, func(page *resources.NestedClientListByTopLevelTrackedResourceResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByTopLevelTrackedResourcePager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + n.newListByTopLevelTrackedResourcePager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByTopLevelTrackedResourcePager) { + n.newListByTopLevelTrackedResourcePager.remove(req) + } + return resp, nil +} + +func (n *NestedServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if n.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := n.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.Resources/topLevelTrackedResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/nestedProxyResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[resources.NestedProxyResource](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + topLevelTrackedResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("topLevelTrackedResourceName")]) + if err != nil { + return nil, err + } + nextedProxyResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("nextedProxyResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.BeginUpdate(req.Context(), resourceGroupNameParam, topLevelTrackedResourceNameParam, nextedProxyResourceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + n.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + n.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + n.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to NestedServerTransport +var nestedServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/resource-manager/resources/fake/zz_server_factory.go b/test/azure-http-specs/azure/resource-manager/resources/fake/zz_server_factory.go new file mode 100644 index 000000000000..23d139912108 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/fake/zz_server_factory.go @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the resources.ClientFactory type. +type ServerFactory struct { + // ExtensionsResourcesServer contains the fakes for client ExtensionsResourcesClient + ExtensionsResourcesServer ExtensionsResourcesServer + + // LocationResourcesServer contains the fakes for client LocationResourcesClient + LocationResourcesServer LocationResourcesServer + + // NestedServer contains the fakes for client NestedClient + NestedServer NestedServer + + // SingletonServer contains the fakes for client SingletonClient + SingletonServer SingletonServer + + // TopLevelServer contains the fakes for client TopLevelClient + TopLevelServer TopLevelServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of resources.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of resources.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trExtensionsResourcesServer *ExtensionsResourcesServerTransport + trLocationResourcesServer *LocationResourcesServerTransport + trNestedServer *NestedServerTransport + trSingletonServer *SingletonServerTransport + trTopLevelServer *TopLevelServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "ExtensionsResourcesClient": + initServer(&s.trMu, &s.trExtensionsResourcesServer, func() *ExtensionsResourcesServerTransport { + return NewExtensionsResourcesServerTransport(&s.srv.ExtensionsResourcesServer) + }) + resp, err = s.trExtensionsResourcesServer.Do(req) + case "LocationResourcesClient": + initServer(&s.trMu, &s.trLocationResourcesServer, func() *LocationResourcesServerTransport { + return NewLocationResourcesServerTransport(&s.srv.LocationResourcesServer) + }) + resp, err = s.trLocationResourcesServer.Do(req) + case "NestedClient": + initServer(&s.trMu, &s.trNestedServer, func() *NestedServerTransport { return NewNestedServerTransport(&s.srv.NestedServer) }) + resp, err = s.trNestedServer.Do(req) + case "SingletonClient": + initServer(&s.trMu, &s.trSingletonServer, func() *SingletonServerTransport { return NewSingletonServerTransport(&s.srv.SingletonServer) }) + resp, err = s.trSingletonServer.Do(req) + case "TopLevelClient": + initServer(&s.trMu, &s.trTopLevelServer, func() *TopLevelServerTransport { return NewTopLevelServerTransport(&s.srv.TopLevelServer) }) + resp, err = s.trTopLevelServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/resources/fake/zz_singleton_server.go b/test/azure-http-specs/azure/resource-manager/resources/fake/zz_singleton_server.go new file mode 100644 index 000000000000..2ba6fa9a6326 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/fake/zz_singleton_server.go @@ -0,0 +1,252 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "resources" + "slices" +) + +// SingletonServer is a fake server for instances of the resources.SingletonClient type. +type SingletonServer struct { + // BeginCreateOrUpdate is the fake for method SingletonClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, resource resources.SingletonTrackedResource, options *resources.SingletonClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[resources.SingletonClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // GetByResourceGroup is the fake for method SingletonClient.GetByResourceGroup + // HTTP status codes to indicate success: http.StatusOK + GetByResourceGroup func(ctx context.Context, resourceGroupName string, options *resources.SingletonClientGetByResourceGroupOptions) (resp azfake.Responder[resources.SingletonClientGetByResourceGroupResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method SingletonClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *resources.SingletonClientListByResourceGroupOptions) (resp azfake.PagerResponder[resources.SingletonClientListByResourceGroupResponse]) + + // Update is the fake for method SingletonClient.Update + // HTTP status codes to indicate success: http.StatusOK + Update func(ctx context.Context, resourceGroupName string, properties resources.SingletonTrackedResource, options *resources.SingletonClientUpdateOptions) (resp azfake.Responder[resources.SingletonClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewSingletonServerTransport creates a new instance of SingletonServerTransport with the provided implementation. +// The returned SingletonServerTransport instance is connected to an instance of resources.SingletonClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSingletonServerTransport(srv *SingletonServer) *SingletonServerTransport { + return &SingletonServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[resources.SingletonClientCreateOrUpdateResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[resources.SingletonClientListByResourceGroupResponse]](), + } +} + +// SingletonServerTransport connects instances of resources.SingletonClient to instances of SingletonServer. +// Don't use this type directly, use NewSingletonServerTransport instead. +type SingletonServerTransport struct { + srv *SingletonServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[resources.SingletonClientCreateOrUpdateResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[resources.SingletonClientListByResourceGroupResponse]] +} + +// Do implements the policy.Transporter interface for SingletonServerTransport. +func (s *SingletonServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *SingletonServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if singletonServerTransportInterceptor != nil { + res.resp, res.err, intercepted = singletonServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SingletonClient.BeginCreateOrUpdate": + res.resp, res.err = s.dispatchBeginCreateOrUpdate(req) + case "SingletonClient.GetByResourceGroup": + res.resp, res.err = s.dispatchGetByResourceGroup(req) + case "SingletonClient.NewListByResourceGroupPager": + res.resp, res.err = s.dispatchNewListByResourceGroupPager(req) + case "SingletonClient.Update": + res.resp, res.err = s.dispatchUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *SingletonServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if s.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := s.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.Resources/singletonTrackedResources/default` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[resources.SingletonTrackedResource](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + s.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + s.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + s.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (s *SingletonServerTransport) dispatchGetByResourceGroup(req *http.Request) (*http.Response, error) { + if s.srv.GetByResourceGroup == nil { + return nil, &nonRetriableError{errors.New("fake for method GetByResourceGroup not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.Resources/singletonTrackedResources/default` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.GetByResourceGroup(req.Context(), resourceGroupNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).SingletonTrackedResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SingletonServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if s.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := s.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.Resources/singletonTrackedResources` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := s.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + s.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *resources.SingletonClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + s.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + s.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (s *SingletonServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) { + if s.srv.Update == nil { + return nil, &nonRetriableError{errors.New("fake for method Update not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.Resources/singletonTrackedResources/default` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[resources.SingletonTrackedResource](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Update(req.Context(), resourceGroupNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).SingletonTrackedResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SingletonServerTransport +var singletonServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/resource-manager/resources/fake/zz_toplevel_server.go b/test/azure-http-specs/azure/resource-manager/resources/fake/zz_toplevel_server.go new file mode 100644 index 000000000000..b1675ef66d0b --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/fake/zz_toplevel_server.go @@ -0,0 +1,413 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "resources" + "slices" +) + +// TopLevelServer is a fake server for instances of the resources.TopLevelClient type. +type TopLevelServer struct { + // ActionSync is the fake for method TopLevelClient.ActionSync + // HTTP status codes to indicate success: http.StatusNoContent + ActionSync func(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, body resources.NotificationDetails, options *resources.TopLevelClientActionSyncOptions) (resp azfake.Responder[resources.TopLevelClientActionSyncResponse], errResp azfake.ErrorResponder) + + // BeginCreateOrReplace is the fake for method TopLevelClient.BeginCreateOrReplace + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrReplace func(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, resource resources.TopLevelTrackedResource, options *resources.TopLevelClientBeginCreateOrReplaceOptions) (resp azfake.PollerResponder[resources.TopLevelClientCreateOrReplaceResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method TopLevelClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, options *resources.TopLevelClientBeginDeleteOptions) (resp azfake.PollerResponder[resources.TopLevelClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method TopLevelClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, options *resources.TopLevelClientGetOptions) (resp azfake.Responder[resources.TopLevelClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method TopLevelClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *resources.TopLevelClientListByResourceGroupOptions) (resp azfake.PagerResponder[resources.TopLevelClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method TopLevelClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *resources.TopLevelClientListBySubscriptionOptions) (resp azfake.PagerResponder[resources.TopLevelClientListBySubscriptionResponse]) + + // BeginUpdate is the fake for method TopLevelClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, properties resources.TopLevelTrackedResource, options *resources.TopLevelClientBeginUpdateOptions) (resp azfake.PollerResponder[resources.TopLevelClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewTopLevelServerTransport creates a new instance of TopLevelServerTransport with the provided implementation. +// The returned TopLevelServerTransport instance is connected to an instance of resources.TopLevelClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewTopLevelServerTransport(srv *TopLevelServer) *TopLevelServerTransport { + return &TopLevelServerTransport{ + srv: srv, + beginCreateOrReplace: newTracker[azfake.PollerResponder[resources.TopLevelClientCreateOrReplaceResponse]](), + beginDelete: newTracker[azfake.PollerResponder[resources.TopLevelClientDeleteResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[resources.TopLevelClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[resources.TopLevelClientListBySubscriptionResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[resources.TopLevelClientUpdateResponse]](), + } +} + +// TopLevelServerTransport connects instances of resources.TopLevelClient to instances of TopLevelServer. +// Don't use this type directly, use NewTopLevelServerTransport instead. +type TopLevelServerTransport struct { + srv *TopLevelServer + beginCreateOrReplace *tracker[azfake.PollerResponder[resources.TopLevelClientCreateOrReplaceResponse]] + beginDelete *tracker[azfake.PollerResponder[resources.TopLevelClientDeleteResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[resources.TopLevelClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[resources.TopLevelClientListBySubscriptionResponse]] + beginUpdate *tracker[azfake.PollerResponder[resources.TopLevelClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for TopLevelServerTransport. +func (t *TopLevelServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return t.dispatchToMethodFake(req, method) +} + +func (t *TopLevelServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if topLevelServerTransportInterceptor != nil { + res.resp, res.err, intercepted = topLevelServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "TopLevelClient.ActionSync": + res.resp, res.err = t.dispatchActionSync(req) + case "TopLevelClient.BeginCreateOrReplace": + res.resp, res.err = t.dispatchBeginCreateOrReplace(req) + case "TopLevelClient.BeginDelete": + res.resp, res.err = t.dispatchBeginDelete(req) + case "TopLevelClient.Get": + res.resp, res.err = t.dispatchGet(req) + case "TopLevelClient.NewListByResourceGroupPager": + res.resp, res.err = t.dispatchNewListByResourceGroupPager(req) + case "TopLevelClient.NewListBySubscriptionPager": + res.resp, res.err = t.dispatchNewListBySubscriptionPager(req) + case "TopLevelClient.BeginUpdate": + res.resp, res.err = t.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (t *TopLevelServerTransport) dispatchActionSync(req *http.Request) (*http.Response, error) { + if t.srv.ActionSync == nil { + return nil, &nonRetriableError{errors.New("fake for method ActionSync not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.Resources/topLevelTrackedResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/actionSync` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[resources.NotificationDetails](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + topLevelTrackedResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("topLevelTrackedResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := t.srv.ActionSync(req.Context(), resourceGroupNameParam, topLevelTrackedResourceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (t *TopLevelServerTransport) dispatchBeginCreateOrReplace(req *http.Request) (*http.Response, error) { + if t.srv.BeginCreateOrReplace == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrReplace not implemented")} + } + beginCreateOrReplace := t.beginCreateOrReplace.get(req) + if beginCreateOrReplace == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.Resources/topLevelTrackedResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[resources.TopLevelTrackedResource](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + topLevelTrackedResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("topLevelTrackedResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := t.srv.BeginCreateOrReplace(req.Context(), resourceGroupNameParam, topLevelTrackedResourceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrReplace = &respr + t.beginCreateOrReplace.add(req, beginCreateOrReplace) + } + + resp, err := server.PollerResponderNext(beginCreateOrReplace, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + t.beginCreateOrReplace.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrReplace) { + t.beginCreateOrReplace.remove(req) + } + + return resp, nil +} + +func (t *TopLevelServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if t.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := t.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.Resources/topLevelTrackedResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + topLevelTrackedResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("topLevelTrackedResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := t.srv.BeginDelete(req.Context(), resourceGroupNameParam, topLevelTrackedResourceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + t.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + t.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + t.beginDelete.remove(req) + } + + return resp, nil +} + +func (t *TopLevelServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if t.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.Resources/topLevelTrackedResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + topLevelTrackedResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("topLevelTrackedResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := t.srv.Get(req.Context(), resourceGroupNameParam, topLevelTrackedResourceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).TopLevelTrackedResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (t *TopLevelServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if t.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := t.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.Resources/topLevelTrackedResources` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := t.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + t.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *resources.TopLevelClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + t.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + t.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (t *TopLevelServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if t.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := t.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.Resources/topLevelTrackedResources` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := t.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + t.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *resources.TopLevelClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + t.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + t.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (t *TopLevelServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if t.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := t.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.Resources/topLevelTrackedResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[resources.TopLevelTrackedResource](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + topLevelTrackedResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("topLevelTrackedResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := t.srv.BeginUpdate(req.Context(), resourceGroupNameParam, topLevelTrackedResourceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + t.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + t.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + t.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to TopLevelServerTransport +var topLevelServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/resource-manager/resources/go.mod b/test/azure-http-specs/azure/resource-manager/resources/go.mod new file mode 100644 index 000000000000..c60c8157415b --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/go.mod @@ -0,0 +1,17 @@ +module resources + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/resource-manager/resources/go.sum b/test/azure-http-specs/azure/resource-manager/resources/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/resource-manager/resources/locationresources_client_test.go b/test/azure-http-specs/azure/resource-manager/resources/locationresources_client_test.go new file mode 100644 index 000000000000..bacac7dbb31a --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/locationresources_client_test.go @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package resources_test + +import ( + "context" + "resources" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestLocationResourcesClient_CreateOrUpdate(t *testing.T) { + resp, err := clientFactory.NewLocationResourcesClient(subscriptionIdExpected).CreateOrUpdate(context.Background(), "eastus", "resource", resources.LocationResource{ + Properties: &resources.LocationResourceProperties{ + Description: to.Ptr("valid"), + }, + }, nil) + require.NoError(t, err) + require.Equal(t, resources.LocationResource{ + Properties: &resources.LocationResourceProperties{ + Description: to.Ptr("valid"), + ProvisioningState: to.Ptr(resources.ProvisioningStateSucceeded), + }, + Name: to.Ptr("resource"), + ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/providers/Azure.ResourceManager.Resources/locations/eastus/locationResources/resource"), + SystemData: &resources.SystemData{ + CreatedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + CreatedBy: to.Ptr("AzureSDK"), + CreatedByType: to.Ptr(resources.CreatedByTypeUser), + LastModifiedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + LastModifiedBy: to.Ptr("AzureSDK"), + LastModifiedByType: to.Ptr(resources.CreatedByTypeUser), + }, + Type: to.Ptr("Azure.ResourceManager.Resources/locationResources"), + }, resp.LocationResource) +} + +func TestLocationResourcesClient_Delete(t *testing.T) { + resp, err := clientFactory.NewLocationResourcesClient(subscriptionIdExpected).Delete(context.Background(), "eastus", "resource", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestLocationResourcesClient_Get(t *testing.T) { + resp, err := clientFactory.NewLocationResourcesClient(subscriptionIdExpected).Get(context.Background(), "eastus", "resource", nil) + require.NoError(t, err) + require.Equal(t, resources.LocationResource{ + Properties: &resources.LocationResourceProperties{ + Description: to.Ptr("valid"), + ProvisioningState: to.Ptr(resources.ProvisioningStateSucceeded), + }, + Name: to.Ptr("resource"), + ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/providers/Azure.ResourceManager.Resources/locations/eastus/locationResources/resource"), + SystemData: &resources.SystemData{ + CreatedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + CreatedBy: to.Ptr("AzureSDK"), + CreatedByType: to.Ptr(resources.CreatedByTypeUser), + LastModifiedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + LastModifiedBy: to.Ptr("AzureSDK"), + LastModifiedByType: to.Ptr(resources.CreatedByTypeUser), + }, + Type: to.Ptr("Azure.ResourceManager.Resources/locationResources"), + }, resp.LocationResource) +} + +func TestLocationResourcesClient_NewListByScopePager(t *testing.T) { + pager := clientFactory.NewLocationResourcesClient(subscriptionIdExpected).NewListByLocationPager("eastus", nil) + pageCount := 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + require.Len(t, page.Value, 1) + require.Equal(t, &resources.LocationResource{ + Properties: &resources.LocationResourceProperties{ + Description: to.Ptr("valid"), + ProvisioningState: to.Ptr(resources.ProvisioningStateSucceeded), + }, + Name: to.Ptr("resource"), + ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/providers/Azure.ResourceManager.Resources/locations/eastus/locationResources/resource"), + SystemData: &resources.SystemData{ + CreatedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + CreatedBy: to.Ptr("AzureSDK"), + CreatedByType: to.Ptr(resources.CreatedByTypeUser), + LastModifiedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + LastModifiedBy: to.Ptr("AzureSDK"), + LastModifiedByType: to.Ptr(resources.CreatedByTypeUser), + }, + Type: to.Ptr("Azure.ResourceManager.Resources/locationResources"), + }, page.Value[0]) + pageCount++ + } + require.EqualValues(t, 1, pageCount) +} + +func TestLocationResourcesClient_Update(t *testing.T) { + resp, err := clientFactory.NewLocationResourcesClient(subscriptionIdExpected).Update(context.Background(), "eastus", "resource", resources.LocationResource{ + Properties: &resources.LocationResourceProperties{ + Description: to.Ptr("valid2"), + }, + }, nil) + require.NoError(t, err) + require.Equal(t, resources.LocationResource{ + Properties: &resources.LocationResourceProperties{ + Description: to.Ptr("valid2"), + ProvisioningState: to.Ptr(resources.ProvisioningStateSucceeded), + }, + Name: to.Ptr("resource"), + ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/providers/Azure.ResourceManager.Resources/locations/eastus/locationResources/resource"), + SystemData: &resources.SystemData{ + CreatedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + CreatedBy: to.Ptr("AzureSDK"), + CreatedByType: to.Ptr(resources.CreatedByTypeUser), + LastModifiedAt: to.Ptr(time.Date(2024, time.October, 4, 0, 56, 7, 442000000, time.UTC)), + LastModifiedBy: to.Ptr("AzureSDK"), + LastModifiedByType: to.Ptr(resources.CreatedByTypeUser), + }, + Type: to.Ptr("Azure.ResourceManager.Resources/locationResources"), + }, resp.LocationResource) +} diff --git a/test/azure-http-specs/azure/resource-manager/resources/nested_client_test.go b/test/azure-http-specs/azure/resource-manager/resources/nested_client_test.go new file mode 100644 index 000000000000..091273175c8d --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/nested_client_test.go @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package resources_test + +import ( + "net/http" + "resources" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +var ( + validNestedResource = resources.NestedProxyResource{ + ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Azure.ResourceManager.Resources/topLevelTrackedResources/top/nestedProxyResources/nested"), + Name: to.Ptr("nested"), + Type: to.Ptr("Azure.ResourceManager.Resources/topLevelTrackedResources/top/nestedProxyResources"), + Properties: &resources.NestedProxyResourceProperties{ + Description: to.Ptr("valid"), + ProvisioningState: to.Ptr(resources.ProvisioningStateSucceeded), + }, + SystemData: &resources.SystemData{ + CreatedBy: to.Ptr("AzureSDK"), + CreatedByType: to.Ptr(resources.CreatedByTypeUser), + CreatedAt: to.Ptr(time.Now()), + LastModifiedBy: to.Ptr("AzureSDK"), + LastModifiedAt: to.Ptr(time.Now()), + LastModifiedByType: to.Ptr(resources.CreatedByTypeUser), + }, + } +) + +func TestNestedClient_Get(t *testing.T) { + nestedClientGetResponse, err := clientFactory.NewNestedClient(subscriptionIdExpected).Get( + ctx, + "test-rg", + "top", + "nested", + nil, + ) + require.NoError(t, err) + require.Equal(t, *validNestedResource.ID, *nestedClientGetResponse.ID) + require.Equal(t, *validNestedResource.Name, *nestedClientGetResponse.Name) + require.Equal(t, *validNestedResource.Type, *nestedClientGetResponse.Type) + require.Equal(t, *validNestedResource.Properties.Description, *nestedClientGetResponse.Properties.Description) + require.Equal(t, *validNestedResource.Properties.ProvisioningState, *nestedClientGetResponse.Properties.ProvisioningState) +} + +func TestNestedClient_BeginCreateOrReplace(t *testing.T) { + nestedClientCreateOrReplaceResponsePoller, err := clientFactory.NewNestedClient(subscriptionIdExpected).BeginCreateOrReplace( + ctx, + "test-rg", + "top", + "nested", + resources.NestedProxyResource{ + Properties: &resources.NestedProxyResourceProperties{ + Description: to.Ptr("valid"), + }, + }, + nil, + ) + require.NoError(t, err) + nestedClientCreateOrReplaceResponse, err := nestedClientCreateOrReplaceResponsePoller.PollUntilDone(ctx, nil) + require.NoError(t, err) + require.Equal(t, *validNestedResource.ID, *nestedClientCreateOrReplaceResponse.ID) + require.Equal(t, *validNestedResource.Name, *nestedClientCreateOrReplaceResponse.Name) + require.Equal(t, *validNestedResource.Type, *nestedClientCreateOrReplaceResponse.Type) + require.Equal(t, *validNestedResource.Properties.Description, *nestedClientCreateOrReplaceResponse.Properties.Description) + require.Equal(t, *validNestedResource.Properties.ProvisioningState, *nestedClientCreateOrReplaceResponse.Properties.ProvisioningState) +} + +func TestNestedClient_BeginUpdate(t *testing.T) { + nestedClientUpdateResponsePoller, err := clientFactory.NewNestedClient(subscriptionIdExpected).BeginUpdate( + ctx, + "test-rg", + "top", + "nested", + resources.NestedProxyResource{ + Properties: &resources.NestedProxyResourceProperties{ + Description: to.Ptr("valid2"), + }, + }, + nil, + ) + require.NoError(t, err) + nestedClientUpdateResponse, err := nestedClientUpdateResponsePoller.PollUntilDone(ctx, nil) + require.NoError(t, err) + require.Equal(t, *validNestedResource.ID, *nestedClientUpdateResponse.ID) + require.Equal(t, *validNestedResource.Name, *nestedClientUpdateResponse.Name) + require.Equal(t, *validNestedResource.Type, *nestedClientUpdateResponse.Type) + require.Equal(t, "valid2", *nestedClientUpdateResponse.Properties.Description) + require.Equal(t, *validNestedResource.Properties.ProvisioningState, *nestedClientUpdateResponse.Properties.ProvisioningState) +} + +func TestNestedClient_BeginDelete(t *testing.T) { + nestedClientDeleteResponsePoller, err := clientFactory.NewNestedClient(subscriptionIdExpected).BeginDelete(ctx, "test-rg", "top", "nested", nil) + require.NoError(t, err) + nestedClientDeleteResponse, err := nestedClientDeleteResponsePoller.Poll(ctx) + require.NoError(t, err) + require.Equal(t, http.StatusNoContent, nestedClientDeleteResponse.StatusCode) +} + +func TestNestedClient_NewListByTopLevelTrackedResourcePager(t *testing.T) { + nestedClientListByTopLevelTrackedResourceResponsePager := clientFactory.NewNestedClient(subscriptionIdExpected).NewListByTopLevelTrackedResourcePager("test-rg", "top", nil) + require.True(t, nestedClientListByTopLevelTrackedResourceResponsePager.More()) + nestedClientListByTopLevelTrackedResourceResponse, err := nestedClientListByTopLevelTrackedResourceResponsePager.NextPage(ctx) + require.NoError(t, err) + require.Len(t, nestedClientListByTopLevelTrackedResourceResponse.Value, 1) + require.Equal(t, *validNestedResource.ID, *nestedClientListByTopLevelTrackedResourceResponse.Value[0].ID) + require.Equal(t, *validNestedResource.Name, *nestedClientListByTopLevelTrackedResourceResponse.Value[0].Name) + require.Equal(t, *validNestedResource.Type, *nestedClientListByTopLevelTrackedResourceResponse.Value[0].Type) + require.Equal(t, *validNestedResource.Properties.Description, *nestedClientListByTopLevelTrackedResourceResponse.Value[0].Properties.Description) + require.Equal(t, *validNestedResource.Properties.ProvisioningState, *nestedClientListByTopLevelTrackedResourceResponse.Value[0].Properties.ProvisioningState) +} diff --git a/test/azure-http-specs/azure/resource-manager/resources/singleton_client_test.go b/test/azure-http-specs/azure/resource-manager/resources/singleton_client_test.go new file mode 100644 index 000000000000..70b696ca8f24 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/singleton_client_test.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package resources_test + +import ( + "resources" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +var ( + validSingletonResource = resources.SingletonTrackedResource{ + ID: to.Ptr("/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Azure.ResourceManager.Resources/singletonTrackedResources/default"), + Name: to.Ptr("default"), + Type: to.Ptr("Azure.ResourceManager.Resources/singletonTrackedResources"), + Location: to.Ptr("eastus"), + Properties: &resources.SingletonTrackedResourceProperties{ + Description: to.Ptr("valid"), + ProvisioningState: to.Ptr(resources.ProvisioningStateSucceeded), + }, + SystemData: &resources.SystemData{ + CreatedBy: to.Ptr("AzureSDK"), + CreatedByType: to.Ptr(resources.CreatedByTypeUser), + CreatedAt: to.Ptr(time.Now()), + LastModifiedBy: to.Ptr("AzureSDK"), + LastModifiedAt: to.Ptr(time.Now()), + LastModifiedByType: to.Ptr(resources.CreatedByTypeUser), + }, + } +) + +func TestSingletonClient_GetByResourceGroup(t *testing.T) { + singletonClientGetByResourceGroupResponse, err := clientFactory.NewSingletonClient(subscriptionIdExpected).GetByResourceGroup( + ctx, + "test-rg", + nil, + ) + require.NoError(t, err) + require.Equal(t, *validSingletonResource.ID, *singletonClientGetByResourceGroupResponse.ID) + require.Equal(t, *validSingletonResource.Name, *singletonClientGetByResourceGroupResponse.Name) + require.Equal(t, *validSingletonResource.Type, *singletonClientGetByResourceGroupResponse.Type) + require.Equal(t, *validSingletonResource.Location, *singletonClientGetByResourceGroupResponse.Location) + require.Equal(t, *validSingletonResource.Properties.Description, *singletonClientGetByResourceGroupResponse.Properties.Description) + require.Equal(t, *validSingletonResource.Properties.ProvisioningState, *singletonClientGetByResourceGroupResponse.Properties.ProvisioningState) +} + +func TestSingletonClient_BeginCreateOrUpdate(t *testing.T) { + singletonClientBeginCreateOrUpdatePoller, err := clientFactory.NewSingletonClient(subscriptionIdExpected).BeginCreateOrUpdate( + ctx, + "test-rg", + resources.SingletonTrackedResource{ + Location: to.Ptr("eastus"), + Properties: &resources.SingletonTrackedResourceProperties{ + Description: to.Ptr("valid"), + }, + }, + nil, + ) + require.NoError(t, err) + singletonClientBeginCreateOrUpdateResponse, err := singletonClientBeginCreateOrUpdatePoller.PollUntilDone(ctx, nil) + require.NoError(t, err) + require.Equal(t, *validSingletonResource.ID, *singletonClientBeginCreateOrUpdateResponse.ID) + require.Equal(t, *validSingletonResource.Name, *singletonClientBeginCreateOrUpdateResponse.Name) + require.Equal(t, *validSingletonResource.Type, *singletonClientBeginCreateOrUpdateResponse.Type) + require.Equal(t, *validSingletonResource.Location, *singletonClientBeginCreateOrUpdateResponse.Location) + require.Equal(t, *validSingletonResource.Properties.Description, *singletonClientBeginCreateOrUpdateResponse.Properties.Description) + require.Equal(t, *validSingletonResource.Properties.ProvisioningState, *singletonClientBeginCreateOrUpdateResponse.Properties.ProvisioningState) +} + +func TestSingletonClient_Update(t *testing.T) { + singletonClientUpdateResponse, err := clientFactory.NewSingletonClient(subscriptionIdExpected).Update( + ctx, + "test-rg", + resources.SingletonTrackedResource{ + Properties: &resources.SingletonTrackedResourceProperties{ + Description: to.Ptr("valid2"), + }, + }, + nil, + ) + require.NoError(t, err) + require.Equal(t, *validSingletonResource.ID, *singletonClientUpdateResponse.ID) + require.Equal(t, *validSingletonResource.Name, *singletonClientUpdateResponse.Name) + require.Equal(t, *validSingletonResource.Type, *singletonClientUpdateResponse.Type) + require.Equal(t, *validSingletonResource.Location, *singletonClientUpdateResponse.Location) + require.Equal(t, "valid2", *singletonClientUpdateResponse.Properties.Description) + require.Equal(t, *validSingletonResource.Properties.ProvisioningState, *singletonClientUpdateResponse.Properties.ProvisioningState) +} + +func TestSingletonClient_NewListByResourceGroupPager(t *testing.T) { + singletonClientListByResourceGroupResponsePager := clientFactory.NewSingletonClient(subscriptionIdExpected).NewListByResourceGroupPager("test-rg", nil) + require.True(t, singletonClientListByResourceGroupResponsePager.More()) + singletonClientListByResourceGroupResponse, err := singletonClientListByResourceGroupResponsePager.NextPage(ctx) + require.NoError(t, err) + require.Len(t, singletonClientListByResourceGroupResponse.Value, 1) + require.Equal(t, *validSingletonResource.ID, *singletonClientListByResourceGroupResponse.Value[0].ID) + require.Equal(t, *validSingletonResource.Name, *singletonClientListByResourceGroupResponse.Value[0].Name) + require.Equal(t, *validSingletonResource.Type, *singletonClientListByResourceGroupResponse.Value[0].Type) + require.Equal(t, *validSingletonResource.Location, *singletonClientListByResourceGroupResponse.Value[0].Location) + require.Equal(t, *validSingletonResource.Properties.Description, *singletonClientListByResourceGroupResponse.Value[0].Properties.Description) + require.Equal(t, *validSingletonResource.Properties.ProvisioningState, *singletonClientListByResourceGroupResponse.Value[0].Properties.ProvisioningState) +} diff --git a/test/azure-http-specs/azure/resource-manager/resources/testdata/_metadata.json b/test/azure-http-specs/azure/resource-manager/resources/testdata/_metadata.json new file mode 100644 index 000000000000..1fabb3fff33f --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Azure.ResourceManager.Resources": "2023-12-01-preview" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/resource-manager/resources/toplevel_client_test.go b/test/azure-http-specs/azure/resource-manager/resources/toplevel_client_test.go new file mode 100644 index 000000000000..69bf9715f248 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/toplevel_client_test.go @@ -0,0 +1,155 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package resources_test + +import ( + "fmt" + "net/http" + "testing" + "time" + + "resources" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +var ( + validTopLevelResource = resources.TopLevelTrackedResource{ + ID: to.Ptr(fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Azure.ResourceManager.Resources/topLevelTrackedResources/top", subscriptionIdExpected, resourceGroupExpected)), + Name: to.Ptr("top"), + Type: to.Ptr("Azure.ResourceManager.Resources/topLevelTrackedResources"), + Location: to.Ptr("eastus"), + Properties: &resources.TopLevelTrackedResourceProperties{ + Description: to.Ptr("valid"), + ProvisioningState: to.Ptr(resources.ProvisioningStateSucceeded), + }, + SystemData: &resources.SystemData{ + CreatedBy: to.Ptr("AzureSDK"), + CreatedByType: to.Ptr(resources.CreatedByTypeUser), + CreatedAt: to.Ptr(time.Now()), + LastModifiedBy: to.Ptr("AzureSDK"), + LastModifiedAt: to.Ptr(time.Now()), + LastModifiedByType: to.Ptr(resources.CreatedByTypeUser), + }, + } +) + +func TestTopLevelClient_Get(t *testing.T) { + topLevelClientGetResponse, err := clientFactory.NewTopLevelClient(subscriptionIdExpected).Get( + ctx, + "test-rg", + "top", + nil, + ) + require.NoError(t, err) + require.Equal(t, *validTopLevelResource.ID, *topLevelClientGetResponse.ID) + require.Equal(t, *validTopLevelResource.Name, *topLevelClientGetResponse.Name) + require.Equal(t, *validTopLevelResource.Type, *topLevelClientGetResponse.Type) + require.Equal(t, *validTopLevelResource.Location, *topLevelClientGetResponse.Location) + require.Equal(t, *validTopLevelResource.Properties.Description, *topLevelClientGetResponse.Properties.Description) + require.Equal(t, *validTopLevelResource.Properties.ProvisioningState, *topLevelClientGetResponse.Properties.ProvisioningState) +} + +func TestTopLevelClient_CreateOrReplace(t *testing.T) { + topLevelClientCreateOrReplaceResponsePoller, err := clientFactory.NewTopLevelClient(subscriptionIdExpected).BeginCreateOrReplace( + ctx, + "test-rg", + "top", + resources.TopLevelTrackedResource{ + Location: to.Ptr("eastus"), + Properties: &resources.TopLevelTrackedResourceProperties{ + Description: to.Ptr("valid"), + }, + }, + nil, + ) + require.NoError(t, err) + topLevelClientCreateOrReplaceResponse, err := topLevelClientCreateOrReplaceResponsePoller.PollUntilDone(ctx, nil) + require.NoError(t, err) + require.Equal(t, *validTopLevelResource.ID, *topLevelClientCreateOrReplaceResponse.ID) + require.Equal(t, *validTopLevelResource.Name, *topLevelClientCreateOrReplaceResponse.Name) + require.Equal(t, *validTopLevelResource.Type, *topLevelClientCreateOrReplaceResponse.Type) + require.Equal(t, *validTopLevelResource.Location, *topLevelClientCreateOrReplaceResponse.Location) + require.Equal(t, *validTopLevelResource.Properties.Description, *topLevelClientCreateOrReplaceResponse.Properties.Description) + require.Equal(t, *validTopLevelResource.Properties.ProvisioningState, *topLevelClientCreateOrReplaceResponse.Properties.ProvisioningState) +} + +func TestTopLevelClient_BeginUpdate(t *testing.T) { + topLevelClientUpdateResponsePoller, err := clientFactory.NewTopLevelClient(subscriptionIdExpected).BeginUpdate( + ctx, + "test-rg", + "top", + resources.TopLevelTrackedResource{ + Properties: &resources.TopLevelTrackedResourceProperties{ + Description: to.Ptr("valid2"), + }, + }, + nil, + ) + require.NoError(t, err) + topLevelClientUpdateResponse, err := topLevelClientUpdateResponsePoller.PollUntilDone(ctx, nil) + require.NoError(t, err) + require.Equal(t, *validTopLevelResource.ID, *topLevelClientUpdateResponse.ID) + require.Equal(t, *validTopLevelResource.Name, *topLevelClientUpdateResponse.Name) + require.Equal(t, *validTopLevelResource.Type, *topLevelClientUpdateResponse.Type) + require.Equal(t, *validTopLevelResource.Location, *topLevelClientUpdateResponse.Location) + require.Equal(t, "valid2", *topLevelClientUpdateResponse.Properties.Description) + require.Equal(t, *validTopLevelResource.Properties.ProvisioningState, *topLevelClientUpdateResponse.Properties.ProvisioningState) +} + +func TestTopLevelClient_BeginDelete(t *testing.T) { + topLevelClientDeleteResponsePoller, err := clientFactory.NewTopLevelClient(subscriptionIdExpected).BeginDelete( + ctx, + "test-rg", + "top", + nil, + ) + require.NoError(t, err) + topLevelClientDeleteResponse, err := topLevelClientDeleteResponsePoller.Poll(ctx) + require.NoError(t, err) + require.Equal(t, http.StatusNoContent, topLevelClientDeleteResponse.StatusCode) +} + +func TestTopLevelClient_NewListByResourceGroupPager(t *testing.T) { + topLevelClientListByResourceGroupResponsePager := clientFactory.NewTopLevelClient(subscriptionIdExpected).NewListByResourceGroupPager("test-rg", nil) + require.True(t, topLevelClientListByResourceGroupResponsePager.More()) + topLevelClientListByResourceGroupResponse, err := topLevelClientListByResourceGroupResponsePager.NextPage(ctx) + require.NoError(t, err) + require.Len(t, topLevelClientListByResourceGroupResponse.Value, 1) + require.Equal(t, *validTopLevelResource.ID, *topLevelClientListByResourceGroupResponse.Value[0].ID) + require.Equal(t, *validTopLevelResource.Name, *topLevelClientListByResourceGroupResponse.Value[0].Name) + require.Equal(t, *validTopLevelResource.Type, *topLevelClientListByResourceGroupResponse.Value[0].Type) + require.Equal(t, *validTopLevelResource.Location, *topLevelClientListByResourceGroupResponse.Value[0].Location) + require.Equal(t, *validTopLevelResource.Properties.Description, *topLevelClientListByResourceGroupResponse.Value[0].Properties.Description) + require.Equal(t, *validTopLevelResource.Properties.ProvisioningState, *topLevelClientListByResourceGroupResponse.Value[0].Properties.ProvisioningState) +} + +func TestTopLevelClient_NewListBySubscriptionPager(t *testing.T) { + TopLevelClientListBySubscriptionResponsePager := clientFactory.NewTopLevelClient(subscriptionIdExpected).NewListBySubscriptionPager(nil) + require.True(t, TopLevelClientListBySubscriptionResponsePager.More()) + TopLevelClientListBySubscriptionResponse, err := TopLevelClientListBySubscriptionResponsePager.NextPage(ctx) + require.NoError(t, err) + require.Len(t, TopLevelClientListBySubscriptionResponse.Value, 1) + require.Equal(t, *validTopLevelResource.ID, *TopLevelClientListBySubscriptionResponse.Value[0].ID) + require.Equal(t, *validTopLevelResource.Name, *TopLevelClientListBySubscriptionResponse.Value[0].Name) + require.Equal(t, *validTopLevelResource.Type, *TopLevelClientListBySubscriptionResponse.Value[0].Type) + require.Equal(t, *validTopLevelResource.Location, *TopLevelClientListBySubscriptionResponse.Value[0].Location) + require.Equal(t, *validTopLevelResource.Properties.Description, *TopLevelClientListBySubscriptionResponse.Value[0].Properties.Description) + require.Equal(t, *validTopLevelResource.Properties.ProvisioningState, *TopLevelClientListBySubscriptionResponse.Value[0].Properties.ProvisioningState) +} + +func TestTopLevelClient_ActionSync(t *testing.T) { + _, err := clientFactory.NewTopLevelClient(subscriptionIdExpected).ActionSync( + ctx, + resourceGroupExpected, + "top", + resources.NotificationDetails{ + Message: to.Ptr("Resource action at top level."), + Urgent: to.Ptr(true), + }, + nil, + ) + require.NoError(t, err) +} diff --git a/test/azure-http-specs/azure/resource-manager/resources/utils_test.go b/test/azure-http-specs/azure/resource-manager/resources/utils_test.go new file mode 100644 index 000000000000..d36a4caffe91 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/utils_test.go @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package resources_test + +import ( + "context" + "resources" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" +) + +var ( + ctx context.Context + clientFactory *resources.ClientFactory + + subscriptionIdExpected = "00000000-0000-0000-0000-000000000000" + resourceGroupExpected = "test-rg" +) + +func TestMain(m *testing.M) { + ctx = context.Background() + clientFactory, _ = resources.NewClientFactory(&azfake.TokenCredential{}, &arm.ClientOptions{ + ClientOptions: azcore.ClientOptions{ + Cloud: cloud.Configuration{ + Services: map[cloud.ServiceName]cloud.ServiceConfiguration{ + cloud.ResourceManager: { + Audience: "fake_audience", + Endpoint: "http://localhost:3000", + }, + }, + }, + InsecureAllowCredentialWithHTTP: true, + }, + }) + + m.Run() +} diff --git a/test/azure-http-specs/azure/resource-manager/resources/zz_client_factory.go b/test/azure-http-specs/azure/resource-manager/resources/zz_client_factory.go new file mode 100644 index 000000000000..b617a4b17c8e --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/zz_client_factory.go @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package resources + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + internal: internal, + }, nil +} + +// NewExtensionsResourcesClient creates a new instance of ExtensionsResourcesClient. +func (c *ClientFactory) NewExtensionsResourcesClient() *ExtensionsResourcesClient { + return &ExtensionsResourcesClient{ + internal: c.internal, + } +} + +// NewLocationResourcesClient creates a new instance of LocationResourcesClient. +func (c *ClientFactory) NewLocationResourcesClient(subscriptionID string) *LocationResourcesClient { + return &LocationResourcesClient{ + subscriptionID: subscriptionID, + internal: c.internal, + } +} + +// NewNestedClient creates a new instance of NestedClient. +func (c *ClientFactory) NewNestedClient(subscriptionID string) *NestedClient { + return &NestedClient{ + subscriptionID: subscriptionID, + internal: c.internal, + } +} + +// NewSingletonClient creates a new instance of SingletonClient. +func (c *ClientFactory) NewSingletonClient(subscriptionID string) *SingletonClient { + return &SingletonClient{ + subscriptionID: subscriptionID, + internal: c.internal, + } +} + +// NewTopLevelClient creates a new instance of TopLevelClient. +func (c *ClientFactory) NewTopLevelClient(subscriptionID string) *TopLevelClient { + return &TopLevelClient{ + subscriptionID: subscriptionID, + internal: c.internal, + } +} diff --git a/test/azure-http-specs/azure/resource-manager/resources/zz_constants.go b/test/azure-http-specs/azure/resource-manager/resources/zz_constants.go new file mode 100644 index 000000000000..7d081ebba3a4 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/zz_constants.go @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package resources + +const ( + version20231201Preview string = "2023-12-01-preview" +) + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +type ProvisioningState string + +const ( + ProvisioningStateAccepted ProvisioningState = "Accepted" + // ProvisioningStateCanceled - Resource creation was canceled. + ProvisioningStateCanceled ProvisioningState = "Canceled" + ProvisioningStateDeleting ProvisioningState = "Deleting" + // ProvisioningStateFailed - Resource creation failed. + ProvisioningStateFailed ProvisioningState = "Failed" + ProvisioningStateProvisioning ProvisioningState = "Provisioning" + // ProvisioningStateSucceeded - Resource has been created. + ProvisioningStateSucceeded ProvisioningState = "Succeeded" + ProvisioningStateUpdating ProvisioningState = "Updating" +) + +// PossibleProvisioningStateValues returns the possible values for the ProvisioningState const type. +func PossibleProvisioningStateValues() []ProvisioningState { + return []ProvisioningState{ + ProvisioningStateAccepted, + ProvisioningStateCanceled, + ProvisioningStateDeleting, + ProvisioningStateFailed, + ProvisioningStateProvisioning, + ProvisioningStateSucceeded, + ProvisioningStateUpdating, + } +} diff --git a/test/azure-http-specs/azure/resource-manager/resources/zz_extensionsresources_client.go b/test/azure-http-specs/azure/resource-manager/resources/zz_extensionsresources_client.go new file mode 100644 index 000000000000..3e7d32f95b10 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/zz_extensionsresources_client.go @@ -0,0 +1,337 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package resources + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ExtensionsResourcesClient - The interface of extensions resources, +// it contains 4 kinds of scopes (resource, resource group, subscription and tenant) +// Don't use this type directly, use NewExtensionsResourcesClient() instead. +// +// Generated from API version 2023-12-01-preview +type ExtensionsResourcesClient struct { + internal *arm.Client +} + +// NewExtensionsResourcesClient creates a new instance of ExtensionsResourcesClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewExtensionsResourcesClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*ExtensionsResourcesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ExtensionsResourcesClient{ + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create a ExtensionsResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - extensionsResourceName - The name of the ExtensionsResource +// - resource - Resource create parameters. +// - options - ExtensionsResourcesClientBeginCreateOrUpdateOptions contains the optional parameters for the ExtensionsResourcesClient.BeginCreateOrUpdate +// method. +func (client *ExtensionsResourcesClient) BeginCreateOrUpdate(ctx context.Context, resourceURI string, extensionsResourceName string, resource ExtensionsResource, options *ExtensionsResourcesClientBeginCreateOrUpdateOptions) (*runtime.Poller[ExtensionsResourcesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceURI, extensionsResourceName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExtensionsResourcesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExtensionsResourcesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create a ExtensionsResource +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ExtensionsResourcesClient) createOrUpdate(ctx context.Context, resourceURI string, extensionsResourceName string, resource ExtensionsResource, options *ExtensionsResourcesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ExtensionsResourcesClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceURI, extensionsResourceName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *ExtensionsResourcesClient) createOrUpdateCreateRequest(ctx context.Context, resourceURI string, extensionsResourceName string, resource ExtensionsResource, _ *ExtensionsResourcesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Azure.ResourceManager.Resources/extensionsResources/{extensionsResourceName}" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + if extensionsResourceName == "" { + return nil, errors.New("parameter extensionsResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{extensionsResourceName}", url.PathEscape(extensionsResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// Delete - Delete a ExtensionsResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - extensionsResourceName - The name of the ExtensionsResource +// - options - ExtensionsResourcesClientDeleteOptions contains the optional parameters for the ExtensionsResourcesClient.Delete +// method. +func (client *ExtensionsResourcesClient) Delete(ctx context.Context, resourceURI string, extensionsResourceName string, options *ExtensionsResourcesClientDeleteOptions) (ExtensionsResourcesClientDeleteResponse, error) { + var err error + const operationName = "ExtensionsResourcesClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceURI, extensionsResourceName, options) + if err != nil { + return ExtensionsResourcesClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExtensionsResourcesClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ExtensionsResourcesClientDeleteResponse{}, err + } + return ExtensionsResourcesClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ExtensionsResourcesClient) deleteCreateRequest(ctx context.Context, resourceURI string, extensionsResourceName string, _ *ExtensionsResourcesClientDeleteOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Azure.ResourceManager.Resources/extensionsResources/{extensionsResourceName}" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + if extensionsResourceName == "" { + return nil, errors.New("parameter extensionsResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{extensionsResourceName}", url.PathEscape(extensionsResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a ExtensionsResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - extensionsResourceName - The name of the ExtensionsResource +// - options - ExtensionsResourcesClientGetOptions contains the optional parameters for the ExtensionsResourcesClient.Get method. +func (client *ExtensionsResourcesClient) Get(ctx context.Context, resourceURI string, extensionsResourceName string, options *ExtensionsResourcesClientGetOptions) (ExtensionsResourcesClientGetResponse, error) { + var err error + const operationName = "ExtensionsResourcesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceURI, extensionsResourceName, options) + if err != nil { + return ExtensionsResourcesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExtensionsResourcesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExtensionsResourcesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ExtensionsResourcesClient) getCreateRequest(ctx context.Context, resourceURI string, extensionsResourceName string, _ *ExtensionsResourcesClientGetOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Azure.ResourceManager.Resources/extensionsResources/{extensionsResourceName}" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + if extensionsResourceName == "" { + return nil, errors.New("parameter extensionsResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{extensionsResourceName}", url.PathEscape(extensionsResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ExtensionsResourcesClient) getHandleResponse(resp *http.Response) (ExtensionsResourcesClientGetResponse, error) { + result := ExtensionsResourcesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExtensionsResource); err != nil { + return ExtensionsResourcesClientGetResponse{}, err + } + return result, nil +} + +// NewListByScopePager - List ExtensionsResource resources by parent +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - options - ExtensionsResourcesClientListByScopeOptions contains the optional parameters for the ExtensionsResourcesClient.NewListByScopePager +// method. +func (client *ExtensionsResourcesClient) NewListByScopePager(resourceURI string, options *ExtensionsResourcesClientListByScopeOptions) *runtime.Pager[ExtensionsResourcesClientListByScopeResponse] { + return runtime.NewPager(runtime.PagingHandler[ExtensionsResourcesClientListByScopeResponse]{ + More: func(page ExtensionsResourcesClientListByScopeResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ExtensionsResourcesClientListByScopeResponse) (ExtensionsResourcesClientListByScopeResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ExtensionsResourcesClient.NewListByScopePager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByScopeCreateRequest(ctx, resourceURI, options) + }, nil) + if err != nil { + return ExtensionsResourcesClientListByScopeResponse{}, err + } + return client.listByScopeHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByScopeCreateRequest creates the ListByScope request. +func (client *ExtensionsResourcesClient) listByScopeCreateRequest(ctx context.Context, resourceURI string, _ *ExtensionsResourcesClientListByScopeOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Azure.ResourceManager.Resources/extensionsResources" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByScopeHandleResponse handles the ListByScope response. +func (client *ExtensionsResourcesClient) listByScopeHandleResponse(resp *http.Response) (ExtensionsResourcesClientListByScopeResponse, error) { + result := ExtensionsResourcesClientListByScopeResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExtensionsResourceListResult); err != nil { + return ExtensionsResourcesClientListByScopeResponse{}, err + } + return result, nil +} + +// Update - Update a ExtensionsResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - extensionsResourceName - The name of the ExtensionsResource +// - properties - The resource properties to be updated. +// - options - ExtensionsResourcesClientUpdateOptions contains the optional parameters for the ExtensionsResourcesClient.Update +// method. +func (client *ExtensionsResourcesClient) Update(ctx context.Context, resourceURI string, extensionsResourceName string, properties ExtensionsResource, options *ExtensionsResourcesClientUpdateOptions) (ExtensionsResourcesClientUpdateResponse, error) { + var err error + const operationName = "ExtensionsResourcesClient.Update" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceURI, extensionsResourceName, properties, options) + if err != nil { + return ExtensionsResourcesClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExtensionsResourcesClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExtensionsResourcesClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *ExtensionsResourcesClient) updateCreateRequest(ctx context.Context, resourceURI string, extensionsResourceName string, properties ExtensionsResource, _ *ExtensionsResourcesClientUpdateOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Azure.ResourceManager.Resources/extensionsResources/{extensionsResourceName}" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + if extensionsResourceName == "" { + return nil, errors.New("parameter extensionsResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{extensionsResourceName}", url.PathEscape(extensionsResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *ExtensionsResourcesClient) updateHandleResponse(resp *http.Response) (ExtensionsResourcesClientUpdateResponse, error) { + result := ExtensionsResourcesClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExtensionsResource); err != nil { + return ExtensionsResourcesClientUpdateResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/resources/zz_locationresources_client.go b/test/azure-http-specs/azure/resource-manager/resources/zz_locationresources_client.go new file mode 100644 index 000000000000..24d7b8944646 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/zz_locationresources_client.go @@ -0,0 +1,350 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package resources + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// LocationResourcesClient contains the methods for the LocationResources group. +// Don't use this type directly, use NewLocationResourcesClient() instead. +// +// Generated from API version 2023-12-01-preview +type LocationResourcesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewLocationResourcesClient creates a new instance of LocationResourcesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewLocationResourcesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*LocationResourcesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &LocationResourcesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Create a LocationResource +// If the operation fails it returns an *azcore.ResponseError type. +// - location - The name of the Azure region. +// - locationResourceName - The name of the LocationResource +// - resource - Resource create parameters. +// - options - LocationResourcesClientCreateOrUpdateOptions contains the optional parameters for the LocationResourcesClient.CreateOrUpdate +// method. +func (client *LocationResourcesClient) CreateOrUpdate(ctx context.Context, location string, locationResourceName string, resource LocationResource, options *LocationResourcesClientCreateOrUpdateOptions) (LocationResourcesClientCreateOrUpdateResponse, error) { + var err error + const operationName = "LocationResourcesClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, location, locationResourceName, resource, options) + if err != nil { + return LocationResourcesClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LocationResourcesClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return LocationResourcesClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *LocationResourcesClient) createOrUpdateCreateRequest(ctx context.Context, location string, locationResourceName string, resource LocationResource, _ *LocationResourcesClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Azure.ResourceManager.Resources/locations/{location}/locationResources/{locationResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if locationResourceName == "" { + return nil, errors.New("parameter locationResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{locationResourceName}", url.PathEscape(locationResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *LocationResourcesClient) createOrUpdateHandleResponse(resp *http.Response) (LocationResourcesClientCreateOrUpdateResponse, error) { + result := LocationResourcesClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LocationResource); err != nil { + return LocationResourcesClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Delete a LocationResource +// If the operation fails it returns an *azcore.ResponseError type. +// - location - The name of the Azure region. +// - locationResourceName - The name of the LocationResource +// - options - LocationResourcesClientDeleteOptions contains the optional parameters for the LocationResourcesClient.Delete +// method. +func (client *LocationResourcesClient) Delete(ctx context.Context, location string, locationResourceName string, options *LocationResourcesClientDeleteOptions) (LocationResourcesClientDeleteResponse, error) { + var err error + const operationName = "LocationResourcesClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, location, locationResourceName, options) + if err != nil { + return LocationResourcesClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LocationResourcesClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return LocationResourcesClientDeleteResponse{}, err + } + return LocationResourcesClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *LocationResourcesClient) deleteCreateRequest(ctx context.Context, location string, locationResourceName string, _ *LocationResourcesClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Azure.ResourceManager.Resources/locations/{location}/locationResources/{locationResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if locationResourceName == "" { + return nil, errors.New("parameter locationResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{locationResourceName}", url.PathEscape(locationResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a LocationResource +// If the operation fails it returns an *azcore.ResponseError type. +// - location - The name of the Azure region. +// - locationResourceName - The name of the LocationResource +// - options - LocationResourcesClientGetOptions contains the optional parameters for the LocationResourcesClient.Get method. +func (client *LocationResourcesClient) Get(ctx context.Context, location string, locationResourceName string, options *LocationResourcesClientGetOptions) (LocationResourcesClientGetResponse, error) { + var err error + const operationName = "LocationResourcesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, location, locationResourceName, options) + if err != nil { + return LocationResourcesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LocationResourcesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return LocationResourcesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *LocationResourcesClient) getCreateRequest(ctx context.Context, location string, locationResourceName string, _ *LocationResourcesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Azure.ResourceManager.Resources/locations/{location}/locationResources/{locationResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if locationResourceName == "" { + return nil, errors.New("parameter locationResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{locationResourceName}", url.PathEscape(locationResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *LocationResourcesClient) getHandleResponse(resp *http.Response) (LocationResourcesClientGetResponse, error) { + result := LocationResourcesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LocationResource); err != nil { + return LocationResourcesClientGetResponse{}, err + } + return result, nil +} + +// NewListByLocationPager - List LocationResource resources by SubscriptionLocationResource +// - location - The name of the Azure region. +// - options - LocationResourcesClientListByLocationOptions contains the optional parameters for the LocationResourcesClient.NewListByLocationPager +// method. +func (client *LocationResourcesClient) NewListByLocationPager(location string, options *LocationResourcesClientListByLocationOptions) *runtime.Pager[LocationResourcesClientListByLocationResponse] { + return runtime.NewPager(runtime.PagingHandler[LocationResourcesClientListByLocationResponse]{ + More: func(page LocationResourcesClientListByLocationResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *LocationResourcesClientListByLocationResponse) (LocationResourcesClientListByLocationResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "LocationResourcesClient.NewListByLocationPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByLocationCreateRequest(ctx, location, options) + }, nil) + if err != nil { + return LocationResourcesClientListByLocationResponse{}, err + } + return client.listByLocationHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByLocationCreateRequest creates the ListByLocation request. +func (client *LocationResourcesClient) listByLocationCreateRequest(ctx context.Context, location string, _ *LocationResourcesClientListByLocationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Azure.ResourceManager.Resources/locations/{location}/locationResources" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByLocationHandleResponse handles the ListByLocation response. +func (client *LocationResourcesClient) listByLocationHandleResponse(resp *http.Response) (LocationResourcesClientListByLocationResponse, error) { + result := LocationResourcesClientListByLocationResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LocationResourceListResult); err != nil { + return LocationResourcesClientListByLocationResponse{}, err + } + return result, nil +} + +// Update - Update a LocationResource +// If the operation fails it returns an *azcore.ResponseError type. +// - location - The name of the Azure region. +// - locationResourceName - The name of the LocationResource +// - properties - The resource properties to be updated. +// - options - LocationResourcesClientUpdateOptions contains the optional parameters for the LocationResourcesClient.Update +// method. +func (client *LocationResourcesClient) Update(ctx context.Context, location string, locationResourceName string, properties LocationResource, options *LocationResourcesClientUpdateOptions) (LocationResourcesClientUpdateResponse, error) { + var err error + const operationName = "LocationResourcesClient.Update" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, location, locationResourceName, properties, options) + if err != nil { + return LocationResourcesClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LocationResourcesClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return LocationResourcesClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *LocationResourcesClient) updateCreateRequest(ctx context.Context, location string, locationResourceName string, properties LocationResource, _ *LocationResourcesClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Azure.ResourceManager.Resources/locations/{location}/locationResources/{locationResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if locationResourceName == "" { + return nil, errors.New("parameter locationResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{locationResourceName}", url.PathEscape(locationResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *LocationResourcesClient) updateHandleResponse(resp *http.Response) (LocationResourcesClientUpdateResponse, error) { + result := LocationResourcesClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LocationResource); err != nil { + return LocationResourcesClientUpdateResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/resources/zz_models.go b/test/azure-http-specs/azure/resource-manager/resources/zz_models.go new file mode 100644 index 000000000000..d99782506ad4 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/zz_models.go @@ -0,0 +1,231 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package resources + +import "time" + +// ExtensionsResource - Concrete extension resource types can be created by aliasing this type using a specific property type. +type ExtensionsResource struct { + // The resource-specific properties for this resource. + Properties *ExtensionsResourceProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ExtensionsResourceListResult - The response of a ExtensionsResource list operation. +type ExtensionsResourceListResult struct { + // REQUIRED; The ExtensionsResource items on this page + Value []*ExtensionsResource + + // The link to the next page of items + NextLink *string +} + +// ExtensionsResourceProperties - ExtensionsResource properties +type ExtensionsResourceProperties struct { + // The description of the resource. + Description *string + + // READ-ONLY; The status of the last operation. + ProvisioningState *ProvisioningState +} + +// LocationResource - Concrete proxy resource types can be created by aliasing this type using a specific property type. +type LocationResource struct { + // The resource-specific properties for this resource. + Properties *LocationResourceProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// LocationResourceListResult - The response of a LocationResource list operation. +type LocationResourceListResult struct { + // REQUIRED; The LocationResource items on this page + Value []*LocationResource + + // The link to the next page of items + NextLink *string +} + +// LocationResourceProperties - Location resource properties +type LocationResourceProperties struct { + // The description of the resource. + Description *string + + // READ-ONLY; The status of the last operation. + ProvisioningState *ProvisioningState +} + +// NestedProxyResource - Nested child of Top Level Tracked Resource. +type NestedProxyResource struct { + // The resource-specific properties for this resource. + Properties *NestedProxyResourceProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// NestedProxyResourceListResult - The response of a NestedProxyResource list operation. +type NestedProxyResourceListResult struct { + // REQUIRED; The NestedProxyResource items on this page + Value []*NestedProxyResource + + // The link to the next page of items + NextLink *string +} + +// NestedProxyResourceProperties - Nested Proxy Resource Properties. +type NestedProxyResourceProperties struct { + // Nested resource description. + Description *string + + // READ-ONLY; Provisioning State of the nested child Resource + ProvisioningState *ProvisioningState +} + +// NotificationDetails - The details of a user notification. +type NotificationDetails struct { + // REQUIRED; The notification message. + Message *string + + // REQUIRED; If true, the notification is urgent. + Urgent *bool +} + +// SingletonTrackedResource - Concrete tracked resource types can be created by aliasing this type using a specific property +// type. +type SingletonTrackedResource struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *SingletonTrackedResourceProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// SingletonTrackedResourceListResult - The response of a SingletonTrackedResource list operation. +type SingletonTrackedResourceListResult struct { + // REQUIRED; The SingletonTrackedResource items on this page + Value []*SingletonTrackedResource + + // The link to the next page of items + NextLink *string +} + +// SingletonTrackedResourceProperties - Singleton Arm Resource Properties. +type SingletonTrackedResourceProperties struct { + // The description of the resource. + Description *string + + // READ-ONLY; The status of the last operation. + ProvisioningState *ProvisioningState +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time + + // The identity that created the resource. + CreatedBy *string + + // The type of identity that created the resource. + CreatedByType *CreatedByType + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time + + // The identity that last modified the resource. + LastModifiedBy *string + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType +} + +// TopLevelTrackedResource - Concrete tracked resource types can be created by aliasing this type using a specific property +// type. +type TopLevelTrackedResource struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *TopLevelTrackedResourceProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// TopLevelTrackedResourceListResult - The response of a TopLevelTrackedResource list operation. +type TopLevelTrackedResourceListResult struct { + // REQUIRED; The TopLevelTrackedResource items on this page + Value []*TopLevelTrackedResource + + // The link to the next page of items + NextLink *string +} + +// TopLevelTrackedResourceProperties - Top Level Arm Resource Properties. +type TopLevelTrackedResourceProperties struct { + // The description of the resource. + Description *string + + // READ-ONLY; The status of the last operation. + ProvisioningState *ProvisioningState +} diff --git a/test/azure-http-specs/azure/resource-manager/resources/zz_models_serde.go b/test/azure-http-specs/azure/resource-manager/resources/zz_models_serde.go new file mode 100644 index 000000000000..f6ca35fb536f --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/zz_models_serde.go @@ -0,0 +1,681 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package resources + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type ExtensionsResource. +func (e ExtensionsResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", e.ID) + populate(objectMap, "name", e.Name) + populate(objectMap, "properties", e.Properties) + populate(objectMap, "systemData", e.SystemData) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExtensionsResource. +func (e *ExtensionsResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &e.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &e.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &e.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &e.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &e.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExtensionsResourceListResult. +func (e ExtensionsResourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", e.NextLink) + populate(objectMap, "value", e.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExtensionsResourceListResult. +func (e *ExtensionsResourceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &e.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &e.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExtensionsResourceProperties. +func (e ExtensionsResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", e.Description) + populate(objectMap, "provisioningState", e.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExtensionsResourceProperties. +func (e *ExtensionsResourceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &e.Description) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &e.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LocationResource. +func (l LocationResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", l.ID) + populate(objectMap, "name", l.Name) + populate(objectMap, "properties", l.Properties) + populate(objectMap, "systemData", l.SystemData) + populate(objectMap, "type", l.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LocationResource. +func (l *LocationResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &l.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &l.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &l.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &l.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &l.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LocationResourceListResult. +func (l LocationResourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", l.NextLink) + populate(objectMap, "value", l.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LocationResourceListResult. +func (l *LocationResourceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &l.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &l.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LocationResourceProperties. +func (l LocationResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", l.Description) + populate(objectMap, "provisioningState", l.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LocationResourceProperties. +func (l *LocationResourceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &l.Description) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &l.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NestedProxyResource. +func (n NestedProxyResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", n.ID) + populate(objectMap, "name", n.Name) + populate(objectMap, "properties", n.Properties) + populate(objectMap, "systemData", n.SystemData) + populate(objectMap, "type", n.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NestedProxyResource. +func (n *NestedProxyResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &n.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &n.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &n.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &n.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &n.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NestedProxyResourceListResult. +func (n NestedProxyResourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", n.NextLink) + populate(objectMap, "value", n.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NestedProxyResourceListResult. +func (n *NestedProxyResourceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &n.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &n.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NestedProxyResourceProperties. +func (n NestedProxyResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", n.Description) + populate(objectMap, "provisioningState", n.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NestedProxyResourceProperties. +func (n *NestedProxyResourceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &n.Description) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &n.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NotificationDetails. +func (n NotificationDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "message", n.Message) + populate(objectMap, "urgent", n.Urgent) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NotificationDetails. +func (n *NotificationDetails) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "message": + err = unpopulate(val, "Message", &n.Message) + delete(rawMsg, key) + case "urgent": + err = unpopulate(val, "Urgent", &n.Urgent) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SingletonTrackedResource. +func (s SingletonTrackedResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + populate(objectMap, "location", s.Location) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "systemData", s.SystemData) + populate(objectMap, "tags", s.Tags) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SingletonTrackedResource. +func (s *SingletonTrackedResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &s.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &s.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &s.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SingletonTrackedResourceListResult. +func (s SingletonTrackedResourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SingletonTrackedResourceListResult. +func (s *SingletonTrackedResourceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &s.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SingletonTrackedResourceProperties. +func (s SingletonTrackedResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", s.Description) + populate(objectMap, "provisioningState", s.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SingletonTrackedResourceProperties. +func (s *SingletonTrackedResourceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &s.Description) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateTime[datetime.RFC3339](objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateTime[datetime.RFC3339](val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateTime[datetime.RFC3339](val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TopLevelTrackedResource. +func (t TopLevelTrackedResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", t.ID) + populate(objectMap, "location", t.Location) + populate(objectMap, "name", t.Name) + populate(objectMap, "properties", t.Properties) + populate(objectMap, "systemData", t.SystemData) + populate(objectMap, "tags", t.Tags) + populate(objectMap, "type", t.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TopLevelTrackedResource. +func (t *TopLevelTrackedResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &t.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &t.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &t.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &t.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &t.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &t.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &t.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TopLevelTrackedResourceListResult. +func (t TopLevelTrackedResourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", t.NextLink) + populate(objectMap, "value", t.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TopLevelTrackedResourceListResult. +func (t *TopLevelTrackedResourceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &t.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &t.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TopLevelTrackedResourceProperties. +func (t TopLevelTrackedResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", t.Description) + populate(objectMap, "provisioningState", t.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TopLevelTrackedResourceProperties. +func (t *TopLevelTrackedResourceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &t.Description) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &t.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/azure-http-specs/azure/resource-manager/resources/zz_nested_client.go b/test/azure-http-specs/azure/resource-manager/resources/zz_nested_client.go new file mode 100644 index 000000000000..cb90d126ff1e --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/zz_nested_client.go @@ -0,0 +1,410 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package resources + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// NestedClient contains the methods for the Nested group. +// Don't use this type directly, use NewNestedClient() instead. +// +// Generated from API version 2023-12-01-preview +type NestedClient struct { + internal *arm.Client + subscriptionID string +} + +// NewNestedClient creates a new instance of NestedClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewNestedClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*NestedClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &NestedClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrReplace - Create a NestedProxyResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - topLevelTrackedResourceName - arm resource name for path +// - nextedProxyResourceName - Name of the nested resource. +// - resource - Resource create parameters. +// - options - NestedClientBeginCreateOrReplaceOptions contains the optional parameters for the NestedClient.BeginCreateOrReplace +// method. +func (client *NestedClient) BeginCreateOrReplace(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, nextedProxyResourceName string, resource NestedProxyResource, options *NestedClientBeginCreateOrReplaceOptions) (*runtime.Poller[NestedClientCreateOrReplaceResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrReplace(ctx, resourceGroupName, topLevelTrackedResourceName, nextedProxyResourceName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[NestedClientCreateOrReplaceResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[NestedClientCreateOrReplaceResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrReplace - Create a NestedProxyResource +// If the operation fails it returns an *azcore.ResponseError type. +func (client *NestedClient) createOrReplace(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, nextedProxyResourceName string, resource NestedProxyResource, options *NestedClientBeginCreateOrReplaceOptions) (*http.Response, error) { + var err error + const operationName = "NestedClient.BeginCreateOrReplace" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrReplaceCreateRequest(ctx, resourceGroupName, topLevelTrackedResourceName, nextedProxyResourceName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrReplaceCreateRequest creates the CreateOrReplace request. +func (client *NestedClient) createOrReplaceCreateRequest(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, nextedProxyResourceName string, resource NestedProxyResource, _ *NestedClientBeginCreateOrReplaceOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Resources/topLevelTrackedResources/{topLevelTrackedResourceName}/nestedProxyResources/{nextedProxyResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if topLevelTrackedResourceName == "" { + return nil, errors.New("parameter topLevelTrackedResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{topLevelTrackedResourceName}", url.PathEscape(topLevelTrackedResourceName)) + if nextedProxyResourceName == "" { + return nil, errors.New("parameter nextedProxyResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{nextedProxyResourceName}", url.PathEscape(nextedProxyResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a NestedProxyResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - topLevelTrackedResourceName - arm resource name for path +// - nextedProxyResourceName - Name of the nested resource. +// - options - NestedClientBeginDeleteOptions contains the optional parameters for the NestedClient.BeginDelete method. +func (client *NestedClient) BeginDelete(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, nextedProxyResourceName string, options *NestedClientBeginDeleteOptions) (*runtime.Poller[NestedClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, topLevelTrackedResourceName, nextedProxyResourceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[NestedClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[NestedClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a NestedProxyResource +// If the operation fails it returns an *azcore.ResponseError type. +func (client *NestedClient) deleteOperation(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, nextedProxyResourceName string, options *NestedClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "NestedClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, topLevelTrackedResourceName, nextedProxyResourceName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *NestedClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, nextedProxyResourceName string, _ *NestedClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Resources/topLevelTrackedResources/{topLevelTrackedResourceName}/nestedProxyResources/{nextedProxyResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if topLevelTrackedResourceName == "" { + return nil, errors.New("parameter topLevelTrackedResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{topLevelTrackedResourceName}", url.PathEscape(topLevelTrackedResourceName)) + if nextedProxyResourceName == "" { + return nil, errors.New("parameter nextedProxyResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{nextedProxyResourceName}", url.PathEscape(nextedProxyResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a NestedProxyResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - topLevelTrackedResourceName - arm resource name for path +// - nextedProxyResourceName - Name of the nested resource. +// - options - NestedClientGetOptions contains the optional parameters for the NestedClient.Get method. +func (client *NestedClient) Get(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, nextedProxyResourceName string, options *NestedClientGetOptions) (NestedClientGetResponse, error) { + var err error + const operationName = "NestedClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, topLevelTrackedResourceName, nextedProxyResourceName, options) + if err != nil { + return NestedClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NestedClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NestedClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *NestedClient) getCreateRequest(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, nextedProxyResourceName string, _ *NestedClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Resources/topLevelTrackedResources/{topLevelTrackedResourceName}/nestedProxyResources/{nextedProxyResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if topLevelTrackedResourceName == "" { + return nil, errors.New("parameter topLevelTrackedResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{topLevelTrackedResourceName}", url.PathEscape(topLevelTrackedResourceName)) + if nextedProxyResourceName == "" { + return nil, errors.New("parameter nextedProxyResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{nextedProxyResourceName}", url.PathEscape(nextedProxyResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *NestedClient) getHandleResponse(resp *http.Response) (NestedClientGetResponse, error) { + result := NestedClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.NestedProxyResource); err != nil { + return NestedClientGetResponse{}, err + } + return result, nil +} + +// NewListByTopLevelTrackedResourcePager - List NestedProxyResource resources by TopLevelTrackedResource +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - topLevelTrackedResourceName - arm resource name for path +// - options - NestedClientListByTopLevelTrackedResourceOptions contains the optional parameters for the NestedClient.NewListByTopLevelTrackedResourcePager +// method. +func (client *NestedClient) NewListByTopLevelTrackedResourcePager(resourceGroupName string, topLevelTrackedResourceName string, options *NestedClientListByTopLevelTrackedResourceOptions) *runtime.Pager[NestedClientListByTopLevelTrackedResourceResponse] { + return runtime.NewPager(runtime.PagingHandler[NestedClientListByTopLevelTrackedResourceResponse]{ + More: func(page NestedClientListByTopLevelTrackedResourceResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *NestedClientListByTopLevelTrackedResourceResponse) (NestedClientListByTopLevelTrackedResourceResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "NestedClient.NewListByTopLevelTrackedResourcePager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByTopLevelTrackedResourceCreateRequest(ctx, resourceGroupName, topLevelTrackedResourceName, options) + }, nil) + if err != nil { + return NestedClientListByTopLevelTrackedResourceResponse{}, err + } + return client.listByTopLevelTrackedResourceHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByTopLevelTrackedResourceCreateRequest creates the ListByTopLevelTrackedResource request. +func (client *NestedClient) listByTopLevelTrackedResourceCreateRequest(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, _ *NestedClientListByTopLevelTrackedResourceOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Resources/topLevelTrackedResources/{topLevelTrackedResourceName}/nestedProxyResources" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if topLevelTrackedResourceName == "" { + return nil, errors.New("parameter topLevelTrackedResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{topLevelTrackedResourceName}", url.PathEscape(topLevelTrackedResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByTopLevelTrackedResourceHandleResponse handles the ListByTopLevelTrackedResource response. +func (client *NestedClient) listByTopLevelTrackedResourceHandleResponse(resp *http.Response) (NestedClientListByTopLevelTrackedResourceResponse, error) { + result := NestedClientListByTopLevelTrackedResourceResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.NestedProxyResourceListResult); err != nil { + return NestedClientListByTopLevelTrackedResourceResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update a NestedProxyResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - topLevelTrackedResourceName - arm resource name for path +// - nextedProxyResourceName - Name of the nested resource. +// - properties - The resource properties to be updated. +// - options - NestedClientBeginUpdateOptions contains the optional parameters for the NestedClient.BeginUpdate method. +func (client *NestedClient) BeginUpdate(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, nextedProxyResourceName string, properties NestedProxyResource, options *NestedClientBeginUpdateOptions) (*runtime.Poller[NestedClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, topLevelTrackedResourceName, nextedProxyResourceName, properties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[NestedClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[NestedClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a NestedProxyResource +// If the operation fails it returns an *azcore.ResponseError type. +func (client *NestedClient) update(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, nextedProxyResourceName string, properties NestedProxyResource, options *NestedClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "NestedClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, topLevelTrackedResourceName, nextedProxyResourceName, properties, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *NestedClient) updateCreateRequest(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, nextedProxyResourceName string, properties NestedProxyResource, _ *NestedClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Resources/topLevelTrackedResources/{topLevelTrackedResourceName}/nestedProxyResources/{nextedProxyResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if topLevelTrackedResourceName == "" { + return nil, errors.New("parameter topLevelTrackedResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{topLevelTrackedResourceName}", url.PathEscape(topLevelTrackedResourceName)) + if nextedProxyResourceName == "" { + return nil, errors.New("parameter nextedProxyResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{nextedProxyResourceName}", url.PathEscape(nextedProxyResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/resources/zz_options.go b/test/azure-http-specs/azure/resource-manager/resources/zz_options.go new file mode 100644 index 000000000000..551a2d70a5bc --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/zz_options.go @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package resources + +// ExtensionsResourcesClientBeginCreateOrUpdateOptions contains the optional parameters for the ExtensionsResourcesClient.BeginCreateOrUpdate +// method. +type ExtensionsResourcesClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ExtensionsResourcesClientDeleteOptions contains the optional parameters for the ExtensionsResourcesClient.Delete method. +type ExtensionsResourcesClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// ExtensionsResourcesClientGetOptions contains the optional parameters for the ExtensionsResourcesClient.Get method. +type ExtensionsResourcesClientGetOptions struct { + // placeholder for future optional parameters +} + +// ExtensionsResourcesClientListByScopeOptions contains the optional parameters for the ExtensionsResourcesClient.NewListByScopePager +// method. +type ExtensionsResourcesClientListByScopeOptions struct { + // placeholder for future optional parameters +} + +// ExtensionsResourcesClientUpdateOptions contains the optional parameters for the ExtensionsResourcesClient.Update method. +type ExtensionsResourcesClientUpdateOptions struct { + // placeholder for future optional parameters +} + +// LocationResourcesClientCreateOrUpdateOptions contains the optional parameters for the LocationResourcesClient.CreateOrUpdate +// method. +type LocationResourcesClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// LocationResourcesClientDeleteOptions contains the optional parameters for the LocationResourcesClient.Delete method. +type LocationResourcesClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// LocationResourcesClientGetOptions contains the optional parameters for the LocationResourcesClient.Get method. +type LocationResourcesClientGetOptions struct { + // placeholder for future optional parameters +} + +// LocationResourcesClientListByLocationOptions contains the optional parameters for the LocationResourcesClient.NewListByLocationPager +// method. +type LocationResourcesClientListByLocationOptions struct { + // placeholder for future optional parameters +} + +// LocationResourcesClientUpdateOptions contains the optional parameters for the LocationResourcesClient.Update method. +type LocationResourcesClientUpdateOptions struct { + // placeholder for future optional parameters +} + +// NestedClientBeginCreateOrReplaceOptions contains the optional parameters for the NestedClient.BeginCreateOrReplace method. +type NestedClientBeginCreateOrReplaceOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// NestedClientBeginDeleteOptions contains the optional parameters for the NestedClient.BeginDelete method. +type NestedClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// NestedClientBeginUpdateOptions contains the optional parameters for the NestedClient.BeginUpdate method. +type NestedClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// NestedClientGetOptions contains the optional parameters for the NestedClient.Get method. +type NestedClientGetOptions struct { + // placeholder for future optional parameters +} + +// NestedClientListByTopLevelTrackedResourceOptions contains the optional parameters for the NestedClient.NewListByTopLevelTrackedResourcePager +// method. +type NestedClientListByTopLevelTrackedResourceOptions struct { + // placeholder for future optional parameters +} + +// SingletonClientBeginCreateOrUpdateOptions contains the optional parameters for the SingletonClient.BeginCreateOrUpdate +// method. +type SingletonClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// SingletonClientGetByResourceGroupOptions contains the optional parameters for the SingletonClient.GetByResourceGroup method. +type SingletonClientGetByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// SingletonClientListByResourceGroupOptions contains the optional parameters for the SingletonClient.NewListByResourceGroupPager +// method. +type SingletonClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// SingletonClientUpdateOptions contains the optional parameters for the SingletonClient.Update method. +type SingletonClientUpdateOptions struct { + // placeholder for future optional parameters +} + +// TopLevelClientActionSyncOptions contains the optional parameters for the TopLevelClient.ActionSync method. +type TopLevelClientActionSyncOptions struct { + // placeholder for future optional parameters +} + +// TopLevelClientBeginCreateOrReplaceOptions contains the optional parameters for the TopLevelClient.BeginCreateOrReplace +// method. +type TopLevelClientBeginCreateOrReplaceOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// TopLevelClientBeginDeleteOptions contains the optional parameters for the TopLevelClient.BeginDelete method. +type TopLevelClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// TopLevelClientBeginUpdateOptions contains the optional parameters for the TopLevelClient.BeginUpdate method. +type TopLevelClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// TopLevelClientGetOptions contains the optional parameters for the TopLevelClient.Get method. +type TopLevelClientGetOptions struct { + // placeholder for future optional parameters +} + +// TopLevelClientListByResourceGroupOptions contains the optional parameters for the TopLevelClient.NewListByResourceGroupPager +// method. +type TopLevelClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// TopLevelClientListBySubscriptionOptions contains the optional parameters for the TopLevelClient.NewListBySubscriptionPager +// method. +type TopLevelClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/azure/resource-manager/resources/zz_responses.go b/test/azure-http-specs/azure/resource-manager/resources/zz_responses.go new file mode 100644 index 000000000000..970634855a26 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/zz_responses.go @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package resources + +// ExtensionsResourcesClientCreateOrUpdateResponse contains the response from method ExtensionsResourcesClient.BeginCreateOrUpdate. +type ExtensionsResourcesClientCreateOrUpdateResponse struct { + // Concrete extension resource types can be created by aliasing this type using a specific property type. + ExtensionsResource +} + +// ExtensionsResourcesClientDeleteResponse contains the response from method ExtensionsResourcesClient.Delete. +type ExtensionsResourcesClientDeleteResponse struct { + // placeholder for future response values +} + +// ExtensionsResourcesClientGetResponse contains the response from method ExtensionsResourcesClient.Get. +type ExtensionsResourcesClientGetResponse struct { + // Concrete extension resource types can be created by aliasing this type using a specific property type. + ExtensionsResource +} + +// ExtensionsResourcesClientListByScopeResponse contains the response from method ExtensionsResourcesClient.NewListByScopePager. +type ExtensionsResourcesClientListByScopeResponse struct { + // The response of a ExtensionsResource list operation. + ExtensionsResourceListResult +} + +// ExtensionsResourcesClientUpdateResponse contains the response from method ExtensionsResourcesClient.Update. +type ExtensionsResourcesClientUpdateResponse struct { + // Concrete extension resource types can be created by aliasing this type using a specific property type. + ExtensionsResource +} + +// LocationResourcesClientCreateOrUpdateResponse contains the response from method LocationResourcesClient.CreateOrUpdate. +type LocationResourcesClientCreateOrUpdateResponse struct { + // Concrete proxy resource types can be created by aliasing this type using a specific property type. + LocationResource +} + +// LocationResourcesClientDeleteResponse contains the response from method LocationResourcesClient.Delete. +type LocationResourcesClientDeleteResponse struct { + // placeholder for future response values +} + +// LocationResourcesClientGetResponse contains the response from method LocationResourcesClient.Get. +type LocationResourcesClientGetResponse struct { + // Concrete proxy resource types can be created by aliasing this type using a specific property type. + LocationResource +} + +// LocationResourcesClientListByLocationResponse contains the response from method LocationResourcesClient.NewListByLocationPager. +type LocationResourcesClientListByLocationResponse struct { + // The response of a LocationResource list operation. + LocationResourceListResult +} + +// LocationResourcesClientUpdateResponse contains the response from method LocationResourcesClient.Update. +type LocationResourcesClientUpdateResponse struct { + // Concrete proxy resource types can be created by aliasing this type using a specific property type. + LocationResource +} + +// NestedClientCreateOrReplaceResponse contains the response from method NestedClient.BeginCreateOrReplace. +type NestedClientCreateOrReplaceResponse struct { + // Nested child of Top Level Tracked Resource. + NestedProxyResource +} + +// NestedClientDeleteResponse contains the response from method NestedClient.BeginDelete. +type NestedClientDeleteResponse struct { + // placeholder for future response values +} + +// NestedClientGetResponse contains the response from method NestedClient.Get. +type NestedClientGetResponse struct { + // Nested child of Top Level Tracked Resource. + NestedProxyResource +} + +// NestedClientListByTopLevelTrackedResourceResponse contains the response from method NestedClient.NewListByTopLevelTrackedResourcePager. +type NestedClientListByTopLevelTrackedResourceResponse struct { + // The response of a NestedProxyResource list operation. + NestedProxyResourceListResult +} + +// NestedClientUpdateResponse contains the response from method NestedClient.BeginUpdate. +type NestedClientUpdateResponse struct { + // Nested child of Top Level Tracked Resource. + NestedProxyResource +} + +// SingletonClientCreateOrUpdateResponse contains the response from method SingletonClient.BeginCreateOrUpdate. +type SingletonClientCreateOrUpdateResponse struct { + // Concrete tracked resource types can be created by aliasing this type using a specific property type. + SingletonTrackedResource +} + +// SingletonClientGetByResourceGroupResponse contains the response from method SingletonClient.GetByResourceGroup. +type SingletonClientGetByResourceGroupResponse struct { + // Concrete tracked resource types can be created by aliasing this type using a specific property type. + SingletonTrackedResource +} + +// SingletonClientListByResourceGroupResponse contains the response from method SingletonClient.NewListByResourceGroupPager. +type SingletonClientListByResourceGroupResponse struct { + // The response of a SingletonTrackedResource list operation. + SingletonTrackedResourceListResult +} + +// SingletonClientUpdateResponse contains the response from method SingletonClient.Update. +type SingletonClientUpdateResponse struct { + // Concrete tracked resource types can be created by aliasing this type using a specific property type. + SingletonTrackedResource +} + +// TopLevelClientActionSyncResponse contains the response from method TopLevelClient.ActionSync. +type TopLevelClientActionSyncResponse struct { + // placeholder for future response values +} + +// TopLevelClientCreateOrReplaceResponse contains the response from method TopLevelClient.BeginCreateOrReplace. +type TopLevelClientCreateOrReplaceResponse struct { + // Concrete tracked resource types can be created by aliasing this type using a specific property type. + TopLevelTrackedResource +} + +// TopLevelClientDeleteResponse contains the response from method TopLevelClient.BeginDelete. +type TopLevelClientDeleteResponse struct { + // placeholder for future response values +} + +// TopLevelClientGetResponse contains the response from method TopLevelClient.Get. +type TopLevelClientGetResponse struct { + // Concrete tracked resource types can be created by aliasing this type using a specific property type. + TopLevelTrackedResource +} + +// TopLevelClientListByResourceGroupResponse contains the response from method TopLevelClient.NewListByResourceGroupPager. +type TopLevelClientListByResourceGroupResponse struct { + // The response of a TopLevelTrackedResource list operation. + TopLevelTrackedResourceListResult +} + +// TopLevelClientListBySubscriptionResponse contains the response from method TopLevelClient.NewListBySubscriptionPager. +type TopLevelClientListBySubscriptionResponse struct { + // The response of a TopLevelTrackedResource list operation. + TopLevelTrackedResourceListResult +} + +// TopLevelClientUpdateResponse contains the response from method TopLevelClient.BeginUpdate. +type TopLevelClientUpdateResponse struct { + // Concrete tracked resource types can be created by aliasing this type using a specific property type. + TopLevelTrackedResource +} diff --git a/test/azure-http-specs/azure/resource-manager/resources/zz_singleton_client.go b/test/azure-http-specs/azure/resource-manager/resources/zz_singleton_client.go new file mode 100644 index 000000000000..4e3b09841391 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/zz_singleton_client.go @@ -0,0 +1,292 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package resources + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// SingletonClient contains the methods for the Singleton group. +// Don't use this type directly, use NewSingletonClient() instead. +// +// Generated from API version 2023-12-01-preview +type SingletonClient struct { + internal *arm.Client + subscriptionID string +} + +// NewSingletonClient creates a new instance of SingletonClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewSingletonClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SingletonClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SingletonClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create a SingletonTrackedResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - resource - Resource create parameters. +// - options - SingletonClientBeginCreateOrUpdateOptions contains the optional parameters for the SingletonClient.BeginCreateOrUpdate +// method. +func (client *SingletonClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, resource SingletonTrackedResource, options *SingletonClientBeginCreateOrUpdateOptions) (*runtime.Poller[SingletonClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SingletonClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SingletonClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create a SingletonTrackedResource +// If the operation fails it returns an *azcore.ResponseError type. +func (client *SingletonClient) createOrUpdate(ctx context.Context, resourceGroupName string, resource SingletonTrackedResource, options *SingletonClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "SingletonClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *SingletonClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, resource SingletonTrackedResource, _ *SingletonClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Resources/singletonTrackedResources/default" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// GetByResourceGroup - Get a SingletonTrackedResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - SingletonClientGetByResourceGroupOptions contains the optional parameters for the SingletonClient.GetByResourceGroup +// method. +func (client *SingletonClient) GetByResourceGroup(ctx context.Context, resourceGroupName string, options *SingletonClientGetByResourceGroupOptions) (SingletonClientGetByResourceGroupResponse, error) { + var err error + const operationName = "SingletonClient.GetByResourceGroup" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getByResourceGroupCreateRequest(ctx, resourceGroupName, options) + if err != nil { + return SingletonClientGetByResourceGroupResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SingletonClientGetByResourceGroupResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SingletonClientGetByResourceGroupResponse{}, err + } + resp, err := client.getByResourceGroupHandleResponse(httpResp) + return resp, err +} + +// getByResourceGroupCreateRequest creates the GetByResourceGroup request. +func (client *SingletonClient) getByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *SingletonClientGetByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Resources/singletonTrackedResources/default" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getByResourceGroupHandleResponse handles the GetByResourceGroup response. +func (client *SingletonClient) getByResourceGroupHandleResponse(resp *http.Response) (SingletonClientGetByResourceGroupResponse, error) { + result := SingletonClientGetByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SingletonTrackedResource); err != nil { + return SingletonClientGetByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - List SingletonTrackedResource resources by resource group +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - SingletonClientListByResourceGroupOptions contains the optional parameters for the SingletonClient.NewListByResourceGroupPager +// method. +func (client *SingletonClient) NewListByResourceGroupPager(resourceGroupName string, options *SingletonClientListByResourceGroupOptions) *runtime.Pager[SingletonClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[SingletonClientListByResourceGroupResponse]{ + More: func(page SingletonClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SingletonClientListByResourceGroupResponse) (SingletonClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SingletonClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return SingletonClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *SingletonClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *SingletonClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Resources/singletonTrackedResources" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *SingletonClient) listByResourceGroupHandleResponse(resp *http.Response) (SingletonClientListByResourceGroupResponse, error) { + result := SingletonClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SingletonTrackedResourceListResult); err != nil { + return SingletonClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// Update - Update a SingletonTrackedResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - properties - The resource properties to be updated. +// - options - SingletonClientUpdateOptions contains the optional parameters for the SingletonClient.Update method. +func (client *SingletonClient) Update(ctx context.Context, resourceGroupName string, properties SingletonTrackedResource, options *SingletonClientUpdateOptions) (SingletonClientUpdateResponse, error) { + var err error + const operationName = "SingletonClient.Update" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, properties, options) + if err != nil { + return SingletonClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SingletonClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SingletonClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *SingletonClient) updateCreateRequest(ctx context.Context, resourceGroupName string, properties SingletonTrackedResource, _ *SingletonClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Resources/singletonTrackedResources/default" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *SingletonClient) updateHandleResponse(resp *http.Response) (SingletonClientUpdateResponse, error) { + result := SingletonClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SingletonTrackedResource); err != nil { + return SingletonClientUpdateResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/resources/zz_toplevel_client.go b/test/azure-http-specs/azure/resource-manager/resources/zz_toplevel_client.go new file mode 100644 index 000000000000..f0f92a611cf5 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/zz_toplevel_client.go @@ -0,0 +1,494 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package resources + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// TopLevelClient contains the methods for the TopLevel group. +// Don't use this type directly, use NewTopLevelClient() instead. +// +// Generated from API version 2023-12-01-preview +type TopLevelClient struct { + internal *arm.Client + subscriptionID string +} + +// NewTopLevelClient creates a new instance of TopLevelClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewTopLevelClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*TopLevelClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &TopLevelClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// ActionSync - A synchronous resource action that returns no content. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - topLevelTrackedResourceName - arm resource name for path +// - body - The content of the action request +// - options - TopLevelClientActionSyncOptions contains the optional parameters for the TopLevelClient.ActionSync method. +func (client *TopLevelClient) ActionSync(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, body NotificationDetails, options *TopLevelClientActionSyncOptions) (TopLevelClientActionSyncResponse, error) { + var err error + const operationName = "TopLevelClient.ActionSync" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.actionSyncCreateRequest(ctx, resourceGroupName, topLevelTrackedResourceName, body, options) + if err != nil { + return TopLevelClientActionSyncResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TopLevelClientActionSyncResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return TopLevelClientActionSyncResponse{}, err + } + return TopLevelClientActionSyncResponse{}, nil +} + +// actionSyncCreateRequest creates the ActionSync request. +func (client *TopLevelClient) actionSyncCreateRequest(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, body NotificationDetails, _ *TopLevelClientActionSyncOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Resources/topLevelTrackedResources/{topLevelTrackedResourceName}/actionSync" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if topLevelTrackedResourceName == "" { + return nil, errors.New("parameter topLevelTrackedResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{topLevelTrackedResourceName}", url.PathEscape(topLevelTrackedResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// BeginCreateOrReplace - Create a TopLevelTrackedResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - topLevelTrackedResourceName - arm resource name for path +// - resource - Resource create parameters. +// - options - TopLevelClientBeginCreateOrReplaceOptions contains the optional parameters for the TopLevelClient.BeginCreateOrReplace +// method. +func (client *TopLevelClient) BeginCreateOrReplace(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, resource TopLevelTrackedResource, options *TopLevelClientBeginCreateOrReplaceOptions) (*runtime.Poller[TopLevelClientCreateOrReplaceResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrReplace(ctx, resourceGroupName, topLevelTrackedResourceName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[TopLevelClientCreateOrReplaceResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[TopLevelClientCreateOrReplaceResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrReplace - Create a TopLevelTrackedResource +// If the operation fails it returns an *azcore.ResponseError type. +func (client *TopLevelClient) createOrReplace(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, resource TopLevelTrackedResource, options *TopLevelClientBeginCreateOrReplaceOptions) (*http.Response, error) { + var err error + const operationName = "TopLevelClient.BeginCreateOrReplace" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrReplaceCreateRequest(ctx, resourceGroupName, topLevelTrackedResourceName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrReplaceCreateRequest creates the CreateOrReplace request. +func (client *TopLevelClient) createOrReplaceCreateRequest(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, resource TopLevelTrackedResource, _ *TopLevelClientBeginCreateOrReplaceOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Resources/topLevelTrackedResources/{topLevelTrackedResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if topLevelTrackedResourceName == "" { + return nil, errors.New("parameter topLevelTrackedResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{topLevelTrackedResourceName}", url.PathEscape(topLevelTrackedResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a TopLevelTrackedResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - topLevelTrackedResourceName - arm resource name for path +// - options - TopLevelClientBeginDeleteOptions contains the optional parameters for the TopLevelClient.BeginDelete method. +func (client *TopLevelClient) BeginDelete(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, options *TopLevelClientBeginDeleteOptions) (*runtime.Poller[TopLevelClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, topLevelTrackedResourceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[TopLevelClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[TopLevelClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a TopLevelTrackedResource +// If the operation fails it returns an *azcore.ResponseError type. +func (client *TopLevelClient) deleteOperation(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, options *TopLevelClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "TopLevelClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, topLevelTrackedResourceName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *TopLevelClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, _ *TopLevelClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Resources/topLevelTrackedResources/{topLevelTrackedResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if topLevelTrackedResourceName == "" { + return nil, errors.New("parameter topLevelTrackedResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{topLevelTrackedResourceName}", url.PathEscape(topLevelTrackedResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a TopLevelTrackedResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - topLevelTrackedResourceName - arm resource name for path +// - options - TopLevelClientGetOptions contains the optional parameters for the TopLevelClient.Get method. +func (client *TopLevelClient) Get(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, options *TopLevelClientGetOptions) (TopLevelClientGetResponse, error) { + var err error + const operationName = "TopLevelClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, topLevelTrackedResourceName, options) + if err != nil { + return TopLevelClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TopLevelClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return TopLevelClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *TopLevelClient) getCreateRequest(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, _ *TopLevelClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Resources/topLevelTrackedResources/{topLevelTrackedResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if topLevelTrackedResourceName == "" { + return nil, errors.New("parameter topLevelTrackedResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{topLevelTrackedResourceName}", url.PathEscape(topLevelTrackedResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *TopLevelClient) getHandleResponse(resp *http.Response) (TopLevelClientGetResponse, error) { + result := TopLevelClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.TopLevelTrackedResource); err != nil { + return TopLevelClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - List TopLevelTrackedResource resources by resource group +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - TopLevelClientListByResourceGroupOptions contains the optional parameters for the TopLevelClient.NewListByResourceGroupPager +// method. +func (client *TopLevelClient) NewListByResourceGroupPager(resourceGroupName string, options *TopLevelClientListByResourceGroupOptions) *runtime.Pager[TopLevelClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[TopLevelClientListByResourceGroupResponse]{ + More: func(page TopLevelClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *TopLevelClientListByResourceGroupResponse) (TopLevelClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "TopLevelClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return TopLevelClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *TopLevelClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *TopLevelClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Resources/topLevelTrackedResources" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *TopLevelClient) listByResourceGroupHandleResponse(resp *http.Response) (TopLevelClientListByResourceGroupResponse, error) { + result := TopLevelClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.TopLevelTrackedResourceListResult); err != nil { + return TopLevelClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - List TopLevelTrackedResource resources by subscription ID +// - options - TopLevelClientListBySubscriptionOptions contains the optional parameters for the TopLevelClient.NewListBySubscriptionPager +// method. +func (client *TopLevelClient) NewListBySubscriptionPager(options *TopLevelClientListBySubscriptionOptions) *runtime.Pager[TopLevelClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[TopLevelClientListBySubscriptionResponse]{ + More: func(page TopLevelClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *TopLevelClientListBySubscriptionResponse) (TopLevelClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "TopLevelClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return TopLevelClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *TopLevelClient) listBySubscriptionCreateRequest(ctx context.Context, _ *TopLevelClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Azure.ResourceManager.Resources/topLevelTrackedResources" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *TopLevelClient) listBySubscriptionHandleResponse(resp *http.Response) (TopLevelClientListBySubscriptionResponse, error) { + result := TopLevelClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.TopLevelTrackedResourceListResult); err != nil { + return TopLevelClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update a TopLevelTrackedResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - topLevelTrackedResourceName - arm resource name for path +// - properties - The resource properties to be updated. +// - options - TopLevelClientBeginUpdateOptions contains the optional parameters for the TopLevelClient.BeginUpdate method. +func (client *TopLevelClient) BeginUpdate(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, properties TopLevelTrackedResource, options *TopLevelClientBeginUpdateOptions) (*runtime.Poller[TopLevelClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, topLevelTrackedResourceName, properties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[TopLevelClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[TopLevelClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a TopLevelTrackedResource +// If the operation fails it returns an *azcore.ResponseError type. +func (client *TopLevelClient) update(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, properties TopLevelTrackedResource, options *TopLevelClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "TopLevelClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, topLevelTrackedResourceName, properties, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *TopLevelClient) updateCreateRequest(ctx context.Context, resourceGroupName string, topLevelTrackedResourceName string, properties TopLevelTrackedResource, _ *TopLevelClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.Resources/topLevelTrackedResources/{topLevelTrackedResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if topLevelTrackedResourceName == "" { + return nil, errors.New("parameter topLevelTrackedResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{topLevelTrackedResourceName}", url.PathEscape(topLevelTrackedResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/resources/zz_version.go b/test/azure-http-specs/azure/resource-manager/resources/zz_version.go new file mode 100644 index 000000000000..2d40ca196cae --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/resources/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package resources + +const ( + moduleName = "resources" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/LICENSE.txt b/test/azure-http-specs/azure/resource-manager/templatesgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/checknameavailability_client_test.go b/test/azure-http-specs/azure/resource-manager/templatesgroup/checknameavailability_client_test.go new file mode 100644 index 000000000000..3ebeb44011ab --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/checknameavailability_client_test.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package templatesgroup_test + +import ( + "templatesgroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestNewCheckNameAvailabilityClient_CheckGlobal(t *testing.T) { + body := templatesgroup.CheckNameAvailabilityRequest{ + Name: to.Ptr("checkName"), + Type: to.Ptr("Microsoft.Web/site"), + } + resp, err := clientFactory.NewCheckNameAvailabilityClient().CheckGlobal(ctx, body, nil) + require.NoError(t, err) + require.NotNil(t, resp) + require.Equal(t, false, *resp.NameAvailable) + require.Equal(t, templatesgroup.CheckNameAvailabilityReason("AlreadyExists"), *resp.Reason) + require.Equal(t, "Hostname 'checkName' already exists. Please select a different name.", *resp.Message) +} + +func TestNewCheckNameAvailabilityClient_CheckLocal(t *testing.T) { + body := templatesgroup.CheckNameAvailabilityRequest{ + Name: to.Ptr("checkName"), + Type: to.Ptr("Microsoft.Web/site"), + } + resp, err := clientFactory.NewCheckNameAvailabilityClient().CheckLocal(ctx, locationExpected, body, nil) + require.NoError(t, err) + require.NotNil(t, resp) + require.Equal(t, false, *resp.NameAvailable) + require.Equal(t, templatesgroup.CheckNameAvailabilityReason("AlreadyExists"), *resp.Reason) + require.Equal(t, "Hostname 'checkName' already exists. Please select a different name.", *resp.Message) +} + +func TestNewOperationsClient_NewListPager(t *testing.T) { + options := &templatesgroup.OperationsClientListOptions{} + pager := clientFactory.NewOperationsClient().NewListPager(options) + require.NotNil(t, pager) + for pager.More() { + _, err := pager.NextPage(ctx) + require.NoError(t, err) + } +} diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_checknameavailability_server.go b/test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_checknameavailability_server.go new file mode 100644 index 000000000000..f69f6f5d9eba --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_checknameavailability_server.go @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" + "templatesgroup" +) + +// CheckNameAvailabilityServer is a fake server for instances of the templatesgroup.CheckNameAvailabilityClient type. +type CheckNameAvailabilityServer struct { + // CheckGlobal is the fake for method CheckNameAvailabilityClient.CheckGlobal + // HTTP status codes to indicate success: http.StatusOK + CheckGlobal func(ctx context.Context, body templatesgroup.CheckNameAvailabilityRequest, options *templatesgroup.CheckNameAvailabilityClientCheckGlobalOptions) (resp azfake.Responder[templatesgroup.CheckNameAvailabilityClientCheckGlobalResponse], errResp azfake.ErrorResponder) + + // CheckLocal is the fake for method CheckNameAvailabilityClient.CheckLocal + // HTTP status codes to indicate success: http.StatusOK + CheckLocal func(ctx context.Context, location string, body templatesgroup.CheckNameAvailabilityRequest, options *templatesgroup.CheckNameAvailabilityClientCheckLocalOptions) (resp azfake.Responder[templatesgroup.CheckNameAvailabilityClientCheckLocalResponse], errResp azfake.ErrorResponder) +} + +// NewCheckNameAvailabilityServerTransport creates a new instance of CheckNameAvailabilityServerTransport with the provided implementation. +// The returned CheckNameAvailabilityServerTransport instance is connected to an instance of templatesgroup.CheckNameAvailabilityClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewCheckNameAvailabilityServerTransport(srv *CheckNameAvailabilityServer) *CheckNameAvailabilityServerTransport { + return &CheckNameAvailabilityServerTransport{srv: srv} +} + +// CheckNameAvailabilityServerTransport connects instances of templatesgroup.CheckNameAvailabilityClient to instances of CheckNameAvailabilityServer. +// Don't use this type directly, use NewCheckNameAvailabilityServerTransport instead. +type CheckNameAvailabilityServerTransport struct { + srv *CheckNameAvailabilityServer +} + +// Do implements the policy.Transporter interface for CheckNameAvailabilityServerTransport. +func (c *CheckNameAvailabilityServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *CheckNameAvailabilityServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if checkNameAvailabilityServerTransportInterceptor != nil { + res.resp, res.err, intercepted = checkNameAvailabilityServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "CheckNameAvailabilityClient.CheckGlobal": + res.resp, res.err = c.dispatchCheckGlobal(req) + case "CheckNameAvailabilityClient.CheckLocal": + res.resp, res.err = c.dispatchCheckLocal(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *CheckNameAvailabilityServerTransport) dispatchCheckGlobal(req *http.Request) (*http.Response, error) { + if c.srv.CheckGlobal == nil { + return nil, &nonRetriableError{errors.New("fake for method CheckGlobal not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.OperationTemplates/checkNameAvailability` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[templatesgroup.CheckNameAvailabilityRequest](req) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.CheckGlobal(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CheckNameAvailabilityResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *CheckNameAvailabilityServerTransport) dispatchCheckLocal(req *http.Request) (*http.Response, error) { + if c.srv.CheckLocal == nil { + return nil, &nonRetriableError{errors.New("fake for method CheckLocal not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.OperationTemplates/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/checkNameAvailability` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[templatesgroup.CheckNameAvailabilityRequest](req) + if err != nil { + return nil, err + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.CheckLocal(req.Context(), locationParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CheckNameAvailabilityResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to CheckNameAvailabilityServerTransport +var checkNameAvailabilityServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_internal.go b/test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_internal.go new file mode 100644 index 000000000000..590b4d743e97 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_internal.go @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_lro_server.go b/test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_lro_server.go new file mode 100644 index 000000000000..da88f3722ae7 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_lro_server.go @@ -0,0 +1,292 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" + "templatesgroup" +) + +// LroServer is a fake server for instances of the templatesgroup.LroClient type. +type LroServer struct { + // BeginCreateOrReplace is the fake for method LroClient.BeginCreateOrReplace + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrReplace func(ctx context.Context, resourceGroupName string, orderName string, resource templatesgroup.Order, options *templatesgroup.LroClientBeginCreateOrReplaceOptions) (resp azfake.PollerResponder[templatesgroup.LroClientCreateOrReplaceResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method LroClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, orderName string, options *templatesgroup.LroClientBeginDeleteOptions) (resp azfake.PollerResponder[templatesgroup.LroClientDeleteResponse], errResp azfake.ErrorResponder) + + // BeginExport is the fake for method LroClient.BeginExport + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginExport func(ctx context.Context, resourceGroupName string, orderName string, body templatesgroup.ExportRequest, options *templatesgroup.LroClientBeginExportOptions) (resp azfake.PollerResponder[templatesgroup.LroClientExportResponse], errResp azfake.ErrorResponder) + + // BeginExportArray is the fake for method LroClient.BeginExportArray + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginExportArray func(ctx context.Context, body templatesgroup.ExportRequest, options *templatesgroup.LroClientBeginExportArrayOptions) (resp azfake.PollerResponder[templatesgroup.LroClientExportArrayResponse], errResp azfake.ErrorResponder) +} + +// NewLroServerTransport creates a new instance of LroServerTransport with the provided implementation. +// The returned LroServerTransport instance is connected to an instance of templatesgroup.LroClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewLroServerTransport(srv *LroServer) *LroServerTransport { + return &LroServerTransport{ + srv: srv, + beginCreateOrReplace: newTracker[azfake.PollerResponder[templatesgroup.LroClientCreateOrReplaceResponse]](), + beginDelete: newTracker[azfake.PollerResponder[templatesgroup.LroClientDeleteResponse]](), + beginExport: newTracker[azfake.PollerResponder[templatesgroup.LroClientExportResponse]](), + beginExportArray: newTracker[azfake.PollerResponder[templatesgroup.LroClientExportArrayResponse]](), + } +} + +// LroServerTransport connects instances of templatesgroup.LroClient to instances of LroServer. +// Don't use this type directly, use NewLroServerTransport instead. +type LroServerTransport struct { + srv *LroServer + beginCreateOrReplace *tracker[azfake.PollerResponder[templatesgroup.LroClientCreateOrReplaceResponse]] + beginDelete *tracker[azfake.PollerResponder[templatesgroup.LroClientDeleteResponse]] + beginExport *tracker[azfake.PollerResponder[templatesgroup.LroClientExportResponse]] + beginExportArray *tracker[azfake.PollerResponder[templatesgroup.LroClientExportArrayResponse]] +} + +// Do implements the policy.Transporter interface for LroServerTransport. +func (l *LroServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return l.dispatchToMethodFake(req, method) +} + +func (l *LroServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if lroServerTransportInterceptor != nil { + res.resp, res.err, intercepted = lroServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "LroClient.BeginCreateOrReplace": + res.resp, res.err = l.dispatchBeginCreateOrReplace(req) + case "LroClient.BeginDelete": + res.resp, res.err = l.dispatchBeginDelete(req) + case "LroClient.BeginExport": + res.resp, res.err = l.dispatchBeginExport(req) + case "LroClient.BeginExportArray": + res.resp, res.err = l.dispatchBeginExportArray(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (l *LroServerTransport) dispatchBeginCreateOrReplace(req *http.Request) (*http.Response, error) { + if l.srv.BeginCreateOrReplace == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrReplace not implemented")} + } + beginCreateOrReplace := l.beginCreateOrReplace.get(req) + if beginCreateOrReplace == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.OperationTemplates/orders/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[templatesgroup.Order](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + orderNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("orderName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.BeginCreateOrReplace(req.Context(), resourceGroupNameParam, orderNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrReplace = &respr + l.beginCreateOrReplace.add(req, beginCreateOrReplace) + } + + resp, err := server.PollerResponderNext(beginCreateOrReplace, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + l.beginCreateOrReplace.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrReplace) { + l.beginCreateOrReplace.remove(req) + } + + return resp, nil +} + +func (l *LroServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if l.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := l.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.OperationTemplates/orders/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + orderNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("orderName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.BeginDelete(req.Context(), resourceGroupNameParam, orderNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + l.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + l.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + l.beginDelete.remove(req) + } + + return resp, nil +} + +func (l *LroServerTransport) dispatchBeginExport(req *http.Request) (*http.Response, error) { + if l.srv.BeginExport == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginExport not implemented")} + } + beginExport := l.beginExport.get(req) + if beginExport == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.OperationTemplates/orders/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/export` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[templatesgroup.ExportRequest](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + orderNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("orderName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.BeginExport(req.Context(), resourceGroupNameParam, orderNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginExport = &respr + l.beginExport.add(req, beginExport) + } + + resp, err := server.PollerResponderNext(beginExport, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + l.beginExport.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginExport) { + l.beginExport.remove(req) + } + + return resp, nil +} + +func (l *LroServerTransport) dispatchBeginExportArray(req *http.Request) (*http.Response, error) { + if l.srv.BeginExportArray == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginExportArray not implemented")} + } + beginExportArray := l.beginExportArray.get(req) + if beginExportArray == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.OperationTemplates/exportArray` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[templatesgroup.ExportRequest](req) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.BeginExportArray(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginExportArray = &respr + l.beginExportArray.add(req, beginExportArray) + } + + resp, err := server.PollerResponderNext(beginExportArray, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + l.beginExportArray.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginExportArray) { + l.beginExportArray.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to LroServerTransport +var lroServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_lropaging_server.go b/test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_lropaging_server.go new file mode 100644 index 000000000000..48eabe1ab2b5 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_lropaging_server.go @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" + "templatesgroup" +) + +// LroPagingServer is a fake server for instances of the templatesgroup.LroPagingClient type. +type LroPagingServer struct { + // BeginPostPagingLro is the fake for method LroPagingClient.BeginPostPagingLro + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginPostPagingLro func(ctx context.Context, resourceGroupName string, productName string, options *templatesgroup.LroPagingClientBeginPostPagingLroOptions) (resp azfake.PollerResponder[azfake.PagerResponder[templatesgroup.LroPagingClientPostPagingLroResponse]], errResp azfake.ErrorResponder) +} + +// NewLroPagingServerTransport creates a new instance of LroPagingServerTransport with the provided implementation. +// The returned LroPagingServerTransport instance is connected to an instance of templatesgroup.LroPagingClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewLroPagingServerTransport(srv *LroPagingServer) *LroPagingServerTransport { + return &LroPagingServerTransport{ + srv: srv, + beginPostPagingLro: newTracker[azfake.PollerResponder[azfake.PagerResponder[templatesgroup.LroPagingClientPostPagingLroResponse]]](), + } +} + +// LroPagingServerTransport connects instances of templatesgroup.LroPagingClient to instances of LroPagingServer. +// Don't use this type directly, use NewLroPagingServerTransport instead. +type LroPagingServerTransport struct { + srv *LroPagingServer + beginPostPagingLro *tracker[azfake.PollerResponder[azfake.PagerResponder[templatesgroup.LroPagingClientPostPagingLroResponse]]] +} + +// Do implements the policy.Transporter interface for LroPagingServerTransport. +func (l *LroPagingServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return l.dispatchToMethodFake(req, method) +} + +func (l *LroPagingServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if lroPagingServerTransportInterceptor != nil { + res.resp, res.err, intercepted = lroPagingServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "LroPagingClient.BeginPostPagingLro": + res.resp, res.err = l.dispatchBeginPostPagingLro(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (l *LroPagingServerTransport) dispatchBeginPostPagingLro(req *http.Request) (*http.Response, error) { + if l.srv.BeginPostPagingLro == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginPostPagingLro not implemented")} + } + beginPostPagingLro := l.beginPostPagingLro.get(req) + if beginPostPagingLro == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.OperationTemplates/products/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/postPagingLro` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + productNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("productName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.BeginPostPagingLro(req.Context(), resourceGroupNameParam, productNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginPostPagingLro = &respr + l.beginPostPagingLro.add(req, beginPostPagingLro) + } + + resp, err := server.PollerResponderNext(beginPostPagingLro, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + l.beginPostPagingLro.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginPostPagingLro) { + l.beginPostPagingLro.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to LroPagingServerTransport +var lroPagingServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_operations_server.go b/test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_operations_server.go new file mode 100644 index 000000000000..0f48a7a6753c --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_operations_server.go @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "slices" + "templatesgroup" +) + +// OperationsServer is a fake server for instances of the templatesgroup.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *templatesgroup.OperationsClientListOptions) (resp azfake.PagerResponder[templatesgroup.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of templatesgroup.OperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOperationsServerTransport(srv *OperationsServer) *OperationsServerTransport { + return &OperationsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[templatesgroup.OperationsClientListResponse]](), + } +} + +// OperationsServerTransport connects instances of templatesgroup.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[templatesgroup.OperationsClientListResponse]] +} + +// Do implements the policy.Transporter interface for OperationsServerTransport. +func (o *OperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if operationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = operationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OperationsClient.NewListPager": + res.resp, res.err = o.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OperationsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := o.newListPager.get(req) + if newListPager == nil { + resp := o.srv.NewListPager(nil) + newListPager = &resp + o.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *templatesgroup.OperationsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + o.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + o.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OperationsServerTransport +var operationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_optionalbody_server.go b/test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_optionalbody_server.go new file mode 100644 index 000000000000..7a2414d4b20b --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_optionalbody_server.go @@ -0,0 +1,251 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "reflect" + "regexp" + "slices" + "templatesgroup" +) + +// OptionalBodyServer is a fake server for instances of the templatesgroup.OptionalBodyClient type. +type OptionalBodyServer struct { + // Get is the fake for method OptionalBodyClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, widgetName string, options *templatesgroup.OptionalBodyClientGetOptions) (resp azfake.Responder[templatesgroup.OptionalBodyClientGetResponse], errResp azfake.ErrorResponder) + + // Patch is the fake for method OptionalBodyClient.Patch + // HTTP status codes to indicate success: http.StatusOK + Patch func(ctx context.Context, resourceGroupName string, widgetName string, properties templatesgroup.Widget, options *templatesgroup.OptionalBodyClientPatchOptions) (resp azfake.Responder[templatesgroup.OptionalBodyClientPatchResponse], errResp azfake.ErrorResponder) + + // Post is the fake for method OptionalBodyClient.Post + // HTTP status codes to indicate success: http.StatusOK + Post func(ctx context.Context, resourceGroupName string, widgetName string, options *templatesgroup.OptionalBodyClientPostOptions) (resp azfake.Responder[templatesgroup.OptionalBodyClientPostResponse], errResp azfake.ErrorResponder) + + // ProviderPost is the fake for method OptionalBodyClient.ProviderPost + // HTTP status codes to indicate success: http.StatusOK + ProviderPost func(ctx context.Context, options *templatesgroup.OptionalBodyClientProviderPostOptions) (resp azfake.Responder[templatesgroup.OptionalBodyClientProviderPostResponse], errResp azfake.ErrorResponder) +} + +// NewOptionalBodyServerTransport creates a new instance of OptionalBodyServerTransport with the provided implementation. +// The returned OptionalBodyServerTransport instance is connected to an instance of templatesgroup.OptionalBodyClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOptionalBodyServerTransport(srv *OptionalBodyServer) *OptionalBodyServerTransport { + return &OptionalBodyServerTransport{srv: srv} +} + +// OptionalBodyServerTransport connects instances of templatesgroup.OptionalBodyClient to instances of OptionalBodyServer. +// Don't use this type directly, use NewOptionalBodyServerTransport instead. +type OptionalBodyServerTransport struct { + srv *OptionalBodyServer +} + +// Do implements the policy.Transporter interface for OptionalBodyServerTransport. +func (o *OptionalBodyServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OptionalBodyServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if optionalBodyServerTransportInterceptor != nil { + res.resp, res.err, intercepted = optionalBodyServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OptionalBodyClient.Get": + res.resp, res.err = o.dispatchGet(req) + case "OptionalBodyClient.Patch": + res.resp, res.err = o.dispatchPatch(req) + case "OptionalBodyClient.Post": + res.resp, res.err = o.dispatchPost(req) + case "OptionalBodyClient.ProviderPost": + res.resp, res.err = o.dispatchProviderPost(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OptionalBodyServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if o.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.OperationTemplates/widgets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + widgetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("widgetName")]) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.Get(req.Context(), resourceGroupNameParam, widgetNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Widget, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalBodyServerTransport) dispatchPatch(req *http.Request) (*http.Response, error) { + if o.srv.Patch == nil { + return nil, &nonRetriableError{errors.New("fake for method Patch not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.OperationTemplates/widgets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[templatesgroup.Widget](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + widgetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("widgetName")]) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.Patch(req.Context(), resourceGroupNameParam, widgetNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Widget, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalBodyServerTransport) dispatchPost(req *http.Request) (*http.Response, error) { + if o.srv.Post == nil { + return nil, &nonRetriableError{errors.New("fake for method Post not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.OperationTemplates/widgets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/post` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[templatesgroup.ActionRequest](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + widgetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("widgetName")]) + if err != nil { + return nil, err + } + var options *templatesgroup.OptionalBodyClientPostOptions + if !reflect.ValueOf(body).IsZero() { + options = &templatesgroup.OptionalBodyClientPostOptions{ + Body: &body, + } + } + respr, errRespr := o.srv.Post(req.Context(), resourceGroupNameParam, widgetNameParam, options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ActionResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalBodyServerTransport) dispatchProviderPost(req *http.Request) (*http.Response, error) { + if o.srv.ProviderPost == nil { + return nil, &nonRetriableError{errors.New("fake for method ProviderPost not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Azure\.ResourceManager\.OperationTemplates/providerPost` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[templatesgroup.ChangeAllowanceRequest](req) + if err != nil { + return nil, err + } + var options *templatesgroup.OptionalBodyClientProviderPostOptions + if !reflect.ValueOf(body).IsZero() { + options = &templatesgroup.OptionalBodyClientProviderPostOptions{ + Body: &body, + } + } + respr, errRespr := o.srv.ProviderPost(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ChangeAllowanceResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OptionalBodyServerTransport +var optionalBodyServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_server_factory.go b/test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_server_factory.go new file mode 100644 index 000000000000..035c478170e2 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/fake/zz_server_factory.go @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the templatesgroup.ClientFactory type. +type ServerFactory struct { + // CheckNameAvailabilityServer contains the fakes for client CheckNameAvailabilityClient + CheckNameAvailabilityServer CheckNameAvailabilityServer + + // LroServer contains the fakes for client LroClient + LroServer LroServer + + // LroPagingServer contains the fakes for client LroPagingClient + LroPagingServer LroPagingServer + + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer + + // OptionalBodyServer contains the fakes for client OptionalBodyClient + OptionalBodyServer OptionalBodyServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of templatesgroup.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of templatesgroup.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trCheckNameAvailabilityServer *CheckNameAvailabilityServerTransport + trLroServer *LroServerTransport + trLroPagingServer *LroPagingServerTransport + trOperationsServer *OperationsServerTransport + trOptionalBodyServer *OptionalBodyServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "CheckNameAvailabilityClient": + initServer(&s.trMu, &s.trCheckNameAvailabilityServer, func() *CheckNameAvailabilityServerTransport { + return NewCheckNameAvailabilityServerTransport(&s.srv.CheckNameAvailabilityServer) + }) + resp, err = s.trCheckNameAvailabilityServer.Do(req) + case "LroClient": + initServer(&s.trMu, &s.trLroServer, func() *LroServerTransport { return NewLroServerTransport(&s.srv.LroServer) }) + resp, err = s.trLroServer.Do(req) + case "LroPagingClient": + initServer(&s.trMu, &s.trLroPagingServer, func() *LroPagingServerTransport { return NewLroPagingServerTransport(&s.srv.LroPagingServer) }) + resp, err = s.trLroPagingServer.Do(req) + case "OperationsClient": + initServer(&s.trMu, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + resp, err = s.trOperationsServer.Do(req) + case "OptionalBodyClient": + initServer(&s.trMu, &s.trOptionalBodyServer, func() *OptionalBodyServerTransport { return NewOptionalBodyServerTransport(&s.srv.OptionalBodyServer) }) + resp, err = s.trOptionalBodyServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/go.mod b/test/azure-http-specs/azure/resource-manager/templatesgroup/go.mod new file mode 100644 index 000000000000..014b3f288a57 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/go.mod @@ -0,0 +1,17 @@ +module templatesgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/go.sum b/test/azure-http-specs/azure/resource-manager/templatesgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/lro_client_test.go b/test/azure-http-specs/azure/resource-manager/templatesgroup/lro_client_test.go new file mode 100644 index 000000000000..1e9c7c858b17 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/lro_client_test.go @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package templatesgroup_test + +import ( + "context" + "templatesgroup" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +const RESOURCE_GROUP_EXPECTED = "test-rg" + +func TestNewLroClient_BeginCreateOrReplace(t *testing.T) { + createdByType := templatesgroup.CreatedByType("User") + lastModifiedByType := templatesgroup.CreatedByType("User") + createdAt, err := time.Parse(time.RFC3339Nano, "2024-10-04T00:56:07.442Z") + require.NoError(t, err) + lastModifiedAt, err := time.Parse(time.RFC3339Nano, "2024-10-04T00:56:07.442Z") + require.NoError(t, err) + + poller, err := clientFactory.NewLroClient().BeginCreateOrReplace(ctx, RESOURCE_GROUP_EXPECTED, "order1", templatesgroup.Order{ + Location: to.Ptr("eastus"), + ID: to.Ptr("/subscriptions/${SUBSCRIPTION_ID_EXPECTED}/resourceGroups/${RESOURCE_GROUP_EXPECTED}/providers/Azure.ResourceManager.OperationTemplates/orders/order1"), + Name: to.Ptr("order1"), + Type: to.Ptr("Azure.ResourceManager.Resources/orders"), + Properties: &templatesgroup.OrderProperties{ + ProvisioningState: to.Ptr("Succeeded"), + ProductID: to.Ptr("product1"), + Amount: to.Ptr(int32(1)), + }, + SystemData: &templatesgroup.SystemData{ + CreatedBy: to.Ptr("AzureSDK"), + CreatedByType: &createdByType, + CreatedAt: &createdAt, + LastModifiedBy: to.Ptr("AzureSDK"), + LastModifiedAt: &lastModifiedAt, + LastModifiedByType: &lastModifiedByType, + }, + }, nil) + require.NoError(t, err) + resp, err := poller.PollUntilDone(context.Background(), &runtime.PollUntilDoneOptions{Frequency: time.Second}) + require.NoError(t, err) + require.NotNil(t, resp.Name) + require.Equal(t, "order1", *resp.Name) + require.Equal(t, "Succeeded", *resp.Properties.ProvisioningState) + +} + +func TestNewLroClient_BeginDelete(t *testing.T) { + poller, err := clientFactory.NewLroClient().BeginDelete(context.Background(), RESOURCE_GROUP_EXPECTED, "order1", nil) + require.NoError(t, err) + _, err = poller.PollUntilDone(context.Background(), &runtime.PollUntilDoneOptions{Frequency: time.Second}) + require.NoError(t, err) + +} + +func TestNewLroClient_BeginExport(t *testing.T) { + body := templatesgroup.ExportRequest{ + Format: to.Ptr("csv"), + } + poller, err := clientFactory.NewLroClient().BeginExport(context.Background(), RESOURCE_GROUP_EXPECTED, "order1", body, nil) + require.NoError(t, err) + resp, err := poller.PollUntilDone(context.Background(), &runtime.PollUntilDoneOptions{Frequency: time.Second}) + require.NoError(t, err) + require.NotNil(t, resp.Content) + require.NotEmpty(t, resp.Content) + require.Equal(t, "order1,product1,1", *resp.Content) +} + +func TestNewLroClient_BeginExportArray(t *testing.T) { + body := templatesgroup.ExportRequest{ + Format: to.Ptr("csv"), + } + poller, err := clientFactory.NewLroClient().BeginExportArray(context.Background(), body, nil) + require.NoError(t, err) + resp, err := poller.PollUntilDone(context.Background(), &runtime.PollUntilDoneOptions{Frequency: time.Second}) + require.NoError(t, err) + require.Len(t, resp.ExportResultArray, 2) + require.NotNil(t, resp.ExportResultArray[0]) + require.NotNil(t, resp.ExportResultArray[0].Content) + require.NotNil(t, resp.ExportResultArray[1]) + require.NotNil(t, resp.ExportResultArray[1].Content) + require.Equal(t, "order1,product1,1", *resp.ExportResultArray[0].Content) + require.Equal(t, "order2,product2,2", *resp.ExportResultArray[1].Content) +} diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/lropaging_client_test.go b/test/azure-http-specs/azure/resource-manager/templatesgroup/lropaging_client_test.go new file mode 100644 index 000000000000..0a5bca28d397 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/lropaging_client_test.go @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package templatesgroup_test + +import ( + "context" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/stretchr/testify/require" +) + +func TestNewLroPagingClient_BeginPostPagingLro(t *testing.T) { + // Start the long-running operation + poller, err := clientFactory.NewLroPagingClient().BeginPostPagingLro(ctx, resourceGroupExpected, "default", nil) + require.NoError(t, err) + + // Poll until the LRO completes and get the pager + pager, err := poller.PollUntilDone(context.Background(), &runtime.PollUntilDoneOptions{Frequency: time.Second}) + require.NoError(t, err) + require.NotNil(t, pager) + + // Iterate through the first page + hasFirstPage := pager.More() + require.True(t, hasFirstPage, "Expected at least one page of results") + + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + require.NotNil(t, page.Value) + require.Len(t, page.Value, 1, "Expected first page to contain 1 product") + + // Validate first product + product1 := page.Value[0] + require.NotNil(t, product1.Name) + require.Equal(t, "product1", *product1.Name) + require.NotNil(t, product1.Properties) + require.NotNil(t, product1.Properties.ProductID) + require.Equal(t, "product1", *product1.Properties.ProductID) + require.NotNil(t, product1.Properties.ProvisioningState) + require.Equal(t, "Succeeded", *product1.Properties.ProvisioningState) + + // Iterate through the second page + hasSecondPage := pager.More() + require.True(t, hasSecondPage, "Expected a second page of results") + + page2, err := pager.NextPage(context.Background()) + require.NoError(t, err) + require.NotNil(t, page2.Value) + require.Len(t, page2.Value, 1, "Expected second page to contain 1 product") + + // Validate second product + product2 := page2.Value[0] + require.NotNil(t, product2.Name) + require.Equal(t, "product2", *product2.Name) + require.NotNil(t, product2.Properties) + require.NotNil(t, product2.Properties.ProductID) + require.Equal(t, "product2", *product2.Properties.ProductID) + require.NotNil(t, product2.Properties.ProvisioningState) + require.Equal(t, "Succeeded", *product2.Properties.ProvisioningState) + + // Verify no more pages + hasMorePages := pager.More() + require.False(t, hasMorePages, "Expected no more pages after the second page") +} diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/optionalbody_client_test.go b/test/azure-http-specs/azure/resource-manager/templatesgroup/optionalbody_client_test.go new file mode 100644 index 000000000000..23e4d159fa58 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/optionalbody_client_test.go @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package templatesgroup_test + +import ( + "context" + "fmt" + "templatesgroup" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +var validWidget = templatesgroup.Widget{ + ID: to.Ptr(fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Azure.ResourceManager.OperationTemplates/widgets/widget1", subscriptionIdExpected, resourceGroupExpected)), + Name: to.Ptr("widget1"), + Type: to.Ptr("Azure.ResourceManager.OperationTemplates/widgets"), + Location: to.Ptr("eastus"), + Properties: &templatesgroup.WidgetProperties{ + Name: to.Ptr("widget1"), + Description: to.Ptr("A test widget"), + ProvisioningState: to.Ptr("Succeeded"), + }, + SystemData: &templatesgroup.SystemData{ + CreatedBy: to.Ptr("AzureSDK"), + CreatedByType: to.Ptr(templatesgroup.CreatedByTypeUser), + CreatedAt: func() *time.Time { + t, _ := time.Parse(time.RFC3339Nano, "2024-10-04T00:56:07.442Z") + return &t + }(), + LastModifiedBy: to.Ptr("AzureSDK"), + LastModifiedAt: func() *time.Time { + t, _ := time.Parse(time.RFC3339Nano, "2024-10-04T00:56:07.442Z") + return &t + }(), + LastModifiedByType: to.Ptr(templatesgroup.CreatedByTypeUser), + }, +} + +func TestOptionalBodyClient_Get(t *testing.T) { + client := clientFactory.NewOptionalBodyClient() + require.NotNil(t, client) + resp, err := client.Get(context.Background(), resourceGroupExpected, widgetName, nil) + require.NoError(t, err) + require.NotNil(t, resp) + require.EqualValues(t, validWidget, resp.Widget) +} + +func TestOptionalBodyClient_Patch(t *testing.T) { + client := clientFactory.NewOptionalBodyClient() + require.NotNil(t, client) + resp, err := client.Patch(context.Background(), resourceGroupExpected, widgetName, templatesgroup.Widget{}, &templatesgroup.OptionalBodyClientPatchOptions{}) + require.NoError(t, err) + require.NotNil(t, resp) + require.EqualValues(t, validWidget, resp.Widget) + + widget := templatesgroup.Widget{ + Name: to.Ptr("widget1"), + Properties: &templatesgroup.WidgetProperties{ + Name: to.Ptr("updated-widget"), + Description: to.Ptr("Updated description"), + }, + } + resp, err = client.Patch(context.Background(), resourceGroupExpected, widgetName, widget, &templatesgroup.OptionalBodyClientPatchOptions{}) + require.NoError(t, err) + require.NotNil(t, resp) + require.EqualValues(t, widget.Properties.Name, resp.Properties.Name) + require.EqualValues(t, widget.Properties.Description, resp.Properties.Description) + require.EqualValues(t, widget.Name, resp.Name) +} + +func TestOptionalBodyClient_Post(t *testing.T) { + client := clientFactory.NewOptionalBodyClient() + require.NotNil(t, client) + resp, err := client.Post(context.Background(), resourceGroupExpected, widgetName, &templatesgroup.OptionalBodyClientPostOptions{}) + require.NoError(t, err) + require.NotNil(t, resp.Result) + require.EqualValues(t, "Action completed successfully", *resp.Result) + + resp, err = client.Post(context.Background(), resourceGroupExpected, widgetName, &templatesgroup.OptionalBodyClientPostOptions{ + Body: &templatesgroup.ActionRequest{ + ActionType: to.Ptr("perform"), + Parameters: to.Ptr("test-parameters"), + }, + }) + require.NoError(t, err) + require.NotNil(t, resp.Result) + require.EqualValues(t, "Action completed successfully with parameters", *resp.Result) +} + +func TestOptionalBodyClient_ProviderPost(t *testing.T) { + client := clientFactory.NewOptionalBodyClient() + require.NotNil(t, client) + resp, err := client.ProviderPost(context.Background(), &templatesgroup.OptionalBodyClientProviderPostOptions{}) + require.NoError(t, err) + require.NotNil(t, resp) + require.EqualValues(t, "Changed to default allowance", *resp.Status) + require.EqualValues(t, 50, *resp.TotalAllowed) + + resp, err = client.ProviderPost(context.Background(), &templatesgroup.OptionalBodyClientProviderPostOptions{ + Body: &templatesgroup.ChangeAllowanceRequest{ + Reason: to.Ptr("Increased demand"), + TotalAllowed: to.Ptr(int32(100)), + }, + }) + require.NoError(t, err) + require.NotNil(t, resp) + require.EqualValues(t, "Changed to requested allowance", *resp.Status) + require.EqualValues(t, 100, *resp.TotalAllowed) +} diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/testdata/_metadata.json b/test/azure-http-specs/azure/resource-manager/templatesgroup/testdata/_metadata.json new file mode 100644 index 000000000000..e77eb5b5a980 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Azure.ResourceManager.OperationTemplates": "2023-12-01-preview" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/utils_test.go b/test/azure-http-specs/azure/resource-manager/templatesgroup/utils_test.go new file mode 100644 index 000000000000..e81d1632592f --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/utils_test.go @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package templatesgroup_test + +import ( + "context" + "templatesgroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" +) + +var ( + ctx context.Context + clientFactory *templatesgroup.ClientFactory + + subscriptionIdExpected = "00000000-0000-0000-0000-000000000000" + locationExpected = "eastus" + resourceGroupExpected = "test-rg" + widgetName = "widget1" +) + +func TestMain(m *testing.M) { + ctx = context.Background() + clientFactory, _ = templatesgroup.NewClientFactory(subscriptionIdExpected, &azfake.TokenCredential{}, &arm.ClientOptions{ + ClientOptions: azcore.ClientOptions{ + Cloud: cloud.Configuration{ + Services: map[cloud.ServiceName]cloud.ServiceConfiguration{ + cloud.ResourceManager: { + Audience: "fake_audience", + Endpoint: "http://localhost:3000", + }, + }, + }, + InsecureAllowCredentialWithHTTP: true, + }, + }) + + m.Run() +} diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_checknameavailability_client.go b/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_checknameavailability_client.go new file mode 100644 index 000000000000..0aaffee0f39e --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_checknameavailability_client.go @@ -0,0 +1,163 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package templatesgroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// CheckNameAvailabilityClient contains the methods for the CheckNameAvailability group. +// Don't use this type directly, use NewCheckNameAvailabilityClient() instead. +// +// Generated from API version 2023-12-01-preview +type CheckNameAvailabilityClient struct { + internal *arm.Client + subscriptionID string +} + +// NewCheckNameAvailabilityClient creates a new instance of CheckNameAvailabilityClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewCheckNameAvailabilityClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CheckNameAvailabilityClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CheckNameAvailabilityClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CheckGlobal - Implements global CheckNameAvailability operations +// If the operation fails it returns an *azcore.ResponseError type. +// - body - The CheckAvailability request +// - options - CheckNameAvailabilityClientCheckGlobalOptions contains the optional parameters for the CheckNameAvailabilityClient.CheckGlobal +// method. +func (client *CheckNameAvailabilityClient) CheckGlobal(ctx context.Context, body CheckNameAvailabilityRequest, options *CheckNameAvailabilityClientCheckGlobalOptions) (CheckNameAvailabilityClientCheckGlobalResponse, error) { + var err error + const operationName = "CheckNameAvailabilityClient.CheckGlobal" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.checkGlobalCreateRequest(ctx, body, options) + if err != nil { + return CheckNameAvailabilityClientCheckGlobalResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CheckNameAvailabilityClientCheckGlobalResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CheckNameAvailabilityClientCheckGlobalResponse{}, err + } + resp, err := client.checkGlobalHandleResponse(httpResp) + return resp, err +} + +// checkGlobalCreateRequest creates the CheckGlobal request. +func (client *CheckNameAvailabilityClient) checkGlobalCreateRequest(ctx context.Context, body CheckNameAvailabilityRequest, _ *CheckNameAvailabilityClientCheckGlobalOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Azure.ResourceManager.OperationTemplates/checkNameAvailability" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// checkGlobalHandleResponse handles the CheckGlobal response. +func (client *CheckNameAvailabilityClient) checkGlobalHandleResponse(resp *http.Response) (CheckNameAvailabilityClientCheckGlobalResponse, error) { + result := CheckNameAvailabilityClientCheckGlobalResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CheckNameAvailabilityResponse); err != nil { + return CheckNameAvailabilityClientCheckGlobalResponse{}, err + } + return result, nil +} + +// CheckLocal - Implements local CheckNameAvailability operations +// If the operation fails it returns an *azcore.ResponseError type. +// - location - The name of the Azure region. +// - body - The CheckAvailability request +// - options - CheckNameAvailabilityClientCheckLocalOptions contains the optional parameters for the CheckNameAvailabilityClient.CheckLocal +// method. +func (client *CheckNameAvailabilityClient) CheckLocal(ctx context.Context, location string, body CheckNameAvailabilityRequest, options *CheckNameAvailabilityClientCheckLocalOptions) (CheckNameAvailabilityClientCheckLocalResponse, error) { + var err error + const operationName = "CheckNameAvailabilityClient.CheckLocal" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.checkLocalCreateRequest(ctx, location, body, options) + if err != nil { + return CheckNameAvailabilityClientCheckLocalResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CheckNameAvailabilityClientCheckLocalResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CheckNameAvailabilityClientCheckLocalResponse{}, err + } + resp, err := client.checkLocalHandleResponse(httpResp) + return resp, err +} + +// checkLocalCreateRequest creates the CheckLocal request. +func (client *CheckNameAvailabilityClient) checkLocalCreateRequest(ctx context.Context, location string, body CheckNameAvailabilityRequest, _ *CheckNameAvailabilityClientCheckLocalOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Azure.ResourceManager.OperationTemplates/locations/{location}/checkNameAvailability" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// checkLocalHandleResponse handles the CheckLocal response. +func (client *CheckNameAvailabilityClient) checkLocalHandleResponse(resp *http.Response) (CheckNameAvailabilityClientCheckLocalResponse, error) { + result := CheckNameAvailabilityClientCheckLocalResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CheckNameAvailabilityResponse); err != nil { + return CheckNameAvailabilityClientCheckLocalResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_client_factory.go b/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_client_factory.go new file mode 100644 index 000000000000..50c47c641796 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_client_factory.go @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package templatesgroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + subscriptionID string + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, + internal: internal, + }, nil +} + +// NewCheckNameAvailabilityClient creates a new instance of CheckNameAvailabilityClient. +func (c *ClientFactory) NewCheckNameAvailabilityClient() *CheckNameAvailabilityClient { + return &CheckNameAvailabilityClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewLroClient creates a new instance of LroClient. +func (c *ClientFactory) NewLroClient() *LroClient { + return &LroClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewLroPagingClient creates a new instance of LroPagingClient. +func (c *ClientFactory) NewLroPagingClient() *LroPagingClient { + return &LroPagingClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: c.internal, + } +} + +// NewOptionalBodyClient creates a new instance of OptionalBodyClient. +func (c *ClientFactory) NewOptionalBodyClient() *OptionalBodyClient { + return &OptionalBodyClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_constants.go b/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_constants.go new file mode 100644 index 000000000000..c60ef17d4b68 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_constants.go @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package templatesgroup + +const ( + version20231201Preview string = "2023-12-01-preview" +) + +// ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +type ActionType string + +const ( + // ActionTypeInternal - Actions are for internal-only APIs. + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// CheckNameAvailabilityReason - Possible reasons for a name not being available. +type CheckNameAvailabilityReason string + +const ( + // CheckNameAvailabilityReasonAlreadyExists - Name already exists. + CheckNameAvailabilityReasonAlreadyExists CheckNameAvailabilityReason = "AlreadyExists" + // CheckNameAvailabilityReasonInvalid - Name is invalid. + CheckNameAvailabilityReasonInvalid CheckNameAvailabilityReason = "Invalid" +) + +// PossibleCheckNameAvailabilityReasonValues returns the possible values for the CheckNameAvailabilityReason const type. +func PossibleCheckNameAvailabilityReasonValues() []CheckNameAvailabilityReason { + return []CheckNameAvailabilityReason{ + CheckNameAvailabilityReasonAlreadyExists, + CheckNameAvailabilityReasonInvalid, + } +} + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// Origin - The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default +// value is "user,system" +type Origin string + +const ( + // OriginSystem - Indicates the operation is initiated by a system. + OriginSystem Origin = "system" + // OriginUser - Indicates the operation is initiated by a user. + OriginUser Origin = "user" + // OriginUserSystem - Indicates the operation is initiated by a user or system. + OriginUserSystem Origin = "user,system" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginSystem, + OriginUser, + OriginUserSystem, + } +} diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_lro_client.go b/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_lro_client.go new file mode 100644 index 000000000000..b479d4514101 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_lro_client.go @@ -0,0 +1,329 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package templatesgroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// LroClient contains the methods for the Lro group. +// Don't use this type directly, use NewLroClient() instead. +// +// Generated from API version 2023-12-01-preview +type LroClient struct { + internal *arm.Client + subscriptionID string +} + +// NewLroClient creates a new instance of LroClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewLroClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*LroClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &LroClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrReplace - Create a Order +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - orderName - The name of the Order +// - resource - Resource create parameters. +// - options - LroClientBeginCreateOrReplaceOptions contains the optional parameters for the LroClient.BeginCreateOrReplace +// method. +func (client *LroClient) BeginCreateOrReplace(ctx context.Context, resourceGroupName string, orderName string, resource Order, options *LroClientBeginCreateOrReplaceOptions) (*runtime.Poller[LroClientCreateOrReplaceResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrReplace(ctx, resourceGroupName, orderName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[LroClientCreateOrReplaceResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[LroClientCreateOrReplaceResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrReplace - Create a Order +// If the operation fails it returns an *azcore.ResponseError type. +func (client *LroClient) createOrReplace(ctx context.Context, resourceGroupName string, orderName string, resource Order, options *LroClientBeginCreateOrReplaceOptions) (*http.Response, error) { + var err error + const operationName = "LroClient.BeginCreateOrReplace" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrReplaceCreateRequest(ctx, resourceGroupName, orderName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrReplaceCreateRequest creates the CreateOrReplace request. +func (client *LroClient) createOrReplaceCreateRequest(ctx context.Context, resourceGroupName string, orderName string, resource Order, _ *LroClientBeginCreateOrReplaceOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.OperationTemplates/orders/{orderName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if orderName == "" { + return nil, errors.New("parameter orderName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{orderName}", url.PathEscape(orderName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a Order +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - orderName - The name of the Order +// - options - LroClientBeginDeleteOptions contains the optional parameters for the LroClient.BeginDelete method. +func (client *LroClient) BeginDelete(ctx context.Context, resourceGroupName string, orderName string, options *LroClientBeginDeleteOptions) (*runtime.Poller[LroClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, orderName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[LroClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[LroClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a Order +// If the operation fails it returns an *azcore.ResponseError type. +func (client *LroClient) deleteOperation(ctx context.Context, resourceGroupName string, orderName string, options *LroClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "LroClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, orderName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *LroClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, orderName string, _ *LroClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.OperationTemplates/orders/{orderName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if orderName == "" { + return nil, errors.New("parameter orderName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{orderName}", url.PathEscape(orderName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// BeginExport - A long-running resource action. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - orderName - The name of the Order +// - body - The content of the action request +// - options - LroClientBeginExportOptions contains the optional parameters for the LroClient.BeginExport method. +func (client *LroClient) BeginExport(ctx context.Context, resourceGroupName string, orderName string, body ExportRequest, options *LroClientBeginExportOptions) (*runtime.Poller[LroClientExportResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.export(ctx, resourceGroupName, orderName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[LroClientExportResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[LroClientExportResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Export - A long-running resource action. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *LroClient) export(ctx context.Context, resourceGroupName string, orderName string, body ExportRequest, options *LroClientBeginExportOptions) (*http.Response, error) { + var err error + const operationName = "LroClient.BeginExport" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.exportCreateRequest(ctx, resourceGroupName, orderName, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// exportCreateRequest creates the Export request. +func (client *LroClient) exportCreateRequest(ctx context.Context, resourceGroupName string, orderName string, body ExportRequest, _ *LroClientBeginExportOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.OperationTemplates/orders/{orderName}/export" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if orderName == "" { + return nil, errors.New("parameter orderName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{orderName}", url.PathEscape(orderName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// - body - The request body +// - options - LroClientBeginExportArrayOptions contains the optional parameters for the LroClient.BeginExportArray method. +func (client *LroClient) BeginExportArray(ctx context.Context, body ExportRequest, options *LroClientBeginExportArrayOptions) (*runtime.Poller[LroClientExportArrayResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.exportArray(ctx, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[LroClientExportArrayResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[LroClientExportArrayResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ExportArray - +// If the operation fails it returns an *azcore.ResponseError type. +func (client *LroClient) exportArray(ctx context.Context, body ExportRequest, options *LroClientBeginExportArrayOptions) (*http.Response, error) { + var err error + const operationName = "LroClient.BeginExportArray" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.exportArrayCreateRequest(ctx, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// exportArrayCreateRequest creates the ExportArray request. +func (client *LroClient) exportArrayCreateRequest(ctx context.Context, body ExportRequest, _ *LroClientBeginExportArrayOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Azure.ResourceManager.OperationTemplates/exportArray" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_lropaging_client.go b/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_lropaging_client.go new file mode 100644 index 000000000000..adf1ce586ecd --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_lropaging_client.go @@ -0,0 +1,139 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package templatesgroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// LroPagingClient contains the methods for the LroPaging group. +// Don't use this type directly, use NewLroPagingClient() instead. +// +// Generated from API version 2023-12-01-preview +type LroPagingClient struct { + internal *arm.Client + subscriptionID string +} + +// NewLroPagingClient creates a new instance of LroPagingClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewLroPagingClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*LroPagingClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &LroPagingClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginPostPagingLro - A long-running resource action. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - productName - The name of the Product +// - options - LroPagingClientBeginPostPagingLroOptions contains the optional parameters for the LroPagingClient.BeginPostPagingLro +// method. +func (client *LroPagingClient) BeginPostPagingLro(ctx context.Context, resourceGroupName string, productName string, options *LroPagingClientBeginPostPagingLroOptions) (*runtime.Poller[*runtime.Pager[LroPagingClientPostPagingLroResponse]], error) { + pager := runtime.NewPager(runtime.PagingHandler[LroPagingClientPostPagingLroResponse]{ + More: func(page LroPagingClientPostPagingLroResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *LroPagingClientPostPagingLroResponse) (LroPagingClientPostPagingLroResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "LroPagingClient.BeginPostPagingLro") + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), *page.NextLink, func(ctx context.Context) (*policy.Request, error) { + return client.postPagingLroCreateRequest(ctx, resourceGroupName, productName, options) + }, nil) + if err != nil { + return LroPagingClientPostPagingLroResponse{}, err + } + return client.postPagingLroHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) + if options == nil || options.ResumeToken == "" { + resp, err := client.postPagingLro(ctx, resourceGroupName, productName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[*runtime.Pager[LroPagingClientPostPagingLroResponse]]{ + Response: &pager, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[*runtime.Pager[LroPagingClientPostPagingLroResponse]]{ + Response: &pager, + Tracer: client.internal.Tracer(), + }) + } +} + +// PostPagingLro - A long-running resource action. +func (client *LroPagingClient) postPagingLro(ctx context.Context, resourceGroupName string, productName string, options *LroPagingClientBeginPostPagingLroOptions) (*http.Response, error) { + var err error + const operationName = "LroPagingClient.BeginPostPagingLro" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.postPagingLroCreateRequest(ctx, resourceGroupName, productName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// postPagingLroCreateRequest creates the PostPagingLro request. +func (client *LroPagingClient) postPagingLroCreateRequest(ctx context.Context, resourceGroupName string, productName string, _ *LroPagingClientBeginPostPagingLroOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.OperationTemplates/products/{productName}/postPagingLro" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if productName == "" { + return nil, errors.New("parameter productName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{productName}", url.PathEscape(productName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// postPagingLroHandleResponse handles the PostPagingLro response. +func (client *LroPagingClient) postPagingLroHandleResponse(resp *http.Response) (LroPagingClientPostPagingLroResponse, error) { + result := LroPagingClientPostPagingLroResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ProductListResult); err != nil { + return LroPagingClientPostPagingLroResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_models.go b/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_models.go new file mode 100644 index 000000000000..e86dfdc125c0 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_models.go @@ -0,0 +1,250 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package templatesgroup + +import "time" + +type ActionRequest struct { + // The action type to perform. + ActionType *string + + // Additional action parameters. + Parameters *string +} + +type ActionResult struct { + // REQUIRED; The result of the action. + Result *string +} + +type ChangeAllowanceRequest struct { + // The reason for the change. + Reason *string + + // The new total allowed widgets. + TotalAllowed *int32 +} + +type ChangeAllowanceResult struct { + // REQUIRED; The status of the change. + Status *string + + // REQUIRED; The new total allowed widgets. + TotalAllowed *int32 +} + +// CheckNameAvailabilityRequest - The check availability request body. +type CheckNameAvailabilityRequest struct { + // The name of the resource for which availability needs to be checked. + Name *string + + // The resource type. + Type *string +} + +// CheckNameAvailabilityResponse - The check availability result. +type CheckNameAvailabilityResponse struct { + // Detailed reason why the given name is not available. + Message *string + + // Indicates if the resource name is available. + NameAvailable *bool + + // The reason why the given name is not available. + Reason *CheckNameAvailabilityReason +} + +type ExportRequest struct { + // REQUIRED; Format of the exported order. + Format *string +} + +type ExportResult struct { + // REQUIRED; Content of the exported order. + Content *string +} + +// Operation - REST API Operation +// +// Details of a REST API operation, returned from the Resource Provider Operations API +type Operation struct { + // Localized display information for this particular operation. + Display *OperationDisplay + + // READ-ONLY; Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + ActionType *ActionType + + // READ-ONLY; Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure + // Resource Manager/control-plane operations. + IsDataAction *bool + + // READ-ONLY; The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + // "Microsoft.Compute/virtualMachines/capture/action" + Name *string + + // READ-ONLY; The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default + // value is "user,system" + Origin *Origin +} + +// OperationDisplay - Localized display information for an operation. +type OperationDisplay struct { + // READ-ONLY; The short, localized friendly description of the operation; suitable for tool tips and detailed views. + Description *string + + // READ-ONLY; The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual + // Machine", "Restart Virtual Machine". + Operation *string + + // READ-ONLY; The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft + // Compute". + Provider *string + + // READ-ONLY; The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job + // Schedule Collections". + Resource *string +} + +// OperationListResult - A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to +// get the next set of results. +type OperationListResult struct { + // REQUIRED; The Operation items on this page + Value []*Operation + + // The link to the next page of items + NextLink *string +} + +// Order - Concrete tracked resource types can be created by aliasing this type using a specific property type. +type Order struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *OrderProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +type OrderProperties struct { + // REQUIRED; Amount of the product. + Amount *int32 + + // REQUIRED; The product ID of the order. + ProductID *string + + // READ-ONLY; The provisioning state of the product. + ProvisioningState *string +} + +// Product - Concrete tracked resource types can be created by aliasing this type using a specific property type. +type Product struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *ProductProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ProductListResult - Paged collection of Product items +type ProductListResult struct { + // REQUIRED; The Product items on this page + Value []*Product + + // The link to the next page of items + NextLink *string +} + +type ProductProperties struct { + // The product ID. + ProductID *string + + // READ-ONLY; The provisioning state of the product. + ProvisioningState *string +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time + + // The identity that created the resource. + CreatedBy *string + + // The type of identity that created the resource. + CreatedByType *CreatedByType + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time + + // The identity that last modified the resource. + LastModifiedBy *string + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType +} + +// Widget - Concrete tracked resource types can be created by aliasing this type using a specific property type. +type Widget struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *WidgetProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +type WidgetProperties struct { + // The description of the widget. + Description *string + + // The name of the widget. + Name *string + + // READ-ONLY; The provisioning state of the widget. + ProvisioningState *string +} diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_models_serde.go b/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_models_serde.go new file mode 100644 index 000000000000..5e898ee55f54 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_models_serde.go @@ -0,0 +1,747 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package templatesgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type ActionRequest. +func (a ActionRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionType", a.ActionType) + populate(objectMap, "parameters", a.Parameters) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ActionRequest. +func (a *ActionRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionType": + err = unpopulate(val, "ActionType", &a.ActionType) + delete(rawMsg, key) + case "parameters": + err = unpopulate(val, "Parameters", &a.Parameters) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ActionResult. +func (a ActionResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "result", a.Result) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ActionResult. +func (a *ActionResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "result": + err = unpopulate(val, "Result", &a.Result) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ChangeAllowanceRequest. +func (c ChangeAllowanceRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "reason", c.Reason) + populate(objectMap, "totalAllowed", c.TotalAllowed) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ChangeAllowanceRequest. +func (c *ChangeAllowanceRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "reason": + err = unpopulate(val, "Reason", &c.Reason) + delete(rawMsg, key) + case "totalAllowed": + err = unpopulate(val, "TotalAllowed", &c.TotalAllowed) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ChangeAllowanceResult. +func (c ChangeAllowanceResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "status", c.Status) + populate(objectMap, "totalAllowed", c.TotalAllowed) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ChangeAllowanceResult. +func (c *ChangeAllowanceResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "status": + err = unpopulate(val, "Status", &c.Status) + delete(rawMsg, key) + case "totalAllowed": + err = unpopulate(val, "TotalAllowed", &c.TotalAllowed) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CheckNameAvailabilityRequest. +func (c CheckNameAvailabilityRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", c.Name) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CheckNameAvailabilityRequest. +func (c *CheckNameAvailabilityRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CheckNameAvailabilityResponse. +func (c CheckNameAvailabilityResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "message", c.Message) + populate(objectMap, "nameAvailable", c.NameAvailable) + populate(objectMap, "reason", c.Reason) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CheckNameAvailabilityResponse. +func (c *CheckNameAvailabilityResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "message": + err = unpopulate(val, "Message", &c.Message) + delete(rawMsg, key) + case "nameAvailable": + err = unpopulate(val, "NameAvailable", &c.NameAvailable) + delete(rawMsg, key) + case "reason": + err = unpopulate(val, "Reason", &c.Reason) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExportRequest. +func (e ExportRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "format", e.Format) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExportRequest. +func (e *ExportRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "format": + err = unpopulate(val, "Format", &e.Format) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExportResult. +func (e ExportResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "content", e.Content) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExportResult. +func (e *ExportResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "content": + err = unpopulate(val, "Content", &e.Content) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Operation. +func (o Operation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionType", o.ActionType) + populate(objectMap, "display", o.Display) + populate(objectMap, "isDataAction", o.IsDataAction) + populate(objectMap, "name", o.Name) + populate(objectMap, "origin", o.Origin) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Operation. +func (o *Operation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionType": + err = unpopulate(val, "ActionType", &o.ActionType) + delete(rawMsg, key) + case "display": + err = unpopulate(val, "Display", &o.Display) + delete(rawMsg, key) + case "isDataAction": + err = unpopulate(val, "IsDataAction", &o.IsDataAction) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "origin": + err = unpopulate(val, "Origin", &o.Origin) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationDisplay. +func (o OperationDisplay) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", o.Description) + populate(objectMap, "operation", o.Operation) + populate(objectMap, "provider", o.Provider) + populate(objectMap, "resource", o.Resource) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationDisplay. +func (o *OperationDisplay) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &o.Description) + delete(rawMsg, key) + case "operation": + err = unpopulate(val, "Operation", &o.Operation) + delete(rawMsg, key) + case "provider": + err = unpopulate(val, "Provider", &o.Provider) + delete(rawMsg, key) + case "resource": + err = unpopulate(val, "Resource", &o.Resource) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationListResult. +func (o *OperationListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &o.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Order. +func (o Order) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", o.ID) + populate(objectMap, "location", o.Location) + populate(objectMap, "name", o.Name) + populate(objectMap, "properties", o.Properties) + populate(objectMap, "systemData", o.SystemData) + populate(objectMap, "tags", o.Tags) + populate(objectMap, "type", o.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Order. +func (o *Order) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &o.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &o.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &o.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &o.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &o.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &o.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OrderProperties. +func (o OrderProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "amount", o.Amount) + populate(objectMap, "productId", o.ProductID) + populate(objectMap, "provisioningState", o.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OrderProperties. +func (o *OrderProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "amount": + err = unpopulate(val, "Amount", &o.Amount) + delete(rawMsg, key) + case "productId": + err = unpopulate(val, "ProductID", &o.ProductID) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &o.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Product. +func (p Product) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", p.ID) + populate(objectMap, "location", p.Location) + populate(objectMap, "name", p.Name) + populate(objectMap, "properties", p.Properties) + populate(objectMap, "systemData", p.SystemData) + populate(objectMap, "tags", p.Tags) + populate(objectMap, "type", p.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Product. +func (p *Product) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &p.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &p.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &p.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &p.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &p.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ProductListResult. +func (p ProductListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", p.NextLink) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ProductListResult. +func (p *ProductListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &p.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ProductProperties. +func (p ProductProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "productId", p.ProductID) + populate(objectMap, "provisioningState", p.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ProductProperties. +func (p *ProductProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "productId": + err = unpopulate(val, "ProductID", &p.ProductID) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateTime[datetime.RFC3339](objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateTime[datetime.RFC3339](val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateTime[datetime.RFC3339](val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Widget. +func (w Widget) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", w.ID) + populate(objectMap, "location", w.Location) + populate(objectMap, "name", w.Name) + populate(objectMap, "properties", w.Properties) + populate(objectMap, "systemData", w.SystemData) + populate(objectMap, "tags", w.Tags) + populate(objectMap, "type", w.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Widget. +func (w *Widget) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &w.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &w.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &w.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &w.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &w.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &w.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &w.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type WidgetProperties. +func (w WidgetProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", w.Description) + populate(objectMap, "name", w.Name) + populate(objectMap, "provisioningState", w.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WidgetProperties. +func (w *WidgetProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &w.Description) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &w.Name) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &w.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_operations_client.go b/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_operations_client.go new file mode 100644 index 000000000000..676531f44c97 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_operations_client.go @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package templatesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +// +// Generated from API version 2023-12-01-preview +type OperationsClient struct { + internal *arm.Client +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*OperationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OperationsClient{ + internal: cl, + } + return client, nil +} + +// NewListPager - List the operations for the provider +// - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ + More: func(page OperationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OperationsClientListResponse) (OperationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OperationsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return OperationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, _ *OperationsClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Azure.ResourceManager.OperationTemplates/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsClientListResponse, error) { + result := OperationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsClientListResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_optionalbody_client.go b/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_optionalbody_client.go new file mode 100644 index 000000000000..e00db558a588 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_optionalbody_client.go @@ -0,0 +1,300 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package templatesgroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// OptionalBodyClient contains the methods for the OptionalBody group. +// Don't use this type directly, use NewOptionalBodyClient() instead. +// +// Generated from API version 2023-12-01-preview +type OptionalBodyClient struct { + internal *arm.Client + subscriptionID string +} + +// NewOptionalBodyClient creates a new instance of OptionalBodyClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewOptionalBodyClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*OptionalBodyClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OptionalBodyClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get a Widget +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - widgetName - The name of the Widget +// - options - OptionalBodyClientGetOptions contains the optional parameters for the OptionalBodyClient.Get method. +func (client *OptionalBodyClient) Get(ctx context.Context, resourceGroupName string, widgetName string, options *OptionalBodyClientGetOptions) (OptionalBodyClientGetResponse, error) { + var err error + const operationName = "OptionalBodyClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, widgetName, options) + if err != nil { + return OptionalBodyClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalBodyClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalBodyClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *OptionalBodyClient) getCreateRequest(ctx context.Context, resourceGroupName string, widgetName string, _ *OptionalBodyClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.OperationTemplates/widgets/{widgetName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if widgetName == "" { + return nil, errors.New("parameter widgetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{widgetName}", url.PathEscape(widgetName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *OptionalBodyClient) getHandleResponse(resp *http.Response) (OptionalBodyClientGetResponse, error) { + result := OptionalBodyClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Widget); err != nil { + return OptionalBodyClientGetResponse{}, err + } + return result, nil +} + +// Patch - Update a Widget +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - widgetName - The name of the Widget +// - properties - The resource properties to be updated. +// - options - OptionalBodyClientPatchOptions contains the optional parameters for the OptionalBodyClient.Patch method. +func (client *OptionalBodyClient) Patch(ctx context.Context, resourceGroupName string, widgetName string, properties Widget, options *OptionalBodyClientPatchOptions) (OptionalBodyClientPatchResponse, error) { + var err error + const operationName = "OptionalBodyClient.Patch" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.patchCreateRequest(ctx, resourceGroupName, widgetName, properties, options) + if err != nil { + return OptionalBodyClientPatchResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalBodyClientPatchResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalBodyClientPatchResponse{}, err + } + resp, err := client.patchHandleResponse(httpResp) + return resp, err +} + +// patchCreateRequest creates the Patch request. +func (client *OptionalBodyClient) patchCreateRequest(ctx context.Context, resourceGroupName string, widgetName string, properties Widget, _ *OptionalBodyClientPatchOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.OperationTemplates/widgets/{widgetName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if widgetName == "" { + return nil, errors.New("parameter widgetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{widgetName}", url.PathEscape(widgetName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} + +// patchHandleResponse handles the Patch response. +func (client *OptionalBodyClient) patchHandleResponse(resp *http.Response) (OptionalBodyClientPatchResponse, error) { + result := OptionalBodyClientPatchResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Widget); err != nil { + return OptionalBodyClientPatchResponse{}, err + } + return result, nil +} + +// Post - A synchronous resource action. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - widgetName - The name of the Widget +// - options - OptionalBodyClientPostOptions contains the optional parameters for the OptionalBodyClient.Post method. +func (client *OptionalBodyClient) Post(ctx context.Context, resourceGroupName string, widgetName string, options *OptionalBodyClientPostOptions) (OptionalBodyClientPostResponse, error) { + var err error + const operationName = "OptionalBodyClient.Post" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.postCreateRequest(ctx, resourceGroupName, widgetName, options) + if err != nil { + return OptionalBodyClientPostResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalBodyClientPostResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalBodyClientPostResponse{}, err + } + resp, err := client.postHandleResponse(httpResp) + return resp, err +} + +// postCreateRequest creates the Post request. +func (client *OptionalBodyClient) postCreateRequest(ctx context.Context, resourceGroupName string, widgetName string, options *OptionalBodyClientPostOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Azure.ResourceManager.OperationTemplates/widgets/{widgetName}/post" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if widgetName == "" { + return nil, errors.New("parameter widgetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{widgetName}", url.PathEscape(widgetName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.Body != nil { + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, *options.Body); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// postHandleResponse handles the Post response. +func (client *OptionalBodyClient) postHandleResponse(resp *http.Response) (OptionalBodyClientPostResponse, error) { + result := OptionalBodyClientPostResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ActionResult); err != nil { + return OptionalBodyClientPostResponse{}, err + } + return result, nil +} + +// ProviderPost - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalBodyClientProviderPostOptions contains the optional parameters for the OptionalBodyClient.ProviderPost +// method. +func (client *OptionalBodyClient) ProviderPost(ctx context.Context, options *OptionalBodyClientProviderPostOptions) (OptionalBodyClientProviderPostResponse, error) { + var err error + const operationName = "OptionalBodyClient.ProviderPost" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.providerPostCreateRequest(ctx, options) + if err != nil { + return OptionalBodyClientProviderPostResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalBodyClientProviderPostResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalBodyClientProviderPostResponse{}, err + } + resp, err := client.providerPostHandleResponse(httpResp) + return resp, err +} + +// providerPostCreateRequest creates the ProviderPost request. +func (client *OptionalBodyClient) providerPostCreateRequest(ctx context.Context, options *OptionalBodyClientProviderPostOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Azure.ResourceManager.OperationTemplates/providerPost" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.Body != nil { + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, *options.Body); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// providerPostHandleResponse handles the ProviderPost response. +func (client *OptionalBodyClient) providerPostHandleResponse(resp *http.Response) (OptionalBodyClientProviderPostResponse, error) { + result := OptionalBodyClientProviderPostResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ChangeAllowanceResult); err != nil { + return OptionalBodyClientProviderPostResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_options.go b/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_options.go new file mode 100644 index 000000000000..2afbf7ec61f4 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_options.go @@ -0,0 +1,74 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package templatesgroup + +// CheckNameAvailabilityClientCheckGlobalOptions contains the optional parameters for the CheckNameAvailabilityClient.CheckGlobal +// method. +type CheckNameAvailabilityClientCheckGlobalOptions struct { + // placeholder for future optional parameters +} + +// CheckNameAvailabilityClientCheckLocalOptions contains the optional parameters for the CheckNameAvailabilityClient.CheckLocal +// method. +type CheckNameAvailabilityClientCheckLocalOptions struct { + // placeholder for future optional parameters +} + +// LroClientBeginCreateOrReplaceOptions contains the optional parameters for the LroClient.BeginCreateOrReplace method. +type LroClientBeginCreateOrReplaceOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// LroClientBeginDeleteOptions contains the optional parameters for the LroClient.BeginDelete method. +type LroClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// LroClientBeginExportArrayOptions contains the optional parameters for the LroClient.BeginExportArray method. +type LroClientBeginExportArrayOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// LroClientBeginExportOptions contains the optional parameters for the LroClient.BeginExport method. +type LroClientBeginExportOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// LroPagingClientBeginPostPagingLroOptions contains the optional parameters for the LroPagingClient.BeginPostPagingLro method. +type LroPagingClientBeginPostPagingLroOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} + +// OptionalBodyClientGetOptions contains the optional parameters for the OptionalBodyClient.Get method. +type OptionalBodyClientGetOptions struct { + // placeholder for future optional parameters +} + +// OptionalBodyClientPatchOptions contains the optional parameters for the OptionalBodyClient.Patch method. +type OptionalBodyClientPatchOptions struct { + // placeholder for future optional parameters +} + +// OptionalBodyClientPostOptions contains the optional parameters for the OptionalBodyClient.Post method. +type OptionalBodyClientPostOptions struct { + // The content of the action request + Body *ActionRequest +} + +// OptionalBodyClientProviderPostOptions contains the optional parameters for the OptionalBodyClient.ProviderPost method. +type OptionalBodyClientProviderPostOptions struct { + // The request body + Body *ChangeAllowanceRequest +} diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_responses.go b/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_responses.go new file mode 100644 index 000000000000..0b1ad19aa524 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_responses.go @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package templatesgroup + +// CheckNameAvailabilityClientCheckGlobalResponse contains the response from method CheckNameAvailabilityClient.CheckGlobal. +type CheckNameAvailabilityClientCheckGlobalResponse struct { + // The check availability result. + CheckNameAvailabilityResponse +} + +// CheckNameAvailabilityClientCheckLocalResponse contains the response from method CheckNameAvailabilityClient.CheckLocal. +type CheckNameAvailabilityClientCheckLocalResponse struct { + // The check availability result. + CheckNameAvailabilityResponse +} + +// LroClientCreateOrReplaceResponse contains the response from method LroClient.BeginCreateOrReplace. +type LroClientCreateOrReplaceResponse struct { + // Concrete tracked resource types can be created by aliasing this type using a specific property type. + Order +} + +// LroClientDeleteResponse contains the response from method LroClient.BeginDelete. +type LroClientDeleteResponse struct { + // placeholder for future response values +} + +// LroClientExportArrayResponse contains the response from method LroClient.BeginExportArray. +type LroClientExportArrayResponse struct { + ExportResultArray []*ExportResult +} + +// LroClientExportResponse contains the response from method LroClient.BeginExport. +type LroClientExportResponse struct { + ExportResult +} + +// LroPagingClientPostPagingLroResponse contains the response from method LroPagingClient.BeginPostPagingLro. +type LroPagingClientPostPagingLroResponse struct { + // Paged collection of Product items + ProductListResult +} + +// OperationsClientListResponse contains the response from method OperationsClient.NewListPager. +type OperationsClientListResponse struct { + // A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. + OperationListResult +} + +// OptionalBodyClientGetResponse contains the response from method OptionalBodyClient.Get. +type OptionalBodyClientGetResponse struct { + // Concrete tracked resource types can be created by aliasing this type using a specific property type. + Widget +} + +// OptionalBodyClientPatchResponse contains the response from method OptionalBodyClient.Patch. +type OptionalBodyClientPatchResponse struct { + // Concrete tracked resource types can be created by aliasing this type using a specific property type. + Widget +} + +// OptionalBodyClientPostResponse contains the response from method OptionalBodyClient.Post. +type OptionalBodyClientPostResponse struct { + ActionResult +} + +// OptionalBodyClientProviderPostResponse contains the response from method OptionalBodyClient.ProviderPost. +type OptionalBodyClientProviderPostResponse struct { + ChangeAllowanceResult +} diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_responses_serde.go b/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_responses_serde.go new file mode 100644 index 000000000000..87bbc2d8fedb --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_responses_serde.go @@ -0,0 +1,12 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package templatesgroup + +import "encoding/json" + +// UnmarshalJSON implements the json.Unmarshaller interface for type LroClientExportArrayResponse. +func (l *LroClientExportArrayResponse) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, &l.ExportResultArray) +} diff --git a/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_version.go b/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_version.go new file mode 100644 index 000000000000..928573ea04f1 --- /dev/null +++ b/test/azure-http-specs/azure/resource-manager/templatesgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package templatesgroup + +const ( + moduleName = "templatesgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/LICENSE.txt b/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/fake/zz_internal.go b/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/fake/zz_internal.go new file mode 100644 index 000000000000..9dadf86c65b5 --- /dev/null +++ b/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/fake/zz_internal.go @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "reflect" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getHeaderValue(h http.Header, k string) string { + v := h[k] + if len(v) == 0 { + return "" + } + return v[0] +} + +func getOptional[T any](v T) *T { + if reflect.ValueOf(v).IsZero() { + return nil + } + return &v +} diff --git a/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/fake/zz_xmsclientrequestid_server.go b/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/fake/zz_xmsclientrequestid_server.go new file mode 100644 index 000000000000..7b5e3e482f45 --- /dev/null +++ b/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/fake/zz_xmsclientrequestid_server.go @@ -0,0 +1,108 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "xmsclientreqidgroup" +) + +// XMSClientRequestIDServer is a fake server for instances of the xmsclientreqidgroup.XMSClientRequestIDClient type. +type XMSClientRequestIDServer struct { + // Get is the fake for method XMSClientRequestIDClient.Get + // HTTP status codes to indicate success: http.StatusNoContent + Get func(ctx context.Context, options *xmsclientreqidgroup.XMSClientRequestIDClientGetOptions) (resp azfake.Responder[xmsclientreqidgroup.XMSClientRequestIDClientGetResponse], errResp azfake.ErrorResponder) +} + +// NewXMSClientRequestIDServerTransport creates a new instance of XMSClientRequestIDServerTransport with the provided implementation. +// The returned XMSClientRequestIDServerTransport instance is connected to an instance of xmsclientreqidgroup.XMSClientRequestIDClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMSClientRequestIDServerTransport(srv *XMSClientRequestIDServer) *XMSClientRequestIDServerTransport { + return &XMSClientRequestIDServerTransport{srv: srv} +} + +// XMSClientRequestIDServerTransport connects instances of xmsclientreqidgroup.XMSClientRequestIDClient to instances of XMSClientRequestIDServer. +// Don't use this type directly, use NewXMSClientRequestIDServerTransport instead. +type XMSClientRequestIDServerTransport struct { + srv *XMSClientRequestIDServer +} + +// Do implements the policy.Transporter interface for XMSClientRequestIDServerTransport. +func (x *XMSClientRequestIDServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToMethodFake(req, method) +} + +func (x *XMSClientRequestIDServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if xmsClientRequestIdserverTransportInterceptor != nil { + res.resp, res.err, intercepted = xmsClientRequestIdserverTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "XMSClientRequestIDClient.Get": + res.resp, res.err = x.dispatchGet(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (x *XMSClientRequestIDServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if x.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + clientRequestIDParam := getOptional(getHeaderValue(req.Header, "x-ms-client-request-id")) + var options *xmsclientreqidgroup.XMSClientRequestIDClientGetOptions + if clientRequestIDParam != nil { + options = &xmsclientreqidgroup.XMSClientRequestIDClientGetOptions{ + ClientRequestID: clientRequestIDParam, + } + } + respr, errRespr := x.srv.Get(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to XMSClientRequestIDServerTransport +var xmsClientRequestIdserverTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/go.mod b/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/go.mod new file mode 100644 index 000000000000..28b568b7ebad --- /dev/null +++ b/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/go.mod @@ -0,0 +1,17 @@ +module xmsclientreqidgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/go.sum b/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/testdata/_metadata.json b/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/xmsclientrequestid_client_test.go b/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/xmsclientrequestid_client_test.go new file mode 100644 index 000000000000..2af685671b6a --- /dev/null +++ b/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/xmsclientrequestid_client_test.go @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package xmsclientreqidgroup_test + +import ( + "context" + "net/http" + "testing" + "xmsclientreqidgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/stretchr/testify/require" +) + +type requestIDPolicy struct{} + +// NewRequestIDPolicy returns a policy that add the x-ms-client-request-id header +func newRequestIDPolicy() policy.Policy { + return &requestIDPolicy{} +} + +func (r *requestIDPolicy) Do(req *policy.Request) (*http.Response, error) { + const requestID = "x-ms-client-request-id" + if req.Raw().Header.Get(requestID) == "" { + req.Raw().Header.Set(requestID, "00000000-0000-0000-0000-000000000000") + } + return req.Next() +} + +func TestXMSClientRequestIDClient_Get(t *testing.T) { + // TODO: https://github.com/Azure/typespec-azure/issues/155 causes ClientRequestID optional param + _ = xmsclientreqidgroup.XMSClientRequestIDClientGetOptions{ + ClientRequestID: nil, // this should evaporate + } + client, err := xmsclientreqidgroup.NewXMSClientRequestIDClientWithNoCredential("http://localhost:3000", &xmsclientreqidgroup.XMSClientRequestIDClientOptions{ + azcore.ClientOptions{ + PerCallPolicies: []policy.Policy{ + newRequestIDPolicy(), + }, + }, + }) + require.NoError(t, err) + var httpResp *http.Response + resp, err := client.Get(policy.WithCaptureResponse(context.Background(), &httpResp), nil) + require.NoError(t, err) + require.Zero(t, resp) + require.EqualValues(t, httpResp.Header.Get("x-ms-client-request-id"), "00000000-0000-0000-0000-000000000000") +} diff --git a/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/zz_options.go b/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/zz_options.go new file mode 100644 index 000000000000..ba3efac48566 --- /dev/null +++ b/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/zz_options.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmsclientreqidgroup + +// XMSClientRequestIDClientGetOptions contains the optional parameters for the XMSClientRequestIDClient.Get method. +type XMSClientRequestIDClientGetOptions struct { + ClientRequestID *string +} diff --git a/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/zz_responses.go b/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/zz_responses.go new file mode 100644 index 000000000000..d6f548d2c668 --- /dev/null +++ b/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/zz_responses.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmsclientreqidgroup + +// XMSClientRequestIDClientGetResponse contains the response from method XMSClientRequestIDClient.Get. +type XMSClientRequestIDClientGetResponse struct { + // placeholder for future response values +} diff --git a/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/zz_version.go b/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/zz_version.go new file mode 100644 index 000000000000..d8615fd94f7c --- /dev/null +++ b/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package xmsclientreqidgroup + +const ( + moduleName = "xmsclientreqidgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/zz_xmsclientrequestid_client.go b/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/zz_xmsclientrequestid_client.go new file mode 100644 index 000000000000..1033f44df26f --- /dev/null +++ b/test/azure-http-specs/azure/special-headers/xmsclientreqidgroup/zz_xmsclientrequestid_client.go @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmsclientreqidgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// XMSClientRequestIDClient - Azure client request id header configurations. +// Don't use this type directly, use NewXMSClientRequestIDClientWithNoCredential() instead. +type XMSClientRequestIDClient struct { + internal *azcore.Client + endpoint string +} + +// XMSClientRequestIDClientOptions contains the optional values for creating a [XMSClientRequestIDClient]. +type XMSClientRequestIDClientOptions struct { + azcore.ClientOptions +} + +// NewXMSClientRequestIDClientWithNoCredential creates a new instance of XMSClientRequestIDClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewXMSClientRequestIDClientWithNoCredential(endpoint string, options *XMSClientRequestIDClientOptions) (*XMSClientRequestIDClient, error) { + if options == nil { + options = &XMSClientRequestIDClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &XMSClientRequestIDClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// Get - Get operation with azure `x-ms-client-request-id` header. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMSClientRequestIDClientGetOptions contains the optional parameters for the XMSClientRequestIDClient.Get method. +func (client *XMSClientRequestIDClient) Get(ctx context.Context, options *XMSClientRequestIDClientGetOptions) (XMSClientRequestIDClientGetResponse, error) { + var err error + const operationName = "XMSClientRequestIDClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return XMSClientRequestIDClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMSClientRequestIDClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return XMSClientRequestIDClientGetResponse{}, err + } + return XMSClientRequestIDClientGetResponse{}, nil +} + +// getCreateRequest creates the Get request. +func (client *XMSClientRequestIDClient) getCreateRequest(ctx context.Context, options *XMSClientRequestIDClientGetOptions) (*policy.Request, error) { + urlPath := "/azure/special-headers/x-ms-client-request-id/" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + return req, nil +} diff --git a/test/azure-http-specs/azure/versioning/previewversiongroup/LICENSE.txt b/test/azure-http-specs/azure/versioning/previewversiongroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/versioning/previewversiongroup/fake/zz_internal.go b/test/azure-http-specs/azure/versioning/previewversiongroup/fake/zz_internal.go new file mode 100644 index 000000000000..53ec711308cc --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroup/fake/zz_internal.go @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "reflect" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getOptional[T any](v T) *T { + if reflect.ValueOf(v).IsZero() { + return nil + } + return &v +} diff --git a/test/azure-http-specs/azure/versioning/previewversiongroup/fake/zz_previewversion_server.go b/test/azure-http-specs/azure/versioning/previewversiongroup/fake/zz_previewversion_server.go new file mode 100644 index 000000000000..6b61cb7956d8 --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroup/fake/zz_previewversion_server.go @@ -0,0 +1,187 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "previewversiongroup" + "regexp" + "slices" +) + +// PreviewVersionServer is a fake server for instances of the previewversiongroup.PreviewVersionClient type. +type PreviewVersionServer struct { + // GetWidget is the fake for method PreviewVersionClient.GetWidget + // HTTP status codes to indicate success: http.StatusOK, http.StatusNotFound + GetWidget func(ctx context.Context, id string, options *previewversiongroup.PreviewVersionClientGetWidgetOptions) (resp azfake.Responder[previewversiongroup.PreviewVersionClientGetWidgetResponse], errResp azfake.ErrorResponder) + + // ListWidgets is the fake for method PreviewVersionClient.ListWidgets + // HTTP status codes to indicate success: http.StatusOK + ListWidgets func(ctx context.Context, options *previewversiongroup.PreviewVersionClientListWidgetsOptions) (resp azfake.Responder[previewversiongroup.PreviewVersionClientListWidgetsResponse], errResp azfake.ErrorResponder) + + // UpdateWidgetColor is the fake for method PreviewVersionClient.UpdateWidgetColor + // HTTP status codes to indicate success: http.StatusOK, http.StatusNotFound + UpdateWidgetColor func(ctx context.Context, id string, colorUpdate previewversiongroup.UpdateWidgetColorRequest, options *previewversiongroup.PreviewVersionClientUpdateWidgetColorOptions) (resp azfake.Responder[previewversiongroup.PreviewVersionClientUpdateWidgetColorResponse], errResp azfake.ErrorResponder) +} + +// NewPreviewVersionServerTransport creates a new instance of PreviewVersionServerTransport with the provided implementation. +// The returned PreviewVersionServerTransport instance is connected to an instance of previewversiongroup.PreviewVersionClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewPreviewVersionServerTransport(srv *PreviewVersionServer) *PreviewVersionServerTransport { + return &PreviewVersionServerTransport{srv: srv} +} + +// PreviewVersionServerTransport connects instances of previewversiongroup.PreviewVersionClient to instances of PreviewVersionServer. +// Don't use this type directly, use NewPreviewVersionServerTransport instead. +type PreviewVersionServerTransport struct { + srv *PreviewVersionServer +} + +// Do implements the policy.Transporter interface for PreviewVersionServerTransport. +func (p *PreviewVersionServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return p.dispatchToMethodFake(req, method) +} + +func (p *PreviewVersionServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if previewVersionServerTransportInterceptor != nil { + res.resp, res.err, intercepted = previewVersionServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "PreviewVersionClient.GetWidget": + res.resp, res.err = p.dispatchGetWidget(req) + case "PreviewVersionClient.ListWidgets": + res.resp, res.err = p.dispatchListWidgets(req) + case "PreviewVersionClient.UpdateWidgetColor": + res.resp, res.err = p.dispatchUpdateWidgetColor(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (p *PreviewVersionServerTransport) dispatchGetWidget(req *http.Request) (*http.Response, error) { + if p.srv.GetWidget == nil { + return nil, &nonRetriableError{errors.New("fake for method GetWidget not implemented")} + } + const regexStr = `/azure/versioning/previewVersion/widgets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + idParam, err := url.PathUnescape(matches[regex.SubexpIndex("id")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.GetWidget(req.Context(), idParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNotFound}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNotFound", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Widget, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (p *PreviewVersionServerTransport) dispatchListWidgets(req *http.Request) (*http.Response, error) { + if p.srv.ListWidgets == nil { + return nil, &nonRetriableError{errors.New("fake for method ListWidgets not implemented")} + } + qp := req.URL.Query() + nameParam := getOptional(qp.Get("name")) + colorParam := getOptional(qp.Get("color")) + var options *previewversiongroup.PreviewVersionClientListWidgetsOptions + if nameParam != nil || colorParam != nil { + options = &previewversiongroup.PreviewVersionClientListWidgetsOptions{ + Name: nameParam, + Color: colorParam, + } + } + respr, errRespr := p.srv.ListWidgets(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ListWidgetsResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (p *PreviewVersionServerTransport) dispatchUpdateWidgetColor(req *http.Request) (*http.Response, error) { + if p.srv.UpdateWidgetColor == nil { + return nil, &nonRetriableError{errors.New("fake for method UpdateWidgetColor not implemented")} + } + const regexStr = `/azure/versioning/previewVersion/widgets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/color` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[previewversiongroup.UpdateWidgetColorRequest](req) + if err != nil { + return nil, err + } + idParam, err := url.PathUnescape(matches[regex.SubexpIndex("id")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.UpdateWidgetColor(req.Context(), idParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNotFound}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNotFound", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Widget, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to PreviewVersionServerTransport +var previewVersionServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/versioning/previewversiongroup/go.mod b/test/azure-http-specs/azure/versioning/previewversiongroup/go.mod new file mode 100644 index 000000000000..f8bc912d677f --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroup/go.mod @@ -0,0 +1,17 @@ +module previewversiongroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/versioning/previewversiongroup/go.sum b/test/azure-http-specs/azure/versioning/previewversiongroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/versioning/previewversiongroup/previewversion_client_test.go b/test/azure-http-specs/azure/versioning/previewversiongroup/previewversion_client_test.go new file mode 100644 index 000000000000..e3038944d8dd --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroup/previewversion_client_test.go @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package previewversiongroup_test + +import ( + "context" + "testing" + + "previewversiongroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestPreviewVersionClient_GetWidget(t *testing.T) { + const fakeID = "widget-123" + client, err := previewversiongroup.NewPreviewVersionClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + ctx := context.Background() + resp, err := client.GetWidget(ctx, fakeID, nil) + + require.NoError(t, err) + require.Equal(t, "widget-123", *resp.ID) + require.Equal(t, "Sample Widget", *resp.Name) + require.Equal(t, "blue", *resp.Color) +} + +func TestPreviewVersionClient_UpdateWidgetColor(t *testing.T) { + const fakeID = "widget-123" + const newColor = "red" + client, err := previewversiongroup.NewPreviewVersionClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + + colorUpdate := previewversiongroup.UpdateWidgetColorRequest{ + Color: to.Ptr(newColor), + } + + resp, err := client.UpdateWidgetColor(context.Background(), fakeID, colorUpdate, nil) + require.NoError(t, err) + require.Equal(t, fakeID, *resp.ID) + require.Equal(t, "Sample Widget", *resp.Name) + require.Equal(t, newColor, *resp.Color) +} diff --git a/test/azure-http-specs/azure/versioning/previewversiongroup/testdata/_metadata.json b/test/azure-http-specs/azure/versioning/previewversiongroup/testdata/_metadata.json new file mode 100644 index 000000000000..6fbf89e40343 --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroup/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "_Specs_.Azure.Versioning.PreviewVersion": "2024-12-01-preview" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/versioning/previewversiongroup/zz_constants.go b/test/azure-http-specs/azure/versioning/previewversiongroup/zz_constants.go new file mode 100644 index 000000000000..451a78cbd0b8 --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroup/zz_constants.go @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package previewversiongroup + +const ( + version20241201Preview string = "2024-12-01-preview" +) diff --git a/test/azure-http-specs/azure/versioning/previewversiongroup/zz_models.go b/test/azure-http-specs/azure/versioning/previewversiongroup/zz_models.go new file mode 100644 index 000000000000..7d934b36bb49 --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroup/zz_models.go @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package previewversiongroup + +type ListWidgetsResponse struct { + // REQUIRED + Widgets []*Widget +} + +// UpdateWidgetColorRequest - Update widget color request. +type UpdateWidgetColorRequest struct { + // REQUIRED; New color for the widget. + Color *string +} + +// Widget - A simple model for testing. +type Widget struct { + // REQUIRED; Widget identifier. + ID *string + + // REQUIRED; Widget name. + Name *string + + // Widget color, only available in preview version. + Color *string +} diff --git a/test/azure-http-specs/azure/versioning/previewversiongroup/zz_models_serde.go b/test/azure-http-specs/azure/versioning/previewversiongroup/zz_models_serde.go new file mode 100644 index 000000000000..d72a6512344f --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroup/zz_models_serde.go @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package previewversiongroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type ListWidgetsResponse. +func (l ListWidgetsResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "widgets", l.Widgets) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ListWidgetsResponse. +func (l *ListWidgetsResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "widgets": + err = unpopulate(val, "Widgets", &l.Widgets) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UpdateWidgetColorRequest. +func (u UpdateWidgetColorRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "color", u.Color) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UpdateWidgetColorRequest. +func (u *UpdateWidgetColorRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "color": + err = unpopulate(val, "Color", &u.Color) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Widget. +func (w Widget) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "color", w.Color) + populate(objectMap, "id", w.ID) + populate(objectMap, "name", w.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Widget. +func (w *Widget) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "color": + err = unpopulate(val, "Color", &w.Color) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &w.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &w.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/azure-http-specs/azure/versioning/previewversiongroup/zz_options.go b/test/azure-http-specs/azure/versioning/previewversiongroup/zz_options.go new file mode 100644 index 000000000000..5cceae082194 --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroup/zz_options.go @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package previewversiongroup + +// PreviewVersionClientGetWidgetOptions contains the optional parameters for the PreviewVersionClient.GetWidget method. +type PreviewVersionClientGetWidgetOptions struct { + // placeholder for future optional parameters +} + +// PreviewVersionClientListWidgetsOptions contains the optional parameters for the PreviewVersionClient.ListWidgets method. +type PreviewVersionClientListWidgetsOptions struct { + Color *string + Name *string +} + +// PreviewVersionClientUpdateWidgetColorOptions contains the optional parameters for the PreviewVersionClient.UpdateWidgetColor +// method. +type PreviewVersionClientUpdateWidgetColorOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/azure/versioning/previewversiongroup/zz_previewversion_client.go b/test/azure-http-specs/azure/versioning/previewversiongroup/zz_previewversion_client.go new file mode 100644 index 000000000000..4c0da0a90d5b --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroup/zz_previewversion_client.go @@ -0,0 +1,218 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package previewversiongroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// PreviewVersionClient contains the methods for the PreviewVersion group. +// Don't use this type directly, use NewPreviewVersionClientWithNoCredential() instead. +// +// Generated from API version 2024-12-01-preview +type PreviewVersionClient struct { + internal *azcore.Client + endpoint string +} + +// PreviewVersionClientOptions contains the optional values for creating a [PreviewVersionClient]. +type PreviewVersionClientOptions struct { + azcore.ClientOptions +} + +// NewPreviewVersionClientWithNoCredential creates a new instance of PreviewVersionClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewPreviewVersionClientWithNoCredential(endpoint string, options *PreviewVersionClientOptions) (*PreviewVersionClient, error) { + if options == nil { + options = &PreviewVersionClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{ + APIVersion: runtime.APIVersionOptions{ + Name: "api-version", + Location: runtime.APIVersionLocationQueryParam, + }, + }, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &PreviewVersionClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// GetWidget - Get widget by id (available in all versions) +// If the operation fails it returns an *azcore.ResponseError type. +// - options - PreviewVersionClientGetWidgetOptions contains the optional parameters for the PreviewVersionClient.GetWidget +// method. +func (client *PreviewVersionClient) GetWidget(ctx context.Context, id string, options *PreviewVersionClientGetWidgetOptions) (PreviewVersionClientGetWidgetResponse, error) { + var err error + const operationName = "PreviewVersionClient.GetWidget" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getWidgetCreateRequest(ctx, id, options) + if err != nil { + return PreviewVersionClientGetWidgetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PreviewVersionClientGetWidgetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNotFound) { + err = runtime.NewResponseError(httpResp) + return PreviewVersionClientGetWidgetResponse{}, err + } + resp, err := client.getWidgetHandleResponse(httpResp) + return resp, err +} + +// getWidgetCreateRequest creates the GetWidget request. +func (client *PreviewVersionClient) getWidgetCreateRequest(ctx context.Context, id string, _ *PreviewVersionClientGetWidgetOptions) (*policy.Request, error) { + urlPath := "/azure/versioning/previewVersion/widgets/{id}" + if id == "" { + return nil, errors.New("parameter id cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{id}", url.PathEscape(id)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20241201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getWidgetHandleResponse handles the GetWidget response. +func (client *PreviewVersionClient) getWidgetHandleResponse(resp *http.Response) (PreviewVersionClientGetWidgetResponse, error) { + result := PreviewVersionClientGetWidgetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Widget); err != nil { + return PreviewVersionClientGetWidgetResponse{}, err + } + return result, nil +} + +// ListWidgets - List widgets with optional color filtering +// If the operation fails it returns an *azcore.ResponseError type. +// - options - PreviewVersionClientListWidgetsOptions contains the optional parameters for the PreviewVersionClient.ListWidgets +// method. +func (client *PreviewVersionClient) ListWidgets(ctx context.Context, options *PreviewVersionClientListWidgetsOptions) (PreviewVersionClientListWidgetsResponse, error) { + var err error + const operationName = "PreviewVersionClient.ListWidgets" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listWidgetsCreateRequest(ctx, options) + if err != nil { + return PreviewVersionClientListWidgetsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PreviewVersionClientListWidgetsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PreviewVersionClientListWidgetsResponse{}, err + } + resp, err := client.listWidgetsHandleResponse(httpResp) + return resp, err +} + +// listWidgetsCreateRequest creates the ListWidgets request. +func (client *PreviewVersionClient) listWidgetsCreateRequest(ctx context.Context, options *PreviewVersionClientListWidgetsOptions) (*policy.Request, error) { + urlPath := "/azure/versioning/previewVersion/widgets" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20241201Preview) + if options != nil && options.Color != nil { + reqQP.Set("color", *options.Color) + } + if options != nil && options.Name != nil { + reqQP.Set("name", *options.Name) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listWidgetsHandleResponse handles the ListWidgets response. +func (client *PreviewVersionClient) listWidgetsHandleResponse(resp *http.Response) (PreviewVersionClientListWidgetsResponse, error) { + result := PreviewVersionClientListWidgetsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListWidgetsResponse); err != nil { + return PreviewVersionClientListWidgetsResponse{}, err + } + return result, nil +} + +// UpdateWidgetColor - Update widget color (preview only) +// If the operation fails it returns an *azcore.ResponseError type. +// - options - PreviewVersionClientUpdateWidgetColorOptions contains the optional parameters for the PreviewVersionClient.UpdateWidgetColor +// method. +func (client *PreviewVersionClient) UpdateWidgetColor(ctx context.Context, id string, colorUpdate UpdateWidgetColorRequest, options *PreviewVersionClientUpdateWidgetColorOptions) (PreviewVersionClientUpdateWidgetColorResponse, error) { + var err error + const operationName = "PreviewVersionClient.UpdateWidgetColor" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateWidgetColorCreateRequest(ctx, id, colorUpdate, options) + if err != nil { + return PreviewVersionClientUpdateWidgetColorResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PreviewVersionClientUpdateWidgetColorResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNotFound) { + err = runtime.NewResponseError(httpResp) + return PreviewVersionClientUpdateWidgetColorResponse{}, err + } + resp, err := client.updateWidgetColorHandleResponse(httpResp) + return resp, err +} + +// updateWidgetColorCreateRequest creates the UpdateWidgetColor request. +func (client *PreviewVersionClient) updateWidgetColorCreateRequest(ctx context.Context, id string, colorUpdate UpdateWidgetColorRequest, _ *PreviewVersionClientUpdateWidgetColorOptions) (*policy.Request, error) { + urlPath := "/azure/versioning/previewVersion/widgets/{id}/color" + if id == "" { + return nil, errors.New("parameter id cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{id}", url.PathEscape(id)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20241201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/merge-patch+json"} + if err := runtime.MarshalAsJSON(req, colorUpdate); err != nil { + return nil, err + } + return req, nil +} + +// updateWidgetColorHandleResponse handles the UpdateWidgetColor response. +func (client *PreviewVersionClient) updateWidgetColorHandleResponse(resp *http.Response) (PreviewVersionClientUpdateWidgetColorResponse, error) { + result := PreviewVersionClientUpdateWidgetColorResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Widget); err != nil { + return PreviewVersionClientUpdateWidgetColorResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/versioning/previewversiongroup/zz_responses.go b/test/azure-http-specs/azure/versioning/previewversiongroup/zz_responses.go new file mode 100644 index 000000000000..1b5b2d6cc0b1 --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroup/zz_responses.go @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package previewversiongroup + +// PreviewVersionClientGetWidgetResponse contains the response from method PreviewVersionClient.GetWidget. +type PreviewVersionClientGetWidgetResponse struct { + // A simple model for testing. + Widget +} + +// PreviewVersionClientListWidgetsResponse contains the response from method PreviewVersionClient.ListWidgets. +type PreviewVersionClientListWidgetsResponse struct { + ListWidgetsResponse +} + +// PreviewVersionClientUpdateWidgetColorResponse contains the response from method PreviewVersionClient.UpdateWidgetColor. +type PreviewVersionClientUpdateWidgetColorResponse struct { + // A simple model for testing. + Widget +} diff --git a/test/azure-http-specs/azure/versioning/previewversiongroup/zz_version.go b/test/azure-http-specs/azure/versioning/previewversiongroup/zz_version.go new file mode 100644 index 000000000000..a6c45b829ce2 --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package previewversiongroup + +const ( + moduleName = "previewversiongroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/LICENSE.txt b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/fake/zz_internal.go b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/fake/zz_internal.go new file mode 100644 index 000000000000..53ec711308cc --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/fake/zz_internal.go @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "reflect" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getOptional[T any](v T) *T { + if reflect.ValueOf(v).IsZero() { + return nil + } + return &v +} diff --git a/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/fake/zz_previewversion_server.go b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/fake/zz_previewversion_server.go new file mode 100644 index 000000000000..35372726eb67 --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/fake/zz_previewversion_server.go @@ -0,0 +1,146 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "previewversiongroupspecificversion" + "regexp" + "slices" +) + +// PreviewVersionServer is a fake server for instances of the previewversiongroupspecificversion.PreviewVersionClient type. +type PreviewVersionServer struct { + // GetWidget is the fake for method PreviewVersionClient.GetWidget + // HTTP status codes to indicate success: http.StatusOK, http.StatusNotFound + GetWidget func(ctx context.Context, id string, options *previewversiongroupspecificversion.PreviewVersionClientGetWidgetOptions) (resp azfake.Responder[previewversiongroupspecificversion.PreviewVersionClientGetWidgetResponse], errResp azfake.ErrorResponder) + + // ListWidgets is the fake for method PreviewVersionClient.ListWidgets + // HTTP status codes to indicate success: http.StatusOK + ListWidgets func(ctx context.Context, options *previewversiongroupspecificversion.PreviewVersionClientListWidgetsOptions) (resp azfake.Responder[previewversiongroupspecificversion.PreviewVersionClientListWidgetsResponse], errResp azfake.ErrorResponder) +} + +// NewPreviewVersionServerTransport creates a new instance of PreviewVersionServerTransport with the provided implementation. +// The returned PreviewVersionServerTransport instance is connected to an instance of previewversiongroupspecificversion.PreviewVersionClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewPreviewVersionServerTransport(srv *PreviewVersionServer) *PreviewVersionServerTransport { + return &PreviewVersionServerTransport{srv: srv} +} + +// PreviewVersionServerTransport connects instances of previewversiongroupspecificversion.PreviewVersionClient to instances of PreviewVersionServer. +// Don't use this type directly, use NewPreviewVersionServerTransport instead. +type PreviewVersionServerTransport struct { + srv *PreviewVersionServer +} + +// Do implements the policy.Transporter interface for PreviewVersionServerTransport. +func (p *PreviewVersionServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return p.dispatchToMethodFake(req, method) +} + +func (p *PreviewVersionServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if previewVersionServerTransportInterceptor != nil { + res.resp, res.err, intercepted = previewVersionServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "PreviewVersionClient.GetWidget": + res.resp, res.err = p.dispatchGetWidget(req) + case "PreviewVersionClient.ListWidgets": + res.resp, res.err = p.dispatchListWidgets(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (p *PreviewVersionServerTransport) dispatchGetWidget(req *http.Request) (*http.Response, error) { + if p.srv.GetWidget == nil { + return nil, &nonRetriableError{errors.New("fake for method GetWidget not implemented")} + } + const regexStr = `/azure/versioning/previewVersion/widgets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + idParam, err := url.PathUnescape(matches[regex.SubexpIndex("id")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.GetWidget(req.Context(), idParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNotFound}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNotFound", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Widget, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (p *PreviewVersionServerTransport) dispatchListWidgets(req *http.Request) (*http.Response, error) { + if p.srv.ListWidgets == nil { + return nil, &nonRetriableError{errors.New("fake for method ListWidgets not implemented")} + } + qp := req.URL.Query() + nameParam := getOptional(qp.Get("name")) + var options *previewversiongroupspecificversion.PreviewVersionClientListWidgetsOptions + if nameParam != nil { + options = &previewversiongroupspecificversion.PreviewVersionClientListWidgetsOptions{ + Name: nameParam, + } + } + respr, errRespr := p.srv.ListWidgets(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ListWidgetsResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to PreviewVersionServerTransport +var previewVersionServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/go.mod b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/go.mod new file mode 100644 index 000000000000..238d93f54deb --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/go.mod @@ -0,0 +1,17 @@ +module previewversiongroupspecificversion + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/go.sum b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/previewversion_client_test.go b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/previewversion_client_test.go new file mode 100644 index 000000000000..1e1a38a0a3dd --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/previewversion_client_test.go @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package previewversiongroupspecificversion_test + +import ( + "context" + "previewversiongroupspecificversion" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestPreviewVersionClient_ListWidgets(t *testing.T) { + client, err := previewversiongroupspecificversion.NewPreviewVersionClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + opts := &previewversiongroupspecificversion.PreviewVersionClientListWidgetsOptions{ + Name: to.Ptr("test"), + } + resp, err := client.ListWidgets(context.Background(), opts) + require.NoError(t, err) + require.Equal(t, "widget-1", *resp.Widgets[0].ID) + require.Equal(t, "test", *resp.Widgets[0].Name) +} diff --git a/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/testdata/_metadata.json b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/testdata/_metadata.json new file mode 100644 index 000000000000..6b20581914ec --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "_Specs_.Azure.Versioning.PreviewVersion": "2024-06-01" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_constants.go b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_constants.go new file mode 100644 index 000000000000..ee5ada11beeb --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_constants.go @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package previewversiongroupspecificversion + +const ( + version20240601 string = "2024-06-01" +) diff --git a/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_models.go b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_models.go new file mode 100644 index 000000000000..0d8035dc3638 --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_models.go @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package previewversiongroupspecificversion + +type ListWidgetsResponse struct { + // REQUIRED + Widgets []*Widget +} + +// Widget - A simple model for testing. +type Widget struct { + // REQUIRED; Widget identifier. + ID *string + + // REQUIRED; Widget name. + Name *string +} diff --git a/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_models_serde.go b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_models_serde.go new file mode 100644 index 000000000000..101d148ee010 --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_models_serde.go @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package previewversiongroupspecificversion + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type ListWidgetsResponse. +func (l ListWidgetsResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "widgets", l.Widgets) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ListWidgetsResponse. +func (l *ListWidgetsResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "widgets": + err = unpopulate(val, "Widgets", &l.Widgets) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Widget. +func (w Widget) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", w.ID) + populate(objectMap, "name", w.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Widget. +func (w *Widget) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &w.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &w.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_options.go b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_options.go new file mode 100644 index 000000000000..c25d9f3787c5 --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_options.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package previewversiongroupspecificversion + +// PreviewVersionClientGetWidgetOptions contains the optional parameters for the PreviewVersionClient.GetWidget method. +type PreviewVersionClientGetWidgetOptions struct { + // placeholder for future optional parameters +} + +// PreviewVersionClientListWidgetsOptions contains the optional parameters for the PreviewVersionClient.ListWidgets method. +type PreviewVersionClientListWidgetsOptions struct { + Name *string +} diff --git a/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_previewversion_client.go b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_previewversion_client.go new file mode 100644 index 000000000000..cd33ef928c83 --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_previewversion_client.go @@ -0,0 +1,158 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package previewversiongroupspecificversion + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// PreviewVersionClient contains the methods for the PreviewVersion group. +// Don't use this type directly, use NewPreviewVersionClientWithNoCredential() instead. +// +// Generated from API version 2024-06-01 +type PreviewVersionClient struct { + internal *azcore.Client + endpoint string +} + +// PreviewVersionClientOptions contains the optional values for creating a [PreviewVersionClient]. +type PreviewVersionClientOptions struct { + azcore.ClientOptions +} + +// NewPreviewVersionClientWithNoCredential creates a new instance of PreviewVersionClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewPreviewVersionClientWithNoCredential(endpoint string, options *PreviewVersionClientOptions) (*PreviewVersionClient, error) { + if options == nil { + options = &PreviewVersionClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{ + APIVersion: runtime.APIVersionOptions{ + Name: "api-version", + Location: runtime.APIVersionLocationQueryParam, + }, + }, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &PreviewVersionClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// GetWidget - Get widget by id (available in all versions) +// If the operation fails it returns an *azcore.ResponseError type. +// - options - PreviewVersionClientGetWidgetOptions contains the optional parameters for the PreviewVersionClient.GetWidget +// method. +func (client *PreviewVersionClient) GetWidget(ctx context.Context, id string, options *PreviewVersionClientGetWidgetOptions) (PreviewVersionClientGetWidgetResponse, error) { + var err error + const operationName = "PreviewVersionClient.GetWidget" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getWidgetCreateRequest(ctx, id, options) + if err != nil { + return PreviewVersionClientGetWidgetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PreviewVersionClientGetWidgetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNotFound) { + err = runtime.NewResponseError(httpResp) + return PreviewVersionClientGetWidgetResponse{}, err + } + resp, err := client.getWidgetHandleResponse(httpResp) + return resp, err +} + +// getWidgetCreateRequest creates the GetWidget request. +func (client *PreviewVersionClient) getWidgetCreateRequest(ctx context.Context, id string, _ *PreviewVersionClientGetWidgetOptions) (*policy.Request, error) { + urlPath := "/azure/versioning/previewVersion/widgets/{id}" + if id == "" { + return nil, errors.New("parameter id cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{id}", url.PathEscape(id)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getWidgetHandleResponse handles the GetWidget response. +func (client *PreviewVersionClient) getWidgetHandleResponse(resp *http.Response) (PreviewVersionClientGetWidgetResponse, error) { + result := PreviewVersionClientGetWidgetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Widget); err != nil { + return PreviewVersionClientGetWidgetResponse{}, err + } + return result, nil +} + +// ListWidgets - List widgets with optional color filtering +// If the operation fails it returns an *azcore.ResponseError type. +// - options - PreviewVersionClientListWidgetsOptions contains the optional parameters for the PreviewVersionClient.ListWidgets +// method. +func (client *PreviewVersionClient) ListWidgets(ctx context.Context, options *PreviewVersionClientListWidgetsOptions) (PreviewVersionClientListWidgetsResponse, error) { + var err error + const operationName = "PreviewVersionClient.ListWidgets" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listWidgetsCreateRequest(ctx, options) + if err != nil { + return PreviewVersionClientListWidgetsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PreviewVersionClientListWidgetsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PreviewVersionClientListWidgetsResponse{}, err + } + resp, err := client.listWidgetsHandleResponse(httpResp) + return resp, err +} + +// listWidgetsCreateRequest creates the ListWidgets request. +func (client *PreviewVersionClient) listWidgetsCreateRequest(ctx context.Context, options *PreviewVersionClientListWidgetsOptions) (*policy.Request, error) { + urlPath := "/azure/versioning/previewVersion/widgets" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601) + if options != nil && options.Name != nil { + reqQP.Set("name", *options.Name) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listWidgetsHandleResponse handles the ListWidgets response. +func (client *PreviewVersionClient) listWidgetsHandleResponse(resp *http.Response) (PreviewVersionClientListWidgetsResponse, error) { + result := PreviewVersionClientListWidgetsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListWidgetsResponse); err != nil { + return PreviewVersionClientListWidgetsResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_responses.go b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_responses.go new file mode 100644 index 000000000000..248d0f0fa77b --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_responses.go @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package previewversiongroupspecificversion + +// PreviewVersionClientGetWidgetResponse contains the response from method PreviewVersionClient.GetWidget. +type PreviewVersionClientGetWidgetResponse struct { + // A simple model for testing. + Widget +} + +// PreviewVersionClientListWidgetsResponse contains the response from method PreviewVersionClient.ListWidgets. +type PreviewVersionClientListWidgetsResponse struct { + ListWidgetsResponse +} diff --git a/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_version.go b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_version.go new file mode 100644 index 000000000000..3a312e07c260 --- /dev/null +++ b/test/azure-http-specs/azure/versioning/previewversiongroupspecificversion/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package previewversiongroupspecificversion + +const ( + moduleName = "previewversiongroupspecificversion" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/client/clientnamespacegroup/LICENSE.txt b/test/azure-http-specs/client/clientnamespacegroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/client/clientnamespacegroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/client/clientnamespacegroup/clientnamespacefirst_client_test.go b/test/azure-http-specs/client/clientnamespacegroup/clientnamespacefirst_client_test.go new file mode 100644 index 000000000000..08eca8e9e7e3 --- /dev/null +++ b/test/azure-http-specs/client/clientnamespacegroup/clientnamespacefirst_client_test.go @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package clientnamespacegroup_test + +import ( + "clientnamespacegroup" + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestClientNamespaceFirstClient_GetFirst(t *testing.T) { + client, err := clientnamespacegroup.NewClientNamespaceFirstClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + require.NotNil(t, client) + resp, err := client.GetFirst(context.Background(), nil) // Use appropriate context and options + require.NoError(t, err) + require.NotNil(t, resp.Name) + require.Equal(t, "first", *resp.Name) +} diff --git a/test/azure-http-specs/client/clientnamespacegroup/clientnamespacesecond_client_test.go b/test/azure-http-specs/client/clientnamespacegroup/clientnamespacesecond_client_test.go new file mode 100644 index 000000000000..d44b9187b33a --- /dev/null +++ b/test/azure-http-specs/client/clientnamespacegroup/clientnamespacesecond_client_test.go @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package clientnamespacegroup_test + +import ( + "clientnamespacegroup" + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestClientNamespaceSecondClient_GetSecond(t *testing.T) { + client, err := clientnamespacegroup.NewClientNamespaceSecondClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.GetSecond(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Type) + require.Equal(t, clientnamespacegroup.SecondClientEnumTypeSecond, *resp.Type) +} diff --git a/test/azure-http-specs/client/clientnamespacegroup/fake/zz_clientnamespacefirst_server.go b/test/azure-http-specs/client/clientnamespacegroup/fake/zz_clientnamespacefirst_server.go new file mode 100644 index 000000000000..7afc4d294026 --- /dev/null +++ b/test/azure-http-specs/client/clientnamespacegroup/fake/zz_clientnamespacefirst_server.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "clientnamespacegroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// ClientNamespaceFirstServer is a fake server for instances of the clientnamespacegroup.ClientNamespaceFirstClient type. +type ClientNamespaceFirstServer struct { + // GetFirst is the fake for method ClientNamespaceFirstClient.GetFirst + // HTTP status codes to indicate success: http.StatusOK + GetFirst func(ctx context.Context, options *clientnamespacegroup.ClientNamespaceFirstClientGetFirstOptions) (resp azfake.Responder[clientnamespacegroup.ClientNamespaceFirstClientGetFirstResponse], errResp azfake.ErrorResponder) +} + +// NewClientNamespaceFirstServerTransport creates a new instance of ClientNamespaceFirstServerTransport with the provided implementation. +// The returned ClientNamespaceFirstServerTransport instance is connected to an instance of clientnamespacegroup.ClientNamespaceFirstClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewClientNamespaceFirstServerTransport(srv *ClientNamespaceFirstServer) *ClientNamespaceFirstServerTransport { + return &ClientNamespaceFirstServerTransport{srv: srv} +} + +// ClientNamespaceFirstServerTransport connects instances of clientnamespacegroup.ClientNamespaceFirstClient to instances of ClientNamespaceFirstServer. +// Don't use this type directly, use NewClientNamespaceFirstServerTransport instead. +type ClientNamespaceFirstServerTransport struct { + srv *ClientNamespaceFirstServer +} + +// Do implements the policy.Transporter interface for ClientNamespaceFirstServerTransport. +func (c *ClientNamespaceFirstServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *ClientNamespaceFirstServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if clientNamespaceFirstServerTransportInterceptor != nil { + res.resp, res.err, intercepted = clientNamespaceFirstServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ClientNamespaceFirstClient.GetFirst": + res.resp, res.err = c.dispatchGetFirst(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *ClientNamespaceFirstServerTransport) dispatchGetFirst(req *http.Request) (*http.Response, error) { + if c.srv.GetFirst == nil { + return nil, &nonRetriableError{errors.New("fake for method GetFirst not implemented")} + } + respr, errRespr := c.srv.GetFirst(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).FirstClientResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ClientNamespaceFirstServerTransport +var clientNamespaceFirstServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/client/clientnamespacegroup/fake/zz_clientnamespacesecond_server.go b/test/azure-http-specs/client/clientnamespacegroup/fake/zz_clientnamespacesecond_server.go new file mode 100644 index 000000000000..2726a666110f --- /dev/null +++ b/test/azure-http-specs/client/clientnamespacegroup/fake/zz_clientnamespacesecond_server.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "clientnamespacegroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// ClientNamespaceSecondServer is a fake server for instances of the clientnamespacegroup.ClientNamespaceSecondClient type. +type ClientNamespaceSecondServer struct { + // GetSecond is the fake for method ClientNamespaceSecondClient.GetSecond + // HTTP status codes to indicate success: http.StatusOK + GetSecond func(ctx context.Context, options *clientnamespacegroup.ClientNamespaceSecondClientGetSecondOptions) (resp azfake.Responder[clientnamespacegroup.ClientNamespaceSecondClientGetSecondResponse], errResp azfake.ErrorResponder) +} + +// NewClientNamespaceSecondServerTransport creates a new instance of ClientNamespaceSecondServerTransport with the provided implementation. +// The returned ClientNamespaceSecondServerTransport instance is connected to an instance of clientnamespacegroup.ClientNamespaceSecondClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewClientNamespaceSecondServerTransport(srv *ClientNamespaceSecondServer) *ClientNamespaceSecondServerTransport { + return &ClientNamespaceSecondServerTransport{srv: srv} +} + +// ClientNamespaceSecondServerTransport connects instances of clientnamespacegroup.ClientNamespaceSecondClient to instances of ClientNamespaceSecondServer. +// Don't use this type directly, use NewClientNamespaceSecondServerTransport instead. +type ClientNamespaceSecondServerTransport struct { + srv *ClientNamespaceSecondServer +} + +// Do implements the policy.Transporter interface for ClientNamespaceSecondServerTransport. +func (c *ClientNamespaceSecondServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *ClientNamespaceSecondServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if clientNamespaceSecondServerTransportInterceptor != nil { + res.resp, res.err, intercepted = clientNamespaceSecondServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ClientNamespaceSecondClient.GetSecond": + res.resp, res.err = c.dispatchGetSecond(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *ClientNamespaceSecondServerTransport) dispatchGetSecond(req *http.Request) (*http.Response, error) { + if c.srv.GetSecond == nil { + return nil, &nonRetriableError{errors.New("fake for method GetSecond not implemented")} + } + respr, errRespr := c.srv.GetSecond(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).SecondClientResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ClientNamespaceSecondServerTransport +var clientNamespaceSecondServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/client/clientnamespacegroup/fake/zz_internal.go b/test/azure-http-specs/client/clientnamespacegroup/fake/zz_internal.go new file mode 100644 index 000000000000..705f81eacafe --- /dev/null +++ b/test/azure-http-specs/client/clientnamespacegroup/fake/zz_internal.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import "net/http" + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} diff --git a/test/azure-http-specs/client/clientnamespacegroup/go.mod b/test/azure-http-specs/client/clientnamespacegroup/go.mod new file mode 100644 index 000000000000..8655adb7d2be --- /dev/null +++ b/test/azure-http-specs/client/clientnamespacegroup/go.mod @@ -0,0 +1,17 @@ +module clientnamespacegroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/client/clientnamespacegroup/go.sum b/test/azure-http-specs/client/clientnamespacegroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/client/clientnamespacegroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/client/clientnamespacegroup/testdata/_metadata.json b/test/azure-http-specs/client/clientnamespacegroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/azure-http-specs/client/clientnamespacegroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/client/clientnamespacegroup/zz_clientnamespacefirst_client.go b/test/azure-http-specs/client/clientnamespacegroup/zz_clientnamespacefirst_client.go new file mode 100644 index 000000000000..fc998d5a454d --- /dev/null +++ b/test/azure-http-specs/client/clientnamespacegroup/zz_clientnamespacefirst_client.go @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientnamespacegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ClientNamespaceFirstClient contains the methods for the ClientNamespaceFirst group. +// Don't use this type directly, use NewClientNamespaceFirstClientWithNoCredential() instead. +type ClientNamespaceFirstClient struct { + internal *azcore.Client + endpoint string +} + +// ClientNamespaceFirstClientOptions contains the optional values for creating a [ClientNamespaceFirstClient]. +type ClientNamespaceFirstClientOptions struct { + azcore.ClientOptions +} + +// NewClientNamespaceFirstClientWithNoCredential creates a new instance of ClientNamespaceFirstClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewClientNamespaceFirstClientWithNoCredential(endpoint string, options *ClientNamespaceFirstClientOptions) (*ClientNamespaceFirstClient, error) { + if options == nil { + options = &ClientNamespaceFirstClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &ClientNamespaceFirstClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// GetFirst - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientNamespaceFirstClientGetFirstOptions contains the optional parameters for the ClientNamespaceFirstClient.GetFirst +// method. +func (client *ClientNamespaceFirstClient) GetFirst(ctx context.Context, options *ClientNamespaceFirstClientGetFirstOptions) (ClientNamespaceFirstClientGetFirstResponse, error) { + var err error + const operationName = "ClientNamespaceFirstClient.GetFirst" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getFirstCreateRequest(ctx, options) + if err != nil { + return ClientNamespaceFirstClientGetFirstResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientNamespaceFirstClientGetFirstResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientNamespaceFirstClientGetFirstResponse{}, err + } + resp, err := client.getFirstHandleResponse(httpResp) + return resp, err +} + +// getFirstCreateRequest creates the GetFirst request. +func (client *ClientNamespaceFirstClient) getFirstCreateRequest(ctx context.Context, _ *ClientNamespaceFirstClientGetFirstOptions) (*policy.Request, error) { + urlPath := "/client/client-namespace/first" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getFirstHandleResponse handles the GetFirst response. +func (client *ClientNamespaceFirstClient) getFirstHandleResponse(resp *http.Response) (ClientNamespaceFirstClientGetFirstResponse, error) { + result := ClientNamespaceFirstClientGetFirstResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FirstClientResult); err != nil { + return ClientNamespaceFirstClientGetFirstResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/client/clientnamespacegroup/zz_clientnamespacesecond_client.go b/test/azure-http-specs/client/clientnamespacegroup/zz_clientnamespacesecond_client.go new file mode 100644 index 000000000000..623164bf5761 --- /dev/null +++ b/test/azure-http-specs/client/clientnamespacegroup/zz_clientnamespacesecond_client.go @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientnamespacegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ClientNamespaceSecondClient contains the methods for the ClientNamespaceSecond group. +// Don't use this type directly, use NewClientNamespaceSecondClientWithNoCredential() instead. +type ClientNamespaceSecondClient struct { + internal *azcore.Client + endpoint string +} + +// ClientNamespaceSecondClientOptions contains the optional values for creating a [ClientNamespaceSecondClient]. +type ClientNamespaceSecondClientOptions struct { + azcore.ClientOptions +} + +// NewClientNamespaceSecondClientWithNoCredential creates a new instance of ClientNamespaceSecondClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewClientNamespaceSecondClientWithNoCredential(endpoint string, options *ClientNamespaceSecondClientOptions) (*ClientNamespaceSecondClient, error) { + if options == nil { + options = &ClientNamespaceSecondClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &ClientNamespaceSecondClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// GetSecond - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientNamespaceSecondClientGetSecondOptions contains the optional parameters for the ClientNamespaceSecondClient.GetSecond +// method. +func (client *ClientNamespaceSecondClient) GetSecond(ctx context.Context, options *ClientNamespaceSecondClientGetSecondOptions) (ClientNamespaceSecondClientGetSecondResponse, error) { + var err error + const operationName = "ClientNamespaceSecondClient.GetSecond" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getSecondCreateRequest(ctx, options) + if err != nil { + return ClientNamespaceSecondClientGetSecondResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientNamespaceSecondClientGetSecondResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientNamespaceSecondClientGetSecondResponse{}, err + } + resp, err := client.getSecondHandleResponse(httpResp) + return resp, err +} + +// getSecondCreateRequest creates the GetSecond request. +func (client *ClientNamespaceSecondClient) getSecondCreateRequest(ctx context.Context, _ *ClientNamespaceSecondClientGetSecondOptions) (*policy.Request, error) { + urlPath := "/client/client-namespace/second" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getSecondHandleResponse handles the GetSecond response. +func (client *ClientNamespaceSecondClient) getSecondHandleResponse(resp *http.Response) (ClientNamespaceSecondClientGetSecondResponse, error) { + result := ClientNamespaceSecondClientGetSecondResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SecondClientResult); err != nil { + return ClientNamespaceSecondClientGetSecondResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/client/clientnamespacegroup/zz_constants.go b/test/azure-http-specs/client/clientnamespacegroup/zz_constants.go new file mode 100644 index 000000000000..3def3f68064e --- /dev/null +++ b/test/azure-http-specs/client/clientnamespacegroup/zz_constants.go @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientnamespacegroup + +type SecondClientEnumType string + +const ( + SecondClientEnumTypeSecond SecondClientEnumType = "second" +) + +// PossibleSecondClientEnumTypeValues returns the possible values for the SecondClientEnumType const type. +func PossibleSecondClientEnumTypeValues() []SecondClientEnumType { + return []SecondClientEnumType{ + SecondClientEnumTypeSecond, + } +} diff --git a/test/azure-http-specs/client/clientnamespacegroup/zz_models.go b/test/azure-http-specs/client/clientnamespacegroup/zz_models.go new file mode 100644 index 000000000000..899746205ab6 --- /dev/null +++ b/test/azure-http-specs/client/clientnamespacegroup/zz_models.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientnamespacegroup + +type FirstClientResult struct { + // REQUIRED + Name *string +} + +type SecondClientResult struct { + // REQUIRED + Type *SecondClientEnumType +} diff --git a/test/azure-http-specs/client/clientnamespacegroup/zz_models_serde.go b/test/azure-http-specs/client/clientnamespacegroup/zz_models_serde.go new file mode 100644 index 000000000000..7a8dd6d71c9b --- /dev/null +++ b/test/azure-http-specs/client/clientnamespacegroup/zz_models_serde.go @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientnamespacegroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type FirstClientResult. +func (f FirstClientResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", f.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirstClientResult. +func (f *FirstClientResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &f.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SecondClientResult. +func (s SecondClientResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecondClientResult. +func (s *SecondClientResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/azure-http-specs/client/clientnamespacegroup/zz_options.go b/test/azure-http-specs/client/clientnamespacegroup/zz_options.go new file mode 100644 index 000000000000..660a4a5b14d8 --- /dev/null +++ b/test/azure-http-specs/client/clientnamespacegroup/zz_options.go @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientnamespacegroup + +// ClientNamespaceFirstClientGetFirstOptions contains the optional parameters for the ClientNamespaceFirstClient.GetFirst +// method. +type ClientNamespaceFirstClientGetFirstOptions struct { + // placeholder for future optional parameters +} + +// ClientNamespaceSecondClientGetSecondOptions contains the optional parameters for the ClientNamespaceSecondClient.GetSecond +// method. +type ClientNamespaceSecondClientGetSecondOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/client/clientnamespacegroup/zz_responses.go b/test/azure-http-specs/client/clientnamespacegroup/zz_responses.go new file mode 100644 index 000000000000..39251cf0045e --- /dev/null +++ b/test/azure-http-specs/client/clientnamespacegroup/zz_responses.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package clientnamespacegroup + +// ClientNamespaceFirstClientGetFirstResponse contains the response from method ClientNamespaceFirstClient.GetFirst. +type ClientNamespaceFirstClientGetFirstResponse struct { + FirstClientResult +} + +// ClientNamespaceSecondClientGetSecondResponse contains the response from method ClientNamespaceSecondClient.GetSecond. +type ClientNamespaceSecondClientGetSecondResponse struct { + SecondClientResult +} diff --git a/test/azure-http-specs/client/clientnamespacegroup/zz_version.go b/test/azure-http-specs/client/clientnamespacegroup/zz_version.go new file mode 100644 index 000000000000..d4865672cab5 --- /dev/null +++ b/test/azure-http-specs/client/clientnamespacegroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package clientnamespacegroup + +const ( + moduleName = "clientnamespacegroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/client/naming/enumconflictgroup/LICENSE.txt b/test/azure-http-specs/client/naming/enumconflictgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/client/naming/enumconflictgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/client/naming/enumconflictgroup/enumconflictfirstoperations_client_test.go b/test/azure-http-specs/client/naming/enumconflictgroup/enumconflictfirstoperations_client_test.go new file mode 100644 index 000000000000..2c09cdf06a52 --- /dev/null +++ b/test/azure-http-specs/client/naming/enumconflictgroup/enumconflictfirstoperations_client_test.go @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package enumconflictgroup_test + +import ( + "context" + "testing" + + "enumconflictgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestEnumConflictFirstOperationsClient_First(t *testing.T) { + enumClient, err := enumconflictgroup.NewEnumConflictClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + + body := enumconflictgroup.FirstModel{ + Status: to.Ptr(enumconflictgroup.StatusActive), + Name: to.Ptr("test"), + } + + resp, err := enumClient.NewEnumConflictFirstOperationsClient().First(context.Background(), body, nil) + require.NoError(t, err) + require.Equal(t, body.Status, resp.Status) + require.Equal(t, body.Name, resp.Name) +} diff --git a/test/azure-http-specs/client/naming/enumconflictgroup/enumconflictsecondoperations_client_test.go b/test/azure-http-specs/client/naming/enumconflictgroup/enumconflictsecondoperations_client_test.go new file mode 100644 index 000000000000..9f284fce34ff --- /dev/null +++ b/test/azure-http-specs/client/naming/enumconflictgroup/enumconflictsecondoperations_client_test.go @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package enumconflictgroup_test + +import ( + "context" + "testing" + + "enumconflictgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestEnumConflictSecondOperationsClient_Second(t *testing.T) { + enumClient, err := enumconflictgroup.NewEnumConflictClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + + body := enumconflictgroup.SecondModel{ + Status: to.Ptr(enumconflictgroup.SecondStatusRunning), + Description: to.Ptr("test description"), + } + + resp, err := enumClient.NewEnumConflictSecondOperationsClient().Second(context.Background(), body, nil) + require.NoError(t, err) + require.Equal(t, body.Status, resp.Status) + require.Equal(t, body.Description, resp.Description) +} diff --git a/test/azure-http-specs/client/naming/enumconflictgroup/fake/zz_enumconflict_server.go b/test/azure-http-specs/client/naming/enumconflictgroup/fake/zz_enumconflict_server.go new file mode 100644 index 000000000000..1cfdc62e1557 --- /dev/null +++ b/test/azure-http-specs/client/naming/enumconflictgroup/fake/zz_enumconflict_server.go @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// EnumConflictServer is a fake server for instances of the enumconflictgroup.EnumConflictClient type. +type EnumConflictServer struct { + // EnumConflictFirstOperationsServer contains the fakes for client EnumConflictFirstOperationsClient + EnumConflictFirstOperationsServer EnumConflictFirstOperationsServer + + // EnumConflictSecondOperationsServer contains the fakes for client EnumConflictSecondOperationsClient + EnumConflictSecondOperationsServer EnumConflictSecondOperationsServer +} + +// NewEnumConflictServerTransport creates a new instance of EnumConflictServerTransport with the provided implementation. +// The returned EnumConflictServerTransport instance is connected to an instance of enumconflictgroup.EnumConflictClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewEnumConflictServerTransport(srv *EnumConflictServer) *EnumConflictServerTransport { + return &EnumConflictServerTransport{srv: srv} +} + +// EnumConflictServerTransport connects instances of enumconflictgroup.EnumConflictClient to instances of EnumConflictServer. +// Don't use this type directly, use NewEnumConflictServerTransport instead. +type EnumConflictServerTransport struct { + srv *EnumConflictServer + trMu sync.Mutex + trEnumConflictFirstOperationsServer *EnumConflictFirstOperationsServerTransport + trEnumConflictSecondOperationsServer *EnumConflictSecondOperationsServerTransport +} + +// Do implements the policy.Transporter interface for EnumConflictServerTransport. +func (e *EnumConflictServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return e.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (e *EnumConflictServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "EnumConflictFirstOperationsClient": + initServer(&e.trMu, &e.trEnumConflictFirstOperationsServer, func() *EnumConflictFirstOperationsServerTransport { + return NewEnumConflictFirstOperationsServerTransport(&e.srv.EnumConflictFirstOperationsServer) + }) + resp, err = e.trEnumConflictFirstOperationsServer.Do(req) + case "EnumConflictSecondOperationsClient": + initServer(&e.trMu, &e.trEnumConflictSecondOperationsServer, func() *EnumConflictSecondOperationsServerTransport { + return NewEnumConflictSecondOperationsServerTransport(&e.srv.EnumConflictSecondOperationsServer) + }) + resp, err = e.trEnumConflictSecondOperationsServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to EnumConflictServerTransport +var enumConflictServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/client/naming/enumconflictgroup/fake/zz_enumconflictfirstoperations_server.go b/test/azure-http-specs/client/naming/enumconflictgroup/fake/zz_enumconflictfirstoperations_server.go new file mode 100644 index 000000000000..0cdb64e72738 --- /dev/null +++ b/test/azure-http-specs/client/naming/enumconflictgroup/fake/zz_enumconflictfirstoperations_server.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "enumconflictgroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// EnumConflictFirstOperationsServer is a fake server for instances of the enumconflictgroup.EnumConflictFirstOperationsClient type. +type EnumConflictFirstOperationsServer struct { + // First is the fake for method EnumConflictFirstOperationsClient.First + // HTTP status codes to indicate success: http.StatusOK + First func(ctx context.Context, body enumconflictgroup.FirstModel, options *enumconflictgroup.EnumConflictFirstOperationsClientFirstOptions) (resp azfake.Responder[enumconflictgroup.EnumConflictFirstOperationsClientFirstResponse], errResp azfake.ErrorResponder) +} + +// NewEnumConflictFirstOperationsServerTransport creates a new instance of EnumConflictFirstOperationsServerTransport with the provided implementation. +// The returned EnumConflictFirstOperationsServerTransport instance is connected to an instance of enumconflictgroup.EnumConflictFirstOperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewEnumConflictFirstOperationsServerTransport(srv *EnumConflictFirstOperationsServer) *EnumConflictFirstOperationsServerTransport { + return &EnumConflictFirstOperationsServerTransport{srv: srv} +} + +// EnumConflictFirstOperationsServerTransport connects instances of enumconflictgroup.EnumConflictFirstOperationsClient to instances of EnumConflictFirstOperationsServer. +// Don't use this type directly, use NewEnumConflictFirstOperationsServerTransport instead. +type EnumConflictFirstOperationsServerTransport struct { + srv *EnumConflictFirstOperationsServer +} + +// Do implements the policy.Transporter interface for EnumConflictFirstOperationsServerTransport. +func (e *EnumConflictFirstOperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return e.dispatchToMethodFake(req, method) +} + +func (e *EnumConflictFirstOperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if enumConflictFirstOperationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = enumConflictFirstOperationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "EnumConflictFirstOperationsClient.First": + res.resp, res.err = e.dispatchFirst(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (e *EnumConflictFirstOperationsServerTransport) dispatchFirst(req *http.Request) (*http.Response, error) { + if e.srv.First == nil { + return nil, &nonRetriableError{errors.New("fake for method First not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[enumconflictgroup.FirstModel](req) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.First(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).FirstModel, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to EnumConflictFirstOperationsServerTransport +var enumConflictFirstOperationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/client/naming/enumconflictgroup/fake/zz_enumconflictsecondoperations_server.go b/test/azure-http-specs/client/naming/enumconflictgroup/fake/zz_enumconflictsecondoperations_server.go new file mode 100644 index 000000000000..a736c9f04594 --- /dev/null +++ b/test/azure-http-specs/client/naming/enumconflictgroup/fake/zz_enumconflictsecondoperations_server.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "enumconflictgroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// EnumConflictSecondOperationsServer is a fake server for instances of the enumconflictgroup.EnumConflictSecondOperationsClient type. +type EnumConflictSecondOperationsServer struct { + // Second is the fake for method EnumConflictSecondOperationsClient.Second + // HTTP status codes to indicate success: http.StatusOK + Second func(ctx context.Context, body enumconflictgroup.SecondModel, options *enumconflictgroup.EnumConflictSecondOperationsClientSecondOptions) (resp azfake.Responder[enumconflictgroup.EnumConflictSecondOperationsClientSecondResponse], errResp azfake.ErrorResponder) +} + +// NewEnumConflictSecondOperationsServerTransport creates a new instance of EnumConflictSecondOperationsServerTransport with the provided implementation. +// The returned EnumConflictSecondOperationsServerTransport instance is connected to an instance of enumconflictgroup.EnumConflictSecondOperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewEnumConflictSecondOperationsServerTransport(srv *EnumConflictSecondOperationsServer) *EnumConflictSecondOperationsServerTransport { + return &EnumConflictSecondOperationsServerTransport{srv: srv} +} + +// EnumConflictSecondOperationsServerTransport connects instances of enumconflictgroup.EnumConflictSecondOperationsClient to instances of EnumConflictSecondOperationsServer. +// Don't use this type directly, use NewEnumConflictSecondOperationsServerTransport instead. +type EnumConflictSecondOperationsServerTransport struct { + srv *EnumConflictSecondOperationsServer +} + +// Do implements the policy.Transporter interface for EnumConflictSecondOperationsServerTransport. +func (e *EnumConflictSecondOperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return e.dispatchToMethodFake(req, method) +} + +func (e *EnumConflictSecondOperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if enumConflictSecondOperationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = enumConflictSecondOperationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "EnumConflictSecondOperationsClient.Second": + res.resp, res.err = e.dispatchSecond(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (e *EnumConflictSecondOperationsServerTransport) dispatchSecond(req *http.Request) (*http.Response, error) { + if e.srv.Second == nil { + return nil, &nonRetriableError{errors.New("fake for method Second not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[enumconflictgroup.SecondModel](req) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.Second(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).SecondModel, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to EnumConflictSecondOperationsServerTransport +var enumConflictSecondOperationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/client/naming/enumconflictgroup/fake/zz_internal.go b/test/azure-http-specs/client/naming/enumconflictgroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/azure-http-specs/client/naming/enumconflictgroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/azure-http-specs/client/naming/enumconflictgroup/go.mod b/test/azure-http-specs/client/naming/enumconflictgroup/go.mod new file mode 100644 index 000000000000..c6bda4de167b --- /dev/null +++ b/test/azure-http-specs/client/naming/enumconflictgroup/go.mod @@ -0,0 +1,17 @@ +module enumconflictgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/client/naming/enumconflictgroup/go.sum b/test/azure-http-specs/client/naming/enumconflictgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/client/naming/enumconflictgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/client/naming/enumconflictgroup/testdata/_metadata.json b/test/azure-http-specs/client/naming/enumconflictgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/azure-http-specs/client/naming/enumconflictgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/client/naming/enumconflictgroup/zz_constants.go b/test/azure-http-specs/client/naming/enumconflictgroup/zz_constants.go new file mode 100644 index 000000000000..264751f95e31 --- /dev/null +++ b/test/azure-http-specs/client/naming/enumconflictgroup/zz_constants.go @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package enumconflictgroup + +// SecondStatus - Status enum in second namespace +type SecondStatus string + +const ( + // SecondStatusRunning - Running status + SecondStatusRunning SecondStatus = "running" + // SecondStatusStopped - Stopped status + SecondStatusStopped SecondStatus = "stopped" +) + +// PossibleSecondStatusValues returns the possible values for the SecondStatus const type. +func PossibleSecondStatusValues() []SecondStatus { + return []SecondStatus{ + SecondStatusRunning, + SecondStatusStopped, + } +} + +// Status - Status enum in first namespace +type Status string + +const ( + // StatusActive - Active status + StatusActive Status = "active" + // StatusInactive - Inactive status + StatusInactive Status = "inactive" +) + +// PossibleStatusValues returns the possible values for the Status const type. +func PossibleStatusValues() []Status { + return []Status{ + StatusActive, + StatusInactive, + } +} diff --git a/test/azure-http-specs/client/naming/enumconflictgroup/zz_enumconflict_client.go b/test/azure-http-specs/client/naming/enumconflictgroup/zz_enumconflict_client.go new file mode 100644 index 000000000000..e6bf45ee518e --- /dev/null +++ b/test/azure-http-specs/client/naming/enumconflictgroup/zz_enumconflict_client.go @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package enumconflictgroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// EnumConflictClient - Test for enum with same name in different namespace. +// Don't use this type directly, use NewEnumConflictClientWithNoCredential() instead. +type EnumConflictClient struct { + internal *azcore.Client + endpoint string +} + +// EnumConflictClientOptions contains the optional values for creating a [EnumConflictClient]. +type EnumConflictClientOptions struct { + azcore.ClientOptions +} + +// NewEnumConflictClientWithNoCredential creates a new instance of EnumConflictClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewEnumConflictClientWithNoCredential(endpoint string, options *EnumConflictClientOptions) (*EnumConflictClient, error) { + if options == nil { + options = &EnumConflictClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &EnumConflictClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewEnumConflictFirstOperationsClient creates a new instance of [EnumConflictFirstOperationsClient]. +func (client *EnumConflictClient) NewEnumConflictFirstOperationsClient() *EnumConflictFirstOperationsClient { + return &EnumConflictFirstOperationsClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewEnumConflictSecondOperationsClient creates a new instance of [EnumConflictSecondOperationsClient]. +func (client *EnumConflictClient) NewEnumConflictSecondOperationsClient() *EnumConflictSecondOperationsClient { + return &EnumConflictSecondOperationsClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/azure-http-specs/client/naming/enumconflictgroup/zz_enumconflictfirstoperations_client.go b/test/azure-http-specs/client/naming/enumconflictgroup/zz_enumconflictfirstoperations_client.go new file mode 100644 index 000000000000..6544e1782a2b --- /dev/null +++ b/test/azure-http-specs/client/naming/enumconflictgroup/zz_enumconflictfirstoperations_client.go @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package enumconflictgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// EnumConflictFirstOperationsClient contains the methods for the EnumConflictFirstOperations group. +// Don't use this type directly, use [EnumConflictClient.NewEnumConflictFirstOperationsClient] instead. +type EnumConflictFirstOperationsClient struct { + internal *azcore.Client + endpoint string +} + +// First - Operation using first namespace Status enum +// If the operation fails it returns an *azcore.ResponseError type. +// - options - EnumConflictFirstOperationsClientFirstOptions contains the optional parameters for the EnumConflictFirstOperationsClient.First +// method. +func (client *EnumConflictFirstOperationsClient) First(ctx context.Context, body FirstModel, options *EnumConflictFirstOperationsClientFirstOptions) (EnumConflictFirstOperationsClientFirstResponse, error) { + var err error + const operationName = "EnumConflictFirstOperationsClient.First" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.firstCreateRequest(ctx, body, options) + if err != nil { + return EnumConflictFirstOperationsClientFirstResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EnumConflictFirstOperationsClientFirstResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return EnumConflictFirstOperationsClientFirstResponse{}, err + } + resp, err := client.firstHandleResponse(httpResp) + return resp, err +} + +// firstCreateRequest creates the First request. +func (client *EnumConflictFirstOperationsClient) firstCreateRequest(ctx context.Context, body FirstModel, _ *EnumConflictFirstOperationsClientFirstOptions) (*policy.Request, error) { + urlPath := "/client/naming/enum-conflict/first" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// firstHandleResponse handles the First response. +func (client *EnumConflictFirstOperationsClient) firstHandleResponse(resp *http.Response) (EnumConflictFirstOperationsClientFirstResponse, error) { + result := EnumConflictFirstOperationsClientFirstResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FirstModel); err != nil { + return EnumConflictFirstOperationsClientFirstResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/client/naming/enumconflictgroup/zz_enumconflictsecondoperations_client.go b/test/azure-http-specs/client/naming/enumconflictgroup/zz_enumconflictsecondoperations_client.go new file mode 100644 index 000000000000..480d9c51b9ac --- /dev/null +++ b/test/azure-http-specs/client/naming/enumconflictgroup/zz_enumconflictsecondoperations_client.go @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package enumconflictgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// EnumConflictSecondOperationsClient contains the methods for the EnumConflictSecondOperations group. +// Don't use this type directly, use [EnumConflictClient.NewEnumConflictSecondOperationsClient] instead. +type EnumConflictSecondOperationsClient struct { + internal *azcore.Client + endpoint string +} + +// Second - Operation using second namespace Status enum +// If the operation fails it returns an *azcore.ResponseError type. +// - options - EnumConflictSecondOperationsClientSecondOptions contains the optional parameters for the EnumConflictSecondOperationsClient.Second +// method. +func (client *EnumConflictSecondOperationsClient) Second(ctx context.Context, body SecondModel, options *EnumConflictSecondOperationsClientSecondOptions) (EnumConflictSecondOperationsClientSecondResponse, error) { + var err error + const operationName = "EnumConflictSecondOperationsClient.Second" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.secondCreateRequest(ctx, body, options) + if err != nil { + return EnumConflictSecondOperationsClientSecondResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EnumConflictSecondOperationsClientSecondResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return EnumConflictSecondOperationsClientSecondResponse{}, err + } + resp, err := client.secondHandleResponse(httpResp) + return resp, err +} + +// secondCreateRequest creates the Second request. +func (client *EnumConflictSecondOperationsClient) secondCreateRequest(ctx context.Context, body SecondModel, _ *EnumConflictSecondOperationsClientSecondOptions) (*policy.Request, error) { + urlPath := "/client/naming/enum-conflict/second" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// secondHandleResponse handles the Second response. +func (client *EnumConflictSecondOperationsClient) secondHandleResponse(resp *http.Response) (EnumConflictSecondOperationsClientSecondResponse, error) { + result := EnumConflictSecondOperationsClientSecondResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SecondModel); err != nil { + return EnumConflictSecondOperationsClientSecondResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/client/naming/enumconflictgroup/zz_models.go b/test/azure-http-specs/client/naming/enumconflictgroup/zz_models.go new file mode 100644 index 000000000000..4a2f437989cf --- /dev/null +++ b/test/azure-http-specs/client/naming/enumconflictgroup/zz_models.go @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package enumconflictgroup + +type FirstModel struct { + // REQUIRED; Name of the item + Name *string + + // REQUIRED; Status from first namespace + Status *Status +} + +type SecondModel struct { + // REQUIRED; Description of the item + Description *string + + // REQUIRED; Status from second namespace + Status *SecondStatus +} diff --git a/test/azure-http-specs/client/naming/enumconflictgroup/zz_models_serde.go b/test/azure-http-specs/client/naming/enumconflictgroup/zz_models_serde.go new file mode 100644 index 000000000000..4454eee7cf3f --- /dev/null +++ b/test/azure-http-specs/client/naming/enumconflictgroup/zz_models_serde.go @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package enumconflictgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type FirstModel. +func (f FirstModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", f.Name) + populate(objectMap, "status", f.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirstModel. +func (f *FirstModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &f.Name) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &f.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SecondModel. +func (s SecondModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", s.Description) + populate(objectMap, "status", s.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecondModel. +func (s *SecondModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &s.Description) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &s.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/azure-http-specs/client/naming/enumconflictgroup/zz_options.go b/test/azure-http-specs/client/naming/enumconflictgroup/zz_options.go new file mode 100644 index 000000000000..3bb39e68a681 --- /dev/null +++ b/test/azure-http-specs/client/naming/enumconflictgroup/zz_options.go @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package enumconflictgroup + +// EnumConflictFirstOperationsClientFirstOptions contains the optional parameters for the EnumConflictFirstOperationsClient.First +// method. +type EnumConflictFirstOperationsClientFirstOptions struct { + // placeholder for future optional parameters +} + +// EnumConflictSecondOperationsClientSecondOptions contains the optional parameters for the EnumConflictSecondOperationsClient.Second +// method. +type EnumConflictSecondOperationsClientSecondOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/client/naming/enumconflictgroup/zz_responses.go b/test/azure-http-specs/client/naming/enumconflictgroup/zz_responses.go new file mode 100644 index 000000000000..938ae4c996d6 --- /dev/null +++ b/test/azure-http-specs/client/naming/enumconflictgroup/zz_responses.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package enumconflictgroup + +// EnumConflictFirstOperationsClientFirstResponse contains the response from method EnumConflictFirstOperationsClient.First. +type EnumConflictFirstOperationsClientFirstResponse struct { + FirstModel +} + +// EnumConflictSecondOperationsClientSecondResponse contains the response from method EnumConflictSecondOperationsClient.Second. +type EnumConflictSecondOperationsClientSecondResponse struct { + SecondModel +} diff --git a/test/azure-http-specs/client/naming/enumconflictgroup/zz_version.go b/test/azure-http-specs/client/naming/enumconflictgroup/zz_version.go new file mode 100644 index 000000000000..ba6f2146c790 --- /dev/null +++ b/test/azure-http-specs/client/naming/enumconflictgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package enumconflictgroup + +const ( + moduleName = "enumconflictgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/client/naminggroup/LICENSE.txt b/test/azure-http-specs/client/naminggroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/client/naminggroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/client/naminggroup/fake/zz_internal.go b/test/azure-http-specs/client/naminggroup/fake/zz_internal.go new file mode 100644 index 000000000000..df56a9f6266b --- /dev/null +++ b/test/azure-http-specs/client/naminggroup/fake/zz_internal.go @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getHeaderValue(h http.Header, k string) string { + v := h[k] + if len(v) == 0 { + return "" + } + return v[0] +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/azure-http-specs/client/naminggroup/fake/zz_naming_server.go b/test/azure-http-specs/client/naminggroup/fake/zz_naming_server.go new file mode 100644 index 000000000000..cd27b667d4c8 --- /dev/null +++ b/test/azure-http-specs/client/naminggroup/fake/zz_naming_server.go @@ -0,0 +1,181 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "naminggroup" + "net/http" + "slices" + "strings" + "sync" +) + +// NamingServer is a fake server for instances of the naminggroup.NamingClient type. +type NamingServer struct { + // NamingHeaderServer contains the fakes for client NamingHeaderClient + NamingHeaderServer NamingHeaderServer + + // NamingModelServer contains the fakes for client NamingModelClient + NamingModelServer NamingModelServer + + // NamingPropertyServer contains the fakes for client NamingPropertyClient + NamingPropertyServer NamingPropertyServer + + // NamingUnionEnumServer contains the fakes for client NamingUnionEnumClient + NamingUnionEnumServer NamingUnionEnumServer + + // ClientName is the fake for method NamingClient.ClientName + // HTTP status codes to indicate success: http.StatusNoContent + ClientName func(ctx context.Context, options *naminggroup.NamingClientClientNameOptions) (resp azfake.Responder[naminggroup.NamingClientClientNameResponse], errResp azfake.ErrorResponder) + + // Parameter is the fake for method NamingClient.Parameter + // HTTP status codes to indicate success: http.StatusNoContent + Parameter func(ctx context.Context, clientName string, options *naminggroup.NamingClientParameterOptions) (resp azfake.Responder[naminggroup.NamingClientParameterResponse], errResp azfake.ErrorResponder) +} + +// NewNamingServerTransport creates a new instance of NamingServerTransport with the provided implementation. +// The returned NamingServerTransport instance is connected to an instance of naminggroup.NamingClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewNamingServerTransport(srv *NamingServer) *NamingServerTransport { + return &NamingServerTransport{srv: srv} +} + +// NamingServerTransport connects instances of naminggroup.NamingClient to instances of NamingServer. +// Don't use this type directly, use NewNamingServerTransport instead. +type NamingServerTransport struct { + srv *NamingServer + trMu sync.Mutex + trNamingHeaderServer *NamingHeaderServerTransport + trNamingModelServer *NamingModelServerTransport + trNamingPropertyServer *NamingPropertyServerTransport + trNamingUnionEnumServer *NamingUnionEnumServerTransport +} + +// Do implements the policy.Transporter interface for NamingServerTransport. +func (n *NamingServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + if client := method[:strings.Index(method, ".")]; client != "NamingClient" { + return n.dispatchToClientFake(req, client) + } + return n.dispatchToMethodFake(req, method) +} + +func (n *NamingServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "NamingHeaderClient": + initServer(&n.trMu, &n.trNamingHeaderServer, func() *NamingHeaderServerTransport { + return NewNamingHeaderServerTransport(&n.srv.NamingHeaderServer) + }) + resp, err = n.trNamingHeaderServer.Do(req) + case "NamingModelClient": + initServer(&n.trMu, &n.trNamingModelServer, func() *NamingModelServerTransport { + return NewNamingModelServerTransport(&n.srv.NamingModelServer) + }) + resp, err = n.trNamingModelServer.Do(req) + case "NamingPropertyClient": + initServer(&n.trMu, &n.trNamingPropertyServer, func() *NamingPropertyServerTransport { + return NewNamingPropertyServerTransport(&n.srv.NamingPropertyServer) + }) + resp, err = n.trNamingPropertyServer.Do(req) + case "NamingUnionEnumClient": + initServer(&n.trMu, &n.trNamingUnionEnumServer, func() *NamingUnionEnumServerTransport { + return NewNamingUnionEnumServerTransport(&n.srv.NamingUnionEnumServer) + }) + resp, err = n.trNamingUnionEnumServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +func (n *NamingServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if namingServerTransportInterceptor != nil { + res.resp, res.err, intercepted = namingServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "NamingClient.ClientName": + res.resp, res.err = n.dispatchClientName(req) + case "NamingClient.Parameter": + res.resp, res.err = n.dispatchParameter(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (n *NamingServerTransport) dispatchClientName(req *http.Request) (*http.Response, error) { + if n.srv.ClientName == nil { + return nil, &nonRetriableError{errors.New("fake for method ClientName not implemented")} + } + respr, errRespr := n.srv.ClientName(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NamingServerTransport) dispatchParameter(req *http.Request) (*http.Response, error) { + if n.srv.Parameter == nil { + return nil, &nonRetriableError{errors.New("fake for method Parameter not implemented")} + } + qp := req.URL.Query() + respr, errRespr := n.srv.Parameter(req.Context(), qp.Get("defaultName"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to NamingServerTransport +var namingServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/client/naminggroup/fake/zz_namingheader_server.go b/test/azure-http-specs/client/naminggroup/fake/zz_namingheader_server.go new file mode 100644 index 000000000000..6de456309f8a --- /dev/null +++ b/test/azure-http-specs/client/naminggroup/fake/zz_namingheader_server.go @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "naminggroup" + "net/http" + "slices" +) + +// NamingHeaderServer is a fake server for instances of the naminggroup.NamingHeaderClient type. +type NamingHeaderServer struct { + // Request is the fake for method NamingHeaderClient.Request + // HTTP status codes to indicate success: http.StatusNoContent + Request func(ctx context.Context, clientName string, options *naminggroup.NamingHeaderClientRequestOptions) (resp azfake.Responder[naminggroup.NamingHeaderClientRequestResponse], errResp azfake.ErrorResponder) + + // Response is the fake for method NamingHeaderClient.Response + // HTTP status codes to indicate success: http.StatusNoContent + Response func(ctx context.Context, options *naminggroup.NamingHeaderClientResponseOptions) (resp azfake.Responder[naminggroup.NamingHeaderClientResponseResponse], errResp azfake.ErrorResponder) +} + +// NewNamingHeaderServerTransport creates a new instance of NamingHeaderServerTransport with the provided implementation. +// The returned NamingHeaderServerTransport instance is connected to an instance of naminggroup.NamingHeaderClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewNamingHeaderServerTransport(srv *NamingHeaderServer) *NamingHeaderServerTransport { + return &NamingHeaderServerTransport{srv: srv} +} + +// NamingHeaderServerTransport connects instances of naminggroup.NamingHeaderClient to instances of NamingHeaderServer. +// Don't use this type directly, use NewNamingHeaderServerTransport instead. +type NamingHeaderServerTransport struct { + srv *NamingHeaderServer +} + +// Do implements the policy.Transporter interface for NamingHeaderServerTransport. +func (n *NamingHeaderServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return n.dispatchToMethodFake(req, method) +} + +func (n *NamingHeaderServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if namingHeaderServerTransportInterceptor != nil { + res.resp, res.err, intercepted = namingHeaderServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "NamingHeaderClient.Request": + res.resp, res.err = n.dispatchRequest(req) + case "NamingHeaderClient.Response": + res.resp, res.err = n.dispatchResponse(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (n *NamingHeaderServerTransport) dispatchRequest(req *http.Request) (*http.Response, error) { + if n.srv.Request == nil { + return nil, &nonRetriableError{errors.New("fake for method Request not implemented")} + } + respr, errRespr := n.srv.Request(req.Context(), getHeaderValue(req.Header, "default-name"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NamingHeaderServerTransport) dispatchResponse(req *http.Request) (*http.Response, error) { + if n.srv.Response == nil { + return nil, &nonRetriableError{errors.New("fake for method Response not implemented")} + } + respr, errRespr := n.srv.Response(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).ClientName; val != nil { + resp.Header.Set("default-name", *val) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to NamingHeaderServerTransport +var namingHeaderServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/client/naminggroup/fake/zz_namingmodel_server.go b/test/azure-http-specs/client/naminggroup/fake/zz_namingmodel_server.go new file mode 100644 index 000000000000..48bcdcad9a64 --- /dev/null +++ b/test/azure-http-specs/client/naminggroup/fake/zz_namingmodel_server.go @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "naminggroup" + "net/http" + "slices" +) + +// NamingModelServer is a fake server for instances of the naminggroup.NamingModelClient type. +type NamingModelServer struct { + // Client is the fake for method NamingModelClient.Client + // HTTP status codes to indicate success: http.StatusNoContent + Client func(ctx context.Context, body naminggroup.ClientModel, options *naminggroup.NamingModelClientClientOptions) (resp azfake.Responder[naminggroup.NamingModelClientClientResponse], errResp azfake.ErrorResponder) + + // Language is the fake for method NamingModelClient.Language + // HTTP status codes to indicate success: http.StatusNoContent + Language func(ctx context.Context, body naminggroup.GoModel, options *naminggroup.NamingModelClientLanguageOptions) (resp azfake.Responder[naminggroup.NamingModelClientLanguageResponse], errResp azfake.ErrorResponder) +} + +// NewNamingModelServerTransport creates a new instance of NamingModelServerTransport with the provided implementation. +// The returned NamingModelServerTransport instance is connected to an instance of naminggroup.NamingModelClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewNamingModelServerTransport(srv *NamingModelServer) *NamingModelServerTransport { + return &NamingModelServerTransport{srv: srv} +} + +// NamingModelServerTransport connects instances of naminggroup.NamingModelClient to instances of NamingModelServer. +// Don't use this type directly, use NewNamingModelServerTransport instead. +type NamingModelServerTransport struct { + srv *NamingModelServer +} + +// Do implements the policy.Transporter interface for NamingModelServerTransport. +func (n *NamingModelServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return n.dispatchToMethodFake(req, method) +} + +func (n *NamingModelServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if namingModelServerTransportInterceptor != nil { + res.resp, res.err, intercepted = namingModelServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "NamingModelClient.Client": + res.resp, res.err = n.dispatchClient(req) + case "NamingModelClient.Language": + res.resp, res.err = n.dispatchLanguage(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (n *NamingModelServerTransport) dispatchClient(req *http.Request) (*http.Response, error) { + if n.srv.Client == nil { + return nil, &nonRetriableError{errors.New("fake for method Client not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[naminggroup.ClientModel](req) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.Client(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NamingModelServerTransport) dispatchLanguage(req *http.Request) (*http.Response, error) { + if n.srv.Language == nil { + return nil, &nonRetriableError{errors.New("fake for method Language not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[naminggroup.GoModel](req) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.Language(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to NamingModelServerTransport +var namingModelServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/client/naminggroup/fake/zz_namingproperty_server.go b/test/azure-http-specs/client/naminggroup/fake/zz_namingproperty_server.go new file mode 100644 index 000000000000..4716ef534c8d --- /dev/null +++ b/test/azure-http-specs/client/naminggroup/fake/zz_namingproperty_server.go @@ -0,0 +1,163 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "naminggroup" + "net/http" + "slices" +) + +// NamingPropertyServer is a fake server for instances of the naminggroup.NamingPropertyClient type. +type NamingPropertyServer struct { + // Client is the fake for method NamingPropertyClient.Client + // HTTP status codes to indicate success: http.StatusNoContent + Client func(ctx context.Context, body naminggroup.ClientNameModel, options *naminggroup.NamingPropertyClientClientOptions) (resp azfake.Responder[naminggroup.NamingPropertyClientClientResponse], errResp azfake.ErrorResponder) + + // CompatibleWithEncodedName is the fake for method NamingPropertyClient.CompatibleWithEncodedName + // HTTP status codes to indicate success: http.StatusNoContent + CompatibleWithEncodedName func(ctx context.Context, body naminggroup.ClientNameAndJSONEncodedNameModel, options *naminggroup.NamingPropertyClientCompatibleWithEncodedNameOptions) (resp azfake.Responder[naminggroup.NamingPropertyClientCompatibleWithEncodedNameResponse], errResp azfake.ErrorResponder) + + // Language is the fake for method NamingPropertyClient.Language + // HTTP status codes to indicate success: http.StatusNoContent + Language func(ctx context.Context, body naminggroup.LanguageClientNameModel, options *naminggroup.NamingPropertyClientLanguageOptions) (resp azfake.Responder[naminggroup.NamingPropertyClientLanguageResponse], errResp azfake.ErrorResponder) +} + +// NewNamingPropertyServerTransport creates a new instance of NamingPropertyServerTransport with the provided implementation. +// The returned NamingPropertyServerTransport instance is connected to an instance of naminggroup.NamingPropertyClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewNamingPropertyServerTransport(srv *NamingPropertyServer) *NamingPropertyServerTransport { + return &NamingPropertyServerTransport{srv: srv} +} + +// NamingPropertyServerTransport connects instances of naminggroup.NamingPropertyClient to instances of NamingPropertyServer. +// Don't use this type directly, use NewNamingPropertyServerTransport instead. +type NamingPropertyServerTransport struct { + srv *NamingPropertyServer +} + +// Do implements the policy.Transporter interface for NamingPropertyServerTransport. +func (n *NamingPropertyServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return n.dispatchToMethodFake(req, method) +} + +func (n *NamingPropertyServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if namingPropertyServerTransportInterceptor != nil { + res.resp, res.err, intercepted = namingPropertyServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "NamingPropertyClient.Client": + res.resp, res.err = n.dispatchClient(req) + case "NamingPropertyClient.CompatibleWithEncodedName": + res.resp, res.err = n.dispatchCompatibleWithEncodedName(req) + case "NamingPropertyClient.Language": + res.resp, res.err = n.dispatchLanguage(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (n *NamingPropertyServerTransport) dispatchClient(req *http.Request) (*http.Response, error) { + if n.srv.Client == nil { + return nil, &nonRetriableError{errors.New("fake for method Client not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[naminggroup.ClientNameModel](req) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.Client(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NamingPropertyServerTransport) dispatchCompatibleWithEncodedName(req *http.Request) (*http.Response, error) { + if n.srv.CompatibleWithEncodedName == nil { + return nil, &nonRetriableError{errors.New("fake for method CompatibleWithEncodedName not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[naminggroup.ClientNameAndJSONEncodedNameModel](req) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.CompatibleWithEncodedName(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NamingPropertyServerTransport) dispatchLanguage(req *http.Request) (*http.Response, error) { + if n.srv.Language == nil { + return nil, &nonRetriableError{errors.New("fake for method Language not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[naminggroup.LanguageClientNameModel](req) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.Language(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to NamingPropertyServerTransport +var namingPropertyServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/client/naminggroup/fake/zz_namingunionenum_server.go b/test/azure-http-specs/client/naminggroup/fake/zz_namingunionenum_server.go new file mode 100644 index 000000000000..fb20e6bfbd61 --- /dev/null +++ b/test/azure-http-specs/client/naminggroup/fake/zz_namingunionenum_server.go @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "naminggroup" + "net/http" + "slices" +) + +// NamingUnionEnumServer is a fake server for instances of the naminggroup.NamingUnionEnumClient type. +type NamingUnionEnumServer struct { + // UnionEnumMemberName is the fake for method NamingUnionEnumClient.UnionEnumMemberName + // HTTP status codes to indicate success: http.StatusNoContent + UnionEnumMemberName func(ctx context.Context, body naminggroup.ExtensibleEnum, options *naminggroup.NamingUnionEnumClientUnionEnumMemberNameOptions) (resp azfake.Responder[naminggroup.NamingUnionEnumClientUnionEnumMemberNameResponse], errResp azfake.ErrorResponder) + + // UnionEnumName is the fake for method NamingUnionEnumClient.UnionEnumName + // HTTP status codes to indicate success: http.StatusNoContent + UnionEnumName func(ctx context.Context, body naminggroup.ClientExtensibleEnum, options *naminggroup.NamingUnionEnumClientUnionEnumNameOptions) (resp azfake.Responder[naminggroup.NamingUnionEnumClientUnionEnumNameResponse], errResp azfake.ErrorResponder) +} + +// NewNamingUnionEnumServerTransport creates a new instance of NamingUnionEnumServerTransport with the provided implementation. +// The returned NamingUnionEnumServerTransport instance is connected to an instance of naminggroup.NamingUnionEnumClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewNamingUnionEnumServerTransport(srv *NamingUnionEnumServer) *NamingUnionEnumServerTransport { + return &NamingUnionEnumServerTransport{srv: srv} +} + +// NamingUnionEnumServerTransport connects instances of naminggroup.NamingUnionEnumClient to instances of NamingUnionEnumServer. +// Don't use this type directly, use NewNamingUnionEnumServerTransport instead. +type NamingUnionEnumServerTransport struct { + srv *NamingUnionEnumServer +} + +// Do implements the policy.Transporter interface for NamingUnionEnumServerTransport. +func (n *NamingUnionEnumServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return n.dispatchToMethodFake(req, method) +} + +func (n *NamingUnionEnumServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if namingUnionEnumServerTransportInterceptor != nil { + res.resp, res.err, intercepted = namingUnionEnumServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "NamingUnionEnumClient.UnionEnumMemberName": + res.resp, res.err = n.dispatchUnionEnumMemberName(req) + case "NamingUnionEnumClient.UnionEnumName": + res.resp, res.err = n.dispatchUnionEnumName(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (n *NamingUnionEnumServerTransport) dispatchUnionEnumMemberName(req *http.Request) (*http.Response, error) { + if n.srv.UnionEnumMemberName == nil { + return nil, &nonRetriableError{errors.New("fake for method UnionEnumMemberName not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[naminggroup.ExtensibleEnum](req) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.UnionEnumMemberName(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NamingUnionEnumServerTransport) dispatchUnionEnumName(req *http.Request) (*http.Response, error) { + if n.srv.UnionEnumName == nil { + return nil, &nonRetriableError{errors.New("fake for method UnionEnumName not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[naminggroup.ClientExtensibleEnum](req) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.UnionEnumName(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to NamingUnionEnumServerTransport +var namingUnionEnumServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/client/naminggroup/fakes_test.go b/test/azure-http-specs/client/naminggroup/fakes_test.go new file mode 100644 index 000000000000..b6bf8e6f1841 --- /dev/null +++ b/test/azure-http-specs/client/naminggroup/fakes_test.go @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package naminggroup_test + +import ( + "context" + "naminggroup" + "naminggroup/fake" + "net/http" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestFakeNamingServer(t *testing.T) { + calledModelServerClient := false + calledPropertyServerClient := false + server := fake.NamingServer{ + NamingModelServer: fake.NamingModelServer{ + Client: func(ctx context.Context, body naminggroup.ClientModel, options *naminggroup.NamingModelClientClientOptions) (resp azfake.Responder[naminggroup.NamingModelClientClientResponse], errResp azfake.ErrorResponder) { + require.NotNil(t, body.DefaultName) + require.True(t, *body.DefaultName) + calledModelServerClient = true + resp.SetResponse(http.StatusNoContent, naminggroup.NamingModelClientClientResponse{}, nil) + return + }, + }, + NamingPropertyServer: fake.NamingPropertyServer{ + Client: func(ctx context.Context, body naminggroup.ClientNameModel, options *naminggroup.NamingPropertyClientClientOptions) (resp azfake.Responder[naminggroup.NamingPropertyClientClientResponse], errResp azfake.ErrorResponder) { + require.NotNil(t, body.ClientName) + require.True(t, *body.ClientName) + calledPropertyServerClient = true + resp.SetResponse(http.StatusNoContent, naminggroup.NamingPropertyClientClientResponse{}, nil) + return + }, + }, + } + client, err := naminggroup.NewNamingClientWithNoCredential("http://localhost:3000", &naminggroup.NamingClientOptions{ + ClientOptions: azcore.ClientOptions{ + Transport: fake.NewNamingServerTransport(&server), + }, + }) + require.NoError(t, err) + + _, err = client.NewNamingModelClient().Client(context.Background(), naminggroup.ClientModel{ + DefaultName: to.Ptr(true), + }, nil) + require.NoError(t, err) + + _, err = client.NewNamingPropertyClient().Client(context.Background(), naminggroup.ClientNameModel{ + ClientName: to.Ptr(true), + }, nil) + require.NoError(t, err) + + require.True(t, calledModelServerClient) + require.True(t, calledPropertyServerClient) +} diff --git a/test/azure-http-specs/client/naminggroup/go.mod b/test/azure-http-specs/client/naminggroup/go.mod new file mode 100644 index 000000000000..4b8c18af8e10 --- /dev/null +++ b/test/azure-http-specs/client/naminggroup/go.mod @@ -0,0 +1,17 @@ +module naminggroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/client/naminggroup/go.sum b/test/azure-http-specs/client/naminggroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/client/naminggroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/client/naminggroup/naming_client_test.go b/test/azure-http-specs/client/naminggroup/naming_client_test.go new file mode 100644 index 000000000000..5d8f562a803d --- /dev/null +++ b/test/azure-http-specs/client/naminggroup/naming_client_test.go @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package naminggroup_test + +import ( + "context" + "naminggroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestPropertyClient_Client(t *testing.T) { + client, err := naminggroup.NewNamingClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNamingPropertyClient().Client(context.Background(), naminggroup.ClientNameModel{ + ClientName: to.Ptr(true), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestNamingClient_ClientName(t *testing.T) { + client, err := naminggroup.NewNamingClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.ClientName(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestPropertyClient_CompatibleWithEncodedName(t *testing.T) { + client, err := naminggroup.NewNamingClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNamingPropertyClient().CompatibleWithEncodedName(context.Background(), naminggroup.ClientNameAndJSONEncodedNameModel{ + ClientName: to.Ptr(true), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestPropertyClient_Language(t *testing.T) { + client, err := naminggroup.NewNamingClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNamingPropertyClient().Language(context.Background(), naminggroup.LanguageClientNameModel{ + GoName: to.Ptr(true), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestNamingClient_Parameter(t *testing.T) { + client, err := naminggroup.NewNamingClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.Parameter(context.Background(), "true", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestHeaderClient_Request(t *testing.T) { + client, err := naminggroup.NewNamingClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNamingHeaderClient().Request(context.Background(), "true", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestHeaderClient_Response(t *testing.T) { + client, err := naminggroup.NewNamingClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNamingHeaderClient().Response(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.ClientName) + require.EqualValues(t, "true", *resp.ClientName) +} + +func TestModelClient_Client(t *testing.T) { + client, err := naminggroup.NewNamingClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNamingModelClient().Client(context.Background(), naminggroup.ClientModel{ + DefaultName: to.Ptr(true), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelClient_Language(t *testing.T) { + client, err := naminggroup.NewNamingClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNamingModelClient().Language(context.Background(), naminggroup.GoModel{ + DefaultName: to.Ptr(true), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestUnionEnumClient_UnionEnumMemberName(t *testing.T) { + client, err := naminggroup.NewNamingClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNamingUnionEnumClient().UnionEnumMemberName(context.Background(), naminggroup.ExtensibleEnumClientEnumValue1, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestUnionEnumClient_UnionEnumName(t *testing.T) { + client, err := naminggroup.NewNamingClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNamingUnionEnumClient().UnionEnumName(context.Background(), naminggroup.ClientExtensibleEnumEnumValue1, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/client/naminggroup/testdata/_metadata.json b/test/azure-http-specs/client/naminggroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/azure-http-specs/client/naminggroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/client/naminggroup/zz_constants.go b/test/azure-http-specs/client/naminggroup/zz_constants.go new file mode 100644 index 000000000000..31f77f4e6605 --- /dev/null +++ b/test/azure-http-specs/client/naminggroup/zz_constants.go @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package naminggroup + +type ClientExtensibleEnum string + +const ( + ClientExtensibleEnumEnumValue1 ClientExtensibleEnum = "value1" +) + +// PossibleClientExtensibleEnumValues returns the possible values for the ClientExtensibleEnum const type. +func PossibleClientExtensibleEnumValues() []ClientExtensibleEnum { + return []ClientExtensibleEnum{ + ClientExtensibleEnumEnumValue1, + } +} + +type ExtensibleEnum string + +const ( + ExtensibleEnumClientEnumValue1 ExtensibleEnum = "value1" + ExtensibleEnumClientEnumValue2 ExtensibleEnum = "value2" +) + +// PossibleExtensibleEnumValues returns the possible values for the ExtensibleEnum const type. +func PossibleExtensibleEnumValues() []ExtensibleEnum { + return []ExtensibleEnum{ + ExtensibleEnumClientEnumValue1, + ExtensibleEnumClientEnumValue2, + } +} diff --git a/test/azure-http-specs/client/naminggroup/zz_models.go b/test/azure-http-specs/client/naminggroup/zz_models.go new file mode 100644 index 000000000000..562b59783611 --- /dev/null +++ b/test/azure-http-specs/client/naminggroup/zz_models.go @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package naminggroup + +type ClientModel struct { + // REQUIRED; Pass in true + DefaultName *bool +} + +type ClientNameAndJSONEncodedNameModel struct { + // REQUIRED; Pass in true + ClientName *bool +} + +type ClientNameModel struct { + // REQUIRED; Pass in true + ClientName *bool +} + +type GoModel struct { + // REQUIRED; Pass in true + DefaultName *bool +} + +type LanguageClientNameModel struct { + // REQUIRED; Pass in true + GoName *bool +} diff --git a/test/azure-http-specs/client/naminggroup/zz_models_serde.go b/test/azure-http-specs/client/naminggroup/zz_models_serde.go new file mode 100644 index 000000000000..9cb87a581a9c --- /dev/null +++ b/test/azure-http-specs/client/naminggroup/zz_models_serde.go @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package naminggroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type ClientModel. +func (c ClientModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "defaultName", c.DefaultName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ClientModel. +func (c *ClientModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "defaultName": + err = unpopulate(val, "DefaultName", &c.DefaultName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ClientNameAndJSONEncodedNameModel. +func (c ClientNameAndJSONEncodedNameModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "wireName", c.ClientName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ClientNameAndJSONEncodedNameModel. +func (c *ClientNameAndJSONEncodedNameModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "wireName": + err = unpopulate(val, "ClientName", &c.ClientName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ClientNameModel. +func (c ClientNameModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "defaultName", c.ClientName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ClientNameModel. +func (c *ClientNameModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "defaultName": + err = unpopulate(val, "ClientName", &c.ClientName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type GoModel. +func (g GoModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "defaultName", g.DefaultName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GoModel. +func (g *GoModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "defaultName": + err = unpopulate(val, "DefaultName", &g.DefaultName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LanguageClientNameModel. +func (l LanguageClientNameModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "defaultName", l.GoName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LanguageClientNameModel. +func (l *LanguageClientNameModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "defaultName": + err = unpopulate(val, "GoName", &l.GoName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/azure-http-specs/client/naminggroup/zz_naming_client.go b/test/azure-http-specs/client/naminggroup/zz_naming_client.go new file mode 100644 index 000000000000..8983c2dd022c --- /dev/null +++ b/test/azure-http-specs/client/naminggroup/zz_naming_client.go @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package naminggroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// NamingClient - Describe changing names of types in a client with `@clientName` +// Don't use this type directly, use NewNamingClientWithNoCredential() instead. +type NamingClient struct { + internal *azcore.Client + endpoint string +} + +// NamingClientOptions contains the optional values for creating a [NamingClient]. +type NamingClientOptions struct { + azcore.ClientOptions +} + +// NewNamingClientWithNoCredential creates a new instance of NamingClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewNamingClientWithNoCredential(endpoint string, options *NamingClientOptions) (*NamingClient, error) { + if options == nil { + options = &NamingClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &NamingClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewNamingHeaderClient creates a new instance of [NamingHeaderClient]. +func (client *NamingClient) NewNamingHeaderClient() *NamingHeaderClient { + return &NamingHeaderClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewNamingModelClient creates a new instance of [NamingModelClient]. +func (client *NamingClient) NewNamingModelClient() *NamingModelClient { + return &NamingModelClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewNamingPropertyClient creates a new instance of [NamingPropertyClient]. +func (client *NamingClient) NewNamingPropertyClient() *NamingPropertyClient { + return &NamingPropertyClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewNamingUnionEnumClient creates a new instance of [NamingUnionEnumClient]. +func (client *NamingClient) NewNamingUnionEnumClient() *NamingUnionEnumClient { + return &NamingUnionEnumClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// ClientName - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NamingClientClientNameOptions contains the optional parameters for the NamingClient.ClientName method. +func (client *NamingClient) ClientName(ctx context.Context, options *NamingClientClientNameOptions) (NamingClientClientNameResponse, error) { + var err error + const operationName = "NamingClient.ClientName" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.clientNameCreateRequest(ctx, options) + if err != nil { + return NamingClientClientNameResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NamingClientClientNameResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return NamingClientClientNameResponse{}, err + } + return NamingClientClientNameResponse{}, nil +} + +// clientNameCreateRequest creates the ClientName request. +func (client *NamingClient) clientNameCreateRequest(ctx context.Context, _ *NamingClientClientNameOptions) (*policy.Request, error) { + urlPath := "/client/naming/operation" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Parameter - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NamingClientParameterOptions contains the optional parameters for the NamingClient.Parameter method. +func (client *NamingClient) Parameter(ctx context.Context, clientName string, options *NamingClientParameterOptions) (NamingClientParameterResponse, error) { + var err error + const operationName = "NamingClient.Parameter" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.parameterCreateRequest(ctx, clientName, options) + if err != nil { + return NamingClientParameterResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NamingClientParameterResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return NamingClientParameterResponse{}, err + } + return NamingClientParameterResponse{}, nil +} + +// parameterCreateRequest creates the Parameter request. +func (client *NamingClient) parameterCreateRequest(ctx context.Context, clientName string, _ *NamingClientParameterOptions) (*policy.Request, error) { + urlPath := "/client/naming/parameter" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("defaultName", clientName) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/azure-http-specs/client/naminggroup/zz_namingheader_client.go b/test/azure-http-specs/client/naminggroup/zz_namingheader_client.go new file mode 100644 index 000000000000..9428dc570a1f --- /dev/null +++ b/test/azure-http-specs/client/naminggroup/zz_namingheader_client.go @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package naminggroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// NamingHeaderClient contains the methods for the NamingHeader group. +// Don't use this type directly, use [NamingClient.NewNamingHeaderClient] instead. +type NamingHeaderClient struct { + internal *azcore.Client + endpoint string +} + +// Request - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NamingHeaderClientRequestOptions contains the optional parameters for the NamingHeaderClient.Request method. +func (client *NamingHeaderClient) Request(ctx context.Context, clientName string, options *NamingHeaderClientRequestOptions) (NamingHeaderClientRequestResponse, error) { + var err error + const operationName = "NamingHeaderClient.Request" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.requestCreateRequest(ctx, clientName, options) + if err != nil { + return NamingHeaderClientRequestResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NamingHeaderClientRequestResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return NamingHeaderClientRequestResponse{}, err + } + return NamingHeaderClientRequestResponse{}, nil +} + +// requestCreateRequest creates the Request request. +func (client *NamingHeaderClient) requestCreateRequest(ctx context.Context, clientName string, _ *NamingHeaderClientRequestOptions) (*policy.Request, error) { + urlPath := "/client/naming/header" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["default-name"] = []string{clientName} + return req, nil +} + +// Response - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NamingHeaderClientResponseOptions contains the optional parameters for the NamingHeaderClient.Response method. +func (client *NamingHeaderClient) Response(ctx context.Context, options *NamingHeaderClientResponseOptions) (NamingHeaderClientResponseResponse, error) { + var err error + const operationName = "NamingHeaderClient.Response" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.responseCreateRequest(ctx, options) + if err != nil { + return NamingHeaderClientResponseResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NamingHeaderClientResponseResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return NamingHeaderClientResponseResponse{}, err + } + resp, err := client.responseHandleResponse(httpResp) + return resp, err +} + +// responseCreateRequest creates the Response request. +func (client *NamingHeaderClient) responseCreateRequest(ctx context.Context, _ *NamingHeaderClientResponseOptions) (*policy.Request, error) { + urlPath := "/client/naming/header" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// responseHandleResponse handles the Response response. +func (client *NamingHeaderClient) responseHandleResponse(resp *http.Response) (NamingHeaderClientResponseResponse, error) { + result := NamingHeaderClientResponseResponse{} + if val := resp.Header.Get("default-name"); val != "" { + result.ClientName = &val + } + return result, nil +} diff --git a/test/azure-http-specs/client/naminggroup/zz_namingmodel_client.go b/test/azure-http-specs/client/naminggroup/zz_namingmodel_client.go new file mode 100644 index 000000000000..b591ab071799 --- /dev/null +++ b/test/azure-http-specs/client/naminggroup/zz_namingmodel_client.go @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package naminggroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// NamingModelClient contains the methods for the NamingModel group. +// Don't use this type directly, use [NamingClient.NewNamingModelClient] instead. +type NamingModelClient struct { + internal *azcore.Client + endpoint string +} + +// Client - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NamingModelClientClientOptions contains the optional parameters for the NamingModelClient.Client method. +func (client *NamingModelClient) Client(ctx context.Context, body ClientModel, options *NamingModelClientClientOptions) (NamingModelClientClientResponse, error) { + var err error + const operationName = "NamingModelClient.Client" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.clientCreateRequest(ctx, body, options) + if err != nil { + return NamingModelClientClientResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NamingModelClientClientResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return NamingModelClientClientResponse{}, err + } + return NamingModelClientClientResponse{}, nil +} + +// clientCreateRequest creates the Client request. +func (client *NamingModelClient) clientCreateRequest(ctx context.Context, body ClientModel, _ *NamingModelClientClientOptions) (*policy.Request, error) { + urlPath := "/client/naming/model/client" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// Language - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NamingModelClientLanguageOptions contains the optional parameters for the NamingModelClient.Language method. +func (client *NamingModelClient) Language(ctx context.Context, body GoModel, options *NamingModelClientLanguageOptions) (NamingModelClientLanguageResponse, error) { + var err error + const operationName = "NamingModelClient.Language" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.languageCreateRequest(ctx, body, options) + if err != nil { + return NamingModelClientLanguageResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NamingModelClientLanguageResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return NamingModelClientLanguageResponse{}, err + } + return NamingModelClientLanguageResponse{}, nil +} + +// languageCreateRequest creates the Language request. +func (client *NamingModelClient) languageCreateRequest(ctx context.Context, body GoModel, _ *NamingModelClientLanguageOptions) (*policy.Request, error) { + urlPath := "/client/naming/model/language" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/client/naminggroup/zz_namingproperty_client.go b/test/azure-http-specs/client/naminggroup/zz_namingproperty_client.go new file mode 100644 index 000000000000..d575c0497a70 --- /dev/null +++ b/test/azure-http-specs/client/naminggroup/zz_namingproperty_client.go @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package naminggroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// NamingPropertyClient contains the methods for the NamingProperty group. +// Don't use this type directly, use [NamingClient.NewNamingPropertyClient] instead. +type NamingPropertyClient struct { + internal *azcore.Client + endpoint string +} + +// Client - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NamingPropertyClientClientOptions contains the optional parameters for the NamingPropertyClient.Client method. +func (client *NamingPropertyClient) Client(ctx context.Context, body ClientNameModel, options *NamingPropertyClientClientOptions) (NamingPropertyClientClientResponse, error) { + var err error + const operationName = "NamingPropertyClient.Client" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.clientCreateRequest(ctx, body, options) + if err != nil { + return NamingPropertyClientClientResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NamingPropertyClientClientResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return NamingPropertyClientClientResponse{}, err + } + return NamingPropertyClientClientResponse{}, nil +} + +// clientCreateRequest creates the Client request. +func (client *NamingPropertyClient) clientCreateRequest(ctx context.Context, body ClientNameModel, _ *NamingPropertyClientClientOptions) (*policy.Request, error) { + urlPath := "/client/naming/property/client" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// CompatibleWithEncodedName - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NamingPropertyClientCompatibleWithEncodedNameOptions contains the optional parameters for the NamingPropertyClient.CompatibleWithEncodedName +// method. +func (client *NamingPropertyClient) CompatibleWithEncodedName(ctx context.Context, body ClientNameAndJSONEncodedNameModel, options *NamingPropertyClientCompatibleWithEncodedNameOptions) (NamingPropertyClientCompatibleWithEncodedNameResponse, error) { + var err error + const operationName = "NamingPropertyClient.CompatibleWithEncodedName" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.compatibleWithEncodedNameCreateRequest(ctx, body, options) + if err != nil { + return NamingPropertyClientCompatibleWithEncodedNameResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NamingPropertyClientCompatibleWithEncodedNameResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return NamingPropertyClientCompatibleWithEncodedNameResponse{}, err + } + return NamingPropertyClientCompatibleWithEncodedNameResponse{}, nil +} + +// compatibleWithEncodedNameCreateRequest creates the CompatibleWithEncodedName request. +func (client *NamingPropertyClient) compatibleWithEncodedNameCreateRequest(ctx context.Context, body ClientNameAndJSONEncodedNameModel, _ *NamingPropertyClientCompatibleWithEncodedNameOptions) (*policy.Request, error) { + urlPath := "/client/naming/property/compatible-with-encoded-name" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// Language - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NamingPropertyClientLanguageOptions contains the optional parameters for the NamingPropertyClient.Language method. +func (client *NamingPropertyClient) Language(ctx context.Context, body LanguageClientNameModel, options *NamingPropertyClientLanguageOptions) (NamingPropertyClientLanguageResponse, error) { + var err error + const operationName = "NamingPropertyClient.Language" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.languageCreateRequest(ctx, body, options) + if err != nil { + return NamingPropertyClientLanguageResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NamingPropertyClientLanguageResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return NamingPropertyClientLanguageResponse{}, err + } + return NamingPropertyClientLanguageResponse{}, nil +} + +// languageCreateRequest creates the Language request. +func (client *NamingPropertyClient) languageCreateRequest(ctx context.Context, body LanguageClientNameModel, _ *NamingPropertyClientLanguageOptions) (*policy.Request, error) { + urlPath := "/client/naming/property/language" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/client/naminggroup/zz_namingunionenum_client.go b/test/azure-http-specs/client/naminggroup/zz_namingunionenum_client.go new file mode 100644 index 000000000000..d54ad38eac49 --- /dev/null +++ b/test/azure-http-specs/client/naminggroup/zz_namingunionenum_client.go @@ -0,0 +1,98 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package naminggroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// NamingUnionEnumClient contains the methods for the NamingUnionEnum group. +// Don't use this type directly, use [NamingClient.NewNamingUnionEnumClient] instead. +type NamingUnionEnumClient struct { + internal *azcore.Client + endpoint string +} + +// UnionEnumMemberName - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NamingUnionEnumClientUnionEnumMemberNameOptions contains the optional parameters for the NamingUnionEnumClient.UnionEnumMemberName +// method. +func (client *NamingUnionEnumClient) UnionEnumMemberName(ctx context.Context, body ExtensibleEnum, options *NamingUnionEnumClientUnionEnumMemberNameOptions) (NamingUnionEnumClientUnionEnumMemberNameResponse, error) { + var err error + const operationName = "NamingUnionEnumClient.UnionEnumMemberName" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.unionEnumMemberNameCreateRequest(ctx, body, options) + if err != nil { + return NamingUnionEnumClientUnionEnumMemberNameResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NamingUnionEnumClientUnionEnumMemberNameResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return NamingUnionEnumClientUnionEnumMemberNameResponse{}, err + } + return NamingUnionEnumClientUnionEnumMemberNameResponse{}, nil +} + +// unionEnumMemberNameCreateRequest creates the UnionEnumMemberName request. +func (client *NamingUnionEnumClient) unionEnumMemberNameCreateRequest(ctx context.Context, body ExtensibleEnum, _ *NamingUnionEnumClientUnionEnumMemberNameOptions) (*policy.Request, error) { + urlPath := "/client/naming/union-enum/union-enum-member-name" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// UnionEnumName - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NamingUnionEnumClientUnionEnumNameOptions contains the optional parameters for the NamingUnionEnumClient.UnionEnumName +// method. +func (client *NamingUnionEnumClient) UnionEnumName(ctx context.Context, body ClientExtensibleEnum, options *NamingUnionEnumClientUnionEnumNameOptions) (NamingUnionEnumClientUnionEnumNameResponse, error) { + var err error + const operationName = "NamingUnionEnumClient.UnionEnumName" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.unionEnumNameCreateRequest(ctx, body, options) + if err != nil { + return NamingUnionEnumClientUnionEnumNameResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NamingUnionEnumClientUnionEnumNameResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return NamingUnionEnumClientUnionEnumNameResponse{}, err + } + return NamingUnionEnumClientUnionEnumNameResponse{}, nil +} + +// unionEnumNameCreateRequest creates the UnionEnumName request. +func (client *NamingUnionEnumClient) unionEnumNameCreateRequest(ctx context.Context, body ClientExtensibleEnum, _ *NamingUnionEnumClientUnionEnumNameOptions) (*policy.Request, error) { + urlPath := "/client/naming/union-enum/union-enum-name" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/client/naminggroup/zz_options.go b/test/azure-http-specs/client/naminggroup/zz_options.go new file mode 100644 index 000000000000..23db6d0b3bb6 --- /dev/null +++ b/test/azure-http-specs/client/naminggroup/zz_options.go @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package naminggroup + +// NamingClientClientNameOptions contains the optional parameters for the NamingClient.ClientName method. +type NamingClientClientNameOptions struct { + // placeholder for future optional parameters +} + +// NamingClientParameterOptions contains the optional parameters for the NamingClient.Parameter method. +type NamingClientParameterOptions struct { + // placeholder for future optional parameters +} + +// NamingHeaderClientRequestOptions contains the optional parameters for the NamingHeaderClient.Request method. +type NamingHeaderClientRequestOptions struct { + // placeholder for future optional parameters +} + +// NamingHeaderClientResponseOptions contains the optional parameters for the NamingHeaderClient.Response method. +type NamingHeaderClientResponseOptions struct { + // placeholder for future optional parameters +} + +// NamingModelClientClientOptions contains the optional parameters for the NamingModelClient.Client method. +type NamingModelClientClientOptions struct { + // placeholder for future optional parameters +} + +// NamingModelClientLanguageOptions contains the optional parameters for the NamingModelClient.Language method. +type NamingModelClientLanguageOptions struct { + // placeholder for future optional parameters +} + +// NamingPropertyClientClientOptions contains the optional parameters for the NamingPropertyClient.Client method. +type NamingPropertyClientClientOptions struct { + // placeholder for future optional parameters +} + +// NamingPropertyClientCompatibleWithEncodedNameOptions contains the optional parameters for the NamingPropertyClient.CompatibleWithEncodedName +// method. +type NamingPropertyClientCompatibleWithEncodedNameOptions struct { + // placeholder for future optional parameters +} + +// NamingPropertyClientLanguageOptions contains the optional parameters for the NamingPropertyClient.Language method. +type NamingPropertyClientLanguageOptions struct { + // placeholder for future optional parameters +} + +// NamingUnionEnumClientUnionEnumMemberNameOptions contains the optional parameters for the NamingUnionEnumClient.UnionEnumMemberName +// method. +type NamingUnionEnumClientUnionEnumMemberNameOptions struct { + // placeholder for future optional parameters +} + +// NamingUnionEnumClientUnionEnumNameOptions contains the optional parameters for the NamingUnionEnumClient.UnionEnumName +// method. +type NamingUnionEnumClientUnionEnumNameOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/client/naminggroup/zz_responses.go b/test/azure-http-specs/client/naminggroup/zz_responses.go new file mode 100644 index 000000000000..5c03bbee161f --- /dev/null +++ b/test/azure-http-specs/client/naminggroup/zz_responses.go @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package naminggroup + +// NamingClientClientNameResponse contains the response from method NamingClient.ClientName. +type NamingClientClientNameResponse struct { + // placeholder for future response values +} + +// NamingClientParameterResponse contains the response from method NamingClient.Parameter. +type NamingClientParameterResponse struct { + // placeholder for future response values +} + +// NamingHeaderClientRequestResponse contains the response from method NamingHeaderClient.Request. +type NamingHeaderClientRequestResponse struct { + // placeholder for future response values +} + +// NamingHeaderClientResponseResponse contains the response from method NamingHeaderClient.Response. +type NamingHeaderClientResponseResponse struct { + ClientName *string +} + +// NamingModelClientClientResponse contains the response from method NamingModelClient.Client. +type NamingModelClientClientResponse struct { + // placeholder for future response values +} + +// NamingModelClientLanguageResponse contains the response from method NamingModelClient.Language. +type NamingModelClientLanguageResponse struct { + // placeholder for future response values +} + +// NamingPropertyClientClientResponse contains the response from method NamingPropertyClient.Client. +type NamingPropertyClientClientResponse struct { + // placeholder for future response values +} + +// NamingPropertyClientCompatibleWithEncodedNameResponse contains the response from method NamingPropertyClient.CompatibleWithEncodedName. +type NamingPropertyClientCompatibleWithEncodedNameResponse struct { + // placeholder for future response values +} + +// NamingPropertyClientLanguageResponse contains the response from method NamingPropertyClient.Language. +type NamingPropertyClientLanguageResponse struct { + // placeholder for future response values +} + +// NamingUnionEnumClientUnionEnumMemberNameResponse contains the response from method NamingUnionEnumClient.UnionEnumMemberName. +type NamingUnionEnumClientUnionEnumMemberNameResponse struct { + // placeholder for future response values +} + +// NamingUnionEnumClientUnionEnumNameResponse contains the response from method NamingUnionEnumClient.UnionEnumName. +type NamingUnionEnumClientUnionEnumNameResponse struct { + // placeholder for future response values +} diff --git a/test/azure-http-specs/client/naminggroup/zz_version.go b/test/azure-http-specs/client/naminggroup/zz_version.go new file mode 100644 index 000000000000..d51fdad13657 --- /dev/null +++ b/test/azure-http-specs/client/naminggroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package naminggroup + +const ( + moduleName = "naminggroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/client/overloadgroup/LICENSE.txt b/test/azure-http-specs/client/overloadgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/client/overloadgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/client/overloadgroup/fake/zz_internal.go b/test/azure-http-specs/client/overloadgroup/fake/zz_internal.go new file mode 100644 index 000000000000..705f81eacafe --- /dev/null +++ b/test/azure-http-specs/client/overloadgroup/fake/zz_internal.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import "net/http" + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} diff --git a/test/azure-http-specs/client/overloadgroup/fake/zz_overload_server.go b/test/azure-http-specs/client/overloadgroup/fake/zz_overload_server.go new file mode 100644 index 000000000000..b4407f63ee72 --- /dev/null +++ b/test/azure-http-specs/client/overloadgroup/fake/zz_overload_server.go @@ -0,0 +1,138 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "overloadgroup" + "regexp" + "slices" +) + +// OverloadServer is a fake server for instances of the overloadgroup.OverloadClient type. +type OverloadServer struct { + // List is the fake for method OverloadClient.List + // HTTP status codes to indicate success: http.StatusOK + List func(ctx context.Context, options *overloadgroup.OverloadClientListOptions) (resp azfake.Responder[overloadgroup.OverloadClientListResponse], errResp azfake.ErrorResponder) + + // ListByScope is the fake for method OverloadClient.ListByScope + // HTTP status codes to indicate success: http.StatusOK + ListByScope func(ctx context.Context, scope string, options *overloadgroup.OverloadClientListByScopeOptions) (resp azfake.Responder[overloadgroup.OverloadClientListByScopeResponse], errResp azfake.ErrorResponder) +} + +// NewOverloadServerTransport creates a new instance of OverloadServerTransport with the provided implementation. +// The returned OverloadServerTransport instance is connected to an instance of overloadgroup.OverloadClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOverloadServerTransport(srv *OverloadServer) *OverloadServerTransport { + return &OverloadServerTransport{srv: srv} +} + +// OverloadServerTransport connects instances of overloadgroup.OverloadClient to instances of OverloadServer. +// Don't use this type directly, use NewOverloadServerTransport instead. +type OverloadServerTransport struct { + srv *OverloadServer +} + +// Do implements the policy.Transporter interface for OverloadServerTransport. +func (o *OverloadServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OverloadServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if overloadServerTransportInterceptor != nil { + res.resp, res.err, intercepted = overloadServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OverloadClient.List": + res.resp, res.err = o.dispatchList(req) + case "OverloadClient.ListByScope": + res.resp, res.err = o.dispatchListByScope(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OverloadServerTransport) dispatchList(req *http.Request) (*http.Response, error) { + if o.srv.List == nil { + return nil, &nonRetriableError{errors.New("fake for method List not implemented")} + } + respr, errRespr := o.srv.List(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ResourceArray, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OverloadServerTransport) dispatchListByScope(req *http.Request) (*http.Response, error) { + if o.srv.ListByScope == nil { + return nil, &nonRetriableError{errors.New("fake for method ListByScope not implemented")} + } + const regexStr = `/client/overload/resources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + scopeParam, err := url.PathUnescape(matches[regex.SubexpIndex("scope")]) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.ListByScope(req.Context(), scopeParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ResourceArray, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OverloadServerTransport +var overloadServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/client/overloadgroup/go.mod b/test/azure-http-specs/client/overloadgroup/go.mod new file mode 100644 index 000000000000..ed3041ca1613 --- /dev/null +++ b/test/azure-http-specs/client/overloadgroup/go.mod @@ -0,0 +1,17 @@ +module overloadgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/client/overloadgroup/go.sum b/test/azure-http-specs/client/overloadgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/client/overloadgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/client/overloadgroup/overload_client_test.go b/test/azure-http-specs/client/overloadgroup/overload_client_test.go new file mode 100644 index 000000000000..241c379dfe7d --- /dev/null +++ b/test/azure-http-specs/client/overloadgroup/overload_client_test.go @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package overloadgroup_test + +import ( + "context" + "testing" + + "overloadgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestOverloadClient_List(t *testing.T) { + client, err := overloadgroup.NewOverloadClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + require.NotNil(t, client) + + expectedResources := []*overloadgroup.Resource{ + { + ID: to.Ptr("1"), + Name: to.Ptr("foo"), + Scope: to.Ptr("car"), + }, + { + ID: to.Ptr("2"), + Name: to.Ptr("bar"), + Scope: to.Ptr("bike"), + }, + } + resp, err := client.List(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.ResourceArray) + require.Equal(t, expectedResources, resp.ResourceArray) + +} + +func TestOverloadClient_ListByScope(t *testing.T) { + client, err := overloadgroup.NewOverloadClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + require.NotNil(t, client) + expectedResources := []*overloadgroup.Resource{ + { + ID: to.Ptr("1"), + Name: to.Ptr("foo"), + Scope: to.Ptr("car"), + }, + } + scope := "car" + resp, err := client.ListByScope(context.Background(), scope, nil) + require.NoError(t, err) + require.NotNil(t, resp.ResourceArray) + require.Equal(t, expectedResources, resp.ResourceArray) +} diff --git a/test/azure-http-specs/client/overloadgroup/testdata/_metadata.json b/test/azure-http-specs/client/overloadgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/azure-http-specs/client/overloadgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/client/overloadgroup/zz_models.go b/test/azure-http-specs/client/overloadgroup/zz_models.go new file mode 100644 index 000000000000..d9ca8e68800e --- /dev/null +++ b/test/azure-http-specs/client/overloadgroup/zz_models.go @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package overloadgroup + +type Resource struct { + // REQUIRED + ID *string + + // REQUIRED + Name *string + + // REQUIRED + Scope *string +} diff --git a/test/azure-http-specs/client/overloadgroup/zz_models_serde.go b/test/azure-http-specs/client/overloadgroup/zz_models_serde.go new file mode 100644 index 000000000000..2cf75a1b022a --- /dev/null +++ b/test/azure-http-specs/client/overloadgroup/zz_models_serde.go @@ -0,0 +1,67 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package overloadgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type Resource. +func (r Resource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "scope", r.Scope) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Resource. +func (r *Resource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "scope": + err = unpopulate(val, "Scope", &r.Scope) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/azure-http-specs/client/overloadgroup/zz_options.go b/test/azure-http-specs/client/overloadgroup/zz_options.go new file mode 100644 index 000000000000..18a80b678b70 --- /dev/null +++ b/test/azure-http-specs/client/overloadgroup/zz_options.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package overloadgroup + +// OverloadClientListByScopeOptions contains the optional parameters for the OverloadClient.ListByScope method. +type OverloadClientListByScopeOptions struct { + // placeholder for future optional parameters +} + +// OverloadClientListOptions contains the optional parameters for the OverloadClient.List method. +type OverloadClientListOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/client/overloadgroup/zz_overload_client.go b/test/azure-http-specs/client/overloadgroup/zz_overload_client.go new file mode 100644 index 000000000000..e871b86b6a98 --- /dev/null +++ b/test/azure-http-specs/client/overloadgroup/zz_overload_client.go @@ -0,0 +1,140 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package overloadgroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// OverloadClient - Test for overload operation in .NET. +// Don't use this type directly, use NewOverloadClientWithNoCredential() instead. +type OverloadClient struct { + internal *azcore.Client + endpoint string +} + +// OverloadClientOptions contains the optional values for creating a [OverloadClient]. +type OverloadClientOptions struct { + azcore.ClientOptions +} + +// NewOverloadClientWithNoCredential creates a new instance of OverloadClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewOverloadClientWithNoCredential(endpoint string, options *OverloadClientOptions) (*OverloadClient, error) { + if options == nil { + options = &OverloadClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &OverloadClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// List - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OverloadClientListOptions contains the optional parameters for the OverloadClient.List method. +func (client *OverloadClient) List(ctx context.Context, options *OverloadClientListOptions) (OverloadClientListResponse, error) { + var err error + const operationName = "OverloadClient.List" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listCreateRequest(ctx, options) + if err != nil { + return OverloadClientListResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OverloadClientListResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OverloadClientListResponse{}, err + } + resp, err := client.listHandleResponse(httpResp) + return resp, err +} + +// listCreateRequest creates the List request. +func (client *OverloadClient) listCreateRequest(ctx context.Context, _ *OverloadClientListOptions) (*policy.Request, error) { + urlPath := "/client/overload/resources" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OverloadClient) listHandleResponse(resp *http.Response) (OverloadClientListResponse, error) { + result := OverloadClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ResourceArray); err != nil { + return OverloadClientListResponse{}, err + } + return result, nil +} + +// ListByScope - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OverloadClientListByScopeOptions contains the optional parameters for the OverloadClient.ListByScope method. +func (client *OverloadClient) ListByScope(ctx context.Context, scope string, options *OverloadClientListByScopeOptions) (OverloadClientListByScopeResponse, error) { + var err error + const operationName = "OverloadClient.ListByScope" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listByScopeCreateRequest(ctx, scope, options) + if err != nil { + return OverloadClientListByScopeResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OverloadClientListByScopeResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OverloadClientListByScopeResponse{}, err + } + resp, err := client.listByScopeHandleResponse(httpResp) + return resp, err +} + +// listByScopeCreateRequest creates the ListByScope request. +func (client *OverloadClient) listByScopeCreateRequest(ctx context.Context, scope string, _ *OverloadClientListByScopeOptions) (*policy.Request, error) { + urlPath := "/client/overload/resources/{scope}" + if scope == "" { + return nil, errors.New("parameter scope cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scope}", url.PathEscape(scope)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByScopeHandleResponse handles the ListByScope response. +func (client *OverloadClient) listByScopeHandleResponse(resp *http.Response) (OverloadClientListByScopeResponse, error) { + result := OverloadClientListByScopeResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ResourceArray); err != nil { + return OverloadClientListByScopeResponse{}, err + } + return result, nil +} diff --git a/test/azure-http-specs/client/overloadgroup/zz_responses.go b/test/azure-http-specs/client/overloadgroup/zz_responses.go new file mode 100644 index 000000000000..2089eb88e0b2 --- /dev/null +++ b/test/azure-http-specs/client/overloadgroup/zz_responses.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package overloadgroup + +// OverloadClientListByScopeResponse contains the response from method OverloadClient.ListByScope. +type OverloadClientListByScopeResponse struct { + ResourceArray []*Resource +} + +// OverloadClientListResponse contains the response from method OverloadClient.List. +type OverloadClientListResponse struct { + ResourceArray []*Resource +} diff --git a/test/azure-http-specs/client/overloadgroup/zz_version.go b/test/azure-http-specs/client/overloadgroup/zz_version.go new file mode 100644 index 000000000000..a5d4e0946fc1 --- /dev/null +++ b/test/azure-http-specs/client/overloadgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package overloadgroup + +const ( + moduleName = "overloadgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/client/structure/clientopgroup/first_client_test.go b/test/azure-http-specs/client/structure/clientopgroup/first_client_test.go new file mode 100644 index 000000000000..e0b2e65b13bf --- /dev/null +++ b/test/azure-http-specs/client/structure/clientopgroup/first_client_test.go @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package clientopgroup_test + +import ( + "clientopgroup" + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestFirstClient_One(t *testing.T) { + client, err := clientopgroup.NewFirstClientWithNoCredential("http://localhost:3000", clientopgroup.ClientTypeClientOperationGroup, nil) + require.Nil(t, err) + require.NotNil(t, client) + resp, err := client.One(context.Background(), &clientopgroup.FirstClientOneOptions{}) + require.Nil(t, err) + require.NotNil(t, resp) +} diff --git a/test/azure-http-specs/client/structure/clientopgroup/firstgroup3_client_test.go b/test/azure-http-specs/client/structure/clientopgroup/firstgroup3_client_test.go new file mode 100644 index 000000000000..8da311bae9e1 --- /dev/null +++ b/test/azure-http-specs/client/structure/clientopgroup/firstgroup3_client_test.go @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package clientopgroup_test + +import ( + "clientopgroup" + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestFirstGroup3Client_Three(t *testing.T) { + client, err := clientopgroup.NewFirstClientWithNoCredential("http://localhost:3000", clientopgroup.ClientTypeClientOperationGroup, nil) + require.Nil(t, err) + require.NotNil(t, client) + resp, err := client.NewFirstGroup3Client().Three(context.Background(), &clientopgroup.FirstGroup3ClientThreeOptions{}) + require.Nil(t, err) + require.NotNil(t, resp) +} + +func TestFirstGroup3Client_Two(t *testing.T) { + client, err := clientopgroup.NewFirstClientWithNoCredential("http://localhost:3000", clientopgroup.ClientTypeClientOperationGroup, nil) + require.Nil(t, err) + require.NotNil(t, client) + resp, err := client.NewFirstGroup3Client().Two(context.Background(), &clientopgroup.FirstGroup3ClientTwoOptions{}) + require.Nil(t, err) + require.NotNil(t, resp) +} diff --git a/test/azure-http-specs/client/structure/clientopgroup/firstgroup4_client_test.go b/test/azure-http-specs/client/structure/clientopgroup/firstgroup4_client_test.go new file mode 100644 index 000000000000..821df88cc477 --- /dev/null +++ b/test/azure-http-specs/client/structure/clientopgroup/firstgroup4_client_test.go @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package clientopgroup_test + +import ( + "clientopgroup" + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestFirstGroup4Client_Four(t *testing.T) { + client, err := clientopgroup.NewFirstClientWithNoCredential("http://localhost:3000", clientopgroup.ClientTypeClientOperationGroup, nil) + require.Nil(t, err) + require.NotNil(t, client) + resp, err := client.NewFirstGroup4Client().Four(context.Background(), &clientopgroup.FirstGroup4ClientFourOptions{}) + require.Nil(t, err) + require.NotNil(t, resp) +} diff --git a/test/azure-http-specs/client/structure/clientopgroup/second_client_test.go b/test/azure-http-specs/client/structure/clientopgroup/second_client_test.go new file mode 100644 index 000000000000..12666179e9fa --- /dev/null +++ b/test/azure-http-specs/client/structure/clientopgroup/second_client_test.go @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package clientopgroup_test + +import ( + "clientopgroup" + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestSecondClientClient_Five(t *testing.T) { + client, err := clientopgroup.NewSecondClientWithNoCredential("http://localhost:3000", clientopgroup.ClientTypeClientOperationGroup, nil) + require.Nil(t, err) + require.NotNil(t, client) + resp, err := client.Five(context.Background(), &clientopgroup.SecondClientFiveOptions{}) + require.Nil(t, err) + require.NotNil(t, resp) +} diff --git a/test/azure-http-specs/client/structure/clientopgroup/secondgroup5_client_test.go b/test/azure-http-specs/client/structure/clientopgroup/secondgroup5_client_test.go new file mode 100644 index 000000000000..b36835912d83 --- /dev/null +++ b/test/azure-http-specs/client/structure/clientopgroup/secondgroup5_client_test.go @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package clientopgroup_test + +import ( + "clientopgroup" + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestSecondGroup5Client_Six(t *testing.T) { + client, err := clientopgroup.NewSecondClientWithNoCredential("http://localhost:3000", clientopgroup.ClientTypeClientOperationGroup, nil) + require.Nil(t, err) + require.NotNil(t, client) + resp, err := client.NewSecondGroup5Client().Six(context.Background(), &clientopgroup.SecondGroup5ClientSixOptions{}) + require.Nil(t, err) + require.NotNil(t, resp) +} diff --git a/test/azure-http-specs/client/structure/defaultgroup/LICENSE.txt b/test/azure-http-specs/client/structure/defaultgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/client/structure/defaultgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/client/structure/defaultgroup/fake/zz_internal.go b/test/azure-http-specs/client/structure/defaultgroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/azure-http-specs/client/structure/defaultgroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/azure-http-specs/client/structure/defaultgroup/fake/zz_service_server.go b/test/azure-http-specs/client/structure/defaultgroup/fake/zz_service_server.go new file mode 100644 index 000000000000..54f1a39dda6d --- /dev/null +++ b/test/azure-http-specs/client/structure/defaultgroup/fake/zz_service_server.go @@ -0,0 +1,171 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "defaultgroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "strings" + "sync" +) + +// ServiceServer is a fake server for instances of the defaultgroup.ServiceClient type. +type ServiceServer struct { + // ServiceBarServer contains the fakes for client ServiceBarClient + ServiceBarServer ServiceBarServer + + // ServiceFooServer contains the fakes for client ServiceFooClient + ServiceFooServer ServiceFooServer + + // ServiceQuxServer contains the fakes for client ServiceQuxClient + ServiceQuxServer ServiceQuxServer + + // One is the fake for method ServiceClient.One + // HTTP status codes to indicate success: http.StatusNoContent + One func(ctx context.Context, options *defaultgroup.ServiceClientOneOptions) (resp azfake.Responder[defaultgroup.ServiceClientOneResponse], errResp azfake.ErrorResponder) + + // Two is the fake for method ServiceClient.Two + // HTTP status codes to indicate success: http.StatusNoContent + Two func(ctx context.Context, options *defaultgroup.ServiceClientTwoOptions) (resp azfake.Responder[defaultgroup.ServiceClientTwoResponse], errResp azfake.ErrorResponder) +} + +// NewServiceServerTransport creates a new instance of ServiceServerTransport with the provided implementation. +// The returned ServiceServerTransport instance is connected to an instance of defaultgroup.ServiceClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServiceServerTransport(srv *ServiceServer) *ServiceServerTransport { + return &ServiceServerTransport{srv: srv} +} + +// ServiceServerTransport connects instances of defaultgroup.ServiceClient to instances of ServiceServer. +// Don't use this type directly, use NewServiceServerTransport instead. +type ServiceServerTransport struct { + srv *ServiceServer + trMu sync.Mutex + trServiceBarServer *ServiceBarServerTransport + trServiceFooServer *ServiceFooServerTransport + trServiceQuxServer *ServiceQuxServerTransport +} + +// Do implements the policy.Transporter interface for ServiceServerTransport. +func (s *ServiceServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + if client := method[:strings.Index(method, ".")]; client != "ServiceClient" { + return s.dispatchToClientFake(req, client) + } + return s.dispatchToMethodFake(req, method) +} + +func (s *ServiceServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "ServiceBarClient": + initServer(&s.trMu, &s.trServiceBarServer, func() *ServiceBarServerTransport { + return NewServiceBarServerTransport(&s.srv.ServiceBarServer) + }) + resp, err = s.trServiceBarServer.Do(req) + case "ServiceFooClient": + initServer(&s.trMu, &s.trServiceFooServer, func() *ServiceFooServerTransport { + return NewServiceFooServerTransport(&s.srv.ServiceFooServer) + }) + resp, err = s.trServiceFooServer.Do(req) + case "ServiceQuxClient", "ServiceQuxBarClient": + initServer(&s.trMu, &s.trServiceQuxServer, func() *ServiceQuxServerTransport { + return NewServiceQuxServerTransport(&s.srv.ServiceQuxServer) + }) + resp, err = s.trServiceQuxServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +func (s *ServiceServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if serviceServerTransportInterceptor != nil { + res.resp, res.err, intercepted = serviceServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ServiceClient.One": + res.resp, res.err = s.dispatchOne(req) + case "ServiceClient.Two": + res.resp, res.err = s.dispatchTwo(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ServiceServerTransport) dispatchOne(req *http.Request) (*http.Response, error) { + if s.srv.One == nil { + return nil, &nonRetriableError{errors.New("fake for method One not implemented")} + } + respr, errRespr := s.srv.One(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServiceServerTransport) dispatchTwo(req *http.Request) (*http.Response, error) { + if s.srv.Two == nil { + return nil, &nonRetriableError{errors.New("fake for method Two not implemented")} + } + respr, errRespr := s.srv.Two(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ServiceServerTransport +var serviceServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/client/structure/defaultgroup/fake/zz_servicebar_server.go b/test/azure-http-specs/client/structure/defaultgroup/fake/zz_servicebar_server.go new file mode 100644 index 000000000000..a84fd42b2f3d --- /dev/null +++ b/test/azure-http-specs/client/structure/defaultgroup/fake/zz_servicebar_server.go @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "defaultgroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// ServiceBarServer is a fake server for instances of the defaultgroup.ServiceBarClient type. +type ServiceBarServer struct { + // Five is the fake for method ServiceBarClient.Five + // HTTP status codes to indicate success: http.StatusNoContent + Five func(ctx context.Context, options *defaultgroup.ServiceBarClientFiveOptions) (resp azfake.Responder[defaultgroup.ServiceBarClientFiveResponse], errResp azfake.ErrorResponder) + + // Six is the fake for method ServiceBarClient.Six + // HTTP status codes to indicate success: http.StatusNoContent + Six func(ctx context.Context, options *defaultgroup.ServiceBarClientSixOptions) (resp azfake.Responder[defaultgroup.ServiceBarClientSixResponse], errResp azfake.ErrorResponder) +} + +// NewServiceBarServerTransport creates a new instance of ServiceBarServerTransport with the provided implementation. +// The returned ServiceBarServerTransport instance is connected to an instance of defaultgroup.ServiceBarClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServiceBarServerTransport(srv *ServiceBarServer) *ServiceBarServerTransport { + return &ServiceBarServerTransport{srv: srv} +} + +// ServiceBarServerTransport connects instances of defaultgroup.ServiceBarClient to instances of ServiceBarServer. +// Don't use this type directly, use NewServiceBarServerTransport instead. +type ServiceBarServerTransport struct { + srv *ServiceBarServer +} + +// Do implements the policy.Transporter interface for ServiceBarServerTransport. +func (s *ServiceBarServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ServiceBarServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if serviceBarServerTransportInterceptor != nil { + res.resp, res.err, intercepted = serviceBarServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ServiceBarClient.Five": + res.resp, res.err = s.dispatchFive(req) + case "ServiceBarClient.Six": + res.resp, res.err = s.dispatchSix(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ServiceBarServerTransport) dispatchFive(req *http.Request) (*http.Response, error) { + if s.srv.Five == nil { + return nil, &nonRetriableError{errors.New("fake for method Five not implemented")} + } + respr, errRespr := s.srv.Five(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServiceBarServerTransport) dispatchSix(req *http.Request) (*http.Response, error) { + if s.srv.Six == nil { + return nil, &nonRetriableError{errors.New("fake for method Six not implemented")} + } + respr, errRespr := s.srv.Six(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ServiceBarServerTransport +var serviceBarServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/client/structure/defaultgroup/fake/zz_servicebaz_server.go b/test/azure-http-specs/client/structure/defaultgroup/fake/zz_servicebaz_server.go new file mode 100644 index 000000000000..e623934cc363 --- /dev/null +++ b/test/azure-http-specs/client/structure/defaultgroup/fake/zz_servicebaz_server.go @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServiceBazServer is a fake server for instances of the defaultgroup.ServiceBazClient type. +type ServiceBazServer struct { + // ServiceBazFooServer contains the fakes for client ServiceBazFooClient + ServiceBazFooServer ServiceBazFooServer +} + +// NewServiceBazServerTransport creates a new instance of ServiceBazServerTransport with the provided implementation. +// The returned ServiceBazServerTransport instance is connected to an instance of defaultgroup.ServiceBazClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServiceBazServerTransport(srv *ServiceBazServer) *ServiceBazServerTransport { + return &ServiceBazServerTransport{srv: srv} +} + +// ServiceBazServerTransport connects instances of defaultgroup.ServiceBazClient to instances of ServiceBazServer. +// Don't use this type directly, use NewServiceBazServerTransport instead. +type ServiceBazServerTransport struct { + srv *ServiceBazServer + trMu sync.Mutex + trServiceBazFooServer *ServiceBazFooServerTransport +} + +// Do implements the policy.Transporter interface for ServiceBazServerTransport. +func (s *ServiceBazServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (s *ServiceBazServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "ServiceBazFooClient": + initServer(&s.trMu, &s.trServiceBazFooServer, func() *ServiceBazFooServerTransport { + return NewServiceBazFooServerTransport(&s.srv.ServiceBazFooServer) + }) + resp, err = s.trServiceBazFooServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to ServiceBazServerTransport +var serviceBazServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/client/structure/defaultgroup/fake/zz_servicebazfoo_server.go b/test/azure-http-specs/client/structure/defaultgroup/fake/zz_servicebazfoo_server.go new file mode 100644 index 000000000000..bb5a1ea0bd9f --- /dev/null +++ b/test/azure-http-specs/client/structure/defaultgroup/fake/zz_servicebazfoo_server.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "defaultgroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// ServiceBazFooServer is a fake server for instances of the defaultgroup.ServiceBazFooClient type. +type ServiceBazFooServer struct { + // Seven is the fake for method ServiceBazFooClient.Seven + // HTTP status codes to indicate success: http.StatusNoContent + Seven func(ctx context.Context, options *defaultgroup.ServiceBazFooClientSevenOptions) (resp azfake.Responder[defaultgroup.ServiceBazFooClientSevenResponse], errResp azfake.ErrorResponder) +} + +// NewServiceBazFooServerTransport creates a new instance of ServiceBazFooServerTransport with the provided implementation. +// The returned ServiceBazFooServerTransport instance is connected to an instance of defaultgroup.ServiceBazFooClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServiceBazFooServerTransport(srv *ServiceBazFooServer) *ServiceBazFooServerTransport { + return &ServiceBazFooServerTransport{srv: srv} +} + +// ServiceBazFooServerTransport connects instances of defaultgroup.ServiceBazFooClient to instances of ServiceBazFooServer. +// Don't use this type directly, use NewServiceBazFooServerTransport instead. +type ServiceBazFooServerTransport struct { + srv *ServiceBazFooServer +} + +// Do implements the policy.Transporter interface for ServiceBazFooServerTransport. +func (s *ServiceBazFooServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ServiceBazFooServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if serviceBazFooServerTransportInterceptor != nil { + res.resp, res.err, intercepted = serviceBazFooServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ServiceBazFooClient.Seven": + res.resp, res.err = s.dispatchSeven(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ServiceBazFooServerTransport) dispatchSeven(req *http.Request) (*http.Response, error) { + if s.srv.Seven == nil { + return nil, &nonRetriableError{errors.New("fake for method Seven not implemented")} + } + respr, errRespr := s.srv.Seven(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ServiceBazFooServerTransport +var serviceBazFooServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/client/structure/defaultgroup/fake/zz_servicefoo_server.go b/test/azure-http-specs/client/structure/defaultgroup/fake/zz_servicefoo_server.go new file mode 100644 index 000000000000..1f518844606b --- /dev/null +++ b/test/azure-http-specs/client/structure/defaultgroup/fake/zz_servicefoo_server.go @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "defaultgroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// ServiceFooServer is a fake server for instances of the defaultgroup.ServiceFooClient type. +type ServiceFooServer struct { + // Four is the fake for method ServiceFooClient.Four + // HTTP status codes to indicate success: http.StatusNoContent + Four func(ctx context.Context, options *defaultgroup.ServiceFooClientFourOptions) (resp azfake.Responder[defaultgroup.ServiceFooClientFourResponse], errResp azfake.ErrorResponder) + + // Three is the fake for method ServiceFooClient.Three + // HTTP status codes to indicate success: http.StatusNoContent + Three func(ctx context.Context, options *defaultgroup.ServiceFooClientThreeOptions) (resp azfake.Responder[defaultgroup.ServiceFooClientThreeResponse], errResp azfake.ErrorResponder) +} + +// NewServiceFooServerTransport creates a new instance of ServiceFooServerTransport with the provided implementation. +// The returned ServiceFooServerTransport instance is connected to an instance of defaultgroup.ServiceFooClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServiceFooServerTransport(srv *ServiceFooServer) *ServiceFooServerTransport { + return &ServiceFooServerTransport{srv: srv} +} + +// ServiceFooServerTransport connects instances of defaultgroup.ServiceFooClient to instances of ServiceFooServer. +// Don't use this type directly, use NewServiceFooServerTransport instead. +type ServiceFooServerTransport struct { + srv *ServiceFooServer +} + +// Do implements the policy.Transporter interface for ServiceFooServerTransport. +func (s *ServiceFooServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ServiceFooServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if serviceFooServerTransportInterceptor != nil { + res.resp, res.err, intercepted = serviceFooServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ServiceFooClient.Four": + res.resp, res.err = s.dispatchFour(req) + case "ServiceFooClient.Three": + res.resp, res.err = s.dispatchThree(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ServiceFooServerTransport) dispatchFour(req *http.Request) (*http.Response, error) { + if s.srv.Four == nil { + return nil, &nonRetriableError{errors.New("fake for method Four not implemented")} + } + respr, errRespr := s.srv.Four(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServiceFooServerTransport) dispatchThree(req *http.Request) (*http.Response, error) { + if s.srv.Three == nil { + return nil, &nonRetriableError{errors.New("fake for method Three not implemented")} + } + respr, errRespr := s.srv.Three(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ServiceFooServerTransport +var serviceFooServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/client/structure/defaultgroup/fake/zz_servicequx_server.go b/test/azure-http-specs/client/structure/defaultgroup/fake/zz_servicequx_server.go new file mode 100644 index 000000000000..ac01957f4208 --- /dev/null +++ b/test/azure-http-specs/client/structure/defaultgroup/fake/zz_servicequx_server.go @@ -0,0 +1,128 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "defaultgroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "strings" + "sync" +) + +// ServiceQuxServer is a fake server for instances of the defaultgroup.ServiceQuxClient type. +type ServiceQuxServer struct { + // ServiceQuxBarServer contains the fakes for client ServiceQuxBarClient + ServiceQuxBarServer ServiceQuxBarServer + + // Eight is the fake for method ServiceQuxClient.Eight + // HTTP status codes to indicate success: http.StatusNoContent + Eight func(ctx context.Context, options *defaultgroup.ServiceQuxClientEightOptions) (resp azfake.Responder[defaultgroup.ServiceQuxClientEightResponse], errResp azfake.ErrorResponder) +} + +// NewServiceQuxServerTransport creates a new instance of ServiceQuxServerTransport with the provided implementation. +// The returned ServiceQuxServerTransport instance is connected to an instance of defaultgroup.ServiceQuxClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServiceQuxServerTransport(srv *ServiceQuxServer) *ServiceQuxServerTransport { + return &ServiceQuxServerTransport{srv: srv} +} + +// ServiceQuxServerTransport connects instances of defaultgroup.ServiceQuxClient to instances of ServiceQuxServer. +// Don't use this type directly, use NewServiceQuxServerTransport instead. +type ServiceQuxServerTransport struct { + srv *ServiceQuxServer + trMu sync.Mutex + trServiceQuxBarServer *ServiceQuxBarServerTransport +} + +// Do implements the policy.Transporter interface for ServiceQuxServerTransport. +func (s *ServiceQuxServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + if client := method[:strings.Index(method, ".")]; client != "ServiceQuxClient" { + return s.dispatchToClientFake(req, client) + } + return s.dispatchToMethodFake(req, method) +} + +func (s *ServiceQuxServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "ServiceQuxBarClient": + initServer(&s.trMu, &s.trServiceQuxBarServer, func() *ServiceQuxBarServerTransport { + return NewServiceQuxBarServerTransport(&s.srv.ServiceQuxBarServer) + }) + resp, err = s.trServiceQuxBarServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +func (s *ServiceQuxServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if serviceQuxServerTransportInterceptor != nil { + res.resp, res.err, intercepted = serviceQuxServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ServiceQuxClient.Eight": + res.resp, res.err = s.dispatchEight(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ServiceQuxServerTransport) dispatchEight(req *http.Request) (*http.Response, error) { + if s.srv.Eight == nil { + return nil, &nonRetriableError{errors.New("fake for method Eight not implemented")} + } + respr, errRespr := s.srv.Eight(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ServiceQuxServerTransport +var serviceQuxServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/client/structure/defaultgroup/fake/zz_servicequxbar_server.go b/test/azure-http-specs/client/structure/defaultgroup/fake/zz_servicequxbar_server.go new file mode 100644 index 000000000000..4b6a76f3ea33 --- /dev/null +++ b/test/azure-http-specs/client/structure/defaultgroup/fake/zz_servicequxbar_server.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "defaultgroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// ServiceQuxBarServer is a fake server for instances of the defaultgroup.ServiceQuxBarClient type. +type ServiceQuxBarServer struct { + // Nine is the fake for method ServiceQuxBarClient.Nine + // HTTP status codes to indicate success: http.StatusNoContent + Nine func(ctx context.Context, options *defaultgroup.ServiceQuxBarClientNineOptions) (resp azfake.Responder[defaultgroup.ServiceQuxBarClientNineResponse], errResp azfake.ErrorResponder) +} + +// NewServiceQuxBarServerTransport creates a new instance of ServiceQuxBarServerTransport with the provided implementation. +// The returned ServiceQuxBarServerTransport instance is connected to an instance of defaultgroup.ServiceQuxBarClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServiceQuxBarServerTransport(srv *ServiceQuxBarServer) *ServiceQuxBarServerTransport { + return &ServiceQuxBarServerTransport{srv: srv} +} + +// ServiceQuxBarServerTransport connects instances of defaultgroup.ServiceQuxBarClient to instances of ServiceQuxBarServer. +// Don't use this type directly, use NewServiceQuxBarServerTransport instead. +type ServiceQuxBarServerTransport struct { + srv *ServiceQuxBarServer +} + +// Do implements the policy.Transporter interface for ServiceQuxBarServerTransport. +func (s *ServiceQuxBarServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ServiceQuxBarServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if serviceQuxBarServerTransportInterceptor != nil { + res.resp, res.err, intercepted = serviceQuxBarServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ServiceQuxBarClient.Nine": + res.resp, res.err = s.dispatchNine(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ServiceQuxBarServerTransport) dispatchNine(req *http.Request) (*http.Response, error) { + if s.srv.Nine == nil { + return nil, &nonRetriableError{errors.New("fake for method Nine not implemented")} + } + respr, errRespr := s.srv.Nine(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ServiceQuxBarServerTransport +var serviceQuxBarServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/client/structure/defaultgroup/go.mod b/test/azure-http-specs/client/structure/defaultgroup/go.mod new file mode 100644 index 000000000000..69a11e8b06c3 --- /dev/null +++ b/test/azure-http-specs/client/structure/defaultgroup/go.mod @@ -0,0 +1,17 @@ +module defaultgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/client/structure/defaultgroup/go.sum b/test/azure-http-specs/client/structure/defaultgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/client/structure/defaultgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/client/structure/defaultgroup/service_client_test.go b/test/azure-http-specs/client/structure/defaultgroup/service_client_test.go new file mode 100644 index 000000000000..40e79443d493 --- /dev/null +++ b/test/azure-http-specs/client/structure/defaultgroup/service_client_test.go @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package defaultgroup_test + +import ( + "context" + "defaultgroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestServiceClient_One(t *testing.T) { + client, err := defaultgroup.NewServiceClientWithNoCredential("http://localhost:3000", defaultgroup.ClientTypeDefault, nil) + require.NoError(t, err) + resp, err := client.One(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestServiceClient_Two(t *testing.T) { + client, err := defaultgroup.NewServiceClientWithNoCredential("http://localhost:3000", defaultgroup.ClientTypeDefault, nil) + require.NoError(t, err) + resp, err := client.Two(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/client/structure/defaultgroup/servicebar_client_test.go b/test/azure-http-specs/client/structure/defaultgroup/servicebar_client_test.go new file mode 100644 index 000000000000..7fb94d4ddf2a --- /dev/null +++ b/test/azure-http-specs/client/structure/defaultgroup/servicebar_client_test.go @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package defaultgroup_test + +import ( + "context" + "defaultgroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestServiceBarClient_Five(t *testing.T) { + client, err := defaultgroup.NewServiceClientWithNoCredential("http://localhost:3000", defaultgroup.ClientTypeDefault, nil) + require.NoError(t, err) + resp, err := client.NewServiceBarClient().Five(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestServiceBarClient_Nine(t *testing.T) { + client, err := defaultgroup.NewServiceClientWithNoCredential("http://localhost:3000", defaultgroup.ClientTypeDefault, nil) + require.NoError(t, err) + resp, err := client.NewServiceQuxClient().NewServiceQuxBarClient().Nine(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestServiceBarClient_Six(t *testing.T) { + client, err := defaultgroup.NewServiceClientWithNoCredential("http://localhost:3000", defaultgroup.ClientTypeDefault, nil) + require.NoError(t, err) + resp, err := client.NewServiceBarClient().Six(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/client/structure/defaultgroup/servicefoo_client_test.go b/test/azure-http-specs/client/structure/defaultgroup/servicefoo_client_test.go new file mode 100644 index 000000000000..17f419969e32 --- /dev/null +++ b/test/azure-http-specs/client/structure/defaultgroup/servicefoo_client_test.go @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package defaultgroup_test + +import ( + "context" + "defaultgroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestServiceFooClient_Four(t *testing.T) { + client, err := defaultgroup.NewServiceClientWithNoCredential("http://localhost:3000", defaultgroup.ClientTypeDefault, nil) + require.NoError(t, err) + resp, err := client.NewServiceFooClient().Four(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestServiceFooClient_Seven(t *testing.T) { + client, err := defaultgroup.NewServiceClientWithNoCredential("http://localhost:3000", defaultgroup.ClientTypeDefault, nil) + require.NoError(t, err) + resp, err := client.NewServiceBazClient().NewServiceBazFooClient().Seven(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestServiceFooClient_Three(t *testing.T) { + client, err := defaultgroup.NewServiceClientWithNoCredential("http://localhost:3000", defaultgroup.ClientTypeDefault, nil) + require.NoError(t, err) + resp, err := client.NewServiceFooClient().Three(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/client/structure/defaultgroup/servicequx_client_test.go b/test/azure-http-specs/client/structure/defaultgroup/servicequx_client_test.go new file mode 100644 index 000000000000..98efbcd9f86d --- /dev/null +++ b/test/azure-http-specs/client/structure/defaultgroup/servicequx_client_test.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package defaultgroup_test + +import ( + "context" + "defaultgroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestServiceQuxClient_Eight(t *testing.T) { + client, err := defaultgroup.NewServiceClientWithNoCredential("http://localhost:3000", defaultgroup.ClientTypeDefault, nil) + require.NoError(t, err) + resp, err := client.NewServiceQuxClient().Eight(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/client/structure/defaultgroup/testdata/_metadata.json b/test/azure-http-specs/client/structure/defaultgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/azure-http-specs/client/structure/defaultgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/client/structure/defaultgroup/zz_constants.go b/test/azure-http-specs/client/structure/defaultgroup/zz_constants.go new file mode 100644 index 000000000000..94917f892a91 --- /dev/null +++ b/test/azure-http-specs/client/structure/defaultgroup/zz_constants.go @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package defaultgroup + +type ClientType string + +const ( + ClientTypeClientOperationGroup ClientType = "client-operation-group" + ClientTypeDefault ClientType = "default" + ClientTypeMultiClient ClientType = "multi-client" + ClientTypeRenamedOperation ClientType = "renamed-operation" + ClientTypeTwoOperationGroup ClientType = "two-operation-group" +) + +// PossibleClientTypeValues returns the possible values for the ClientType const type. +func PossibleClientTypeValues() []ClientType { + return []ClientType{ + ClientTypeClientOperationGroup, + ClientTypeDefault, + ClientTypeMultiClient, + ClientTypeRenamedOperation, + ClientTypeTwoOperationGroup, + } +} diff --git a/test/azure-http-specs/client/structure/defaultgroup/zz_options.go b/test/azure-http-specs/client/structure/defaultgroup/zz_options.go new file mode 100644 index 000000000000..cd3aff9ff8c2 --- /dev/null +++ b/test/azure-http-specs/client/structure/defaultgroup/zz_options.go @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package defaultgroup + +// ServiceBarClientFiveOptions contains the optional parameters for the ServiceBarClient.Five method. +type ServiceBarClientFiveOptions struct { + // placeholder for future optional parameters +} + +// ServiceBarClientSixOptions contains the optional parameters for the ServiceBarClient.Six method. +type ServiceBarClientSixOptions struct { + // placeholder for future optional parameters +} + +// ServiceBazFooClientSevenOptions contains the optional parameters for the ServiceBazFooClient.Seven method. +type ServiceBazFooClientSevenOptions struct { + // placeholder for future optional parameters +} + +// ServiceClientOneOptions contains the optional parameters for the ServiceClient.One method. +type ServiceClientOneOptions struct { + // placeholder for future optional parameters +} + +// ServiceClientTwoOptions contains the optional parameters for the ServiceClient.Two method. +type ServiceClientTwoOptions struct { + // placeholder for future optional parameters +} + +// ServiceFooClientFourOptions contains the optional parameters for the ServiceFooClient.Four method. +type ServiceFooClientFourOptions struct { + // placeholder for future optional parameters +} + +// ServiceFooClientThreeOptions contains the optional parameters for the ServiceFooClient.Three method. +type ServiceFooClientThreeOptions struct { + // placeholder for future optional parameters +} + +// ServiceQuxBarClientNineOptions contains the optional parameters for the ServiceQuxBarClient.Nine method. +type ServiceQuxBarClientNineOptions struct { + // placeholder for future optional parameters +} + +// ServiceQuxClientEightOptions contains the optional parameters for the ServiceQuxClient.Eight method. +type ServiceQuxClientEightOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/client/structure/defaultgroup/zz_responses.go b/test/azure-http-specs/client/structure/defaultgroup/zz_responses.go new file mode 100644 index 000000000000..642241097653 --- /dev/null +++ b/test/azure-http-specs/client/structure/defaultgroup/zz_responses.go @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package defaultgroup + +// ServiceBarClientFiveResponse contains the response from method ServiceBarClient.Five. +type ServiceBarClientFiveResponse struct { + // placeholder for future response values +} + +// ServiceBarClientSixResponse contains the response from method ServiceBarClient.Six. +type ServiceBarClientSixResponse struct { + // placeholder for future response values +} + +// ServiceBazFooClientSevenResponse contains the response from method ServiceBazFooClient.Seven. +type ServiceBazFooClientSevenResponse struct { + // placeholder for future response values +} + +// ServiceClientOneResponse contains the response from method ServiceClient.One. +type ServiceClientOneResponse struct { + // placeholder for future response values +} + +// ServiceClientTwoResponse contains the response from method ServiceClient.Two. +type ServiceClientTwoResponse struct { + // placeholder for future response values +} + +// ServiceFooClientFourResponse contains the response from method ServiceFooClient.Four. +type ServiceFooClientFourResponse struct { + // placeholder for future response values +} + +// ServiceFooClientThreeResponse contains the response from method ServiceFooClient.Three. +type ServiceFooClientThreeResponse struct { + // placeholder for future response values +} + +// ServiceQuxBarClientNineResponse contains the response from method ServiceQuxBarClient.Nine. +type ServiceQuxBarClientNineResponse struct { + // placeholder for future response values +} + +// ServiceQuxClientEightResponse contains the response from method ServiceQuxClient.Eight. +type ServiceQuxClientEightResponse struct { + // placeholder for future response values +} diff --git a/test/azure-http-specs/client/structure/defaultgroup/zz_service_client.go b/test/azure-http-specs/client/structure/defaultgroup/zz_service_client.go new file mode 100644 index 000000000000..2e3a46fe68b3 --- /dev/null +++ b/test/azure-http-specs/client/structure/defaultgroup/zz_service_client.go @@ -0,0 +1,154 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package defaultgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// ServiceClient - Test that we can use @client decorators to customize client side code structure, such as: +// 1. have everything as default. +// 2. to rename client or operation group +// 3. one client can have more than one operations groups +// 4. split one interface into two clients +// 5. have two clients with operations come from different interfaces +// 6. have two clients with a hierarchy relation. +// Don't use this type directly, use NewServiceClientWithNoCredential() instead. +type ServiceClient struct { + internal *azcore.Client + endpoint string +} + +// ServiceClientOptions contains the optional values for creating a [ServiceClient]. +type ServiceClientOptions struct { + azcore.ClientOptions +} + +// NewServiceClientWithNoCredential creates a new instance of ServiceClient with the specified values. +// - endpoint - Service host +// - client - Need to be set as 'default', 'multi-client', 'renamed-operation', 'two-operation-group' in client. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewServiceClientWithNoCredential(endpoint string, client ClientType, options *ServiceClientOptions) (*ServiceClient, error) { + if options == nil { + options = &ServiceClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + host := "client/structure/{client}" + host = strings.ReplaceAll(host, "{client}", string(client)) + endpoint = runtime.JoinPaths(endpoint, host) + serviceClient := &ServiceClient{ + endpoint: endpoint, + internal: cl, + } + return serviceClient, nil +} + +// NewServiceBarClient creates a new instance of [ServiceBarClient]. +func (client *ServiceClient) NewServiceBarClient() *ServiceBarClient { + return &ServiceBarClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewServiceBazClient creates a new instance of [ServiceBazClient]. +func (client *ServiceClient) NewServiceBazClient() *ServiceBazClient { + return &ServiceBazClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewServiceFooClient creates a new instance of [ServiceFooClient]. +func (client *ServiceClient) NewServiceFooClient() *ServiceFooClient { + return &ServiceFooClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewServiceQuxClient creates a new instance of [ServiceQuxClient]. +func (client *ServiceClient) NewServiceQuxClient() *ServiceQuxClient { + return &ServiceQuxClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// One - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ServiceClientOneOptions contains the optional parameters for the ServiceClient.One method. +func (client *ServiceClient) One(ctx context.Context, options *ServiceClientOneOptions) (ServiceClientOneResponse, error) { + var err error + const operationName = "ServiceClient.One" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.oneCreateRequest(ctx, options) + if err != nil { + return ServiceClientOneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServiceClientOneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ServiceClientOneResponse{}, err + } + return ServiceClientOneResponse{}, nil +} + +// oneCreateRequest creates the One request. +func (client *ServiceClient) oneCreateRequest(ctx context.Context, _ *ServiceClientOneOptions) (*policy.Request, error) { + urlPath := "/one" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Two - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ServiceClientTwoOptions contains the optional parameters for the ServiceClient.Two method. +func (client *ServiceClient) Two(ctx context.Context, options *ServiceClientTwoOptions) (ServiceClientTwoResponse, error) { + var err error + const operationName = "ServiceClient.Two" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.twoCreateRequest(ctx, options) + if err != nil { + return ServiceClientTwoResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServiceClientTwoResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ServiceClientTwoResponse{}, err + } + return ServiceClientTwoResponse{}, nil +} + +// twoCreateRequest creates the Two request. +func (client *ServiceClient) twoCreateRequest(ctx context.Context, _ *ServiceClientTwoOptions) (*policy.Request, error) { + urlPath := "/two" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/client/structure/defaultgroup/zz_servicebar_client.go b/test/azure-http-specs/client/structure/defaultgroup/zz_servicebar_client.go new file mode 100644 index 000000000000..8731b75dd9d8 --- /dev/null +++ b/test/azure-http-specs/client/structure/defaultgroup/zz_servicebar_client.go @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package defaultgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ServiceBarClient contains the methods for the ServiceBar group. +// Don't use this type directly, use [ServiceClient.NewServiceBarClient] instead. +type ServiceBarClient struct { + internal *azcore.Client + endpoint string +} + +// Five - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ServiceBarClientFiveOptions contains the optional parameters for the ServiceBarClient.Five method. +func (client *ServiceBarClient) Five(ctx context.Context, options *ServiceBarClientFiveOptions) (ServiceBarClientFiveResponse, error) { + var err error + const operationName = "ServiceBarClient.Five" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.fiveCreateRequest(ctx, options) + if err != nil { + return ServiceBarClientFiveResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServiceBarClientFiveResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ServiceBarClientFiveResponse{}, err + } + return ServiceBarClientFiveResponse{}, nil +} + +// fiveCreateRequest creates the Five request. +func (client *ServiceBarClient) fiveCreateRequest(ctx context.Context, _ *ServiceBarClientFiveOptions) (*policy.Request, error) { + urlPath := "/five" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Six - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ServiceBarClientSixOptions contains the optional parameters for the ServiceBarClient.Six method. +func (client *ServiceBarClient) Six(ctx context.Context, options *ServiceBarClientSixOptions) (ServiceBarClientSixResponse, error) { + var err error + const operationName = "ServiceBarClient.Six" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.sixCreateRequest(ctx, options) + if err != nil { + return ServiceBarClientSixResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServiceBarClientSixResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ServiceBarClientSixResponse{}, err + } + return ServiceBarClientSixResponse{}, nil +} + +// sixCreateRequest creates the Six request. +func (client *ServiceBarClient) sixCreateRequest(ctx context.Context, _ *ServiceBarClientSixOptions) (*policy.Request, error) { + urlPath := "/six" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/client/structure/defaultgroup/zz_servicebaz_client.go b/test/azure-http-specs/client/structure/defaultgroup/zz_servicebaz_client.go new file mode 100644 index 000000000000..4bea961f5452 --- /dev/null +++ b/test/azure-http-specs/client/structure/defaultgroup/zz_servicebaz_client.go @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package defaultgroup + +import "github.com/Azure/azure-sdk-for-go/sdk/azcore" + +// ServiceBazClient contains the methods for the ServiceBaz group. +// Don't use this type directly, use [ServiceClient.NewServiceBazClient] instead. +type ServiceBazClient struct { + internal *azcore.Client + endpoint string +} + +// NewServiceBazFooClient creates a new instance of [ServiceBazFooClient]. +func (client *ServiceBazClient) NewServiceBazFooClient() *ServiceBazFooClient { + return &ServiceBazFooClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/azure-http-specs/client/structure/defaultgroup/zz_servicebazfoo_client.go b/test/azure-http-specs/client/structure/defaultgroup/zz_servicebazfoo_client.go new file mode 100644 index 000000000000..b7026c78bedc --- /dev/null +++ b/test/azure-http-specs/client/structure/defaultgroup/zz_servicebazfoo_client.go @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package defaultgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ServiceBazFooClient contains the methods for the ServiceBazFoo group. +// Don't use this type directly, use [ServiceBazClient.NewServiceBazFooClient] instead. +type ServiceBazFooClient struct { + internal *azcore.Client + endpoint string +} + +// Seven - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ServiceBazFooClientSevenOptions contains the optional parameters for the ServiceBazFooClient.Seven method. +func (client *ServiceBazFooClient) Seven(ctx context.Context, options *ServiceBazFooClientSevenOptions) (ServiceBazFooClientSevenResponse, error) { + var err error + const operationName = "ServiceBazFooClient.Seven" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.sevenCreateRequest(ctx, options) + if err != nil { + return ServiceBazFooClientSevenResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServiceBazFooClientSevenResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ServiceBazFooClientSevenResponse{}, err + } + return ServiceBazFooClientSevenResponse{}, nil +} + +// sevenCreateRequest creates the Seven request. +func (client *ServiceBazFooClient) sevenCreateRequest(ctx context.Context, _ *ServiceBazFooClientSevenOptions) (*policy.Request, error) { + urlPath := "/seven" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/client/structure/defaultgroup/zz_servicefoo_client.go b/test/azure-http-specs/client/structure/defaultgroup/zz_servicefoo_client.go new file mode 100644 index 000000000000..dded99f5178d --- /dev/null +++ b/test/azure-http-specs/client/structure/defaultgroup/zz_servicefoo_client.go @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package defaultgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ServiceFooClient contains the methods for the ServiceFoo group. +// Don't use this type directly, use [ServiceClient.NewServiceFooClient] instead. +type ServiceFooClient struct { + internal *azcore.Client + endpoint string +} + +// Four - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ServiceFooClientFourOptions contains the optional parameters for the ServiceFooClient.Four method. +func (client *ServiceFooClient) Four(ctx context.Context, options *ServiceFooClientFourOptions) (ServiceFooClientFourResponse, error) { + var err error + const operationName = "ServiceFooClient.Four" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.fourCreateRequest(ctx, options) + if err != nil { + return ServiceFooClientFourResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServiceFooClientFourResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ServiceFooClientFourResponse{}, err + } + return ServiceFooClientFourResponse{}, nil +} + +// fourCreateRequest creates the Four request. +func (client *ServiceFooClient) fourCreateRequest(ctx context.Context, _ *ServiceFooClientFourOptions) (*policy.Request, error) { + urlPath := "/four" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Three - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ServiceFooClientThreeOptions contains the optional parameters for the ServiceFooClient.Three method. +func (client *ServiceFooClient) Three(ctx context.Context, options *ServiceFooClientThreeOptions) (ServiceFooClientThreeResponse, error) { + var err error + const operationName = "ServiceFooClient.Three" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.threeCreateRequest(ctx, options) + if err != nil { + return ServiceFooClientThreeResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServiceFooClientThreeResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ServiceFooClientThreeResponse{}, err + } + return ServiceFooClientThreeResponse{}, nil +} + +// threeCreateRequest creates the Three request. +func (client *ServiceFooClient) threeCreateRequest(ctx context.Context, _ *ServiceFooClientThreeOptions) (*policy.Request, error) { + urlPath := "/three" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/client/structure/defaultgroup/zz_servicequx_client.go b/test/azure-http-specs/client/structure/defaultgroup/zz_servicequx_client.go new file mode 100644 index 000000000000..8ebd37509d08 --- /dev/null +++ b/test/azure-http-specs/client/structure/defaultgroup/zz_servicequx_client.go @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package defaultgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ServiceQuxClient contains the methods for the ServiceQux group. +// Don't use this type directly, use [ServiceClient.NewServiceQuxClient] instead. +type ServiceQuxClient struct { + internal *azcore.Client + endpoint string +} + +// NewServiceQuxBarClient creates a new instance of [ServiceQuxBarClient]. +func (client *ServiceQuxClient) NewServiceQuxBarClient() *ServiceQuxBarClient { + return &ServiceQuxBarClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// Eight - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ServiceQuxClientEightOptions contains the optional parameters for the ServiceQuxClient.Eight method. +func (client *ServiceQuxClient) Eight(ctx context.Context, options *ServiceQuxClientEightOptions) (ServiceQuxClientEightResponse, error) { + var err error + const operationName = "ServiceQuxClient.Eight" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.eightCreateRequest(ctx, options) + if err != nil { + return ServiceQuxClientEightResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServiceQuxClientEightResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ServiceQuxClientEightResponse{}, err + } + return ServiceQuxClientEightResponse{}, nil +} + +// eightCreateRequest creates the Eight request. +func (client *ServiceQuxClient) eightCreateRequest(ctx context.Context, _ *ServiceQuxClientEightOptions) (*policy.Request, error) { + urlPath := "/eight" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/client/structure/defaultgroup/zz_servicequxbar_client.go b/test/azure-http-specs/client/structure/defaultgroup/zz_servicequxbar_client.go new file mode 100644 index 000000000000..ff1372112356 --- /dev/null +++ b/test/azure-http-specs/client/structure/defaultgroup/zz_servicequxbar_client.go @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package defaultgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ServiceQuxBarClient contains the methods for the ServiceQuxBar group. +// Don't use this type directly, use [ServiceQuxClient.NewServiceQuxBarClient] instead. +type ServiceQuxBarClient struct { + internal *azcore.Client + endpoint string +} + +// Nine - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ServiceQuxBarClientNineOptions contains the optional parameters for the ServiceQuxBarClient.Nine method. +func (client *ServiceQuxBarClient) Nine(ctx context.Context, options *ServiceQuxBarClientNineOptions) (ServiceQuxBarClientNineResponse, error) { + var err error + const operationName = "ServiceQuxBarClient.Nine" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.nineCreateRequest(ctx, options) + if err != nil { + return ServiceQuxBarClientNineResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServiceQuxBarClientNineResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ServiceQuxBarClientNineResponse{}, err + } + return ServiceQuxBarClientNineResponse{}, nil +} + +// nineCreateRequest creates the Nine request. +func (client *ServiceQuxBarClient) nineCreateRequest(ctx context.Context, _ *ServiceQuxBarClientNineOptions) (*policy.Request, error) { + urlPath := "/nine" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/azure-http-specs/client/structure/defaultgroup/zz_version.go b/test/azure-http-specs/client/structure/defaultgroup/zz_version.go new file mode 100644 index 000000000000..f590d48d6a9b --- /dev/null +++ b/test/azure-http-specs/client/structure/defaultgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package defaultgroup + +const ( + moduleName = "defaultgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/client/structure/multiclientgroup/clienta_client_test.go b/test/azure-http-specs/client/structure/multiclientgroup/clienta_client_test.go new file mode 100644 index 000000000000..7e2496c4aace --- /dev/null +++ b/test/azure-http-specs/client/structure/multiclientgroup/clienta_client_test.go @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package multiclientgroup_test + +import ( + "context" + "multiclientgroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestClientAClient_RenamedFive(t *testing.T) { + client, err := multiclientgroup.NewClientAClientWithNoCredential("http://localhost:3000", multiclientgroup.ClientTypeMultiClient, nil) + require.NoError(t, err) + resp, err := client.RenamedFive(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestClientAClient_RenamedOne(t *testing.T) { + client, err := multiclientgroup.NewClientAClientWithNoCredential("http://localhost:3000", multiclientgroup.ClientTypeMultiClient, nil) + require.NoError(t, err) + resp, err := client.RenamedOne(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestClientAClient_RenamedThree(t *testing.T) { + client, err := multiclientgroup.NewClientAClientWithNoCredential("http://localhost:3000", multiclientgroup.ClientTypeMultiClient, nil) + require.NoError(t, err) + resp, err := client.RenamedThree(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/client/structure/multiclientgroup/clientb_client_test.go b/test/azure-http-specs/client/structure/multiclientgroup/clientb_client_test.go new file mode 100644 index 000000000000..fabcb32838ed --- /dev/null +++ b/test/azure-http-specs/client/structure/multiclientgroup/clientb_client_test.go @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package multiclientgroup_test + +import ( + "context" + "multiclientgroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestClientBClient_RenamedFour(t *testing.T) { + client, err := multiclientgroup.NewClientBClientWithNoCredential("http://localhost:3000", multiclientgroup.ClientTypeMultiClient, nil) + require.NoError(t, err) + resp, err := client.RenamedFour(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestClientBClient_RenamedSix(t *testing.T) { + client, err := multiclientgroup.NewClientBClientWithNoCredential("http://localhost:3000", multiclientgroup.ClientTypeMultiClient, nil) + require.NoError(t, err) + resp, err := client.RenamedSix(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestClientBClient_RenamedTwo(t *testing.T) { + client, err := multiclientgroup.NewClientBClientWithNoCredential("http://localhost:3000", multiclientgroup.ClientTypeMultiClient, nil) + require.NoError(t, err) + resp, err := client.RenamedTwo(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/client/structure/renamedopgroup/group_client_test.go b/test/azure-http-specs/client/structure/renamedopgroup/group_client_test.go new file mode 100644 index 000000000000..3e7349c17a98 --- /dev/null +++ b/test/azure-http-specs/client/structure/renamedopgroup/group_client_test.go @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package renamedopgroup_test + +import ( + "context" + "renamedopgroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestRenamedOperationGroupClient_RenamedFour(t *testing.T) { + client, err := renamedopgroup.NewRenamedOperationClientWithNoCredential("http://localhost:3000", renamedopgroup.ClientTypeRenamedOperation, nil) + require.NoError(t, err) + resp, err := client.NewRenamedOperationGroupClient().RenamedFour(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestRenamedOperationGroupClient_RenamedSix(t *testing.T) { + client, err := renamedopgroup.NewRenamedOperationClientWithNoCredential("http://localhost:3000", renamedopgroup.ClientTypeRenamedOperation, nil) + require.NoError(t, err) + resp, err := client.NewRenamedOperationGroupClient().RenamedSix(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestRenamedOperationGroupClient_RenamedTwo(t *testing.T) { + client, err := renamedopgroup.NewRenamedOperationClientWithNoCredential("http://localhost:3000", renamedopgroup.ClientTypeRenamedOperation, nil) + require.NoError(t, err) + resp, err := client.NewRenamedOperationGroupClient().RenamedTwo(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/client/structure/renamedopgroup/renamedoperation_client_test.go b/test/azure-http-specs/client/structure/renamedopgroup/renamedoperation_client_test.go new file mode 100644 index 000000000000..b5212d14a2f5 --- /dev/null +++ b/test/azure-http-specs/client/structure/renamedopgroup/renamedoperation_client_test.go @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package renamedopgroup_test + +import ( + "context" + "renamedopgroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestRenamedOperationClient_RenamedFive(t *testing.T) { + client, err := renamedopgroup.NewRenamedOperationClientWithNoCredential("http://localhost:3000", renamedopgroup.ClientTypeRenamedOperation, nil) + require.NoError(t, err) + resp, err := client.RenamedFive(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestRenamedOperationClient_RenamedOne(t *testing.T) { + client, err := renamedopgroup.NewRenamedOperationClientWithNoCredential("http://localhost:3000", renamedopgroup.ClientTypeRenamedOperation, nil) + require.NoError(t, err) + resp, err := client.RenamedOne(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestRenamedOperationClient_RenamedThree(t *testing.T) { + client, err := renamedopgroup.NewRenamedOperationClientWithNoCredential("http://localhost:3000", renamedopgroup.ClientTypeRenamedOperation, nil) + require.NoError(t, err) + resp, err := client.RenamedThree(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/client/structure/twoopgroup/group1_client_test.go b/test/azure-http-specs/client/structure/twoopgroup/group1_client_test.go new file mode 100644 index 000000000000..101c771fdb68 --- /dev/null +++ b/test/azure-http-specs/client/structure/twoopgroup/group1_client_test.go @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package twoopgroup_test + +import ( + "context" + "testing" + "twoopgroup" + + "github.com/stretchr/testify/require" +) + +func TestGroup1Client_Four(t *testing.T) { + client, err := twoopgroup.NewTwoOperationGroupClientWithNoCredential("http://localhost:3000", twoopgroup.ClientTypeTwoOperationGroup, nil) + require.NoError(t, err) + resp, err := client.NewTwoOperationGroupGroup1Client().Four(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestGroup1Client_One(t *testing.T) { + client, err := twoopgroup.NewTwoOperationGroupClientWithNoCredential("http://localhost:3000", twoopgroup.ClientTypeTwoOperationGroup, nil) + require.NoError(t, err) + resp, err := client.NewTwoOperationGroupGroup1Client().One(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestGroup1Client_Three(t *testing.T) { + client, err := twoopgroup.NewTwoOperationGroupClientWithNoCredential("http://localhost:3000", twoopgroup.ClientTypeTwoOperationGroup, nil) + require.NoError(t, err) + resp, err := client.NewTwoOperationGroupGroup1Client().Three(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/client/structure/twoopgroup/group2_client_test.go b/test/azure-http-specs/client/structure/twoopgroup/group2_client_test.go new file mode 100644 index 000000000000..f1363c178169 --- /dev/null +++ b/test/azure-http-specs/client/structure/twoopgroup/group2_client_test.go @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package twoopgroup_test + +import ( + "context" + "testing" + "twoopgroup" + + "github.com/stretchr/testify/require" +) + +func TestGroup2Client_Five(t *testing.T) { + client, err := twoopgroup.NewTwoOperationGroupClientWithNoCredential("http://localhost:3000", twoopgroup.ClientTypeTwoOperationGroup, nil) + require.NoError(t, err) + resp, err := client.NewTwoOperationGroupGroup2Client().Five(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestGroup2Client_Six(t *testing.T) { + client, err := twoopgroup.NewTwoOperationGroupClientWithNoCredential("http://localhost:3000", twoopgroup.ClientTypeTwoOperationGroup, nil) + require.NoError(t, err) + resp, err := client.NewTwoOperationGroupGroup2Client().Six(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestGroup2Client_Two(t *testing.T) { + client, err := twoopgroup.NewTwoOperationGroupClientWithNoCredential("http://localhost:3000", twoopgroup.ClientTypeTwoOperationGroup, nil) + require.NoError(t, err) + resp, err := client.NewTwoOperationGroupGroup2Client().Two(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/resiliency/srvdrivennewgroup/LICENSE.txt b/test/azure-http-specs/resiliency/srvdrivennewgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/resiliency/srvdrivennewgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/resiliency/srvdrivennewgroup/fake/zz_internal.go b/test/azure-http-specs/resiliency/srvdrivennewgroup/fake/zz_internal.go new file mode 100644 index 000000000000..53ec711308cc --- /dev/null +++ b/test/azure-http-specs/resiliency/srvdrivennewgroup/fake/zz_internal.go @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "reflect" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getOptional[T any](v T) *T { + if reflect.ValueOf(v).IsZero() { + return nil + } + return &v +} diff --git a/test/azure-http-specs/resiliency/srvdrivennewgroup/fake/zz_resiliencyservicedriven_server.go b/test/azure-http-specs/resiliency/srvdrivennewgroup/fake/zz_resiliencyservicedriven_server.go new file mode 100644 index 000000000000..26a325dedefc --- /dev/null +++ b/test/azure-http-specs/resiliency/srvdrivennewgroup/fake/zz_resiliencyservicedriven_server.go @@ -0,0 +1,202 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "srvdrivennewgroup" +) + +// ResiliencyServiceDrivenServer is a fake server for instances of the srvdrivennewgroup.ResiliencyServiceDrivenClient type. +type ResiliencyServiceDrivenServer struct { + // AddOperation is the fake for method ResiliencyServiceDrivenClient.AddOperation + // HTTP status codes to indicate success: http.StatusNoContent + AddOperation func(ctx context.Context, options *srvdrivennewgroup.ResiliencyServiceDrivenClientAddOperationOptions) (resp azfake.Responder[srvdrivennewgroup.ResiliencyServiceDrivenClientAddOperationResponse], errResp azfake.ErrorResponder) + + // FromNone is the fake for method ResiliencyServiceDrivenClient.FromNone + // HTTP status codes to indicate success: http.StatusNoContent + FromNone func(ctx context.Context, options *srvdrivennewgroup.ResiliencyServiceDrivenClientFromNoneOptions) (resp azfake.Responder[srvdrivennewgroup.ResiliencyServiceDrivenClientFromNoneResponse], errResp azfake.ErrorResponder) + + // FromOneOptional is the fake for method ResiliencyServiceDrivenClient.FromOneOptional + // HTTP status codes to indicate success: http.StatusNoContent + FromOneOptional func(ctx context.Context, options *srvdrivennewgroup.ResiliencyServiceDrivenClientFromOneOptionalOptions) (resp azfake.Responder[srvdrivennewgroup.ResiliencyServiceDrivenClientFromOneOptionalResponse], errResp azfake.ErrorResponder) + + // FromOneRequired is the fake for method ResiliencyServiceDrivenClient.FromOneRequired + // HTTP status codes to indicate success: http.StatusNoContent + FromOneRequired func(ctx context.Context, parameter string, options *srvdrivennewgroup.ResiliencyServiceDrivenClientFromOneRequiredOptions) (resp azfake.Responder[srvdrivennewgroup.ResiliencyServiceDrivenClientFromOneRequiredResponse], errResp azfake.ErrorResponder) +} + +// NewResiliencyServiceDrivenServerTransport creates a new instance of ResiliencyServiceDrivenServerTransport with the provided implementation. +// The returned ResiliencyServiceDrivenServerTransport instance is connected to an instance of srvdrivennewgroup.ResiliencyServiceDrivenClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewResiliencyServiceDrivenServerTransport(srv *ResiliencyServiceDrivenServer) *ResiliencyServiceDrivenServerTransport { + return &ResiliencyServiceDrivenServerTransport{srv: srv} +} + +// ResiliencyServiceDrivenServerTransport connects instances of srvdrivennewgroup.ResiliencyServiceDrivenClient to instances of ResiliencyServiceDrivenServer. +// Don't use this type directly, use NewResiliencyServiceDrivenServerTransport instead. +type ResiliencyServiceDrivenServerTransport struct { + srv *ResiliencyServiceDrivenServer +} + +// Do implements the policy.Transporter interface for ResiliencyServiceDrivenServerTransport. +func (r *ResiliencyServiceDrivenServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return r.dispatchToMethodFake(req, method) +} + +func (r *ResiliencyServiceDrivenServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if resiliencyServiceDrivenServerTransportInterceptor != nil { + res.resp, res.err, intercepted = resiliencyServiceDrivenServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ResiliencyServiceDrivenClient.AddOperation": + res.resp, res.err = r.dispatchAddOperation(req) + case "ResiliencyServiceDrivenClient.FromNone": + res.resp, res.err = r.dispatchFromNone(req) + case "ResiliencyServiceDrivenClient.FromOneOptional": + res.resp, res.err = r.dispatchFromOneOptional(req) + case "ResiliencyServiceDrivenClient.FromOneRequired": + res.resp, res.err = r.dispatchFromOneRequired(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (r *ResiliencyServiceDrivenServerTransport) dispatchAddOperation(req *http.Request) (*http.Response, error) { + if r.srv.AddOperation == nil { + return nil, &nonRetriableError{errors.New("fake for method AddOperation not implemented")} + } + respr, errRespr := r.srv.AddOperation(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (r *ResiliencyServiceDrivenServerTransport) dispatchFromNone(req *http.Request) (*http.Response, error) { + if r.srv.FromNone == nil { + return nil, &nonRetriableError{errors.New("fake for method FromNone not implemented")} + } + qp := req.URL.Query() + newParameterParam := getOptional(qp.Get("new-parameter")) + var options *srvdrivennewgroup.ResiliencyServiceDrivenClientFromNoneOptions + if newParameterParam != nil { + options = &srvdrivennewgroup.ResiliencyServiceDrivenClientFromNoneOptions{ + NewParameter: newParameterParam, + } + } + respr, errRespr := r.srv.FromNone(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (r *ResiliencyServiceDrivenServerTransport) dispatchFromOneOptional(req *http.Request) (*http.Response, error) { + if r.srv.FromOneOptional == nil { + return nil, &nonRetriableError{errors.New("fake for method FromOneOptional not implemented")} + } + qp := req.URL.Query() + parameterParam := getOptional(qp.Get("parameter")) + newParameterParam := getOptional(qp.Get("new-parameter")) + var options *srvdrivennewgroup.ResiliencyServiceDrivenClientFromOneOptionalOptions + if parameterParam != nil || newParameterParam != nil { + options = &srvdrivennewgroup.ResiliencyServiceDrivenClientFromOneOptionalOptions{ + Parameter: parameterParam, + NewParameter: newParameterParam, + } + } + respr, errRespr := r.srv.FromOneOptional(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (r *ResiliencyServiceDrivenServerTransport) dispatchFromOneRequired(req *http.Request) (*http.Response, error) { + if r.srv.FromOneRequired == nil { + return nil, &nonRetriableError{errors.New("fake for method FromOneRequired not implemented")} + } + qp := req.URL.Query() + newParameterParam := getOptional(qp.Get("new-parameter")) + var options *srvdrivennewgroup.ResiliencyServiceDrivenClientFromOneRequiredOptions + if newParameterParam != nil { + options = &srvdrivennewgroup.ResiliencyServiceDrivenClientFromOneRequiredOptions{ + NewParameter: newParameterParam, + } + } + respr, errRespr := r.srv.FromOneRequired(req.Context(), qp.Get("parameter"), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ResiliencyServiceDrivenServerTransport +var resiliencyServiceDrivenServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/resiliency/srvdrivennewgroup/go.mod b/test/azure-http-specs/resiliency/srvdrivennewgroup/go.mod new file mode 100644 index 000000000000..9f819cd80dfb --- /dev/null +++ b/test/azure-http-specs/resiliency/srvdrivennewgroup/go.mod @@ -0,0 +1,17 @@ +module srvdrivennewgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/resiliency/srvdrivennewgroup/go.sum b/test/azure-http-specs/resiliency/srvdrivennewgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/resiliency/srvdrivennewgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/resiliency/srvdrivennewgroup/resiliencyservicedriven_client_test.go b/test/azure-http-specs/resiliency/srvdrivennewgroup/resiliencyservicedriven_client_test.go new file mode 100644 index 000000000000..0d2f2c8cd10c --- /dev/null +++ b/test/azure-http-specs/resiliency/srvdrivennewgroup/resiliencyservicedriven_client_test.go @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package srvdrivennewgroup_test + +import ( + "context" + "srvdrivennewgroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestResiliencyServiceDrivenClientv2_AddOperation(t *testing.T) { + client, err := srvdrivennewgroup.NewResiliencyServiceDrivenClientWithNoCredential("http://localhost:3000", "v2", nil) + require.NoError(t, err) + resp, err := client.AddOperation(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestResiliencyServiceDrivenClientv1_FromNone(t *testing.T) { + client, err := srvdrivennewgroup.NewResiliencyServiceDrivenClientWithNoCredential("http://localhost:3000", "v2", &srvdrivennewgroup.ResiliencyServiceDrivenClientOptions{ + ClientOptions: azcore.ClientOptions{ + APIVersion: "v1", + }, + }) + require.NoError(t, err) + resp, err := client.FromNone(context.Background(), &srvdrivennewgroup.ResiliencyServiceDrivenClientFromNoneOptions{ + NewParameter: to.Ptr("new"), + }) + require.NoError(t, err) + require.True(t, resp.Success) +} + +func TestResiliencyServiceDrivenClientv1_FromOneOptional(t *testing.T) { + client, err := srvdrivennewgroup.NewResiliencyServiceDrivenClientWithNoCredential("http://localhost:3000", "v2", &srvdrivennewgroup.ResiliencyServiceDrivenClientOptions{ + ClientOptions: azcore.ClientOptions{ + APIVersion: "v1", + }, + }) + require.NoError(t, err) + resp, err := client.FromOneOptional(context.Background(), &srvdrivennewgroup.ResiliencyServiceDrivenClientFromOneOptionalOptions{ + NewParameter: to.Ptr("new"), + Parameter: to.Ptr("optional"), + }) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestResiliencyServiceDrivenClientv1_FromOneRequired(t *testing.T) { + client, err := srvdrivennewgroup.NewResiliencyServiceDrivenClientWithNoCredential("http://localhost:3000", "v2", &srvdrivennewgroup.ResiliencyServiceDrivenClientOptions{ + ClientOptions: azcore.ClientOptions{ + APIVersion: "v1", + }, + }) + require.NoError(t, err) + resp, err := client.FromOneRequired(context.Background(), "required", &srvdrivennewgroup.ResiliencyServiceDrivenClientFromOneRequiredOptions{ + NewParameter: to.Ptr("new"), + }) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestResiliencyServiceDrivenClientv2_FromNone(t *testing.T) { + client, err := srvdrivennewgroup.NewResiliencyServiceDrivenClientWithNoCredential("http://localhost:3000", "v2", nil) + require.NoError(t, err) + resp, err := client.FromNone(context.Background(), &srvdrivennewgroup.ResiliencyServiceDrivenClientFromNoneOptions{ + NewParameter: to.Ptr("new"), + }) + require.NoError(t, err) + require.True(t, resp.Success) +} + +func TestResiliencyServiceDrivenClientv2_FromOneOptional(t *testing.T) { + client, err := srvdrivennewgroup.NewResiliencyServiceDrivenClientWithNoCredential("http://localhost:3000", "v2", nil) + require.NoError(t, err) + resp, err := client.FromOneOptional(context.Background(), &srvdrivennewgroup.ResiliencyServiceDrivenClientFromOneOptionalOptions{ + NewParameter: to.Ptr("new"), + Parameter: to.Ptr("optional"), + }) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestResiliencyServiceDrivenClientv2_FromOneRequired(t *testing.T) { + client, err := srvdrivennewgroup.NewResiliencyServiceDrivenClientWithNoCredential("http://localhost:3000", "v2", nil) + require.NoError(t, err) + resp, err := client.FromOneRequired(context.Background(), "required", &srvdrivennewgroup.ResiliencyServiceDrivenClientFromOneRequiredOptions{ + NewParameter: to.Ptr("new"), + }) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/resiliency/srvdrivennewgroup/testdata/_metadata.json b/test/azure-http-specs/resiliency/srvdrivennewgroup/testdata/_metadata.json new file mode 100644 index 000000000000..65b918215eff --- /dev/null +++ b/test/azure-http-specs/resiliency/srvdrivennewgroup/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Resiliency.ServiceDriven": "v2" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/resiliency/srvdrivennewgroup/zz_options.go b/test/azure-http-specs/resiliency/srvdrivennewgroup/zz_options.go new file mode 100644 index 000000000000..4c27e2cb6c92 --- /dev/null +++ b/test/azure-http-specs/resiliency/srvdrivennewgroup/zz_options.go @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package srvdrivennewgroup + +// ResiliencyServiceDrivenClientAddOperationOptions contains the optional parameters for the ResiliencyServiceDrivenClient.AddOperation +// method. +type ResiliencyServiceDrivenClientAddOperationOptions struct { + // placeholder for future optional parameters +} + +// ResiliencyServiceDrivenClientFromNoneOptions contains the optional parameters for the ResiliencyServiceDrivenClient.FromNone +// method. +type ResiliencyServiceDrivenClientFromNoneOptions struct { + // I'm a new input optional parameter + NewParameter *string +} + +// ResiliencyServiceDrivenClientFromOneOptionalOptions contains the optional parameters for the ResiliencyServiceDrivenClient.FromOneOptional +// method. +type ResiliencyServiceDrivenClientFromOneOptionalOptions struct { + // I'm a new input optional parameter + NewParameter *string + + // I am an optional parameter + Parameter *string +} + +// ResiliencyServiceDrivenClientFromOneRequiredOptions contains the optional parameters for the ResiliencyServiceDrivenClient.FromOneRequired +// method. +type ResiliencyServiceDrivenClientFromOneRequiredOptions struct { + // I'm a new input optional parameter + NewParameter *string +} diff --git a/test/azure-http-specs/resiliency/srvdrivennewgroup/zz_resiliencyservicedriven_client.go b/test/azure-http-specs/resiliency/srvdrivennewgroup/zz_resiliencyservicedriven_client.go new file mode 100644 index 000000000000..203e86cef9d7 --- /dev/null +++ b/test/azure-http-specs/resiliency/srvdrivennewgroup/zz_resiliencyservicedriven_client.go @@ -0,0 +1,231 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package srvdrivennewgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// ResiliencyServiceDrivenClient - Test that we can grow up a service spec and service deployment into a multi-versioned service +// with full client support. +// There are three concepts that should be clarified: +// 1. Client spec version: refers to the spec that the client is generated from. 'v1' is a client generated from old.tsp and +// 'v2' is a client generated from main.tsp. +// 2. Service deployment version: refers to a deployment version of the service. 'v1' represents the initial deployment of +// the service with a single api version. 'v2' represents the new deployment of a service with multiple api versions +// 3. Api version: The initial deployment of the service only supports api version 'v1'. The new deployment of the service +// supports api versions 'v1' and 'v2'. +// We test the following configurations from this service spec: +// - A client generated from the second service spec can call the second deployment of a service with api version v1 +// - A client generated from the second service spec can call the second deployment of a service with api version v2 +// Don't use this type directly, use NewResiliencyServiceDrivenClientWithNoCredential() instead. +type ResiliencyServiceDrivenClient struct { + internal *azcore.Client + endpoint string +} + +// ResiliencyServiceDrivenClientOptions contains the optional values for creating a [ResiliencyServiceDrivenClient]. +type ResiliencyServiceDrivenClientOptions struct { + azcore.ClientOptions +} + +// NewResiliencyServiceDrivenClientWithNoCredential creates a new instance of ResiliencyServiceDrivenClient with the specified values. +// - endpoint - Service host +// - serviceDeploymentVersion - Pass in either 'v1' or 'v2'. This represents a version of the service deployment in history. +// 'v1' is for the deployment when the service had only one api version. 'v2' is for the deployment when the service had api-versions +// 'v1' and 'v2'. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewResiliencyServiceDrivenClientWithNoCredential(endpoint string, serviceDeploymentVersion string, options *ResiliencyServiceDrivenClientOptions) (*ResiliencyServiceDrivenClient, error) { + if options == nil { + options = &ResiliencyServiceDrivenClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{ + APIVersion: runtime.APIVersionOptions{ + Location: runtime.APIVersionLocationPath, + }, + }, &options.ClientOptions) + if err != nil { + return nil, err + } + apiVersion := "v2" + if options.APIVersion != "" { + apiVersion = options.APIVersion + } + host := "resiliency/service-driven/client:v2/service:{serviceDeploymentVersion}/api-version:{apiVersion}" + host = strings.ReplaceAll(host, "{serviceDeploymentVersion}", serviceDeploymentVersion) + host = strings.ReplaceAll(host, "{apiVersion}", apiVersion) + endpoint = runtime.JoinPaths(endpoint, host) + client := &ResiliencyServiceDrivenClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// AddOperation - Added operation +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ResiliencyServiceDrivenClientAddOperationOptions contains the optional parameters for the ResiliencyServiceDrivenClient.AddOperation +// method. +func (client *ResiliencyServiceDrivenClient) AddOperation(ctx context.Context, options *ResiliencyServiceDrivenClientAddOperationOptions) (ResiliencyServiceDrivenClientAddOperationResponse, error) { + var err error + const operationName = "ResiliencyServiceDrivenClient.AddOperation" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.addOperationCreateRequest(ctx, options) + if err != nil { + return ResiliencyServiceDrivenClientAddOperationResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ResiliencyServiceDrivenClientAddOperationResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ResiliencyServiceDrivenClientAddOperationResponse{}, err + } + return ResiliencyServiceDrivenClientAddOperationResponse{}, nil +} + +// addOperationCreateRequest creates the AddOperation request. +func (client *ResiliencyServiceDrivenClient) addOperationCreateRequest(ctx context.Context, _ *ResiliencyServiceDrivenClientAddOperationOptions) (*policy.Request, error) { + urlPath := "/add-operation" + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// FromNone - Test that grew up from accepting no parameters to an optional input parameter +// - options - ResiliencyServiceDrivenClientFromNoneOptions contains the optional parameters for the ResiliencyServiceDrivenClient.FromNone +// method. +func (client *ResiliencyServiceDrivenClient) FromNone(ctx context.Context, options *ResiliencyServiceDrivenClientFromNoneOptions) (ResiliencyServiceDrivenClientFromNoneResponse, error) { + var err error + const operationName = "ResiliencyServiceDrivenClient.FromNone" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.fromNoneCreateRequest(ctx, options) + if err != nil { + return ResiliencyServiceDrivenClientFromNoneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ResiliencyServiceDrivenClientFromNoneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ResiliencyServiceDrivenClientFromNoneResponse{}, err + } + return ResiliencyServiceDrivenClientFromNoneResponse{Success: httpResp.StatusCode >= 200 && httpResp.StatusCode < 300}, nil +} + +// fromNoneCreateRequest creates the FromNone request. +func (client *ResiliencyServiceDrivenClient) fromNoneCreateRequest(ctx context.Context, options *ResiliencyServiceDrivenClientFromNoneOptions) (*policy.Request, error) { + urlPath := "/add-optional-param/from-none" + req, err := runtime.NewRequest(ctx, http.MethodHead, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.NewParameter != nil { + reqQP.Set("new-parameter", *options.NewParameter) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// FromOneOptional - Tests that we can grow up an operation from accepting one optional parameter to accepting two optional +// parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ResiliencyServiceDrivenClientFromOneOptionalOptions contains the optional parameters for the ResiliencyServiceDrivenClient.FromOneOptional +// method. +func (client *ResiliencyServiceDrivenClient) FromOneOptional(ctx context.Context, options *ResiliencyServiceDrivenClientFromOneOptionalOptions) (ResiliencyServiceDrivenClientFromOneOptionalResponse, error) { + var err error + const operationName = "ResiliencyServiceDrivenClient.FromOneOptional" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.fromOneOptionalCreateRequest(ctx, options) + if err != nil { + return ResiliencyServiceDrivenClientFromOneOptionalResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ResiliencyServiceDrivenClientFromOneOptionalResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ResiliencyServiceDrivenClientFromOneOptionalResponse{}, err + } + return ResiliencyServiceDrivenClientFromOneOptionalResponse{}, nil +} + +// fromOneOptionalCreateRequest creates the FromOneOptional request. +func (client *ResiliencyServiceDrivenClient) fromOneOptionalCreateRequest(ctx context.Context, options *ResiliencyServiceDrivenClientFromOneOptionalOptions) (*policy.Request, error) { + urlPath := "/add-optional-param/from-one-optional" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.NewParameter != nil { + reqQP.Set("new-parameter", *options.NewParameter) + } + if options != nil && options.Parameter != nil { + reqQP.Set("parameter", *options.Parameter) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// FromOneRequired - Operation that grew up from accepting one required parameter to accepting a required parameter and an +// optional parameter. +// If the operation fails it returns an *azcore.ResponseError type. +// - parameter - I am a required parameter +// - options - ResiliencyServiceDrivenClientFromOneRequiredOptions contains the optional parameters for the ResiliencyServiceDrivenClient.FromOneRequired +// method. +func (client *ResiliencyServiceDrivenClient) FromOneRequired(ctx context.Context, parameter string, options *ResiliencyServiceDrivenClientFromOneRequiredOptions) (ResiliencyServiceDrivenClientFromOneRequiredResponse, error) { + var err error + const operationName = "ResiliencyServiceDrivenClient.FromOneRequired" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.fromOneRequiredCreateRequest(ctx, parameter, options) + if err != nil { + return ResiliencyServiceDrivenClientFromOneRequiredResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ResiliencyServiceDrivenClientFromOneRequiredResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ResiliencyServiceDrivenClientFromOneRequiredResponse{}, err + } + return ResiliencyServiceDrivenClientFromOneRequiredResponse{}, nil +} + +// fromOneRequiredCreateRequest creates the FromOneRequired request. +func (client *ResiliencyServiceDrivenClient) fromOneRequiredCreateRequest(ctx context.Context, parameter string, options *ResiliencyServiceDrivenClientFromOneRequiredOptions) (*policy.Request, error) { + urlPath := "/add-optional-param/from-one-required" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.NewParameter != nil { + reqQP.Set("new-parameter", *options.NewParameter) + } + reqQP.Set("parameter", parameter) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/azure-http-specs/resiliency/srvdrivennewgroup/zz_responses.go b/test/azure-http-specs/resiliency/srvdrivennewgroup/zz_responses.go new file mode 100644 index 000000000000..3eed45d5f24a --- /dev/null +++ b/test/azure-http-specs/resiliency/srvdrivennewgroup/zz_responses.go @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package srvdrivennewgroup + +// ResiliencyServiceDrivenClientAddOperationResponse contains the response from method ResiliencyServiceDrivenClient.AddOperation. +type ResiliencyServiceDrivenClientAddOperationResponse struct { + // placeholder for future response values +} + +// ResiliencyServiceDrivenClientFromNoneResponse contains the response from method ResiliencyServiceDrivenClient.FromNone. +type ResiliencyServiceDrivenClientFromNoneResponse struct { + // Success indicates if the operation succeeded or failed. + Success bool +} + +// ResiliencyServiceDrivenClientFromOneOptionalResponse contains the response from method ResiliencyServiceDrivenClient.FromOneOptional. +type ResiliencyServiceDrivenClientFromOneOptionalResponse struct { + // placeholder for future response values +} + +// ResiliencyServiceDrivenClientFromOneRequiredResponse contains the response from method ResiliencyServiceDrivenClient.FromOneRequired. +type ResiliencyServiceDrivenClientFromOneRequiredResponse struct { + // placeholder for future response values +} diff --git a/test/azure-http-specs/resiliency/srvdrivennewgroup/zz_version.go b/test/azure-http-specs/resiliency/srvdrivennewgroup/zz_version.go new file mode 100644 index 000000000000..87cae4d6cd6b --- /dev/null +++ b/test/azure-http-specs/resiliency/srvdrivennewgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package srvdrivennewgroup + +const ( + moduleName = "srvdrivennewgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/resiliency/srvdrivenoldgroup/LICENSE.txt b/test/azure-http-specs/resiliency/srvdrivenoldgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/resiliency/srvdrivenoldgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/resiliency/srvdrivenoldgroup/fake/zz_internal.go b/test/azure-http-specs/resiliency/srvdrivenoldgroup/fake/zz_internal.go new file mode 100644 index 000000000000..53ec711308cc --- /dev/null +++ b/test/azure-http-specs/resiliency/srvdrivenoldgroup/fake/zz_internal.go @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "reflect" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getOptional[T any](v T) *T { + if reflect.ValueOf(v).IsZero() { + return nil + } + return &v +} diff --git a/test/azure-http-specs/resiliency/srvdrivenoldgroup/fake/zz_resiliencyservicedriven_server.go b/test/azure-http-specs/resiliency/srvdrivenoldgroup/fake/zz_resiliencyservicedriven_server.go new file mode 100644 index 000000000000..65ca735b1f4a --- /dev/null +++ b/test/azure-http-specs/resiliency/srvdrivenoldgroup/fake/zz_resiliencyservicedriven_server.go @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "srvdrivenoldgroup" +) + +// ResiliencyServiceDrivenServer is a fake server for instances of the srvdrivenoldgroup.ResiliencyServiceDrivenClient type. +type ResiliencyServiceDrivenServer struct { + // FromNone is the fake for method ResiliencyServiceDrivenClient.FromNone + // HTTP status codes to indicate success: http.StatusNoContent + FromNone func(ctx context.Context, options *srvdrivenoldgroup.ResiliencyServiceDrivenClientFromNoneOptions) (resp azfake.Responder[srvdrivenoldgroup.ResiliencyServiceDrivenClientFromNoneResponse], errResp azfake.ErrorResponder) + + // FromOneOptional is the fake for method ResiliencyServiceDrivenClient.FromOneOptional + // HTTP status codes to indicate success: http.StatusNoContent + FromOneOptional func(ctx context.Context, options *srvdrivenoldgroup.ResiliencyServiceDrivenClientFromOneOptionalOptions) (resp azfake.Responder[srvdrivenoldgroup.ResiliencyServiceDrivenClientFromOneOptionalResponse], errResp azfake.ErrorResponder) + + // FromOneRequired is the fake for method ResiliencyServiceDrivenClient.FromOneRequired + // HTTP status codes to indicate success: http.StatusNoContent + FromOneRequired func(ctx context.Context, parameter string, options *srvdrivenoldgroup.ResiliencyServiceDrivenClientFromOneRequiredOptions) (resp azfake.Responder[srvdrivenoldgroup.ResiliencyServiceDrivenClientFromOneRequiredResponse], errResp azfake.ErrorResponder) +} + +// NewResiliencyServiceDrivenServerTransport creates a new instance of ResiliencyServiceDrivenServerTransport with the provided implementation. +// The returned ResiliencyServiceDrivenServerTransport instance is connected to an instance of srvdrivenoldgroup.ResiliencyServiceDrivenClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewResiliencyServiceDrivenServerTransport(srv *ResiliencyServiceDrivenServer) *ResiliencyServiceDrivenServerTransport { + return &ResiliencyServiceDrivenServerTransport{srv: srv} +} + +// ResiliencyServiceDrivenServerTransport connects instances of srvdrivenoldgroup.ResiliencyServiceDrivenClient to instances of ResiliencyServiceDrivenServer. +// Don't use this type directly, use NewResiliencyServiceDrivenServerTransport instead. +type ResiliencyServiceDrivenServerTransport struct { + srv *ResiliencyServiceDrivenServer +} + +// Do implements the policy.Transporter interface for ResiliencyServiceDrivenServerTransport. +func (r *ResiliencyServiceDrivenServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return r.dispatchToMethodFake(req, method) +} + +func (r *ResiliencyServiceDrivenServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if resiliencyServiceDrivenServerTransportInterceptor != nil { + res.resp, res.err, intercepted = resiliencyServiceDrivenServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ResiliencyServiceDrivenClient.FromNone": + res.resp, res.err = r.dispatchFromNone(req) + case "ResiliencyServiceDrivenClient.FromOneOptional": + res.resp, res.err = r.dispatchFromOneOptional(req) + case "ResiliencyServiceDrivenClient.FromOneRequired": + res.resp, res.err = r.dispatchFromOneRequired(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (r *ResiliencyServiceDrivenServerTransport) dispatchFromNone(req *http.Request) (*http.Response, error) { + if r.srv.FromNone == nil { + return nil, &nonRetriableError{errors.New("fake for method FromNone not implemented")} + } + respr, errRespr := r.srv.FromNone(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (r *ResiliencyServiceDrivenServerTransport) dispatchFromOneOptional(req *http.Request) (*http.Response, error) { + if r.srv.FromOneOptional == nil { + return nil, &nonRetriableError{errors.New("fake for method FromOneOptional not implemented")} + } + qp := req.URL.Query() + parameterParam := getOptional(qp.Get("parameter")) + var options *srvdrivenoldgroup.ResiliencyServiceDrivenClientFromOneOptionalOptions + if parameterParam != nil { + options = &srvdrivenoldgroup.ResiliencyServiceDrivenClientFromOneOptionalOptions{ + Parameter: parameterParam, + } + } + respr, errRespr := r.srv.FromOneOptional(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (r *ResiliencyServiceDrivenServerTransport) dispatchFromOneRequired(req *http.Request) (*http.Response, error) { + if r.srv.FromOneRequired == nil { + return nil, &nonRetriableError{errors.New("fake for method FromOneRequired not implemented")} + } + qp := req.URL.Query() + respr, errRespr := r.srv.FromOneRequired(req.Context(), qp.Get("parameter"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ResiliencyServiceDrivenServerTransport +var resiliencyServiceDrivenServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/resiliency/srvdrivenoldgroup/go.mod b/test/azure-http-specs/resiliency/srvdrivenoldgroup/go.mod new file mode 100644 index 000000000000..eb180a051e2f --- /dev/null +++ b/test/azure-http-specs/resiliency/srvdrivenoldgroup/go.mod @@ -0,0 +1,17 @@ +module srvdrivenoldgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/resiliency/srvdrivenoldgroup/go.sum b/test/azure-http-specs/resiliency/srvdrivenoldgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/resiliency/srvdrivenoldgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/resiliency/srvdrivenoldgroup/resiliencyservicedriven_client_test.go b/test/azure-http-specs/resiliency/srvdrivenoldgroup/resiliencyservicedriven_client_test.go new file mode 100644 index 000000000000..210c0048db8f --- /dev/null +++ b/test/azure-http-specs/resiliency/srvdrivenoldgroup/resiliencyservicedriven_client_test.go @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package srvdrivenoldgroup_test + +import ( + "context" + "srvdrivenoldgroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestResiliencyServiceDrivenClientv1_FromNone(t *testing.T) { + client, err := srvdrivenoldgroup.NewResiliencyServiceDrivenClientWithNoCredential("http://localhost:3000", "v1", nil) + require.NoError(t, err) + resp, err := client.FromNone(context.Background(), nil) + require.NoError(t, err) + require.True(t, resp.Success) +} + +func TestResiliencyServiceDrivenClientv1_FromOneOptional(t *testing.T) { + client, err := srvdrivenoldgroup.NewResiliencyServiceDrivenClientWithNoCredential("http://localhost:3000", "v1", nil) + require.NoError(t, err) + resp, err := client.FromOneOptional(context.Background(), &srvdrivenoldgroup.ResiliencyServiceDrivenClientFromOneOptionalOptions{ + Parameter: to.Ptr("optional"), + }) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestResiliencyServiceDrivenClientv1_FromOneRequired(t *testing.T) { + client, err := srvdrivenoldgroup.NewResiliencyServiceDrivenClientWithNoCredential("http://localhost:3000", "v1", nil) + require.NoError(t, err) + resp, err := client.FromOneRequired(context.Background(), "required", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestResiliencyServiceDrivenClientv2_FromNone(t *testing.T) { + client, err := srvdrivenoldgroup.NewResiliencyServiceDrivenClientWithNoCredential("http://localhost:3000", "v2", nil) + require.NoError(t, err) + resp, err := client.FromNone(context.Background(), nil) + require.NoError(t, err) + require.True(t, resp.Success) +} + +func TestResiliencyServiceDrivenClientv2_FromOneOptional(t *testing.T) { + client, err := srvdrivenoldgroup.NewResiliencyServiceDrivenClientWithNoCredential("http://localhost:3000", "v2", nil) + require.NoError(t, err) + resp, err := client.FromOneOptional(context.Background(), &srvdrivenoldgroup.ResiliencyServiceDrivenClientFromOneOptionalOptions{ + Parameter: to.Ptr("optional"), + }) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestResiliencyServiceDrivenClientv2_FromOneRequired(t *testing.T) { + client, err := srvdrivenoldgroup.NewResiliencyServiceDrivenClientWithNoCredential("http://localhost:3000", "v2", nil) + require.NoError(t, err) + resp, err := client.FromOneRequired(context.Background(), "required", nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/azure-http-specs/resiliency/srvdrivenoldgroup/testdata/_metadata.json b/test/azure-http-specs/resiliency/srvdrivenoldgroup/testdata/_metadata.json new file mode 100644 index 000000000000..28a462abcce0 --- /dev/null +++ b/test/azure-http-specs/resiliency/srvdrivenoldgroup/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Resiliency.ServiceDriven": "v1" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/resiliency/srvdrivenoldgroup/zz_options.go b/test/azure-http-specs/resiliency/srvdrivenoldgroup/zz_options.go new file mode 100644 index 000000000000..06451d245fb3 --- /dev/null +++ b/test/azure-http-specs/resiliency/srvdrivenoldgroup/zz_options.go @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package srvdrivenoldgroup + +// ResiliencyServiceDrivenClientFromNoneOptions contains the optional parameters for the ResiliencyServiceDrivenClient.FromNone +// method. +type ResiliencyServiceDrivenClientFromNoneOptions struct { + // placeholder for future optional parameters +} + +// ResiliencyServiceDrivenClientFromOneOptionalOptions contains the optional parameters for the ResiliencyServiceDrivenClient.FromOneOptional +// method. +type ResiliencyServiceDrivenClientFromOneOptionalOptions struct { + // I am an optional parameter + Parameter *string +} + +// ResiliencyServiceDrivenClientFromOneRequiredOptions contains the optional parameters for the ResiliencyServiceDrivenClient.FromOneRequired +// method. +type ResiliencyServiceDrivenClientFromOneRequiredOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/resiliency/srvdrivenoldgroup/zz_resiliencyservicedriven_client.go b/test/azure-http-specs/resiliency/srvdrivenoldgroup/zz_resiliencyservicedriven_client.go new file mode 100644 index 000000000000..6413a3fc3fe3 --- /dev/null +++ b/test/azure-http-specs/resiliency/srvdrivenoldgroup/zz_resiliencyservicedriven_client.go @@ -0,0 +1,176 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package srvdrivenoldgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// ResiliencyServiceDrivenClient - Test that we can grow up a service spec and service deployment into a multi-versioned service +// with full client support. +// Don't use this type directly, use NewResiliencyServiceDrivenClientWithNoCredential() instead. +type ResiliencyServiceDrivenClient struct { + internal *azcore.Client + endpoint string +} + +// ResiliencyServiceDrivenClientOptions contains the optional values for creating a [ResiliencyServiceDrivenClient]. +type ResiliencyServiceDrivenClientOptions struct { + azcore.ClientOptions +} + +// NewResiliencyServiceDrivenClientWithNoCredential creates a new instance of ResiliencyServiceDrivenClient with the specified values. +// - endpoint - Service host +// - serviceDeploymentVersion - Pass in either 'v1' or 'v2'. This represents a version of the service deployment in history. +// 'v1' is for the deployment when the service had only one api version. 'v2' is for the deployment when the service had api-versions +// 'v1' and 'v2'. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewResiliencyServiceDrivenClientWithNoCredential(endpoint string, serviceDeploymentVersion string, options *ResiliencyServiceDrivenClientOptions) (*ResiliencyServiceDrivenClient, error) { + if options == nil { + options = &ResiliencyServiceDrivenClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{ + APIVersion: runtime.APIVersionOptions{ + Location: runtime.APIVersionLocationPath, + }, + }, &options.ClientOptions) + if err != nil { + return nil, err + } + apiVersion := "v1" + if options.APIVersion != "" { + apiVersion = options.APIVersion + } + host := "resiliency/service-driven/client:v1/service:{serviceDeploymentVersion}/api-version:{apiVersion}" + host = strings.ReplaceAll(host, "{serviceDeploymentVersion}", serviceDeploymentVersion) + host = strings.ReplaceAll(host, "{apiVersion}", apiVersion) + endpoint = runtime.JoinPaths(endpoint, host) + client := &ResiliencyServiceDrivenClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// FromNone - Test that currently accepts no parameters, will be updated in next spec to accept a new optional parameter as +// well +// - options - ResiliencyServiceDrivenClientFromNoneOptions contains the optional parameters for the ResiliencyServiceDrivenClient.FromNone +// method. +func (client *ResiliencyServiceDrivenClient) FromNone(ctx context.Context, options *ResiliencyServiceDrivenClientFromNoneOptions) (ResiliencyServiceDrivenClientFromNoneResponse, error) { + var err error + const operationName = "ResiliencyServiceDrivenClient.FromNone" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.fromNoneCreateRequest(ctx, options) + if err != nil { + return ResiliencyServiceDrivenClientFromNoneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ResiliencyServiceDrivenClientFromNoneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ResiliencyServiceDrivenClientFromNoneResponse{}, err + } + return ResiliencyServiceDrivenClientFromNoneResponse{Success: httpResp.StatusCode >= 200 && httpResp.StatusCode < 300}, nil +} + +// fromNoneCreateRequest creates the FromNone request. +func (client *ResiliencyServiceDrivenClient) fromNoneCreateRequest(ctx context.Context, _ *ResiliencyServiceDrivenClientFromNoneOptions) (*policy.Request, error) { + urlPath := "/add-optional-param/from-none" + req, err := runtime.NewRequest(ctx, http.MethodHead, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// FromOneOptional - Test that currently accepts one optional parameter, will be updated in next spec to accept a new optional +// parameter as well +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ResiliencyServiceDrivenClientFromOneOptionalOptions contains the optional parameters for the ResiliencyServiceDrivenClient.FromOneOptional +// method. +func (client *ResiliencyServiceDrivenClient) FromOneOptional(ctx context.Context, options *ResiliencyServiceDrivenClientFromOneOptionalOptions) (ResiliencyServiceDrivenClientFromOneOptionalResponse, error) { + var err error + const operationName = "ResiliencyServiceDrivenClient.FromOneOptional" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.fromOneOptionalCreateRequest(ctx, options) + if err != nil { + return ResiliencyServiceDrivenClientFromOneOptionalResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ResiliencyServiceDrivenClientFromOneOptionalResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ResiliencyServiceDrivenClientFromOneOptionalResponse{}, err + } + return ResiliencyServiceDrivenClientFromOneOptionalResponse{}, nil +} + +// fromOneOptionalCreateRequest creates the FromOneOptional request. +func (client *ResiliencyServiceDrivenClient) fromOneOptionalCreateRequest(ctx context.Context, options *ResiliencyServiceDrivenClientFromOneOptionalOptions) (*policy.Request, error) { + urlPath := "/add-optional-param/from-one-optional" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Parameter != nil { + reqQP.Set("parameter", *options.Parameter) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// FromOneRequired - Test that currently accepts one required parameter, will be updated in next spec to accept a new optional +// parameter as well +// If the operation fails it returns an *azcore.ResponseError type. +// - parameter - I am a required parameter +// - options - ResiliencyServiceDrivenClientFromOneRequiredOptions contains the optional parameters for the ResiliencyServiceDrivenClient.FromOneRequired +// method. +func (client *ResiliencyServiceDrivenClient) FromOneRequired(ctx context.Context, parameter string, options *ResiliencyServiceDrivenClientFromOneRequiredOptions) (ResiliencyServiceDrivenClientFromOneRequiredResponse, error) { + var err error + const operationName = "ResiliencyServiceDrivenClient.FromOneRequired" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.fromOneRequiredCreateRequest(ctx, parameter, options) + if err != nil { + return ResiliencyServiceDrivenClientFromOneRequiredResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ResiliencyServiceDrivenClientFromOneRequiredResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ResiliencyServiceDrivenClientFromOneRequiredResponse{}, err + } + return ResiliencyServiceDrivenClientFromOneRequiredResponse{}, nil +} + +// fromOneRequiredCreateRequest creates the FromOneRequired request. +func (client *ResiliencyServiceDrivenClient) fromOneRequiredCreateRequest(ctx context.Context, parameter string, _ *ResiliencyServiceDrivenClientFromOneRequiredOptions) (*policy.Request, error) { + urlPath := "/add-optional-param/from-one-required" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("parameter", parameter) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/azure-http-specs/resiliency/srvdrivenoldgroup/zz_responses.go b/test/azure-http-specs/resiliency/srvdrivenoldgroup/zz_responses.go new file mode 100644 index 000000000000..17e06b934a04 --- /dev/null +++ b/test/azure-http-specs/resiliency/srvdrivenoldgroup/zz_responses.go @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package srvdrivenoldgroup + +// ResiliencyServiceDrivenClientFromNoneResponse contains the response from method ResiliencyServiceDrivenClient.FromNone. +type ResiliencyServiceDrivenClientFromNoneResponse struct { + // Success indicates if the operation succeeded or failed. + Success bool +} + +// ResiliencyServiceDrivenClientFromOneOptionalResponse contains the response from method ResiliencyServiceDrivenClient.FromOneOptional. +type ResiliencyServiceDrivenClientFromOneOptionalResponse struct { + // placeholder for future response values +} + +// ResiliencyServiceDrivenClientFromOneRequiredResponse contains the response from method ResiliencyServiceDrivenClient.FromOneRequired. +type ResiliencyServiceDrivenClientFromOneRequiredResponse struct { + // placeholder for future response values +} diff --git a/test/azure-http-specs/resiliency/srvdrivenoldgroup/zz_version.go b/test/azure-http-specs/resiliency/srvdrivenoldgroup/zz_version.go new file mode 100644 index 000000000000..347e406a1805 --- /dev/null +++ b/test/azure-http-specs/resiliency/srvdrivenoldgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package srvdrivenoldgroup + +const ( + moduleName = "srvdrivenoldgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/service/multipleservicesgroup/LICENSE.txt b/test/azure-http-specs/service/multipleservicesgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/service/multipleservicesgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/service/multipleservicesgroup/fake/zz_internal.go b/test/azure-http-specs/service/multipleservicesgroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/azure-http-specs/service/multipleservicesgroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/azure-http-specs/service/multipleservicesgroup/fake/zz_servicea_server.go b/test/azure-http-specs/service/multipleservicesgroup/fake/zz_servicea_server.go new file mode 100644 index 000000000000..df7e4f267e5e --- /dev/null +++ b/test/azure-http-specs/service/multipleservicesgroup/fake/zz_servicea_server.go @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServiceAServer is a fake server for instances of the multipleservicesgroup.ServiceAClient type. +type ServiceAServer struct { + // ServiceAOperationsServer contains the fakes for client ServiceAOperationsClient + ServiceAOperationsServer ServiceAOperationsServer + + // ServiceASubNamespaceServer contains the fakes for client ServiceASubNamespaceClient + ServiceASubNamespaceServer ServiceASubNamespaceServer +} + +// NewServiceAServerTransport creates a new instance of ServiceAServerTransport with the provided implementation. +// The returned ServiceAServerTransport instance is connected to an instance of multipleservicesgroup.ServiceAClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServiceAServerTransport(srv *ServiceAServer) *ServiceAServerTransport { + return &ServiceAServerTransport{srv: srv} +} + +// ServiceAServerTransport connects instances of multipleservicesgroup.ServiceAClient to instances of ServiceAServer. +// Don't use this type directly, use NewServiceAServerTransport instead. +type ServiceAServerTransport struct { + srv *ServiceAServer + trMu sync.Mutex + trServiceAOperationsServer *ServiceAOperationsServerTransport + trServiceASubNamespaceServer *ServiceASubNamespaceServerTransport +} + +// Do implements the policy.Transporter interface for ServiceAServerTransport. +func (s *ServiceAServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (s *ServiceAServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "ServiceAOperationsClient": + initServer(&s.trMu, &s.trServiceAOperationsServer, func() *ServiceAOperationsServerTransport { + return NewServiceAOperationsServerTransport(&s.srv.ServiceAOperationsServer) + }) + resp, err = s.trServiceAOperationsServer.Do(req) + case "ServiceASubNamespaceClient": + initServer(&s.trMu, &s.trServiceASubNamespaceServer, func() *ServiceASubNamespaceServerTransport { + return NewServiceASubNamespaceServerTransport(&s.srv.ServiceASubNamespaceServer) + }) + resp, err = s.trServiceASubNamespaceServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to ServiceAServerTransport +var serviceAServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/service/multipleservicesgroup/fake/zz_serviceaoperations_server.go b/test/azure-http-specs/service/multipleservicesgroup/fake/zz_serviceaoperations_server.go new file mode 100644 index 000000000000..96e9a58b1328 --- /dev/null +++ b/test/azure-http-specs/service/multipleservicesgroup/fake/zz_serviceaoperations_server.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "multipleservicesgroup" + "net/http" + "slices" +) + +// ServiceAOperationsServer is a fake server for instances of the multipleservicesgroup.ServiceAOperationsClient type. +type ServiceAOperationsServer struct { + // OpA is the fake for method ServiceAOperationsClient.OpA + // HTTP status codes to indicate success: http.StatusNoContent + OpA func(ctx context.Context, options *multipleservicesgroup.ServiceAOperationsClientOpAOptions) (resp azfake.Responder[multipleservicesgroup.ServiceAOperationsClientOpAResponse], errResp azfake.ErrorResponder) +} + +// NewServiceAOperationsServerTransport creates a new instance of ServiceAOperationsServerTransport with the provided implementation. +// The returned ServiceAOperationsServerTransport instance is connected to an instance of multipleservicesgroup.ServiceAOperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServiceAOperationsServerTransport(srv *ServiceAOperationsServer) *ServiceAOperationsServerTransport { + return &ServiceAOperationsServerTransport{srv: srv} +} + +// ServiceAOperationsServerTransport connects instances of multipleservicesgroup.ServiceAOperationsClient to instances of ServiceAOperationsServer. +// Don't use this type directly, use NewServiceAOperationsServerTransport instead. +type ServiceAOperationsServerTransport struct { + srv *ServiceAOperationsServer +} + +// Do implements the policy.Transporter interface for ServiceAOperationsServerTransport. +func (s *ServiceAOperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ServiceAOperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if serviceAOperationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = serviceAOperationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ServiceAOperationsClient.OpA": + res.resp, res.err = s.dispatchOpA(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ServiceAOperationsServerTransport) dispatchOpA(req *http.Request) (*http.Response, error) { + if s.srv.OpA == nil { + return nil, &nonRetriableError{errors.New("fake for method OpA not implemented")} + } + respr, errRespr := s.srv.OpA(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ServiceAOperationsServerTransport +var serviceAOperationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/service/multipleservicesgroup/fake/zz_serviceasubnamespace_server.go b/test/azure-http-specs/service/multipleservicesgroup/fake/zz_serviceasubnamespace_server.go new file mode 100644 index 000000000000..231b410db5e2 --- /dev/null +++ b/test/azure-http-specs/service/multipleservicesgroup/fake/zz_serviceasubnamespace_server.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "multipleservicesgroup" + "net/http" + "slices" +) + +// ServiceASubNamespaceServer is a fake server for instances of the multipleservicesgroup.ServiceASubNamespaceClient type. +type ServiceASubNamespaceServer struct { + // SubOpA is the fake for method ServiceASubNamespaceClient.SubOpA + // HTTP status codes to indicate success: http.StatusNoContent + SubOpA func(ctx context.Context, options *multipleservicesgroup.ServiceASubNamespaceClientSubOpAOptions) (resp azfake.Responder[multipleservicesgroup.ServiceASubNamespaceClientSubOpAResponse], errResp azfake.ErrorResponder) +} + +// NewServiceASubNamespaceServerTransport creates a new instance of ServiceASubNamespaceServerTransport with the provided implementation. +// The returned ServiceASubNamespaceServerTransport instance is connected to an instance of multipleservicesgroup.ServiceASubNamespaceClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServiceASubNamespaceServerTransport(srv *ServiceASubNamespaceServer) *ServiceASubNamespaceServerTransport { + return &ServiceASubNamespaceServerTransport{srv: srv} +} + +// ServiceASubNamespaceServerTransport connects instances of multipleservicesgroup.ServiceASubNamespaceClient to instances of ServiceASubNamespaceServer. +// Don't use this type directly, use NewServiceASubNamespaceServerTransport instead. +type ServiceASubNamespaceServerTransport struct { + srv *ServiceASubNamespaceServer +} + +// Do implements the policy.Transporter interface for ServiceASubNamespaceServerTransport. +func (s *ServiceASubNamespaceServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ServiceASubNamespaceServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if serviceASubNamespaceServerTransportInterceptor != nil { + res.resp, res.err, intercepted = serviceASubNamespaceServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ServiceASubNamespaceClient.SubOpA": + res.resp, res.err = s.dispatchSubOpA(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ServiceASubNamespaceServerTransport) dispatchSubOpA(req *http.Request) (*http.Response, error) { + if s.srv.SubOpA == nil { + return nil, &nonRetriableError{errors.New("fake for method SubOpA not implemented")} + } + respr, errRespr := s.srv.SubOpA(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ServiceASubNamespaceServerTransport +var serviceASubNamespaceServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/service/multipleservicesgroup/fake/zz_serviceb_server.go b/test/azure-http-specs/service/multipleservicesgroup/fake/zz_serviceb_server.go new file mode 100644 index 000000000000..eea28edfcf73 --- /dev/null +++ b/test/azure-http-specs/service/multipleservicesgroup/fake/zz_serviceb_server.go @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServiceBServer is a fake server for instances of the multipleservicesgroup.ServiceBClient type. +type ServiceBServer struct { + // ServiceBOperationsServer contains the fakes for client ServiceBOperationsClient + ServiceBOperationsServer ServiceBOperationsServer + + // ServiceBSubNamespaceServer contains the fakes for client ServiceBSubNamespaceClient + ServiceBSubNamespaceServer ServiceBSubNamespaceServer +} + +// NewServiceBServerTransport creates a new instance of ServiceBServerTransport with the provided implementation. +// The returned ServiceBServerTransport instance is connected to an instance of multipleservicesgroup.ServiceBClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServiceBServerTransport(srv *ServiceBServer) *ServiceBServerTransport { + return &ServiceBServerTransport{srv: srv} +} + +// ServiceBServerTransport connects instances of multipleservicesgroup.ServiceBClient to instances of ServiceBServer. +// Don't use this type directly, use NewServiceBServerTransport instead. +type ServiceBServerTransport struct { + srv *ServiceBServer + trMu sync.Mutex + trServiceBOperationsServer *ServiceBOperationsServerTransport + trServiceBSubNamespaceServer *ServiceBSubNamespaceServerTransport +} + +// Do implements the policy.Transporter interface for ServiceBServerTransport. +func (s *ServiceBServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (s *ServiceBServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "ServiceBOperationsClient": + initServer(&s.trMu, &s.trServiceBOperationsServer, func() *ServiceBOperationsServerTransport { + return NewServiceBOperationsServerTransport(&s.srv.ServiceBOperationsServer) + }) + resp, err = s.trServiceBOperationsServer.Do(req) + case "ServiceBSubNamespaceClient": + initServer(&s.trMu, &s.trServiceBSubNamespaceServer, func() *ServiceBSubNamespaceServerTransport { + return NewServiceBSubNamespaceServerTransport(&s.srv.ServiceBSubNamespaceServer) + }) + resp, err = s.trServiceBSubNamespaceServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to ServiceBServerTransport +var serviceBServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/service/multipleservicesgroup/fake/zz_serviceboperations_server.go b/test/azure-http-specs/service/multipleservicesgroup/fake/zz_serviceboperations_server.go new file mode 100644 index 000000000000..4c3ce67acb0f --- /dev/null +++ b/test/azure-http-specs/service/multipleservicesgroup/fake/zz_serviceboperations_server.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "multipleservicesgroup" + "net/http" + "slices" +) + +// ServiceBOperationsServer is a fake server for instances of the multipleservicesgroup.ServiceBOperationsClient type. +type ServiceBOperationsServer struct { + // OpB is the fake for method ServiceBOperationsClient.OpB + // HTTP status codes to indicate success: http.StatusNoContent + OpB func(ctx context.Context, options *multipleservicesgroup.ServiceBOperationsClientOpBOptions) (resp azfake.Responder[multipleservicesgroup.ServiceBOperationsClientOpBResponse], errResp azfake.ErrorResponder) +} + +// NewServiceBOperationsServerTransport creates a new instance of ServiceBOperationsServerTransport with the provided implementation. +// The returned ServiceBOperationsServerTransport instance is connected to an instance of multipleservicesgroup.ServiceBOperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServiceBOperationsServerTransport(srv *ServiceBOperationsServer) *ServiceBOperationsServerTransport { + return &ServiceBOperationsServerTransport{srv: srv} +} + +// ServiceBOperationsServerTransport connects instances of multipleservicesgroup.ServiceBOperationsClient to instances of ServiceBOperationsServer. +// Don't use this type directly, use NewServiceBOperationsServerTransport instead. +type ServiceBOperationsServerTransport struct { + srv *ServiceBOperationsServer +} + +// Do implements the policy.Transporter interface for ServiceBOperationsServerTransport. +func (s *ServiceBOperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ServiceBOperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if serviceBOperationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = serviceBOperationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ServiceBOperationsClient.OpB": + res.resp, res.err = s.dispatchOpB(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ServiceBOperationsServerTransport) dispatchOpB(req *http.Request) (*http.Response, error) { + if s.srv.OpB == nil { + return nil, &nonRetriableError{errors.New("fake for method OpB not implemented")} + } + respr, errRespr := s.srv.OpB(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ServiceBOperationsServerTransport +var serviceBOperationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/service/multipleservicesgroup/fake/zz_servicebsubnamespace_server.go b/test/azure-http-specs/service/multipleservicesgroup/fake/zz_servicebsubnamespace_server.go new file mode 100644 index 000000000000..def99686817e --- /dev/null +++ b/test/azure-http-specs/service/multipleservicesgroup/fake/zz_servicebsubnamespace_server.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "multipleservicesgroup" + "net/http" + "slices" +) + +// ServiceBSubNamespaceServer is a fake server for instances of the multipleservicesgroup.ServiceBSubNamespaceClient type. +type ServiceBSubNamespaceServer struct { + // SubOpB is the fake for method ServiceBSubNamespaceClient.SubOpB + // HTTP status codes to indicate success: http.StatusNoContent + SubOpB func(ctx context.Context, options *multipleservicesgroup.ServiceBSubNamespaceClientSubOpBOptions) (resp azfake.Responder[multipleservicesgroup.ServiceBSubNamespaceClientSubOpBResponse], errResp azfake.ErrorResponder) +} + +// NewServiceBSubNamespaceServerTransport creates a new instance of ServiceBSubNamespaceServerTransport with the provided implementation. +// The returned ServiceBSubNamespaceServerTransport instance is connected to an instance of multipleservicesgroup.ServiceBSubNamespaceClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServiceBSubNamespaceServerTransport(srv *ServiceBSubNamespaceServer) *ServiceBSubNamespaceServerTransport { + return &ServiceBSubNamespaceServerTransport{srv: srv} +} + +// ServiceBSubNamespaceServerTransport connects instances of multipleservicesgroup.ServiceBSubNamespaceClient to instances of ServiceBSubNamespaceServer. +// Don't use this type directly, use NewServiceBSubNamespaceServerTransport instead. +type ServiceBSubNamespaceServerTransport struct { + srv *ServiceBSubNamespaceServer +} + +// Do implements the policy.Transporter interface for ServiceBSubNamespaceServerTransport. +func (s *ServiceBSubNamespaceServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ServiceBSubNamespaceServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if serviceBSubNamespaceServerTransportInterceptor != nil { + res.resp, res.err, intercepted = serviceBSubNamespaceServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ServiceBSubNamespaceClient.SubOpB": + res.resp, res.err = s.dispatchSubOpB(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ServiceBSubNamespaceServerTransport) dispatchSubOpB(req *http.Request) (*http.Response, error) { + if s.srv.SubOpB == nil { + return nil, &nonRetriableError{errors.New("fake for method SubOpB not implemented")} + } + respr, errRespr := s.srv.SubOpB(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ServiceBSubNamespaceServerTransport +var serviceBSubNamespaceServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/service/multipleservicesgroup/fakes_test.go b/test/azure-http-specs/service/multipleservicesgroup/fakes_test.go new file mode 100644 index 000000000000..4712d829be34 --- /dev/null +++ b/test/azure-http-specs/service/multipleservicesgroup/fakes_test.go @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package multipleservicesgroup_test + +import ( + "context" + "multipleservicesgroup" + "multipleservicesgroup/fake" + "net/http" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/stretchr/testify/require" +) + +func TestFakeServiceAServer(t *testing.T) { + calledOpA := false + calledSubOpA := false + server := fake.ServiceAServer{ + ServiceAOperationsServer: fake.ServiceAOperationsServer{ + OpA: func(ctx context.Context, options *multipleservicesgroup.ServiceAOperationsClientOpAOptions) (resp azfake.Responder[multipleservicesgroup.ServiceAOperationsClientOpAResponse], errResp azfake.ErrorResponder) { + calledOpA = true + resp.SetResponse(http.StatusNoContent, multipleservicesgroup.ServiceAOperationsClientOpAResponse{}, nil) + return + }, + }, + ServiceASubNamespaceServer: fake.ServiceASubNamespaceServer{ + SubOpA: func(ctx context.Context, options *multipleservicesgroup.ServiceASubNamespaceClientSubOpAOptions) (resp azfake.Responder[multipleservicesgroup.ServiceASubNamespaceClientSubOpAResponse], errResp azfake.ErrorResponder) { + calledSubOpA = true + resp.SetResponse(http.StatusNoContent, multipleservicesgroup.ServiceASubNamespaceClientSubOpAResponse{}, nil) + return + }, + }, + } + client, err := multipleservicesgroup.NewServiceAClientWithNoCredential("http://localhost:3000", &multipleservicesgroup.ServiceAClientOptions{ + ClientOptions: azcore.ClientOptions{ + Transport: fake.NewServiceAServerTransport(&server), + }, + }) + require.NoError(t, err) + + _, err = client.NewServiceAOperationsClient().OpA(context.Background(), nil) + require.NoError(t, err) + + _, err = client.NewServiceASubNamespaceClient().SubOpA(context.Background(), nil) + require.NoError(t, err) + + require.True(t, calledOpA) + require.True(t, calledSubOpA) +} + +func TestFakeServiceBServer(t *testing.T) { + calledOpB := false + calledSubOpB := false + server := fake.ServiceBServer{ + ServiceBOperationsServer: fake.ServiceBOperationsServer{ + OpB: func(ctx context.Context, options *multipleservicesgroup.ServiceBOperationsClientOpBOptions) (resp azfake.Responder[multipleservicesgroup.ServiceBOperationsClientOpBResponse], errResp azfake.ErrorResponder) { + calledOpB = true + resp.SetResponse(http.StatusNoContent, multipleservicesgroup.ServiceBOperationsClientOpBResponse{}, nil) + return + }, + }, + ServiceBSubNamespaceServer: fake.ServiceBSubNamespaceServer{ + SubOpB: func(ctx context.Context, options *multipleservicesgroup.ServiceBSubNamespaceClientSubOpBOptions) (resp azfake.Responder[multipleservicesgroup.ServiceBSubNamespaceClientSubOpBResponse], errResp azfake.ErrorResponder) { + calledSubOpB = true + resp.SetResponse(http.StatusNoContent, multipleservicesgroup.ServiceBSubNamespaceClientSubOpBResponse{}, nil) + return + }, + }, + } + client, err := multipleservicesgroup.NewServiceBClientWithNoCredential("http://localhost:3000", &multipleservicesgroup.ServiceBClientOptions{ + ClientOptions: azcore.ClientOptions{ + Transport: fake.NewServiceBServerTransport(&server), + }, + }) + require.NoError(t, err) + + _, err = client.NewServiceBOperationsClient().OpB(context.Background(), nil) + require.NoError(t, err) + + _, err = client.NewServiceBSubNamespaceClient().SubOpB(context.Background(), nil) + require.NoError(t, err) + + require.True(t, calledOpB) + require.True(t, calledSubOpB) +} diff --git a/test/azure-http-specs/service/multipleservicesgroup/go.mod b/test/azure-http-specs/service/multipleservicesgroup/go.mod new file mode 100644 index 000000000000..c198065d7945 --- /dev/null +++ b/test/azure-http-specs/service/multipleservicesgroup/go.mod @@ -0,0 +1,17 @@ +module multipleservicesgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/service/multipleservicesgroup/go.sum b/test/azure-http-specs/service/multipleservicesgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/service/multipleservicesgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/service/multipleservicesgroup/multipleservices_client_test.go b/test/azure-http-specs/service/multipleservicesgroup/multipleservices_client_test.go new file mode 100644 index 000000000000..e129a3b586ad --- /dev/null +++ b/test/azure-http-specs/service/multipleservicesgroup/multipleservices_client_test.go @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package multipleservicesgroup_test + +import ( + "context" + "multipleservicesgroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestServiceAOperationsClient_OpA(t *testing.T) { + client, err := multipleservicesgroup.NewServiceAClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + _, err = client.NewServiceAOperationsClient().OpA(context.Background(), nil) + require.NoError(t, err) +} + +func TestServiceASubNamespaceClient_SubOpA(t *testing.T) { + client, err := multipleservicesgroup.NewServiceAClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + _, err = client.NewServiceASubNamespaceClient().SubOpA(context.Background(), nil) + require.NoError(t, err) +} + +func TestServiceBOperationsClient_OpB(t *testing.T) { + client, err := multipleservicesgroup.NewServiceBClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + _, err = client.NewServiceBOperationsClient().OpB(context.Background(), nil) + require.NoError(t, err) +} + +func TestServiceBSubNamespaceClient_SubOpB(t *testing.T) { + client, err := multipleservicesgroup.NewServiceBClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + _, err = client.NewServiceBSubNamespaceClient().SubOpB(context.Background(), nil) + require.NoError(t, err) +} diff --git a/test/azure-http-specs/service/multipleservicesgroup/testdata/_metadata.json b/test/azure-http-specs/service/multipleservicesgroup/testdata/_metadata.json new file mode 100644 index 000000000000..8187f5ff8b91 --- /dev/null +++ b/test/azure-http-specs/service/multipleservicesgroup/testdata/_metadata.json @@ -0,0 +1,7 @@ +{ + "apiVersions": { + "Service.MultipleServices.ServiceA": "av2", + "Service.MultipleServices.ServiceB": "bv2" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/service/multipleservicesgroup/zz_constants.go b/test/azure-http-specs/service/multipleservicesgroup/zz_constants.go new file mode 100644 index 000000000000..8860435b9ffc --- /dev/null +++ b/test/azure-http-specs/service/multipleservicesgroup/zz_constants.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multipleservicesgroup + +const ( + versionAv2 string = "av2" + versionBv2 string = "bv2" +) diff --git a/test/azure-http-specs/service/multipleservicesgroup/zz_options.go b/test/azure-http-specs/service/multipleservicesgroup/zz_options.go new file mode 100644 index 000000000000..42fc8fd3f623 --- /dev/null +++ b/test/azure-http-specs/service/multipleservicesgroup/zz_options.go @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multipleservicesgroup + +// ServiceAOperationsClientOpAOptions contains the optional parameters for the ServiceAOperationsClient.OpA method. +type ServiceAOperationsClientOpAOptions struct { + // placeholder for future optional parameters +} + +// ServiceASubNamespaceClientSubOpAOptions contains the optional parameters for the ServiceASubNamespaceClient.SubOpA method. +type ServiceASubNamespaceClientSubOpAOptions struct { + // placeholder for future optional parameters +} + +// ServiceBOperationsClientOpBOptions contains the optional parameters for the ServiceBOperationsClient.OpB method. +type ServiceBOperationsClientOpBOptions struct { + // placeholder for future optional parameters +} + +// ServiceBSubNamespaceClientSubOpBOptions contains the optional parameters for the ServiceBSubNamespaceClient.SubOpB method. +type ServiceBSubNamespaceClientSubOpBOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/service/multipleservicesgroup/zz_responses.go b/test/azure-http-specs/service/multipleservicesgroup/zz_responses.go new file mode 100644 index 000000000000..ffb30a24361c --- /dev/null +++ b/test/azure-http-specs/service/multipleservicesgroup/zz_responses.go @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multipleservicesgroup + +// ServiceAOperationsClientOpAResponse contains the response from method ServiceAOperationsClient.OpA. +type ServiceAOperationsClientOpAResponse struct { + // placeholder for future response values +} + +// ServiceASubNamespaceClientSubOpAResponse contains the response from method ServiceASubNamespaceClient.SubOpA. +type ServiceASubNamespaceClientSubOpAResponse struct { + // placeholder for future response values +} + +// ServiceBOperationsClientOpBResponse contains the response from method ServiceBOperationsClient.OpB. +type ServiceBOperationsClientOpBResponse struct { + // placeholder for future response values +} + +// ServiceBSubNamespaceClientSubOpBResponse contains the response from method ServiceBSubNamespaceClient.SubOpB. +type ServiceBSubNamespaceClientSubOpBResponse struct { + // placeholder for future response values +} diff --git a/test/azure-http-specs/service/multipleservicesgroup/zz_servicea_client.go b/test/azure-http-specs/service/multipleservicesgroup/zz_servicea_client.go new file mode 100644 index 000000000000..44f7554735ec --- /dev/null +++ b/test/azure-http-specs/service/multipleservicesgroup/zz_servicea_client.go @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multipleservicesgroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// ServiceAClient - First service definition in a multiple-services package with versioning. +// Without explicit `@client`, this should create a separate root client (`ServiceAClient`). +// Don't use this type directly, use NewServiceAClientWithNoCredential() instead. +type ServiceAClient struct { + internal *azcore.Client + endpoint string +} + +// ServiceAClientOptions contains the optional values for creating a [ServiceAClient]. +type ServiceAClientOptions struct { + azcore.ClientOptions +} + +// NewServiceAClientWithNoCredential creates a new instance of ServiceAClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewServiceAClientWithNoCredential(endpoint string, options *ServiceAClientOptions) (*ServiceAClient, error) { + if options == nil { + options = &ServiceAClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &ServiceAClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewServiceAOperationsClient creates a new instance of [ServiceAOperationsClient]. +func (client *ServiceAClient) NewServiceAOperationsClient() *ServiceAOperationsClient { + return &ServiceAOperationsClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewServiceASubNamespaceClient creates a new instance of [ServiceASubNamespaceClient]. +func (client *ServiceAClient) NewServiceASubNamespaceClient() *ServiceASubNamespaceClient { + return &ServiceASubNamespaceClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/azure-http-specs/service/multipleservicesgroup/zz_serviceaoperations_client.go b/test/azure-http-specs/service/multipleservicesgroup/zz_serviceaoperations_client.go new file mode 100644 index 000000000000..8d00cdb6cf19 --- /dev/null +++ b/test/azure-http-specs/service/multipleservicesgroup/zz_serviceaoperations_client.go @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multipleservicesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// ServiceAOperationsClient contains the methods for the ServiceAOperations group. +// Don't use this type directly, use [ServiceAClient.NewServiceAOperationsClient] instead. +// +// Generated from API version av2 +type ServiceAOperationsClient struct { + internal *azcore.Client + endpoint string +} + +// OpA - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ServiceAOperationsClientOpAOptions contains the optional parameters for the ServiceAOperationsClient.OpA method. +func (client *ServiceAOperationsClient) OpA(ctx context.Context, options *ServiceAOperationsClientOpAOptions) (ServiceAOperationsClientOpAResponse, error) { + var err error + const operationName = "ServiceAOperationsClient.OpA" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.opACreateRequest(ctx, options) + if err != nil { + return ServiceAOperationsClientOpAResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServiceAOperationsClientOpAResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ServiceAOperationsClientOpAResponse{}, err + } + return ServiceAOperationsClientOpAResponse{}, nil +} + +// opACreateRequest creates the OpA request. +func (client *ServiceAOperationsClient) opACreateRequest(ctx context.Context, _ *ServiceAOperationsClientOpAOptions) (*policy.Request, error) { + urlPath := "/service/multiple-services/service-a/a-test" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", versionAv2) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/azure-http-specs/service/multipleservicesgroup/zz_serviceasubnamespace_client.go b/test/azure-http-specs/service/multipleservicesgroup/zz_serviceasubnamespace_client.go new file mode 100644 index 000000000000..151b820e31e0 --- /dev/null +++ b/test/azure-http-specs/service/multipleservicesgroup/zz_serviceasubnamespace_client.go @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multipleservicesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// ServiceASubNamespaceClient contains the methods for the ServiceASubNamespace group. +// Don't use this type directly, use [ServiceAClient.NewServiceASubNamespaceClient] instead. +// +// Generated from API version av2 +type ServiceASubNamespaceClient struct { + internal *azcore.Client + endpoint string +} + +// SubOpA - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ServiceASubNamespaceClientSubOpAOptions contains the optional parameters for the ServiceASubNamespaceClient.SubOpA +// method. +func (client *ServiceASubNamespaceClient) SubOpA(ctx context.Context, options *ServiceASubNamespaceClientSubOpAOptions) (ServiceASubNamespaceClientSubOpAResponse, error) { + var err error + const operationName = "ServiceASubNamespaceClient.SubOpA" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.subOpACreateRequest(ctx, options) + if err != nil { + return ServiceASubNamespaceClientSubOpAResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServiceASubNamespaceClientSubOpAResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ServiceASubNamespaceClientSubOpAResponse{}, err + } + return ServiceASubNamespaceClientSubOpAResponse{}, nil +} + +// subOpACreateRequest creates the SubOpA request. +func (client *ServiceASubNamespaceClient) subOpACreateRequest(ctx context.Context, _ *ServiceASubNamespaceClientSubOpAOptions) (*policy.Request, error) { + urlPath := "/service/multiple-services/service-a/a-sub-test" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", versionAv2) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/azure-http-specs/service/multipleservicesgroup/zz_serviceb_client.go b/test/azure-http-specs/service/multipleservicesgroup/zz_serviceb_client.go new file mode 100644 index 000000000000..ccd14b628091 --- /dev/null +++ b/test/azure-http-specs/service/multipleservicesgroup/zz_serviceb_client.go @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multipleservicesgroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// ServiceBClient - Second service definition in a multiple-services package with versioning. +// Without explicit `@client`, this should create a separate root client (`ServiceBClient`). +// Don't use this type directly, use NewServiceBClientWithNoCredential() instead. +type ServiceBClient struct { + internal *azcore.Client + endpoint string +} + +// ServiceBClientOptions contains the optional values for creating a [ServiceBClient]. +type ServiceBClientOptions struct { + azcore.ClientOptions +} + +// NewServiceBClientWithNoCredential creates a new instance of ServiceBClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewServiceBClientWithNoCredential(endpoint string, options *ServiceBClientOptions) (*ServiceBClient, error) { + if options == nil { + options = &ServiceBClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &ServiceBClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewServiceBOperationsClient creates a new instance of [ServiceBOperationsClient]. +func (client *ServiceBClient) NewServiceBOperationsClient() *ServiceBOperationsClient { + return &ServiceBOperationsClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewServiceBSubNamespaceClient creates a new instance of [ServiceBSubNamespaceClient]. +func (client *ServiceBClient) NewServiceBSubNamespaceClient() *ServiceBSubNamespaceClient { + return &ServiceBSubNamespaceClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/azure-http-specs/service/multipleservicesgroup/zz_serviceboperations_client.go b/test/azure-http-specs/service/multipleservicesgroup/zz_serviceboperations_client.go new file mode 100644 index 000000000000..20ccf221e365 --- /dev/null +++ b/test/azure-http-specs/service/multipleservicesgroup/zz_serviceboperations_client.go @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multipleservicesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// ServiceBOperationsClient contains the methods for the ServiceBOperations group. +// Don't use this type directly, use [ServiceBClient.NewServiceBOperationsClient] instead. +// +// Generated from API version bv2 +type ServiceBOperationsClient struct { + internal *azcore.Client + endpoint string +} + +// OpB - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ServiceBOperationsClientOpBOptions contains the optional parameters for the ServiceBOperationsClient.OpB method. +func (client *ServiceBOperationsClient) OpB(ctx context.Context, options *ServiceBOperationsClientOpBOptions) (ServiceBOperationsClientOpBResponse, error) { + var err error + const operationName = "ServiceBOperationsClient.OpB" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.opBCreateRequest(ctx, options) + if err != nil { + return ServiceBOperationsClientOpBResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServiceBOperationsClientOpBResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ServiceBOperationsClientOpBResponse{}, err + } + return ServiceBOperationsClientOpBResponse{}, nil +} + +// opBCreateRequest creates the OpB request. +func (client *ServiceBOperationsClient) opBCreateRequest(ctx context.Context, _ *ServiceBOperationsClientOpBOptions) (*policy.Request, error) { + urlPath := "/service/multiple-services/service-b/b-test" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", versionBv2) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/azure-http-specs/service/multipleservicesgroup/zz_servicebsubnamespace_client.go b/test/azure-http-specs/service/multipleservicesgroup/zz_servicebsubnamespace_client.go new file mode 100644 index 000000000000..ad0113b1fdbd --- /dev/null +++ b/test/azure-http-specs/service/multipleservicesgroup/zz_servicebsubnamespace_client.go @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multipleservicesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// ServiceBSubNamespaceClient contains the methods for the ServiceBSubNamespace group. +// Don't use this type directly, use [ServiceBClient.NewServiceBSubNamespaceClient] instead. +// +// Generated from API version bv2 +type ServiceBSubNamespaceClient struct { + internal *azcore.Client + endpoint string +} + +// SubOpB - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ServiceBSubNamespaceClientSubOpBOptions contains the optional parameters for the ServiceBSubNamespaceClient.SubOpB +// method. +func (client *ServiceBSubNamespaceClient) SubOpB(ctx context.Context, options *ServiceBSubNamespaceClientSubOpBOptions) (ServiceBSubNamespaceClientSubOpBResponse, error) { + var err error + const operationName = "ServiceBSubNamespaceClient.SubOpB" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.subOpBCreateRequest(ctx, options) + if err != nil { + return ServiceBSubNamespaceClientSubOpBResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServiceBSubNamespaceClientSubOpBResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ServiceBSubNamespaceClientSubOpBResponse{}, err + } + return ServiceBSubNamespaceClientSubOpBResponse{}, nil +} + +// subOpBCreateRequest creates the SubOpB request. +func (client *ServiceBSubNamespaceClient) subOpBCreateRequest(ctx context.Context, _ *ServiceBSubNamespaceClientSubOpBOptions) (*policy.Request, error) { + urlPath := "/service/multiple-services/service-b/b-sub-test" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", versionBv2) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/azure-http-specs/service/multipleservicesgroup/zz_version.go b/test/azure-http-specs/service/multipleservicesgroup/zz_version.go new file mode 100644 index 000000000000..8b1de705c0f2 --- /dev/null +++ b/test/azure-http-specs/service/multipleservicesgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package multipleservicesgroup + +const ( + moduleName = "multipleservicesgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/azure-http-specs/service/multiservicegroup/LICENSE.txt b/test/azure-http-specs/service/multiservicegroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/azure-http-specs/service/multiservicegroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/azure-http-specs/service/multiservicegroup/combined_client_test.go b/test/azure-http-specs/service/multiservicegroup/combined_client_test.go new file mode 100644 index 000000000000..095dc969983d --- /dev/null +++ b/test/azure-http-specs/service/multiservicegroup/combined_client_test.go @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package multiservicegroup_test + +import ( + "context" + "multiservicegroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestCombinedClient(t *testing.T) { + client, err := multiservicegroup.NewCombinedClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + require.NotNil(t, client) + resp, err := client.NewCombinedFooClient().Test(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp) + resp2, err := client.NewCombinedBarClient().Test(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp2) +} diff --git a/test/azure-http-specs/service/multiservicegroup/fake/zz_combined_server.go b/test/azure-http-specs/service/multiservicegroup/fake/zz_combined_server.go new file mode 100644 index 000000000000..7f0a4a814491 --- /dev/null +++ b/test/azure-http-specs/service/multiservicegroup/fake/zz_combined_server.go @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// CombinedServer is a fake server for instances of the multiservicegroup.CombinedClient type. +type CombinedServer struct { + // CombinedBarServer contains the fakes for client CombinedBarClient + CombinedBarServer CombinedBarServer + + // CombinedFooServer contains the fakes for client CombinedFooClient + CombinedFooServer CombinedFooServer +} + +// NewCombinedServerTransport creates a new instance of CombinedServerTransport with the provided implementation. +// The returned CombinedServerTransport instance is connected to an instance of multiservicegroup.CombinedClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewCombinedServerTransport(srv *CombinedServer) *CombinedServerTransport { + return &CombinedServerTransport{srv: srv} +} + +// CombinedServerTransport connects instances of multiservicegroup.CombinedClient to instances of CombinedServer. +// Don't use this type directly, use NewCombinedServerTransport instead. +type CombinedServerTransport struct { + srv *CombinedServer + trMu sync.Mutex + trCombinedBarServer *CombinedBarServerTransport + trCombinedFooServer *CombinedFooServerTransport +} + +// Do implements the policy.Transporter interface for CombinedServerTransport. +func (c *CombinedServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (c *CombinedServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "CombinedBarClient": + initServer(&c.trMu, &c.trCombinedBarServer, func() *CombinedBarServerTransport { + return NewCombinedBarServerTransport(&c.srv.CombinedBarServer) + }) + resp, err = c.trCombinedBarServer.Do(req) + case "CombinedFooClient": + initServer(&c.trMu, &c.trCombinedFooServer, func() *CombinedFooServerTransport { + return NewCombinedFooServerTransport(&c.srv.CombinedFooServer) + }) + resp, err = c.trCombinedFooServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to CombinedServerTransport +var combinedServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/service/multiservicegroup/fake/zz_combinedbar_server.go b/test/azure-http-specs/service/multiservicegroup/fake/zz_combinedbar_server.go new file mode 100644 index 000000000000..6962dec7adcc --- /dev/null +++ b/test/azure-http-specs/service/multiservicegroup/fake/zz_combinedbar_server.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "multiservicegroup" + "net/http" + "slices" +) + +// CombinedBarServer is a fake server for instances of the multiservicegroup.CombinedBarClient type. +type CombinedBarServer struct { + // Test is the fake for method CombinedBarClient.Test + // HTTP status codes to indicate success: http.StatusNoContent + Test func(ctx context.Context, options *multiservicegroup.CombinedBarClientTestOptions) (resp azfake.Responder[multiservicegroup.CombinedBarClientTestResponse], errResp azfake.ErrorResponder) +} + +// NewCombinedBarServerTransport creates a new instance of CombinedBarServerTransport with the provided implementation. +// The returned CombinedBarServerTransport instance is connected to an instance of multiservicegroup.CombinedBarClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewCombinedBarServerTransport(srv *CombinedBarServer) *CombinedBarServerTransport { + return &CombinedBarServerTransport{srv: srv} +} + +// CombinedBarServerTransport connects instances of multiservicegroup.CombinedBarClient to instances of CombinedBarServer. +// Don't use this type directly, use NewCombinedBarServerTransport instead. +type CombinedBarServerTransport struct { + srv *CombinedBarServer +} + +// Do implements the policy.Transporter interface for CombinedBarServerTransport. +func (c *CombinedBarServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *CombinedBarServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if combinedBarServerTransportInterceptor != nil { + res.resp, res.err, intercepted = combinedBarServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "CombinedBarClient.Test": + res.resp, res.err = c.dispatchTest(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *CombinedBarServerTransport) dispatchTest(req *http.Request) (*http.Response, error) { + if c.srv.Test == nil { + return nil, &nonRetriableError{errors.New("fake for method Test not implemented")} + } + respr, errRespr := c.srv.Test(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to CombinedBarServerTransport +var combinedBarServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/service/multiservicegroup/fake/zz_combinedfoo_server.go b/test/azure-http-specs/service/multiservicegroup/fake/zz_combinedfoo_server.go new file mode 100644 index 000000000000..822d0fd5c416 --- /dev/null +++ b/test/azure-http-specs/service/multiservicegroup/fake/zz_combinedfoo_server.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "multiservicegroup" + "net/http" + "slices" +) + +// CombinedFooServer is a fake server for instances of the multiservicegroup.CombinedFooClient type. +type CombinedFooServer struct { + // Test is the fake for method CombinedFooClient.Test + // HTTP status codes to indicate success: http.StatusNoContent + Test func(ctx context.Context, options *multiservicegroup.CombinedFooClientTestOptions) (resp azfake.Responder[multiservicegroup.CombinedFooClientTestResponse], errResp azfake.ErrorResponder) +} + +// NewCombinedFooServerTransport creates a new instance of CombinedFooServerTransport with the provided implementation. +// The returned CombinedFooServerTransport instance is connected to an instance of multiservicegroup.CombinedFooClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewCombinedFooServerTransport(srv *CombinedFooServer) *CombinedFooServerTransport { + return &CombinedFooServerTransport{srv: srv} +} + +// CombinedFooServerTransport connects instances of multiservicegroup.CombinedFooClient to instances of CombinedFooServer. +// Don't use this type directly, use NewCombinedFooServerTransport instead. +type CombinedFooServerTransport struct { + srv *CombinedFooServer +} + +// Do implements the policy.Transporter interface for CombinedFooServerTransport. +func (c *CombinedFooServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *CombinedFooServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if combinedFooServerTransportInterceptor != nil { + res.resp, res.err, intercepted = combinedFooServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "CombinedFooClient.Test": + res.resp, res.err = c.dispatchTest(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *CombinedFooServerTransport) dispatchTest(req *http.Request) (*http.Response, error) { + if c.srv.Test == nil { + return nil, &nonRetriableError{errors.New("fake for method Test not implemented")} + } + respr, errRespr := c.srv.Test(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to CombinedFooServerTransport +var combinedFooServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/azure-http-specs/service/multiservicegroup/fake/zz_internal.go b/test/azure-http-specs/service/multiservicegroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/azure-http-specs/service/multiservicegroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/azure-http-specs/service/multiservicegroup/go.mod b/test/azure-http-specs/service/multiservicegroup/go.mod new file mode 100644 index 000000000000..3fe9377549f3 --- /dev/null +++ b/test/azure-http-specs/service/multiservicegroup/go.mod @@ -0,0 +1,17 @@ +module multiservicegroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/azure-http-specs/service/multiservicegroup/go.sum b/test/azure-http-specs/service/multiservicegroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/azure-http-specs/service/multiservicegroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/azure-http-specs/service/multiservicegroup/testdata/_metadata.json b/test/azure-http-specs/service/multiservicegroup/testdata/_metadata.json new file mode 100644 index 000000000000..49fa6f1d3732 --- /dev/null +++ b/test/azure-http-specs/service/multiservicegroup/testdata/_metadata.json @@ -0,0 +1,7 @@ +{ + "apiVersions": { + "Service.MultiService.ServiceA": "av2", + "Service.MultiService.ServiceB": "bv2" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/azure-http-specs/service/multiservicegroup/zz_combined_client.go b/test/azure-http-specs/service/multiservicegroup/zz_combined_client.go new file mode 100644 index 000000000000..b6b6dca26e33 --- /dev/null +++ b/test/azure-http-specs/service/multiservicegroup/zz_combined_client.go @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multiservicegroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// CombinedClient contains the methods for the Combined group. +// Don't use this type directly, use NewCombinedClientWithNoCredential() instead. +type CombinedClient struct { + internal *azcore.Client + endpoint string +} + +// CombinedClientOptions contains the optional values for creating a [CombinedClient]. +type CombinedClientOptions struct { + azcore.ClientOptions +} + +// NewCombinedClientWithNoCredential creates a new instance of CombinedClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewCombinedClientWithNoCredential(endpoint string, options *CombinedClientOptions) (*CombinedClient, error) { + if options == nil { + options = &CombinedClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &CombinedClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewCombinedBarClient creates a new instance of [CombinedBarClient]. +func (client *CombinedClient) NewCombinedBarClient() *CombinedBarClient { + return &CombinedBarClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewCombinedFooClient creates a new instance of [CombinedFooClient]. +func (client *CombinedClient) NewCombinedFooClient() *CombinedFooClient { + return &CombinedFooClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/azure-http-specs/service/multiservicegroup/zz_combinedbar_client.go b/test/azure-http-specs/service/multiservicegroup/zz_combinedbar_client.go new file mode 100644 index 000000000000..e453e7a3027d --- /dev/null +++ b/test/azure-http-specs/service/multiservicegroup/zz_combinedbar_client.go @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multiservicegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// CombinedBarClient contains the methods for the CombinedBar group. +// Don't use this type directly, use [CombinedClient.NewCombinedBarClient] instead. +// +// Generated from API version bv2 +type CombinedBarClient struct { + internal *azcore.Client + endpoint string +} + +// Test - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - CombinedBarClientTestOptions contains the optional parameters for the CombinedBarClient.Test method. +func (client *CombinedBarClient) Test(ctx context.Context, options *CombinedBarClientTestOptions) (CombinedBarClientTestResponse, error) { + var err error + const operationName = "CombinedBarClient.Test" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.testCreateRequest(ctx, options) + if err != nil { + return CombinedBarClientTestResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CombinedBarClientTestResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return CombinedBarClientTestResponse{}, err + } + return CombinedBarClientTestResponse{}, nil +} + +// testCreateRequest creates the Test request. +func (client *CombinedBarClient) testCreateRequest(ctx context.Context, _ *CombinedBarClientTestOptions) (*policy.Request, error) { + urlPath := "/service/multi-service/service-b/bar/test" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", versionBv2) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/azure-http-specs/service/multiservicegroup/zz_combinedfoo_client.go b/test/azure-http-specs/service/multiservicegroup/zz_combinedfoo_client.go new file mode 100644 index 000000000000..f62103488bd9 --- /dev/null +++ b/test/azure-http-specs/service/multiservicegroup/zz_combinedfoo_client.go @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multiservicegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// CombinedFooClient contains the methods for the CombinedFoo group. +// Don't use this type directly, use [CombinedClient.NewCombinedFooClient] instead. +// +// Generated from API version av2 +type CombinedFooClient struct { + internal *azcore.Client + endpoint string +} + +// Test - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - CombinedFooClientTestOptions contains the optional parameters for the CombinedFooClient.Test method. +func (client *CombinedFooClient) Test(ctx context.Context, options *CombinedFooClientTestOptions) (CombinedFooClientTestResponse, error) { + var err error + const operationName = "CombinedFooClient.Test" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.testCreateRequest(ctx, options) + if err != nil { + return CombinedFooClientTestResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CombinedFooClientTestResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return CombinedFooClientTestResponse{}, err + } + return CombinedFooClientTestResponse{}, nil +} + +// testCreateRequest creates the Test request. +func (client *CombinedFooClient) testCreateRequest(ctx context.Context, _ *CombinedFooClientTestOptions) (*policy.Request, error) { + urlPath := "/service/multi-service/service-a/foo/test" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", versionAv2) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/azure-http-specs/service/multiservicegroup/zz_constants.go b/test/azure-http-specs/service/multiservicegroup/zz_constants.go new file mode 100644 index 000000000000..b34ad0031d8b --- /dev/null +++ b/test/azure-http-specs/service/multiservicegroup/zz_constants.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multiservicegroup + +const ( + versionAv2 string = "av2" + versionBv2 string = "bv2" +) diff --git a/test/azure-http-specs/service/multiservicegroup/zz_options.go b/test/azure-http-specs/service/multiservicegroup/zz_options.go new file mode 100644 index 000000000000..d7f6402bb915 --- /dev/null +++ b/test/azure-http-specs/service/multiservicegroup/zz_options.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multiservicegroup + +// CombinedBarClientTestOptions contains the optional parameters for the CombinedBarClient.Test method. +type CombinedBarClientTestOptions struct { + // placeholder for future optional parameters +} + +// CombinedFooClientTestOptions contains the optional parameters for the CombinedFooClient.Test method. +type CombinedFooClientTestOptions struct { + // placeholder for future optional parameters +} diff --git a/test/azure-http-specs/service/multiservicegroup/zz_responses.go b/test/azure-http-specs/service/multiservicegroup/zz_responses.go new file mode 100644 index 000000000000..754a52ff3126 --- /dev/null +++ b/test/azure-http-specs/service/multiservicegroup/zz_responses.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multiservicegroup + +// CombinedBarClientTestResponse contains the response from method CombinedBarClient.Test. +type CombinedBarClientTestResponse struct { + // placeholder for future response values +} + +// CombinedFooClientTestResponse contains the response from method CombinedFooClient.Test. +type CombinedFooClientTestResponse struct { + // placeholder for future response values +} diff --git a/test/azure-http-specs/service/multiservicegroup/zz_version.go b/test/azure-http-specs/service/multiservicegroup/zz_version.go new file mode 100644 index 000000000000..681e8c5ca133 --- /dev/null +++ b/test/azure-http-specs/service/multiservicegroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package multiservicegroup + +const ( + moduleName = "multiservicegroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/authentication/apikeygroup/LICENSE.txt b/test/http-specs/authentication/apikeygroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/authentication/apikeygroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/authentication/apikeygroup/apikey_client_test.go b/test/http-specs/authentication/apikeygroup/apikey_client_test.go new file mode 100644 index 000000000000..74831f3f7291 --- /dev/null +++ b/test/http-specs/authentication/apikeygroup/apikey_client_test.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package apikeygroup_test + +import ( + "apikeygroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/stretchr/testify/require" +) + +func TestAPIKeyClient_Invalid(t *testing.T) { + client, err := apikeygroup.NewAPIKeyClient("http://localhost:3000", azcore.NewKeyCredential("invalid-key"), nil) + require.NoError(t, err) + resp, err := client.Invalid(context.Background(), nil) + require.Error(t, err) + require.Contains(t, err.Error(), "invalid-api-key") + require.Zero(t, resp) +} + +func TestAPIKeyClient_Valid(t *testing.T) { + client, err := apikeygroup.NewAPIKeyClient("http://localhost:3000", azcore.NewKeyCredential("valid-key"), nil) + require.NoError(t, err) + resp, err := client.Valid(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) + +} diff --git a/test/http-specs/authentication/apikeygroup/custom_client.go b/test/http-specs/authentication/apikeygroup/custom_client.go new file mode 100644 index 000000000000..955218594f88 --- /dev/null +++ b/test/http-specs/authentication/apikeygroup/custom_client.go @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package apikeygroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +func NewAPIKeyClient(endpoint string, credential *azcore.KeyCredential, options *azcore.ClientOptions) (*APIKeyClient, error) { + internal, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{ + PerRetry: []policy.Policy{ + runtime.NewKeyCredentialPolicy(credential, "x-ms-api-key", &runtime.KeyCredentialPolicyOptions{ + InsecureAllowCredentialWithHTTP: true, + }), + }, + }, options) + if err != nil { + return nil, err + } + return &APIKeyClient{ + internal: internal, + endpoint: endpoint, + }, nil +} diff --git a/test/http-specs/authentication/apikeygroup/fake/zz_apikey_server.go b/test/http-specs/authentication/apikeygroup/fake/zz_apikey_server.go new file mode 100644 index 000000000000..e653c0b54a21 --- /dev/null +++ b/test/http-specs/authentication/apikeygroup/fake/zz_apikey_server.go @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "apikeygroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// APIKeyServer is a fake server for instances of the apikeygroup.APIKeyClient type. +type APIKeyServer struct { + // Invalid is the fake for method APIKeyClient.Invalid + // HTTP status codes to indicate success: http.StatusNoContent + Invalid func(ctx context.Context, options *apikeygroup.APIKeyClientInvalidOptions) (resp azfake.Responder[apikeygroup.APIKeyClientInvalidResponse], errResp azfake.ErrorResponder) + + // Valid is the fake for method APIKeyClient.Valid + // HTTP status codes to indicate success: http.StatusNoContent + Valid func(ctx context.Context, options *apikeygroup.APIKeyClientValidOptions) (resp azfake.Responder[apikeygroup.APIKeyClientValidResponse], errResp azfake.ErrorResponder) +} + +// NewAPIKeyServerTransport creates a new instance of APIKeyServerTransport with the provided implementation. +// The returned APIKeyServerTransport instance is connected to an instance of apikeygroup.APIKeyClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAPIKeyServerTransport(srv *APIKeyServer) *APIKeyServerTransport { + return &APIKeyServerTransport{srv: srv} +} + +// APIKeyServerTransport connects instances of apikeygroup.APIKeyClient to instances of APIKeyServer. +// Don't use this type directly, use NewAPIKeyServerTransport instead. +type APIKeyServerTransport struct { + srv *APIKeyServer +} + +// Do implements the policy.Transporter interface for APIKeyServerTransport. +func (a *APIKeyServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *APIKeyServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if apiKeyServerTransportInterceptor != nil { + res.resp, res.err, intercepted = apiKeyServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "APIKeyClient.Invalid": + res.resp, res.err = a.dispatchInvalid(req) + case "APIKeyClient.Valid": + res.resp, res.err = a.dispatchValid(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *APIKeyServerTransport) dispatchInvalid(req *http.Request) (*http.Response, error) { + if a.srv.Invalid == nil { + return nil, &nonRetriableError{errors.New("fake for method Invalid not implemented")} + } + respr, errRespr := a.srv.Invalid(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *APIKeyServerTransport) dispatchValid(req *http.Request) (*http.Response, error) { + if a.srv.Valid == nil { + return nil, &nonRetriableError{errors.New("fake for method Valid not implemented")} + } + respr, errRespr := a.srv.Valid(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to APIKeyServerTransport +var apiKeyServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/authentication/apikeygroup/fake/zz_internal.go b/test/http-specs/authentication/apikeygroup/fake/zz_internal.go new file mode 100644 index 000000000000..705f81eacafe --- /dev/null +++ b/test/http-specs/authentication/apikeygroup/fake/zz_internal.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import "net/http" + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} diff --git a/test/http-specs/authentication/apikeygroup/go.mod b/test/http-specs/authentication/apikeygroup/go.mod new file mode 100644 index 000000000000..df0ed6954414 --- /dev/null +++ b/test/http-specs/authentication/apikeygroup/go.mod @@ -0,0 +1,17 @@ +module apikeygroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/authentication/apikeygroup/go.sum b/test/http-specs/authentication/apikeygroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/authentication/apikeygroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/authentication/apikeygroup/testdata/_metadata.json b/test/http-specs/authentication/apikeygroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/authentication/apikeygroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/authentication/apikeygroup/version.go b/test/http-specs/authentication/apikeygroup/version.go new file mode 100644 index 000000000000..626257261357 --- /dev/null +++ b/test/http-specs/authentication/apikeygroup/version.go @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package apikeygroup + +// suppress unused vars lint +var _ = moduleName +var _ = moduleVersion diff --git a/test/http-specs/authentication/apikeygroup/zz_apikey_client.go b/test/http-specs/authentication/apikeygroup/zz_apikey_client.go new file mode 100644 index 000000000000..633ba949afe8 --- /dev/null +++ b/test/http-specs/authentication/apikeygroup/zz_apikey_client.go @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package apikeygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// APIKeyClient - Illustrates clients generated with ApiKey authentication. +// Don't use this type directly, use a constructor function instead. +type APIKeyClient struct { + internal *azcore.Client + endpoint string +} + +// APIKeyClientOptions contains the optional values for creating a [APIKeyClient]. +type APIKeyClientOptions struct { + azcore.ClientOptions +} + +// Invalid - Check whether client is authenticated. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - APIKeyClientInvalidOptions contains the optional parameters for the APIKeyClient.Invalid method. +func (client *APIKeyClient) Invalid(ctx context.Context, options *APIKeyClientInvalidOptions) (APIKeyClientInvalidResponse, error) { + var err error + const operationName = "APIKeyClient.Invalid" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.invalidCreateRequest(ctx, options) + if err != nil { + return APIKeyClientInvalidResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return APIKeyClientInvalidResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return APIKeyClientInvalidResponse{}, err + } + return APIKeyClientInvalidResponse{}, nil +} + +// invalidCreateRequest creates the Invalid request. +func (client *APIKeyClient) invalidCreateRequest(ctx context.Context, _ *APIKeyClientInvalidOptions) (*policy.Request, error) { + urlPath := "/authentication/api-key/invalid" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Valid - Check whether client is authenticated +// If the operation fails it returns an *azcore.ResponseError type. +// - options - APIKeyClientValidOptions contains the optional parameters for the APIKeyClient.Valid method. +func (client *APIKeyClient) Valid(ctx context.Context, options *APIKeyClientValidOptions) (APIKeyClientValidResponse, error) { + var err error + const operationName = "APIKeyClient.Valid" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.validCreateRequest(ctx, options) + if err != nil { + return APIKeyClientValidResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return APIKeyClientValidResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return APIKeyClientValidResponse{}, err + } + return APIKeyClientValidResponse{}, nil +} + +// validCreateRequest creates the Valid request. +func (client *APIKeyClient) validCreateRequest(ctx context.Context, _ *APIKeyClientValidOptions) (*policy.Request, error) { + urlPath := "/authentication/api-key/valid" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/authentication/apikeygroup/zz_options.go b/test/http-specs/authentication/apikeygroup/zz_options.go new file mode 100644 index 000000000000..09533d84381d --- /dev/null +++ b/test/http-specs/authentication/apikeygroup/zz_options.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package apikeygroup + +// APIKeyClientInvalidOptions contains the optional parameters for the APIKeyClient.Invalid method. +type APIKeyClientInvalidOptions struct { + // placeholder for future optional parameters +} + +// APIKeyClientValidOptions contains the optional parameters for the APIKeyClient.Valid method. +type APIKeyClientValidOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/authentication/apikeygroup/zz_responses.go b/test/http-specs/authentication/apikeygroup/zz_responses.go new file mode 100644 index 000000000000..08ff46be0ebd --- /dev/null +++ b/test/http-specs/authentication/apikeygroup/zz_responses.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package apikeygroup + +// APIKeyClientInvalidResponse contains the response from method APIKeyClient.Invalid. +type APIKeyClientInvalidResponse struct { + // placeholder for future response values +} + +// APIKeyClientValidResponse contains the response from method APIKeyClient.Valid. +type APIKeyClientValidResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/authentication/apikeygroup/zz_version.go b/test/http-specs/authentication/apikeygroup/zz_version.go new file mode 100644 index 000000000000..7285afe519a8 --- /dev/null +++ b/test/http-specs/authentication/apikeygroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package apikeygroup + +const ( + moduleName = "apikeygroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/authentication/http/customgroup/LICENSE.txt b/test/http-specs/authentication/http/customgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/authentication/http/customgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/authentication/http/customgroup/custom_client.go b/test/http-specs/authentication/http/customgroup/custom_client.go new file mode 100644 index 000000000000..528af2f75fe3 --- /dev/null +++ b/test/http-specs/authentication/http/customgroup/custom_client.go @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package customgroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +func NewCustomClient(endpoint string, credential *azcore.KeyCredential, options *azcore.ClientOptions) (*CustomClient, error) { + internal, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{ + PerRetry: []policy.Policy{ + runtime.NewKeyCredentialPolicy(credential, "authorization", &runtime.KeyCredentialPolicyOptions{ + InsecureAllowCredentialWithHTTP: true, + Prefix: "SharedAccessKey ", + }), + }, + }, options) + if err != nil { + return nil, err + } + return &CustomClient{ + internal: internal, + endpoint: endpoint, + }, nil +} diff --git a/test/http-specs/authentication/http/customgroup/custom_client_test.go b/test/http-specs/authentication/http/customgroup/custom_client_test.go new file mode 100644 index 000000000000..9951711bba29 --- /dev/null +++ b/test/http-specs/authentication/http/customgroup/custom_client_test.go @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package customgroup_test + +import ( + "context" + "customgroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/stretchr/testify/require" +) + +func TestCustomClient_Invalid(t *testing.T) { + client, err := customgroup.NewCustomClient("http://localhost:3000", azcore.NewKeyCredential("invalid-key"), nil) + require.NoError(t, err) + resp, err := client.Invalid(context.Background(), nil) + require.Error(t, err) + require.Zero(t, resp) +} + +func TestCustomClient_Valid(t *testing.T) { + client, err := customgroup.NewCustomClient("http://localhost:3000", azcore.NewKeyCredential("valid-key"), nil) + require.NoError(t, err) + resp, err := client.Valid(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/authentication/http/customgroup/fake/zz_custom_server.go b/test/http-specs/authentication/http/customgroup/fake/zz_custom_server.go new file mode 100644 index 000000000000..2c11aaf9aca9 --- /dev/null +++ b/test/http-specs/authentication/http/customgroup/fake/zz_custom_server.go @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "customgroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// CustomServer is a fake server for instances of the customgroup.CustomClient type. +type CustomServer struct { + // Invalid is the fake for method CustomClient.Invalid + // HTTP status codes to indicate success: http.StatusNoContent + Invalid func(ctx context.Context, options *customgroup.CustomClientInvalidOptions) (resp azfake.Responder[customgroup.CustomClientInvalidResponse], errResp azfake.ErrorResponder) + + // Valid is the fake for method CustomClient.Valid + // HTTP status codes to indicate success: http.StatusNoContent + Valid func(ctx context.Context, options *customgroup.CustomClientValidOptions) (resp azfake.Responder[customgroup.CustomClientValidResponse], errResp azfake.ErrorResponder) +} + +// NewCustomServerTransport creates a new instance of CustomServerTransport with the provided implementation. +// The returned CustomServerTransport instance is connected to an instance of customgroup.CustomClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewCustomServerTransport(srv *CustomServer) *CustomServerTransport { + return &CustomServerTransport{srv: srv} +} + +// CustomServerTransport connects instances of customgroup.CustomClient to instances of CustomServer. +// Don't use this type directly, use NewCustomServerTransport instead. +type CustomServerTransport struct { + srv *CustomServer +} + +// Do implements the policy.Transporter interface for CustomServerTransport. +func (c *CustomServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *CustomServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if customServerTransportInterceptor != nil { + res.resp, res.err, intercepted = customServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "CustomClient.Invalid": + res.resp, res.err = c.dispatchInvalid(req) + case "CustomClient.Valid": + res.resp, res.err = c.dispatchValid(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *CustomServerTransport) dispatchInvalid(req *http.Request) (*http.Response, error) { + if c.srv.Invalid == nil { + return nil, &nonRetriableError{errors.New("fake for method Invalid not implemented")} + } + respr, errRespr := c.srv.Invalid(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *CustomServerTransport) dispatchValid(req *http.Request) (*http.Response, error) { + if c.srv.Valid == nil { + return nil, &nonRetriableError{errors.New("fake for method Valid not implemented")} + } + respr, errRespr := c.srv.Valid(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to CustomServerTransport +var customServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/authentication/http/customgroup/fake/zz_internal.go b/test/http-specs/authentication/http/customgroup/fake/zz_internal.go new file mode 100644 index 000000000000..705f81eacafe --- /dev/null +++ b/test/http-specs/authentication/http/customgroup/fake/zz_internal.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import "net/http" + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} diff --git a/test/http-specs/authentication/http/customgroup/go.mod b/test/http-specs/authentication/http/customgroup/go.mod new file mode 100644 index 000000000000..6bfee6a84aa0 --- /dev/null +++ b/test/http-specs/authentication/http/customgroup/go.mod @@ -0,0 +1,17 @@ +module customgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/authentication/http/customgroup/go.sum b/test/http-specs/authentication/http/customgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/authentication/http/customgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/authentication/http/customgroup/testdata/_metadata.json b/test/http-specs/authentication/http/customgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/authentication/http/customgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/authentication/http/customgroup/version.go b/test/http-specs/authentication/http/customgroup/version.go new file mode 100644 index 000000000000..35c73489a509 --- /dev/null +++ b/test/http-specs/authentication/http/customgroup/version.go @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package customgroup + +// suppress unused vars lint +var _ = moduleName +var _ = moduleVersion diff --git a/test/http-specs/authentication/http/customgroup/zz_custom_client.go b/test/http-specs/authentication/http/customgroup/zz_custom_client.go new file mode 100644 index 000000000000..22156c6c2a0d --- /dev/null +++ b/test/http-specs/authentication/http/customgroup/zz_custom_client.go @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package customgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// CustomClient - Illustrates clients generated with generic HTTP auth. +// Don't use this type directly, use a constructor function instead. +type CustomClient struct { + internal *azcore.Client + endpoint string +} + +// CustomClientOptions contains the optional values for creating a [CustomClient]. +type CustomClientOptions struct { + azcore.ClientOptions +} + +// Invalid - Check whether client is authenticated. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - CustomClientInvalidOptions contains the optional parameters for the CustomClient.Invalid method. +func (client *CustomClient) Invalid(ctx context.Context, options *CustomClientInvalidOptions) (CustomClientInvalidResponse, error) { + var err error + const operationName = "CustomClient.Invalid" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.invalidCreateRequest(ctx, options) + if err != nil { + return CustomClientInvalidResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CustomClientInvalidResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return CustomClientInvalidResponse{}, err + } + return CustomClientInvalidResponse{}, nil +} + +// invalidCreateRequest creates the Invalid request. +func (client *CustomClient) invalidCreateRequest(ctx context.Context, _ *CustomClientInvalidOptions) (*policy.Request, error) { + urlPath := "/authentication/http/custom/invalid" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Valid - Check whether client is authenticated +// If the operation fails it returns an *azcore.ResponseError type. +// - options - CustomClientValidOptions contains the optional parameters for the CustomClient.Valid method. +func (client *CustomClient) Valid(ctx context.Context, options *CustomClientValidOptions) (CustomClientValidResponse, error) { + var err error + const operationName = "CustomClient.Valid" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.validCreateRequest(ctx, options) + if err != nil { + return CustomClientValidResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CustomClientValidResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return CustomClientValidResponse{}, err + } + return CustomClientValidResponse{}, nil +} + +// validCreateRequest creates the Valid request. +func (client *CustomClient) validCreateRequest(ctx context.Context, _ *CustomClientValidOptions) (*policy.Request, error) { + urlPath := "/authentication/http/custom/valid" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/authentication/http/customgroup/zz_options.go b/test/http-specs/authentication/http/customgroup/zz_options.go new file mode 100644 index 000000000000..76576bbb2357 --- /dev/null +++ b/test/http-specs/authentication/http/customgroup/zz_options.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package customgroup + +// CustomClientInvalidOptions contains the optional parameters for the CustomClient.Invalid method. +type CustomClientInvalidOptions struct { + // placeholder for future optional parameters +} + +// CustomClientValidOptions contains the optional parameters for the CustomClient.Valid method. +type CustomClientValidOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/authentication/http/customgroup/zz_responses.go b/test/http-specs/authentication/http/customgroup/zz_responses.go new file mode 100644 index 000000000000..66539b85cc0a --- /dev/null +++ b/test/http-specs/authentication/http/customgroup/zz_responses.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package customgroup + +// CustomClientInvalidResponse contains the response from method CustomClient.Invalid. +type CustomClientInvalidResponse struct { + // placeholder for future response values +} + +// CustomClientValidResponse contains the response from method CustomClient.Valid. +type CustomClientValidResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/authentication/http/customgroup/zz_version.go b/test/http-specs/authentication/http/customgroup/zz_version.go new file mode 100644 index 000000000000..f576ed1c66d4 --- /dev/null +++ b/test/http-specs/authentication/http/customgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package customgroup + +const ( + moduleName = "customgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/authentication/oauth2group/LICENSE.txt b/test/http-specs/authentication/oauth2group/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/authentication/oauth2group/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/authentication/oauth2group/fake/zz_internal.go b/test/http-specs/authentication/oauth2group/fake/zz_internal.go new file mode 100644 index 000000000000..705f81eacafe --- /dev/null +++ b/test/http-specs/authentication/oauth2group/fake/zz_internal.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import "net/http" + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} diff --git a/test/http-specs/authentication/oauth2group/fake/zz_oauth2_server.go b/test/http-specs/authentication/oauth2group/fake/zz_oauth2_server.go new file mode 100644 index 000000000000..03c2f3044005 --- /dev/null +++ b/test/http-specs/authentication/oauth2group/fake/zz_oauth2_server.go @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "oauth2group" + "slices" +) + +// OAuth2Server is a fake server for instances of the oauth2group.OAuth2Client type. +type OAuth2Server struct { + // Invalid is the fake for method OAuth2Client.Invalid + // HTTP status codes to indicate success: http.StatusNoContent + Invalid func(ctx context.Context, options *oauth2group.OAuth2ClientInvalidOptions) (resp azfake.Responder[oauth2group.OAuth2ClientInvalidResponse], errResp azfake.ErrorResponder) + + // Valid is the fake for method OAuth2Client.Valid + // HTTP status codes to indicate success: http.StatusNoContent + Valid func(ctx context.Context, options *oauth2group.OAuth2ClientValidOptions) (resp azfake.Responder[oauth2group.OAuth2ClientValidResponse], errResp azfake.ErrorResponder) +} + +// NewOAuth2ServerTransport creates a new instance of OAuth2ServerTransport with the provided implementation. +// The returned OAuth2ServerTransport instance is connected to an instance of oauth2group.OAuth2Client via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOAuth2ServerTransport(srv *OAuth2Server) *OAuth2ServerTransport { + return &OAuth2ServerTransport{srv: srv} +} + +// OAuth2ServerTransport connects instances of oauth2group.OAuth2Client to instances of OAuth2Server. +// Don't use this type directly, use NewOAuth2ServerTransport instead. +type OAuth2ServerTransport struct { + srv *OAuth2Server +} + +// Do implements the policy.Transporter interface for OAuth2ServerTransport. +func (o *OAuth2ServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OAuth2ServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if oAuth2ServerTransportInterceptor != nil { + res.resp, res.err, intercepted = oAuth2ServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OAuth2Client.Invalid": + res.resp, res.err = o.dispatchInvalid(req) + case "OAuth2Client.Valid": + res.resp, res.err = o.dispatchValid(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OAuth2ServerTransport) dispatchInvalid(req *http.Request) (*http.Response, error) { + if o.srv.Invalid == nil { + return nil, &nonRetriableError{errors.New("fake for method Invalid not implemented")} + } + respr, errRespr := o.srv.Invalid(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OAuth2ServerTransport) dispatchValid(req *http.Request) (*http.Response, error) { + if o.srv.Valid == nil { + return nil, &nonRetriableError{errors.New("fake for method Valid not implemented")} + } + respr, errRespr := o.srv.Valid(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OAuth2ServerTransport +var oAuth2ServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/authentication/oauth2group/go.mod b/test/http-specs/authentication/oauth2group/go.mod new file mode 100644 index 000000000000..9d79cf1ee3c9 --- /dev/null +++ b/test/http-specs/authentication/oauth2group/go.mod @@ -0,0 +1,17 @@ +module oauth2group + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/authentication/oauth2group/go.sum b/test/http-specs/authentication/oauth2group/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/authentication/oauth2group/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/authentication/oauth2group/oauth2_client_test.go b/test/http-specs/authentication/oauth2group/oauth2_client_test.go new file mode 100644 index 000000000000..e176a915a919 --- /dev/null +++ b/test/http-specs/authentication/oauth2group/oauth2_client_test.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package oauth2group_test + +import ( + "context" + "net/http" + "oauth2group" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/stretchr/testify/require" +) + +type fakeCredential struct{} + +func (mc fakeCredential) GetToken(context.Context, policy.TokenRequestOptions) (azcore.AccessToken, error) { + return azcore.AccessToken{Token: "https://security.microsoft.com/.default", ExpiresOn: time.Now().Add(time.Hour)}, nil +} + +func TestInvalid(t *testing.T) { + client, err := oauth2group.NewOAuth2Client("http://localhost:3000", &fakeCredential{}, &oauth2group.OAuth2ClientOptions{ + ClientOptions: azcore.ClientOptions{ + InsecureAllowCredentialWithHTTP: true, + }, + }) + require.NoError(t, err) + resp, err := client.Invalid(context.Background(), nil) + var respErr *azcore.ResponseError + require.ErrorAs(t, err, &respErr) + require.EqualValues(t, http.StatusForbidden, respErr.StatusCode) + require.Zero(t, resp) +} + +func TestValid(t *testing.T) { + client, err := oauth2group.NewOAuth2Client("http://localhost:3000", &fakeCredential{}, &oauth2group.OAuth2ClientOptions{ + ClientOptions: azcore.ClientOptions{ + InsecureAllowCredentialWithHTTP: true, + }, + }) + require.NoError(t, err) + resp, err := client.Valid(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/authentication/oauth2group/testdata/_metadata.json b/test/http-specs/authentication/oauth2group/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/authentication/oauth2group/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/authentication/oauth2group/zz_cloud_config.go b/test/http-specs/authentication/oauth2group/zz_cloud_config.go new file mode 100644 index 000000000000..5f78645372df --- /dev/null +++ b/test/http-specs/authentication/oauth2group/zz_cloud_config.go @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package oauth2group + +import "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" + +// ServiceName is the [cloud.ServiceName] for this module, used to identify the respective [cloud.ServiceConfiguration]. +const ServiceName cloud.ServiceName = "oauth2group" + +func init() { + cloud.AzurePublic.Services[ServiceName] = cloud.ServiceConfiguration{ + Audience: "https://security.microsoft.com", + } +} diff --git a/test/http-specs/authentication/oauth2group/zz_oauth2_client.go b/test/http-specs/authentication/oauth2group/zz_oauth2_client.go new file mode 100644 index 000000000000..0d22f057195e --- /dev/null +++ b/test/http-specs/authentication/oauth2group/zz_oauth2_client.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package oauth2group + +import ( + "context" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "reflect" +) + +// OAuth2Client - Illustrates clients generated with OAuth2 authentication. +// Don't use this type directly, use NewOAuth2Client() instead. +type OAuth2Client struct { + internal *azcore.Client + endpoint string +} + +// OAuth2ClientOptions contains the optional values for creating a [OAuth2Client]. +type OAuth2ClientOptions struct { + azcore.ClientOptions +} + +// NewOAuth2Client creates a new instance of OAuth2Client with the specified values. +// - endpoint - Service host +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewOAuth2Client(endpoint string, credential azcore.TokenCredential, options *OAuth2ClientOptions) (*OAuth2Client, error) { + if options == nil { + options = &OAuth2ClientOptions{} + } + if reflect.ValueOf(options.Cloud).IsZero() { + options.Cloud = cloud.AzurePublic + } + c, ok := options.Cloud.Services[ServiceName] + if !ok { + return nil, fmt.Errorf("provided Cloud field is missing configuration for %s", ServiceName) + } else if c.Audience == "" { + return nil, fmt.Errorf("provided Cloud field is missing Audience for %s", ServiceName) + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{ + PerCall: []policy.Policy{ + runtime.NewBearerTokenPolicy(credential, []string{c.Audience + "/.default"}, &policy.BearerTokenOptions{ + InsecureAllowCredentialWithHTTP: options.InsecureAllowCredentialWithHTTP, + }), + }, + }, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &OAuth2Client{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// Invalid - Check whether client is authenticated. Will return an invalid bearer error. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OAuth2ClientInvalidOptions contains the optional parameters for the OAuth2Client.Invalid method. +func (client *OAuth2Client) Invalid(ctx context.Context, options *OAuth2ClientInvalidOptions) (OAuth2ClientInvalidResponse, error) { + var err error + const operationName = "OAuth2Client.Invalid" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.invalidCreateRequest(ctx, options) + if err != nil { + return OAuth2ClientInvalidResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OAuth2ClientInvalidResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OAuth2ClientInvalidResponse{}, err + } + return OAuth2ClientInvalidResponse{}, nil +} + +// invalidCreateRequest creates the Invalid request. +func (client *OAuth2Client) invalidCreateRequest(ctx context.Context, _ *OAuth2ClientInvalidOptions) (*policy.Request, error) { + urlPath := "/authentication/oauth2/invalid" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Valid - Check whether client is authenticated +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OAuth2ClientValidOptions contains the optional parameters for the OAuth2Client.Valid method. +func (client *OAuth2Client) Valid(ctx context.Context, options *OAuth2ClientValidOptions) (OAuth2ClientValidResponse, error) { + var err error + const operationName = "OAuth2Client.Valid" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.validCreateRequest(ctx, options) + if err != nil { + return OAuth2ClientValidResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OAuth2ClientValidResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OAuth2ClientValidResponse{}, err + } + return OAuth2ClientValidResponse{}, nil +} + +// validCreateRequest creates the Valid request. +func (client *OAuth2Client) validCreateRequest(ctx context.Context, _ *OAuth2ClientValidOptions) (*policy.Request, error) { + urlPath := "/authentication/oauth2/valid" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/authentication/oauth2group/zz_options.go b/test/http-specs/authentication/oauth2group/zz_options.go new file mode 100644 index 000000000000..955051fa2114 --- /dev/null +++ b/test/http-specs/authentication/oauth2group/zz_options.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package oauth2group + +// OAuth2ClientInvalidOptions contains the optional parameters for the OAuth2Client.Invalid method. +type OAuth2ClientInvalidOptions struct { + // placeholder for future optional parameters +} + +// OAuth2ClientValidOptions contains the optional parameters for the OAuth2Client.Valid method. +type OAuth2ClientValidOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/authentication/oauth2group/zz_responses.go b/test/http-specs/authentication/oauth2group/zz_responses.go new file mode 100644 index 000000000000..95ec1e8851f2 --- /dev/null +++ b/test/http-specs/authentication/oauth2group/zz_responses.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package oauth2group + +// OAuth2ClientInvalidResponse contains the response from method OAuth2Client.Invalid. +type OAuth2ClientInvalidResponse struct { + // placeholder for future response values +} + +// OAuth2ClientValidResponse contains the response from method OAuth2Client.Valid. +type OAuth2ClientValidResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/authentication/oauth2group/zz_version.go b/test/http-specs/authentication/oauth2group/zz_version.go new file mode 100644 index 000000000000..bdd0af096d8e --- /dev/null +++ b/test/http-specs/authentication/oauth2group/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package oauth2group + +const ( + moduleName = "oauth2group" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/authentication/unionauthgroup/LICENSE.txt b/test/http-specs/authentication/unionauthgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/authentication/unionauthgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/authentication/unionauthgroup/fake/zz_internal.go b/test/http-specs/authentication/unionauthgroup/fake/zz_internal.go new file mode 100644 index 000000000000..705f81eacafe --- /dev/null +++ b/test/http-specs/authentication/unionauthgroup/fake/zz_internal.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import "net/http" + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} diff --git a/test/http-specs/authentication/unionauthgroup/fake/zz_union_server.go b/test/http-specs/authentication/unionauthgroup/fake/zz_union_server.go new file mode 100644 index 000000000000..2375ef89ca91 --- /dev/null +++ b/test/http-specs/authentication/unionauthgroup/fake/zz_union_server.go @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "unionauthgroup" +) + +// UnionServer is a fake server for instances of the unionauthgroup.UnionClient type. +type UnionServer struct { + // ValidKey is the fake for method UnionClient.ValidKey + // HTTP status codes to indicate success: http.StatusNoContent + ValidKey func(ctx context.Context, options *unionauthgroup.UnionClientValidKeyOptions) (resp azfake.Responder[unionauthgroup.UnionClientValidKeyResponse], errResp azfake.ErrorResponder) + + // ValidToken is the fake for method UnionClient.ValidToken + // HTTP status codes to indicate success: http.StatusNoContent + ValidToken func(ctx context.Context, options *unionauthgroup.UnionClientValidTokenOptions) (resp azfake.Responder[unionauthgroup.UnionClientValidTokenResponse], errResp azfake.ErrorResponder) +} + +// NewUnionServerTransport creates a new instance of UnionServerTransport with the provided implementation. +// The returned UnionServerTransport instance is connected to an instance of unionauthgroup.UnionClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewUnionServerTransport(srv *UnionServer) *UnionServerTransport { + return &UnionServerTransport{srv: srv} +} + +// UnionServerTransport connects instances of unionauthgroup.UnionClient to instances of UnionServer. +// Don't use this type directly, use NewUnionServerTransport instead. +type UnionServerTransport struct { + srv *UnionServer +} + +// Do implements the policy.Transporter interface for UnionServerTransport. +func (u *UnionServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return u.dispatchToMethodFake(req, method) +} + +func (u *UnionServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if unionServerTransportInterceptor != nil { + res.resp, res.err, intercepted = unionServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "UnionClient.ValidKey": + res.resp, res.err = u.dispatchValidKey(req) + case "UnionClient.ValidToken": + res.resp, res.err = u.dispatchValidToken(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (u *UnionServerTransport) dispatchValidKey(req *http.Request) (*http.Response, error) { + if u.srv.ValidKey == nil { + return nil, &nonRetriableError{errors.New("fake for method ValidKey not implemented")} + } + respr, errRespr := u.srv.ValidKey(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (u *UnionServerTransport) dispatchValidToken(req *http.Request) (*http.Response, error) { + if u.srv.ValidToken == nil { + return nil, &nonRetriableError{errors.New("fake for method ValidToken not implemented")} + } + respr, errRespr := u.srv.ValidToken(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to UnionServerTransport +var unionServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/authentication/unionauthgroup/go.mod b/test/http-specs/authentication/unionauthgroup/go.mod new file mode 100644 index 000000000000..a714478b6679 --- /dev/null +++ b/test/http-specs/authentication/unionauthgroup/go.mod @@ -0,0 +1,17 @@ +module unionauthgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/authentication/unionauthgroup/go.sum b/test/http-specs/authentication/unionauthgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/authentication/unionauthgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/authentication/unionauthgroup/testdata/_metadata.json b/test/http-specs/authentication/unionauthgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/authentication/unionauthgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/authentication/unionauthgroup/union_client_test.go b/test/http-specs/authentication/unionauthgroup/union_client_test.go new file mode 100644 index 000000000000..34a773cc9268 --- /dev/null +++ b/test/http-specs/authentication/unionauthgroup/union_client_test.go @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package unionauthgroup_test + +import ( + "context" + "testing" + "time" + "unionauthgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/stretchr/testify/require" +) + +type fakeCredential struct{} + +func (mc fakeCredential) GetToken(context.Context, policy.TokenRequestOptions) (azcore.AccessToken, error) { + return azcore.AccessToken{Token: "https://security.microsoft.com/.default", ExpiresOn: time.Now().Add(time.Hour)}, nil +} + +func TestValidKey(t *testing.T) { + t.Skip("API key credential is not supported") +} + +func TestValidToken(t *testing.T) { + client, err := unionauthgroup.NewUnionClient("http://localhost:3000", &fakeCredential{}, &unionauthgroup.UnionClientOptions{ + ClientOptions: azcore.ClientOptions{ + InsecureAllowCredentialWithHTTP: true, + }, + }) + require.NoError(t, err) + resp, err := client.ValidToken(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/authentication/unionauthgroup/zz_cloud_config.go b/test/http-specs/authentication/unionauthgroup/zz_cloud_config.go new file mode 100644 index 000000000000..66d8c0a0a098 --- /dev/null +++ b/test/http-specs/authentication/unionauthgroup/zz_cloud_config.go @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package unionauthgroup + +import "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" + +// ServiceName is the [cloud.ServiceName] for this module, used to identify the respective [cloud.ServiceConfiguration]. +const ServiceName cloud.ServiceName = "unionauthgroup" + +func init() { + cloud.AzurePublic.Services[ServiceName] = cloud.ServiceConfiguration{ + Audience: "https://security.microsoft.com", + } +} diff --git a/test/http-specs/authentication/unionauthgroup/zz_options.go b/test/http-specs/authentication/unionauthgroup/zz_options.go new file mode 100644 index 000000000000..577b72cdfc78 --- /dev/null +++ b/test/http-specs/authentication/unionauthgroup/zz_options.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package unionauthgroup + +// UnionClientValidKeyOptions contains the optional parameters for the UnionClient.ValidKey method. +type UnionClientValidKeyOptions struct { + // placeholder for future optional parameters +} + +// UnionClientValidTokenOptions contains the optional parameters for the UnionClient.ValidToken method. +type UnionClientValidTokenOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/authentication/unionauthgroup/zz_responses.go b/test/http-specs/authentication/unionauthgroup/zz_responses.go new file mode 100644 index 000000000000..f7aa9b8034e1 --- /dev/null +++ b/test/http-specs/authentication/unionauthgroup/zz_responses.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package unionauthgroup + +// UnionClientValidKeyResponse contains the response from method UnionClient.ValidKey. +type UnionClientValidKeyResponse struct { + // placeholder for future response values +} + +// UnionClientValidTokenResponse contains the response from method UnionClient.ValidToken. +type UnionClientValidTokenResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/authentication/unionauthgroup/zz_union_client.go b/test/http-specs/authentication/unionauthgroup/zz_union_client.go new file mode 100644 index 000000000000..8c4cc3d42adc --- /dev/null +++ b/test/http-specs/authentication/unionauthgroup/zz_union_client.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package unionauthgroup + +import ( + "context" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "reflect" +) + +// UnionClient - Illustrates clients generated with ApiKey and OAuth2 authentication. +// Don't use this type directly, use NewUnionClient() instead. +type UnionClient struct { + internal *azcore.Client + endpoint string +} + +// UnionClientOptions contains the optional values for creating a [UnionClient]. +type UnionClientOptions struct { + azcore.ClientOptions +} + +// NewUnionClient creates a new instance of UnionClient with the specified values. +// - endpoint - Service host +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewUnionClient(endpoint string, credential azcore.TokenCredential, options *UnionClientOptions) (*UnionClient, error) { + if options == nil { + options = &UnionClientOptions{} + } + if reflect.ValueOf(options.Cloud).IsZero() { + options.Cloud = cloud.AzurePublic + } + c, ok := options.Cloud.Services[ServiceName] + if !ok { + return nil, fmt.Errorf("provided Cloud field is missing configuration for %s", ServiceName) + } else if c.Audience == "" { + return nil, fmt.Errorf("provided Cloud field is missing Audience for %s", ServiceName) + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{ + PerCall: []policy.Policy{ + runtime.NewBearerTokenPolicy(credential, []string{c.Audience + "/.default"}, &policy.BearerTokenOptions{ + InsecureAllowCredentialWithHTTP: options.InsecureAllowCredentialWithHTTP, + }), + }, + }, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &UnionClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// ValidKey - Check whether client is authenticated +// If the operation fails it returns an *azcore.ResponseError type. +// - options - UnionClientValidKeyOptions contains the optional parameters for the UnionClient.ValidKey method. +func (client *UnionClient) ValidKey(ctx context.Context, options *UnionClientValidKeyOptions) (UnionClientValidKeyResponse, error) { + var err error + const operationName = "UnionClient.ValidKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.validKeyCreateRequest(ctx, options) + if err != nil { + return UnionClientValidKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return UnionClientValidKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return UnionClientValidKeyResponse{}, err + } + return UnionClientValidKeyResponse{}, nil +} + +// validKeyCreateRequest creates the ValidKey request. +func (client *UnionClient) validKeyCreateRequest(ctx context.Context, _ *UnionClientValidKeyOptions) (*policy.Request, error) { + urlPath := "/authentication/union/validkey" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// ValidToken - Check whether client is authenticated +// If the operation fails it returns an *azcore.ResponseError type. +// - options - UnionClientValidTokenOptions contains the optional parameters for the UnionClient.ValidToken method. +func (client *UnionClient) ValidToken(ctx context.Context, options *UnionClientValidTokenOptions) (UnionClientValidTokenResponse, error) { + var err error + const operationName = "UnionClient.ValidToken" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.validTokenCreateRequest(ctx, options) + if err != nil { + return UnionClientValidTokenResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return UnionClientValidTokenResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return UnionClientValidTokenResponse{}, err + } + return UnionClientValidTokenResponse{}, nil +} + +// validTokenCreateRequest creates the ValidToken request. +func (client *UnionClient) validTokenCreateRequest(ctx context.Context, _ *UnionClientValidTokenOptions) (*policy.Request, error) { + urlPath := "/authentication/union/validtoken" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/authentication/unionauthgroup/zz_version.go b/test/http-specs/authentication/unionauthgroup/zz_version.go new file mode 100644 index 000000000000..91bed09ab8c5 --- /dev/null +++ b/test/http-specs/authentication/unionauthgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package unionauthgroup + +const ( + moduleName = "unionauthgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/encode/bytesgroup/LICENSE.txt b/test/http-specs/encode/bytesgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/encode/bytesgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/encode/bytesgroup/custom_client_test.go b/test/http-specs/encode/bytesgroup/custom_client_test.go new file mode 100644 index 000000000000..e59c7237a00a --- /dev/null +++ b/test/http-specs/encode/bytesgroup/custom_client_test.go @@ -0,0 +1,225 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package bytesgroup_test + +import ( + "bytesgroup" + "context" + "io" + "os" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestHeaderClientBase64(t *testing.T) { + client, err := bytesgroup.NewBytesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewBytesHeaderClient().Base64(context.Background(), []byte("test"), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestHeaderClientBase64URL(t *testing.T) { + client, err := bytesgroup.NewBytesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewBytesHeaderClient().Base64URL(context.Background(), []byte("test"), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestHeaderClientBase64URLArray(t *testing.T) { + client, err := bytesgroup.NewBytesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewBytesHeaderClient().Base64URLArray(context.Background(), [][]byte{[]byte("test"), []byte("test")}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestHeaderClientDefault(t *testing.T) { + client, err := bytesgroup.NewBytesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewBytesHeaderClient().Default(context.Background(), []byte("test"), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestPropertyClientBase64(t *testing.T) { + client, err := bytesgroup.NewBytesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewBytesPropertyClient().Base64(context.Background(), bytesgroup.Base64BytesProperty{ + Value: []byte("test"), + }, nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, []byte("test"), resp.Value) +} + +func TestPropertyClientBase64URL(t *testing.T) { + client, err := bytesgroup.NewBytesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewBytesPropertyClient().Base64URL(context.Background(), bytesgroup.Base64URLBytesProperty{ + Value: []byte("test"), + }, nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, []byte("test"), resp.Value) +} + +func TestPropertyClientBase64URLArray(t *testing.T) { + client, err := bytesgroup.NewBytesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewBytesPropertyClient().Base64URLArray(context.Background(), bytesgroup.Base64URLArrayBytesProperty{ + Value: [][]byte{[]byte("test"), []byte("test")}, + }, nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, [][]byte{[]byte("test"), []byte("test")}, resp.Value) +} + +func TestPropertyClientDefault(t *testing.T) { + client, err := bytesgroup.NewBytesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewBytesPropertyClient().Default(context.Background(), bytesgroup.DefaultBytesProperty{ + Value: []byte("test"), + }, nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, []byte("test"), resp.Value) +} + +func TestQueryClientBase64(t *testing.T) { + client, err := bytesgroup.NewBytesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewBytesQueryClient().Base64(context.Background(), []byte("test"), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestQueryClientBase64URL(t *testing.T) { + client, err := bytesgroup.NewBytesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewBytesQueryClient().Base64URL(context.Background(), []byte("test"), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestQueryClientBase64URLArray(t *testing.T) { + client, err := bytesgroup.NewBytesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewBytesQueryClient().Base64URLArray(context.Background(), [][]byte{[]byte("test"), []byte("test")}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestQueryClientDefault(t *testing.T) { + client, err := bytesgroup.NewBytesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewBytesQueryClient().Default(context.Background(), []byte("test"), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestRequestBodyClientBase64(t *testing.T) { + client, err := bytesgroup.NewBytesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewBytesRequestBodyClient().Base64(context.Background(), []byte("test"), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestRequestBodyClientBase64URL(t *testing.T) { + client, err := bytesgroup.NewBytesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewBytesRequestBodyClient().Base64URL(context.Background(), []byte("test"), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestRequestBodyClientCustomContentType(t *testing.T) { + client, err := bytesgroup.NewBytesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + pngFile, err := os.OpenFile("../../../../node_modules/@typespec/http-specs/assets/image.png", os.O_RDONLY, 0) + require.NoError(t, err) + resp, err := client.NewBytesRequestBodyClient().CustomContentType(context.Background(), pngFile, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestRequestBodyClientDefault(t *testing.T) { + client, err := bytesgroup.NewBytesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + pngFile, err := os.OpenFile("../../../../node_modules/@typespec/http-specs/assets/image.png", os.O_RDONLY, 0) + require.NoError(t, err) + resp, err := client.NewBytesRequestBodyClient().Default(context.Background(), pngFile, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestRequestBodyClientOctetStream(t *testing.T) { + client, err := bytesgroup.NewBytesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + pngFile, err := os.OpenFile("../../../../node_modules/@typespec/http-specs/assets/image.png", os.O_RDONLY, 0) + require.NoError(t, err) + resp, err := client.NewBytesRequestBodyClient().OctetStream(context.Background(), pngFile, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestResponseBodyClientBase64(t *testing.T) { + client, err := bytesgroup.NewBytesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewBytesResponseBodyClient().Base64(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, []byte("test"), resp.Value) +} + +func TestResponseBodyClientBase64URL(t *testing.T) { + client, err := bytesgroup.NewBytesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewBytesResponseBodyClient().Base64URL(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, []byte("test"), resp.Value) +} + +func TestResponseBodyClientCustomContent(t *testing.T) { + client, err := bytesgroup.NewBytesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewBytesResponseBodyClient().CustomContentType(context.Background(), nil) + require.NoError(t, err) + respBody, err := io.ReadAll(resp.Body) + require.NoError(t, err) + require.NoError(t, resp.Body.Close()) + pngFile, err := os.ReadFile("../../../../node_modules/@typespec/http-specs/assets/image.png") + require.NoError(t, err) + require.EqualValues(t, pngFile, respBody) +} + +func TestResponseBodyClientDefault(t *testing.T) { + client, err := bytesgroup.NewBytesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewBytesResponseBodyClient().Default(context.Background(), nil) + require.NoError(t, err) + respBody, err := io.ReadAll(resp.Body) + require.NoError(t, err) + require.NoError(t, resp.Body.Close()) + pngFile, err := os.ReadFile("../../../../node_modules/@typespec/http-specs/assets/image.png") + require.NoError(t, err) + require.EqualValues(t, pngFile, respBody) +} + +func TestResponseBodyClientOctetStream(t *testing.T) { + client, err := bytesgroup.NewBytesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewBytesResponseBodyClient().OctetStream(context.Background(), nil) + require.NoError(t, err) + respBody, err := io.ReadAll(resp.Body) + require.NoError(t, err) + require.NoError(t, resp.Body.Close()) + pngFile, err := os.ReadFile("../../../../node_modules/@typespec/http-specs/assets/image.png") + require.NoError(t, err) + require.EqualValues(t, pngFile, respBody) +} diff --git a/test/http-specs/encode/bytesgroup/fake/zz_bytes_server.go b/test/http-specs/encode/bytesgroup/fake/zz_bytes_server.go new file mode 100644 index 000000000000..226d65fc2272 --- /dev/null +++ b/test/http-specs/encode/bytesgroup/fake/zz_bytes_server.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// BytesServer is a fake server for instances of the bytesgroup.BytesClient type. +type BytesServer struct { + // BytesHeaderServer contains the fakes for client BytesHeaderClient + BytesHeaderServer BytesHeaderServer + + // BytesPropertyServer contains the fakes for client BytesPropertyClient + BytesPropertyServer BytesPropertyServer + + // BytesQueryServer contains the fakes for client BytesQueryClient + BytesQueryServer BytesQueryServer + + // BytesRequestBodyServer contains the fakes for client BytesRequestBodyClient + BytesRequestBodyServer BytesRequestBodyServer + + // BytesResponseBodyServer contains the fakes for client BytesResponseBodyClient + BytesResponseBodyServer BytesResponseBodyServer +} + +// NewBytesServerTransport creates a new instance of BytesServerTransport with the provided implementation. +// The returned BytesServerTransport instance is connected to an instance of bytesgroup.BytesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewBytesServerTransport(srv *BytesServer) *BytesServerTransport { + return &BytesServerTransport{srv: srv} +} + +// BytesServerTransport connects instances of bytesgroup.BytesClient to instances of BytesServer. +// Don't use this type directly, use NewBytesServerTransport instead. +type BytesServerTransport struct { + srv *BytesServer + trMu sync.Mutex + trBytesHeaderServer *BytesHeaderServerTransport + trBytesPropertyServer *BytesPropertyServerTransport + trBytesQueryServer *BytesQueryServerTransport + trBytesRequestBodyServer *BytesRequestBodyServerTransport + trBytesResponseBodyServer *BytesResponseBodyServerTransport +} + +// Do implements the policy.Transporter interface for BytesServerTransport. +func (b *BytesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return b.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (b *BytesServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "BytesHeaderClient": + initServer(&b.trMu, &b.trBytesHeaderServer, func() *BytesHeaderServerTransport { + return NewBytesHeaderServerTransport(&b.srv.BytesHeaderServer) + }) + resp, err = b.trBytesHeaderServer.Do(req) + case "BytesPropertyClient": + initServer(&b.trMu, &b.trBytesPropertyServer, func() *BytesPropertyServerTransport { + return NewBytesPropertyServerTransport(&b.srv.BytesPropertyServer) + }) + resp, err = b.trBytesPropertyServer.Do(req) + case "BytesQueryClient": + initServer(&b.trMu, &b.trBytesQueryServer, func() *BytesQueryServerTransport { + return NewBytesQueryServerTransport(&b.srv.BytesQueryServer) + }) + resp, err = b.trBytesQueryServer.Do(req) + case "BytesRequestBodyClient": + initServer(&b.trMu, &b.trBytesRequestBodyServer, func() *BytesRequestBodyServerTransport { + return NewBytesRequestBodyServerTransport(&b.srv.BytesRequestBodyServer) + }) + resp, err = b.trBytesRequestBodyServer.Do(req) + case "BytesResponseBodyClient": + initServer(&b.trMu, &b.trBytesResponseBodyServer, func() *BytesResponseBodyServerTransport { + return NewBytesResponseBodyServerTransport(&b.srv.BytesResponseBodyServer) + }) + resp, err = b.trBytesResponseBodyServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to BytesServerTransport +var bytesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/encode/bytesgroup/fake/zz_bytesheader_server.go b/test/http-specs/encode/bytesgroup/fake/zz_bytesheader_server.go new file mode 100644 index 000000000000..101b81175011 --- /dev/null +++ b/test/http-specs/encode/bytesgroup/fake/zz_bytesheader_server.go @@ -0,0 +1,198 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "bytesgroup" + "context" + "encoding/base64" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// BytesHeaderServer is a fake server for instances of the bytesgroup.BytesHeaderClient type. +type BytesHeaderServer struct { + // Base64 is the fake for method BytesHeaderClient.Base64 + // HTTP status codes to indicate success: http.StatusNoContent + Base64 func(ctx context.Context, value []byte, options *bytesgroup.BytesHeaderClientBase64Options) (resp azfake.Responder[bytesgroup.BytesHeaderClientBase64Response], errResp azfake.ErrorResponder) + + // Base64URL is the fake for method BytesHeaderClient.Base64URL + // HTTP status codes to indicate success: http.StatusNoContent + Base64URL func(ctx context.Context, value []byte, options *bytesgroup.BytesHeaderClientBase64URLOptions) (resp azfake.Responder[bytesgroup.BytesHeaderClientBase64URLResponse], errResp azfake.ErrorResponder) + + // Base64URLArray is the fake for method BytesHeaderClient.Base64URLArray + // HTTP status codes to indicate success: http.StatusNoContent + Base64URLArray func(ctx context.Context, value [][]byte, options *bytesgroup.BytesHeaderClientBase64URLArrayOptions) (resp azfake.Responder[bytesgroup.BytesHeaderClientBase64URLArrayResponse], errResp azfake.ErrorResponder) + + // Default is the fake for method BytesHeaderClient.Default + // HTTP status codes to indicate success: http.StatusNoContent + Default func(ctx context.Context, value []byte, options *bytesgroup.BytesHeaderClientDefaultOptions) (resp azfake.Responder[bytesgroup.BytesHeaderClientDefaultResponse], errResp azfake.ErrorResponder) +} + +// NewBytesHeaderServerTransport creates a new instance of BytesHeaderServerTransport with the provided implementation. +// The returned BytesHeaderServerTransport instance is connected to an instance of bytesgroup.BytesHeaderClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewBytesHeaderServerTransport(srv *BytesHeaderServer) *BytesHeaderServerTransport { + return &BytesHeaderServerTransport{srv: srv} +} + +// BytesHeaderServerTransport connects instances of bytesgroup.BytesHeaderClient to instances of BytesHeaderServer. +// Don't use this type directly, use NewBytesHeaderServerTransport instead. +type BytesHeaderServerTransport struct { + srv *BytesHeaderServer +} + +// Do implements the policy.Transporter interface for BytesHeaderServerTransport. +func (b *BytesHeaderServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return b.dispatchToMethodFake(req, method) +} + +func (b *BytesHeaderServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if bytesHeaderServerTransportInterceptor != nil { + res.resp, res.err, intercepted = bytesHeaderServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "BytesHeaderClient.Base64": + res.resp, res.err = b.dispatchBase64(req) + case "BytesHeaderClient.Base64URL": + res.resp, res.err = b.dispatchBase64URL(req) + case "BytesHeaderClient.Base64URLArray": + res.resp, res.err = b.dispatchBase64URLArray(req) + case "BytesHeaderClient.Default": + res.resp, res.err = b.dispatchDefault(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (b *BytesHeaderServerTransport) dispatchBase64(req *http.Request) (*http.Response, error) { + if b.srv.Base64 == nil { + return nil, &nonRetriableError{errors.New("fake for method Base64 not implemented")} + } + valueParam, err := base64.StdEncoding.DecodeString(getHeaderValue(req.Header, "value")) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.Base64(req.Context(), valueParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BytesHeaderServerTransport) dispatchBase64URL(req *http.Request) (*http.Response, error) { + if b.srv.Base64URL == nil { + return nil, &nonRetriableError{errors.New("fake for method Base64URL not implemented")} + } + valueParam, err := base64.URLEncoding.DecodeString(getHeaderValue(req.Header, "value")) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.Base64URL(req.Context(), valueParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BytesHeaderServerTransport) dispatchBase64URLArray(req *http.Request) (*http.Response, error) { + if b.srv.Base64URLArray == nil { + return nil, &nonRetriableError{errors.New("fake for method Base64URLArray not implemented")} + } + valueElements := splitHelper(getHeaderValue(req.Header, "value"), ",") + valueParam := make([][]byte, len(valueElements)) + for i := 0; i < len(valueElements); i++ { + parsedURL, parseErr := base64.URLEncoding.DecodeString(valueElements[i]) + if parseErr != nil { + return nil, parseErr + } + valueParam[i] = []byte(parsedURL) + } + respr, errRespr := b.srv.Base64URLArray(req.Context(), valueParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BytesHeaderServerTransport) dispatchDefault(req *http.Request) (*http.Response, error) { + if b.srv.Default == nil { + return nil, &nonRetriableError{errors.New("fake for method Default not implemented")} + } + valueParam, err := base64.StdEncoding.DecodeString(getHeaderValue(req.Header, "value")) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.Default(req.Context(), valueParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to BytesHeaderServerTransport +var bytesHeaderServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/encode/bytesgroup/fake/zz_bytesproperty_server.go b/test/http-specs/encode/bytesgroup/fake/zz_bytesproperty_server.go new file mode 100644 index 000000000000..7d839260851c --- /dev/null +++ b/test/http-specs/encode/bytesgroup/fake/zz_bytesproperty_server.go @@ -0,0 +1,192 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "bytesgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// BytesPropertyServer is a fake server for instances of the bytesgroup.BytesPropertyClient type. +type BytesPropertyServer struct { + // Base64 is the fake for method BytesPropertyClient.Base64 + // HTTP status codes to indicate success: http.StatusOK + Base64 func(ctx context.Context, body bytesgroup.Base64BytesProperty, options *bytesgroup.BytesPropertyClientBase64Options) (resp azfake.Responder[bytesgroup.BytesPropertyClientBase64Response], errResp azfake.ErrorResponder) + + // Base64URL is the fake for method BytesPropertyClient.Base64URL + // HTTP status codes to indicate success: http.StatusOK + Base64URL func(ctx context.Context, body bytesgroup.Base64URLBytesProperty, options *bytesgroup.BytesPropertyClientBase64URLOptions) (resp azfake.Responder[bytesgroup.BytesPropertyClientBase64URLResponse], errResp azfake.ErrorResponder) + + // Base64URLArray is the fake for method BytesPropertyClient.Base64URLArray + // HTTP status codes to indicate success: http.StatusOK + Base64URLArray func(ctx context.Context, body bytesgroup.Base64URLArrayBytesProperty, options *bytesgroup.BytesPropertyClientBase64URLArrayOptions) (resp azfake.Responder[bytesgroup.BytesPropertyClientBase64URLArrayResponse], errResp azfake.ErrorResponder) + + // Default is the fake for method BytesPropertyClient.Default + // HTTP status codes to indicate success: http.StatusOK + Default func(ctx context.Context, body bytesgroup.DefaultBytesProperty, options *bytesgroup.BytesPropertyClientDefaultOptions) (resp azfake.Responder[bytesgroup.BytesPropertyClientDefaultResponse], errResp azfake.ErrorResponder) +} + +// NewBytesPropertyServerTransport creates a new instance of BytesPropertyServerTransport with the provided implementation. +// The returned BytesPropertyServerTransport instance is connected to an instance of bytesgroup.BytesPropertyClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewBytesPropertyServerTransport(srv *BytesPropertyServer) *BytesPropertyServerTransport { + return &BytesPropertyServerTransport{srv: srv} +} + +// BytesPropertyServerTransport connects instances of bytesgroup.BytesPropertyClient to instances of BytesPropertyServer. +// Don't use this type directly, use NewBytesPropertyServerTransport instead. +type BytesPropertyServerTransport struct { + srv *BytesPropertyServer +} + +// Do implements the policy.Transporter interface for BytesPropertyServerTransport. +func (b *BytesPropertyServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return b.dispatchToMethodFake(req, method) +} + +func (b *BytesPropertyServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if bytesPropertyServerTransportInterceptor != nil { + res.resp, res.err, intercepted = bytesPropertyServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "BytesPropertyClient.Base64": + res.resp, res.err = b.dispatchBase64(req) + case "BytesPropertyClient.Base64URL": + res.resp, res.err = b.dispatchBase64URL(req) + case "BytesPropertyClient.Base64URLArray": + res.resp, res.err = b.dispatchBase64URLArray(req) + case "BytesPropertyClient.Default": + res.resp, res.err = b.dispatchDefault(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (b *BytesPropertyServerTransport) dispatchBase64(req *http.Request) (*http.Response, error) { + if b.srv.Base64 == nil { + return nil, &nonRetriableError{errors.New("fake for method Base64 not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[bytesgroup.Base64BytesProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.Base64(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Base64BytesProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BytesPropertyServerTransport) dispatchBase64URL(req *http.Request) (*http.Response, error) { + if b.srv.Base64URL == nil { + return nil, &nonRetriableError{errors.New("fake for method Base64URL not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[bytesgroup.Base64URLBytesProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.Base64URL(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Base64URLBytesProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BytesPropertyServerTransport) dispatchBase64URLArray(req *http.Request) (*http.Response, error) { + if b.srv.Base64URLArray == nil { + return nil, &nonRetriableError{errors.New("fake for method Base64URLArray not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[bytesgroup.Base64URLArrayBytesProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.Base64URLArray(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Base64URLArrayBytesProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BytesPropertyServerTransport) dispatchDefault(req *http.Request) (*http.Response, error) { + if b.srv.Default == nil { + return nil, &nonRetriableError{errors.New("fake for method Default not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[bytesgroup.DefaultBytesProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.Default(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DefaultBytesProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to BytesPropertyServerTransport +var bytesPropertyServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/encode/bytesgroup/fake/zz_bytesquery_server.go b/test/http-specs/encode/bytesgroup/fake/zz_bytesquery_server.go new file mode 100644 index 000000000000..cfd710b58995 --- /dev/null +++ b/test/http-specs/encode/bytesgroup/fake/zz_bytesquery_server.go @@ -0,0 +1,202 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "bytesgroup" + "context" + "encoding/base64" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// BytesQueryServer is a fake server for instances of the bytesgroup.BytesQueryClient type. +type BytesQueryServer struct { + // Base64 is the fake for method BytesQueryClient.Base64 + // HTTP status codes to indicate success: http.StatusNoContent + Base64 func(ctx context.Context, value []byte, options *bytesgroup.BytesQueryClientBase64Options) (resp azfake.Responder[bytesgroup.BytesQueryClientBase64Response], errResp azfake.ErrorResponder) + + // Base64URL is the fake for method BytesQueryClient.Base64URL + // HTTP status codes to indicate success: http.StatusNoContent + Base64URL func(ctx context.Context, value []byte, options *bytesgroup.BytesQueryClientBase64URLOptions) (resp azfake.Responder[bytesgroup.BytesQueryClientBase64URLResponse], errResp azfake.ErrorResponder) + + // Base64URLArray is the fake for method BytesQueryClient.Base64URLArray + // HTTP status codes to indicate success: http.StatusNoContent + Base64URLArray func(ctx context.Context, value [][]byte, options *bytesgroup.BytesQueryClientBase64URLArrayOptions) (resp azfake.Responder[bytesgroup.BytesQueryClientBase64URLArrayResponse], errResp azfake.ErrorResponder) + + // Default is the fake for method BytesQueryClient.Default + // HTTP status codes to indicate success: http.StatusNoContent + Default func(ctx context.Context, value []byte, options *bytesgroup.BytesQueryClientDefaultOptions) (resp azfake.Responder[bytesgroup.BytesQueryClientDefaultResponse], errResp azfake.ErrorResponder) +} + +// NewBytesQueryServerTransport creates a new instance of BytesQueryServerTransport with the provided implementation. +// The returned BytesQueryServerTransport instance is connected to an instance of bytesgroup.BytesQueryClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewBytesQueryServerTransport(srv *BytesQueryServer) *BytesQueryServerTransport { + return &BytesQueryServerTransport{srv: srv} +} + +// BytesQueryServerTransport connects instances of bytesgroup.BytesQueryClient to instances of BytesQueryServer. +// Don't use this type directly, use NewBytesQueryServerTransport instead. +type BytesQueryServerTransport struct { + srv *BytesQueryServer +} + +// Do implements the policy.Transporter interface for BytesQueryServerTransport. +func (b *BytesQueryServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return b.dispatchToMethodFake(req, method) +} + +func (b *BytesQueryServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if bytesQueryServerTransportInterceptor != nil { + res.resp, res.err, intercepted = bytesQueryServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "BytesQueryClient.Base64": + res.resp, res.err = b.dispatchBase64(req) + case "BytesQueryClient.Base64URL": + res.resp, res.err = b.dispatchBase64URL(req) + case "BytesQueryClient.Base64URLArray": + res.resp, res.err = b.dispatchBase64URLArray(req) + case "BytesQueryClient.Default": + res.resp, res.err = b.dispatchDefault(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (b *BytesQueryServerTransport) dispatchBase64(req *http.Request) (*http.Response, error) { + if b.srv.Base64 == nil { + return nil, &nonRetriableError{errors.New("fake for method Base64 not implemented")} + } + qp := req.URL.Query() + valueParam, err := base64.StdEncoding.DecodeString(qp.Get("value")) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.Base64(req.Context(), valueParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BytesQueryServerTransport) dispatchBase64URL(req *http.Request) (*http.Response, error) { + if b.srv.Base64URL == nil { + return nil, &nonRetriableError{errors.New("fake for method Base64URL not implemented")} + } + qp := req.URL.Query() + valueParam, err := base64.URLEncoding.DecodeString(qp.Get("value")) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.Base64URL(req.Context(), valueParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BytesQueryServerTransport) dispatchBase64URLArray(req *http.Request) (*http.Response, error) { + if b.srv.Base64URLArray == nil { + return nil, &nonRetriableError{errors.New("fake for method Base64URLArray not implemented")} + } + qp := req.URL.Query() + valueElements := splitHelper(qp.Get("value"), ",") + valueParam := make([][]byte, len(valueElements)) + for i := 0; i < len(valueElements); i++ { + parsedURL, parseErr := base64.URLEncoding.DecodeString(valueElements[i]) + if parseErr != nil { + return nil, parseErr + } + valueParam[i] = []byte(parsedURL) + } + respr, errRespr := b.srv.Base64URLArray(req.Context(), valueParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BytesQueryServerTransport) dispatchDefault(req *http.Request) (*http.Response, error) { + if b.srv.Default == nil { + return nil, &nonRetriableError{errors.New("fake for method Default not implemented")} + } + qp := req.URL.Query() + valueParam, err := base64.StdEncoding.DecodeString(qp.Get("value")) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.Default(req.Context(), valueParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to BytesQueryServerTransport +var bytesQueryServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/encode/bytesgroup/fake/zz_bytesrequestbody_server.go b/test/http-specs/encode/bytesgroup/fake/zz_bytesrequestbody_server.go new file mode 100644 index 000000000000..6f5735bf3d87 --- /dev/null +++ b/test/http-specs/encode/bytesgroup/fake/zz_bytesrequestbody_server.go @@ -0,0 +1,210 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "bytesgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "io" + "net/http" + "slices" +) + +// BytesRequestBodyServer is a fake server for instances of the bytesgroup.BytesRequestBodyClient type. +type BytesRequestBodyServer struct { + // Base64 is the fake for method BytesRequestBodyClient.Base64 + // HTTP status codes to indicate success: http.StatusNoContent + Base64 func(ctx context.Context, value []byte, options *bytesgroup.BytesRequestBodyClientBase64Options) (resp azfake.Responder[bytesgroup.BytesRequestBodyClientBase64Response], errResp azfake.ErrorResponder) + + // Base64URL is the fake for method BytesRequestBodyClient.Base64URL + // HTTP status codes to indicate success: http.StatusNoContent + Base64URL func(ctx context.Context, value []byte, options *bytesgroup.BytesRequestBodyClientBase64URLOptions) (resp azfake.Responder[bytesgroup.BytesRequestBodyClientBase64URLResponse], errResp azfake.ErrorResponder) + + // CustomContentType is the fake for method BytesRequestBodyClient.CustomContentType + // HTTP status codes to indicate success: http.StatusNoContent + CustomContentType func(ctx context.Context, value io.ReadSeekCloser, options *bytesgroup.BytesRequestBodyClientCustomContentTypeOptions) (resp azfake.Responder[bytesgroup.BytesRequestBodyClientCustomContentTypeResponse], errResp azfake.ErrorResponder) + + // Default is the fake for method BytesRequestBodyClient.Default + // HTTP status codes to indicate success: http.StatusNoContent + Default func(ctx context.Context, value io.ReadSeekCloser, options *bytesgroup.BytesRequestBodyClientDefaultOptions) (resp azfake.Responder[bytesgroup.BytesRequestBodyClientDefaultResponse], errResp azfake.ErrorResponder) + + // OctetStream is the fake for method BytesRequestBodyClient.OctetStream + // HTTP status codes to indicate success: http.StatusNoContent + OctetStream func(ctx context.Context, value io.ReadSeekCloser, options *bytesgroup.BytesRequestBodyClientOctetStreamOptions) (resp azfake.Responder[bytesgroup.BytesRequestBodyClientOctetStreamResponse], errResp azfake.ErrorResponder) +} + +// NewBytesRequestBodyServerTransport creates a new instance of BytesRequestBodyServerTransport with the provided implementation. +// The returned BytesRequestBodyServerTransport instance is connected to an instance of bytesgroup.BytesRequestBodyClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewBytesRequestBodyServerTransport(srv *BytesRequestBodyServer) *BytesRequestBodyServerTransport { + return &BytesRequestBodyServerTransport{srv: srv} +} + +// BytesRequestBodyServerTransport connects instances of bytesgroup.BytesRequestBodyClient to instances of BytesRequestBodyServer. +// Don't use this type directly, use NewBytesRequestBodyServerTransport instead. +type BytesRequestBodyServerTransport struct { + srv *BytesRequestBodyServer +} + +// Do implements the policy.Transporter interface for BytesRequestBodyServerTransport. +func (b *BytesRequestBodyServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return b.dispatchToMethodFake(req, method) +} + +func (b *BytesRequestBodyServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if bytesRequestBodyServerTransportInterceptor != nil { + res.resp, res.err, intercepted = bytesRequestBodyServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "BytesRequestBodyClient.Base64": + res.resp, res.err = b.dispatchBase64(req) + case "BytesRequestBodyClient.Base64URL": + res.resp, res.err = b.dispatchBase64URL(req) + case "BytesRequestBodyClient.CustomContentType": + res.resp, res.err = b.dispatchCustomContentType(req) + case "BytesRequestBodyClient.Default": + res.resp, res.err = b.dispatchDefault(req) + case "BytesRequestBodyClient.OctetStream": + res.resp, res.err = b.dispatchOctetStream(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (b *BytesRequestBodyServerTransport) dispatchBase64(req *http.Request) (*http.Response, error) { + if b.srv.Base64 == nil { + return nil, &nonRetriableError{errors.New("fake for method Base64 not implemented")} + } + body, err := server.UnmarshalRequestAsByteArray(req, runtime.Base64StdFormat) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.Base64(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BytesRequestBodyServerTransport) dispatchBase64URL(req *http.Request) (*http.Response, error) { + if b.srv.Base64URL == nil { + return nil, &nonRetriableError{errors.New("fake for method Base64URL not implemented")} + } + body, err := server.UnmarshalRequestAsByteArray(req, runtime.Base64URLFormat) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.Base64URL(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BytesRequestBodyServerTransport) dispatchCustomContentType(req *http.Request) (*http.Response, error) { + if b.srv.CustomContentType == nil { + return nil, &nonRetriableError{errors.New("fake for method CustomContentType not implemented")} + } + respr, errRespr := b.srv.CustomContentType(req.Context(), req.Body.(io.ReadSeekCloser), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BytesRequestBodyServerTransport) dispatchDefault(req *http.Request) (*http.Response, error) { + if b.srv.Default == nil { + return nil, &nonRetriableError{errors.New("fake for method Default not implemented")} + } + respr, errRespr := b.srv.Default(req.Context(), req.Body.(io.ReadSeekCloser), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BytesRequestBodyServerTransport) dispatchOctetStream(req *http.Request) (*http.Response, error) { + if b.srv.OctetStream == nil { + return nil, &nonRetriableError{errors.New("fake for method OctetStream not implemented")} + } + respr, errRespr := b.srv.OctetStream(req.Context(), req.Body.(io.ReadSeekCloser), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to BytesRequestBodyServerTransport +var bytesRequestBodyServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/encode/bytesgroup/fake/zz_bytesresponsebody_server.go b/test/http-specs/encode/bytesgroup/fake/zz_bytesresponsebody_server.go new file mode 100644 index 000000000000..bdb861f41b0e --- /dev/null +++ b/test/http-specs/encode/bytesgroup/fake/zz_bytesresponsebody_server.go @@ -0,0 +1,216 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "bytesgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// BytesResponseBodyServer is a fake server for instances of the bytesgroup.BytesResponseBodyClient type. +type BytesResponseBodyServer struct { + // Base64 is the fake for method BytesResponseBodyClient.Base64 + // HTTP status codes to indicate success: http.StatusOK + Base64 func(ctx context.Context, options *bytesgroup.BytesResponseBodyClientBase64Options) (resp azfake.Responder[bytesgroup.BytesResponseBodyClientBase64Response], errResp azfake.ErrorResponder) + + // Base64URL is the fake for method BytesResponseBodyClient.Base64URL + // HTTP status codes to indicate success: http.StatusOK + Base64URL func(ctx context.Context, options *bytesgroup.BytesResponseBodyClientBase64URLOptions) (resp azfake.Responder[bytesgroup.BytesResponseBodyClientBase64URLResponse], errResp azfake.ErrorResponder) + + // CustomContentType is the fake for method BytesResponseBodyClient.CustomContentType + // HTTP status codes to indicate success: http.StatusOK + CustomContentType func(ctx context.Context, options *bytesgroup.BytesResponseBodyClientCustomContentTypeOptions) (resp azfake.Responder[bytesgroup.BytesResponseBodyClientCustomContentTypeResponse], errResp azfake.ErrorResponder) + + // Default is the fake for method BytesResponseBodyClient.Default + // HTTP status codes to indicate success: http.StatusOK + Default func(ctx context.Context, options *bytesgroup.BytesResponseBodyClientDefaultOptions) (resp azfake.Responder[bytesgroup.BytesResponseBodyClientDefaultResponse], errResp azfake.ErrorResponder) + + // OctetStream is the fake for method BytesResponseBodyClient.OctetStream + // HTTP status codes to indicate success: http.StatusOK + OctetStream func(ctx context.Context, options *bytesgroup.BytesResponseBodyClientOctetStreamOptions) (resp azfake.Responder[bytesgroup.BytesResponseBodyClientOctetStreamResponse], errResp azfake.ErrorResponder) +} + +// NewBytesResponseBodyServerTransport creates a new instance of BytesResponseBodyServerTransport with the provided implementation. +// The returned BytesResponseBodyServerTransport instance is connected to an instance of bytesgroup.BytesResponseBodyClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewBytesResponseBodyServerTransport(srv *BytesResponseBodyServer) *BytesResponseBodyServerTransport { + return &BytesResponseBodyServerTransport{srv: srv} +} + +// BytesResponseBodyServerTransport connects instances of bytesgroup.BytesResponseBodyClient to instances of BytesResponseBodyServer. +// Don't use this type directly, use NewBytesResponseBodyServerTransport instead. +type BytesResponseBodyServerTransport struct { + srv *BytesResponseBodyServer +} + +// Do implements the policy.Transporter interface for BytesResponseBodyServerTransport. +func (b *BytesResponseBodyServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return b.dispatchToMethodFake(req, method) +} + +func (b *BytesResponseBodyServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if bytesResponseBodyServerTransportInterceptor != nil { + res.resp, res.err, intercepted = bytesResponseBodyServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "BytesResponseBodyClient.Base64": + res.resp, res.err = b.dispatchBase64(req) + case "BytesResponseBodyClient.Base64URL": + res.resp, res.err = b.dispatchBase64URL(req) + case "BytesResponseBodyClient.CustomContentType": + res.resp, res.err = b.dispatchCustomContentType(req) + case "BytesResponseBodyClient.Default": + res.resp, res.err = b.dispatchDefault(req) + case "BytesResponseBodyClient.OctetStream": + res.resp, res.err = b.dispatchOctetStream(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (b *BytesResponseBodyServerTransport) dispatchBase64(req *http.Request) (*http.Response, error) { + if b.srv.Base64 == nil { + return nil, &nonRetriableError{errors.New("fake for method Base64 not implemented")} + } + respr, errRespr := b.srv.Base64(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsByteArray(respContent, server.GetResponse(respr).Value, runtime.Base64StdFormat, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BytesResponseBodyServerTransport) dispatchBase64URL(req *http.Request) (*http.Response, error) { + if b.srv.Base64URL == nil { + return nil, &nonRetriableError{errors.New("fake for method Base64URL not implemented")} + } + respr, errRespr := b.srv.Base64URL(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsByteArray(respContent, server.GetResponse(respr).Value, runtime.Base64URLFormat, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BytesResponseBodyServerTransport) dispatchCustomContentType(req *http.Request) (*http.Response, error) { + if b.srv.CustomContentType == nil { + return nil, &nonRetriableError{errors.New("fake for method CustomContentType not implemented")} + } + respr, errRespr := b.srv.CustomContentType(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, &server.ResponseOptions{ + Body: server.GetResponse(respr).Body, + ContentType: req.Header.Get("Content-Type"), + }) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).ContentType; val != nil { + resp.Header.Set("content-type", "image/png") + } + return resp, nil +} + +func (b *BytesResponseBodyServerTransport) dispatchDefault(req *http.Request) (*http.Response, error) { + if b.srv.Default == nil { + return nil, &nonRetriableError{errors.New("fake for method Default not implemented")} + } + respr, errRespr := b.srv.Default(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, &server.ResponseOptions{ + Body: server.GetResponse(respr).Body, + ContentType: req.Header.Get("Content-Type"), + }) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BytesResponseBodyServerTransport) dispatchOctetStream(req *http.Request) (*http.Response, error) { + if b.srv.OctetStream == nil { + return nil, &nonRetriableError{errors.New("fake for method OctetStream not implemented")} + } + respr, errRespr := b.srv.OctetStream(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, &server.ResponseOptions{ + Body: server.GetResponse(respr).Body, + ContentType: req.Header.Get("Content-Type"), + }) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).ContentType; val != nil { + resp.Header.Set("content-type", "application/octet-stream") + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to BytesResponseBodyServerTransport +var bytesResponseBodyServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/encode/bytesgroup/fake/zz_internal.go b/test/http-specs/encode/bytesgroup/fake/zz_internal.go new file mode 100644 index 000000000000..e07e08de861a --- /dev/null +++ b/test/http-specs/encode/bytesgroup/fake/zz_internal.go @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "strings" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getHeaderValue(h http.Header, k string) string { + v := h[k] + if len(v) == 0 { + return "" + } + return v[0] +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func splitHelper(s, sep string) []string { + if s == "" { + return nil + } + return strings.Split(s, sep) +} diff --git a/test/http-specs/encode/bytesgroup/go.mod b/test/http-specs/encode/bytesgroup/go.mod new file mode 100644 index 000000000000..205895b59705 --- /dev/null +++ b/test/http-specs/encode/bytesgroup/go.mod @@ -0,0 +1,17 @@ +module bytesgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/encode/bytesgroup/go.sum b/test/http-specs/encode/bytesgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/encode/bytesgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/encode/bytesgroup/testdata/_metadata.json b/test/http-specs/encode/bytesgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/encode/bytesgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/encode/bytesgroup/zz_bytes_client.go b/test/http-specs/encode/bytesgroup/zz_bytes_client.go new file mode 100644 index 000000000000..e447f14a57d6 --- /dev/null +++ b/test/http-specs/encode/bytesgroup/zz_bytes_client.go @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package bytesgroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// BytesClient - Test for encode decorator on bytes. +// Don't use this type directly, use NewBytesClientWithNoCredential() instead. +type BytesClient struct { + internal *azcore.Client + endpoint string +} + +// BytesClientOptions contains the optional values for creating a [BytesClient]. +type BytesClientOptions struct { + azcore.ClientOptions +} + +// NewBytesClientWithNoCredential creates a new instance of BytesClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewBytesClientWithNoCredential(endpoint string, options *BytesClientOptions) (*BytesClient, error) { + if options == nil { + options = &BytesClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &BytesClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewBytesHeaderClient creates a new instance of [BytesHeaderClient]. +func (client *BytesClient) NewBytesHeaderClient() *BytesHeaderClient { + return &BytesHeaderClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewBytesPropertyClient creates a new instance of [BytesPropertyClient]. +func (client *BytesClient) NewBytesPropertyClient() *BytesPropertyClient { + return &BytesPropertyClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewBytesQueryClient creates a new instance of [BytesQueryClient]. +func (client *BytesClient) NewBytesQueryClient() *BytesQueryClient { + return &BytesQueryClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewBytesRequestBodyClient creates a new instance of [BytesRequestBodyClient]. +func (client *BytesClient) NewBytesRequestBodyClient() *BytesRequestBodyClient { + return &BytesRequestBodyClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewBytesResponseBodyClient creates a new instance of [BytesResponseBodyClient]. +func (client *BytesClient) NewBytesResponseBodyClient() *BytesResponseBodyClient { + return &BytesResponseBodyClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/http-specs/encode/bytesgroup/zz_bytesheader_client.go b/test/http-specs/encode/bytesgroup/zz_bytesheader_client.go new file mode 100644 index 000000000000..13d7abc7c12f --- /dev/null +++ b/test/http-specs/encode/bytesgroup/zz_bytesheader_client.go @@ -0,0 +1,169 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package bytesgroup + +import ( + "context" + "encoding/base64" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// BytesHeaderClient contains the methods for the BytesHeader group. +// Don't use this type directly, use [BytesClient.NewBytesHeaderClient] instead. +type BytesHeaderClient struct { + internal *azcore.Client + endpoint string +} + +// Base64 - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BytesHeaderClientBase64Options contains the optional parameters for the BytesHeaderClient.Base64 method. +func (client *BytesHeaderClient) Base64(ctx context.Context, value []byte, options *BytesHeaderClientBase64Options) (BytesHeaderClientBase64Response, error) { + var err error + const operationName = "BytesHeaderClient.Base64" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.base64CreateRequest(ctx, value, options) + if err != nil { + return BytesHeaderClientBase64Response{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BytesHeaderClientBase64Response{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return BytesHeaderClientBase64Response{}, err + } + return BytesHeaderClientBase64Response{}, nil +} + +// base64CreateRequest creates the Base64 request. +func (client *BytesHeaderClient) base64CreateRequest(ctx context.Context, value []byte, _ *BytesHeaderClientBase64Options) (*policy.Request, error) { + urlPath := "/encode/bytes/header/base64" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["value"] = []string{base64.StdEncoding.EncodeToString(value)} + return req, nil +} + +// Base64URL - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BytesHeaderClientBase64URLOptions contains the optional parameters for the BytesHeaderClient.Base64URL method. +func (client *BytesHeaderClient) Base64URL(ctx context.Context, value []byte, options *BytesHeaderClientBase64URLOptions) (BytesHeaderClientBase64URLResponse, error) { + var err error + const operationName = "BytesHeaderClient.Base64URL" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.base64URLCreateRequest(ctx, value, options) + if err != nil { + return BytesHeaderClientBase64URLResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BytesHeaderClientBase64URLResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return BytesHeaderClientBase64URLResponse{}, err + } + return BytesHeaderClientBase64URLResponse{}, nil +} + +// base64URLCreateRequest creates the Base64URL request. +func (client *BytesHeaderClient) base64URLCreateRequest(ctx context.Context, value []byte, _ *BytesHeaderClientBase64URLOptions) (*policy.Request, error) { + urlPath := "/encode/bytes/header/base64url" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["value"] = []string{base64.RawURLEncoding.EncodeToString(value)} + return req, nil +} + +// Base64URLArray - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BytesHeaderClientBase64URLArrayOptions contains the optional parameters for the BytesHeaderClient.Base64URLArray +// method. +func (client *BytesHeaderClient) Base64URLArray(ctx context.Context, value [][]byte, options *BytesHeaderClientBase64URLArrayOptions) (BytesHeaderClientBase64URLArrayResponse, error) { + var err error + const operationName = "BytesHeaderClient.Base64URLArray" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.base64URLArrayCreateRequest(ctx, value, options) + if err != nil { + return BytesHeaderClientBase64URLArrayResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BytesHeaderClientBase64URLArrayResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return BytesHeaderClientBase64URLArrayResponse{}, err + } + return BytesHeaderClientBase64URLArrayResponse{}, nil +} + +// base64URLArrayCreateRequest creates the Base64URLArray request. +func (client *BytesHeaderClient) base64URLArrayCreateRequest(ctx context.Context, value [][]byte, _ *BytesHeaderClientBase64URLArrayOptions) (*policy.Request, error) { + urlPath := "/encode/bytes/header/base64url-array" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["value"] = []string{strings.Join(func() []string { + encodedValue := make([]string, len(value)) + for i := 0; i < len(value); i++ { + encodedValue[i] = base64.RawURLEncoding.EncodeToString(value[i]) + } + return encodedValue + }(), ",")} + return req, nil +} + +// Default - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BytesHeaderClientDefaultOptions contains the optional parameters for the BytesHeaderClient.Default method. +func (client *BytesHeaderClient) Default(ctx context.Context, value []byte, options *BytesHeaderClientDefaultOptions) (BytesHeaderClientDefaultResponse, error) { + var err error + const operationName = "BytesHeaderClient.Default" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.defaultCreateRequest(ctx, value, options) + if err != nil { + return BytesHeaderClientDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BytesHeaderClientDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return BytesHeaderClientDefaultResponse{}, err + } + return BytesHeaderClientDefaultResponse{}, nil +} + +// defaultCreateRequest creates the Default request. +func (client *BytesHeaderClient) defaultCreateRequest(ctx context.Context, value []byte, _ *BytesHeaderClientDefaultOptions) (*policy.Request, error) { + urlPath := "/encode/bytes/header/default" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["value"] = []string{base64.StdEncoding.EncodeToString(value)} + return req, nil +} diff --git a/test/http-specs/encode/bytesgroup/zz_bytesproperty_client.go b/test/http-specs/encode/bytesgroup/zz_bytesproperty_client.go new file mode 100644 index 000000000000..b29c9447fe11 --- /dev/null +++ b/test/http-specs/encode/bytesgroup/zz_bytesproperty_client.go @@ -0,0 +1,217 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package bytesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// BytesPropertyClient contains the methods for the BytesProperty group. +// Don't use this type directly, use [BytesClient.NewBytesPropertyClient] instead. +type BytesPropertyClient struct { + internal *azcore.Client + endpoint string +} + +// Base64 - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BytesPropertyClientBase64Options contains the optional parameters for the BytesPropertyClient.Base64 method. +func (client *BytesPropertyClient) Base64(ctx context.Context, body Base64BytesProperty, options *BytesPropertyClientBase64Options) (BytesPropertyClientBase64Response, error) { + var err error + const operationName = "BytesPropertyClient.Base64" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.base64CreateRequest(ctx, body, options) + if err != nil { + return BytesPropertyClientBase64Response{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BytesPropertyClientBase64Response{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BytesPropertyClientBase64Response{}, err + } + resp, err := client.base64HandleResponse(httpResp) + return resp, err +} + +// base64CreateRequest creates the Base64 request. +func (client *BytesPropertyClient) base64CreateRequest(ctx context.Context, body Base64BytesProperty, _ *BytesPropertyClientBase64Options) (*policy.Request, error) { + urlPath := "/encode/bytes/property/base64" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// base64HandleResponse handles the Base64 response. +func (client *BytesPropertyClient) base64HandleResponse(resp *http.Response) (BytesPropertyClientBase64Response, error) { + result := BytesPropertyClientBase64Response{} + if err := runtime.UnmarshalAsJSON(resp, &result.Base64BytesProperty); err != nil { + return BytesPropertyClientBase64Response{}, err + } + return result, nil +} + +// Base64URL - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BytesPropertyClientBase64URLOptions contains the optional parameters for the BytesPropertyClient.Base64URL method. +func (client *BytesPropertyClient) Base64URL(ctx context.Context, body Base64URLBytesProperty, options *BytesPropertyClientBase64URLOptions) (BytesPropertyClientBase64URLResponse, error) { + var err error + const operationName = "BytesPropertyClient.Base64URL" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.base64URLCreateRequest(ctx, body, options) + if err != nil { + return BytesPropertyClientBase64URLResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BytesPropertyClientBase64URLResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BytesPropertyClientBase64URLResponse{}, err + } + resp, err := client.base64URLHandleResponse(httpResp) + return resp, err +} + +// base64URLCreateRequest creates the Base64URL request. +func (client *BytesPropertyClient) base64URLCreateRequest(ctx context.Context, body Base64URLBytesProperty, _ *BytesPropertyClientBase64URLOptions) (*policy.Request, error) { + urlPath := "/encode/bytes/property/base64url" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// base64URLHandleResponse handles the Base64URL response. +func (client *BytesPropertyClient) base64URLHandleResponse(resp *http.Response) (BytesPropertyClientBase64URLResponse, error) { + result := BytesPropertyClientBase64URLResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Base64URLBytesProperty); err != nil { + return BytesPropertyClientBase64URLResponse{}, err + } + return result, nil +} + +// Base64URLArray - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BytesPropertyClientBase64URLArrayOptions contains the optional parameters for the BytesPropertyClient.Base64URLArray +// method. +func (client *BytesPropertyClient) Base64URLArray(ctx context.Context, body Base64URLArrayBytesProperty, options *BytesPropertyClientBase64URLArrayOptions) (BytesPropertyClientBase64URLArrayResponse, error) { + var err error + const operationName = "BytesPropertyClient.Base64URLArray" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.base64URLArrayCreateRequest(ctx, body, options) + if err != nil { + return BytesPropertyClientBase64URLArrayResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BytesPropertyClientBase64URLArrayResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BytesPropertyClientBase64URLArrayResponse{}, err + } + resp, err := client.base64URLArrayHandleResponse(httpResp) + return resp, err +} + +// base64URLArrayCreateRequest creates the Base64URLArray request. +func (client *BytesPropertyClient) base64URLArrayCreateRequest(ctx context.Context, body Base64URLArrayBytesProperty, _ *BytesPropertyClientBase64URLArrayOptions) (*policy.Request, error) { + urlPath := "/encode/bytes/property/base64url-array" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// base64URLArrayHandleResponse handles the Base64URLArray response. +func (client *BytesPropertyClient) base64URLArrayHandleResponse(resp *http.Response) (BytesPropertyClientBase64URLArrayResponse, error) { + result := BytesPropertyClientBase64URLArrayResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Base64URLArrayBytesProperty); err != nil { + return BytesPropertyClientBase64URLArrayResponse{}, err + } + return result, nil +} + +// Default - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BytesPropertyClientDefaultOptions contains the optional parameters for the BytesPropertyClient.Default method. +func (client *BytesPropertyClient) Default(ctx context.Context, body DefaultBytesProperty, options *BytesPropertyClientDefaultOptions) (BytesPropertyClientDefaultResponse, error) { + var err error + const operationName = "BytesPropertyClient.Default" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.defaultCreateRequest(ctx, body, options) + if err != nil { + return BytesPropertyClientDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BytesPropertyClientDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BytesPropertyClientDefaultResponse{}, err + } + resp, err := client.defaultHandleResponse(httpResp) + return resp, err +} + +// defaultCreateRequest creates the Default request. +func (client *BytesPropertyClient) defaultCreateRequest(ctx context.Context, body DefaultBytesProperty, _ *BytesPropertyClientDefaultOptions) (*policy.Request, error) { + urlPath := "/encode/bytes/property/default" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// defaultHandleResponse handles the Default response. +func (client *BytesPropertyClient) defaultHandleResponse(resp *http.Response) (BytesPropertyClientDefaultResponse, error) { + result := BytesPropertyClientDefaultResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DefaultBytesProperty); err != nil { + return BytesPropertyClientDefaultResponse{}, err + } + return result, nil +} diff --git a/test/http-specs/encode/bytesgroup/zz_bytesquery_client.go b/test/http-specs/encode/bytesgroup/zz_bytesquery_client.go new file mode 100644 index 000000000000..37b58f598897 --- /dev/null +++ b/test/http-specs/encode/bytesgroup/zz_bytesquery_client.go @@ -0,0 +1,177 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package bytesgroup + +import ( + "context" + "encoding/base64" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// BytesQueryClient contains the methods for the BytesQuery group. +// Don't use this type directly, use [BytesClient.NewBytesQueryClient] instead. +type BytesQueryClient struct { + internal *azcore.Client + endpoint string +} + +// Base64 - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BytesQueryClientBase64Options contains the optional parameters for the BytesQueryClient.Base64 method. +func (client *BytesQueryClient) Base64(ctx context.Context, value []byte, options *BytesQueryClientBase64Options) (BytesQueryClientBase64Response, error) { + var err error + const operationName = "BytesQueryClient.Base64" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.base64CreateRequest(ctx, value, options) + if err != nil { + return BytesQueryClientBase64Response{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BytesQueryClientBase64Response{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return BytesQueryClientBase64Response{}, err + } + return BytesQueryClientBase64Response{}, nil +} + +// base64CreateRequest creates the Base64 request. +func (client *BytesQueryClient) base64CreateRequest(ctx context.Context, value []byte, _ *BytesQueryClientBase64Options) (*policy.Request, error) { + urlPath := "/encode/bytes/query/base64" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("value", base64.StdEncoding.EncodeToString(value)) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Base64URL - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BytesQueryClientBase64URLOptions contains the optional parameters for the BytesQueryClient.Base64URL method. +func (client *BytesQueryClient) Base64URL(ctx context.Context, value []byte, options *BytesQueryClientBase64URLOptions) (BytesQueryClientBase64URLResponse, error) { + var err error + const operationName = "BytesQueryClient.Base64URL" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.base64URLCreateRequest(ctx, value, options) + if err != nil { + return BytesQueryClientBase64URLResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BytesQueryClientBase64URLResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return BytesQueryClientBase64URLResponse{}, err + } + return BytesQueryClientBase64URLResponse{}, nil +} + +// base64URLCreateRequest creates the Base64URL request. +func (client *BytesQueryClient) base64URLCreateRequest(ctx context.Context, value []byte, _ *BytesQueryClientBase64URLOptions) (*policy.Request, error) { + urlPath := "/encode/bytes/query/base64url" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("value", base64.RawURLEncoding.EncodeToString(value)) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Base64URLArray - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BytesQueryClientBase64URLArrayOptions contains the optional parameters for the BytesQueryClient.Base64URLArray +// method. +func (client *BytesQueryClient) Base64URLArray(ctx context.Context, value [][]byte, options *BytesQueryClientBase64URLArrayOptions) (BytesQueryClientBase64URLArrayResponse, error) { + var err error + const operationName = "BytesQueryClient.Base64URLArray" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.base64URLArrayCreateRequest(ctx, value, options) + if err != nil { + return BytesQueryClientBase64URLArrayResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BytesQueryClientBase64URLArrayResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return BytesQueryClientBase64URLArrayResponse{}, err + } + return BytesQueryClientBase64URLArrayResponse{}, nil +} + +// base64URLArrayCreateRequest creates the Base64URLArray request. +func (client *BytesQueryClient) base64URLArrayCreateRequest(ctx context.Context, value [][]byte, _ *BytesQueryClientBase64URLArrayOptions) (*policy.Request, error) { + urlPath := "/encode/bytes/query/base64url-array" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("value", strings.Join(func() []string { + encodedValue := make([]string, len(value)) + for i := 0; i < len(value); i++ { + encodedValue[i] = base64.RawURLEncoding.EncodeToString(value[i]) + } + return encodedValue + }(), ",")) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Default - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BytesQueryClientDefaultOptions contains the optional parameters for the BytesQueryClient.Default method. +func (client *BytesQueryClient) Default(ctx context.Context, value []byte, options *BytesQueryClientDefaultOptions) (BytesQueryClientDefaultResponse, error) { + var err error + const operationName = "BytesQueryClient.Default" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.defaultCreateRequest(ctx, value, options) + if err != nil { + return BytesQueryClientDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BytesQueryClientDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return BytesQueryClientDefaultResponse{}, err + } + return BytesQueryClientDefaultResponse{}, nil +} + +// defaultCreateRequest creates the Default request. +func (client *BytesQueryClient) defaultCreateRequest(ctx context.Context, value []byte, _ *BytesQueryClientDefaultOptions) (*policy.Request, error) { + urlPath := "/encode/bytes/query/default" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("value", base64.StdEncoding.EncodeToString(value)) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/http-specs/encode/bytesgroup/zz_bytesrequestbody_client.go b/test/http-specs/encode/bytesgroup/zz_bytesrequestbody_client.go new file mode 100644 index 000000000000..bcf0946159ad --- /dev/null +++ b/test/http-specs/encode/bytesgroup/zz_bytesrequestbody_client.go @@ -0,0 +1,215 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package bytesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "io" + "net/http" +) + +// BytesRequestBodyClient contains the methods for the BytesRequestBody group. +// Don't use this type directly, use [BytesClient.NewBytesRequestBodyClient] instead. +type BytesRequestBodyClient struct { + internal *azcore.Client + endpoint string +} + +// Base64 - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BytesRequestBodyClientBase64Options contains the optional parameters for the BytesRequestBodyClient.Base64 method. +func (client *BytesRequestBodyClient) Base64(ctx context.Context, value []byte, options *BytesRequestBodyClientBase64Options) (BytesRequestBodyClientBase64Response, error) { + var err error + const operationName = "BytesRequestBodyClient.Base64" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.base64CreateRequest(ctx, value, options) + if err != nil { + return BytesRequestBodyClientBase64Response{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BytesRequestBodyClientBase64Response{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return BytesRequestBodyClientBase64Response{}, err + } + return BytesRequestBodyClientBase64Response{}, nil +} + +// base64CreateRequest creates the Base64 request. +func (client *BytesRequestBodyClient) base64CreateRequest(ctx context.Context, value []byte, _ *BytesRequestBodyClientBase64Options) (*policy.Request, error) { + urlPath := "/encode/bytes/body/request/base64" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsByteArray(req, value, runtime.Base64StdFormat); err != nil { + return nil, err + } + return req, nil +} + +// Base64URL - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BytesRequestBodyClientBase64URLOptions contains the optional parameters for the BytesRequestBodyClient.Base64URL +// method. +func (client *BytesRequestBodyClient) Base64URL(ctx context.Context, value []byte, options *BytesRequestBodyClientBase64URLOptions) (BytesRequestBodyClientBase64URLResponse, error) { + var err error + const operationName = "BytesRequestBodyClient.Base64URL" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.base64URLCreateRequest(ctx, value, options) + if err != nil { + return BytesRequestBodyClientBase64URLResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BytesRequestBodyClientBase64URLResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return BytesRequestBodyClientBase64URLResponse{}, err + } + return BytesRequestBodyClientBase64URLResponse{}, nil +} + +// base64URLCreateRequest creates the Base64URL request. +func (client *BytesRequestBodyClient) base64URLCreateRequest(ctx context.Context, value []byte, _ *BytesRequestBodyClientBase64URLOptions) (*policy.Request, error) { + urlPath := "/encode/bytes/body/request/base64url" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsByteArray(req, value, runtime.Base64URLFormat); err != nil { + return nil, err + } + return req, nil +} + +// CustomContentType - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BytesRequestBodyClientCustomContentTypeOptions contains the optional parameters for the BytesRequestBodyClient.CustomContentType +// method. +func (client *BytesRequestBodyClient) CustomContentType(ctx context.Context, value io.ReadSeekCloser, options *BytesRequestBodyClientCustomContentTypeOptions) (BytesRequestBodyClientCustomContentTypeResponse, error) { + var err error + const operationName = "BytesRequestBodyClient.CustomContentType" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.customContentTypeCreateRequest(ctx, value, options) + if err != nil { + return BytesRequestBodyClientCustomContentTypeResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BytesRequestBodyClientCustomContentTypeResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return BytesRequestBodyClientCustomContentTypeResponse{}, err + } + return BytesRequestBodyClientCustomContentTypeResponse{}, nil +} + +// customContentTypeCreateRequest creates the CustomContentType request. +func (client *BytesRequestBodyClient) customContentTypeCreateRequest(ctx context.Context, value io.ReadSeekCloser, _ *BytesRequestBodyClientCustomContentTypeOptions) (*policy.Request, error) { + urlPath := "/encode/bytes/body/request/custom-content-type" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"image/png"} + if err := req.SetBody(value, "image/png"); err != nil { + return nil, err + } + return req, nil +} + +// Default - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BytesRequestBodyClientDefaultOptions contains the optional parameters for the BytesRequestBodyClient.Default +// method. +func (client *BytesRequestBodyClient) Default(ctx context.Context, value io.ReadSeekCloser, options *BytesRequestBodyClientDefaultOptions) (BytesRequestBodyClientDefaultResponse, error) { + var err error + const operationName = "BytesRequestBodyClient.Default" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.defaultCreateRequest(ctx, value, options) + if err != nil { + return BytesRequestBodyClientDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BytesRequestBodyClientDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return BytesRequestBodyClientDefaultResponse{}, err + } + return BytesRequestBodyClientDefaultResponse{}, nil +} + +// defaultCreateRequest creates the Default request. +func (client *BytesRequestBodyClient) defaultCreateRequest(ctx context.Context, value io.ReadSeekCloser, _ *BytesRequestBodyClientDefaultOptions) (*policy.Request, error) { + urlPath := "/encode/bytes/body/request/default" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/octet-stream"} + if err := req.SetBody(value, "application/octet-stream"); err != nil { + return nil, err + } + return req, nil +} + +// OctetStream - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BytesRequestBodyClientOctetStreamOptions contains the optional parameters for the BytesRequestBodyClient.OctetStream +// method. +func (client *BytesRequestBodyClient) OctetStream(ctx context.Context, value io.ReadSeekCloser, options *BytesRequestBodyClientOctetStreamOptions) (BytesRequestBodyClientOctetStreamResponse, error) { + var err error + const operationName = "BytesRequestBodyClient.OctetStream" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.octetStreamCreateRequest(ctx, value, options) + if err != nil { + return BytesRequestBodyClientOctetStreamResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BytesRequestBodyClientOctetStreamResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return BytesRequestBodyClientOctetStreamResponse{}, err + } + return BytesRequestBodyClientOctetStreamResponse{}, nil +} + +// octetStreamCreateRequest creates the OctetStream request. +func (client *BytesRequestBodyClient) octetStreamCreateRequest(ctx context.Context, value io.ReadSeekCloser, _ *BytesRequestBodyClientOctetStreamOptions) (*policy.Request, error) { + urlPath := "/encode/bytes/body/request/octet-stream" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/octet-stream"} + if err := req.SetBody(value, "application/octet-stream"); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/encode/bytesgroup/zz_bytesresponsebody_client.go b/test/http-specs/encode/bytesgroup/zz_bytesresponsebody_client.go new file mode 100644 index 000000000000..2f15a09ba0b3 --- /dev/null +++ b/test/http-specs/encode/bytesgroup/zz_bytesresponsebody_client.go @@ -0,0 +1,243 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package bytesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// BytesResponseBodyClient contains the methods for the BytesResponseBody group. +// Don't use this type directly, use [BytesClient.NewBytesResponseBodyClient] instead. +type BytesResponseBodyClient struct { + internal *azcore.Client + endpoint string +} + +// Base64 - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BytesResponseBodyClientBase64Options contains the optional parameters for the BytesResponseBodyClient.Base64 +// method. +func (client *BytesResponseBodyClient) Base64(ctx context.Context, options *BytesResponseBodyClientBase64Options) (BytesResponseBodyClientBase64Response, error) { + var err error + const operationName = "BytesResponseBodyClient.Base64" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.base64CreateRequest(ctx, options) + if err != nil { + return BytesResponseBodyClientBase64Response{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BytesResponseBodyClientBase64Response{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BytesResponseBodyClientBase64Response{}, err + } + resp, err := client.base64HandleResponse(httpResp) + return resp, err +} + +// base64CreateRequest creates the Base64 request. +func (client *BytesResponseBodyClient) base64CreateRequest(ctx context.Context, _ *BytesResponseBodyClientBase64Options) (*policy.Request, error) { + urlPath := "/encode/bytes/body/response/base64" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// base64HandleResponse handles the Base64 response. +func (client *BytesResponseBodyClient) base64HandleResponse(resp *http.Response) (BytesResponseBodyClientBase64Response, error) { + result := BytesResponseBodyClientBase64Response{} + if err := runtime.UnmarshalAsByteArray(resp, &result.Value, runtime.Base64StdFormat); err != nil { + return BytesResponseBodyClientBase64Response{}, err + } + return result, nil +} + +// Base64URL - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BytesResponseBodyClientBase64URLOptions contains the optional parameters for the BytesResponseBodyClient.Base64URL +// method. +func (client *BytesResponseBodyClient) Base64URL(ctx context.Context, options *BytesResponseBodyClientBase64URLOptions) (BytesResponseBodyClientBase64URLResponse, error) { + var err error + const operationName = "BytesResponseBodyClient.Base64URL" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.base64URLCreateRequest(ctx, options) + if err != nil { + return BytesResponseBodyClientBase64URLResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BytesResponseBodyClientBase64URLResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BytesResponseBodyClientBase64URLResponse{}, err + } + resp, err := client.base64URLHandleResponse(httpResp) + return resp, err +} + +// base64URLCreateRequest creates the Base64URL request. +func (client *BytesResponseBodyClient) base64URLCreateRequest(ctx context.Context, _ *BytesResponseBodyClientBase64URLOptions) (*policy.Request, error) { + urlPath := "/encode/bytes/body/response/base64url" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// base64URLHandleResponse handles the Base64URL response. +func (client *BytesResponseBodyClient) base64URLHandleResponse(resp *http.Response) (BytesResponseBodyClientBase64URLResponse, error) { + result := BytesResponseBodyClientBase64URLResponse{} + if err := runtime.UnmarshalAsByteArray(resp, &result.Value, runtime.Base64URLFormat); err != nil { + return BytesResponseBodyClientBase64URLResponse{}, err + } + return result, nil +} + +// CustomContentType - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BytesResponseBodyClientCustomContentTypeOptions contains the optional parameters for the BytesResponseBodyClient.CustomContentType +// method. +func (client *BytesResponseBodyClient) CustomContentType(ctx context.Context, options *BytesResponseBodyClientCustomContentTypeOptions) (BytesResponseBodyClientCustomContentTypeResponse, error) { + var err error + const operationName = "BytesResponseBodyClient.CustomContentType" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.customContentTypeCreateRequest(ctx, options) + if err != nil { + return BytesResponseBodyClientCustomContentTypeResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BytesResponseBodyClientCustomContentTypeResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BytesResponseBodyClientCustomContentTypeResponse{}, err + } + resp, err := client.customContentTypeHandleResponse(httpResp) + return resp, err +} + +// customContentTypeCreateRequest creates the CustomContentType request. +func (client *BytesResponseBodyClient) customContentTypeCreateRequest(ctx context.Context, _ *BytesResponseBodyClientCustomContentTypeOptions) (*policy.Request, error) { + urlPath := "/encode/bytes/body/response/custom-content-type" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + runtime.SkipBodyDownload(req) + req.Raw().Header["Accept"] = []string{"image/png"} + return req, nil +} + +// customContentTypeHandleResponse handles the CustomContentType response. +func (client *BytesResponseBodyClient) customContentTypeHandleResponse(resp *http.Response) (BytesResponseBodyClientCustomContentTypeResponse, error) { + result := BytesResponseBodyClientCustomContentTypeResponse{Body: resp.Body} + if val := resp.Header.Get("content-type"); val != "" { + result.ContentType = &val + } + return result, nil +} + +// Default - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BytesResponseBodyClientDefaultOptions contains the optional parameters for the BytesResponseBodyClient.Default +// method. +func (client *BytesResponseBodyClient) Default(ctx context.Context, options *BytesResponseBodyClientDefaultOptions) (BytesResponseBodyClientDefaultResponse, error) { + var err error + const operationName = "BytesResponseBodyClient.Default" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.defaultCreateRequest(ctx, options) + if err != nil { + return BytesResponseBodyClientDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BytesResponseBodyClientDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BytesResponseBodyClientDefaultResponse{}, err + } + return BytesResponseBodyClientDefaultResponse{Body: httpResp.Body}, nil +} + +// defaultCreateRequest creates the Default request. +func (client *BytesResponseBodyClient) defaultCreateRequest(ctx context.Context, _ *BytesResponseBodyClientDefaultOptions) (*policy.Request, error) { + urlPath := "/encode/bytes/body/response/default" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + runtime.SkipBodyDownload(req) + req.Raw().Header["Accept"] = []string{"application/octet-stream"} + return req, nil +} + +// OctetStream - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BytesResponseBodyClientOctetStreamOptions contains the optional parameters for the BytesResponseBodyClient.OctetStream +// method. +func (client *BytesResponseBodyClient) OctetStream(ctx context.Context, options *BytesResponseBodyClientOctetStreamOptions) (BytesResponseBodyClientOctetStreamResponse, error) { + var err error + const operationName = "BytesResponseBodyClient.OctetStream" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.octetStreamCreateRequest(ctx, options) + if err != nil { + return BytesResponseBodyClientOctetStreamResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BytesResponseBodyClientOctetStreamResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BytesResponseBodyClientOctetStreamResponse{}, err + } + resp, err := client.octetStreamHandleResponse(httpResp) + return resp, err +} + +// octetStreamCreateRequest creates the OctetStream request. +func (client *BytesResponseBodyClient) octetStreamCreateRequest(ctx context.Context, _ *BytesResponseBodyClientOctetStreamOptions) (*policy.Request, error) { + urlPath := "/encode/bytes/body/response/octet-stream" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + runtime.SkipBodyDownload(req) + req.Raw().Header["Accept"] = []string{"application/octet-stream"} + return req, nil +} + +// octetStreamHandleResponse handles the OctetStream response. +func (client *BytesResponseBodyClient) octetStreamHandleResponse(resp *http.Response) (BytesResponseBodyClientOctetStreamResponse, error) { + result := BytesResponseBodyClientOctetStreamResponse{Body: resp.Body} + if val := resp.Header.Get("content-type"); val != "" { + result.ContentType = &val + } + return result, nil +} diff --git a/test/http-specs/encode/bytesgroup/zz_models.go b/test/http-specs/encode/bytesgroup/zz_models.go new file mode 100644 index 000000000000..b0584137ca6e --- /dev/null +++ b/test/http-specs/encode/bytesgroup/zz_models.go @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package bytesgroup + +type Base64BytesProperty struct { + // REQUIRED + Value []byte +} + +type Base64URLArrayBytesProperty struct { + // REQUIRED + Value [][]byte +} + +type Base64URLBytesProperty struct { + // REQUIRED + Value []byte +} + +type DefaultBytesProperty struct { + // REQUIRED + Value []byte +} diff --git a/test/http-specs/encode/bytesgroup/zz_models_serde.go b/test/http-specs/encode/bytesgroup/zz_models_serde.go new file mode 100644 index 000000000000..bc0f8a4b7c76 --- /dev/null +++ b/test/http-specs/encode/bytesgroup/zz_models_serde.go @@ -0,0 +1,165 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package bytesgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// MarshalJSON implements the json.Marshaller interface for type Base64BytesProperty. +func (b Base64BytesProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateByteArray(objectMap, "value", b.Value, func() any { + return runtime.EncodeByteArray(b.Value, runtime.Base64StdFormat) + }) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Base64BytesProperty. +func (b *Base64BytesProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &b.Value, runtime.Base64StdFormat) + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Base64URLArrayBytesProperty. +func (b Base64URLArrayBytesProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateByteArray(objectMap, "value", b.Value, func() any { + encodedValue := make([]string, len(b.Value)) + for i := 0; i < len(b.Value); i++ { + encodedValue[i] = runtime.EncodeByteArray(b.Value[i], runtime.Base64URLFormat) + } + return encodedValue + }) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Base64URLArrayBytesProperty. +func (b *Base64URLArrayBytesProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + var encodedValue []string + err = unpopulate(val, "Value", &encodedValue) + if err == nil && len(encodedValue) > 0 { + b.Value = make([][]byte, len(encodedValue)) + for i := 0; i < len(encodedValue) && err == nil; i++ { + err = runtime.DecodeByteArray(encodedValue[i], &b.Value[i], runtime.Base64URLFormat) + } + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Base64URLBytesProperty. +func (b Base64URLBytesProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateByteArray(objectMap, "value", b.Value, func() any { + return runtime.EncodeByteArray(b.Value, runtime.Base64URLFormat) + }) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Base64URLBytesProperty. +func (b *Base64URLBytesProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &b.Value, runtime.Base64URLFormat) + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DefaultBytesProperty. +func (d DefaultBytesProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateByteArray(objectMap, "value", d.Value, func() any { + return runtime.EncodeByteArray(d.Value, runtime.Base64StdFormat) + }) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DefaultBytesProperty. +func (d *DefaultBytesProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &d.Value, runtime.Base64StdFormat) + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +func populateByteArray[T any](m map[string]any, k string, b []T, convert func() any) { + if azcore.IsNullValue(b) { + m[k] = nil + } else if len(b) == 0 { + return + } else { + m[k] = convert() + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/http-specs/encode/bytesgroup/zz_options.go b/test/http-specs/encode/bytesgroup/zz_options.go new file mode 100644 index 000000000000..1e660324f7da --- /dev/null +++ b/test/http-specs/encode/bytesgroup/zz_options.go @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package bytesgroup + +// BytesHeaderClientBase64Options contains the optional parameters for the BytesHeaderClient.Base64 method. +type BytesHeaderClientBase64Options struct { + // placeholder for future optional parameters +} + +// BytesHeaderClientBase64URLArrayOptions contains the optional parameters for the BytesHeaderClient.Base64URLArray method. +type BytesHeaderClientBase64URLArrayOptions struct { + // placeholder for future optional parameters +} + +// BytesHeaderClientBase64URLOptions contains the optional parameters for the BytesHeaderClient.Base64URL method. +type BytesHeaderClientBase64URLOptions struct { + // placeholder for future optional parameters +} + +// BytesHeaderClientDefaultOptions contains the optional parameters for the BytesHeaderClient.Default method. +type BytesHeaderClientDefaultOptions struct { + // placeholder for future optional parameters +} + +// BytesPropertyClientBase64Options contains the optional parameters for the BytesPropertyClient.Base64 method. +type BytesPropertyClientBase64Options struct { + // placeholder for future optional parameters +} + +// BytesPropertyClientBase64URLArrayOptions contains the optional parameters for the BytesPropertyClient.Base64URLArray method. +type BytesPropertyClientBase64URLArrayOptions struct { + // placeholder for future optional parameters +} + +// BytesPropertyClientBase64URLOptions contains the optional parameters for the BytesPropertyClient.Base64URL method. +type BytesPropertyClientBase64URLOptions struct { + // placeholder for future optional parameters +} + +// BytesPropertyClientDefaultOptions contains the optional parameters for the BytesPropertyClient.Default method. +type BytesPropertyClientDefaultOptions struct { + // placeholder for future optional parameters +} + +// BytesQueryClientBase64Options contains the optional parameters for the BytesQueryClient.Base64 method. +type BytesQueryClientBase64Options struct { + // placeholder for future optional parameters +} + +// BytesQueryClientBase64URLArrayOptions contains the optional parameters for the BytesQueryClient.Base64URLArray method. +type BytesQueryClientBase64URLArrayOptions struct { + // placeholder for future optional parameters +} + +// BytesQueryClientBase64URLOptions contains the optional parameters for the BytesQueryClient.Base64URL method. +type BytesQueryClientBase64URLOptions struct { + // placeholder for future optional parameters +} + +// BytesQueryClientDefaultOptions contains the optional parameters for the BytesQueryClient.Default method. +type BytesQueryClientDefaultOptions struct { + // placeholder for future optional parameters +} + +// BytesRequestBodyClientBase64Options contains the optional parameters for the BytesRequestBodyClient.Base64 method. +type BytesRequestBodyClientBase64Options struct { + // placeholder for future optional parameters +} + +// BytesRequestBodyClientBase64URLOptions contains the optional parameters for the BytesRequestBodyClient.Base64URL method. +type BytesRequestBodyClientBase64URLOptions struct { + // placeholder for future optional parameters +} + +// BytesRequestBodyClientCustomContentTypeOptions contains the optional parameters for the BytesRequestBodyClient.CustomContentType +// method. +type BytesRequestBodyClientCustomContentTypeOptions struct { + // placeholder for future optional parameters +} + +// BytesRequestBodyClientDefaultOptions contains the optional parameters for the BytesRequestBodyClient.Default method. +type BytesRequestBodyClientDefaultOptions struct { + // placeholder for future optional parameters +} + +// BytesRequestBodyClientOctetStreamOptions contains the optional parameters for the BytesRequestBodyClient.OctetStream method. +type BytesRequestBodyClientOctetStreamOptions struct { + // placeholder for future optional parameters +} + +// BytesResponseBodyClientBase64Options contains the optional parameters for the BytesResponseBodyClient.Base64 method. +type BytesResponseBodyClientBase64Options struct { + // placeholder for future optional parameters +} + +// BytesResponseBodyClientBase64URLOptions contains the optional parameters for the BytesResponseBodyClient.Base64URL method. +type BytesResponseBodyClientBase64URLOptions struct { + // placeholder for future optional parameters +} + +// BytesResponseBodyClientCustomContentTypeOptions contains the optional parameters for the BytesResponseBodyClient.CustomContentType +// method. +type BytesResponseBodyClientCustomContentTypeOptions struct { + // placeholder for future optional parameters +} + +// BytesResponseBodyClientDefaultOptions contains the optional parameters for the BytesResponseBodyClient.Default method. +type BytesResponseBodyClientDefaultOptions struct { + // placeholder for future optional parameters +} + +// BytesResponseBodyClientOctetStreamOptions contains the optional parameters for the BytesResponseBodyClient.OctetStream +// method. +type BytesResponseBodyClientOctetStreamOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/encode/bytesgroup/zz_responses.go b/test/http-specs/encode/bytesgroup/zz_responses.go new file mode 100644 index 000000000000..5638a3612f2c --- /dev/null +++ b/test/http-specs/encode/bytesgroup/zz_responses.go @@ -0,0 +1,122 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package bytesgroup + +import "io" + +// BytesHeaderClientBase64Response contains the response from method BytesHeaderClient.Base64. +type BytesHeaderClientBase64Response struct { + // placeholder for future response values +} + +// BytesHeaderClientBase64URLArrayResponse contains the response from method BytesHeaderClient.Base64URLArray. +type BytesHeaderClientBase64URLArrayResponse struct { + // placeholder for future response values +} + +// BytesHeaderClientBase64URLResponse contains the response from method BytesHeaderClient.Base64URL. +type BytesHeaderClientBase64URLResponse struct { + // placeholder for future response values +} + +// BytesHeaderClientDefaultResponse contains the response from method BytesHeaderClient.Default. +type BytesHeaderClientDefaultResponse struct { + // placeholder for future response values +} + +// BytesPropertyClientBase64Response contains the response from method BytesPropertyClient.Base64. +type BytesPropertyClientBase64Response struct { + Base64BytesProperty +} + +// BytesPropertyClientBase64URLArrayResponse contains the response from method BytesPropertyClient.Base64URLArray. +type BytesPropertyClientBase64URLArrayResponse struct { + Base64URLArrayBytesProperty +} + +// BytesPropertyClientBase64URLResponse contains the response from method BytesPropertyClient.Base64URL. +type BytesPropertyClientBase64URLResponse struct { + Base64URLBytesProperty +} + +// BytesPropertyClientDefaultResponse contains the response from method BytesPropertyClient.Default. +type BytesPropertyClientDefaultResponse struct { + DefaultBytesProperty +} + +// BytesQueryClientBase64Response contains the response from method BytesQueryClient.Base64. +type BytesQueryClientBase64Response struct { + // placeholder for future response values +} + +// BytesQueryClientBase64URLArrayResponse contains the response from method BytesQueryClient.Base64URLArray. +type BytesQueryClientBase64URLArrayResponse struct { + // placeholder for future response values +} + +// BytesQueryClientBase64URLResponse contains the response from method BytesQueryClient.Base64URL. +type BytesQueryClientBase64URLResponse struct { + // placeholder for future response values +} + +// BytesQueryClientDefaultResponse contains the response from method BytesQueryClient.Default. +type BytesQueryClientDefaultResponse struct { + // placeholder for future response values +} + +// BytesRequestBodyClientBase64Response contains the response from method BytesRequestBodyClient.Base64. +type BytesRequestBodyClientBase64Response struct { + // placeholder for future response values +} + +// BytesRequestBodyClientBase64URLResponse contains the response from method BytesRequestBodyClient.Base64URL. +type BytesRequestBodyClientBase64URLResponse struct { + // placeholder for future response values +} + +// BytesRequestBodyClientCustomContentTypeResponse contains the response from method BytesRequestBodyClient.CustomContentType. +type BytesRequestBodyClientCustomContentTypeResponse struct { + // placeholder for future response values +} + +// BytesRequestBodyClientDefaultResponse contains the response from method BytesRequestBodyClient.Default. +type BytesRequestBodyClientDefaultResponse struct { + // placeholder for future response values +} + +// BytesRequestBodyClientOctetStreamResponse contains the response from method BytesRequestBodyClient.OctetStream. +type BytesRequestBodyClientOctetStreamResponse struct { + // placeholder for future response values +} + +// BytesResponseBodyClientBase64Response contains the response from method BytesResponseBodyClient.Base64. +type BytesResponseBodyClientBase64Response struct { + Value []byte +} + +// BytesResponseBodyClientBase64URLResponse contains the response from method BytesResponseBodyClient.Base64URL. +type BytesResponseBodyClientBase64URLResponse struct { + Value []byte +} + +// BytesResponseBodyClientCustomContentTypeResponse contains the response from method BytesResponseBodyClient.CustomContentType. +type BytesResponseBodyClientCustomContentTypeResponse struct { + // Body contains the streaming response. + Body io.ReadCloser + ContentType *string +} + +// BytesResponseBodyClientDefaultResponse contains the response from method BytesResponseBodyClient.Default. +type BytesResponseBodyClientDefaultResponse struct { + // Body contains the streaming response. + Body io.ReadCloser +} + +// BytesResponseBodyClientOctetStreamResponse contains the response from method BytesResponseBodyClient.OctetStream. +type BytesResponseBodyClientOctetStreamResponse struct { + // Body contains the streaming response. + Body io.ReadCloser + ContentType *string +} diff --git a/test/http-specs/encode/bytesgroup/zz_version.go b/test/http-specs/encode/bytesgroup/zz_version.go new file mode 100644 index 000000000000..debcdd4975bd --- /dev/null +++ b/test/http-specs/encode/bytesgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package bytesgroup + +const ( + moduleName = "bytesgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/encode/datetimegroup/LICENSE.txt b/test/http-specs/encode/datetimegroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/encode/datetimegroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/encode/datetimegroup/custom_client_test.go b/test/http-specs/encode/datetimegroup/custom_client_test.go new file mode 100644 index 000000000000..ef4eb9cd2df0 --- /dev/null +++ b/test/http-specs/encode/datetimegroup/custom_client_test.go @@ -0,0 +1,201 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package datetimegroup_test + +import ( + "context" + "datetimegroup" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestHeaderClientDefault(t *testing.T) { + client, err := datetimegroup.NewDatetimeClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDatetimeHeaderClient().Default(context.Background(), time.Date(2022, time.August, 26, 14, 38, 0, 0, time.UTC), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestHeaderClientRFC3339(t *testing.T) { + client, err := datetimegroup.NewDatetimeClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDatetimeHeaderClient().RFC3339(context.Background(), time.Date(2022, time.August, 26, 18, 38, 0, 0, time.UTC), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestHeaderClientRFC7231(t *testing.T) { + client, err := datetimegroup.NewDatetimeClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDatetimeHeaderClient().RFC7231(context.Background(), time.Date(2022, time.August, 26, 14, 38, 0, 0, time.UTC), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestHeaderClientUnixTimestamp(t *testing.T) { + client, err := datetimegroup.NewDatetimeClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDatetimeHeaderClient().UnixTimestamp(context.Background(), time.Unix(1686566864, 0), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestHeaderClientUnixTimestampArray(t *testing.T) { + client, err := datetimegroup.NewDatetimeClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDatetimeHeaderClient().UnixTimestampArray(context.Background(), []time.Time{ + time.Unix(1686566864, 0), + time.Unix(1686734256, 0), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestPropertyClientDefault(t *testing.T) { + client, err := datetimegroup.NewDatetimeClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + v := time.Date(2022, time.August, 26, 18, 38, 0, 0, time.UTC) + resp, err := client.NewDatetimePropertyClient().Default(context.Background(), datetimegroup.DefaultDatetimeProperty{ + Value: to.Ptr(v), + }, nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.WithinDuration(t, v, *resp.Value, 0) +} + +func TestPropertyClientRFC3339(t *testing.T) { + client, err := datetimegroup.NewDatetimeClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + v := time.Date(2022, time.August, 26, 18, 38, 0, 0, time.UTC) + resp, err := client.NewDatetimePropertyClient().RFC3339(context.Background(), datetimegroup.RFC3339DatetimeProperty{ + Value: to.Ptr(v), + }, nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.WithinDuration(t, v, *resp.Value, 0) +} + +func TestPropertyClientRFC7231(t *testing.T) { + client, err := datetimegroup.NewDatetimeClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + v := time.Date(2022, time.August, 26, 14, 38, 0, 0, time.UTC) + resp, err := client.NewDatetimePropertyClient().RFC7231(context.Background(), datetimegroup.RFC7231DatetimeProperty{ + Value: to.Ptr(v), + }, nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.WithinDuration(t, v, *resp.Value, 0) +} + +func TestPropertyClientUnixTimestamp(t *testing.T) { + client, err := datetimegroup.NewDatetimeClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + v := time.Unix(1686566864, 0) + resp, err := client.NewDatetimePropertyClient().UnixTimestamp(context.Background(), datetimegroup.UnixTimestampDatetimeProperty{ + Value: to.Ptr(v), + }, nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.WithinDuration(t, v, *resp.Value, 0) +} + +func TestPropertyClientUnixTimestampArray(t *testing.T) { + client, err := datetimegroup.NewDatetimeClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + v := []time.Time{ + time.Unix(1686566864, 0), + time.Unix(1686734256, 0), + } + resp, err := client.NewDatetimePropertyClient().UnixTimestampArray(context.Background(), datetimegroup.UnixTimestampArrayDatetimeProperty{ + Value: v, + }, nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + for i := 0; i < len(v); i++ { + require.WithinDuration(t, v[i], resp.Value[i], 0) + } +} + +func TestQueryClientDefault(t *testing.T) { + client, err := datetimegroup.NewDatetimeClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDatetimeQueryClient().Default(context.Background(), time.Date(2022, time.August, 26, 18, 38, 0, 0, time.UTC), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestQueryClientRFC3339(t *testing.T) { + client, err := datetimegroup.NewDatetimeClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDatetimeQueryClient().RFC3339(context.Background(), time.Date(2022, time.August, 26, 18, 38, 0, 0, time.UTC), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestQueryClientRFC7231(t *testing.T) { + client, err := datetimegroup.NewDatetimeClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDatetimeQueryClient().RFC7231(context.Background(), time.Date(2022, time.August, 26, 14, 38, 0, 0, time.UTC), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestQueryClientUnixTimestamp(t *testing.T) { + client, err := datetimegroup.NewDatetimeClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDatetimeQueryClient().UnixTimestamp(context.Background(), time.Unix(1686566864, 0), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestQueryClientUnixTimestampArray(t *testing.T) { + client, err := datetimegroup.NewDatetimeClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDatetimeQueryClient().UnixTimestampArray(context.Background(), []time.Time{ + time.Unix(1686566864, 0), + time.Unix(1686734256, 0), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestResponseHeaderClientDefault(t *testing.T) { + client, err := datetimegroup.NewDatetimeClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDatetimeResponseHeaderClient().Default(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.WithinDuration(t, time.Date(2022, time.August, 26, 14, 38, 0, 0, time.UTC), *resp.Value, 0) +} + +func TestResponseHeaderClientRFC3339(t *testing.T) { + client, err := datetimegroup.NewDatetimeClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDatetimeResponseHeaderClient().RFC3339(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.WithinDuration(t, time.Date(2022, time.August, 26, 18, 38, 0, 0, time.UTC), *resp.Value, 0) +} + +func TestResponseHeaderClientRFC7231(t *testing.T) { + client, err := datetimegroup.NewDatetimeClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDatetimeResponseHeaderClient().RFC7231(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.WithinDuration(t, time.Date(2022, time.August, 26, 14, 38, 0, 0, time.UTC), *resp.Value, 0) +} + +func TestResponseHeaderClientUnixTimestamp(t *testing.T) { + client, err := datetimegroup.NewDatetimeClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDatetimeResponseHeaderClient().UnixTimestamp(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.WithinDuration(t, time.Unix(1686566864, 0), *resp.Value, 0) +} diff --git a/test/http-specs/encode/datetimegroup/fake/zz_datetime_server.go b/test/http-specs/encode/datetimegroup/fake/zz_datetime_server.go new file mode 100644 index 000000000000..c59d36a7762b --- /dev/null +++ b/test/http-specs/encode/datetimegroup/fake/zz_datetime_server.go @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// DatetimeServer is a fake server for instances of the datetimegroup.DatetimeClient type. +type DatetimeServer struct { + // DatetimeHeaderServer contains the fakes for client DatetimeHeaderClient + DatetimeHeaderServer DatetimeHeaderServer + + // DatetimePropertyServer contains the fakes for client DatetimePropertyClient + DatetimePropertyServer DatetimePropertyServer + + // DatetimeQueryServer contains the fakes for client DatetimeQueryClient + DatetimeQueryServer DatetimeQueryServer + + // DatetimeResponseHeaderServer contains the fakes for client DatetimeResponseHeaderClient + DatetimeResponseHeaderServer DatetimeResponseHeaderServer +} + +// NewDatetimeServerTransport creates a new instance of DatetimeServerTransport with the provided implementation. +// The returned DatetimeServerTransport instance is connected to an instance of datetimegroup.DatetimeClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDatetimeServerTransport(srv *DatetimeServer) *DatetimeServerTransport { + return &DatetimeServerTransport{srv: srv} +} + +// DatetimeServerTransport connects instances of datetimegroup.DatetimeClient to instances of DatetimeServer. +// Don't use this type directly, use NewDatetimeServerTransport instead. +type DatetimeServerTransport struct { + srv *DatetimeServer + trMu sync.Mutex + trDatetimeHeaderServer *DatetimeHeaderServerTransport + trDatetimePropertyServer *DatetimePropertyServerTransport + trDatetimeQueryServer *DatetimeQueryServerTransport + trDatetimeResponseHeaderServer *DatetimeResponseHeaderServerTransport +} + +// Do implements the policy.Transporter interface for DatetimeServerTransport. +func (d *DatetimeServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (d *DatetimeServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "DatetimeHeaderClient": + initServer(&d.trMu, &d.trDatetimeHeaderServer, func() *DatetimeHeaderServerTransport { + return NewDatetimeHeaderServerTransport(&d.srv.DatetimeHeaderServer) + }) + resp, err = d.trDatetimeHeaderServer.Do(req) + case "DatetimePropertyClient": + initServer(&d.trMu, &d.trDatetimePropertyServer, func() *DatetimePropertyServerTransport { + return NewDatetimePropertyServerTransport(&d.srv.DatetimePropertyServer) + }) + resp, err = d.trDatetimePropertyServer.Do(req) + case "DatetimeQueryClient": + initServer(&d.trMu, &d.trDatetimeQueryServer, func() *DatetimeQueryServerTransport { + return NewDatetimeQueryServerTransport(&d.srv.DatetimeQueryServer) + }) + resp, err = d.trDatetimeQueryServer.Do(req) + case "DatetimeResponseHeaderClient": + initServer(&d.trMu, &d.trDatetimeResponseHeaderServer, func() *DatetimeResponseHeaderServerTransport { + return NewDatetimeResponseHeaderServerTransport(&d.srv.DatetimeResponseHeaderServer) + }) + resp, err = d.trDatetimeResponseHeaderServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to DatetimeServerTransport +var datetimeServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/encode/datetimegroup/fake/zz_datetimeheader_server.go b/test/http-specs/encode/datetimegroup/fake/zz_datetimeheader_server.go new file mode 100644 index 000000000000..c2f09eda6bc7 --- /dev/null +++ b/test/http-specs/encode/datetimegroup/fake/zz_datetimeheader_server.go @@ -0,0 +1,235 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "datetimegroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "strconv" + "time" +) + +// DatetimeHeaderServer is a fake server for instances of the datetimegroup.DatetimeHeaderClient type. +type DatetimeHeaderServer struct { + // Default is the fake for method DatetimeHeaderClient.Default + // HTTP status codes to indicate success: http.StatusNoContent + Default func(ctx context.Context, value time.Time, options *datetimegroup.DatetimeHeaderClientDefaultOptions) (resp azfake.Responder[datetimegroup.DatetimeHeaderClientDefaultResponse], errResp azfake.ErrorResponder) + + // RFC3339 is the fake for method DatetimeHeaderClient.RFC3339 + // HTTP status codes to indicate success: http.StatusNoContent + RFC3339 func(ctx context.Context, value time.Time, options *datetimegroup.DatetimeHeaderClientRFC3339Options) (resp azfake.Responder[datetimegroup.DatetimeHeaderClientRFC3339Response], errResp azfake.ErrorResponder) + + // RFC7231 is the fake for method DatetimeHeaderClient.RFC7231 + // HTTP status codes to indicate success: http.StatusNoContent + RFC7231 func(ctx context.Context, value time.Time, options *datetimegroup.DatetimeHeaderClientRFC7231Options) (resp azfake.Responder[datetimegroup.DatetimeHeaderClientRFC7231Response], errResp azfake.ErrorResponder) + + // UnixTimestamp is the fake for method DatetimeHeaderClient.UnixTimestamp + // HTTP status codes to indicate success: http.StatusNoContent + UnixTimestamp func(ctx context.Context, value time.Time, options *datetimegroup.DatetimeHeaderClientUnixTimestampOptions) (resp azfake.Responder[datetimegroup.DatetimeHeaderClientUnixTimestampResponse], errResp azfake.ErrorResponder) + + // UnixTimestampArray is the fake for method DatetimeHeaderClient.UnixTimestampArray + // HTTP status codes to indicate success: http.StatusNoContent + UnixTimestampArray func(ctx context.Context, value []time.Time, options *datetimegroup.DatetimeHeaderClientUnixTimestampArrayOptions) (resp azfake.Responder[datetimegroup.DatetimeHeaderClientUnixTimestampArrayResponse], errResp azfake.ErrorResponder) +} + +// NewDatetimeHeaderServerTransport creates a new instance of DatetimeHeaderServerTransport with the provided implementation. +// The returned DatetimeHeaderServerTransport instance is connected to an instance of datetimegroup.DatetimeHeaderClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDatetimeHeaderServerTransport(srv *DatetimeHeaderServer) *DatetimeHeaderServerTransport { + return &DatetimeHeaderServerTransport{srv: srv} +} + +// DatetimeHeaderServerTransport connects instances of datetimegroup.DatetimeHeaderClient to instances of DatetimeHeaderServer. +// Don't use this type directly, use NewDatetimeHeaderServerTransport instead. +type DatetimeHeaderServerTransport struct { + srv *DatetimeHeaderServer +} + +// Do implements the policy.Transporter interface for DatetimeHeaderServerTransport. +func (d *DatetimeHeaderServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DatetimeHeaderServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if datetimeHeaderServerTransportInterceptor != nil { + res.resp, res.err, intercepted = datetimeHeaderServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DatetimeHeaderClient.Default": + res.resp, res.err = d.dispatchDefault(req) + case "DatetimeHeaderClient.RFC3339": + res.resp, res.err = d.dispatchRFC3339(req) + case "DatetimeHeaderClient.RFC7231": + res.resp, res.err = d.dispatchRFC7231(req) + case "DatetimeHeaderClient.UnixTimestamp": + res.resp, res.err = d.dispatchUnixTimestamp(req) + case "DatetimeHeaderClient.UnixTimestampArray": + res.resp, res.err = d.dispatchUnixTimestampArray(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DatetimeHeaderServerTransport) dispatchDefault(req *http.Request) (*http.Response, error) { + if d.srv.Default == nil { + return nil, &nonRetriableError{errors.New("fake for method Default not implemented")} + } + valueParam, err := time.Parse(time.RFC1123, getHeaderValue(req.Header, "value")) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Default(req.Context(), valueParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DatetimeHeaderServerTransport) dispatchRFC3339(req *http.Request) (*http.Response, error) { + if d.srv.RFC3339 == nil { + return nil, &nonRetriableError{errors.New("fake for method RFC3339 not implemented")} + } + valueParam, err := time.Parse(time.RFC3339Nano, getHeaderValue(req.Header, "value")) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.RFC3339(req.Context(), valueParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DatetimeHeaderServerTransport) dispatchRFC7231(req *http.Request) (*http.Response, error) { + if d.srv.RFC7231 == nil { + return nil, &nonRetriableError{errors.New("fake for method RFC7231 not implemented")} + } + valueParam, err := time.Parse(time.RFC1123, getHeaderValue(req.Header, "value")) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.RFC7231(req.Context(), valueParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DatetimeHeaderServerTransport) dispatchUnixTimestamp(req *http.Request) (*http.Response, error) { + if d.srv.UnixTimestamp == nil { + return nil, &nonRetriableError{errors.New("fake for method UnixTimestamp not implemented")} + } + valueParam, err := parseWithCast(getHeaderValue(req.Header, "value"), func(v string) (time.Time, error) { + p, parseErr := strconv.ParseInt(v, 10, 64) + if parseErr != nil { + return time.Time{}, parseErr + } + return time.Unix(p, 0).UTC(), nil + }) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.UnixTimestamp(req.Context(), valueParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DatetimeHeaderServerTransport) dispatchUnixTimestampArray(req *http.Request) (*http.Response, error) { + if d.srv.UnixTimestampArray == nil { + return nil, &nonRetriableError{errors.New("fake for method UnixTimestampArray not implemented")} + } + valueElements := splitHelper(getHeaderValue(req.Header, "value"), ",") + valueParam := make([]time.Time, len(valueElements)) + for i := 0; i < len(valueElements); i++ { + p, parseErr := strconv.ParseInt(valueElements[i], 10, 64) + if parseErr != nil { + return nil, parseErr + } + parsedUnix := time.Unix(p, 0).UTC() + valueParam[i] = time.Time(parsedUnix) + } + respr, errRespr := d.srv.UnixTimestampArray(req.Context(), valueParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DatetimeHeaderServerTransport +var datetimeHeaderServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/encode/datetimegroup/fake/zz_datetimeproperty_server.go b/test/http-specs/encode/datetimegroup/fake/zz_datetimeproperty_server.go new file mode 100644 index 000000000000..9bf407aa5b42 --- /dev/null +++ b/test/http-specs/encode/datetimegroup/fake/zz_datetimeproperty_server.go @@ -0,0 +1,221 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "datetimegroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// DatetimePropertyServer is a fake server for instances of the datetimegroup.DatetimePropertyClient type. +type DatetimePropertyServer struct { + // Default is the fake for method DatetimePropertyClient.Default + // HTTP status codes to indicate success: http.StatusOK + Default func(ctx context.Context, body datetimegroup.DefaultDatetimeProperty, options *datetimegroup.DatetimePropertyClientDefaultOptions) (resp azfake.Responder[datetimegroup.DatetimePropertyClientDefaultResponse], errResp azfake.ErrorResponder) + + // RFC3339 is the fake for method DatetimePropertyClient.RFC3339 + // HTTP status codes to indicate success: http.StatusOK + RFC3339 func(ctx context.Context, body datetimegroup.RFC3339DatetimeProperty, options *datetimegroup.DatetimePropertyClientRFC3339Options) (resp azfake.Responder[datetimegroup.DatetimePropertyClientRFC3339Response], errResp azfake.ErrorResponder) + + // RFC7231 is the fake for method DatetimePropertyClient.RFC7231 + // HTTP status codes to indicate success: http.StatusOK + RFC7231 func(ctx context.Context, body datetimegroup.RFC7231DatetimeProperty, options *datetimegroup.DatetimePropertyClientRFC7231Options) (resp azfake.Responder[datetimegroup.DatetimePropertyClientRFC7231Response], errResp azfake.ErrorResponder) + + // UnixTimestamp is the fake for method DatetimePropertyClient.UnixTimestamp + // HTTP status codes to indicate success: http.StatusOK + UnixTimestamp func(ctx context.Context, body datetimegroup.UnixTimestampDatetimeProperty, options *datetimegroup.DatetimePropertyClientUnixTimestampOptions) (resp azfake.Responder[datetimegroup.DatetimePropertyClientUnixTimestampResponse], errResp azfake.ErrorResponder) + + // UnixTimestampArray is the fake for method DatetimePropertyClient.UnixTimestampArray + // HTTP status codes to indicate success: http.StatusOK + UnixTimestampArray func(ctx context.Context, body datetimegroup.UnixTimestampArrayDatetimeProperty, options *datetimegroup.DatetimePropertyClientUnixTimestampArrayOptions) (resp azfake.Responder[datetimegroup.DatetimePropertyClientUnixTimestampArrayResponse], errResp azfake.ErrorResponder) +} + +// NewDatetimePropertyServerTransport creates a new instance of DatetimePropertyServerTransport with the provided implementation. +// The returned DatetimePropertyServerTransport instance is connected to an instance of datetimegroup.DatetimePropertyClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDatetimePropertyServerTransport(srv *DatetimePropertyServer) *DatetimePropertyServerTransport { + return &DatetimePropertyServerTransport{srv: srv} +} + +// DatetimePropertyServerTransport connects instances of datetimegroup.DatetimePropertyClient to instances of DatetimePropertyServer. +// Don't use this type directly, use NewDatetimePropertyServerTransport instead. +type DatetimePropertyServerTransport struct { + srv *DatetimePropertyServer +} + +// Do implements the policy.Transporter interface for DatetimePropertyServerTransport. +func (d *DatetimePropertyServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DatetimePropertyServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if datetimePropertyServerTransportInterceptor != nil { + res.resp, res.err, intercepted = datetimePropertyServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DatetimePropertyClient.Default": + res.resp, res.err = d.dispatchDefault(req) + case "DatetimePropertyClient.RFC3339": + res.resp, res.err = d.dispatchRFC3339(req) + case "DatetimePropertyClient.RFC7231": + res.resp, res.err = d.dispatchRFC7231(req) + case "DatetimePropertyClient.UnixTimestamp": + res.resp, res.err = d.dispatchUnixTimestamp(req) + case "DatetimePropertyClient.UnixTimestampArray": + res.resp, res.err = d.dispatchUnixTimestampArray(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DatetimePropertyServerTransport) dispatchDefault(req *http.Request) (*http.Response, error) { + if d.srv.Default == nil { + return nil, &nonRetriableError{errors.New("fake for method Default not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[datetimegroup.DefaultDatetimeProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Default(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DefaultDatetimeProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DatetimePropertyServerTransport) dispatchRFC3339(req *http.Request) (*http.Response, error) { + if d.srv.RFC3339 == nil { + return nil, &nonRetriableError{errors.New("fake for method RFC3339 not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[datetimegroup.RFC3339DatetimeProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.RFC3339(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RFC3339DatetimeProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DatetimePropertyServerTransport) dispatchRFC7231(req *http.Request) (*http.Response, error) { + if d.srv.RFC7231 == nil { + return nil, &nonRetriableError{errors.New("fake for method RFC7231 not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[datetimegroup.RFC7231DatetimeProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.RFC7231(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RFC7231DatetimeProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DatetimePropertyServerTransport) dispatchUnixTimestamp(req *http.Request) (*http.Response, error) { + if d.srv.UnixTimestamp == nil { + return nil, &nonRetriableError{errors.New("fake for method UnixTimestamp not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[datetimegroup.UnixTimestampDatetimeProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.UnixTimestamp(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).UnixTimestampDatetimeProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DatetimePropertyServerTransport) dispatchUnixTimestampArray(req *http.Request) (*http.Response, error) { + if d.srv.UnixTimestampArray == nil { + return nil, &nonRetriableError{errors.New("fake for method UnixTimestampArray not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[datetimegroup.UnixTimestampArrayDatetimeProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.UnixTimestampArray(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).UnixTimestampArrayDatetimeProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DatetimePropertyServerTransport +var datetimePropertyServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/encode/datetimegroup/fake/zz_datetimequery_server.go b/test/http-specs/encode/datetimegroup/fake/zz_datetimequery_server.go new file mode 100644 index 000000000000..683092922afa --- /dev/null +++ b/test/http-specs/encode/datetimegroup/fake/zz_datetimequery_server.go @@ -0,0 +1,240 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "datetimegroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "strconv" + "time" +) + +// DatetimeQueryServer is a fake server for instances of the datetimegroup.DatetimeQueryClient type. +type DatetimeQueryServer struct { + // Default is the fake for method DatetimeQueryClient.Default + // HTTP status codes to indicate success: http.StatusNoContent + Default func(ctx context.Context, value time.Time, options *datetimegroup.DatetimeQueryClientDefaultOptions) (resp azfake.Responder[datetimegroup.DatetimeQueryClientDefaultResponse], errResp azfake.ErrorResponder) + + // RFC3339 is the fake for method DatetimeQueryClient.RFC3339 + // HTTP status codes to indicate success: http.StatusNoContent + RFC3339 func(ctx context.Context, value time.Time, options *datetimegroup.DatetimeQueryClientRFC3339Options) (resp azfake.Responder[datetimegroup.DatetimeQueryClientRFC3339Response], errResp azfake.ErrorResponder) + + // RFC7231 is the fake for method DatetimeQueryClient.RFC7231 + // HTTP status codes to indicate success: http.StatusNoContent + RFC7231 func(ctx context.Context, value time.Time, options *datetimegroup.DatetimeQueryClientRFC7231Options) (resp azfake.Responder[datetimegroup.DatetimeQueryClientRFC7231Response], errResp azfake.ErrorResponder) + + // UnixTimestamp is the fake for method DatetimeQueryClient.UnixTimestamp + // HTTP status codes to indicate success: http.StatusNoContent + UnixTimestamp func(ctx context.Context, value time.Time, options *datetimegroup.DatetimeQueryClientUnixTimestampOptions) (resp azfake.Responder[datetimegroup.DatetimeQueryClientUnixTimestampResponse], errResp azfake.ErrorResponder) + + // UnixTimestampArray is the fake for method DatetimeQueryClient.UnixTimestampArray + // HTTP status codes to indicate success: http.StatusNoContent + UnixTimestampArray func(ctx context.Context, value []time.Time, options *datetimegroup.DatetimeQueryClientUnixTimestampArrayOptions) (resp azfake.Responder[datetimegroup.DatetimeQueryClientUnixTimestampArrayResponse], errResp azfake.ErrorResponder) +} + +// NewDatetimeQueryServerTransport creates a new instance of DatetimeQueryServerTransport with the provided implementation. +// The returned DatetimeQueryServerTransport instance is connected to an instance of datetimegroup.DatetimeQueryClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDatetimeQueryServerTransport(srv *DatetimeQueryServer) *DatetimeQueryServerTransport { + return &DatetimeQueryServerTransport{srv: srv} +} + +// DatetimeQueryServerTransport connects instances of datetimegroup.DatetimeQueryClient to instances of DatetimeQueryServer. +// Don't use this type directly, use NewDatetimeQueryServerTransport instead. +type DatetimeQueryServerTransport struct { + srv *DatetimeQueryServer +} + +// Do implements the policy.Transporter interface for DatetimeQueryServerTransport. +func (d *DatetimeQueryServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DatetimeQueryServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if datetimeQueryServerTransportInterceptor != nil { + res.resp, res.err, intercepted = datetimeQueryServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DatetimeQueryClient.Default": + res.resp, res.err = d.dispatchDefault(req) + case "DatetimeQueryClient.RFC3339": + res.resp, res.err = d.dispatchRFC3339(req) + case "DatetimeQueryClient.RFC7231": + res.resp, res.err = d.dispatchRFC7231(req) + case "DatetimeQueryClient.UnixTimestamp": + res.resp, res.err = d.dispatchUnixTimestamp(req) + case "DatetimeQueryClient.UnixTimestampArray": + res.resp, res.err = d.dispatchUnixTimestampArray(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DatetimeQueryServerTransport) dispatchDefault(req *http.Request) (*http.Response, error) { + if d.srv.Default == nil { + return nil, &nonRetriableError{errors.New("fake for method Default not implemented")} + } + qp := req.URL.Query() + valueParam, err := time.Parse(time.RFC3339Nano, qp.Get("value")) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Default(req.Context(), valueParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DatetimeQueryServerTransport) dispatchRFC3339(req *http.Request) (*http.Response, error) { + if d.srv.RFC3339 == nil { + return nil, &nonRetriableError{errors.New("fake for method RFC3339 not implemented")} + } + qp := req.URL.Query() + valueParam, err := time.Parse(time.RFC3339Nano, qp.Get("value")) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.RFC3339(req.Context(), valueParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DatetimeQueryServerTransport) dispatchRFC7231(req *http.Request) (*http.Response, error) { + if d.srv.RFC7231 == nil { + return nil, &nonRetriableError{errors.New("fake for method RFC7231 not implemented")} + } + qp := req.URL.Query() + valueParam, err := time.Parse(time.RFC1123, qp.Get("value")) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.RFC7231(req.Context(), valueParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DatetimeQueryServerTransport) dispatchUnixTimestamp(req *http.Request) (*http.Response, error) { + if d.srv.UnixTimestamp == nil { + return nil, &nonRetriableError{errors.New("fake for method UnixTimestamp not implemented")} + } + qp := req.URL.Query() + valueParam, err := parseWithCast(qp.Get("value"), func(v string) (time.Time, error) { + p, parseErr := strconv.ParseInt(v, 10, 64) + if parseErr != nil { + return time.Time{}, parseErr + } + return time.Unix(p, 0).UTC(), nil + }) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.UnixTimestamp(req.Context(), valueParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DatetimeQueryServerTransport) dispatchUnixTimestampArray(req *http.Request) (*http.Response, error) { + if d.srv.UnixTimestampArray == nil { + return nil, &nonRetriableError{errors.New("fake for method UnixTimestampArray not implemented")} + } + qp := req.URL.Query() + valueElements := splitHelper(qp.Get("value"), ",") + valueParam := make([]time.Time, len(valueElements)) + for i := 0; i < len(valueElements); i++ { + p, parseErr := strconv.ParseInt(valueElements[i], 10, 64) + if parseErr != nil { + return nil, parseErr + } + parsedUnix := time.Unix(p, 0).UTC() + valueParam[i] = time.Time(parsedUnix) + } + respr, errRespr := d.srv.UnixTimestampArray(req.Context(), valueParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DatetimeQueryServerTransport +var datetimeQueryServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/encode/datetimegroup/fake/zz_datetimeresponseheader_server.go b/test/http-specs/encode/datetimegroup/fake/zz_datetimeresponseheader_server.go new file mode 100644 index 000000000000..f92e3018e041 --- /dev/null +++ b/test/http-specs/encode/datetimegroup/fake/zz_datetimeresponseheader_server.go @@ -0,0 +1,189 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "datetimegroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "net/http" + "slices" +) + +// DatetimeResponseHeaderServer is a fake server for instances of the datetimegroup.DatetimeResponseHeaderClient type. +type DatetimeResponseHeaderServer struct { + // Default is the fake for method DatetimeResponseHeaderClient.Default + // HTTP status codes to indicate success: http.StatusNoContent + Default func(ctx context.Context, options *datetimegroup.DatetimeResponseHeaderClientDefaultOptions) (resp azfake.Responder[datetimegroup.DatetimeResponseHeaderClientDefaultResponse], errResp azfake.ErrorResponder) + + // RFC3339 is the fake for method DatetimeResponseHeaderClient.RFC3339 + // HTTP status codes to indicate success: http.StatusNoContent + RFC3339 func(ctx context.Context, options *datetimegroup.DatetimeResponseHeaderClientRFC3339Options) (resp azfake.Responder[datetimegroup.DatetimeResponseHeaderClientRFC3339Response], errResp azfake.ErrorResponder) + + // RFC7231 is the fake for method DatetimeResponseHeaderClient.RFC7231 + // HTTP status codes to indicate success: http.StatusNoContent + RFC7231 func(ctx context.Context, options *datetimegroup.DatetimeResponseHeaderClientRFC7231Options) (resp azfake.Responder[datetimegroup.DatetimeResponseHeaderClientRFC7231Response], errResp azfake.ErrorResponder) + + // UnixTimestamp is the fake for method DatetimeResponseHeaderClient.UnixTimestamp + // HTTP status codes to indicate success: http.StatusNoContent + UnixTimestamp func(ctx context.Context, options *datetimegroup.DatetimeResponseHeaderClientUnixTimestampOptions) (resp azfake.Responder[datetimegroup.DatetimeResponseHeaderClientUnixTimestampResponse], errResp azfake.ErrorResponder) +} + +// NewDatetimeResponseHeaderServerTransport creates a new instance of DatetimeResponseHeaderServerTransport with the provided implementation. +// The returned DatetimeResponseHeaderServerTransport instance is connected to an instance of datetimegroup.DatetimeResponseHeaderClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDatetimeResponseHeaderServerTransport(srv *DatetimeResponseHeaderServer) *DatetimeResponseHeaderServerTransport { + return &DatetimeResponseHeaderServerTransport{srv: srv} +} + +// DatetimeResponseHeaderServerTransport connects instances of datetimegroup.DatetimeResponseHeaderClient to instances of DatetimeResponseHeaderServer. +// Don't use this type directly, use NewDatetimeResponseHeaderServerTransport instead. +type DatetimeResponseHeaderServerTransport struct { + srv *DatetimeResponseHeaderServer +} + +// Do implements the policy.Transporter interface for DatetimeResponseHeaderServerTransport. +func (d *DatetimeResponseHeaderServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DatetimeResponseHeaderServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if datetimeResponseHeaderServerTransportInterceptor != nil { + res.resp, res.err, intercepted = datetimeResponseHeaderServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DatetimeResponseHeaderClient.Default": + res.resp, res.err = d.dispatchDefault(req) + case "DatetimeResponseHeaderClient.RFC3339": + res.resp, res.err = d.dispatchRFC3339(req) + case "DatetimeResponseHeaderClient.RFC7231": + res.resp, res.err = d.dispatchRFC7231(req) + case "DatetimeResponseHeaderClient.UnixTimestamp": + res.resp, res.err = d.dispatchUnixTimestamp(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DatetimeResponseHeaderServerTransport) dispatchDefault(req *http.Request) (*http.Response, error) { + if d.srv.Default == nil { + return nil, &nonRetriableError{errors.New("fake for method Default not implemented")} + } + respr, errRespr := d.srv.Default(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).Value; val != nil { + resp.Header.Set("value", datetime.RFC7231(*val).String()) + } + return resp, nil +} + +func (d *DatetimeResponseHeaderServerTransport) dispatchRFC3339(req *http.Request) (*http.Response, error) { + if d.srv.RFC3339 == nil { + return nil, &nonRetriableError{errors.New("fake for method RFC3339 not implemented")} + } + respr, errRespr := d.srv.RFC3339(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).Value; val != nil { + resp.Header.Set("value", datetime.RFC3339(*val).String()) + } + return resp, nil +} + +func (d *DatetimeResponseHeaderServerTransport) dispatchRFC7231(req *http.Request) (*http.Response, error) { + if d.srv.RFC7231 == nil { + return nil, &nonRetriableError{errors.New("fake for method RFC7231 not implemented")} + } + respr, errRespr := d.srv.RFC7231(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).Value; val != nil { + resp.Header.Set("value", datetime.RFC7231(*val).String()) + } + return resp, nil +} + +func (d *DatetimeResponseHeaderServerTransport) dispatchUnixTimestamp(req *http.Request) (*http.Response, error) { + if d.srv.UnixTimestamp == nil { + return nil, &nonRetriableError{errors.New("fake for method UnixTimestamp not implemented")} + } + respr, errRespr := d.srv.UnixTimestamp(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).Value; val != nil { + resp.Header.Set("value", datetime.Unix(*val).String()) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DatetimeResponseHeaderServerTransport +var datetimeResponseHeaderServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/encode/datetimegroup/fake/zz_internal.go b/test/http-specs/encode/datetimegroup/fake/zz_internal.go new file mode 100644 index 000000000000..155bc694c069 --- /dev/null +++ b/test/http-specs/encode/datetimegroup/fake/zz_internal.go @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "strings" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getHeaderValue(h http.Header, k string) string { + v := h[k] + if len(v) == 0 { + return "" + } + return v[0] +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func parseWithCast[T any](v string, parse func(v string) (T, error)) (T, error) { + t, err := parse(v) + if err != nil { + return *new(T), err + } + return t, err +} + +func splitHelper(s, sep string) []string { + if s == "" { + return nil + } + return strings.Split(s, sep) +} diff --git a/test/http-specs/encode/datetimegroup/go.mod b/test/http-specs/encode/datetimegroup/go.mod new file mode 100644 index 000000000000..7460b2595861 --- /dev/null +++ b/test/http-specs/encode/datetimegroup/go.mod @@ -0,0 +1,17 @@ +module datetimegroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/encode/datetimegroup/go.sum b/test/http-specs/encode/datetimegroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/encode/datetimegroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/encode/datetimegroup/testdata/_metadata.json b/test/http-specs/encode/datetimegroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/encode/datetimegroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/encode/datetimegroup/zz_datetime_client.go b/test/http-specs/encode/datetimegroup/zz_datetime_client.go new file mode 100644 index 000000000000..8c1def001dc0 --- /dev/null +++ b/test/http-specs/encode/datetimegroup/zz_datetime_client.go @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package datetimegroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// DatetimeClient - Test for encode decorator on datetime. +// Don't use this type directly, use NewDatetimeClientWithNoCredential() instead. +type DatetimeClient struct { + internal *azcore.Client + endpoint string +} + +// DatetimeClientOptions contains the optional values for creating a [DatetimeClient]. +type DatetimeClientOptions struct { + azcore.ClientOptions +} + +// NewDatetimeClientWithNoCredential creates a new instance of DatetimeClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewDatetimeClientWithNoCredential(endpoint string, options *DatetimeClientOptions) (*DatetimeClient, error) { + if options == nil { + options = &DatetimeClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &DatetimeClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewDatetimeHeaderClient creates a new instance of [DatetimeHeaderClient]. +func (client *DatetimeClient) NewDatetimeHeaderClient() *DatetimeHeaderClient { + return &DatetimeHeaderClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewDatetimePropertyClient creates a new instance of [DatetimePropertyClient]. +func (client *DatetimeClient) NewDatetimePropertyClient() *DatetimePropertyClient { + return &DatetimePropertyClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewDatetimeQueryClient creates a new instance of [DatetimeQueryClient]. +func (client *DatetimeClient) NewDatetimeQueryClient() *DatetimeQueryClient { + return &DatetimeQueryClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewDatetimeResponseHeaderClient creates a new instance of [DatetimeResponseHeaderClient]. +func (client *DatetimeClient) NewDatetimeResponseHeaderClient() *DatetimeResponseHeaderClient { + return &DatetimeResponseHeaderClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/http-specs/encode/datetimegroup/zz_datetimeheader_client.go b/test/http-specs/encode/datetimegroup/zz_datetimeheader_client.go new file mode 100644 index 000000000000..1d18740b33ce --- /dev/null +++ b/test/http-specs/encode/datetimegroup/zz_datetimeheader_client.go @@ -0,0 +1,206 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package datetimegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "net/http" + "strings" + "time" +) + +// DatetimeHeaderClient contains the methods for the DatetimeHeader group. +// Don't use this type directly, use [DatetimeClient.NewDatetimeHeaderClient] instead. +type DatetimeHeaderClient struct { + internal *azcore.Client + endpoint string +} + +// Default - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DatetimeHeaderClientDefaultOptions contains the optional parameters for the DatetimeHeaderClient.Default method. +func (client *DatetimeHeaderClient) Default(ctx context.Context, value time.Time, options *DatetimeHeaderClientDefaultOptions) (DatetimeHeaderClientDefaultResponse, error) { + var err error + const operationName = "DatetimeHeaderClient.Default" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.defaultCreateRequest(ctx, value, options) + if err != nil { + return DatetimeHeaderClientDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DatetimeHeaderClientDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DatetimeHeaderClientDefaultResponse{}, err + } + return DatetimeHeaderClientDefaultResponse{}, nil +} + +// defaultCreateRequest creates the Default request. +func (client *DatetimeHeaderClient) defaultCreateRequest(ctx context.Context, value time.Time, _ *DatetimeHeaderClientDefaultOptions) (*policy.Request, error) { + urlPath := "/encode/datetime/header/default" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["value"] = []string{datetime.RFC7231(value).String()} + return req, nil +} + +// RFC3339 - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DatetimeHeaderClientRFC3339Options contains the optional parameters for the DatetimeHeaderClient.RFC3339 method. +func (client *DatetimeHeaderClient) RFC3339(ctx context.Context, value time.Time, options *DatetimeHeaderClientRFC3339Options) (DatetimeHeaderClientRFC3339Response, error) { + var err error + const operationName = "DatetimeHeaderClient.RFC3339" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.rfc3339CreateRequest(ctx, value, options) + if err != nil { + return DatetimeHeaderClientRFC3339Response{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DatetimeHeaderClientRFC3339Response{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DatetimeHeaderClientRFC3339Response{}, err + } + return DatetimeHeaderClientRFC3339Response{}, nil +} + +// rfc3339CreateRequest creates the RFC3339 request. +func (client *DatetimeHeaderClient) rfc3339CreateRequest(ctx context.Context, value time.Time, _ *DatetimeHeaderClientRFC3339Options) (*policy.Request, error) { + urlPath := "/encode/datetime/header/rfc3339" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["value"] = []string{datetime.RFC3339(value).String()} + return req, nil +} + +// RFC7231 - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DatetimeHeaderClientRFC7231Options contains the optional parameters for the DatetimeHeaderClient.RFC7231 method. +func (client *DatetimeHeaderClient) RFC7231(ctx context.Context, value time.Time, options *DatetimeHeaderClientRFC7231Options) (DatetimeHeaderClientRFC7231Response, error) { + var err error + const operationName = "DatetimeHeaderClient.RFC7231" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.rfc7231CreateRequest(ctx, value, options) + if err != nil { + return DatetimeHeaderClientRFC7231Response{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DatetimeHeaderClientRFC7231Response{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DatetimeHeaderClientRFC7231Response{}, err + } + return DatetimeHeaderClientRFC7231Response{}, nil +} + +// rfc7231CreateRequest creates the RFC7231 request. +func (client *DatetimeHeaderClient) rfc7231CreateRequest(ctx context.Context, value time.Time, _ *DatetimeHeaderClientRFC7231Options) (*policy.Request, error) { + urlPath := "/encode/datetime/header/rfc7231" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["value"] = []string{datetime.RFC7231(value).String()} + return req, nil +} + +// UnixTimestamp - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DatetimeHeaderClientUnixTimestampOptions contains the optional parameters for the DatetimeHeaderClient.UnixTimestamp +// method. +func (client *DatetimeHeaderClient) UnixTimestamp(ctx context.Context, value time.Time, options *DatetimeHeaderClientUnixTimestampOptions) (DatetimeHeaderClientUnixTimestampResponse, error) { + var err error + const operationName = "DatetimeHeaderClient.UnixTimestamp" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.unixTimestampCreateRequest(ctx, value, options) + if err != nil { + return DatetimeHeaderClientUnixTimestampResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DatetimeHeaderClientUnixTimestampResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DatetimeHeaderClientUnixTimestampResponse{}, err + } + return DatetimeHeaderClientUnixTimestampResponse{}, nil +} + +// unixTimestampCreateRequest creates the UnixTimestamp request. +func (client *DatetimeHeaderClient) unixTimestampCreateRequest(ctx context.Context, value time.Time, _ *DatetimeHeaderClientUnixTimestampOptions) (*policy.Request, error) { + urlPath := "/encode/datetime/header/unix-timestamp" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["value"] = []string{datetime.Unix(value).String()} + return req, nil +} + +// UnixTimestampArray - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DatetimeHeaderClientUnixTimestampArrayOptions contains the optional parameters for the DatetimeHeaderClient.UnixTimestampArray +// method. +func (client *DatetimeHeaderClient) UnixTimestampArray(ctx context.Context, value []time.Time, options *DatetimeHeaderClientUnixTimestampArrayOptions) (DatetimeHeaderClientUnixTimestampArrayResponse, error) { + var err error + const operationName = "DatetimeHeaderClient.UnixTimestampArray" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.unixTimestampArrayCreateRequest(ctx, value, options) + if err != nil { + return DatetimeHeaderClientUnixTimestampArrayResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DatetimeHeaderClientUnixTimestampArrayResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DatetimeHeaderClientUnixTimestampArrayResponse{}, err + } + return DatetimeHeaderClientUnixTimestampArrayResponse{}, nil +} + +// unixTimestampArrayCreateRequest creates the UnixTimestampArray request. +func (client *DatetimeHeaderClient) unixTimestampArrayCreateRequest(ctx context.Context, value []time.Time, _ *DatetimeHeaderClientUnixTimestampArrayOptions) (*policy.Request, error) { + urlPath := "/encode/datetime/header/unix-timestamp-array" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["value"] = []string{strings.Join(func() []string { + encodedValue := make([]string, len(value)) + for i := 0; i < len(value); i++ { + encodedValue[i] = datetime.Unix(value[i]).String() + } + return encodedValue + }(), ",")} + return req, nil +} diff --git a/test/http-specs/encode/datetimegroup/zz_datetimeproperty_client.go b/test/http-specs/encode/datetimegroup/zz_datetimeproperty_client.go new file mode 100644 index 000000000000..01e90acb12dc --- /dev/null +++ b/test/http-specs/encode/datetimegroup/zz_datetimeproperty_client.go @@ -0,0 +1,270 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package datetimegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// DatetimePropertyClient contains the methods for the DatetimeProperty group. +// Don't use this type directly, use [DatetimeClient.NewDatetimePropertyClient] instead. +type DatetimePropertyClient struct { + internal *azcore.Client + endpoint string +} + +// Default - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DatetimePropertyClientDefaultOptions contains the optional parameters for the DatetimePropertyClient.Default +// method. +func (client *DatetimePropertyClient) Default(ctx context.Context, body DefaultDatetimeProperty, options *DatetimePropertyClientDefaultOptions) (DatetimePropertyClientDefaultResponse, error) { + var err error + const operationName = "DatetimePropertyClient.Default" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.defaultCreateRequest(ctx, body, options) + if err != nil { + return DatetimePropertyClientDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DatetimePropertyClientDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DatetimePropertyClientDefaultResponse{}, err + } + resp, err := client.defaultHandleResponse(httpResp) + return resp, err +} + +// defaultCreateRequest creates the Default request. +func (client *DatetimePropertyClient) defaultCreateRequest(ctx context.Context, body DefaultDatetimeProperty, _ *DatetimePropertyClientDefaultOptions) (*policy.Request, error) { + urlPath := "/encode/datetime/property/default" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// defaultHandleResponse handles the Default response. +func (client *DatetimePropertyClient) defaultHandleResponse(resp *http.Response) (DatetimePropertyClientDefaultResponse, error) { + result := DatetimePropertyClientDefaultResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DefaultDatetimeProperty); err != nil { + return DatetimePropertyClientDefaultResponse{}, err + } + return result, nil +} + +// RFC3339 - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DatetimePropertyClientRFC3339Options contains the optional parameters for the DatetimePropertyClient.RFC3339 +// method. +func (client *DatetimePropertyClient) RFC3339(ctx context.Context, body RFC3339DatetimeProperty, options *DatetimePropertyClientRFC3339Options) (DatetimePropertyClientRFC3339Response, error) { + var err error + const operationName = "DatetimePropertyClient.RFC3339" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.rfc3339CreateRequest(ctx, body, options) + if err != nil { + return DatetimePropertyClientRFC3339Response{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DatetimePropertyClientRFC3339Response{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DatetimePropertyClientRFC3339Response{}, err + } + resp, err := client.rfc3339HandleResponse(httpResp) + return resp, err +} + +// rfc3339CreateRequest creates the RFC3339 request. +func (client *DatetimePropertyClient) rfc3339CreateRequest(ctx context.Context, body RFC3339DatetimeProperty, _ *DatetimePropertyClientRFC3339Options) (*policy.Request, error) { + urlPath := "/encode/datetime/property/rfc3339" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// rfc3339HandleResponse handles the RFC3339 response. +func (client *DatetimePropertyClient) rfc3339HandleResponse(resp *http.Response) (DatetimePropertyClientRFC3339Response, error) { + result := DatetimePropertyClientRFC3339Response{} + if err := runtime.UnmarshalAsJSON(resp, &result.RFC3339DatetimeProperty); err != nil { + return DatetimePropertyClientRFC3339Response{}, err + } + return result, nil +} + +// RFC7231 - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DatetimePropertyClientRFC7231Options contains the optional parameters for the DatetimePropertyClient.RFC7231 +// method. +func (client *DatetimePropertyClient) RFC7231(ctx context.Context, body RFC7231DatetimeProperty, options *DatetimePropertyClientRFC7231Options) (DatetimePropertyClientRFC7231Response, error) { + var err error + const operationName = "DatetimePropertyClient.RFC7231" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.rfc7231CreateRequest(ctx, body, options) + if err != nil { + return DatetimePropertyClientRFC7231Response{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DatetimePropertyClientRFC7231Response{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DatetimePropertyClientRFC7231Response{}, err + } + resp, err := client.rfc7231HandleResponse(httpResp) + return resp, err +} + +// rfc7231CreateRequest creates the RFC7231 request. +func (client *DatetimePropertyClient) rfc7231CreateRequest(ctx context.Context, body RFC7231DatetimeProperty, _ *DatetimePropertyClientRFC7231Options) (*policy.Request, error) { + urlPath := "/encode/datetime/property/rfc7231" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// rfc7231HandleResponse handles the RFC7231 response. +func (client *DatetimePropertyClient) rfc7231HandleResponse(resp *http.Response) (DatetimePropertyClientRFC7231Response, error) { + result := DatetimePropertyClientRFC7231Response{} + if err := runtime.UnmarshalAsJSON(resp, &result.RFC7231DatetimeProperty); err != nil { + return DatetimePropertyClientRFC7231Response{}, err + } + return result, nil +} + +// UnixTimestamp - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DatetimePropertyClientUnixTimestampOptions contains the optional parameters for the DatetimePropertyClient.UnixTimestamp +// method. +func (client *DatetimePropertyClient) UnixTimestamp(ctx context.Context, body UnixTimestampDatetimeProperty, options *DatetimePropertyClientUnixTimestampOptions) (DatetimePropertyClientUnixTimestampResponse, error) { + var err error + const operationName = "DatetimePropertyClient.UnixTimestamp" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.unixTimestampCreateRequest(ctx, body, options) + if err != nil { + return DatetimePropertyClientUnixTimestampResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DatetimePropertyClientUnixTimestampResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DatetimePropertyClientUnixTimestampResponse{}, err + } + resp, err := client.unixTimestampHandleResponse(httpResp) + return resp, err +} + +// unixTimestampCreateRequest creates the UnixTimestamp request. +func (client *DatetimePropertyClient) unixTimestampCreateRequest(ctx context.Context, body UnixTimestampDatetimeProperty, _ *DatetimePropertyClientUnixTimestampOptions) (*policy.Request, error) { + urlPath := "/encode/datetime/property/unix-timestamp" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// unixTimestampHandleResponse handles the UnixTimestamp response. +func (client *DatetimePropertyClient) unixTimestampHandleResponse(resp *http.Response) (DatetimePropertyClientUnixTimestampResponse, error) { + result := DatetimePropertyClientUnixTimestampResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.UnixTimestampDatetimeProperty); err != nil { + return DatetimePropertyClientUnixTimestampResponse{}, err + } + return result, nil +} + +// UnixTimestampArray - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DatetimePropertyClientUnixTimestampArrayOptions contains the optional parameters for the DatetimePropertyClient.UnixTimestampArray +// method. +func (client *DatetimePropertyClient) UnixTimestampArray(ctx context.Context, body UnixTimestampArrayDatetimeProperty, options *DatetimePropertyClientUnixTimestampArrayOptions) (DatetimePropertyClientUnixTimestampArrayResponse, error) { + var err error + const operationName = "DatetimePropertyClient.UnixTimestampArray" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.unixTimestampArrayCreateRequest(ctx, body, options) + if err != nil { + return DatetimePropertyClientUnixTimestampArrayResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DatetimePropertyClientUnixTimestampArrayResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DatetimePropertyClientUnixTimestampArrayResponse{}, err + } + resp, err := client.unixTimestampArrayHandleResponse(httpResp) + return resp, err +} + +// unixTimestampArrayCreateRequest creates the UnixTimestampArray request. +func (client *DatetimePropertyClient) unixTimestampArrayCreateRequest(ctx context.Context, body UnixTimestampArrayDatetimeProperty, _ *DatetimePropertyClientUnixTimestampArrayOptions) (*policy.Request, error) { + urlPath := "/encode/datetime/property/unix-timestamp-array" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// unixTimestampArrayHandleResponse handles the UnixTimestampArray response. +func (client *DatetimePropertyClient) unixTimestampArrayHandleResponse(resp *http.Response) (DatetimePropertyClientUnixTimestampArrayResponse, error) { + result := DatetimePropertyClientUnixTimestampArrayResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.UnixTimestampArrayDatetimeProperty); err != nil { + return DatetimePropertyClientUnixTimestampArrayResponse{}, err + } + return result, nil +} diff --git a/test/http-specs/encode/datetimegroup/zz_datetimequery_client.go b/test/http-specs/encode/datetimegroup/zz_datetimequery_client.go new file mode 100644 index 000000000000..e30c16b5d937 --- /dev/null +++ b/test/http-specs/encode/datetimegroup/zz_datetimequery_client.go @@ -0,0 +1,216 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package datetimegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "net/http" + "strings" + "time" +) + +// DatetimeQueryClient contains the methods for the DatetimeQuery group. +// Don't use this type directly, use [DatetimeClient.NewDatetimeQueryClient] instead. +type DatetimeQueryClient struct { + internal *azcore.Client + endpoint string +} + +// Default - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DatetimeQueryClientDefaultOptions contains the optional parameters for the DatetimeQueryClient.Default method. +func (client *DatetimeQueryClient) Default(ctx context.Context, value time.Time, options *DatetimeQueryClientDefaultOptions) (DatetimeQueryClientDefaultResponse, error) { + var err error + const operationName = "DatetimeQueryClient.Default" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.defaultCreateRequest(ctx, value, options) + if err != nil { + return DatetimeQueryClientDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DatetimeQueryClientDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DatetimeQueryClientDefaultResponse{}, err + } + return DatetimeQueryClientDefaultResponse{}, nil +} + +// defaultCreateRequest creates the Default request. +func (client *DatetimeQueryClient) defaultCreateRequest(ctx context.Context, value time.Time, _ *DatetimeQueryClientDefaultOptions) (*policy.Request, error) { + urlPath := "/encode/datetime/query/default" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("value", datetime.RFC3339(value).String()) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// RFC3339 - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DatetimeQueryClientRFC3339Options contains the optional parameters for the DatetimeQueryClient.RFC3339 method. +func (client *DatetimeQueryClient) RFC3339(ctx context.Context, value time.Time, options *DatetimeQueryClientRFC3339Options) (DatetimeQueryClientRFC3339Response, error) { + var err error + const operationName = "DatetimeQueryClient.RFC3339" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.rfc3339CreateRequest(ctx, value, options) + if err != nil { + return DatetimeQueryClientRFC3339Response{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DatetimeQueryClientRFC3339Response{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DatetimeQueryClientRFC3339Response{}, err + } + return DatetimeQueryClientRFC3339Response{}, nil +} + +// rfc3339CreateRequest creates the RFC3339 request. +func (client *DatetimeQueryClient) rfc3339CreateRequest(ctx context.Context, value time.Time, _ *DatetimeQueryClientRFC3339Options) (*policy.Request, error) { + urlPath := "/encode/datetime/query/rfc3339" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("value", datetime.RFC3339(value).String()) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// RFC7231 - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DatetimeQueryClientRFC7231Options contains the optional parameters for the DatetimeQueryClient.RFC7231 method. +func (client *DatetimeQueryClient) RFC7231(ctx context.Context, value time.Time, options *DatetimeQueryClientRFC7231Options) (DatetimeQueryClientRFC7231Response, error) { + var err error + const operationName = "DatetimeQueryClient.RFC7231" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.rfc7231CreateRequest(ctx, value, options) + if err != nil { + return DatetimeQueryClientRFC7231Response{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DatetimeQueryClientRFC7231Response{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DatetimeQueryClientRFC7231Response{}, err + } + return DatetimeQueryClientRFC7231Response{}, nil +} + +// rfc7231CreateRequest creates the RFC7231 request. +func (client *DatetimeQueryClient) rfc7231CreateRequest(ctx context.Context, value time.Time, _ *DatetimeQueryClientRFC7231Options) (*policy.Request, error) { + urlPath := "/encode/datetime/query/rfc7231" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("value", datetime.RFC7231(value).String()) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// UnixTimestamp - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DatetimeQueryClientUnixTimestampOptions contains the optional parameters for the DatetimeQueryClient.UnixTimestamp +// method. +func (client *DatetimeQueryClient) UnixTimestamp(ctx context.Context, value time.Time, options *DatetimeQueryClientUnixTimestampOptions) (DatetimeQueryClientUnixTimestampResponse, error) { + var err error + const operationName = "DatetimeQueryClient.UnixTimestamp" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.unixTimestampCreateRequest(ctx, value, options) + if err != nil { + return DatetimeQueryClientUnixTimestampResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DatetimeQueryClientUnixTimestampResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DatetimeQueryClientUnixTimestampResponse{}, err + } + return DatetimeQueryClientUnixTimestampResponse{}, nil +} + +// unixTimestampCreateRequest creates the UnixTimestamp request. +func (client *DatetimeQueryClient) unixTimestampCreateRequest(ctx context.Context, value time.Time, _ *DatetimeQueryClientUnixTimestampOptions) (*policy.Request, error) { + urlPath := "/encode/datetime/query/unix-timestamp" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("value", datetime.Unix(value).String()) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// UnixTimestampArray - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DatetimeQueryClientUnixTimestampArrayOptions contains the optional parameters for the DatetimeQueryClient.UnixTimestampArray +// method. +func (client *DatetimeQueryClient) UnixTimestampArray(ctx context.Context, value []time.Time, options *DatetimeQueryClientUnixTimestampArrayOptions) (DatetimeQueryClientUnixTimestampArrayResponse, error) { + var err error + const operationName = "DatetimeQueryClient.UnixTimestampArray" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.unixTimestampArrayCreateRequest(ctx, value, options) + if err != nil { + return DatetimeQueryClientUnixTimestampArrayResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DatetimeQueryClientUnixTimestampArrayResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DatetimeQueryClientUnixTimestampArrayResponse{}, err + } + return DatetimeQueryClientUnixTimestampArrayResponse{}, nil +} + +// unixTimestampArrayCreateRequest creates the UnixTimestampArray request. +func (client *DatetimeQueryClient) unixTimestampArrayCreateRequest(ctx context.Context, value []time.Time, _ *DatetimeQueryClientUnixTimestampArrayOptions) (*policy.Request, error) { + urlPath := "/encode/datetime/query/unix-timestamp-array" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("value", strings.Join(func() []string { + encodedValue := make([]string, len(value)) + for i := 0; i < len(value); i++ { + encodedValue[i] = datetime.Unix(value[i]).String() + } + return encodedValue + }(), ",")) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/http-specs/encode/datetimegroup/zz_datetimeresponseheader_client.go b/test/http-specs/encode/datetimegroup/zz_datetimeresponseheader_client.go new file mode 100644 index 000000000000..245464b5d552 --- /dev/null +++ b/test/http-specs/encode/datetimegroup/zz_datetimeresponseheader_client.go @@ -0,0 +1,219 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package datetimegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "strconv" + "time" +) + +// DatetimeResponseHeaderClient contains the methods for the DatetimeResponseHeader group. +// Don't use this type directly, use [DatetimeClient.NewDatetimeResponseHeaderClient] instead. +type DatetimeResponseHeaderClient struct { + internal *azcore.Client + endpoint string +} + +// Default - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DatetimeResponseHeaderClientDefaultOptions contains the optional parameters for the DatetimeResponseHeaderClient.Default +// method. +func (client *DatetimeResponseHeaderClient) Default(ctx context.Context, options *DatetimeResponseHeaderClientDefaultOptions) (DatetimeResponseHeaderClientDefaultResponse, error) { + var err error + const operationName = "DatetimeResponseHeaderClient.Default" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.defaultCreateRequest(ctx, options) + if err != nil { + return DatetimeResponseHeaderClientDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DatetimeResponseHeaderClientDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DatetimeResponseHeaderClientDefaultResponse{}, err + } + resp, err := client.defaultHandleResponse(httpResp) + return resp, err +} + +// defaultCreateRequest creates the Default request. +func (client *DatetimeResponseHeaderClient) defaultCreateRequest(ctx context.Context, _ *DatetimeResponseHeaderClientDefaultOptions) (*policy.Request, error) { + urlPath := "/encode/datetime/responseheader/default" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// defaultHandleResponse handles the Default response. +func (client *DatetimeResponseHeaderClient) defaultHandleResponse(resp *http.Response) (DatetimeResponseHeaderClientDefaultResponse, error) { + result := DatetimeResponseHeaderClientDefaultResponse{} + if val := resp.Header.Get("value"); val != "" { + value, err := time.Parse(time.RFC1123, val) + if err != nil { + return DatetimeResponseHeaderClientDefaultResponse{}, err + } + result.Value = &value + } + return result, nil +} + +// RFC3339 - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DatetimeResponseHeaderClientRFC3339Options contains the optional parameters for the DatetimeResponseHeaderClient.RFC3339 +// method. +func (client *DatetimeResponseHeaderClient) RFC3339(ctx context.Context, options *DatetimeResponseHeaderClientRFC3339Options) (DatetimeResponseHeaderClientRFC3339Response, error) { + var err error + const operationName = "DatetimeResponseHeaderClient.RFC3339" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.rfc3339CreateRequest(ctx, options) + if err != nil { + return DatetimeResponseHeaderClientRFC3339Response{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DatetimeResponseHeaderClientRFC3339Response{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DatetimeResponseHeaderClientRFC3339Response{}, err + } + resp, err := client.rfc3339HandleResponse(httpResp) + return resp, err +} + +// rfc3339CreateRequest creates the RFC3339 request. +func (client *DatetimeResponseHeaderClient) rfc3339CreateRequest(ctx context.Context, _ *DatetimeResponseHeaderClientRFC3339Options) (*policy.Request, error) { + urlPath := "/encode/datetime/responseheader/rfc3339" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// rfc3339HandleResponse handles the RFC3339 response. +func (client *DatetimeResponseHeaderClient) rfc3339HandleResponse(resp *http.Response) (DatetimeResponseHeaderClientRFC3339Response, error) { + result := DatetimeResponseHeaderClientRFC3339Response{} + if val := resp.Header.Get("value"); val != "" { + value, err := time.Parse(time.RFC3339Nano, val) + if err != nil { + return DatetimeResponseHeaderClientRFC3339Response{}, err + } + result.Value = &value + } + return result, nil +} + +// RFC7231 - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DatetimeResponseHeaderClientRFC7231Options contains the optional parameters for the DatetimeResponseHeaderClient.RFC7231 +// method. +func (client *DatetimeResponseHeaderClient) RFC7231(ctx context.Context, options *DatetimeResponseHeaderClientRFC7231Options) (DatetimeResponseHeaderClientRFC7231Response, error) { + var err error + const operationName = "DatetimeResponseHeaderClient.RFC7231" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.rfc7231CreateRequest(ctx, options) + if err != nil { + return DatetimeResponseHeaderClientRFC7231Response{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DatetimeResponseHeaderClientRFC7231Response{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DatetimeResponseHeaderClientRFC7231Response{}, err + } + resp, err := client.rfc7231HandleResponse(httpResp) + return resp, err +} + +// rfc7231CreateRequest creates the RFC7231 request. +func (client *DatetimeResponseHeaderClient) rfc7231CreateRequest(ctx context.Context, _ *DatetimeResponseHeaderClientRFC7231Options) (*policy.Request, error) { + urlPath := "/encode/datetime/responseheader/rfc7231" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// rfc7231HandleResponse handles the RFC7231 response. +func (client *DatetimeResponseHeaderClient) rfc7231HandleResponse(resp *http.Response) (DatetimeResponseHeaderClientRFC7231Response, error) { + result := DatetimeResponseHeaderClientRFC7231Response{} + if val := resp.Header.Get("value"); val != "" { + value, err := time.Parse(time.RFC1123, val) + if err != nil { + return DatetimeResponseHeaderClientRFC7231Response{}, err + } + result.Value = &value + } + return result, nil +} + +// UnixTimestamp - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DatetimeResponseHeaderClientUnixTimestampOptions contains the optional parameters for the DatetimeResponseHeaderClient.UnixTimestamp +// method. +func (client *DatetimeResponseHeaderClient) UnixTimestamp(ctx context.Context, options *DatetimeResponseHeaderClientUnixTimestampOptions) (DatetimeResponseHeaderClientUnixTimestampResponse, error) { + var err error + const operationName = "DatetimeResponseHeaderClient.UnixTimestamp" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.unixTimestampCreateRequest(ctx, options) + if err != nil { + return DatetimeResponseHeaderClientUnixTimestampResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DatetimeResponseHeaderClientUnixTimestampResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DatetimeResponseHeaderClientUnixTimestampResponse{}, err + } + resp, err := client.unixTimestampHandleResponse(httpResp) + return resp, err +} + +// unixTimestampCreateRequest creates the UnixTimestamp request. +func (client *DatetimeResponseHeaderClient) unixTimestampCreateRequest(ctx context.Context, _ *DatetimeResponseHeaderClientUnixTimestampOptions) (*policy.Request, error) { + urlPath := "/encode/datetime/responseheader/unix-timestamp" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// unixTimestampHandleResponse handles the UnixTimestamp response. +func (client *DatetimeResponseHeaderClient) unixTimestampHandleResponse(resp *http.Response) (DatetimeResponseHeaderClientUnixTimestampResponse, error) { + result := DatetimeResponseHeaderClientUnixTimestampResponse{} + if val := resp.Header.Get("value"); val != "" { + sec, err := strconv.ParseInt(val, 10, 64) + if err != nil { + return DatetimeResponseHeaderClientUnixTimestampResponse{}, err + } + result.Value = to.Ptr(time.Unix(sec, 0)) + } + return result, nil +} diff --git a/test/http-specs/encode/datetimegroup/zz_models.go b/test/http-specs/encode/datetimegroup/zz_models.go new file mode 100644 index 000000000000..f5dc019e8608 --- /dev/null +++ b/test/http-specs/encode/datetimegroup/zz_models.go @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package datetimegroup + +import "time" + +type DefaultDatetimeProperty struct { + // REQUIRED + Value *time.Time +} + +type RFC3339DatetimeProperty struct { + // REQUIRED + Value *time.Time +} + +type RFC7231DatetimeProperty struct { + // REQUIRED + Value *time.Time +} + +type UnixTimestampArrayDatetimeProperty struct { + // REQUIRED + Value []time.Time +} + +type UnixTimestampDatetimeProperty struct { + // REQUIRED + Value *time.Time +} diff --git a/test/http-specs/encode/datetimegroup/zz_models_serde.go b/test/http-specs/encode/datetimegroup/zz_models_serde.go new file mode 100644 index 000000000000..2dda95e611bf --- /dev/null +++ b/test/http-specs/encode/datetimegroup/zz_models_serde.go @@ -0,0 +1,205 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package datetimegroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type DefaultDatetimeProperty. +func (d DefaultDatetimeProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DefaultDatetimeProperty. +func (d *DefaultDatetimeProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulateTime[datetime.RFC3339](val, "Value", &d.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RFC3339DatetimeProperty. +func (r RFC3339DatetimeProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "value", r.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RFC3339DatetimeProperty. +func (r *RFC3339DatetimeProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulateTime[datetime.RFC3339](val, "Value", &r.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RFC7231DatetimeProperty. +func (r RFC7231DatetimeProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC7231](objectMap, "value", r.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RFC7231DatetimeProperty. +func (r *RFC7231DatetimeProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulateTime[datetime.RFC7231](val, "Value", &r.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UnixTimestampArrayDatetimeProperty. +func (u UnixTimestampArrayDatetimeProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + aux := make([]datetime.Unix, len(u.Value), len(u.Value)) + for i := 0; i < len(u.Value); i++ { + aux[i] = (datetime.Unix)(u.Value[i]) + } + populate(objectMap, "value", aux) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UnixTimestampArrayDatetimeProperty. +func (u *UnixTimestampArrayDatetimeProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + var aux []datetime.Unix + err = unpopulate(val, "Value", &aux) + for _, au := range aux { + u.Value = append(u.Value, (time.Time)(au)) + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UnixTimestampDatetimeProperty. +func (u UnixTimestampDatetimeProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.Unix](objectMap, "value", u.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UnixTimestampDatetimeProperty. +func (u *UnixTimestampDatetimeProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulateTime[datetime.Unix](val, "Value", &u.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/http-specs/encode/datetimegroup/zz_options.go b/test/http-specs/encode/datetimegroup/zz_options.go new file mode 100644 index 000000000000..b7af3db47e6c --- /dev/null +++ b/test/http-specs/encode/datetimegroup/zz_options.go @@ -0,0 +1,108 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package datetimegroup + +// DatetimeHeaderClientDefaultOptions contains the optional parameters for the DatetimeHeaderClient.Default method. +type DatetimeHeaderClientDefaultOptions struct { + // placeholder for future optional parameters +} + +// DatetimeHeaderClientRFC3339Options contains the optional parameters for the DatetimeHeaderClient.RFC3339 method. +type DatetimeHeaderClientRFC3339Options struct { + // placeholder for future optional parameters +} + +// DatetimeHeaderClientRFC7231Options contains the optional parameters for the DatetimeHeaderClient.RFC7231 method. +type DatetimeHeaderClientRFC7231Options struct { + // placeholder for future optional parameters +} + +// DatetimeHeaderClientUnixTimestampArrayOptions contains the optional parameters for the DatetimeHeaderClient.UnixTimestampArray +// method. +type DatetimeHeaderClientUnixTimestampArrayOptions struct { + // placeholder for future optional parameters +} + +// DatetimeHeaderClientUnixTimestampOptions contains the optional parameters for the DatetimeHeaderClient.UnixTimestamp method. +type DatetimeHeaderClientUnixTimestampOptions struct { + // placeholder for future optional parameters +} + +// DatetimePropertyClientDefaultOptions contains the optional parameters for the DatetimePropertyClient.Default method. +type DatetimePropertyClientDefaultOptions struct { + // placeholder for future optional parameters +} + +// DatetimePropertyClientRFC3339Options contains the optional parameters for the DatetimePropertyClient.RFC3339 method. +type DatetimePropertyClientRFC3339Options struct { + // placeholder for future optional parameters +} + +// DatetimePropertyClientRFC7231Options contains the optional parameters for the DatetimePropertyClient.RFC7231 method. +type DatetimePropertyClientRFC7231Options struct { + // placeholder for future optional parameters +} + +// DatetimePropertyClientUnixTimestampArrayOptions contains the optional parameters for the DatetimePropertyClient.UnixTimestampArray +// method. +type DatetimePropertyClientUnixTimestampArrayOptions struct { + // placeholder for future optional parameters +} + +// DatetimePropertyClientUnixTimestampOptions contains the optional parameters for the DatetimePropertyClient.UnixTimestamp +// method. +type DatetimePropertyClientUnixTimestampOptions struct { + // placeholder for future optional parameters +} + +// DatetimeQueryClientDefaultOptions contains the optional parameters for the DatetimeQueryClient.Default method. +type DatetimeQueryClientDefaultOptions struct { + // placeholder for future optional parameters +} + +// DatetimeQueryClientRFC3339Options contains the optional parameters for the DatetimeQueryClient.RFC3339 method. +type DatetimeQueryClientRFC3339Options struct { + // placeholder for future optional parameters +} + +// DatetimeQueryClientRFC7231Options contains the optional parameters for the DatetimeQueryClient.RFC7231 method. +type DatetimeQueryClientRFC7231Options struct { + // placeholder for future optional parameters +} + +// DatetimeQueryClientUnixTimestampArrayOptions contains the optional parameters for the DatetimeQueryClient.UnixTimestampArray +// method. +type DatetimeQueryClientUnixTimestampArrayOptions struct { + // placeholder for future optional parameters +} + +// DatetimeQueryClientUnixTimestampOptions contains the optional parameters for the DatetimeQueryClient.UnixTimestamp method. +type DatetimeQueryClientUnixTimestampOptions struct { + // placeholder for future optional parameters +} + +// DatetimeResponseHeaderClientDefaultOptions contains the optional parameters for the DatetimeResponseHeaderClient.Default +// method. +type DatetimeResponseHeaderClientDefaultOptions struct { + // placeholder for future optional parameters +} + +// DatetimeResponseHeaderClientRFC3339Options contains the optional parameters for the DatetimeResponseHeaderClient.RFC3339 +// method. +type DatetimeResponseHeaderClientRFC3339Options struct { + // placeholder for future optional parameters +} + +// DatetimeResponseHeaderClientRFC7231Options contains the optional parameters for the DatetimeResponseHeaderClient.RFC7231 +// method. +type DatetimeResponseHeaderClientRFC7231Options struct { + // placeholder for future optional parameters +} + +// DatetimeResponseHeaderClientUnixTimestampOptions contains the optional parameters for the DatetimeResponseHeaderClient.UnixTimestamp +// method. +type DatetimeResponseHeaderClientUnixTimestampOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/encode/datetimegroup/zz_responses.go b/test/http-specs/encode/datetimegroup/zz_responses.go new file mode 100644 index 000000000000..0a2685d4c5c1 --- /dev/null +++ b/test/http-specs/encode/datetimegroup/zz_responses.go @@ -0,0 +1,102 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package datetimegroup + +import "time" + +// DatetimeHeaderClientDefaultResponse contains the response from method DatetimeHeaderClient.Default. +type DatetimeHeaderClientDefaultResponse struct { + // placeholder for future response values +} + +// DatetimeHeaderClientRFC3339Response contains the response from method DatetimeHeaderClient.RFC3339. +type DatetimeHeaderClientRFC3339Response struct { + // placeholder for future response values +} + +// DatetimeHeaderClientRFC7231Response contains the response from method DatetimeHeaderClient.RFC7231. +type DatetimeHeaderClientRFC7231Response struct { + // placeholder for future response values +} + +// DatetimeHeaderClientUnixTimestampArrayResponse contains the response from method DatetimeHeaderClient.UnixTimestampArray. +type DatetimeHeaderClientUnixTimestampArrayResponse struct { + // placeholder for future response values +} + +// DatetimeHeaderClientUnixTimestampResponse contains the response from method DatetimeHeaderClient.UnixTimestamp. +type DatetimeHeaderClientUnixTimestampResponse struct { + // placeholder for future response values +} + +// DatetimePropertyClientDefaultResponse contains the response from method DatetimePropertyClient.Default. +type DatetimePropertyClientDefaultResponse struct { + DefaultDatetimeProperty +} + +// DatetimePropertyClientRFC3339Response contains the response from method DatetimePropertyClient.RFC3339. +type DatetimePropertyClientRFC3339Response struct { + RFC3339DatetimeProperty +} + +// DatetimePropertyClientRFC7231Response contains the response from method DatetimePropertyClient.RFC7231. +type DatetimePropertyClientRFC7231Response struct { + RFC7231DatetimeProperty +} + +// DatetimePropertyClientUnixTimestampArrayResponse contains the response from method DatetimePropertyClient.UnixTimestampArray. +type DatetimePropertyClientUnixTimestampArrayResponse struct { + UnixTimestampArrayDatetimeProperty +} + +// DatetimePropertyClientUnixTimestampResponse contains the response from method DatetimePropertyClient.UnixTimestamp. +type DatetimePropertyClientUnixTimestampResponse struct { + UnixTimestampDatetimeProperty +} + +// DatetimeQueryClientDefaultResponse contains the response from method DatetimeQueryClient.Default. +type DatetimeQueryClientDefaultResponse struct { + // placeholder for future response values +} + +// DatetimeQueryClientRFC3339Response contains the response from method DatetimeQueryClient.RFC3339. +type DatetimeQueryClientRFC3339Response struct { + // placeholder for future response values +} + +// DatetimeQueryClientRFC7231Response contains the response from method DatetimeQueryClient.RFC7231. +type DatetimeQueryClientRFC7231Response struct { + // placeholder for future response values +} + +// DatetimeQueryClientUnixTimestampArrayResponse contains the response from method DatetimeQueryClient.UnixTimestampArray. +type DatetimeQueryClientUnixTimestampArrayResponse struct { + // placeholder for future response values +} + +// DatetimeQueryClientUnixTimestampResponse contains the response from method DatetimeQueryClient.UnixTimestamp. +type DatetimeQueryClientUnixTimestampResponse struct { + // placeholder for future response values +} + +// DatetimeResponseHeaderClientDefaultResponse contains the response from method DatetimeResponseHeaderClient.Default. +type DatetimeResponseHeaderClientDefaultResponse struct { + Value *time.Time +} + +// DatetimeResponseHeaderClientRFC3339Response contains the response from method DatetimeResponseHeaderClient.RFC3339. +type DatetimeResponseHeaderClientRFC3339Response struct { + Value *time.Time +} + +// DatetimeResponseHeaderClientRFC7231Response contains the response from method DatetimeResponseHeaderClient.RFC7231. +type DatetimeResponseHeaderClientRFC7231Response struct { + Value *time.Time +} + +// DatetimeResponseHeaderClientUnixTimestampResponse contains the response from method DatetimeResponseHeaderClient.UnixTimestamp. +type DatetimeResponseHeaderClientUnixTimestampResponse struct { + Value *time.Time +} diff --git a/test/http-specs/encode/datetimegroup/zz_version.go b/test/http-specs/encode/datetimegroup/zz_version.go new file mode 100644 index 000000000000..14ba628ef291 --- /dev/null +++ b/test/http-specs/encode/datetimegroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package datetimegroup + +const ( + moduleName = "datetimegroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/encode/durationgroup/LICENSE.txt b/test/http-specs/encode/durationgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/encode/durationgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/encode/durationgroup/custom_client_test.go b/test/http-specs/encode/durationgroup/custom_client_test.go new file mode 100644 index 000000000000..dc7d511fa369 --- /dev/null +++ b/test/http-specs/encode/durationgroup/custom_client_test.go @@ -0,0 +1,403 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package durationgroup_test + +import ( + "context" + "durationgroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestHeaderClientDefault(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationHeaderClient().Default(context.Background(), "P40D", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestHeaderClientFloat64Milliseconds(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationHeaderClient().Float64Milliseconds(context.Background(), 35625, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestHeaderClientFloat64Seconds(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationHeaderClient().Float64Seconds(context.Background(), 35.625, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestHeaderClientFloatMilliseconds(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationHeaderClient().FloatMilliseconds(context.Background(), 35625, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestHeaderClientFloatMillisecondsLargerUnit(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationHeaderClient().FloatMillisecondsLargerUnit(context.Background(), 210000, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestHeaderClientFloatSeconds(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationHeaderClient().FloatSeconds(context.Background(), 35.625, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestHeaderClientFloatSecondsLargerUnit(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationHeaderClient().FloatSecondsLargerUnit(context.Background(), 150.0, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestHeaderClientInt32Milliseconds(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationHeaderClient().Int32Milliseconds(context.Background(), 36000, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestHeaderClientInt32MillisecondsArray(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationHeaderClient().Int32MillisecondsArray(context.Background(), []int32{36000, 47000}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestHeaderClientInt32MillisecondsLargerUnit(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationHeaderClient().Int32MillisecondsLargerUnit(context.Background(), 180000, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestHeaderClientInt32Seconds(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationHeaderClient().Int32Seconds(context.Background(), 36, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestHeaderClientInt32SecondsLargerUnit(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationHeaderClient().Int32SecondsLargerUnit(context.Background(), 120, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestHeaderClientIso8601(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationHeaderClient().Iso8601(context.Background(), "P40D", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestHeaderClientIso8601Array(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationHeaderClient().Iso8601Array(context.Background(), []string{"P40D", "P50D"}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestPropertyClientDefault(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationPropertyClient().Default(context.Background(), durationgroup.DefaultDurationProperty{ + Value: to.Ptr("P40D"), + }, nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, "P40D", *resp.Value) +} + +func TestPropertyClientFloat64Milliseconds(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationPropertyClient().Float64Milliseconds(context.Background(), durationgroup.Float64MillisecondsDurationProperty{ + Value: to.Ptr(35625.0), + }, nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, float64(35625), *resp.Value) +} + +func TestPropertyClientFloat64Seconds(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationPropertyClient().Float64Seconds(context.Background(), durationgroup.Float64SecondsDurationProperty{ + Value: to.Ptr(35.625), + }, nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, float64(35.625), *resp.Value) +} + +func TestPropertyClientFloatMilliseconds(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationPropertyClient().FloatMilliseconds(context.Background(), durationgroup.FloatMillisecondsDurationProperty{ + Value: to.Ptr[float32](35625), + }, nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, float32(35625), *resp.Value) +} + +func TestPropertyClientFloatMillisecondsArray(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationPropertyClient().FloatMillisecondsArray(context.Background(), durationgroup.FloatMillisecondsDurationArrayProperty{ + Value: []*float32{ + to.Ptr[float32](35625), + to.Ptr[float32](46750), + }, + }, nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, []*float32{ + to.Ptr[float32](35625), + to.Ptr[float32](46750), + }, resp.Value) +} + +func TestPropertyClientFloatMillisecondsLargerUnit(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationPropertyClient().FloatMillisecondsLargerUnit(context.Background(), durationgroup.FloatMillisecondsLargerUnitDurationProperty{ + Value: to.Ptr[float32](210000), + }, nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, float32(210000), *resp.Value) +} + +func TestPropertyClientFloatSeconds(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationPropertyClient().FloatSeconds(context.Background(), durationgroup.FloatSecondsDurationProperty{ + Value: to.Ptr[float32](35.625), + }, nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, float32(35.625), *resp.Value) +} + +func TestPropertyClientFloatSecondsArray(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationPropertyClient().FloatSecondsArray(context.Background(), durationgroup.FloatSecondsDurationArrayProperty{ + Value: []*float32{ + to.Ptr[float32](35.625), + to.Ptr[float32](46.75), + }, + }, nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, []*float32{ + to.Ptr[float32](35.625), + to.Ptr[float32](46.75), + }, resp.Value) +} + +func TestPropertyClientFloatSecondsLargerUnit(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationPropertyClient().FloatSecondsLargerUnit(context.Background(), durationgroup.FloatSecondsLargerUnitDurationProperty{ + Value: to.Ptr[float32](150.0), + }, nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, float32(150.0), *resp.Value) +} + +func TestPropertyClientInt32Milliseconds(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationPropertyClient().Int32Milliseconds(context.Background(), durationgroup.Int32MillisecondsDurationProperty{ + Value: to.Ptr[int32](36000), + }, nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, int32(36000), *resp.Value) +} + +func TestPropertyClientInt32MillisecondsLargerUnit(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationPropertyClient().Int32MillisecondsLargerUnit(context.Background(), durationgroup.Int32MillisecondsLargerUnitDurationProperty{ + Value: to.Ptr[int32](180000), + }, nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, int32(180000), *resp.Value) +} + +func TestPropertyClientInt32Seconds(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationPropertyClient().Int32Seconds(context.Background(), durationgroup.Int32SecondsDurationProperty{ + Value: to.Ptr[int32](36), + }, nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, int32(36), *resp.Value) +} + +func TestPropertyClientInt32SecondsLargerUnit(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationPropertyClient().Int32SecondsLargerUnit(context.Background(), durationgroup.Int32SecondsLargerUnitDurationProperty{ + Value: to.Ptr[int32](120), + }, nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, int32(120), *resp.Value) +} + +func TestPropertyClientIso8601(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationPropertyClient().Iso8601(context.Background(), durationgroup.ISO8601DurationProperty{ + Value: to.Ptr("P40D"), + }, nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, "P40D", *resp.Value) +} + +func TestQueryClientDefault(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationQueryClient().Default(context.Background(), "P40D", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestQueryClientFloat64Milliseconds(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationQueryClient().Float64Milliseconds(context.Background(), 35625, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestQueryClientFloat64Seconds(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationQueryClient().Float64Seconds(context.Background(), 35.625, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestQueryClientFloatMilliseconds(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationQueryClient().FloatMilliseconds(context.Background(), 35625, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestQueryClientFloatMillisecondsLargerUnit(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationQueryClient().FloatMillisecondsLargerUnit(context.Background(), 210000, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestQueryClientFloatSeconds(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationQueryClient().FloatSeconds(context.Background(), 35.625, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestQueryClientFloatSecondsLargerUnit(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationQueryClient().FloatSecondsLargerUnit(context.Background(), 150.0, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestQueryClientInt32Milliseconds(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationQueryClient().Int32Milliseconds(context.Background(), 36000, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestQueryClientInt32MillisecondsArray(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationQueryClient().Int32MillisecondsArray(context.Background(), []int32{36000, 47000}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestQueryClientInt32MillisecondsLargerUnit(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationQueryClient().Int32MillisecondsLargerUnit(context.Background(), 180000, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestQueryClientInt32Seconds(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationQueryClient().Int32Seconds(context.Background(), 36, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestQueryClientInt32SecondsArray(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationQueryClient().Int32SecondsArray(context.Background(), []int32{36, 47}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestQueryClientInt32SecondsLargerUnit(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationQueryClient().Int32SecondsLargerUnit(context.Background(), 120, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestQueryClientIso8601(t *testing.T) { + client, err := durationgroup.NewDurationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDurationQueryClient().Iso8601(context.Background(), "P40D", nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/encode/durationgroup/fake/zz_duration_server.go b/test/http-specs/encode/durationgroup/fake/zz_duration_server.go new file mode 100644 index 000000000000..c1a406da7a23 --- /dev/null +++ b/test/http-specs/encode/durationgroup/fake/zz_duration_server.go @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// DurationServer is a fake server for instances of the durationgroup.DurationClient type. +type DurationServer struct { + // DurationHeaderServer contains the fakes for client DurationHeaderClient + DurationHeaderServer DurationHeaderServer + + // DurationPropertyServer contains the fakes for client DurationPropertyClient + DurationPropertyServer DurationPropertyServer + + // DurationQueryServer contains the fakes for client DurationQueryClient + DurationQueryServer DurationQueryServer +} + +// NewDurationServerTransport creates a new instance of DurationServerTransport with the provided implementation. +// The returned DurationServerTransport instance is connected to an instance of durationgroup.DurationClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDurationServerTransport(srv *DurationServer) *DurationServerTransport { + return &DurationServerTransport{srv: srv} +} + +// DurationServerTransport connects instances of durationgroup.DurationClient to instances of DurationServer. +// Don't use this type directly, use NewDurationServerTransport instead. +type DurationServerTransport struct { + srv *DurationServer + trMu sync.Mutex + trDurationHeaderServer *DurationHeaderServerTransport + trDurationPropertyServer *DurationPropertyServerTransport + trDurationQueryServer *DurationQueryServerTransport +} + +// Do implements the policy.Transporter interface for DurationServerTransport. +func (d *DurationServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (d *DurationServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "DurationHeaderClient": + initServer(&d.trMu, &d.trDurationHeaderServer, func() *DurationHeaderServerTransport { + return NewDurationHeaderServerTransport(&d.srv.DurationHeaderServer) + }) + resp, err = d.trDurationHeaderServer.Do(req) + case "DurationPropertyClient": + initServer(&d.trMu, &d.trDurationPropertyServer, func() *DurationPropertyServerTransport { + return NewDurationPropertyServerTransport(&d.srv.DurationPropertyServer) + }) + resp, err = d.trDurationPropertyServer.Do(req) + case "DurationQueryClient": + initServer(&d.trMu, &d.trDurationQueryServer, func() *DurationQueryServerTransport { + return NewDurationQueryServerTransport(&d.srv.DurationQueryServer) + }) + resp, err = d.trDurationQueryServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to DurationServerTransport +var durationServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/encode/durationgroup/fake/zz_durationheader_server.go b/test/http-specs/encode/durationgroup/fake/zz_durationheader_server.go new file mode 100644 index 000000000000..4986e89612aa --- /dev/null +++ b/test/http-specs/encode/durationgroup/fake/zz_durationheader_server.go @@ -0,0 +1,524 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "durationgroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "strconv" +) + +// DurationHeaderServer is a fake server for instances of the durationgroup.DurationHeaderClient type. +type DurationHeaderServer struct { + // Default is the fake for method DurationHeaderClient.Default + // HTTP status codes to indicate success: http.StatusNoContent + Default func(ctx context.Context, duration string, options *durationgroup.DurationHeaderClientDefaultOptions) (resp azfake.Responder[durationgroup.DurationHeaderClientDefaultResponse], errResp azfake.ErrorResponder) + + // Float64Milliseconds is the fake for method DurationHeaderClient.Float64Milliseconds + // HTTP status codes to indicate success: http.StatusNoContent + Float64Milliseconds func(ctx context.Context, duration float64, options *durationgroup.DurationHeaderClientFloat64MillisecondsOptions) (resp azfake.Responder[durationgroup.DurationHeaderClientFloat64MillisecondsResponse], errResp azfake.ErrorResponder) + + // Float64Seconds is the fake for method DurationHeaderClient.Float64Seconds + // HTTP status codes to indicate success: http.StatusNoContent + Float64Seconds func(ctx context.Context, duration float64, options *durationgroup.DurationHeaderClientFloat64SecondsOptions) (resp azfake.Responder[durationgroup.DurationHeaderClientFloat64SecondsResponse], errResp azfake.ErrorResponder) + + // FloatMilliseconds is the fake for method DurationHeaderClient.FloatMilliseconds + // HTTP status codes to indicate success: http.StatusNoContent + FloatMilliseconds func(ctx context.Context, duration float32, options *durationgroup.DurationHeaderClientFloatMillisecondsOptions) (resp azfake.Responder[durationgroup.DurationHeaderClientFloatMillisecondsResponse], errResp azfake.ErrorResponder) + + // FloatMillisecondsLargerUnit is the fake for method DurationHeaderClient.FloatMillisecondsLargerUnit + // HTTP status codes to indicate success: http.StatusNoContent + FloatMillisecondsLargerUnit func(ctx context.Context, duration float32, options *durationgroup.DurationHeaderClientFloatMillisecondsLargerUnitOptions) (resp azfake.Responder[durationgroup.DurationHeaderClientFloatMillisecondsLargerUnitResponse], errResp azfake.ErrorResponder) + + // FloatSeconds is the fake for method DurationHeaderClient.FloatSeconds + // HTTP status codes to indicate success: http.StatusNoContent + FloatSeconds func(ctx context.Context, duration float32, options *durationgroup.DurationHeaderClientFloatSecondsOptions) (resp azfake.Responder[durationgroup.DurationHeaderClientFloatSecondsResponse], errResp azfake.ErrorResponder) + + // FloatSecondsLargerUnit is the fake for method DurationHeaderClient.FloatSecondsLargerUnit + // HTTP status codes to indicate success: http.StatusNoContent + FloatSecondsLargerUnit func(ctx context.Context, duration float32, options *durationgroup.DurationHeaderClientFloatSecondsLargerUnitOptions) (resp azfake.Responder[durationgroup.DurationHeaderClientFloatSecondsLargerUnitResponse], errResp azfake.ErrorResponder) + + // Int32Milliseconds is the fake for method DurationHeaderClient.Int32Milliseconds + // HTTP status codes to indicate success: http.StatusNoContent + Int32Milliseconds func(ctx context.Context, duration int32, options *durationgroup.DurationHeaderClientInt32MillisecondsOptions) (resp azfake.Responder[durationgroup.DurationHeaderClientInt32MillisecondsResponse], errResp azfake.ErrorResponder) + + // Int32MillisecondsArray is the fake for method DurationHeaderClient.Int32MillisecondsArray + // HTTP status codes to indicate success: http.StatusNoContent + Int32MillisecondsArray func(ctx context.Context, duration []int32, options *durationgroup.DurationHeaderClientInt32MillisecondsArrayOptions) (resp azfake.Responder[durationgroup.DurationHeaderClientInt32MillisecondsArrayResponse], errResp azfake.ErrorResponder) + + // Int32MillisecondsLargerUnit is the fake for method DurationHeaderClient.Int32MillisecondsLargerUnit + // HTTP status codes to indicate success: http.StatusNoContent + Int32MillisecondsLargerUnit func(ctx context.Context, duration int32, options *durationgroup.DurationHeaderClientInt32MillisecondsLargerUnitOptions) (resp azfake.Responder[durationgroup.DurationHeaderClientInt32MillisecondsLargerUnitResponse], errResp azfake.ErrorResponder) + + // Int32Seconds is the fake for method DurationHeaderClient.Int32Seconds + // HTTP status codes to indicate success: http.StatusNoContent + Int32Seconds func(ctx context.Context, duration int32, options *durationgroup.DurationHeaderClientInt32SecondsOptions) (resp azfake.Responder[durationgroup.DurationHeaderClientInt32SecondsResponse], errResp azfake.ErrorResponder) + + // Int32SecondsLargerUnit is the fake for method DurationHeaderClient.Int32SecondsLargerUnit + // HTTP status codes to indicate success: http.StatusNoContent + Int32SecondsLargerUnit func(ctx context.Context, duration int32, options *durationgroup.DurationHeaderClientInt32SecondsLargerUnitOptions) (resp azfake.Responder[durationgroup.DurationHeaderClientInt32SecondsLargerUnitResponse], errResp azfake.ErrorResponder) + + // Iso8601 is the fake for method DurationHeaderClient.Iso8601 + // HTTP status codes to indicate success: http.StatusNoContent + Iso8601 func(ctx context.Context, duration string, options *durationgroup.DurationHeaderClientIso8601Options) (resp azfake.Responder[durationgroup.DurationHeaderClientIso8601Response], errResp azfake.ErrorResponder) + + // Iso8601Array is the fake for method DurationHeaderClient.Iso8601Array + // HTTP status codes to indicate success: http.StatusNoContent + Iso8601Array func(ctx context.Context, duration []string, options *durationgroup.DurationHeaderClientIso8601ArrayOptions) (resp azfake.Responder[durationgroup.DurationHeaderClientIso8601ArrayResponse], errResp azfake.ErrorResponder) +} + +// NewDurationHeaderServerTransport creates a new instance of DurationHeaderServerTransport with the provided implementation. +// The returned DurationHeaderServerTransport instance is connected to an instance of durationgroup.DurationHeaderClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDurationHeaderServerTransport(srv *DurationHeaderServer) *DurationHeaderServerTransport { + return &DurationHeaderServerTransport{srv: srv} +} + +// DurationHeaderServerTransport connects instances of durationgroup.DurationHeaderClient to instances of DurationHeaderServer. +// Don't use this type directly, use NewDurationHeaderServerTransport instead. +type DurationHeaderServerTransport struct { + srv *DurationHeaderServer +} + +// Do implements the policy.Transporter interface for DurationHeaderServerTransport. +func (d *DurationHeaderServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DurationHeaderServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if durationHeaderServerTransportInterceptor != nil { + res.resp, res.err, intercepted = durationHeaderServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DurationHeaderClient.Default": + res.resp, res.err = d.dispatchDefault(req) + case "DurationHeaderClient.Float64Milliseconds": + res.resp, res.err = d.dispatchFloat64Milliseconds(req) + case "DurationHeaderClient.Float64Seconds": + res.resp, res.err = d.dispatchFloat64Seconds(req) + case "DurationHeaderClient.FloatMilliseconds": + res.resp, res.err = d.dispatchFloatMilliseconds(req) + case "DurationHeaderClient.FloatMillisecondsLargerUnit": + res.resp, res.err = d.dispatchFloatMillisecondsLargerUnit(req) + case "DurationHeaderClient.FloatSeconds": + res.resp, res.err = d.dispatchFloatSeconds(req) + case "DurationHeaderClient.FloatSecondsLargerUnit": + res.resp, res.err = d.dispatchFloatSecondsLargerUnit(req) + case "DurationHeaderClient.Int32Milliseconds": + res.resp, res.err = d.dispatchInt32Milliseconds(req) + case "DurationHeaderClient.Int32MillisecondsArray": + res.resp, res.err = d.dispatchInt32MillisecondsArray(req) + case "DurationHeaderClient.Int32MillisecondsLargerUnit": + res.resp, res.err = d.dispatchInt32MillisecondsLargerUnit(req) + case "DurationHeaderClient.Int32Seconds": + res.resp, res.err = d.dispatchInt32Seconds(req) + case "DurationHeaderClient.Int32SecondsLargerUnit": + res.resp, res.err = d.dispatchInt32SecondsLargerUnit(req) + case "DurationHeaderClient.Iso8601": + res.resp, res.err = d.dispatchIso8601(req) + case "DurationHeaderClient.Iso8601Array": + res.resp, res.err = d.dispatchIso8601Array(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DurationHeaderServerTransport) dispatchDefault(req *http.Request) (*http.Response, error) { + if d.srv.Default == nil { + return nil, &nonRetriableError{errors.New("fake for method Default not implemented")} + } + respr, errRespr := d.srv.Default(req.Context(), getHeaderValue(req.Header, "duration"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationHeaderServerTransport) dispatchFloat64Milliseconds(req *http.Request) (*http.Response, error) { + if d.srv.Float64Milliseconds == nil { + return nil, &nonRetriableError{errors.New("fake for method Float64Milliseconds not implemented")} + } + durationParam, err := strconv.ParseFloat(getHeaderValue(req.Header, "duration"), 64) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Float64Milliseconds(req.Context(), durationParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationHeaderServerTransport) dispatchFloat64Seconds(req *http.Request) (*http.Response, error) { + if d.srv.Float64Seconds == nil { + return nil, &nonRetriableError{errors.New("fake for method Float64Seconds not implemented")} + } + durationParam, err := strconv.ParseFloat(getHeaderValue(req.Header, "duration"), 64) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Float64Seconds(req.Context(), durationParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationHeaderServerTransport) dispatchFloatMilliseconds(req *http.Request) (*http.Response, error) { + if d.srv.FloatMilliseconds == nil { + return nil, &nonRetriableError{errors.New("fake for method FloatMilliseconds not implemented")} + } + durationParam, err := parseWithCast(getHeaderValue(req.Header, "duration"), func(v string) (float32, error) { + p, parseErr := strconv.ParseFloat(v, 32) + if parseErr != nil { + return 0, parseErr + } + return float32(p), nil + }) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.FloatMilliseconds(req.Context(), durationParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationHeaderServerTransport) dispatchFloatMillisecondsLargerUnit(req *http.Request) (*http.Response, error) { + if d.srv.FloatMillisecondsLargerUnit == nil { + return nil, &nonRetriableError{errors.New("fake for method FloatMillisecondsLargerUnit not implemented")} + } + durationParam, err := parseWithCast(getHeaderValue(req.Header, "duration"), func(v string) (float32, error) { + p, parseErr := strconv.ParseFloat(v, 32) + if parseErr != nil { + return 0, parseErr + } + return float32(p), nil + }) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.FloatMillisecondsLargerUnit(req.Context(), durationParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationHeaderServerTransport) dispatchFloatSeconds(req *http.Request) (*http.Response, error) { + if d.srv.FloatSeconds == nil { + return nil, &nonRetriableError{errors.New("fake for method FloatSeconds not implemented")} + } + durationParam, err := parseWithCast(getHeaderValue(req.Header, "duration"), func(v string) (float32, error) { + p, parseErr := strconv.ParseFloat(v, 32) + if parseErr != nil { + return 0, parseErr + } + return float32(p), nil + }) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.FloatSeconds(req.Context(), durationParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationHeaderServerTransport) dispatchFloatSecondsLargerUnit(req *http.Request) (*http.Response, error) { + if d.srv.FloatSecondsLargerUnit == nil { + return nil, &nonRetriableError{errors.New("fake for method FloatSecondsLargerUnit not implemented")} + } + durationParam, err := parseWithCast(getHeaderValue(req.Header, "duration"), func(v string) (float32, error) { + p, parseErr := strconv.ParseFloat(v, 32) + if parseErr != nil { + return 0, parseErr + } + return float32(p), nil + }) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.FloatSecondsLargerUnit(req.Context(), durationParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationHeaderServerTransport) dispatchInt32Milliseconds(req *http.Request) (*http.Response, error) { + if d.srv.Int32Milliseconds == nil { + return nil, &nonRetriableError{errors.New("fake for method Int32Milliseconds not implemented")} + } + durationParam, err := parseWithCast(getHeaderValue(req.Header, "duration"), func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Int32Milliseconds(req.Context(), durationParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationHeaderServerTransport) dispatchInt32MillisecondsArray(req *http.Request) (*http.Response, error) { + if d.srv.Int32MillisecondsArray == nil { + return nil, &nonRetriableError{errors.New("fake for method Int32MillisecondsArray not implemented")} + } + durationElements := splitHelper(getHeaderValue(req.Header, "duration"), ",") + durationParam := make([]int32, len(durationElements)) + for i := 0; i < len(durationElements); i++ { + parsedInt32, parseErr := strconv.ParseInt(durationElements[i], 10, 32) + if parseErr != nil { + return nil, parseErr + } + durationParam[i] = int32(parsedInt32) + } + respr, errRespr := d.srv.Int32MillisecondsArray(req.Context(), durationParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationHeaderServerTransport) dispatchInt32MillisecondsLargerUnit(req *http.Request) (*http.Response, error) { + if d.srv.Int32MillisecondsLargerUnit == nil { + return nil, &nonRetriableError{errors.New("fake for method Int32MillisecondsLargerUnit not implemented")} + } + durationParam, err := parseWithCast(getHeaderValue(req.Header, "duration"), func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Int32MillisecondsLargerUnit(req.Context(), durationParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationHeaderServerTransport) dispatchInt32Seconds(req *http.Request) (*http.Response, error) { + if d.srv.Int32Seconds == nil { + return nil, &nonRetriableError{errors.New("fake for method Int32Seconds not implemented")} + } + durationParam, err := parseWithCast(getHeaderValue(req.Header, "duration"), func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Int32Seconds(req.Context(), durationParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationHeaderServerTransport) dispatchInt32SecondsLargerUnit(req *http.Request) (*http.Response, error) { + if d.srv.Int32SecondsLargerUnit == nil { + return nil, &nonRetriableError{errors.New("fake for method Int32SecondsLargerUnit not implemented")} + } + durationParam, err := parseWithCast(getHeaderValue(req.Header, "duration"), func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Int32SecondsLargerUnit(req.Context(), durationParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationHeaderServerTransport) dispatchIso8601(req *http.Request) (*http.Response, error) { + if d.srv.Iso8601 == nil { + return nil, &nonRetriableError{errors.New("fake for method Iso8601 not implemented")} + } + respr, errRespr := d.srv.Iso8601(req.Context(), getHeaderValue(req.Header, "duration"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationHeaderServerTransport) dispatchIso8601Array(req *http.Request) (*http.Response, error) { + if d.srv.Iso8601Array == nil { + return nil, &nonRetriableError{errors.New("fake for method Iso8601Array not implemented")} + } + respr, errRespr := d.srv.Iso8601Array(req.Context(), splitHelper(getHeaderValue(req.Header, "duration"), ","), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DurationHeaderServerTransport +var durationHeaderServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/encode/durationgroup/fake/zz_durationproperty_server.go b/test/http-specs/encode/durationgroup/fake/zz_durationproperty_server.go new file mode 100644 index 000000000000..033591ae9af4 --- /dev/null +++ b/test/http-specs/encode/durationgroup/fake/zz_durationproperty_server.go @@ -0,0 +1,482 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "durationgroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// DurationPropertyServer is a fake server for instances of the durationgroup.DurationPropertyClient type. +type DurationPropertyServer struct { + // Default is the fake for method DurationPropertyClient.Default + // HTTP status codes to indicate success: http.StatusOK + Default func(ctx context.Context, body durationgroup.DefaultDurationProperty, options *durationgroup.DurationPropertyClientDefaultOptions) (resp azfake.Responder[durationgroup.DurationPropertyClientDefaultResponse], errResp azfake.ErrorResponder) + + // Float64Milliseconds is the fake for method DurationPropertyClient.Float64Milliseconds + // HTTP status codes to indicate success: http.StatusOK + Float64Milliseconds func(ctx context.Context, body durationgroup.Float64MillisecondsDurationProperty, options *durationgroup.DurationPropertyClientFloat64MillisecondsOptions) (resp azfake.Responder[durationgroup.DurationPropertyClientFloat64MillisecondsResponse], errResp azfake.ErrorResponder) + + // Float64Seconds is the fake for method DurationPropertyClient.Float64Seconds + // HTTP status codes to indicate success: http.StatusOK + Float64Seconds func(ctx context.Context, body durationgroup.Float64SecondsDurationProperty, options *durationgroup.DurationPropertyClientFloat64SecondsOptions) (resp azfake.Responder[durationgroup.DurationPropertyClientFloat64SecondsResponse], errResp azfake.ErrorResponder) + + // FloatMilliseconds is the fake for method DurationPropertyClient.FloatMilliseconds + // HTTP status codes to indicate success: http.StatusOK + FloatMilliseconds func(ctx context.Context, body durationgroup.FloatMillisecondsDurationProperty, options *durationgroup.DurationPropertyClientFloatMillisecondsOptions) (resp azfake.Responder[durationgroup.DurationPropertyClientFloatMillisecondsResponse], errResp azfake.ErrorResponder) + + // FloatMillisecondsArray is the fake for method DurationPropertyClient.FloatMillisecondsArray + // HTTP status codes to indicate success: http.StatusOK + FloatMillisecondsArray func(ctx context.Context, body durationgroup.FloatMillisecondsDurationArrayProperty, options *durationgroup.DurationPropertyClientFloatMillisecondsArrayOptions) (resp azfake.Responder[durationgroup.DurationPropertyClientFloatMillisecondsArrayResponse], errResp azfake.ErrorResponder) + + // FloatMillisecondsLargerUnit is the fake for method DurationPropertyClient.FloatMillisecondsLargerUnit + // HTTP status codes to indicate success: http.StatusOK + FloatMillisecondsLargerUnit func(ctx context.Context, body durationgroup.FloatMillisecondsLargerUnitDurationProperty, options *durationgroup.DurationPropertyClientFloatMillisecondsLargerUnitOptions) (resp azfake.Responder[durationgroup.DurationPropertyClientFloatMillisecondsLargerUnitResponse], errResp azfake.ErrorResponder) + + // FloatSeconds is the fake for method DurationPropertyClient.FloatSeconds + // HTTP status codes to indicate success: http.StatusOK + FloatSeconds func(ctx context.Context, body durationgroup.FloatSecondsDurationProperty, options *durationgroup.DurationPropertyClientFloatSecondsOptions) (resp azfake.Responder[durationgroup.DurationPropertyClientFloatSecondsResponse], errResp azfake.ErrorResponder) + + // FloatSecondsArray is the fake for method DurationPropertyClient.FloatSecondsArray + // HTTP status codes to indicate success: http.StatusOK + FloatSecondsArray func(ctx context.Context, body durationgroup.FloatSecondsDurationArrayProperty, options *durationgroup.DurationPropertyClientFloatSecondsArrayOptions) (resp azfake.Responder[durationgroup.DurationPropertyClientFloatSecondsArrayResponse], errResp azfake.ErrorResponder) + + // FloatSecondsLargerUnit is the fake for method DurationPropertyClient.FloatSecondsLargerUnit + // HTTP status codes to indicate success: http.StatusOK + FloatSecondsLargerUnit func(ctx context.Context, body durationgroup.FloatSecondsLargerUnitDurationProperty, options *durationgroup.DurationPropertyClientFloatSecondsLargerUnitOptions) (resp azfake.Responder[durationgroup.DurationPropertyClientFloatSecondsLargerUnitResponse], errResp azfake.ErrorResponder) + + // Int32Milliseconds is the fake for method DurationPropertyClient.Int32Milliseconds + // HTTP status codes to indicate success: http.StatusOK + Int32Milliseconds func(ctx context.Context, body durationgroup.Int32MillisecondsDurationProperty, options *durationgroup.DurationPropertyClientInt32MillisecondsOptions) (resp azfake.Responder[durationgroup.DurationPropertyClientInt32MillisecondsResponse], errResp azfake.ErrorResponder) + + // Int32MillisecondsLargerUnit is the fake for method DurationPropertyClient.Int32MillisecondsLargerUnit + // HTTP status codes to indicate success: http.StatusOK + Int32MillisecondsLargerUnit func(ctx context.Context, body durationgroup.Int32MillisecondsLargerUnitDurationProperty, options *durationgroup.DurationPropertyClientInt32MillisecondsLargerUnitOptions) (resp azfake.Responder[durationgroup.DurationPropertyClientInt32MillisecondsLargerUnitResponse], errResp azfake.ErrorResponder) + + // Int32Seconds is the fake for method DurationPropertyClient.Int32Seconds + // HTTP status codes to indicate success: http.StatusOK + Int32Seconds func(ctx context.Context, body durationgroup.Int32SecondsDurationProperty, options *durationgroup.DurationPropertyClientInt32SecondsOptions) (resp azfake.Responder[durationgroup.DurationPropertyClientInt32SecondsResponse], errResp azfake.ErrorResponder) + + // Int32SecondsLargerUnit is the fake for method DurationPropertyClient.Int32SecondsLargerUnit + // HTTP status codes to indicate success: http.StatusOK + Int32SecondsLargerUnit func(ctx context.Context, body durationgroup.Int32SecondsLargerUnitDurationProperty, options *durationgroup.DurationPropertyClientInt32SecondsLargerUnitOptions) (resp azfake.Responder[durationgroup.DurationPropertyClientInt32SecondsLargerUnitResponse], errResp azfake.ErrorResponder) + + // Iso8601 is the fake for method DurationPropertyClient.Iso8601 + // HTTP status codes to indicate success: http.StatusOK + Iso8601 func(ctx context.Context, body durationgroup.ISO8601DurationProperty, options *durationgroup.DurationPropertyClientIso8601Options) (resp azfake.Responder[durationgroup.DurationPropertyClientIso8601Response], errResp azfake.ErrorResponder) +} + +// NewDurationPropertyServerTransport creates a new instance of DurationPropertyServerTransport with the provided implementation. +// The returned DurationPropertyServerTransport instance is connected to an instance of durationgroup.DurationPropertyClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDurationPropertyServerTransport(srv *DurationPropertyServer) *DurationPropertyServerTransport { + return &DurationPropertyServerTransport{srv: srv} +} + +// DurationPropertyServerTransport connects instances of durationgroup.DurationPropertyClient to instances of DurationPropertyServer. +// Don't use this type directly, use NewDurationPropertyServerTransport instead. +type DurationPropertyServerTransport struct { + srv *DurationPropertyServer +} + +// Do implements the policy.Transporter interface for DurationPropertyServerTransport. +func (d *DurationPropertyServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DurationPropertyServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if durationPropertyServerTransportInterceptor != nil { + res.resp, res.err, intercepted = durationPropertyServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DurationPropertyClient.Default": + res.resp, res.err = d.dispatchDefault(req) + case "DurationPropertyClient.Float64Milliseconds": + res.resp, res.err = d.dispatchFloat64Milliseconds(req) + case "DurationPropertyClient.Float64Seconds": + res.resp, res.err = d.dispatchFloat64Seconds(req) + case "DurationPropertyClient.FloatMilliseconds": + res.resp, res.err = d.dispatchFloatMilliseconds(req) + case "DurationPropertyClient.FloatMillisecondsArray": + res.resp, res.err = d.dispatchFloatMillisecondsArray(req) + case "DurationPropertyClient.FloatMillisecondsLargerUnit": + res.resp, res.err = d.dispatchFloatMillisecondsLargerUnit(req) + case "DurationPropertyClient.FloatSeconds": + res.resp, res.err = d.dispatchFloatSeconds(req) + case "DurationPropertyClient.FloatSecondsArray": + res.resp, res.err = d.dispatchFloatSecondsArray(req) + case "DurationPropertyClient.FloatSecondsLargerUnit": + res.resp, res.err = d.dispatchFloatSecondsLargerUnit(req) + case "DurationPropertyClient.Int32Milliseconds": + res.resp, res.err = d.dispatchInt32Milliseconds(req) + case "DurationPropertyClient.Int32MillisecondsLargerUnit": + res.resp, res.err = d.dispatchInt32MillisecondsLargerUnit(req) + case "DurationPropertyClient.Int32Seconds": + res.resp, res.err = d.dispatchInt32Seconds(req) + case "DurationPropertyClient.Int32SecondsLargerUnit": + res.resp, res.err = d.dispatchInt32SecondsLargerUnit(req) + case "DurationPropertyClient.Iso8601": + res.resp, res.err = d.dispatchIso8601(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DurationPropertyServerTransport) dispatchDefault(req *http.Request) (*http.Response, error) { + if d.srv.Default == nil { + return nil, &nonRetriableError{errors.New("fake for method Default not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[durationgroup.DefaultDurationProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Default(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DefaultDurationProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationPropertyServerTransport) dispatchFloat64Milliseconds(req *http.Request) (*http.Response, error) { + if d.srv.Float64Milliseconds == nil { + return nil, &nonRetriableError{errors.New("fake for method Float64Milliseconds not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[durationgroup.Float64MillisecondsDurationProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Float64Milliseconds(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Float64MillisecondsDurationProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationPropertyServerTransport) dispatchFloat64Seconds(req *http.Request) (*http.Response, error) { + if d.srv.Float64Seconds == nil { + return nil, &nonRetriableError{errors.New("fake for method Float64Seconds not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[durationgroup.Float64SecondsDurationProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Float64Seconds(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Float64SecondsDurationProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationPropertyServerTransport) dispatchFloatMilliseconds(req *http.Request) (*http.Response, error) { + if d.srv.FloatMilliseconds == nil { + return nil, &nonRetriableError{errors.New("fake for method FloatMilliseconds not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[durationgroup.FloatMillisecondsDurationProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.FloatMilliseconds(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).FloatMillisecondsDurationProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationPropertyServerTransport) dispatchFloatMillisecondsArray(req *http.Request) (*http.Response, error) { + if d.srv.FloatMillisecondsArray == nil { + return nil, &nonRetriableError{errors.New("fake for method FloatMillisecondsArray not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[durationgroup.FloatMillisecondsDurationArrayProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.FloatMillisecondsArray(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).FloatMillisecondsDurationArrayProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationPropertyServerTransport) dispatchFloatMillisecondsLargerUnit(req *http.Request) (*http.Response, error) { + if d.srv.FloatMillisecondsLargerUnit == nil { + return nil, &nonRetriableError{errors.New("fake for method FloatMillisecondsLargerUnit not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[durationgroup.FloatMillisecondsLargerUnitDurationProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.FloatMillisecondsLargerUnit(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).FloatMillisecondsLargerUnitDurationProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationPropertyServerTransport) dispatchFloatSeconds(req *http.Request) (*http.Response, error) { + if d.srv.FloatSeconds == nil { + return nil, &nonRetriableError{errors.New("fake for method FloatSeconds not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[durationgroup.FloatSecondsDurationProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.FloatSeconds(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).FloatSecondsDurationProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationPropertyServerTransport) dispatchFloatSecondsArray(req *http.Request) (*http.Response, error) { + if d.srv.FloatSecondsArray == nil { + return nil, &nonRetriableError{errors.New("fake for method FloatSecondsArray not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[durationgroup.FloatSecondsDurationArrayProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.FloatSecondsArray(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).FloatSecondsDurationArrayProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationPropertyServerTransport) dispatchFloatSecondsLargerUnit(req *http.Request) (*http.Response, error) { + if d.srv.FloatSecondsLargerUnit == nil { + return nil, &nonRetriableError{errors.New("fake for method FloatSecondsLargerUnit not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[durationgroup.FloatSecondsLargerUnitDurationProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.FloatSecondsLargerUnit(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).FloatSecondsLargerUnitDurationProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationPropertyServerTransport) dispatchInt32Milliseconds(req *http.Request) (*http.Response, error) { + if d.srv.Int32Milliseconds == nil { + return nil, &nonRetriableError{errors.New("fake for method Int32Milliseconds not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[durationgroup.Int32MillisecondsDurationProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Int32Milliseconds(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Int32MillisecondsDurationProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationPropertyServerTransport) dispatchInt32MillisecondsLargerUnit(req *http.Request) (*http.Response, error) { + if d.srv.Int32MillisecondsLargerUnit == nil { + return nil, &nonRetriableError{errors.New("fake for method Int32MillisecondsLargerUnit not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[durationgroup.Int32MillisecondsLargerUnitDurationProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Int32MillisecondsLargerUnit(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Int32MillisecondsLargerUnitDurationProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationPropertyServerTransport) dispatchInt32Seconds(req *http.Request) (*http.Response, error) { + if d.srv.Int32Seconds == nil { + return nil, &nonRetriableError{errors.New("fake for method Int32Seconds not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[durationgroup.Int32SecondsDurationProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Int32Seconds(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Int32SecondsDurationProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationPropertyServerTransport) dispatchInt32SecondsLargerUnit(req *http.Request) (*http.Response, error) { + if d.srv.Int32SecondsLargerUnit == nil { + return nil, &nonRetriableError{errors.New("fake for method Int32SecondsLargerUnit not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[durationgroup.Int32SecondsLargerUnitDurationProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Int32SecondsLargerUnit(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Int32SecondsLargerUnitDurationProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationPropertyServerTransport) dispatchIso8601(req *http.Request) (*http.Response, error) { + if d.srv.Iso8601 == nil { + return nil, &nonRetriableError{errors.New("fake for method Iso8601 not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[durationgroup.ISO8601DurationProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Iso8601(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ISO8601DurationProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DurationPropertyServerTransport +var durationPropertyServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/encode/durationgroup/fake/zz_durationquery_server.go b/test/http-specs/encode/durationgroup/fake/zz_durationquery_server.go new file mode 100644 index 000000000000..b426fe162c29 --- /dev/null +++ b/test/http-specs/encode/durationgroup/fake/zz_durationquery_server.go @@ -0,0 +1,547 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "durationgroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "strconv" +) + +// DurationQueryServer is a fake server for instances of the durationgroup.DurationQueryClient type. +type DurationQueryServer struct { + // Default is the fake for method DurationQueryClient.Default + // HTTP status codes to indicate success: http.StatusNoContent + Default func(ctx context.Context, input string, options *durationgroup.DurationQueryClientDefaultOptions) (resp azfake.Responder[durationgroup.DurationQueryClientDefaultResponse], errResp azfake.ErrorResponder) + + // Float64Milliseconds is the fake for method DurationQueryClient.Float64Milliseconds + // HTTP status codes to indicate success: http.StatusNoContent + Float64Milliseconds func(ctx context.Context, input float64, options *durationgroup.DurationQueryClientFloat64MillisecondsOptions) (resp azfake.Responder[durationgroup.DurationQueryClientFloat64MillisecondsResponse], errResp azfake.ErrorResponder) + + // Float64Seconds is the fake for method DurationQueryClient.Float64Seconds + // HTTP status codes to indicate success: http.StatusNoContent + Float64Seconds func(ctx context.Context, input float64, options *durationgroup.DurationQueryClientFloat64SecondsOptions) (resp azfake.Responder[durationgroup.DurationQueryClientFloat64SecondsResponse], errResp azfake.ErrorResponder) + + // FloatMilliseconds is the fake for method DurationQueryClient.FloatMilliseconds + // HTTP status codes to indicate success: http.StatusNoContent + FloatMilliseconds func(ctx context.Context, input float32, options *durationgroup.DurationQueryClientFloatMillisecondsOptions) (resp azfake.Responder[durationgroup.DurationQueryClientFloatMillisecondsResponse], errResp azfake.ErrorResponder) + + // FloatMillisecondsLargerUnit is the fake for method DurationQueryClient.FloatMillisecondsLargerUnit + // HTTP status codes to indicate success: http.StatusNoContent + FloatMillisecondsLargerUnit func(ctx context.Context, input float32, options *durationgroup.DurationQueryClientFloatMillisecondsLargerUnitOptions) (resp azfake.Responder[durationgroup.DurationQueryClientFloatMillisecondsLargerUnitResponse], errResp azfake.ErrorResponder) + + // FloatSeconds is the fake for method DurationQueryClient.FloatSeconds + // HTTP status codes to indicate success: http.StatusNoContent + FloatSeconds func(ctx context.Context, input float32, options *durationgroup.DurationQueryClientFloatSecondsOptions) (resp azfake.Responder[durationgroup.DurationQueryClientFloatSecondsResponse], errResp azfake.ErrorResponder) + + // FloatSecondsLargerUnit is the fake for method DurationQueryClient.FloatSecondsLargerUnit + // HTTP status codes to indicate success: http.StatusNoContent + FloatSecondsLargerUnit func(ctx context.Context, input float32, options *durationgroup.DurationQueryClientFloatSecondsLargerUnitOptions) (resp azfake.Responder[durationgroup.DurationQueryClientFloatSecondsLargerUnitResponse], errResp azfake.ErrorResponder) + + // Int32Milliseconds is the fake for method DurationQueryClient.Int32Milliseconds + // HTTP status codes to indicate success: http.StatusNoContent + Int32Milliseconds func(ctx context.Context, input int32, options *durationgroup.DurationQueryClientInt32MillisecondsOptions) (resp azfake.Responder[durationgroup.DurationQueryClientInt32MillisecondsResponse], errResp azfake.ErrorResponder) + + // Int32MillisecondsArray is the fake for method DurationQueryClient.Int32MillisecondsArray + // HTTP status codes to indicate success: http.StatusNoContent + Int32MillisecondsArray func(ctx context.Context, input []int32, options *durationgroup.DurationQueryClientInt32MillisecondsArrayOptions) (resp azfake.Responder[durationgroup.DurationQueryClientInt32MillisecondsArrayResponse], errResp azfake.ErrorResponder) + + // Int32MillisecondsLargerUnit is the fake for method DurationQueryClient.Int32MillisecondsLargerUnit + // HTTP status codes to indicate success: http.StatusNoContent + Int32MillisecondsLargerUnit func(ctx context.Context, input int32, options *durationgroup.DurationQueryClientInt32MillisecondsLargerUnitOptions) (resp azfake.Responder[durationgroup.DurationQueryClientInt32MillisecondsLargerUnitResponse], errResp azfake.ErrorResponder) + + // Int32Seconds is the fake for method DurationQueryClient.Int32Seconds + // HTTP status codes to indicate success: http.StatusNoContent + Int32Seconds func(ctx context.Context, input int32, options *durationgroup.DurationQueryClientInt32SecondsOptions) (resp azfake.Responder[durationgroup.DurationQueryClientInt32SecondsResponse], errResp azfake.ErrorResponder) + + // Int32SecondsArray is the fake for method DurationQueryClient.Int32SecondsArray + // HTTP status codes to indicate success: http.StatusNoContent + Int32SecondsArray func(ctx context.Context, input []int32, options *durationgroup.DurationQueryClientInt32SecondsArrayOptions) (resp azfake.Responder[durationgroup.DurationQueryClientInt32SecondsArrayResponse], errResp azfake.ErrorResponder) + + // Int32SecondsLargerUnit is the fake for method DurationQueryClient.Int32SecondsLargerUnit + // HTTP status codes to indicate success: http.StatusNoContent + Int32SecondsLargerUnit func(ctx context.Context, input int32, options *durationgroup.DurationQueryClientInt32SecondsLargerUnitOptions) (resp azfake.Responder[durationgroup.DurationQueryClientInt32SecondsLargerUnitResponse], errResp azfake.ErrorResponder) + + // Iso8601 is the fake for method DurationQueryClient.Iso8601 + // HTTP status codes to indicate success: http.StatusNoContent + Iso8601 func(ctx context.Context, input string, options *durationgroup.DurationQueryClientIso8601Options) (resp azfake.Responder[durationgroup.DurationQueryClientIso8601Response], errResp azfake.ErrorResponder) +} + +// NewDurationQueryServerTransport creates a new instance of DurationQueryServerTransport with the provided implementation. +// The returned DurationQueryServerTransport instance is connected to an instance of durationgroup.DurationQueryClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDurationQueryServerTransport(srv *DurationQueryServer) *DurationQueryServerTransport { + return &DurationQueryServerTransport{srv: srv} +} + +// DurationQueryServerTransport connects instances of durationgroup.DurationQueryClient to instances of DurationQueryServer. +// Don't use this type directly, use NewDurationQueryServerTransport instead. +type DurationQueryServerTransport struct { + srv *DurationQueryServer +} + +// Do implements the policy.Transporter interface for DurationQueryServerTransport. +func (d *DurationQueryServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DurationQueryServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if durationQueryServerTransportInterceptor != nil { + res.resp, res.err, intercepted = durationQueryServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DurationQueryClient.Default": + res.resp, res.err = d.dispatchDefault(req) + case "DurationQueryClient.Float64Milliseconds": + res.resp, res.err = d.dispatchFloat64Milliseconds(req) + case "DurationQueryClient.Float64Seconds": + res.resp, res.err = d.dispatchFloat64Seconds(req) + case "DurationQueryClient.FloatMilliseconds": + res.resp, res.err = d.dispatchFloatMilliseconds(req) + case "DurationQueryClient.FloatMillisecondsLargerUnit": + res.resp, res.err = d.dispatchFloatMillisecondsLargerUnit(req) + case "DurationQueryClient.FloatSeconds": + res.resp, res.err = d.dispatchFloatSeconds(req) + case "DurationQueryClient.FloatSecondsLargerUnit": + res.resp, res.err = d.dispatchFloatSecondsLargerUnit(req) + case "DurationQueryClient.Int32Milliseconds": + res.resp, res.err = d.dispatchInt32Milliseconds(req) + case "DurationQueryClient.Int32MillisecondsArray": + res.resp, res.err = d.dispatchInt32MillisecondsArray(req) + case "DurationQueryClient.Int32MillisecondsLargerUnit": + res.resp, res.err = d.dispatchInt32MillisecondsLargerUnit(req) + case "DurationQueryClient.Int32Seconds": + res.resp, res.err = d.dispatchInt32Seconds(req) + case "DurationQueryClient.Int32SecondsArray": + res.resp, res.err = d.dispatchInt32SecondsArray(req) + case "DurationQueryClient.Int32SecondsLargerUnit": + res.resp, res.err = d.dispatchInt32SecondsLargerUnit(req) + case "DurationQueryClient.Iso8601": + res.resp, res.err = d.dispatchIso8601(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DurationQueryServerTransport) dispatchDefault(req *http.Request) (*http.Response, error) { + if d.srv.Default == nil { + return nil, &nonRetriableError{errors.New("fake for method Default not implemented")} + } + qp := req.URL.Query() + respr, errRespr := d.srv.Default(req.Context(), qp.Get("input"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationQueryServerTransport) dispatchFloat64Milliseconds(req *http.Request) (*http.Response, error) { + if d.srv.Float64Milliseconds == nil { + return nil, &nonRetriableError{errors.New("fake for method Float64Milliseconds not implemented")} + } + qp := req.URL.Query() + inputParam, err := strconv.ParseFloat(qp.Get("input"), 64) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Float64Milliseconds(req.Context(), inputParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationQueryServerTransport) dispatchFloat64Seconds(req *http.Request) (*http.Response, error) { + if d.srv.Float64Seconds == nil { + return nil, &nonRetriableError{errors.New("fake for method Float64Seconds not implemented")} + } + qp := req.URL.Query() + inputParam, err := strconv.ParseFloat(qp.Get("input"), 64) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Float64Seconds(req.Context(), inputParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationQueryServerTransport) dispatchFloatMilliseconds(req *http.Request) (*http.Response, error) { + if d.srv.FloatMilliseconds == nil { + return nil, &nonRetriableError{errors.New("fake for method FloatMilliseconds not implemented")} + } + qp := req.URL.Query() + inputParam, err := parseWithCast(qp.Get("input"), func(v string) (float32, error) { + p, parseErr := strconv.ParseFloat(v, 32) + if parseErr != nil { + return 0, parseErr + } + return float32(p), nil + }) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.FloatMilliseconds(req.Context(), inputParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationQueryServerTransport) dispatchFloatMillisecondsLargerUnit(req *http.Request) (*http.Response, error) { + if d.srv.FloatMillisecondsLargerUnit == nil { + return nil, &nonRetriableError{errors.New("fake for method FloatMillisecondsLargerUnit not implemented")} + } + qp := req.URL.Query() + inputParam, err := parseWithCast(qp.Get("input"), func(v string) (float32, error) { + p, parseErr := strconv.ParseFloat(v, 32) + if parseErr != nil { + return 0, parseErr + } + return float32(p), nil + }) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.FloatMillisecondsLargerUnit(req.Context(), inputParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationQueryServerTransport) dispatchFloatSeconds(req *http.Request) (*http.Response, error) { + if d.srv.FloatSeconds == nil { + return nil, &nonRetriableError{errors.New("fake for method FloatSeconds not implemented")} + } + qp := req.URL.Query() + inputParam, err := parseWithCast(qp.Get("input"), func(v string) (float32, error) { + p, parseErr := strconv.ParseFloat(v, 32) + if parseErr != nil { + return 0, parseErr + } + return float32(p), nil + }) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.FloatSeconds(req.Context(), inputParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationQueryServerTransport) dispatchFloatSecondsLargerUnit(req *http.Request) (*http.Response, error) { + if d.srv.FloatSecondsLargerUnit == nil { + return nil, &nonRetriableError{errors.New("fake for method FloatSecondsLargerUnit not implemented")} + } + qp := req.URL.Query() + inputParam, err := parseWithCast(qp.Get("input"), func(v string) (float32, error) { + p, parseErr := strconv.ParseFloat(v, 32) + if parseErr != nil { + return 0, parseErr + } + return float32(p), nil + }) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.FloatSecondsLargerUnit(req.Context(), inputParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationQueryServerTransport) dispatchInt32Milliseconds(req *http.Request) (*http.Response, error) { + if d.srv.Int32Milliseconds == nil { + return nil, &nonRetriableError{errors.New("fake for method Int32Milliseconds not implemented")} + } + qp := req.URL.Query() + inputParam, err := parseWithCast(qp.Get("input"), func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Int32Milliseconds(req.Context(), inputParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationQueryServerTransport) dispatchInt32MillisecondsArray(req *http.Request) (*http.Response, error) { + if d.srv.Int32MillisecondsArray == nil { + return nil, &nonRetriableError{errors.New("fake for method Int32MillisecondsArray not implemented")} + } + qp := req.URL.Query() + inputElements := splitHelper(qp.Get("input"), ",") + inputParam := make([]int32, len(inputElements)) + for i := 0; i < len(inputElements); i++ { + parsedInt32, parseErr := strconv.ParseInt(inputElements[i], 10, 32) + if parseErr != nil { + return nil, parseErr + } + inputParam[i] = int32(parsedInt32) + } + respr, errRespr := d.srv.Int32MillisecondsArray(req.Context(), inputParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationQueryServerTransport) dispatchInt32MillisecondsLargerUnit(req *http.Request) (*http.Response, error) { + if d.srv.Int32MillisecondsLargerUnit == nil { + return nil, &nonRetriableError{errors.New("fake for method Int32MillisecondsLargerUnit not implemented")} + } + qp := req.URL.Query() + inputParam, err := parseWithCast(qp.Get("input"), func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Int32MillisecondsLargerUnit(req.Context(), inputParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationQueryServerTransport) dispatchInt32Seconds(req *http.Request) (*http.Response, error) { + if d.srv.Int32Seconds == nil { + return nil, &nonRetriableError{errors.New("fake for method Int32Seconds not implemented")} + } + qp := req.URL.Query() + inputParam, err := parseWithCast(qp.Get("input"), func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Int32Seconds(req.Context(), inputParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationQueryServerTransport) dispatchInt32SecondsArray(req *http.Request) (*http.Response, error) { + if d.srv.Int32SecondsArray == nil { + return nil, &nonRetriableError{errors.New("fake for method Int32SecondsArray not implemented")} + } + qp := req.URL.Query() + inputElements := splitHelper(qp.Get("input"), ",") + inputParam := make([]int32, len(inputElements)) + for i := 0; i < len(inputElements); i++ { + parsedInt32, parseErr := strconv.ParseInt(inputElements[i], 10, 32) + if parseErr != nil { + return nil, parseErr + } + inputParam[i] = int32(parsedInt32) + } + respr, errRespr := d.srv.Int32SecondsArray(req.Context(), inputParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationQueryServerTransport) dispatchInt32SecondsLargerUnit(req *http.Request) (*http.Response, error) { + if d.srv.Int32SecondsLargerUnit == nil { + return nil, &nonRetriableError{errors.New("fake for method Int32SecondsLargerUnit not implemented")} + } + qp := req.URL.Query() + inputParam, err := parseWithCast(qp.Get("input"), func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Int32SecondsLargerUnit(req.Context(), inputParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DurationQueryServerTransport) dispatchIso8601(req *http.Request) (*http.Response, error) { + if d.srv.Iso8601 == nil { + return nil, &nonRetriableError{errors.New("fake for method Iso8601 not implemented")} + } + qp := req.URL.Query() + respr, errRespr := d.srv.Iso8601(req.Context(), qp.Get("input"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DurationQueryServerTransport +var durationQueryServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/encode/durationgroup/fake/zz_internal.go b/test/http-specs/encode/durationgroup/fake/zz_internal.go new file mode 100644 index 000000000000..155bc694c069 --- /dev/null +++ b/test/http-specs/encode/durationgroup/fake/zz_internal.go @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "strings" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getHeaderValue(h http.Header, k string) string { + v := h[k] + if len(v) == 0 { + return "" + } + return v[0] +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func parseWithCast[T any](v string, parse func(v string) (T, error)) (T, error) { + t, err := parse(v) + if err != nil { + return *new(T), err + } + return t, err +} + +func splitHelper(s, sep string) []string { + if s == "" { + return nil + } + return strings.Split(s, sep) +} diff --git a/test/http-specs/encode/durationgroup/go.mod b/test/http-specs/encode/durationgroup/go.mod new file mode 100644 index 000000000000..92792f500f88 --- /dev/null +++ b/test/http-specs/encode/durationgroup/go.mod @@ -0,0 +1,17 @@ +module durationgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/encode/durationgroup/go.sum b/test/http-specs/encode/durationgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/encode/durationgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/encode/durationgroup/testdata/_metadata.json b/test/http-specs/encode/durationgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/encode/durationgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/encode/durationgroup/zz_duration_client.go b/test/http-specs/encode/durationgroup/zz_duration_client.go new file mode 100644 index 000000000000..8cd81d5c9eaa --- /dev/null +++ b/test/http-specs/encode/durationgroup/zz_duration_client.go @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package durationgroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// DurationClient - Test for encode decorator on duration. +// Don't use this type directly, use NewDurationClientWithNoCredential() instead. +type DurationClient struct { + internal *azcore.Client + endpoint string +} + +// DurationClientOptions contains the optional values for creating a [DurationClient]. +type DurationClientOptions struct { + azcore.ClientOptions +} + +// NewDurationClientWithNoCredential creates a new instance of DurationClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewDurationClientWithNoCredential(endpoint string, options *DurationClientOptions) (*DurationClient, error) { + if options == nil { + options = &DurationClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &DurationClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewDurationHeaderClient creates a new instance of [DurationHeaderClient]. +func (client *DurationClient) NewDurationHeaderClient() *DurationHeaderClient { + return &DurationHeaderClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewDurationPropertyClient creates a new instance of [DurationPropertyClient]. +func (client *DurationClient) NewDurationPropertyClient() *DurationPropertyClient { + return &DurationPropertyClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewDurationQueryClient creates a new instance of [DurationQueryClient]. +func (client *DurationClient) NewDurationQueryClient() *DurationQueryClient { + return &DurationQueryClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/http-specs/encode/durationgroup/zz_durationheader_client.go b/test/http-specs/encode/durationgroup/zz_durationheader_client.go new file mode 100644 index 000000000000..27f0ee4297fe --- /dev/null +++ b/test/http-specs/encode/durationgroup/zz_durationheader_client.go @@ -0,0 +1,525 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package durationgroup + +import ( + "context" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strconv" + "strings" +) + +// DurationHeaderClient contains the methods for the DurationHeader group. +// Don't use this type directly, use [DurationClient.NewDurationHeaderClient] instead. +type DurationHeaderClient struct { + internal *azcore.Client + endpoint string +} + +// Default - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationHeaderClientDefaultOptions contains the optional parameters for the DurationHeaderClient.Default method. +func (client *DurationHeaderClient) Default(ctx context.Context, duration string, options *DurationHeaderClientDefaultOptions) (DurationHeaderClientDefaultResponse, error) { + var err error + const operationName = "DurationHeaderClient.Default" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.defaultCreateRequest(ctx, duration, options) + if err != nil { + return DurationHeaderClientDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationHeaderClientDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationHeaderClientDefaultResponse{}, err + } + return DurationHeaderClientDefaultResponse{}, nil +} + +// defaultCreateRequest creates the Default request. +func (client *DurationHeaderClient) defaultCreateRequest(ctx context.Context, duration string, _ *DurationHeaderClientDefaultOptions) (*policy.Request, error) { + urlPath := "/encode/duration/header/default" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["duration"] = []string{duration} + return req, nil +} + +// Float64Milliseconds - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationHeaderClientFloat64MillisecondsOptions contains the optional parameters for the DurationHeaderClient.Float64Milliseconds +// method. +func (client *DurationHeaderClient) Float64Milliseconds(ctx context.Context, duration float64, options *DurationHeaderClientFloat64MillisecondsOptions) (DurationHeaderClientFloat64MillisecondsResponse, error) { + var err error + const operationName = "DurationHeaderClient.Float64Milliseconds" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.float64MillisecondsCreateRequest(ctx, duration, options) + if err != nil { + return DurationHeaderClientFloat64MillisecondsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationHeaderClientFloat64MillisecondsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationHeaderClientFloat64MillisecondsResponse{}, err + } + return DurationHeaderClientFloat64MillisecondsResponse{}, nil +} + +// float64MillisecondsCreateRequest creates the Float64Milliseconds request. +func (client *DurationHeaderClient) float64MillisecondsCreateRequest(ctx context.Context, duration float64, _ *DurationHeaderClientFloat64MillisecondsOptions) (*policy.Request, error) { + urlPath := "/encode/duration/header/float64-milliseconds" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["duration"] = []string{strconv.FormatFloat(duration, 'f', -1, 64)} + return req, nil +} + +// Float64Seconds - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationHeaderClientFloat64SecondsOptions contains the optional parameters for the DurationHeaderClient.Float64Seconds +// method. +func (client *DurationHeaderClient) Float64Seconds(ctx context.Context, duration float64, options *DurationHeaderClientFloat64SecondsOptions) (DurationHeaderClientFloat64SecondsResponse, error) { + var err error + const operationName = "DurationHeaderClient.Float64Seconds" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.float64SecondsCreateRequest(ctx, duration, options) + if err != nil { + return DurationHeaderClientFloat64SecondsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationHeaderClientFloat64SecondsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationHeaderClientFloat64SecondsResponse{}, err + } + return DurationHeaderClientFloat64SecondsResponse{}, nil +} + +// float64SecondsCreateRequest creates the Float64Seconds request. +func (client *DurationHeaderClient) float64SecondsCreateRequest(ctx context.Context, duration float64, _ *DurationHeaderClientFloat64SecondsOptions) (*policy.Request, error) { + urlPath := "/encode/duration/header/float64-seconds" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["duration"] = []string{strconv.FormatFloat(duration, 'f', -1, 64)} + return req, nil +} + +// FloatMilliseconds - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationHeaderClientFloatMillisecondsOptions contains the optional parameters for the DurationHeaderClient.FloatMilliseconds +// method. +func (client *DurationHeaderClient) FloatMilliseconds(ctx context.Context, duration float32, options *DurationHeaderClientFloatMillisecondsOptions) (DurationHeaderClientFloatMillisecondsResponse, error) { + var err error + const operationName = "DurationHeaderClient.FloatMilliseconds" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.floatMillisecondsCreateRequest(ctx, duration, options) + if err != nil { + return DurationHeaderClientFloatMillisecondsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationHeaderClientFloatMillisecondsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationHeaderClientFloatMillisecondsResponse{}, err + } + return DurationHeaderClientFloatMillisecondsResponse{}, nil +} + +// floatMillisecondsCreateRequest creates the FloatMilliseconds request. +func (client *DurationHeaderClient) floatMillisecondsCreateRequest(ctx context.Context, duration float32, _ *DurationHeaderClientFloatMillisecondsOptions) (*policy.Request, error) { + urlPath := "/encode/duration/header/float-milliseconds" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["duration"] = []string{strconv.FormatFloat(float64(duration), 'f', -1, 32)} + return req, nil +} + +// FloatMillisecondsLargerUnit - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationHeaderClientFloatMillisecondsLargerUnitOptions contains the optional parameters for the DurationHeaderClient.FloatMillisecondsLargerUnit +// method. +func (client *DurationHeaderClient) FloatMillisecondsLargerUnit(ctx context.Context, duration float32, options *DurationHeaderClientFloatMillisecondsLargerUnitOptions) (DurationHeaderClientFloatMillisecondsLargerUnitResponse, error) { + var err error + const operationName = "DurationHeaderClient.FloatMillisecondsLargerUnit" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.floatMillisecondsLargerUnitCreateRequest(ctx, duration, options) + if err != nil { + return DurationHeaderClientFloatMillisecondsLargerUnitResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationHeaderClientFloatMillisecondsLargerUnitResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationHeaderClientFloatMillisecondsLargerUnitResponse{}, err + } + return DurationHeaderClientFloatMillisecondsLargerUnitResponse{}, nil +} + +// floatMillisecondsLargerUnitCreateRequest creates the FloatMillisecondsLargerUnit request. +func (client *DurationHeaderClient) floatMillisecondsLargerUnitCreateRequest(ctx context.Context, duration float32, _ *DurationHeaderClientFloatMillisecondsLargerUnitOptions) (*policy.Request, error) { + urlPath := "/encode/duration/header/float-milliseconds-larger-unit" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["duration"] = []string{strconv.FormatFloat(float64(duration), 'f', -1, 32)} + return req, nil +} + +// FloatSeconds - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationHeaderClientFloatSecondsOptions contains the optional parameters for the DurationHeaderClient.FloatSeconds +// method. +func (client *DurationHeaderClient) FloatSeconds(ctx context.Context, duration float32, options *DurationHeaderClientFloatSecondsOptions) (DurationHeaderClientFloatSecondsResponse, error) { + var err error + const operationName = "DurationHeaderClient.FloatSeconds" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.floatSecondsCreateRequest(ctx, duration, options) + if err != nil { + return DurationHeaderClientFloatSecondsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationHeaderClientFloatSecondsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationHeaderClientFloatSecondsResponse{}, err + } + return DurationHeaderClientFloatSecondsResponse{}, nil +} + +// floatSecondsCreateRequest creates the FloatSeconds request. +func (client *DurationHeaderClient) floatSecondsCreateRequest(ctx context.Context, duration float32, _ *DurationHeaderClientFloatSecondsOptions) (*policy.Request, error) { + urlPath := "/encode/duration/header/float-seconds" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["duration"] = []string{strconv.FormatFloat(float64(duration), 'f', -1, 32)} + return req, nil +} + +// FloatSecondsLargerUnit - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationHeaderClientFloatSecondsLargerUnitOptions contains the optional parameters for the DurationHeaderClient.FloatSecondsLargerUnit +// method. +func (client *DurationHeaderClient) FloatSecondsLargerUnit(ctx context.Context, duration float32, options *DurationHeaderClientFloatSecondsLargerUnitOptions) (DurationHeaderClientFloatSecondsLargerUnitResponse, error) { + var err error + const operationName = "DurationHeaderClient.FloatSecondsLargerUnit" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.floatSecondsLargerUnitCreateRequest(ctx, duration, options) + if err != nil { + return DurationHeaderClientFloatSecondsLargerUnitResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationHeaderClientFloatSecondsLargerUnitResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationHeaderClientFloatSecondsLargerUnitResponse{}, err + } + return DurationHeaderClientFloatSecondsLargerUnitResponse{}, nil +} + +// floatSecondsLargerUnitCreateRequest creates the FloatSecondsLargerUnit request. +func (client *DurationHeaderClient) floatSecondsLargerUnitCreateRequest(ctx context.Context, duration float32, _ *DurationHeaderClientFloatSecondsLargerUnitOptions) (*policy.Request, error) { + urlPath := "/encode/duration/header/float-seconds-larger-unit" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["duration"] = []string{strconv.FormatFloat(float64(duration), 'f', -1, 32)} + return req, nil +} + +// Int32Milliseconds - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationHeaderClientInt32MillisecondsOptions contains the optional parameters for the DurationHeaderClient.Int32Milliseconds +// method. +func (client *DurationHeaderClient) Int32Milliseconds(ctx context.Context, duration int32, options *DurationHeaderClientInt32MillisecondsOptions) (DurationHeaderClientInt32MillisecondsResponse, error) { + var err error + const operationName = "DurationHeaderClient.Int32Milliseconds" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.int32MillisecondsCreateRequest(ctx, duration, options) + if err != nil { + return DurationHeaderClientInt32MillisecondsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationHeaderClientInt32MillisecondsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationHeaderClientInt32MillisecondsResponse{}, err + } + return DurationHeaderClientInt32MillisecondsResponse{}, nil +} + +// int32MillisecondsCreateRequest creates the Int32Milliseconds request. +func (client *DurationHeaderClient) int32MillisecondsCreateRequest(ctx context.Context, duration int32, _ *DurationHeaderClientInt32MillisecondsOptions) (*policy.Request, error) { + urlPath := "/encode/duration/header/int32-milliseconds" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["duration"] = []string{strconv.FormatInt(int64(duration), 10)} + return req, nil +} + +// Int32MillisecondsArray - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationHeaderClientInt32MillisecondsArrayOptions contains the optional parameters for the DurationHeaderClient.Int32MillisecondsArray +// method. +func (client *DurationHeaderClient) Int32MillisecondsArray(ctx context.Context, duration []int32, options *DurationHeaderClientInt32MillisecondsArrayOptions) (DurationHeaderClientInt32MillisecondsArrayResponse, error) { + var err error + const operationName = "DurationHeaderClient.Int32MillisecondsArray" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.int32MillisecondsArrayCreateRequest(ctx, duration, options) + if err != nil { + return DurationHeaderClientInt32MillisecondsArrayResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationHeaderClientInt32MillisecondsArrayResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationHeaderClientInt32MillisecondsArrayResponse{}, err + } + return DurationHeaderClientInt32MillisecondsArrayResponse{}, nil +} + +// int32MillisecondsArrayCreateRequest creates the Int32MillisecondsArray request. +func (client *DurationHeaderClient) int32MillisecondsArrayCreateRequest(ctx context.Context, duration []int32, _ *DurationHeaderClientInt32MillisecondsArrayOptions) (*policy.Request, error) { + urlPath := "/encode/duration/header/int32-milliseconds-array" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["duration"] = []string{strings.Join(strings.Fields(strings.Trim(fmt.Sprint(duration), "[]")), ",")} + return req, nil +} + +// Int32MillisecondsLargerUnit - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationHeaderClientInt32MillisecondsLargerUnitOptions contains the optional parameters for the DurationHeaderClient.Int32MillisecondsLargerUnit +// method. +func (client *DurationHeaderClient) Int32MillisecondsLargerUnit(ctx context.Context, duration int32, options *DurationHeaderClientInt32MillisecondsLargerUnitOptions) (DurationHeaderClientInt32MillisecondsLargerUnitResponse, error) { + var err error + const operationName = "DurationHeaderClient.Int32MillisecondsLargerUnit" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.int32MillisecondsLargerUnitCreateRequest(ctx, duration, options) + if err != nil { + return DurationHeaderClientInt32MillisecondsLargerUnitResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationHeaderClientInt32MillisecondsLargerUnitResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationHeaderClientInt32MillisecondsLargerUnitResponse{}, err + } + return DurationHeaderClientInt32MillisecondsLargerUnitResponse{}, nil +} + +// int32MillisecondsLargerUnitCreateRequest creates the Int32MillisecondsLargerUnit request. +func (client *DurationHeaderClient) int32MillisecondsLargerUnitCreateRequest(ctx context.Context, duration int32, _ *DurationHeaderClientInt32MillisecondsLargerUnitOptions) (*policy.Request, error) { + urlPath := "/encode/duration/header/int32-milliseconds-larger-unit" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["duration"] = []string{strconv.FormatInt(int64(duration), 10)} + return req, nil +} + +// Int32Seconds - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationHeaderClientInt32SecondsOptions contains the optional parameters for the DurationHeaderClient.Int32Seconds +// method. +func (client *DurationHeaderClient) Int32Seconds(ctx context.Context, duration int32, options *DurationHeaderClientInt32SecondsOptions) (DurationHeaderClientInt32SecondsResponse, error) { + var err error + const operationName = "DurationHeaderClient.Int32Seconds" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.int32SecondsCreateRequest(ctx, duration, options) + if err != nil { + return DurationHeaderClientInt32SecondsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationHeaderClientInt32SecondsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationHeaderClientInt32SecondsResponse{}, err + } + return DurationHeaderClientInt32SecondsResponse{}, nil +} + +// int32SecondsCreateRequest creates the Int32Seconds request. +func (client *DurationHeaderClient) int32SecondsCreateRequest(ctx context.Context, duration int32, _ *DurationHeaderClientInt32SecondsOptions) (*policy.Request, error) { + urlPath := "/encode/duration/header/int32-seconds" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["duration"] = []string{strconv.FormatInt(int64(duration), 10)} + return req, nil +} + +// Int32SecondsLargerUnit - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationHeaderClientInt32SecondsLargerUnitOptions contains the optional parameters for the DurationHeaderClient.Int32SecondsLargerUnit +// method. +func (client *DurationHeaderClient) Int32SecondsLargerUnit(ctx context.Context, duration int32, options *DurationHeaderClientInt32SecondsLargerUnitOptions) (DurationHeaderClientInt32SecondsLargerUnitResponse, error) { + var err error + const operationName = "DurationHeaderClient.Int32SecondsLargerUnit" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.int32SecondsLargerUnitCreateRequest(ctx, duration, options) + if err != nil { + return DurationHeaderClientInt32SecondsLargerUnitResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationHeaderClientInt32SecondsLargerUnitResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationHeaderClientInt32SecondsLargerUnitResponse{}, err + } + return DurationHeaderClientInt32SecondsLargerUnitResponse{}, nil +} + +// int32SecondsLargerUnitCreateRequest creates the Int32SecondsLargerUnit request. +func (client *DurationHeaderClient) int32SecondsLargerUnitCreateRequest(ctx context.Context, duration int32, _ *DurationHeaderClientInt32SecondsLargerUnitOptions) (*policy.Request, error) { + urlPath := "/encode/duration/header/int32-seconds-larger-unit" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["duration"] = []string{strconv.FormatInt(int64(duration), 10)} + return req, nil +} + +// Iso8601 - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationHeaderClientIso8601Options contains the optional parameters for the DurationHeaderClient.Iso8601 method. +func (client *DurationHeaderClient) Iso8601(ctx context.Context, duration string, options *DurationHeaderClientIso8601Options) (DurationHeaderClientIso8601Response, error) { + var err error + const operationName = "DurationHeaderClient.Iso8601" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.iso8601CreateRequest(ctx, duration, options) + if err != nil { + return DurationHeaderClientIso8601Response{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationHeaderClientIso8601Response{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationHeaderClientIso8601Response{}, err + } + return DurationHeaderClientIso8601Response{}, nil +} + +// iso8601CreateRequest creates the Iso8601 request. +func (client *DurationHeaderClient) iso8601CreateRequest(ctx context.Context, duration string, _ *DurationHeaderClientIso8601Options) (*policy.Request, error) { + urlPath := "/encode/duration/header/iso8601" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["duration"] = []string{duration} + return req, nil +} + +// Iso8601Array - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationHeaderClientIso8601ArrayOptions contains the optional parameters for the DurationHeaderClient.Iso8601Array +// method. +func (client *DurationHeaderClient) Iso8601Array(ctx context.Context, duration []string, options *DurationHeaderClientIso8601ArrayOptions) (DurationHeaderClientIso8601ArrayResponse, error) { + var err error + const operationName = "DurationHeaderClient.Iso8601Array" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.iso8601ArrayCreateRequest(ctx, duration, options) + if err != nil { + return DurationHeaderClientIso8601ArrayResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationHeaderClientIso8601ArrayResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationHeaderClientIso8601ArrayResponse{}, err + } + return DurationHeaderClientIso8601ArrayResponse{}, nil +} + +// iso8601ArrayCreateRequest creates the Iso8601Array request. +func (client *DurationHeaderClient) iso8601ArrayCreateRequest(ctx context.Context, duration []string, _ *DurationHeaderClientIso8601ArrayOptions) (*policy.Request, error) { + urlPath := "/encode/duration/header/iso8601-array" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["duration"] = []string{strings.Join(duration, ",")} + return req, nil +} diff --git a/test/http-specs/encode/durationgroup/zz_durationproperty_client.go b/test/http-specs/encode/durationgroup/zz_durationproperty_client.go new file mode 100644 index 000000000000..eeab1434d26e --- /dev/null +++ b/test/http-specs/encode/durationgroup/zz_durationproperty_client.go @@ -0,0 +1,720 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package durationgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// DurationPropertyClient contains the methods for the DurationProperty group. +// Don't use this type directly, use [DurationClient.NewDurationPropertyClient] instead. +type DurationPropertyClient struct { + internal *azcore.Client + endpoint string +} + +// Default - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationPropertyClientDefaultOptions contains the optional parameters for the DurationPropertyClient.Default +// method. +func (client *DurationPropertyClient) Default(ctx context.Context, body DefaultDurationProperty, options *DurationPropertyClientDefaultOptions) (DurationPropertyClientDefaultResponse, error) { + var err error + const operationName = "DurationPropertyClient.Default" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.defaultCreateRequest(ctx, body, options) + if err != nil { + return DurationPropertyClientDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationPropertyClientDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DurationPropertyClientDefaultResponse{}, err + } + resp, err := client.defaultHandleResponse(httpResp) + return resp, err +} + +// defaultCreateRequest creates the Default request. +func (client *DurationPropertyClient) defaultCreateRequest(ctx context.Context, body DefaultDurationProperty, _ *DurationPropertyClientDefaultOptions) (*policy.Request, error) { + urlPath := "/encode/duration/property/default" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// defaultHandleResponse handles the Default response. +func (client *DurationPropertyClient) defaultHandleResponse(resp *http.Response) (DurationPropertyClientDefaultResponse, error) { + result := DurationPropertyClientDefaultResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DefaultDurationProperty); err != nil { + return DurationPropertyClientDefaultResponse{}, err + } + return result, nil +} + +// Float64Milliseconds - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationPropertyClientFloat64MillisecondsOptions contains the optional parameters for the DurationPropertyClient.Float64Milliseconds +// method. +func (client *DurationPropertyClient) Float64Milliseconds(ctx context.Context, body Float64MillisecondsDurationProperty, options *DurationPropertyClientFloat64MillisecondsOptions) (DurationPropertyClientFloat64MillisecondsResponse, error) { + var err error + const operationName = "DurationPropertyClient.Float64Milliseconds" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.float64MillisecondsCreateRequest(ctx, body, options) + if err != nil { + return DurationPropertyClientFloat64MillisecondsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationPropertyClientFloat64MillisecondsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DurationPropertyClientFloat64MillisecondsResponse{}, err + } + resp, err := client.float64MillisecondsHandleResponse(httpResp) + return resp, err +} + +// float64MillisecondsCreateRequest creates the Float64Milliseconds request. +func (client *DurationPropertyClient) float64MillisecondsCreateRequest(ctx context.Context, body Float64MillisecondsDurationProperty, _ *DurationPropertyClientFloat64MillisecondsOptions) (*policy.Request, error) { + urlPath := "/encode/duration/property/float64-milliseconds" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// float64MillisecondsHandleResponse handles the Float64Milliseconds response. +func (client *DurationPropertyClient) float64MillisecondsHandleResponse(resp *http.Response) (DurationPropertyClientFloat64MillisecondsResponse, error) { + result := DurationPropertyClientFloat64MillisecondsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Float64MillisecondsDurationProperty); err != nil { + return DurationPropertyClientFloat64MillisecondsResponse{}, err + } + return result, nil +} + +// Float64Seconds - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationPropertyClientFloat64SecondsOptions contains the optional parameters for the DurationPropertyClient.Float64Seconds +// method. +func (client *DurationPropertyClient) Float64Seconds(ctx context.Context, body Float64SecondsDurationProperty, options *DurationPropertyClientFloat64SecondsOptions) (DurationPropertyClientFloat64SecondsResponse, error) { + var err error + const operationName = "DurationPropertyClient.Float64Seconds" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.float64SecondsCreateRequest(ctx, body, options) + if err != nil { + return DurationPropertyClientFloat64SecondsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationPropertyClientFloat64SecondsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DurationPropertyClientFloat64SecondsResponse{}, err + } + resp, err := client.float64SecondsHandleResponse(httpResp) + return resp, err +} + +// float64SecondsCreateRequest creates the Float64Seconds request. +func (client *DurationPropertyClient) float64SecondsCreateRequest(ctx context.Context, body Float64SecondsDurationProperty, _ *DurationPropertyClientFloat64SecondsOptions) (*policy.Request, error) { + urlPath := "/encode/duration/property/float64-seconds" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// float64SecondsHandleResponse handles the Float64Seconds response. +func (client *DurationPropertyClient) float64SecondsHandleResponse(resp *http.Response) (DurationPropertyClientFloat64SecondsResponse, error) { + result := DurationPropertyClientFloat64SecondsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Float64SecondsDurationProperty); err != nil { + return DurationPropertyClientFloat64SecondsResponse{}, err + } + return result, nil +} + +// FloatMilliseconds - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationPropertyClientFloatMillisecondsOptions contains the optional parameters for the DurationPropertyClient.FloatMilliseconds +// method. +func (client *DurationPropertyClient) FloatMilliseconds(ctx context.Context, body FloatMillisecondsDurationProperty, options *DurationPropertyClientFloatMillisecondsOptions) (DurationPropertyClientFloatMillisecondsResponse, error) { + var err error + const operationName = "DurationPropertyClient.FloatMilliseconds" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.floatMillisecondsCreateRequest(ctx, body, options) + if err != nil { + return DurationPropertyClientFloatMillisecondsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationPropertyClientFloatMillisecondsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DurationPropertyClientFloatMillisecondsResponse{}, err + } + resp, err := client.floatMillisecondsHandleResponse(httpResp) + return resp, err +} + +// floatMillisecondsCreateRequest creates the FloatMilliseconds request. +func (client *DurationPropertyClient) floatMillisecondsCreateRequest(ctx context.Context, body FloatMillisecondsDurationProperty, _ *DurationPropertyClientFloatMillisecondsOptions) (*policy.Request, error) { + urlPath := "/encode/duration/property/float-milliseconds" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// floatMillisecondsHandleResponse handles the FloatMilliseconds response. +func (client *DurationPropertyClient) floatMillisecondsHandleResponse(resp *http.Response) (DurationPropertyClientFloatMillisecondsResponse, error) { + result := DurationPropertyClientFloatMillisecondsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FloatMillisecondsDurationProperty); err != nil { + return DurationPropertyClientFloatMillisecondsResponse{}, err + } + return result, nil +} + +// FloatMillisecondsArray - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationPropertyClientFloatMillisecondsArrayOptions contains the optional parameters for the DurationPropertyClient.FloatMillisecondsArray +// method. +func (client *DurationPropertyClient) FloatMillisecondsArray(ctx context.Context, body FloatMillisecondsDurationArrayProperty, options *DurationPropertyClientFloatMillisecondsArrayOptions) (DurationPropertyClientFloatMillisecondsArrayResponse, error) { + var err error + const operationName = "DurationPropertyClient.FloatMillisecondsArray" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.floatMillisecondsArrayCreateRequest(ctx, body, options) + if err != nil { + return DurationPropertyClientFloatMillisecondsArrayResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationPropertyClientFloatMillisecondsArrayResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DurationPropertyClientFloatMillisecondsArrayResponse{}, err + } + resp, err := client.floatMillisecondsArrayHandleResponse(httpResp) + return resp, err +} + +// floatMillisecondsArrayCreateRequest creates the FloatMillisecondsArray request. +func (client *DurationPropertyClient) floatMillisecondsArrayCreateRequest(ctx context.Context, body FloatMillisecondsDurationArrayProperty, _ *DurationPropertyClientFloatMillisecondsArrayOptions) (*policy.Request, error) { + urlPath := "/encode/duration/property/float-milliseconds-array" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// floatMillisecondsArrayHandleResponse handles the FloatMillisecondsArray response. +func (client *DurationPropertyClient) floatMillisecondsArrayHandleResponse(resp *http.Response) (DurationPropertyClientFloatMillisecondsArrayResponse, error) { + result := DurationPropertyClientFloatMillisecondsArrayResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FloatMillisecondsDurationArrayProperty); err != nil { + return DurationPropertyClientFloatMillisecondsArrayResponse{}, err + } + return result, nil +} + +// FloatMillisecondsLargerUnit - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationPropertyClientFloatMillisecondsLargerUnitOptions contains the optional parameters for the DurationPropertyClient.FloatMillisecondsLargerUnit +// method. +func (client *DurationPropertyClient) FloatMillisecondsLargerUnit(ctx context.Context, body FloatMillisecondsLargerUnitDurationProperty, options *DurationPropertyClientFloatMillisecondsLargerUnitOptions) (DurationPropertyClientFloatMillisecondsLargerUnitResponse, error) { + var err error + const operationName = "DurationPropertyClient.FloatMillisecondsLargerUnit" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.floatMillisecondsLargerUnitCreateRequest(ctx, body, options) + if err != nil { + return DurationPropertyClientFloatMillisecondsLargerUnitResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationPropertyClientFloatMillisecondsLargerUnitResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DurationPropertyClientFloatMillisecondsLargerUnitResponse{}, err + } + resp, err := client.floatMillisecondsLargerUnitHandleResponse(httpResp) + return resp, err +} + +// floatMillisecondsLargerUnitCreateRequest creates the FloatMillisecondsLargerUnit request. +func (client *DurationPropertyClient) floatMillisecondsLargerUnitCreateRequest(ctx context.Context, body FloatMillisecondsLargerUnitDurationProperty, _ *DurationPropertyClientFloatMillisecondsLargerUnitOptions) (*policy.Request, error) { + urlPath := "/encode/duration/property/float-milliseconds-larger-unit" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// floatMillisecondsLargerUnitHandleResponse handles the FloatMillisecondsLargerUnit response. +func (client *DurationPropertyClient) floatMillisecondsLargerUnitHandleResponse(resp *http.Response) (DurationPropertyClientFloatMillisecondsLargerUnitResponse, error) { + result := DurationPropertyClientFloatMillisecondsLargerUnitResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FloatMillisecondsLargerUnitDurationProperty); err != nil { + return DurationPropertyClientFloatMillisecondsLargerUnitResponse{}, err + } + return result, nil +} + +// FloatSeconds - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationPropertyClientFloatSecondsOptions contains the optional parameters for the DurationPropertyClient.FloatSeconds +// method. +func (client *DurationPropertyClient) FloatSeconds(ctx context.Context, body FloatSecondsDurationProperty, options *DurationPropertyClientFloatSecondsOptions) (DurationPropertyClientFloatSecondsResponse, error) { + var err error + const operationName = "DurationPropertyClient.FloatSeconds" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.floatSecondsCreateRequest(ctx, body, options) + if err != nil { + return DurationPropertyClientFloatSecondsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationPropertyClientFloatSecondsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DurationPropertyClientFloatSecondsResponse{}, err + } + resp, err := client.floatSecondsHandleResponse(httpResp) + return resp, err +} + +// floatSecondsCreateRequest creates the FloatSeconds request. +func (client *DurationPropertyClient) floatSecondsCreateRequest(ctx context.Context, body FloatSecondsDurationProperty, _ *DurationPropertyClientFloatSecondsOptions) (*policy.Request, error) { + urlPath := "/encode/duration/property/float-seconds" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// floatSecondsHandleResponse handles the FloatSeconds response. +func (client *DurationPropertyClient) floatSecondsHandleResponse(resp *http.Response) (DurationPropertyClientFloatSecondsResponse, error) { + result := DurationPropertyClientFloatSecondsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FloatSecondsDurationProperty); err != nil { + return DurationPropertyClientFloatSecondsResponse{}, err + } + return result, nil +} + +// FloatSecondsArray - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationPropertyClientFloatSecondsArrayOptions contains the optional parameters for the DurationPropertyClient.FloatSecondsArray +// method. +func (client *DurationPropertyClient) FloatSecondsArray(ctx context.Context, body FloatSecondsDurationArrayProperty, options *DurationPropertyClientFloatSecondsArrayOptions) (DurationPropertyClientFloatSecondsArrayResponse, error) { + var err error + const operationName = "DurationPropertyClient.FloatSecondsArray" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.floatSecondsArrayCreateRequest(ctx, body, options) + if err != nil { + return DurationPropertyClientFloatSecondsArrayResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationPropertyClientFloatSecondsArrayResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DurationPropertyClientFloatSecondsArrayResponse{}, err + } + resp, err := client.floatSecondsArrayHandleResponse(httpResp) + return resp, err +} + +// floatSecondsArrayCreateRequest creates the FloatSecondsArray request. +func (client *DurationPropertyClient) floatSecondsArrayCreateRequest(ctx context.Context, body FloatSecondsDurationArrayProperty, _ *DurationPropertyClientFloatSecondsArrayOptions) (*policy.Request, error) { + urlPath := "/encode/duration/property/float-seconds-array" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// floatSecondsArrayHandleResponse handles the FloatSecondsArray response. +func (client *DurationPropertyClient) floatSecondsArrayHandleResponse(resp *http.Response) (DurationPropertyClientFloatSecondsArrayResponse, error) { + result := DurationPropertyClientFloatSecondsArrayResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FloatSecondsDurationArrayProperty); err != nil { + return DurationPropertyClientFloatSecondsArrayResponse{}, err + } + return result, nil +} + +// FloatSecondsLargerUnit - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationPropertyClientFloatSecondsLargerUnitOptions contains the optional parameters for the DurationPropertyClient.FloatSecondsLargerUnit +// method. +func (client *DurationPropertyClient) FloatSecondsLargerUnit(ctx context.Context, body FloatSecondsLargerUnitDurationProperty, options *DurationPropertyClientFloatSecondsLargerUnitOptions) (DurationPropertyClientFloatSecondsLargerUnitResponse, error) { + var err error + const operationName = "DurationPropertyClient.FloatSecondsLargerUnit" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.floatSecondsLargerUnitCreateRequest(ctx, body, options) + if err != nil { + return DurationPropertyClientFloatSecondsLargerUnitResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationPropertyClientFloatSecondsLargerUnitResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DurationPropertyClientFloatSecondsLargerUnitResponse{}, err + } + resp, err := client.floatSecondsLargerUnitHandleResponse(httpResp) + return resp, err +} + +// floatSecondsLargerUnitCreateRequest creates the FloatSecondsLargerUnit request. +func (client *DurationPropertyClient) floatSecondsLargerUnitCreateRequest(ctx context.Context, body FloatSecondsLargerUnitDurationProperty, _ *DurationPropertyClientFloatSecondsLargerUnitOptions) (*policy.Request, error) { + urlPath := "/encode/duration/property/float-seconds-larger-unit" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// floatSecondsLargerUnitHandleResponse handles the FloatSecondsLargerUnit response. +func (client *DurationPropertyClient) floatSecondsLargerUnitHandleResponse(resp *http.Response) (DurationPropertyClientFloatSecondsLargerUnitResponse, error) { + result := DurationPropertyClientFloatSecondsLargerUnitResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FloatSecondsLargerUnitDurationProperty); err != nil { + return DurationPropertyClientFloatSecondsLargerUnitResponse{}, err + } + return result, nil +} + +// Int32Milliseconds - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationPropertyClientInt32MillisecondsOptions contains the optional parameters for the DurationPropertyClient.Int32Milliseconds +// method. +func (client *DurationPropertyClient) Int32Milliseconds(ctx context.Context, body Int32MillisecondsDurationProperty, options *DurationPropertyClientInt32MillisecondsOptions) (DurationPropertyClientInt32MillisecondsResponse, error) { + var err error + const operationName = "DurationPropertyClient.Int32Milliseconds" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.int32MillisecondsCreateRequest(ctx, body, options) + if err != nil { + return DurationPropertyClientInt32MillisecondsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationPropertyClientInt32MillisecondsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DurationPropertyClientInt32MillisecondsResponse{}, err + } + resp, err := client.int32MillisecondsHandleResponse(httpResp) + return resp, err +} + +// int32MillisecondsCreateRequest creates the Int32Milliseconds request. +func (client *DurationPropertyClient) int32MillisecondsCreateRequest(ctx context.Context, body Int32MillisecondsDurationProperty, _ *DurationPropertyClientInt32MillisecondsOptions) (*policy.Request, error) { + urlPath := "/encode/duration/property/int32-milliseconds" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// int32MillisecondsHandleResponse handles the Int32Milliseconds response. +func (client *DurationPropertyClient) int32MillisecondsHandleResponse(resp *http.Response) (DurationPropertyClientInt32MillisecondsResponse, error) { + result := DurationPropertyClientInt32MillisecondsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Int32MillisecondsDurationProperty); err != nil { + return DurationPropertyClientInt32MillisecondsResponse{}, err + } + return result, nil +} + +// Int32MillisecondsLargerUnit - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationPropertyClientInt32MillisecondsLargerUnitOptions contains the optional parameters for the DurationPropertyClient.Int32MillisecondsLargerUnit +// method. +func (client *DurationPropertyClient) Int32MillisecondsLargerUnit(ctx context.Context, body Int32MillisecondsLargerUnitDurationProperty, options *DurationPropertyClientInt32MillisecondsLargerUnitOptions) (DurationPropertyClientInt32MillisecondsLargerUnitResponse, error) { + var err error + const operationName = "DurationPropertyClient.Int32MillisecondsLargerUnit" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.int32MillisecondsLargerUnitCreateRequest(ctx, body, options) + if err != nil { + return DurationPropertyClientInt32MillisecondsLargerUnitResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationPropertyClientInt32MillisecondsLargerUnitResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DurationPropertyClientInt32MillisecondsLargerUnitResponse{}, err + } + resp, err := client.int32MillisecondsLargerUnitHandleResponse(httpResp) + return resp, err +} + +// int32MillisecondsLargerUnitCreateRequest creates the Int32MillisecondsLargerUnit request. +func (client *DurationPropertyClient) int32MillisecondsLargerUnitCreateRequest(ctx context.Context, body Int32MillisecondsLargerUnitDurationProperty, _ *DurationPropertyClientInt32MillisecondsLargerUnitOptions) (*policy.Request, error) { + urlPath := "/encode/duration/property/int32-milliseconds-larger-unit" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// int32MillisecondsLargerUnitHandleResponse handles the Int32MillisecondsLargerUnit response. +func (client *DurationPropertyClient) int32MillisecondsLargerUnitHandleResponse(resp *http.Response) (DurationPropertyClientInt32MillisecondsLargerUnitResponse, error) { + result := DurationPropertyClientInt32MillisecondsLargerUnitResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Int32MillisecondsLargerUnitDurationProperty); err != nil { + return DurationPropertyClientInt32MillisecondsLargerUnitResponse{}, err + } + return result, nil +} + +// Int32Seconds - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationPropertyClientInt32SecondsOptions contains the optional parameters for the DurationPropertyClient.Int32Seconds +// method. +func (client *DurationPropertyClient) Int32Seconds(ctx context.Context, body Int32SecondsDurationProperty, options *DurationPropertyClientInt32SecondsOptions) (DurationPropertyClientInt32SecondsResponse, error) { + var err error + const operationName = "DurationPropertyClient.Int32Seconds" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.int32SecondsCreateRequest(ctx, body, options) + if err != nil { + return DurationPropertyClientInt32SecondsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationPropertyClientInt32SecondsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DurationPropertyClientInt32SecondsResponse{}, err + } + resp, err := client.int32SecondsHandleResponse(httpResp) + return resp, err +} + +// int32SecondsCreateRequest creates the Int32Seconds request. +func (client *DurationPropertyClient) int32SecondsCreateRequest(ctx context.Context, body Int32SecondsDurationProperty, _ *DurationPropertyClientInt32SecondsOptions) (*policy.Request, error) { + urlPath := "/encode/duration/property/int32-seconds" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// int32SecondsHandleResponse handles the Int32Seconds response. +func (client *DurationPropertyClient) int32SecondsHandleResponse(resp *http.Response) (DurationPropertyClientInt32SecondsResponse, error) { + result := DurationPropertyClientInt32SecondsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Int32SecondsDurationProperty); err != nil { + return DurationPropertyClientInt32SecondsResponse{}, err + } + return result, nil +} + +// Int32SecondsLargerUnit - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationPropertyClientInt32SecondsLargerUnitOptions contains the optional parameters for the DurationPropertyClient.Int32SecondsLargerUnit +// method. +func (client *DurationPropertyClient) Int32SecondsLargerUnit(ctx context.Context, body Int32SecondsLargerUnitDurationProperty, options *DurationPropertyClientInt32SecondsLargerUnitOptions) (DurationPropertyClientInt32SecondsLargerUnitResponse, error) { + var err error + const operationName = "DurationPropertyClient.Int32SecondsLargerUnit" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.int32SecondsLargerUnitCreateRequest(ctx, body, options) + if err != nil { + return DurationPropertyClientInt32SecondsLargerUnitResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationPropertyClientInt32SecondsLargerUnitResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DurationPropertyClientInt32SecondsLargerUnitResponse{}, err + } + resp, err := client.int32SecondsLargerUnitHandleResponse(httpResp) + return resp, err +} + +// int32SecondsLargerUnitCreateRequest creates the Int32SecondsLargerUnit request. +func (client *DurationPropertyClient) int32SecondsLargerUnitCreateRequest(ctx context.Context, body Int32SecondsLargerUnitDurationProperty, _ *DurationPropertyClientInt32SecondsLargerUnitOptions) (*policy.Request, error) { + urlPath := "/encode/duration/property/int32-seconds-larger-unit" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// int32SecondsLargerUnitHandleResponse handles the Int32SecondsLargerUnit response. +func (client *DurationPropertyClient) int32SecondsLargerUnitHandleResponse(resp *http.Response) (DurationPropertyClientInt32SecondsLargerUnitResponse, error) { + result := DurationPropertyClientInt32SecondsLargerUnitResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Int32SecondsLargerUnitDurationProperty); err != nil { + return DurationPropertyClientInt32SecondsLargerUnitResponse{}, err + } + return result, nil +} + +// Iso8601 - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationPropertyClientIso8601Options contains the optional parameters for the DurationPropertyClient.Iso8601 +// method. +func (client *DurationPropertyClient) Iso8601(ctx context.Context, body ISO8601DurationProperty, options *DurationPropertyClientIso8601Options) (DurationPropertyClientIso8601Response, error) { + var err error + const operationName = "DurationPropertyClient.Iso8601" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.iso8601CreateRequest(ctx, body, options) + if err != nil { + return DurationPropertyClientIso8601Response{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationPropertyClientIso8601Response{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DurationPropertyClientIso8601Response{}, err + } + resp, err := client.iso8601HandleResponse(httpResp) + return resp, err +} + +// iso8601CreateRequest creates the Iso8601 request. +func (client *DurationPropertyClient) iso8601CreateRequest(ctx context.Context, body ISO8601DurationProperty, _ *DurationPropertyClientIso8601Options) (*policy.Request, error) { + urlPath := "/encode/duration/property/iso8601" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// iso8601HandleResponse handles the Iso8601 response. +func (client *DurationPropertyClient) iso8601HandleResponse(resp *http.Response) (DurationPropertyClientIso8601Response, error) { + result := DurationPropertyClientIso8601Response{} + if err := runtime.UnmarshalAsJSON(resp, &result.ISO8601DurationProperty); err != nil { + return DurationPropertyClientIso8601Response{}, err + } + return result, nil +} diff --git a/test/http-specs/encode/durationgroup/zz_durationquery_client.go b/test/http-specs/encode/durationgroup/zz_durationquery_client.go new file mode 100644 index 000000000000..d735138a77fa --- /dev/null +++ b/test/http-specs/encode/durationgroup/zz_durationquery_client.go @@ -0,0 +1,553 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package durationgroup + +import ( + "context" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strconv" + "strings" +) + +// DurationQueryClient contains the methods for the DurationQuery group. +// Don't use this type directly, use [DurationClient.NewDurationQueryClient] instead. +type DurationQueryClient struct { + internal *azcore.Client + endpoint string +} + +// Default - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationQueryClientDefaultOptions contains the optional parameters for the DurationQueryClient.Default method. +func (client *DurationQueryClient) Default(ctx context.Context, input string, options *DurationQueryClientDefaultOptions) (DurationQueryClientDefaultResponse, error) { + var err error + const operationName = "DurationQueryClient.Default" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.defaultCreateRequest(ctx, input, options) + if err != nil { + return DurationQueryClientDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationQueryClientDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationQueryClientDefaultResponse{}, err + } + return DurationQueryClientDefaultResponse{}, nil +} + +// defaultCreateRequest creates the Default request. +func (client *DurationQueryClient) defaultCreateRequest(ctx context.Context, input string, _ *DurationQueryClientDefaultOptions) (*policy.Request, error) { + urlPath := "/encode/duration/query/default" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("input", input) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Float64Milliseconds - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationQueryClientFloat64MillisecondsOptions contains the optional parameters for the DurationQueryClient.Float64Milliseconds +// method. +func (client *DurationQueryClient) Float64Milliseconds(ctx context.Context, input float64, options *DurationQueryClientFloat64MillisecondsOptions) (DurationQueryClientFloat64MillisecondsResponse, error) { + var err error + const operationName = "DurationQueryClient.Float64Milliseconds" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.float64MillisecondsCreateRequest(ctx, input, options) + if err != nil { + return DurationQueryClientFloat64MillisecondsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationQueryClientFloat64MillisecondsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationQueryClientFloat64MillisecondsResponse{}, err + } + return DurationQueryClientFloat64MillisecondsResponse{}, nil +} + +// float64MillisecondsCreateRequest creates the Float64Milliseconds request. +func (client *DurationQueryClient) float64MillisecondsCreateRequest(ctx context.Context, input float64, _ *DurationQueryClientFloat64MillisecondsOptions) (*policy.Request, error) { + urlPath := "/encode/duration/query/float64-milliseconds" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("input", strconv.FormatFloat(input, 'f', -1, 64)) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Float64Seconds - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationQueryClientFloat64SecondsOptions contains the optional parameters for the DurationQueryClient.Float64Seconds +// method. +func (client *DurationQueryClient) Float64Seconds(ctx context.Context, input float64, options *DurationQueryClientFloat64SecondsOptions) (DurationQueryClientFloat64SecondsResponse, error) { + var err error + const operationName = "DurationQueryClient.Float64Seconds" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.float64SecondsCreateRequest(ctx, input, options) + if err != nil { + return DurationQueryClientFloat64SecondsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationQueryClientFloat64SecondsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationQueryClientFloat64SecondsResponse{}, err + } + return DurationQueryClientFloat64SecondsResponse{}, nil +} + +// float64SecondsCreateRequest creates the Float64Seconds request. +func (client *DurationQueryClient) float64SecondsCreateRequest(ctx context.Context, input float64, _ *DurationQueryClientFloat64SecondsOptions) (*policy.Request, error) { + urlPath := "/encode/duration/query/float64-seconds" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("input", strconv.FormatFloat(input, 'f', -1, 64)) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// FloatMilliseconds - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationQueryClientFloatMillisecondsOptions contains the optional parameters for the DurationQueryClient.FloatMilliseconds +// method. +func (client *DurationQueryClient) FloatMilliseconds(ctx context.Context, input float32, options *DurationQueryClientFloatMillisecondsOptions) (DurationQueryClientFloatMillisecondsResponse, error) { + var err error + const operationName = "DurationQueryClient.FloatMilliseconds" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.floatMillisecondsCreateRequest(ctx, input, options) + if err != nil { + return DurationQueryClientFloatMillisecondsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationQueryClientFloatMillisecondsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationQueryClientFloatMillisecondsResponse{}, err + } + return DurationQueryClientFloatMillisecondsResponse{}, nil +} + +// floatMillisecondsCreateRequest creates the FloatMilliseconds request. +func (client *DurationQueryClient) floatMillisecondsCreateRequest(ctx context.Context, input float32, _ *DurationQueryClientFloatMillisecondsOptions) (*policy.Request, error) { + urlPath := "/encode/duration/query/float-milliseconds" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("input", strconv.FormatFloat(float64(input), 'f', -1, 32)) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// FloatMillisecondsLargerUnit - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationQueryClientFloatMillisecondsLargerUnitOptions contains the optional parameters for the DurationQueryClient.FloatMillisecondsLargerUnit +// method. +func (client *DurationQueryClient) FloatMillisecondsLargerUnit(ctx context.Context, input float32, options *DurationQueryClientFloatMillisecondsLargerUnitOptions) (DurationQueryClientFloatMillisecondsLargerUnitResponse, error) { + var err error + const operationName = "DurationQueryClient.FloatMillisecondsLargerUnit" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.floatMillisecondsLargerUnitCreateRequest(ctx, input, options) + if err != nil { + return DurationQueryClientFloatMillisecondsLargerUnitResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationQueryClientFloatMillisecondsLargerUnitResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationQueryClientFloatMillisecondsLargerUnitResponse{}, err + } + return DurationQueryClientFloatMillisecondsLargerUnitResponse{}, nil +} + +// floatMillisecondsLargerUnitCreateRequest creates the FloatMillisecondsLargerUnit request. +func (client *DurationQueryClient) floatMillisecondsLargerUnitCreateRequest(ctx context.Context, input float32, _ *DurationQueryClientFloatMillisecondsLargerUnitOptions) (*policy.Request, error) { + urlPath := "/encode/duration/query/float-milliseconds-larger-unit" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("input", strconv.FormatFloat(float64(input), 'f', -1, 32)) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// FloatSeconds - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationQueryClientFloatSecondsOptions contains the optional parameters for the DurationQueryClient.FloatSeconds +// method. +func (client *DurationQueryClient) FloatSeconds(ctx context.Context, input float32, options *DurationQueryClientFloatSecondsOptions) (DurationQueryClientFloatSecondsResponse, error) { + var err error + const operationName = "DurationQueryClient.FloatSeconds" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.floatSecondsCreateRequest(ctx, input, options) + if err != nil { + return DurationQueryClientFloatSecondsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationQueryClientFloatSecondsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationQueryClientFloatSecondsResponse{}, err + } + return DurationQueryClientFloatSecondsResponse{}, nil +} + +// floatSecondsCreateRequest creates the FloatSeconds request. +func (client *DurationQueryClient) floatSecondsCreateRequest(ctx context.Context, input float32, _ *DurationQueryClientFloatSecondsOptions) (*policy.Request, error) { + urlPath := "/encode/duration/query/float-seconds" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("input", strconv.FormatFloat(float64(input), 'f', -1, 32)) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// FloatSecondsLargerUnit - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationQueryClientFloatSecondsLargerUnitOptions contains the optional parameters for the DurationQueryClient.FloatSecondsLargerUnit +// method. +func (client *DurationQueryClient) FloatSecondsLargerUnit(ctx context.Context, input float32, options *DurationQueryClientFloatSecondsLargerUnitOptions) (DurationQueryClientFloatSecondsLargerUnitResponse, error) { + var err error + const operationName = "DurationQueryClient.FloatSecondsLargerUnit" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.floatSecondsLargerUnitCreateRequest(ctx, input, options) + if err != nil { + return DurationQueryClientFloatSecondsLargerUnitResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationQueryClientFloatSecondsLargerUnitResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationQueryClientFloatSecondsLargerUnitResponse{}, err + } + return DurationQueryClientFloatSecondsLargerUnitResponse{}, nil +} + +// floatSecondsLargerUnitCreateRequest creates the FloatSecondsLargerUnit request. +func (client *DurationQueryClient) floatSecondsLargerUnitCreateRequest(ctx context.Context, input float32, _ *DurationQueryClientFloatSecondsLargerUnitOptions) (*policy.Request, error) { + urlPath := "/encode/duration/query/float-seconds-larger-unit" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("input", strconv.FormatFloat(float64(input), 'f', -1, 32)) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Int32Milliseconds - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationQueryClientInt32MillisecondsOptions contains the optional parameters for the DurationQueryClient.Int32Milliseconds +// method. +func (client *DurationQueryClient) Int32Milliseconds(ctx context.Context, input int32, options *DurationQueryClientInt32MillisecondsOptions) (DurationQueryClientInt32MillisecondsResponse, error) { + var err error + const operationName = "DurationQueryClient.Int32Milliseconds" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.int32MillisecondsCreateRequest(ctx, input, options) + if err != nil { + return DurationQueryClientInt32MillisecondsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationQueryClientInt32MillisecondsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationQueryClientInt32MillisecondsResponse{}, err + } + return DurationQueryClientInt32MillisecondsResponse{}, nil +} + +// int32MillisecondsCreateRequest creates the Int32Milliseconds request. +func (client *DurationQueryClient) int32MillisecondsCreateRequest(ctx context.Context, input int32, _ *DurationQueryClientInt32MillisecondsOptions) (*policy.Request, error) { + urlPath := "/encode/duration/query/int32-milliseconds" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("input", strconv.FormatInt(int64(input), 10)) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Int32MillisecondsArray - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationQueryClientInt32MillisecondsArrayOptions contains the optional parameters for the DurationQueryClient.Int32MillisecondsArray +// method. +func (client *DurationQueryClient) Int32MillisecondsArray(ctx context.Context, input []int32, options *DurationQueryClientInt32MillisecondsArrayOptions) (DurationQueryClientInt32MillisecondsArrayResponse, error) { + var err error + const operationName = "DurationQueryClient.Int32MillisecondsArray" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.int32MillisecondsArrayCreateRequest(ctx, input, options) + if err != nil { + return DurationQueryClientInt32MillisecondsArrayResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationQueryClientInt32MillisecondsArrayResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationQueryClientInt32MillisecondsArrayResponse{}, err + } + return DurationQueryClientInt32MillisecondsArrayResponse{}, nil +} + +// int32MillisecondsArrayCreateRequest creates the Int32MillisecondsArray request. +func (client *DurationQueryClient) int32MillisecondsArrayCreateRequest(ctx context.Context, input []int32, _ *DurationQueryClientInt32MillisecondsArrayOptions) (*policy.Request, error) { + urlPath := "/encode/duration/query/int32-milliseconds-array" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("input", strings.Join(strings.Fields(strings.Trim(fmt.Sprint(input), "[]")), ",")) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Int32MillisecondsLargerUnit - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationQueryClientInt32MillisecondsLargerUnitOptions contains the optional parameters for the DurationQueryClient.Int32MillisecondsLargerUnit +// method. +func (client *DurationQueryClient) Int32MillisecondsLargerUnit(ctx context.Context, input int32, options *DurationQueryClientInt32MillisecondsLargerUnitOptions) (DurationQueryClientInt32MillisecondsLargerUnitResponse, error) { + var err error + const operationName = "DurationQueryClient.Int32MillisecondsLargerUnit" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.int32MillisecondsLargerUnitCreateRequest(ctx, input, options) + if err != nil { + return DurationQueryClientInt32MillisecondsLargerUnitResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationQueryClientInt32MillisecondsLargerUnitResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationQueryClientInt32MillisecondsLargerUnitResponse{}, err + } + return DurationQueryClientInt32MillisecondsLargerUnitResponse{}, nil +} + +// int32MillisecondsLargerUnitCreateRequest creates the Int32MillisecondsLargerUnit request. +func (client *DurationQueryClient) int32MillisecondsLargerUnitCreateRequest(ctx context.Context, input int32, _ *DurationQueryClientInt32MillisecondsLargerUnitOptions) (*policy.Request, error) { + urlPath := "/encode/duration/query/int32-milliseconds-larger-unit" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("input", strconv.FormatInt(int64(input), 10)) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Int32Seconds - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationQueryClientInt32SecondsOptions contains the optional parameters for the DurationQueryClient.Int32Seconds +// method. +func (client *DurationQueryClient) Int32Seconds(ctx context.Context, input int32, options *DurationQueryClientInt32SecondsOptions) (DurationQueryClientInt32SecondsResponse, error) { + var err error + const operationName = "DurationQueryClient.Int32Seconds" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.int32SecondsCreateRequest(ctx, input, options) + if err != nil { + return DurationQueryClientInt32SecondsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationQueryClientInt32SecondsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationQueryClientInt32SecondsResponse{}, err + } + return DurationQueryClientInt32SecondsResponse{}, nil +} + +// int32SecondsCreateRequest creates the Int32Seconds request. +func (client *DurationQueryClient) int32SecondsCreateRequest(ctx context.Context, input int32, _ *DurationQueryClientInt32SecondsOptions) (*policy.Request, error) { + urlPath := "/encode/duration/query/int32-seconds" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("input", strconv.FormatInt(int64(input), 10)) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Int32SecondsArray - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationQueryClientInt32SecondsArrayOptions contains the optional parameters for the DurationQueryClient.Int32SecondsArray +// method. +func (client *DurationQueryClient) Int32SecondsArray(ctx context.Context, input []int32, options *DurationQueryClientInt32SecondsArrayOptions) (DurationQueryClientInt32SecondsArrayResponse, error) { + var err error + const operationName = "DurationQueryClient.Int32SecondsArray" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.int32SecondsArrayCreateRequest(ctx, input, options) + if err != nil { + return DurationQueryClientInt32SecondsArrayResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationQueryClientInt32SecondsArrayResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationQueryClientInt32SecondsArrayResponse{}, err + } + return DurationQueryClientInt32SecondsArrayResponse{}, nil +} + +// int32SecondsArrayCreateRequest creates the Int32SecondsArray request. +func (client *DurationQueryClient) int32SecondsArrayCreateRequest(ctx context.Context, input []int32, _ *DurationQueryClientInt32SecondsArrayOptions) (*policy.Request, error) { + urlPath := "/encode/duration/query/int32-seconds-array" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("input", strings.Join(strings.Fields(strings.Trim(fmt.Sprint(input), "[]")), ",")) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Int32SecondsLargerUnit - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationQueryClientInt32SecondsLargerUnitOptions contains the optional parameters for the DurationQueryClient.Int32SecondsLargerUnit +// method. +func (client *DurationQueryClient) Int32SecondsLargerUnit(ctx context.Context, input int32, options *DurationQueryClientInt32SecondsLargerUnitOptions) (DurationQueryClientInt32SecondsLargerUnitResponse, error) { + var err error + const operationName = "DurationQueryClient.Int32SecondsLargerUnit" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.int32SecondsLargerUnitCreateRequest(ctx, input, options) + if err != nil { + return DurationQueryClientInt32SecondsLargerUnitResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationQueryClientInt32SecondsLargerUnitResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationQueryClientInt32SecondsLargerUnitResponse{}, err + } + return DurationQueryClientInt32SecondsLargerUnitResponse{}, nil +} + +// int32SecondsLargerUnitCreateRequest creates the Int32SecondsLargerUnit request. +func (client *DurationQueryClient) int32SecondsLargerUnitCreateRequest(ctx context.Context, input int32, _ *DurationQueryClientInt32SecondsLargerUnitOptions) (*policy.Request, error) { + urlPath := "/encode/duration/query/int32-seconds-larger-unit" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("input", strconv.FormatInt(int64(input), 10)) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Iso8601 - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DurationQueryClientIso8601Options contains the optional parameters for the DurationQueryClient.Iso8601 method. +func (client *DurationQueryClient) Iso8601(ctx context.Context, input string, options *DurationQueryClientIso8601Options) (DurationQueryClientIso8601Response, error) { + var err error + const operationName = "DurationQueryClient.Iso8601" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.iso8601CreateRequest(ctx, input, options) + if err != nil { + return DurationQueryClientIso8601Response{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DurationQueryClientIso8601Response{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DurationQueryClientIso8601Response{}, err + } + return DurationQueryClientIso8601Response{}, nil +} + +// iso8601CreateRequest creates the Iso8601 request. +func (client *DurationQueryClient) iso8601CreateRequest(ctx context.Context, input string, _ *DurationQueryClientIso8601Options) (*policy.Request, error) { + urlPath := "/encode/duration/query/iso8601" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("input", input) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/http-specs/encode/durationgroup/zz_models.go b/test/http-specs/encode/durationgroup/zz_models.go new file mode 100644 index 000000000000..67ae022a42a5 --- /dev/null +++ b/test/http-specs/encode/durationgroup/zz_models.go @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package durationgroup + +type DefaultDurationProperty struct { + // REQUIRED + Value *string +} + +type Float64MillisecondsDurationProperty struct { + // REQUIRED + Value *float64 +} + +type Float64SecondsDurationProperty struct { + // REQUIRED + Value *float64 +} + +type FloatMillisecondsDurationArrayProperty struct { + // REQUIRED + Value []*float32 +} + +type FloatMillisecondsDurationProperty struct { + // REQUIRED + Value *float32 +} + +type FloatMillisecondsLargerUnitDurationProperty struct { + // REQUIRED + Value *float32 +} + +type FloatSecondsDurationArrayProperty struct { + // REQUIRED + Value []*float32 +} + +type FloatSecondsDurationProperty struct { + // REQUIRED + Value *float32 +} + +type FloatSecondsLargerUnitDurationProperty struct { + // REQUIRED + Value *float32 +} + +type ISO8601DurationProperty struct { + // REQUIRED + Value *string +} + +type Int32MillisecondsDurationProperty struct { + // REQUIRED + Value *int32 +} + +type Int32MillisecondsLargerUnitDurationProperty struct { + // REQUIRED + Value *int32 +} + +type Int32SecondsDurationProperty struct { + // REQUIRED + Value *int32 +} + +type Int32SecondsLargerUnitDurationProperty struct { + // REQUIRED + Value *int32 +} diff --git a/test/http-specs/encode/durationgroup/zz_models_serde.go b/test/http-specs/encode/durationgroup/zz_models_serde.go new file mode 100644 index 000000000000..0dd4003577b9 --- /dev/null +++ b/test/http-specs/encode/durationgroup/zz_models_serde.go @@ -0,0 +1,410 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package durationgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type DefaultDurationProperty. +func (d DefaultDurationProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DefaultDurationProperty. +func (d *DefaultDurationProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &d.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Float64MillisecondsDurationProperty. +func (f Float64MillisecondsDurationProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", f.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Float64MillisecondsDurationProperty. +func (f *Float64MillisecondsDurationProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &f.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Float64SecondsDurationProperty. +func (f Float64SecondsDurationProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", f.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Float64SecondsDurationProperty. +func (f *Float64SecondsDurationProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &f.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FloatMillisecondsDurationArrayProperty. +func (f FloatMillisecondsDurationArrayProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", f.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FloatMillisecondsDurationArrayProperty. +func (f *FloatMillisecondsDurationArrayProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &f.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FloatMillisecondsDurationProperty. +func (f FloatMillisecondsDurationProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", f.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FloatMillisecondsDurationProperty. +func (f *FloatMillisecondsDurationProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &f.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FloatMillisecondsLargerUnitDurationProperty. +func (f FloatMillisecondsLargerUnitDurationProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", f.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FloatMillisecondsLargerUnitDurationProperty. +func (f *FloatMillisecondsLargerUnitDurationProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &f.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FloatSecondsDurationArrayProperty. +func (f FloatSecondsDurationArrayProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", f.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FloatSecondsDurationArrayProperty. +func (f *FloatSecondsDurationArrayProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &f.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FloatSecondsDurationProperty. +func (f FloatSecondsDurationProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", f.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FloatSecondsDurationProperty. +func (f *FloatSecondsDurationProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &f.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FloatSecondsLargerUnitDurationProperty. +func (f FloatSecondsLargerUnitDurationProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", f.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FloatSecondsLargerUnitDurationProperty. +func (f *FloatSecondsLargerUnitDurationProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &f.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ISO8601DurationProperty. +func (i ISO8601DurationProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", i.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ISO8601DurationProperty. +func (i *ISO8601DurationProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &i.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Int32MillisecondsDurationProperty. +func (i Int32MillisecondsDurationProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", i.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Int32MillisecondsDurationProperty. +func (i *Int32MillisecondsDurationProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &i.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Int32MillisecondsLargerUnitDurationProperty. +func (i Int32MillisecondsLargerUnitDurationProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", i.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Int32MillisecondsLargerUnitDurationProperty. +func (i *Int32MillisecondsLargerUnitDurationProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &i.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Int32SecondsDurationProperty. +func (i Int32SecondsDurationProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", i.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Int32SecondsDurationProperty. +func (i *Int32SecondsDurationProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &i.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Int32SecondsLargerUnitDurationProperty. +func (i Int32SecondsLargerUnitDurationProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", i.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Int32SecondsLargerUnitDurationProperty. +func (i *Int32SecondsLargerUnitDurationProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &i.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/http-specs/encode/durationgroup/zz_options.go b/test/http-specs/encode/durationgroup/zz_options.go new file mode 100644 index 000000000000..26d4bde9de98 --- /dev/null +++ b/test/http-specs/encode/durationgroup/zz_options.go @@ -0,0 +1,245 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package durationgroup + +// DurationHeaderClientDefaultOptions contains the optional parameters for the DurationHeaderClient.Default method. +type DurationHeaderClientDefaultOptions struct { + // placeholder for future optional parameters +} + +// DurationHeaderClientFloat64MillisecondsOptions contains the optional parameters for the DurationHeaderClient.Float64Milliseconds +// method. +type DurationHeaderClientFloat64MillisecondsOptions struct { + // placeholder for future optional parameters +} + +// DurationHeaderClientFloat64SecondsOptions contains the optional parameters for the DurationHeaderClient.Float64Seconds +// method. +type DurationHeaderClientFloat64SecondsOptions struct { + // placeholder for future optional parameters +} + +// DurationHeaderClientFloatMillisecondsLargerUnitOptions contains the optional parameters for the DurationHeaderClient.FloatMillisecondsLargerUnit +// method. +type DurationHeaderClientFloatMillisecondsLargerUnitOptions struct { + // placeholder for future optional parameters +} + +// DurationHeaderClientFloatMillisecondsOptions contains the optional parameters for the DurationHeaderClient.FloatMilliseconds +// method. +type DurationHeaderClientFloatMillisecondsOptions struct { + // placeholder for future optional parameters +} + +// DurationHeaderClientFloatSecondsLargerUnitOptions contains the optional parameters for the DurationHeaderClient.FloatSecondsLargerUnit +// method. +type DurationHeaderClientFloatSecondsLargerUnitOptions struct { + // placeholder for future optional parameters +} + +// DurationHeaderClientFloatSecondsOptions contains the optional parameters for the DurationHeaderClient.FloatSeconds method. +type DurationHeaderClientFloatSecondsOptions struct { + // placeholder for future optional parameters +} + +// DurationHeaderClientInt32MillisecondsArrayOptions contains the optional parameters for the DurationHeaderClient.Int32MillisecondsArray +// method. +type DurationHeaderClientInt32MillisecondsArrayOptions struct { + // placeholder for future optional parameters +} + +// DurationHeaderClientInt32MillisecondsLargerUnitOptions contains the optional parameters for the DurationHeaderClient.Int32MillisecondsLargerUnit +// method. +type DurationHeaderClientInt32MillisecondsLargerUnitOptions struct { + // placeholder for future optional parameters +} + +// DurationHeaderClientInt32MillisecondsOptions contains the optional parameters for the DurationHeaderClient.Int32Milliseconds +// method. +type DurationHeaderClientInt32MillisecondsOptions struct { + // placeholder for future optional parameters +} + +// DurationHeaderClientInt32SecondsLargerUnitOptions contains the optional parameters for the DurationHeaderClient.Int32SecondsLargerUnit +// method. +type DurationHeaderClientInt32SecondsLargerUnitOptions struct { + // placeholder for future optional parameters +} + +// DurationHeaderClientInt32SecondsOptions contains the optional parameters for the DurationHeaderClient.Int32Seconds method. +type DurationHeaderClientInt32SecondsOptions struct { + // placeholder for future optional parameters +} + +// DurationHeaderClientIso8601ArrayOptions contains the optional parameters for the DurationHeaderClient.Iso8601Array method. +type DurationHeaderClientIso8601ArrayOptions struct { + // placeholder for future optional parameters +} + +// DurationHeaderClientIso8601Options contains the optional parameters for the DurationHeaderClient.Iso8601 method. +type DurationHeaderClientIso8601Options struct { + // placeholder for future optional parameters +} + +// DurationPropertyClientDefaultOptions contains the optional parameters for the DurationPropertyClient.Default method. +type DurationPropertyClientDefaultOptions struct { + // placeholder for future optional parameters +} + +// DurationPropertyClientFloat64MillisecondsOptions contains the optional parameters for the DurationPropertyClient.Float64Milliseconds +// method. +type DurationPropertyClientFloat64MillisecondsOptions struct { + // placeholder for future optional parameters +} + +// DurationPropertyClientFloat64SecondsOptions contains the optional parameters for the DurationPropertyClient.Float64Seconds +// method. +type DurationPropertyClientFloat64SecondsOptions struct { + // placeholder for future optional parameters +} + +// DurationPropertyClientFloatMillisecondsArrayOptions contains the optional parameters for the DurationPropertyClient.FloatMillisecondsArray +// method. +type DurationPropertyClientFloatMillisecondsArrayOptions struct { + // placeholder for future optional parameters +} + +// DurationPropertyClientFloatMillisecondsLargerUnitOptions contains the optional parameters for the DurationPropertyClient.FloatMillisecondsLargerUnit +// method. +type DurationPropertyClientFloatMillisecondsLargerUnitOptions struct { + // placeholder for future optional parameters +} + +// DurationPropertyClientFloatMillisecondsOptions contains the optional parameters for the DurationPropertyClient.FloatMilliseconds +// method. +type DurationPropertyClientFloatMillisecondsOptions struct { + // placeholder for future optional parameters +} + +// DurationPropertyClientFloatSecondsArrayOptions contains the optional parameters for the DurationPropertyClient.FloatSecondsArray +// method. +type DurationPropertyClientFloatSecondsArrayOptions struct { + // placeholder for future optional parameters +} + +// DurationPropertyClientFloatSecondsLargerUnitOptions contains the optional parameters for the DurationPropertyClient.FloatSecondsLargerUnit +// method. +type DurationPropertyClientFloatSecondsLargerUnitOptions struct { + // placeholder for future optional parameters +} + +// DurationPropertyClientFloatSecondsOptions contains the optional parameters for the DurationPropertyClient.FloatSeconds +// method. +type DurationPropertyClientFloatSecondsOptions struct { + // placeholder for future optional parameters +} + +// DurationPropertyClientInt32MillisecondsLargerUnitOptions contains the optional parameters for the DurationPropertyClient.Int32MillisecondsLargerUnit +// method. +type DurationPropertyClientInt32MillisecondsLargerUnitOptions struct { + // placeholder for future optional parameters +} + +// DurationPropertyClientInt32MillisecondsOptions contains the optional parameters for the DurationPropertyClient.Int32Milliseconds +// method. +type DurationPropertyClientInt32MillisecondsOptions struct { + // placeholder for future optional parameters +} + +// DurationPropertyClientInt32SecondsLargerUnitOptions contains the optional parameters for the DurationPropertyClient.Int32SecondsLargerUnit +// method. +type DurationPropertyClientInt32SecondsLargerUnitOptions struct { + // placeholder for future optional parameters +} + +// DurationPropertyClientInt32SecondsOptions contains the optional parameters for the DurationPropertyClient.Int32Seconds +// method. +type DurationPropertyClientInt32SecondsOptions struct { + // placeholder for future optional parameters +} + +// DurationPropertyClientIso8601Options contains the optional parameters for the DurationPropertyClient.Iso8601 method. +type DurationPropertyClientIso8601Options struct { + // placeholder for future optional parameters +} + +// DurationQueryClientDefaultOptions contains the optional parameters for the DurationQueryClient.Default method. +type DurationQueryClientDefaultOptions struct { + // placeholder for future optional parameters +} + +// DurationQueryClientFloat64MillisecondsOptions contains the optional parameters for the DurationQueryClient.Float64Milliseconds +// method. +type DurationQueryClientFloat64MillisecondsOptions struct { + // placeholder for future optional parameters +} + +// DurationQueryClientFloat64SecondsOptions contains the optional parameters for the DurationQueryClient.Float64Seconds method. +type DurationQueryClientFloat64SecondsOptions struct { + // placeholder for future optional parameters +} + +// DurationQueryClientFloatMillisecondsLargerUnitOptions contains the optional parameters for the DurationQueryClient.FloatMillisecondsLargerUnit +// method. +type DurationQueryClientFloatMillisecondsLargerUnitOptions struct { + // placeholder for future optional parameters +} + +// DurationQueryClientFloatMillisecondsOptions contains the optional parameters for the DurationQueryClient.FloatMilliseconds +// method. +type DurationQueryClientFloatMillisecondsOptions struct { + // placeholder for future optional parameters +} + +// DurationQueryClientFloatSecondsLargerUnitOptions contains the optional parameters for the DurationQueryClient.FloatSecondsLargerUnit +// method. +type DurationQueryClientFloatSecondsLargerUnitOptions struct { + // placeholder for future optional parameters +} + +// DurationQueryClientFloatSecondsOptions contains the optional parameters for the DurationQueryClient.FloatSeconds method. +type DurationQueryClientFloatSecondsOptions struct { + // placeholder for future optional parameters +} + +// DurationQueryClientInt32MillisecondsArrayOptions contains the optional parameters for the DurationQueryClient.Int32MillisecondsArray +// method. +type DurationQueryClientInt32MillisecondsArrayOptions struct { + // placeholder for future optional parameters +} + +// DurationQueryClientInt32MillisecondsLargerUnitOptions contains the optional parameters for the DurationQueryClient.Int32MillisecondsLargerUnit +// method. +type DurationQueryClientInt32MillisecondsLargerUnitOptions struct { + // placeholder for future optional parameters +} + +// DurationQueryClientInt32MillisecondsOptions contains the optional parameters for the DurationQueryClient.Int32Milliseconds +// method. +type DurationQueryClientInt32MillisecondsOptions struct { + // placeholder for future optional parameters +} + +// DurationQueryClientInt32SecondsArrayOptions contains the optional parameters for the DurationQueryClient.Int32SecondsArray +// method. +type DurationQueryClientInt32SecondsArrayOptions struct { + // placeholder for future optional parameters +} + +// DurationQueryClientInt32SecondsLargerUnitOptions contains the optional parameters for the DurationQueryClient.Int32SecondsLargerUnit +// method. +type DurationQueryClientInt32SecondsLargerUnitOptions struct { + // placeholder for future optional parameters +} + +// DurationQueryClientInt32SecondsOptions contains the optional parameters for the DurationQueryClient.Int32Seconds method. +type DurationQueryClientInt32SecondsOptions struct { + // placeholder for future optional parameters +} + +// DurationQueryClientIso8601Options contains the optional parameters for the DurationQueryClient.Iso8601 method. +type DurationQueryClientIso8601Options struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/encode/durationgroup/zz_responses.go b/test/http-specs/encode/durationgroup/zz_responses.go new file mode 100644 index 000000000000..79f43acc51ff --- /dev/null +++ b/test/http-specs/encode/durationgroup/zz_responses.go @@ -0,0 +1,215 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package durationgroup + +// DurationHeaderClientDefaultResponse contains the response from method DurationHeaderClient.Default. +type DurationHeaderClientDefaultResponse struct { + // placeholder for future response values +} + +// DurationHeaderClientFloat64MillisecondsResponse contains the response from method DurationHeaderClient.Float64Milliseconds. +type DurationHeaderClientFloat64MillisecondsResponse struct { + // placeholder for future response values +} + +// DurationHeaderClientFloat64SecondsResponse contains the response from method DurationHeaderClient.Float64Seconds. +type DurationHeaderClientFloat64SecondsResponse struct { + // placeholder for future response values +} + +// DurationHeaderClientFloatMillisecondsLargerUnitResponse contains the response from method DurationHeaderClient.FloatMillisecondsLargerUnit. +type DurationHeaderClientFloatMillisecondsLargerUnitResponse struct { + // placeholder for future response values +} + +// DurationHeaderClientFloatMillisecondsResponse contains the response from method DurationHeaderClient.FloatMilliseconds. +type DurationHeaderClientFloatMillisecondsResponse struct { + // placeholder for future response values +} + +// DurationHeaderClientFloatSecondsLargerUnitResponse contains the response from method DurationHeaderClient.FloatSecondsLargerUnit. +type DurationHeaderClientFloatSecondsLargerUnitResponse struct { + // placeholder for future response values +} + +// DurationHeaderClientFloatSecondsResponse contains the response from method DurationHeaderClient.FloatSeconds. +type DurationHeaderClientFloatSecondsResponse struct { + // placeholder for future response values +} + +// DurationHeaderClientInt32MillisecondsArrayResponse contains the response from method DurationHeaderClient.Int32MillisecondsArray. +type DurationHeaderClientInt32MillisecondsArrayResponse struct { + // placeholder for future response values +} + +// DurationHeaderClientInt32MillisecondsLargerUnitResponse contains the response from method DurationHeaderClient.Int32MillisecondsLargerUnit. +type DurationHeaderClientInt32MillisecondsLargerUnitResponse struct { + // placeholder for future response values +} + +// DurationHeaderClientInt32MillisecondsResponse contains the response from method DurationHeaderClient.Int32Milliseconds. +type DurationHeaderClientInt32MillisecondsResponse struct { + // placeholder for future response values +} + +// DurationHeaderClientInt32SecondsLargerUnitResponse contains the response from method DurationHeaderClient.Int32SecondsLargerUnit. +type DurationHeaderClientInt32SecondsLargerUnitResponse struct { + // placeholder for future response values +} + +// DurationHeaderClientInt32SecondsResponse contains the response from method DurationHeaderClient.Int32Seconds. +type DurationHeaderClientInt32SecondsResponse struct { + // placeholder for future response values +} + +// DurationHeaderClientIso8601ArrayResponse contains the response from method DurationHeaderClient.Iso8601Array. +type DurationHeaderClientIso8601ArrayResponse struct { + // placeholder for future response values +} + +// DurationHeaderClientIso8601Response contains the response from method DurationHeaderClient.Iso8601. +type DurationHeaderClientIso8601Response struct { + // placeholder for future response values +} + +// DurationPropertyClientDefaultResponse contains the response from method DurationPropertyClient.Default. +type DurationPropertyClientDefaultResponse struct { + DefaultDurationProperty +} + +// DurationPropertyClientFloat64MillisecondsResponse contains the response from method DurationPropertyClient.Float64Milliseconds. +type DurationPropertyClientFloat64MillisecondsResponse struct { + Float64MillisecondsDurationProperty +} + +// DurationPropertyClientFloat64SecondsResponse contains the response from method DurationPropertyClient.Float64Seconds. +type DurationPropertyClientFloat64SecondsResponse struct { + Float64SecondsDurationProperty +} + +// DurationPropertyClientFloatMillisecondsArrayResponse contains the response from method DurationPropertyClient.FloatMillisecondsArray. +type DurationPropertyClientFloatMillisecondsArrayResponse struct { + FloatMillisecondsDurationArrayProperty +} + +// DurationPropertyClientFloatMillisecondsLargerUnitResponse contains the response from method DurationPropertyClient.FloatMillisecondsLargerUnit. +type DurationPropertyClientFloatMillisecondsLargerUnitResponse struct { + FloatMillisecondsLargerUnitDurationProperty +} + +// DurationPropertyClientFloatMillisecondsResponse contains the response from method DurationPropertyClient.FloatMilliseconds. +type DurationPropertyClientFloatMillisecondsResponse struct { + FloatMillisecondsDurationProperty +} + +// DurationPropertyClientFloatSecondsArrayResponse contains the response from method DurationPropertyClient.FloatSecondsArray. +type DurationPropertyClientFloatSecondsArrayResponse struct { + FloatSecondsDurationArrayProperty +} + +// DurationPropertyClientFloatSecondsLargerUnitResponse contains the response from method DurationPropertyClient.FloatSecondsLargerUnit. +type DurationPropertyClientFloatSecondsLargerUnitResponse struct { + FloatSecondsLargerUnitDurationProperty +} + +// DurationPropertyClientFloatSecondsResponse contains the response from method DurationPropertyClient.FloatSeconds. +type DurationPropertyClientFloatSecondsResponse struct { + FloatSecondsDurationProperty +} + +// DurationPropertyClientInt32MillisecondsLargerUnitResponse contains the response from method DurationPropertyClient.Int32MillisecondsLargerUnit. +type DurationPropertyClientInt32MillisecondsLargerUnitResponse struct { + Int32MillisecondsLargerUnitDurationProperty +} + +// DurationPropertyClientInt32MillisecondsResponse contains the response from method DurationPropertyClient.Int32Milliseconds. +type DurationPropertyClientInt32MillisecondsResponse struct { + Int32MillisecondsDurationProperty +} + +// DurationPropertyClientInt32SecondsLargerUnitResponse contains the response from method DurationPropertyClient.Int32SecondsLargerUnit. +type DurationPropertyClientInt32SecondsLargerUnitResponse struct { + Int32SecondsLargerUnitDurationProperty +} + +// DurationPropertyClientInt32SecondsResponse contains the response from method DurationPropertyClient.Int32Seconds. +type DurationPropertyClientInt32SecondsResponse struct { + Int32SecondsDurationProperty +} + +// DurationPropertyClientIso8601Response contains the response from method DurationPropertyClient.Iso8601. +type DurationPropertyClientIso8601Response struct { + ISO8601DurationProperty +} + +// DurationQueryClientDefaultResponse contains the response from method DurationQueryClient.Default. +type DurationQueryClientDefaultResponse struct { + // placeholder for future response values +} + +// DurationQueryClientFloat64MillisecondsResponse contains the response from method DurationQueryClient.Float64Milliseconds. +type DurationQueryClientFloat64MillisecondsResponse struct { + // placeholder for future response values +} + +// DurationQueryClientFloat64SecondsResponse contains the response from method DurationQueryClient.Float64Seconds. +type DurationQueryClientFloat64SecondsResponse struct { + // placeholder for future response values +} + +// DurationQueryClientFloatMillisecondsLargerUnitResponse contains the response from method DurationQueryClient.FloatMillisecondsLargerUnit. +type DurationQueryClientFloatMillisecondsLargerUnitResponse struct { + // placeholder for future response values +} + +// DurationQueryClientFloatMillisecondsResponse contains the response from method DurationQueryClient.FloatMilliseconds. +type DurationQueryClientFloatMillisecondsResponse struct { + // placeholder for future response values +} + +// DurationQueryClientFloatSecondsLargerUnitResponse contains the response from method DurationQueryClient.FloatSecondsLargerUnit. +type DurationQueryClientFloatSecondsLargerUnitResponse struct { + // placeholder for future response values +} + +// DurationQueryClientFloatSecondsResponse contains the response from method DurationQueryClient.FloatSeconds. +type DurationQueryClientFloatSecondsResponse struct { + // placeholder for future response values +} + +// DurationQueryClientInt32MillisecondsArrayResponse contains the response from method DurationQueryClient.Int32MillisecondsArray. +type DurationQueryClientInt32MillisecondsArrayResponse struct { + // placeholder for future response values +} + +// DurationQueryClientInt32MillisecondsLargerUnitResponse contains the response from method DurationQueryClient.Int32MillisecondsLargerUnit. +type DurationQueryClientInt32MillisecondsLargerUnitResponse struct { + // placeholder for future response values +} + +// DurationQueryClientInt32MillisecondsResponse contains the response from method DurationQueryClient.Int32Milliseconds. +type DurationQueryClientInt32MillisecondsResponse struct { + // placeholder for future response values +} + +// DurationQueryClientInt32SecondsArrayResponse contains the response from method DurationQueryClient.Int32SecondsArray. +type DurationQueryClientInt32SecondsArrayResponse struct { + // placeholder for future response values +} + +// DurationQueryClientInt32SecondsLargerUnitResponse contains the response from method DurationQueryClient.Int32SecondsLargerUnit. +type DurationQueryClientInt32SecondsLargerUnitResponse struct { + // placeholder for future response values +} + +// DurationQueryClientInt32SecondsResponse contains the response from method DurationQueryClient.Int32Seconds. +type DurationQueryClientInt32SecondsResponse struct { + // placeholder for future response values +} + +// DurationQueryClientIso8601Response contains the response from method DurationQueryClient.Iso8601. +type DurationQueryClientIso8601Response struct { + // placeholder for future response values +} diff --git a/test/http-specs/encode/durationgroup/zz_version.go b/test/http-specs/encode/durationgroup/zz_version.go new file mode 100644 index 000000000000..2873098f9aa1 --- /dev/null +++ b/test/http-specs/encode/durationgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package durationgroup + +const ( + moduleName = "durationgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/encode/numericgroup/LICENSE.txt b/test/http-specs/encode/numericgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/encode/numericgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/encode/numericgroup/fake/zz_internal.go b/test/http-specs/encode/numericgroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/http-specs/encode/numericgroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/http-specs/encode/numericgroup/fake/zz_numeric_server.go b/test/http-specs/encode/numericgroup/fake/zz_numeric_server.go new file mode 100644 index 000000000000..06eda9f5844c --- /dev/null +++ b/test/http-specs/encode/numericgroup/fake/zz_numeric_server.go @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// NumericServer is a fake server for instances of the numericgroup.NumericClient type. +type NumericServer struct { + // NumericPropertyServer contains the fakes for client NumericPropertyClient + NumericPropertyServer NumericPropertyServer +} + +// NewNumericServerTransport creates a new instance of NumericServerTransport with the provided implementation. +// The returned NumericServerTransport instance is connected to an instance of numericgroup.NumericClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewNumericServerTransport(srv *NumericServer) *NumericServerTransport { + return &NumericServerTransport{srv: srv} +} + +// NumericServerTransport connects instances of numericgroup.NumericClient to instances of NumericServer. +// Don't use this type directly, use NewNumericServerTransport instead. +type NumericServerTransport struct { + srv *NumericServer + trMu sync.Mutex + trNumericPropertyServer *NumericPropertyServerTransport +} + +// Do implements the policy.Transporter interface for NumericServerTransport. +func (n *NumericServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return n.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (n *NumericServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "NumericPropertyClient": + initServer(&n.trMu, &n.trNumericPropertyServer, func() *NumericPropertyServerTransport { + return NewNumericPropertyServerTransport(&n.srv.NumericPropertyServer) + }) + resp, err = n.trNumericPropertyServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to NumericServerTransport +var numericServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/encode/numericgroup/fake/zz_numericproperty_server.go b/test/http-specs/encode/numericgroup/fake/zz_numericproperty_server.go new file mode 100644 index 000000000000..8720417d382b --- /dev/null +++ b/test/http-specs/encode/numericgroup/fake/zz_numericproperty_server.go @@ -0,0 +1,163 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "numericgroup" + "slices" +) + +// NumericPropertyServer is a fake server for instances of the numericgroup.NumericPropertyClient type. +type NumericPropertyServer struct { + // SafeintAsString is the fake for method NumericPropertyClient.SafeintAsString + // HTTP status codes to indicate success: http.StatusOK + SafeintAsString func(ctx context.Context, value numericgroup.SafeintAsStringProperty, options *numericgroup.NumericPropertyClientSafeintAsStringOptions) (resp azfake.Responder[numericgroup.NumericPropertyClientSafeintAsStringResponse], errResp azfake.ErrorResponder) + + // Uint32AsStringOptional is the fake for method NumericPropertyClient.Uint32AsStringOptional + // HTTP status codes to indicate success: http.StatusOK + Uint32AsStringOptional func(ctx context.Context, value numericgroup.Uint32AsStringProperty, options *numericgroup.NumericPropertyClientUint32AsStringOptionalOptions) (resp azfake.Responder[numericgroup.NumericPropertyClientUint32AsStringOptionalResponse], errResp azfake.ErrorResponder) + + // Uint8AsString is the fake for method NumericPropertyClient.Uint8AsString + // HTTP status codes to indicate success: http.StatusOK + Uint8AsString func(ctx context.Context, value numericgroup.Uint8AsStringProperty, options *numericgroup.NumericPropertyClientUint8AsStringOptions) (resp azfake.Responder[numericgroup.NumericPropertyClientUint8AsStringResponse], errResp azfake.ErrorResponder) +} + +// NewNumericPropertyServerTransport creates a new instance of NumericPropertyServerTransport with the provided implementation. +// The returned NumericPropertyServerTransport instance is connected to an instance of numericgroup.NumericPropertyClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewNumericPropertyServerTransport(srv *NumericPropertyServer) *NumericPropertyServerTransport { + return &NumericPropertyServerTransport{srv: srv} +} + +// NumericPropertyServerTransport connects instances of numericgroup.NumericPropertyClient to instances of NumericPropertyServer. +// Don't use this type directly, use NewNumericPropertyServerTransport instead. +type NumericPropertyServerTransport struct { + srv *NumericPropertyServer +} + +// Do implements the policy.Transporter interface for NumericPropertyServerTransport. +func (n *NumericPropertyServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return n.dispatchToMethodFake(req, method) +} + +func (n *NumericPropertyServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if numericPropertyServerTransportInterceptor != nil { + res.resp, res.err, intercepted = numericPropertyServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "NumericPropertyClient.SafeintAsString": + res.resp, res.err = n.dispatchSafeintAsString(req) + case "NumericPropertyClient.Uint32AsStringOptional": + res.resp, res.err = n.dispatchUint32AsStringOptional(req) + case "NumericPropertyClient.Uint8AsString": + res.resp, res.err = n.dispatchUint8AsString(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (n *NumericPropertyServerTransport) dispatchSafeintAsString(req *http.Request) (*http.Response, error) { + if n.srv.SafeintAsString == nil { + return nil, &nonRetriableError{errors.New("fake for method SafeintAsString not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[numericgroup.SafeintAsStringProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.SafeintAsString(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).SafeintAsStringProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NumericPropertyServerTransport) dispatchUint32AsStringOptional(req *http.Request) (*http.Response, error) { + if n.srv.Uint32AsStringOptional == nil { + return nil, &nonRetriableError{errors.New("fake for method Uint32AsStringOptional not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[numericgroup.Uint32AsStringProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.Uint32AsStringOptional(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Uint32AsStringProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NumericPropertyServerTransport) dispatchUint8AsString(req *http.Request) (*http.Response, error) { + if n.srv.Uint8AsString == nil { + return nil, &nonRetriableError{errors.New("fake for method Uint8AsString not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[numericgroup.Uint8AsStringProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.Uint8AsString(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Uint8AsStringProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to NumericPropertyServerTransport +var numericPropertyServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/encode/numericgroup/go.mod b/test/http-specs/encode/numericgroup/go.mod new file mode 100644 index 000000000000..8556a25eb6d2 --- /dev/null +++ b/test/http-specs/encode/numericgroup/go.mod @@ -0,0 +1,17 @@ +module numericgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/encode/numericgroup/go.sum b/test/http-specs/encode/numericgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/encode/numericgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/encode/numericgroup/numericproperty_client_test.go b/test/http-specs/encode/numericgroup/numericproperty_client_test.go new file mode 100644 index 000000000000..00f8c81441ea --- /dev/null +++ b/test/http-specs/encode/numericgroup/numericproperty_client_test.go @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package numericgroup_test + +import ( + "context" + "numericgroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestNumericPropertyClient_SafeintAsString(t *testing.T) { + client, err := numericgroup.NewNumericClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNumericPropertyClient().SafeintAsString(context.Background(), numericgroup.SafeintAsStringProperty{Value: to.Ptr(int64(10000000000))}, nil) + require.NoError(t, err) + require.Equal(t, numericgroup.SafeintAsStringProperty{ + Value: to.Ptr(int64(10000000000)), + }, resp.SafeintAsStringProperty) +} + +func TestNumericPropertyClient_Uint32AsStringOptional(t *testing.T) { + client, err := numericgroup.NewNumericClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNumericPropertyClient().Uint32AsStringOptional(context.Background(), numericgroup.Uint32AsStringProperty{Value: to.Ptr(uint32(1))}, nil) + require.NoError(t, err) + require.Equal(t, numericgroup.Uint32AsStringProperty{ + Value: to.Ptr(uint32(1)), + }, resp.Uint32AsStringProperty) +} + +func TestNumericPropertyClient_Uint8AsString(t *testing.T) { + client, err := numericgroup.NewNumericClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNumericPropertyClient().Uint8AsString(context.Background(), numericgroup.Uint8AsStringProperty{Value: to.Ptr(uint8(255))}, nil) + require.NoError(t, err) + require.Equal(t, numericgroup.Uint8AsStringProperty{ + Value: to.Ptr(uint8(255)), + }, resp.Uint8AsStringProperty) +} diff --git a/test/http-specs/encode/numericgroup/testdata/_metadata.json b/test/http-specs/encode/numericgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/encode/numericgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/encode/numericgroup/zz_models.go b/test/http-specs/encode/numericgroup/zz_models.go new file mode 100644 index 000000000000..fc761d34b076 --- /dev/null +++ b/test/http-specs/encode/numericgroup/zz_models.go @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package numericgroup + +type SafeintAsStringProperty struct { + // REQUIRED + Value *int64 +} + +type Uint32AsStringProperty struct { + Value *uint32 +} + +type Uint8AsStringProperty struct { + // REQUIRED + Value *uint8 +} diff --git a/test/http-specs/encode/numericgroup/zz_models_serde.go b/test/http-specs/encode/numericgroup/zz_models_serde.go new file mode 100644 index 000000000000..76ccd0dca850 --- /dev/null +++ b/test/http-specs/encode/numericgroup/zz_models_serde.go @@ -0,0 +1,139 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package numericgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "reflect" + "strconv" +) + +// MarshalJSON implements the json.Marshaller interface for type SafeintAsStringProperty. +func (s SafeintAsStringProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", to.Ptr(strconv.FormatInt(*s.Value, 10))) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SafeintAsStringProperty. +func (s *SafeintAsStringProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + var aux string + err = unpopulate(val, "Value", &aux) + if err == nil { + var v int64 + v, err = strconv.ParseInt(aux, 10, 0) + if err == nil { + s.Value = to.Ptr(v) + } + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Uint32AsStringProperty. +func (u Uint32AsStringProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", to.Ptr(strconv.FormatUint(uint64(*u.Value), 10))) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Uint32AsStringProperty. +func (u *Uint32AsStringProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + var aux string + err = unpopulate(val, "Value", &aux) + if err == nil { + var v uint64 + v, err = strconv.ParseUint(aux, 10, 0) + if err == nil { + u.Value = to.Ptr(uint32(v)) + } + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Uint8AsStringProperty. +func (u Uint8AsStringProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", to.Ptr(strconv.FormatUint(uint64(*u.Value), 10))) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Uint8AsStringProperty. +func (u *Uint8AsStringProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + var aux string + err = unpopulate(val, "Value", &aux) + if err == nil { + var v uint64 + v, err = strconv.ParseUint(aux, 10, 0) + if err == nil { + u.Value = to.Ptr(uint8(v)) + } + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/http-specs/encode/numericgroup/zz_numeric_client.go b/test/http-specs/encode/numericgroup/zz_numeric_client.go new file mode 100644 index 000000000000..b9246ebd65ad --- /dev/null +++ b/test/http-specs/encode/numericgroup/zz_numeric_client.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package numericgroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// NumericClient - Test for encode decorator on integer. +// Don't use this type directly, use NewNumericClientWithNoCredential() instead. +type NumericClient struct { + internal *azcore.Client + endpoint string +} + +// NumericClientOptions contains the optional values for creating a [NumericClient]. +type NumericClientOptions struct { + azcore.ClientOptions +} + +// NewNumericClientWithNoCredential creates a new instance of NumericClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewNumericClientWithNoCredential(endpoint string, options *NumericClientOptions) (*NumericClient, error) { + if options == nil { + options = &NumericClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &NumericClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewNumericPropertyClient creates a new instance of [NumericPropertyClient]. +func (client *NumericClient) NewNumericPropertyClient() *NumericPropertyClient { + return &NumericPropertyClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/http-specs/encode/numericgroup/zz_numericproperty_client.go b/test/http-specs/encode/numericgroup/zz_numericproperty_client.go new file mode 100644 index 000000000000..5857e1ab515c --- /dev/null +++ b/test/http-specs/encode/numericgroup/zz_numericproperty_client.go @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package numericgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// NumericPropertyClient contains the methods for the NumericProperty group. +// Don't use this type directly, use [NumericClient.NewNumericPropertyClient] instead. +type NumericPropertyClient struct { + internal *azcore.Client + endpoint string +} + +// SafeintAsString - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NumericPropertyClientSafeintAsStringOptions contains the optional parameters for the NumericPropertyClient.SafeintAsString +// method. +func (client *NumericPropertyClient) SafeintAsString(ctx context.Context, value SafeintAsStringProperty, options *NumericPropertyClientSafeintAsStringOptions) (NumericPropertyClientSafeintAsStringResponse, error) { + var err error + const operationName = "NumericPropertyClient.SafeintAsString" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.safeintAsStringCreateRequest(ctx, value, options) + if err != nil { + return NumericPropertyClientSafeintAsStringResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NumericPropertyClientSafeintAsStringResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NumericPropertyClientSafeintAsStringResponse{}, err + } + resp, err := client.safeintAsStringHandleResponse(httpResp) + return resp, err +} + +// safeintAsStringCreateRequest creates the SafeintAsString request. +func (client *NumericPropertyClient) safeintAsStringCreateRequest(ctx context.Context, value SafeintAsStringProperty, _ *NumericPropertyClientSafeintAsStringOptions) (*policy.Request, error) { + urlPath := "/encode/numeric/property/safeint" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, value); err != nil { + return nil, err + } + return req, nil +} + +// safeintAsStringHandleResponse handles the SafeintAsString response. +func (client *NumericPropertyClient) safeintAsStringHandleResponse(resp *http.Response) (NumericPropertyClientSafeintAsStringResponse, error) { + result := NumericPropertyClientSafeintAsStringResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SafeintAsStringProperty); err != nil { + return NumericPropertyClientSafeintAsStringResponse{}, err + } + return result, nil +} + +// Uint32AsStringOptional - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NumericPropertyClientUint32AsStringOptionalOptions contains the optional parameters for the NumericPropertyClient.Uint32AsStringOptional +// method. +func (client *NumericPropertyClient) Uint32AsStringOptional(ctx context.Context, value Uint32AsStringProperty, options *NumericPropertyClientUint32AsStringOptionalOptions) (NumericPropertyClientUint32AsStringOptionalResponse, error) { + var err error + const operationName = "NumericPropertyClient.Uint32AsStringOptional" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.uint32AsStringOptionalCreateRequest(ctx, value, options) + if err != nil { + return NumericPropertyClientUint32AsStringOptionalResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NumericPropertyClientUint32AsStringOptionalResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NumericPropertyClientUint32AsStringOptionalResponse{}, err + } + resp, err := client.uint32AsStringOptionalHandleResponse(httpResp) + return resp, err +} + +// uint32AsStringOptionalCreateRequest creates the Uint32AsStringOptional request. +func (client *NumericPropertyClient) uint32AsStringOptionalCreateRequest(ctx context.Context, value Uint32AsStringProperty, _ *NumericPropertyClientUint32AsStringOptionalOptions) (*policy.Request, error) { + urlPath := "/encode/numeric/property/uint32" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, value); err != nil { + return nil, err + } + return req, nil +} + +// uint32AsStringOptionalHandleResponse handles the Uint32AsStringOptional response. +func (client *NumericPropertyClient) uint32AsStringOptionalHandleResponse(resp *http.Response) (NumericPropertyClientUint32AsStringOptionalResponse, error) { + result := NumericPropertyClientUint32AsStringOptionalResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Uint32AsStringProperty); err != nil { + return NumericPropertyClientUint32AsStringOptionalResponse{}, err + } + return result, nil +} + +// Uint8AsString - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NumericPropertyClientUint8AsStringOptions contains the optional parameters for the NumericPropertyClient.Uint8AsString +// method. +func (client *NumericPropertyClient) Uint8AsString(ctx context.Context, value Uint8AsStringProperty, options *NumericPropertyClientUint8AsStringOptions) (NumericPropertyClientUint8AsStringResponse, error) { + var err error + const operationName = "NumericPropertyClient.Uint8AsString" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.uint8AsStringCreateRequest(ctx, value, options) + if err != nil { + return NumericPropertyClientUint8AsStringResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NumericPropertyClientUint8AsStringResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NumericPropertyClientUint8AsStringResponse{}, err + } + resp, err := client.uint8AsStringHandleResponse(httpResp) + return resp, err +} + +// uint8AsStringCreateRequest creates the Uint8AsString request. +func (client *NumericPropertyClient) uint8AsStringCreateRequest(ctx context.Context, value Uint8AsStringProperty, _ *NumericPropertyClientUint8AsStringOptions) (*policy.Request, error) { + urlPath := "/encode/numeric/property/uint8" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, value); err != nil { + return nil, err + } + return req, nil +} + +// uint8AsStringHandleResponse handles the Uint8AsString response. +func (client *NumericPropertyClient) uint8AsStringHandleResponse(resp *http.Response) (NumericPropertyClientUint8AsStringResponse, error) { + result := NumericPropertyClientUint8AsStringResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Uint8AsStringProperty); err != nil { + return NumericPropertyClientUint8AsStringResponse{}, err + } + return result, nil +} diff --git a/test/http-specs/encode/numericgroup/zz_options.go b/test/http-specs/encode/numericgroup/zz_options.go new file mode 100644 index 000000000000..b000c4f9de80 --- /dev/null +++ b/test/http-specs/encode/numericgroup/zz_options.go @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package numericgroup + +// NumericPropertyClientSafeintAsStringOptions contains the optional parameters for the NumericPropertyClient.SafeintAsString +// method. +type NumericPropertyClientSafeintAsStringOptions struct { + // placeholder for future optional parameters +} + +// NumericPropertyClientUint32AsStringOptionalOptions contains the optional parameters for the NumericPropertyClient.Uint32AsStringOptional +// method. +type NumericPropertyClientUint32AsStringOptionalOptions struct { + // placeholder for future optional parameters +} + +// NumericPropertyClientUint8AsStringOptions contains the optional parameters for the NumericPropertyClient.Uint8AsString +// method. +type NumericPropertyClientUint8AsStringOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/encode/numericgroup/zz_responses.go b/test/http-specs/encode/numericgroup/zz_responses.go new file mode 100644 index 000000000000..035574130e52 --- /dev/null +++ b/test/http-specs/encode/numericgroup/zz_responses.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package numericgroup + +// NumericPropertyClientSafeintAsStringResponse contains the response from method NumericPropertyClient.SafeintAsString. +type NumericPropertyClientSafeintAsStringResponse struct { + SafeintAsStringProperty +} + +// NumericPropertyClientUint32AsStringOptionalResponse contains the response from method NumericPropertyClient.Uint32AsStringOptional. +type NumericPropertyClientUint32AsStringOptionalResponse struct { + Uint32AsStringProperty +} + +// NumericPropertyClientUint8AsStringResponse contains the response from method NumericPropertyClient.Uint8AsString. +type NumericPropertyClientUint8AsStringResponse struct { + Uint8AsStringProperty +} diff --git a/test/http-specs/encode/numericgroup/zz_version.go b/test/http-specs/encode/numericgroup/zz_version.go new file mode 100644 index 000000000000..4ae2da236700 --- /dev/null +++ b/test/http-specs/encode/numericgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package numericgroup + +const ( + moduleName = "numericgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/parameters/basicparamsgroup/LICENSE.txt b/test/http-specs/parameters/basicparamsgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/parameters/basicparamsgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/parameters/basicparamsgroup/basicexplicitbody_client_test.go b/test/http-specs/parameters/basicparamsgroup/basicexplicitbody_client_test.go new file mode 100644 index 000000000000..75ebb658e718 --- /dev/null +++ b/test/http-specs/parameters/basicparamsgroup/basicexplicitbody_client_test.go @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package basicparamsgroup_test + +import ( + "basicparamsgroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestBasicExplicitBodyClient_Simple(t *testing.T) { + client, err := basicparamsgroup.NewBasicClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewBasicExplicitBodyClient().Simple(context.Background(), basicparamsgroup.User{ + Name: to.Ptr("foo"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/parameters/basicparamsgroup/basicimplicitbody_client_test.go b/test/http-specs/parameters/basicparamsgroup/basicimplicitbody_client_test.go new file mode 100644 index 000000000000..155c9aaada34 --- /dev/null +++ b/test/http-specs/parameters/basicparamsgroup/basicimplicitbody_client_test.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package basicparamsgroup_test + +import ( + "basicparamsgroup" + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestBasicImplicitBodyClient_Simple(t *testing.T) { + client, err := basicparamsgroup.NewBasicClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewBasicImplicitBodyClient().Simple(context.Background(), "foo", nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/parameters/basicparamsgroup/fake/zz_basic_server.go b/test/http-specs/parameters/basicparamsgroup/fake/zz_basic_server.go new file mode 100644 index 000000000000..42494693fb87 --- /dev/null +++ b/test/http-specs/parameters/basicparamsgroup/fake/zz_basic_server.go @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// BasicServer is a fake server for instances of the basicparamsgroup.BasicClient type. +type BasicServer struct { + // BasicExplicitBodyServer contains the fakes for client BasicExplicitBodyClient + BasicExplicitBodyServer BasicExplicitBodyServer + + // BasicImplicitBodyServer contains the fakes for client BasicImplicitBodyClient + BasicImplicitBodyServer BasicImplicitBodyServer +} + +// NewBasicServerTransport creates a new instance of BasicServerTransport with the provided implementation. +// The returned BasicServerTransport instance is connected to an instance of basicparamsgroup.BasicClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewBasicServerTransport(srv *BasicServer) *BasicServerTransport { + return &BasicServerTransport{srv: srv} +} + +// BasicServerTransport connects instances of basicparamsgroup.BasicClient to instances of BasicServer. +// Don't use this type directly, use NewBasicServerTransport instead. +type BasicServerTransport struct { + srv *BasicServer + trMu sync.Mutex + trBasicExplicitBodyServer *BasicExplicitBodyServerTransport + trBasicImplicitBodyServer *BasicImplicitBodyServerTransport +} + +// Do implements the policy.Transporter interface for BasicServerTransport. +func (b *BasicServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return b.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (b *BasicServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "BasicExplicitBodyClient": + initServer(&b.trMu, &b.trBasicExplicitBodyServer, func() *BasicExplicitBodyServerTransport { + return NewBasicExplicitBodyServerTransport(&b.srv.BasicExplicitBodyServer) + }) + resp, err = b.trBasicExplicitBodyServer.Do(req) + case "BasicImplicitBodyClient": + initServer(&b.trMu, &b.trBasicImplicitBodyServer, func() *BasicImplicitBodyServerTransport { + return NewBasicImplicitBodyServerTransport(&b.srv.BasicImplicitBodyServer) + }) + resp, err = b.trBasicImplicitBodyServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to BasicServerTransport +var basicServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/parameters/basicparamsgroup/fake/zz_basicexplicitbody_server.go b/test/http-specs/parameters/basicparamsgroup/fake/zz_basicexplicitbody_server.go new file mode 100644 index 000000000000..2cd40ae7a19b --- /dev/null +++ b/test/http-specs/parameters/basicparamsgroup/fake/zz_basicexplicitbody_server.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "basicparamsgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// BasicExplicitBodyServer is a fake server for instances of the basicparamsgroup.BasicExplicitBodyClient type. +type BasicExplicitBodyServer struct { + // Simple is the fake for method BasicExplicitBodyClient.Simple + // HTTP status codes to indicate success: http.StatusNoContent + Simple func(ctx context.Context, body basicparamsgroup.User, options *basicparamsgroup.BasicExplicitBodyClientSimpleOptions) (resp azfake.Responder[basicparamsgroup.BasicExplicitBodyClientSimpleResponse], errResp azfake.ErrorResponder) +} + +// NewBasicExplicitBodyServerTransport creates a new instance of BasicExplicitBodyServerTransport with the provided implementation. +// The returned BasicExplicitBodyServerTransport instance is connected to an instance of basicparamsgroup.BasicExplicitBodyClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewBasicExplicitBodyServerTransport(srv *BasicExplicitBodyServer) *BasicExplicitBodyServerTransport { + return &BasicExplicitBodyServerTransport{srv: srv} +} + +// BasicExplicitBodyServerTransport connects instances of basicparamsgroup.BasicExplicitBodyClient to instances of BasicExplicitBodyServer. +// Don't use this type directly, use NewBasicExplicitBodyServerTransport instead. +type BasicExplicitBodyServerTransport struct { + srv *BasicExplicitBodyServer +} + +// Do implements the policy.Transporter interface for BasicExplicitBodyServerTransport. +func (b *BasicExplicitBodyServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return b.dispatchToMethodFake(req, method) +} + +func (b *BasicExplicitBodyServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if basicExplicitBodyServerTransportInterceptor != nil { + res.resp, res.err, intercepted = basicExplicitBodyServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "BasicExplicitBodyClient.Simple": + res.resp, res.err = b.dispatchSimple(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (b *BasicExplicitBodyServerTransport) dispatchSimple(req *http.Request) (*http.Response, error) { + if b.srv.Simple == nil { + return nil, &nonRetriableError{errors.New("fake for method Simple not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[basicparamsgroup.User](req) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.Simple(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to BasicExplicitBodyServerTransport +var basicExplicitBodyServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/parameters/basicparamsgroup/fake/zz_basicimplicitbody_server.go b/test/http-specs/parameters/basicparamsgroup/fake/zz_basicimplicitbody_server.go new file mode 100644 index 000000000000..e9816eb6e30e --- /dev/null +++ b/test/http-specs/parameters/basicparamsgroup/fake/zz_basicimplicitbody_server.go @@ -0,0 +1,108 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "basicparamsgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// BasicImplicitBodyServer is a fake server for instances of the basicparamsgroup.BasicImplicitBodyClient type. +type BasicImplicitBodyServer struct { + // Simple is the fake for method BasicImplicitBodyClient.Simple + // HTTP status codes to indicate success: http.StatusNoContent + Simple func(ctx context.Context, name string, options *basicparamsgroup.BasicImplicitBodyClientSimpleOptions) (resp azfake.Responder[basicparamsgroup.BasicImplicitBodyClientSimpleResponse], errResp azfake.ErrorResponder) +} + +// NewBasicImplicitBodyServerTransport creates a new instance of BasicImplicitBodyServerTransport with the provided implementation. +// The returned BasicImplicitBodyServerTransport instance is connected to an instance of basicparamsgroup.BasicImplicitBodyClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewBasicImplicitBodyServerTransport(srv *BasicImplicitBodyServer) *BasicImplicitBodyServerTransport { + return &BasicImplicitBodyServerTransport{srv: srv} +} + +// BasicImplicitBodyServerTransport connects instances of basicparamsgroup.BasicImplicitBodyClient to instances of BasicImplicitBodyServer. +// Don't use this type directly, use NewBasicImplicitBodyServerTransport instead. +type BasicImplicitBodyServerTransport struct { + srv *BasicImplicitBodyServer +} + +// Do implements the policy.Transporter interface for BasicImplicitBodyServerTransport. +func (b *BasicImplicitBodyServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return b.dispatchToMethodFake(req, method) +} + +func (b *BasicImplicitBodyServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if basicImplicitBodyServerTransportInterceptor != nil { + res.resp, res.err, intercepted = basicImplicitBodyServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "BasicImplicitBodyClient.Simple": + res.resp, res.err = b.dispatchSimple(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (b *BasicImplicitBodyServerTransport) dispatchSimple(req *http.Request) (*http.Response, error) { + if b.srv.Simple == nil { + return nil, &nonRetriableError{errors.New("fake for method Simple not implemented")} + } + type partialBodyParams struct { + Name string `json:"name"` + } + body, err := server.UnmarshalRequestAsJSON[partialBodyParams](req) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.Simple(req.Context(), body.Name, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to BasicImplicitBodyServerTransport +var basicImplicitBodyServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/parameters/basicparamsgroup/fake/zz_internal.go b/test/http-specs/parameters/basicparamsgroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/http-specs/parameters/basicparamsgroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/http-specs/parameters/basicparamsgroup/go.mod b/test/http-specs/parameters/basicparamsgroup/go.mod new file mode 100644 index 000000000000..12ca5e9c350b --- /dev/null +++ b/test/http-specs/parameters/basicparamsgroup/go.mod @@ -0,0 +1,17 @@ +module basicparamsgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/parameters/basicparamsgroup/go.sum b/test/http-specs/parameters/basicparamsgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/parameters/basicparamsgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/parameters/basicparamsgroup/testdata/_metadata.json b/test/http-specs/parameters/basicparamsgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/parameters/basicparamsgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/parameters/basicparamsgroup/zz_basic_client.go b/test/http-specs/parameters/basicparamsgroup/zz_basic_client.go new file mode 100644 index 000000000000..4646989b260d --- /dev/null +++ b/test/http-specs/parameters/basicparamsgroup/zz_basic_client.go @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package basicparamsgroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// BasicClient - Test for basic parameters cases. +// Don't use this type directly, use NewBasicClientWithNoCredential() instead. +type BasicClient struct { + internal *azcore.Client + endpoint string +} + +// BasicClientOptions contains the optional values for creating a [BasicClient]. +type BasicClientOptions struct { + azcore.ClientOptions +} + +// NewBasicClientWithNoCredential creates a new instance of BasicClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewBasicClientWithNoCredential(endpoint string, options *BasicClientOptions) (*BasicClient, error) { + if options == nil { + options = &BasicClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &BasicClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewBasicExplicitBodyClient creates a new instance of [BasicExplicitBodyClient]. +func (client *BasicClient) NewBasicExplicitBodyClient() *BasicExplicitBodyClient { + return &BasicExplicitBodyClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewBasicImplicitBodyClient creates a new instance of [BasicImplicitBodyClient]. +func (client *BasicClient) NewBasicImplicitBodyClient() *BasicImplicitBodyClient { + return &BasicImplicitBodyClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/http-specs/parameters/basicparamsgroup/zz_basicexplicitbody_client.go b/test/http-specs/parameters/basicparamsgroup/zz_basicexplicitbody_client.go new file mode 100644 index 000000000000..1b5ef018f49c --- /dev/null +++ b/test/http-specs/parameters/basicparamsgroup/zz_basicexplicitbody_client.go @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package basicparamsgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// BasicExplicitBodyClient contains the methods for the BasicExplicitBody group. +// Don't use this type directly, use [BasicClient.NewBasicExplicitBodyClient] instead. +type BasicExplicitBodyClient struct { + internal *azcore.Client + endpoint string +} + +// Simple - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BasicExplicitBodyClientSimpleOptions contains the optional parameters for the BasicExplicitBodyClient.Simple +// method. +func (client *BasicExplicitBodyClient) Simple(ctx context.Context, body User, options *BasicExplicitBodyClientSimpleOptions) (BasicExplicitBodyClientSimpleResponse, error) { + var err error + const operationName = "BasicExplicitBodyClient.Simple" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.simpleCreateRequest(ctx, body, options) + if err != nil { + return BasicExplicitBodyClientSimpleResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BasicExplicitBodyClientSimpleResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return BasicExplicitBodyClientSimpleResponse{}, err + } + return BasicExplicitBodyClientSimpleResponse{}, nil +} + +// simpleCreateRequest creates the Simple request. +func (client *BasicExplicitBodyClient) simpleCreateRequest(ctx context.Context, body User, _ *BasicExplicitBodyClientSimpleOptions) (*policy.Request, error) { + urlPath := "/parameters/basic/explicit-body/simple" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/parameters/basicparamsgroup/zz_basicimplicitbody_client.go b/test/http-specs/parameters/basicparamsgroup/zz_basicimplicitbody_client.go new file mode 100644 index 000000000000..61b9ba7c063b --- /dev/null +++ b/test/http-specs/parameters/basicparamsgroup/zz_basicimplicitbody_client.go @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package basicparamsgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// BasicImplicitBodyClient contains the methods for the BasicImplicitBody group. +// Don't use this type directly, use [BasicClient.NewBasicImplicitBodyClient] instead. +type BasicImplicitBodyClient struct { + internal *azcore.Client + endpoint string +} + +// Simple - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BasicImplicitBodyClientSimpleOptions contains the optional parameters for the BasicImplicitBodyClient.Simple +// method. +func (client *BasicImplicitBodyClient) Simple(ctx context.Context, name string, options *BasicImplicitBodyClientSimpleOptions) (BasicImplicitBodyClientSimpleResponse, error) { + var err error + const operationName = "BasicImplicitBodyClient.Simple" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.simpleCreateRequest(ctx, name, options) + if err != nil { + return BasicImplicitBodyClientSimpleResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BasicImplicitBodyClientSimpleResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return BasicImplicitBodyClientSimpleResponse{}, err + } + return BasicImplicitBodyClientSimpleResponse{}, nil +} + +// simpleCreateRequest creates the Simple request. +func (client *BasicImplicitBodyClient) simpleCreateRequest(ctx context.Context, name string, _ *BasicImplicitBodyClientSimpleOptions) (*policy.Request, error) { + urlPath := "/parameters/basic/implicit-body/simple" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + body := struct { + Name string `json:"name"` + }{ + Name: name, + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/parameters/basicparamsgroup/zz_models.go b/test/http-specs/parameters/basicparamsgroup/zz_models.go new file mode 100644 index 000000000000..5d4d0c6a73df --- /dev/null +++ b/test/http-specs/parameters/basicparamsgroup/zz_models.go @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package basicparamsgroup + +// User - This is a simple model. +type User struct { + // REQUIRED + Name *string +} diff --git a/test/http-specs/parameters/basicparamsgroup/zz_models_serde.go b/test/http-specs/parameters/basicparamsgroup/zz_models_serde.go new file mode 100644 index 000000000000..3f0da160d814 --- /dev/null +++ b/test/http-specs/parameters/basicparamsgroup/zz_models_serde.go @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package basicparamsgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type User. +func (u User) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", u.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type User. +func (u *User) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &u.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/http-specs/parameters/basicparamsgroup/zz_options.go b/test/http-specs/parameters/basicparamsgroup/zz_options.go new file mode 100644 index 000000000000..753dd013c864 --- /dev/null +++ b/test/http-specs/parameters/basicparamsgroup/zz_options.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package basicparamsgroup + +// BasicExplicitBodyClientSimpleOptions contains the optional parameters for the BasicExplicitBodyClient.Simple method. +type BasicExplicitBodyClientSimpleOptions struct { + // placeholder for future optional parameters +} + +// BasicImplicitBodyClientSimpleOptions contains the optional parameters for the BasicImplicitBodyClient.Simple method. +type BasicImplicitBodyClientSimpleOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/parameters/basicparamsgroup/zz_responses.go b/test/http-specs/parameters/basicparamsgroup/zz_responses.go new file mode 100644 index 000000000000..e18e25107d8f --- /dev/null +++ b/test/http-specs/parameters/basicparamsgroup/zz_responses.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package basicparamsgroup + +// BasicExplicitBodyClientSimpleResponse contains the response from method BasicExplicitBodyClient.Simple. +type BasicExplicitBodyClientSimpleResponse struct { + // placeholder for future response values +} + +// BasicImplicitBodyClientSimpleResponse contains the response from method BasicImplicitBodyClient.Simple. +type BasicImplicitBodyClientSimpleResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/parameters/basicparamsgroup/zz_version.go b/test/http-specs/parameters/basicparamsgroup/zz_version.go new file mode 100644 index 000000000000..3559c06b9795 --- /dev/null +++ b/test/http-specs/parameters/basicparamsgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package basicparamsgroup + +const ( + moduleName = "basicparamsgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/parameters/bodyoptionalgroup/LICENSE.txt b/test/http-specs/parameters/bodyoptionalgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/parameters/bodyoptionalgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/parameters/bodyoptionalgroup/bodyoptionality_client_test.go b/test/http-specs/parameters/bodyoptionalgroup/bodyoptionality_client_test.go new file mode 100644 index 000000000000..d77700bf8874 --- /dev/null +++ b/test/http-specs/parameters/bodyoptionalgroup/bodyoptionality_client_test.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package bodyoptionalgroup_test + +import ( + "bodyoptionalgroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestBodyOptionalityClient_RequiredExplicit(t *testing.T) { + client, err := bodyoptionalgroup.NewBodyOptionalityClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.RequiredExplicit(context.Background(), bodyoptionalgroup.BodyModel{ + Name: to.Ptr("foo"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestBodyOptionalityClient_RequiredImplicit(t *testing.T) { + client, err := bodyoptionalgroup.NewBodyOptionalityClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.RequiredImplicit(context.Background(), "foo", nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/parameters/bodyoptionalgroup/fake/zz_bodyoptionality_server.go b/test/http-specs/parameters/bodyoptionalgroup/fake/zz_bodyoptionality_server.go new file mode 100644 index 000000000000..bdb8c4c46a85 --- /dev/null +++ b/test/http-specs/parameters/bodyoptionalgroup/fake/zz_bodyoptionality_server.go @@ -0,0 +1,164 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "bodyoptionalgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "strings" + "sync" +) + +// BodyOptionalityServer is a fake server for instances of the bodyoptionalgroup.BodyOptionalityClient type. +type BodyOptionalityServer struct { + // BodyOptionalityOptionalExplicitServer contains the fakes for client BodyOptionalityOptionalExplicitClient + BodyOptionalityOptionalExplicitServer BodyOptionalityOptionalExplicitServer + + // RequiredExplicit is the fake for method BodyOptionalityClient.RequiredExplicit + // HTTP status codes to indicate success: http.StatusNoContent + RequiredExplicit func(ctx context.Context, body bodyoptionalgroup.BodyModel, options *bodyoptionalgroup.BodyOptionalityClientRequiredExplicitOptions) (resp azfake.Responder[bodyoptionalgroup.BodyOptionalityClientRequiredExplicitResponse], errResp azfake.ErrorResponder) + + // RequiredImplicit is the fake for method BodyOptionalityClient.RequiredImplicit + // HTTP status codes to indicate success: http.StatusNoContent + RequiredImplicit func(ctx context.Context, name string, options *bodyoptionalgroup.BodyOptionalityClientRequiredImplicitOptions) (resp azfake.Responder[bodyoptionalgroup.BodyOptionalityClientRequiredImplicitResponse], errResp azfake.ErrorResponder) +} + +// NewBodyOptionalityServerTransport creates a new instance of BodyOptionalityServerTransport with the provided implementation. +// The returned BodyOptionalityServerTransport instance is connected to an instance of bodyoptionalgroup.BodyOptionalityClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewBodyOptionalityServerTransport(srv *BodyOptionalityServer) *BodyOptionalityServerTransport { + return &BodyOptionalityServerTransport{srv: srv} +} + +// BodyOptionalityServerTransport connects instances of bodyoptionalgroup.BodyOptionalityClient to instances of BodyOptionalityServer. +// Don't use this type directly, use NewBodyOptionalityServerTransport instead. +type BodyOptionalityServerTransport struct { + srv *BodyOptionalityServer + trMu sync.Mutex + trBodyOptionalityOptionalExplicitServer *BodyOptionalityOptionalExplicitServerTransport +} + +// Do implements the policy.Transporter interface for BodyOptionalityServerTransport. +func (b *BodyOptionalityServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + if client := method[:strings.Index(method, ".")]; client != "BodyOptionalityClient" { + return b.dispatchToClientFake(req, client) + } + return b.dispatchToMethodFake(req, method) +} + +func (b *BodyOptionalityServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "BodyOptionalityOptionalExplicitClient": + initServer(&b.trMu, &b.trBodyOptionalityOptionalExplicitServer, func() *BodyOptionalityOptionalExplicitServerTransport { + return NewBodyOptionalityOptionalExplicitServerTransport(&b.srv.BodyOptionalityOptionalExplicitServer) + }) + resp, err = b.trBodyOptionalityOptionalExplicitServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +func (b *BodyOptionalityServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if bodyOptionalityServerTransportInterceptor != nil { + res.resp, res.err, intercepted = bodyOptionalityServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "BodyOptionalityClient.RequiredExplicit": + res.resp, res.err = b.dispatchRequiredExplicit(req) + case "BodyOptionalityClient.RequiredImplicit": + res.resp, res.err = b.dispatchRequiredImplicit(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (b *BodyOptionalityServerTransport) dispatchRequiredExplicit(req *http.Request) (*http.Response, error) { + if b.srv.RequiredExplicit == nil { + return nil, &nonRetriableError{errors.New("fake for method RequiredExplicit not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[bodyoptionalgroup.BodyModel](req) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.RequiredExplicit(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BodyOptionalityServerTransport) dispatchRequiredImplicit(req *http.Request) (*http.Response, error) { + if b.srv.RequiredImplicit == nil { + return nil, &nonRetriableError{errors.New("fake for method RequiredImplicit not implemented")} + } + type partialBodyParams struct { + Name string `json:"name"` + } + body, err := server.UnmarshalRequestAsJSON[partialBodyParams](req) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.RequiredImplicit(req.Context(), body.Name, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to BodyOptionalityServerTransport +var bodyOptionalityServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/parameters/bodyoptionalgroup/fake/zz_bodyoptionalityoptionalexplicit_server.go b/test/http-specs/parameters/bodyoptionalgroup/fake/zz_bodyoptionalityoptionalexplicit_server.go new file mode 100644 index 000000000000..c19a6fcd7b92 --- /dev/null +++ b/test/http-specs/parameters/bodyoptionalgroup/fake/zz_bodyoptionalityoptionalexplicit_server.go @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "bodyoptionalgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "reflect" + "slices" +) + +// BodyOptionalityOptionalExplicitServer is a fake server for instances of the bodyoptionalgroup.BodyOptionalityOptionalExplicitClient type. +type BodyOptionalityOptionalExplicitServer struct { + // Omit is the fake for method BodyOptionalityOptionalExplicitClient.Omit + // HTTP status codes to indicate success: http.StatusNoContent + Omit func(ctx context.Context, options *bodyoptionalgroup.BodyOptionalityOptionalExplicitClientOmitOptions) (resp azfake.Responder[bodyoptionalgroup.BodyOptionalityOptionalExplicitClientOmitResponse], errResp azfake.ErrorResponder) + + // Set is the fake for method BodyOptionalityOptionalExplicitClient.Set + // HTTP status codes to indicate success: http.StatusNoContent + Set func(ctx context.Context, options *bodyoptionalgroup.BodyOptionalityOptionalExplicitClientSetOptions) (resp azfake.Responder[bodyoptionalgroup.BodyOptionalityOptionalExplicitClientSetResponse], errResp azfake.ErrorResponder) +} + +// NewBodyOptionalityOptionalExplicitServerTransport creates a new instance of BodyOptionalityOptionalExplicitServerTransport with the provided implementation. +// The returned BodyOptionalityOptionalExplicitServerTransport instance is connected to an instance of bodyoptionalgroup.BodyOptionalityOptionalExplicitClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewBodyOptionalityOptionalExplicitServerTransport(srv *BodyOptionalityOptionalExplicitServer) *BodyOptionalityOptionalExplicitServerTransport { + return &BodyOptionalityOptionalExplicitServerTransport{srv: srv} +} + +// BodyOptionalityOptionalExplicitServerTransport connects instances of bodyoptionalgroup.BodyOptionalityOptionalExplicitClient to instances of BodyOptionalityOptionalExplicitServer. +// Don't use this type directly, use NewBodyOptionalityOptionalExplicitServerTransport instead. +type BodyOptionalityOptionalExplicitServerTransport struct { + srv *BodyOptionalityOptionalExplicitServer +} + +// Do implements the policy.Transporter interface for BodyOptionalityOptionalExplicitServerTransport. +func (b *BodyOptionalityOptionalExplicitServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return b.dispatchToMethodFake(req, method) +} + +func (b *BodyOptionalityOptionalExplicitServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if bodyOptionalityOptionalExplicitServerTransportInterceptor != nil { + res.resp, res.err, intercepted = bodyOptionalityOptionalExplicitServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "BodyOptionalityOptionalExplicitClient.Omit": + res.resp, res.err = b.dispatchOmit(req) + case "BodyOptionalityOptionalExplicitClient.Set": + res.resp, res.err = b.dispatchSet(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (b *BodyOptionalityOptionalExplicitServerTransport) dispatchOmit(req *http.Request) (*http.Response, error) { + if b.srv.Omit == nil { + return nil, &nonRetriableError{errors.New("fake for method Omit not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[bodyoptionalgroup.BodyModel](req) + if err != nil { + return nil, err + } + var options *bodyoptionalgroup.BodyOptionalityOptionalExplicitClientOmitOptions + if !reflect.ValueOf(body).IsZero() { + options = &bodyoptionalgroup.BodyOptionalityOptionalExplicitClientOmitOptions{ + Body: &body, + } + } + respr, errRespr := b.srv.Omit(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BodyOptionalityOptionalExplicitServerTransport) dispatchSet(req *http.Request) (*http.Response, error) { + if b.srv.Set == nil { + return nil, &nonRetriableError{errors.New("fake for method Set not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[bodyoptionalgroup.BodyModel](req) + if err != nil { + return nil, err + } + var options *bodyoptionalgroup.BodyOptionalityOptionalExplicitClientSetOptions + if !reflect.ValueOf(body).IsZero() { + options = &bodyoptionalgroup.BodyOptionalityOptionalExplicitClientSetOptions{ + Body: &body, + } + } + respr, errRespr := b.srv.Set(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to BodyOptionalityOptionalExplicitServerTransport +var bodyOptionalityOptionalExplicitServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/parameters/bodyoptionalgroup/fake/zz_internal.go b/test/http-specs/parameters/bodyoptionalgroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/http-specs/parameters/bodyoptionalgroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/http-specs/parameters/bodyoptionalgroup/go.mod b/test/http-specs/parameters/bodyoptionalgroup/go.mod new file mode 100644 index 000000000000..6493d58468a1 --- /dev/null +++ b/test/http-specs/parameters/bodyoptionalgroup/go.mod @@ -0,0 +1,17 @@ +module bodyoptionalgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/parameters/bodyoptionalgroup/go.sum b/test/http-specs/parameters/bodyoptionalgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/parameters/bodyoptionalgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/parameters/bodyoptionalgroup/optionalexplicit_client_test.go b/test/http-specs/parameters/bodyoptionalgroup/optionalexplicit_client_test.go new file mode 100644 index 000000000000..eaeee2c17b13 --- /dev/null +++ b/test/http-specs/parameters/bodyoptionalgroup/optionalexplicit_client_test.go @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package bodyoptionalgroup_test + +import ( + "bodyoptionalgroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestOptionalExplicitClient_Omit(t *testing.T) { + client, err := bodyoptionalgroup.NewBodyOptionalityClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewBodyOptionalityOptionalExplicitClient().Omit(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalExplicitClient_Set(t *testing.T) { + client, err := bodyoptionalgroup.NewBodyOptionalityClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewBodyOptionalityOptionalExplicitClient().Set(context.Background(), &bodyoptionalgroup.BodyOptionalityOptionalExplicitClientSetOptions{ + Body: &bodyoptionalgroup.BodyModel{ + Name: to.Ptr("foo"), + }, + }) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/parameters/bodyoptionalgroup/testdata/_metadata.json b/test/http-specs/parameters/bodyoptionalgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/parameters/bodyoptionalgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/parameters/bodyoptionalgroup/zz_bodyoptionality_client.go b/test/http-specs/parameters/bodyoptionalgroup/zz_bodyoptionality_client.go new file mode 100644 index 000000000000..e43fd043a5e6 --- /dev/null +++ b/test/http-specs/parameters/bodyoptionalgroup/zz_bodyoptionality_client.go @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package bodyoptionalgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// BodyOptionalityClient - Test describing optionality of the request body. +// Don't use this type directly, use NewBodyOptionalityClientWithNoCredential() instead. +type BodyOptionalityClient struct { + internal *azcore.Client + endpoint string +} + +// BodyOptionalityClientOptions contains the optional values for creating a [BodyOptionalityClient]. +type BodyOptionalityClientOptions struct { + azcore.ClientOptions +} + +// NewBodyOptionalityClientWithNoCredential creates a new instance of BodyOptionalityClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewBodyOptionalityClientWithNoCredential(endpoint string, options *BodyOptionalityClientOptions) (*BodyOptionalityClient, error) { + if options == nil { + options = &BodyOptionalityClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &BodyOptionalityClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewBodyOptionalityOptionalExplicitClient creates a new instance of [BodyOptionalityOptionalExplicitClient]. +func (client *BodyOptionalityClient) NewBodyOptionalityOptionalExplicitClient() *BodyOptionalityOptionalExplicitClient { + return &BodyOptionalityOptionalExplicitClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// RequiredExplicit - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BodyOptionalityClientRequiredExplicitOptions contains the optional parameters for the BodyOptionalityClient.RequiredExplicit +// method. +func (client *BodyOptionalityClient) RequiredExplicit(ctx context.Context, body BodyModel, options *BodyOptionalityClientRequiredExplicitOptions) (BodyOptionalityClientRequiredExplicitResponse, error) { + var err error + const operationName = "BodyOptionalityClient.RequiredExplicit" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.requiredExplicitCreateRequest(ctx, body, options) + if err != nil { + return BodyOptionalityClientRequiredExplicitResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BodyOptionalityClientRequiredExplicitResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return BodyOptionalityClientRequiredExplicitResponse{}, err + } + return BodyOptionalityClientRequiredExplicitResponse{}, nil +} + +// requiredExplicitCreateRequest creates the RequiredExplicit request. +func (client *BodyOptionalityClient) requiredExplicitCreateRequest(ctx context.Context, body BodyModel, _ *BodyOptionalityClientRequiredExplicitOptions) (*policy.Request, error) { + urlPath := "/parameters/body-optionality/required-explicit" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// RequiredImplicit - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BodyOptionalityClientRequiredImplicitOptions contains the optional parameters for the BodyOptionalityClient.RequiredImplicit +// method. +func (client *BodyOptionalityClient) RequiredImplicit(ctx context.Context, name string, options *BodyOptionalityClientRequiredImplicitOptions) (BodyOptionalityClientRequiredImplicitResponse, error) { + var err error + const operationName = "BodyOptionalityClient.RequiredImplicit" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.requiredImplicitCreateRequest(ctx, name, options) + if err != nil { + return BodyOptionalityClientRequiredImplicitResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BodyOptionalityClientRequiredImplicitResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return BodyOptionalityClientRequiredImplicitResponse{}, err + } + return BodyOptionalityClientRequiredImplicitResponse{}, nil +} + +// requiredImplicitCreateRequest creates the RequiredImplicit request. +func (client *BodyOptionalityClient) requiredImplicitCreateRequest(ctx context.Context, name string, _ *BodyOptionalityClientRequiredImplicitOptions) (*policy.Request, error) { + urlPath := "/parameters/body-optionality/required-implicit" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + body := struct { + Name string `json:"name"` + }{ + Name: name, + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/parameters/bodyoptionalgroup/zz_bodyoptionalityoptionalexplicit_client.go b/test/http-specs/parameters/bodyoptionalgroup/zz_bodyoptionalityoptionalexplicit_client.go new file mode 100644 index 000000000000..7e1b4622c3e3 --- /dev/null +++ b/test/http-specs/parameters/bodyoptionalgroup/zz_bodyoptionalityoptionalexplicit_client.go @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package bodyoptionalgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// BodyOptionalityOptionalExplicitClient contains the methods for the BodyOptionalityOptionalExplicit group. +// Don't use this type directly, use [BodyOptionalityClient.NewBodyOptionalityOptionalExplicitClient] instead. +type BodyOptionalityOptionalExplicitClient struct { + internal *azcore.Client + endpoint string +} + +// Omit - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BodyOptionalityOptionalExplicitClientOmitOptions contains the optional parameters for the BodyOptionalityOptionalExplicitClient.Omit +// method. +func (client *BodyOptionalityOptionalExplicitClient) Omit(ctx context.Context, options *BodyOptionalityOptionalExplicitClientOmitOptions) (BodyOptionalityOptionalExplicitClientOmitResponse, error) { + var err error + const operationName = "BodyOptionalityOptionalExplicitClient.Omit" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.omitCreateRequest(ctx, options) + if err != nil { + return BodyOptionalityOptionalExplicitClientOmitResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BodyOptionalityOptionalExplicitClientOmitResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return BodyOptionalityOptionalExplicitClientOmitResponse{}, err + } + return BodyOptionalityOptionalExplicitClientOmitResponse{}, nil +} + +// omitCreateRequest creates the Omit request. +func (client *BodyOptionalityOptionalExplicitClient) omitCreateRequest(ctx context.Context, options *BodyOptionalityOptionalExplicitClientOmitOptions) (*policy.Request, error) { + urlPath := "/parameters/body-optionality/optional-explicit/omit" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + if options != nil && options.Body != nil { + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, *options.Body); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// Set - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - BodyOptionalityOptionalExplicitClientSetOptions contains the optional parameters for the BodyOptionalityOptionalExplicitClient.Set +// method. +func (client *BodyOptionalityOptionalExplicitClient) Set(ctx context.Context, options *BodyOptionalityOptionalExplicitClientSetOptions) (BodyOptionalityOptionalExplicitClientSetResponse, error) { + var err error + const operationName = "BodyOptionalityOptionalExplicitClient.Set" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.setCreateRequest(ctx, options) + if err != nil { + return BodyOptionalityOptionalExplicitClientSetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BodyOptionalityOptionalExplicitClientSetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return BodyOptionalityOptionalExplicitClientSetResponse{}, err + } + return BodyOptionalityOptionalExplicitClientSetResponse{}, nil +} + +// setCreateRequest creates the Set request. +func (client *BodyOptionalityOptionalExplicitClient) setCreateRequest(ctx context.Context, options *BodyOptionalityOptionalExplicitClientSetOptions) (*policy.Request, error) { + urlPath := "/parameters/body-optionality/optional-explicit/set" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + if options != nil && options.Body != nil { + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, *options.Body); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} diff --git a/test/http-specs/parameters/bodyoptionalgroup/zz_models.go b/test/http-specs/parameters/bodyoptionalgroup/zz_models.go new file mode 100644 index 000000000000..de57df4145f6 --- /dev/null +++ b/test/http-specs/parameters/bodyoptionalgroup/zz_models.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package bodyoptionalgroup + +type BodyModel struct { + // REQUIRED + Name *string +} diff --git a/test/http-specs/parameters/bodyoptionalgroup/zz_models_serde.go b/test/http-specs/parameters/bodyoptionalgroup/zz_models_serde.go new file mode 100644 index 000000000000..4959b3b0e50f --- /dev/null +++ b/test/http-specs/parameters/bodyoptionalgroup/zz_models_serde.go @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package bodyoptionalgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type BodyModel. +func (b BodyModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", b.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BodyModel. +func (b *BodyModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &b.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/http-specs/parameters/bodyoptionalgroup/zz_options.go b/test/http-specs/parameters/bodyoptionalgroup/zz_options.go new file mode 100644 index 000000000000..19e1fef07a8d --- /dev/null +++ b/test/http-specs/parameters/bodyoptionalgroup/zz_options.go @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package bodyoptionalgroup + +// BodyOptionalityClientRequiredExplicitOptions contains the optional parameters for the BodyOptionalityClient.RequiredExplicit +// method. +type BodyOptionalityClientRequiredExplicitOptions struct { + // placeholder for future optional parameters +} + +// BodyOptionalityClientRequiredImplicitOptions contains the optional parameters for the BodyOptionalityClient.RequiredImplicit +// method. +type BodyOptionalityClientRequiredImplicitOptions struct { + // placeholder for future optional parameters +} + +// BodyOptionalityOptionalExplicitClientOmitOptions contains the optional parameters for the BodyOptionalityOptionalExplicitClient.Omit +// method. +type BodyOptionalityOptionalExplicitClientOmitOptions struct { + Body *BodyModel +} + +// BodyOptionalityOptionalExplicitClientSetOptions contains the optional parameters for the BodyOptionalityOptionalExplicitClient.Set +// method. +type BodyOptionalityOptionalExplicitClientSetOptions struct { + Body *BodyModel +} diff --git a/test/http-specs/parameters/bodyoptionalgroup/zz_responses.go b/test/http-specs/parameters/bodyoptionalgroup/zz_responses.go new file mode 100644 index 000000000000..82e145d10b64 --- /dev/null +++ b/test/http-specs/parameters/bodyoptionalgroup/zz_responses.go @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package bodyoptionalgroup + +// BodyOptionalityClientRequiredExplicitResponse contains the response from method BodyOptionalityClient.RequiredExplicit. +type BodyOptionalityClientRequiredExplicitResponse struct { + // placeholder for future response values +} + +// BodyOptionalityClientRequiredImplicitResponse contains the response from method BodyOptionalityClient.RequiredImplicit. +type BodyOptionalityClientRequiredImplicitResponse struct { + // placeholder for future response values +} + +// BodyOptionalityOptionalExplicitClientOmitResponse contains the response from method BodyOptionalityOptionalExplicitClient.Omit. +type BodyOptionalityOptionalExplicitClientOmitResponse struct { + // placeholder for future response values +} + +// BodyOptionalityOptionalExplicitClientSetResponse contains the response from method BodyOptionalityOptionalExplicitClient.Set. +type BodyOptionalityOptionalExplicitClientSetResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/parameters/bodyoptionalgroup/zz_version.go b/test/http-specs/parameters/bodyoptionalgroup/zz_version.go new file mode 100644 index 000000000000..747c2e8bed93 --- /dev/null +++ b/test/http-specs/parameters/bodyoptionalgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package bodyoptionalgroup + +const ( + moduleName = "bodyoptionalgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/parameters/collectionfmtgroup/LICENSE.txt b/test/http-specs/parameters/collectionfmtgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/parameters/collectionfmtgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/parameters/collectionfmtgroup/fake/zz_collectionformat_server.go b/test/http-specs/parameters/collectionfmtgroup/fake/zz_collectionformat_server.go new file mode 100644 index 000000000000..7c42716655da --- /dev/null +++ b/test/http-specs/parameters/collectionfmtgroup/fake/zz_collectionformat_server.go @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// CollectionFormatServer is a fake server for instances of the collectionfmtgroup.CollectionFormatClient type. +type CollectionFormatServer struct { + // CollectionFormatHeaderServer contains the fakes for client CollectionFormatHeaderClient + CollectionFormatHeaderServer CollectionFormatHeaderServer + + // CollectionFormatQueryServer contains the fakes for client CollectionFormatQueryClient + CollectionFormatQueryServer CollectionFormatQueryServer +} + +// NewCollectionFormatServerTransport creates a new instance of CollectionFormatServerTransport with the provided implementation. +// The returned CollectionFormatServerTransport instance is connected to an instance of collectionfmtgroup.CollectionFormatClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewCollectionFormatServerTransport(srv *CollectionFormatServer) *CollectionFormatServerTransport { + return &CollectionFormatServerTransport{srv: srv} +} + +// CollectionFormatServerTransport connects instances of collectionfmtgroup.CollectionFormatClient to instances of CollectionFormatServer. +// Don't use this type directly, use NewCollectionFormatServerTransport instead. +type CollectionFormatServerTransport struct { + srv *CollectionFormatServer + trMu sync.Mutex + trCollectionFormatHeaderServer *CollectionFormatHeaderServerTransport + trCollectionFormatQueryServer *CollectionFormatQueryServerTransport +} + +// Do implements the policy.Transporter interface for CollectionFormatServerTransport. +func (c *CollectionFormatServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (c *CollectionFormatServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "CollectionFormatHeaderClient": + initServer(&c.trMu, &c.trCollectionFormatHeaderServer, func() *CollectionFormatHeaderServerTransport { + return NewCollectionFormatHeaderServerTransport(&c.srv.CollectionFormatHeaderServer) + }) + resp, err = c.trCollectionFormatHeaderServer.Do(req) + case "CollectionFormatQueryClient": + initServer(&c.trMu, &c.trCollectionFormatQueryServer, func() *CollectionFormatQueryServerTransport { + return NewCollectionFormatQueryServerTransport(&c.srv.CollectionFormatQueryServer) + }) + resp, err = c.trCollectionFormatQueryServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to CollectionFormatServerTransport +var collectionFormatServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/parameters/collectionfmtgroup/fake/zz_collectionformatheader_server.go b/test/http-specs/parameters/collectionfmtgroup/fake/zz_collectionformatheader_server.go new file mode 100644 index 000000000000..67b660898176 --- /dev/null +++ b/test/http-specs/parameters/collectionfmtgroup/fake/zz_collectionformatheader_server.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "collectionfmtgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// CollectionFormatHeaderServer is a fake server for instances of the collectionfmtgroup.CollectionFormatHeaderClient type. +type CollectionFormatHeaderServer struct { + // CSV is the fake for method CollectionFormatHeaderClient.CSV + // HTTP status codes to indicate success: http.StatusNoContent + CSV func(ctx context.Context, colors []string, options *collectionfmtgroup.CollectionFormatHeaderClientCSVOptions) (resp azfake.Responder[collectionfmtgroup.CollectionFormatHeaderClientCSVResponse], errResp azfake.ErrorResponder) +} + +// NewCollectionFormatHeaderServerTransport creates a new instance of CollectionFormatHeaderServerTransport with the provided implementation. +// The returned CollectionFormatHeaderServerTransport instance is connected to an instance of collectionfmtgroup.CollectionFormatHeaderClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewCollectionFormatHeaderServerTransport(srv *CollectionFormatHeaderServer) *CollectionFormatHeaderServerTransport { + return &CollectionFormatHeaderServerTransport{srv: srv} +} + +// CollectionFormatHeaderServerTransport connects instances of collectionfmtgroup.CollectionFormatHeaderClient to instances of CollectionFormatHeaderServer. +// Don't use this type directly, use NewCollectionFormatHeaderServerTransport instead. +type CollectionFormatHeaderServerTransport struct { + srv *CollectionFormatHeaderServer +} + +// Do implements the policy.Transporter interface for CollectionFormatHeaderServerTransport. +func (c *CollectionFormatHeaderServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *CollectionFormatHeaderServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if collectionFormatHeaderServerTransportInterceptor != nil { + res.resp, res.err, intercepted = collectionFormatHeaderServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "CollectionFormatHeaderClient.CSV": + res.resp, res.err = c.dispatchCSV(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *CollectionFormatHeaderServerTransport) dispatchCSV(req *http.Request) (*http.Response, error) { + if c.srv.CSV == nil { + return nil, &nonRetriableError{errors.New("fake for method CSV not implemented")} + } + respr, errRespr := c.srv.CSV(req.Context(), splitHelper(getHeaderValue(req.Header, "colors"), ","), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to CollectionFormatHeaderServerTransport +var collectionFormatHeaderServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/parameters/collectionfmtgroup/fake/zz_collectionformatquery_server.go b/test/http-specs/parameters/collectionfmtgroup/fake/zz_collectionformatquery_server.go new file mode 100644 index 000000000000..3987d2510e14 --- /dev/null +++ b/test/http-specs/parameters/collectionfmtgroup/fake/zz_collectionformatquery_server.go @@ -0,0 +1,180 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "collectionfmtgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// CollectionFormatQueryServer is a fake server for instances of the collectionfmtgroup.CollectionFormatQueryClient type. +type CollectionFormatQueryServer struct { + // CSV is the fake for method CollectionFormatQueryClient.CSV + // HTTP status codes to indicate success: http.StatusNoContent + CSV func(ctx context.Context, colors []string, options *collectionfmtgroup.CollectionFormatQueryClientCSVOptions) (resp azfake.Responder[collectionfmtgroup.CollectionFormatQueryClientCSVResponse], errResp azfake.ErrorResponder) + + // Multi is the fake for method CollectionFormatQueryClient.Multi + // HTTP status codes to indicate success: http.StatusNoContent + Multi func(ctx context.Context, colors []string, options *collectionfmtgroup.CollectionFormatQueryClientMultiOptions) (resp azfake.Responder[collectionfmtgroup.CollectionFormatQueryClientMultiResponse], errResp azfake.ErrorResponder) + + // Pipes is the fake for method CollectionFormatQueryClient.Pipes + // HTTP status codes to indicate success: http.StatusNoContent + Pipes func(ctx context.Context, colors []string, options *collectionfmtgroup.CollectionFormatQueryClientPipesOptions) (resp azfake.Responder[collectionfmtgroup.CollectionFormatQueryClientPipesResponse], errResp azfake.ErrorResponder) + + // Ssv is the fake for method CollectionFormatQueryClient.Ssv + // HTTP status codes to indicate success: http.StatusNoContent + Ssv func(ctx context.Context, colors []string, options *collectionfmtgroup.CollectionFormatQueryClientSsvOptions) (resp azfake.Responder[collectionfmtgroup.CollectionFormatQueryClientSsvResponse], errResp azfake.ErrorResponder) +} + +// NewCollectionFormatQueryServerTransport creates a new instance of CollectionFormatQueryServerTransport with the provided implementation. +// The returned CollectionFormatQueryServerTransport instance is connected to an instance of collectionfmtgroup.CollectionFormatQueryClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewCollectionFormatQueryServerTransport(srv *CollectionFormatQueryServer) *CollectionFormatQueryServerTransport { + return &CollectionFormatQueryServerTransport{srv: srv} +} + +// CollectionFormatQueryServerTransport connects instances of collectionfmtgroup.CollectionFormatQueryClient to instances of CollectionFormatQueryServer. +// Don't use this type directly, use NewCollectionFormatQueryServerTransport instead. +type CollectionFormatQueryServerTransport struct { + srv *CollectionFormatQueryServer +} + +// Do implements the policy.Transporter interface for CollectionFormatQueryServerTransport. +func (c *CollectionFormatQueryServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *CollectionFormatQueryServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if collectionFormatQueryServerTransportInterceptor != nil { + res.resp, res.err, intercepted = collectionFormatQueryServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "CollectionFormatQueryClient.CSV": + res.resp, res.err = c.dispatchCSV(req) + case "CollectionFormatQueryClient.Multi": + res.resp, res.err = c.dispatchMulti(req) + case "CollectionFormatQueryClient.Pipes": + res.resp, res.err = c.dispatchPipes(req) + case "CollectionFormatQueryClient.Ssv": + res.resp, res.err = c.dispatchSsv(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *CollectionFormatQueryServerTransport) dispatchCSV(req *http.Request) (*http.Response, error) { + if c.srv.CSV == nil { + return nil, &nonRetriableError{errors.New("fake for method CSV not implemented")} + } + qp := req.URL.Query() + respr, errRespr := c.srv.CSV(req.Context(), splitHelper(qp.Get("colors"), ","), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *CollectionFormatQueryServerTransport) dispatchMulti(req *http.Request) (*http.Response, error) { + if c.srv.Multi == nil { + return nil, &nonRetriableError{errors.New("fake for method Multi not implemented")} + } + qp := req.URL.Query() + respr, errRespr := c.srv.Multi(req.Context(), qp["colors"], nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *CollectionFormatQueryServerTransport) dispatchPipes(req *http.Request) (*http.Response, error) { + if c.srv.Pipes == nil { + return nil, &nonRetriableError{errors.New("fake for method Pipes not implemented")} + } + qp := req.URL.Query() + respr, errRespr := c.srv.Pipes(req.Context(), splitHelper(qp.Get("colors"), "|"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *CollectionFormatQueryServerTransport) dispatchSsv(req *http.Request) (*http.Response, error) { + if c.srv.Ssv == nil { + return nil, &nonRetriableError{errors.New("fake for method Ssv not implemented")} + } + qp := req.URL.Query() + respr, errRespr := c.srv.Ssv(req.Context(), splitHelper(qp.Get("colors"), " "), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to CollectionFormatQueryServerTransport +var collectionFormatQueryServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/parameters/collectionfmtgroup/fake/zz_internal.go b/test/http-specs/parameters/collectionfmtgroup/fake/zz_internal.go new file mode 100644 index 000000000000..e07e08de861a --- /dev/null +++ b/test/http-specs/parameters/collectionfmtgroup/fake/zz_internal.go @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "strings" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getHeaderValue(h http.Header, k string) string { + v := h[k] + if len(v) == 0 { + return "" + } + return v[0] +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func splitHelper(s, sep string) []string { + if s == "" { + return nil + } + return strings.Split(s, sep) +} diff --git a/test/http-specs/parameters/collectionfmtgroup/go.mod b/test/http-specs/parameters/collectionfmtgroup/go.mod new file mode 100644 index 000000000000..e32b8db101ac --- /dev/null +++ b/test/http-specs/parameters/collectionfmtgroup/go.mod @@ -0,0 +1,17 @@ +module collectionfmtgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/parameters/collectionfmtgroup/go.sum b/test/http-specs/parameters/collectionfmtgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/parameters/collectionfmtgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/parameters/collectionfmtgroup/header_client_test.go b/test/http-specs/parameters/collectionfmtgroup/header_client_test.go new file mode 100644 index 000000000000..bffc6d080bc6 --- /dev/null +++ b/test/http-specs/parameters/collectionfmtgroup/header_client_test.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package collectionfmtgroup_test + +import ( + "collectionfmtgroup" + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestHeaderClient_CSV(t *testing.T) { + client, err := collectionfmtgroup.NewCollectionFormatClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewCollectionFormatHeaderClient().CSV(context.Background(), []string{"blue", "red", "green"}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/parameters/collectionfmtgroup/query_client_test.go b/test/http-specs/parameters/collectionfmtgroup/query_client_test.go new file mode 100644 index 000000000000..d62bc64e1903 --- /dev/null +++ b/test/http-specs/parameters/collectionfmtgroup/query_client_test.go @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package collectionfmtgroup_test + +import ( + "collectionfmtgroup" + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestQueryClient_CSV(t *testing.T) { + client, err := collectionfmtgroup.NewCollectionFormatClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewCollectionFormatQueryClient().CSV(context.Background(), []string{"blue", "red", "green"}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestQueryClient_Multi(t *testing.T) { + client, err := collectionfmtgroup.NewCollectionFormatClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewCollectionFormatQueryClient().Multi(context.Background(), []string{"blue", "red", "green"}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestQueryClient_Pipes(t *testing.T) { + client, err := collectionfmtgroup.NewCollectionFormatClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewCollectionFormatQueryClient().Pipes(context.Background(), []string{"blue", "red", "green"}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestQueryClient_Ssv(t *testing.T) { + client, err := collectionfmtgroup.NewCollectionFormatClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewCollectionFormatQueryClient().Ssv(context.Background(), []string{"blue", "red", "green"}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/parameters/collectionfmtgroup/testdata/_metadata.json b/test/http-specs/parameters/collectionfmtgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/parameters/collectionfmtgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/parameters/collectionfmtgroup/zz_collectionformat_client.go b/test/http-specs/parameters/collectionfmtgroup/zz_collectionformat_client.go new file mode 100644 index 000000000000..ef343a20bbb3 --- /dev/null +++ b/test/http-specs/parameters/collectionfmtgroup/zz_collectionformat_client.go @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package collectionfmtgroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// CollectionFormatClient - Test for collectionFormat. +// Don't use this type directly, use NewCollectionFormatClientWithNoCredential() instead. +type CollectionFormatClient struct { + internal *azcore.Client + endpoint string +} + +// CollectionFormatClientOptions contains the optional values for creating a [CollectionFormatClient]. +type CollectionFormatClientOptions struct { + azcore.ClientOptions +} + +// NewCollectionFormatClientWithNoCredential creates a new instance of CollectionFormatClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewCollectionFormatClientWithNoCredential(endpoint string, options *CollectionFormatClientOptions) (*CollectionFormatClient, error) { + if options == nil { + options = &CollectionFormatClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &CollectionFormatClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewCollectionFormatHeaderClient creates a new instance of [CollectionFormatHeaderClient]. +func (client *CollectionFormatClient) NewCollectionFormatHeaderClient() *CollectionFormatHeaderClient { + return &CollectionFormatHeaderClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewCollectionFormatQueryClient creates a new instance of [CollectionFormatQueryClient]. +func (client *CollectionFormatClient) NewCollectionFormatQueryClient() *CollectionFormatQueryClient { + return &CollectionFormatQueryClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/http-specs/parameters/collectionfmtgroup/zz_collectionformatheader_client.go b/test/http-specs/parameters/collectionfmtgroup/zz_collectionformatheader_client.go new file mode 100644 index 000000000000..7f13bf8af7b7 --- /dev/null +++ b/test/http-specs/parameters/collectionfmtgroup/zz_collectionformatheader_client.go @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package collectionfmtgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// CollectionFormatHeaderClient contains the methods for the CollectionFormatHeader group. +// Don't use this type directly, use [CollectionFormatClient.NewCollectionFormatHeaderClient] instead. +type CollectionFormatHeaderClient struct { + internal *azcore.Client + endpoint string +} + +// CSV - +// If the operation fails it returns an *azcore.ResponseError type. +// - colors - Possible values for colors are [blue,red,green] +// - options - CollectionFormatHeaderClientCSVOptions contains the optional parameters for the CollectionFormatHeaderClient.CSV +// method. +func (client *CollectionFormatHeaderClient) CSV(ctx context.Context, colors []string, options *CollectionFormatHeaderClientCSVOptions) (CollectionFormatHeaderClientCSVResponse, error) { + var err error + const operationName = "CollectionFormatHeaderClient.CSV" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.csvCreateRequest(ctx, colors, options) + if err != nil { + return CollectionFormatHeaderClientCSVResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CollectionFormatHeaderClientCSVResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return CollectionFormatHeaderClientCSVResponse{}, err + } + return CollectionFormatHeaderClientCSVResponse{}, nil +} + +// csvCreateRequest creates the CSV request. +func (client *CollectionFormatHeaderClient) csvCreateRequest(ctx context.Context, colors []string, _ *CollectionFormatHeaderClientCSVOptions) (*policy.Request, error) { + urlPath := "/parameters/collection-format/header/csv" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["colors"] = []string{strings.Join(colors, ",")} + return req, nil +} diff --git a/test/http-specs/parameters/collectionfmtgroup/zz_collectionformatquery_client.go b/test/http-specs/parameters/collectionfmtgroup/zz_collectionformatquery_client.go new file mode 100644 index 000000000000..796991d2d6ec --- /dev/null +++ b/test/http-specs/parameters/collectionfmtgroup/zz_collectionformatquery_client.go @@ -0,0 +1,179 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package collectionfmtgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// CollectionFormatQueryClient contains the methods for the CollectionFormatQuery group. +// Don't use this type directly, use [CollectionFormatClient.NewCollectionFormatQueryClient] instead. +type CollectionFormatQueryClient struct { + internal *azcore.Client + endpoint string +} + +// CSV - +// If the operation fails it returns an *azcore.ResponseError type. +// - colors - Possible values for colors are [blue,red,green] +// - options - CollectionFormatQueryClientCSVOptions contains the optional parameters for the CollectionFormatQueryClient.CSV +// method. +func (client *CollectionFormatQueryClient) CSV(ctx context.Context, colors []string, options *CollectionFormatQueryClientCSVOptions) (CollectionFormatQueryClientCSVResponse, error) { + var err error + const operationName = "CollectionFormatQueryClient.CSV" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.csvCreateRequest(ctx, colors, options) + if err != nil { + return CollectionFormatQueryClientCSVResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CollectionFormatQueryClientCSVResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return CollectionFormatQueryClientCSVResponse{}, err + } + return CollectionFormatQueryClientCSVResponse{}, nil +} + +// csvCreateRequest creates the CSV request. +func (client *CollectionFormatQueryClient) csvCreateRequest(ctx context.Context, colors []string, _ *CollectionFormatQueryClientCSVOptions) (*policy.Request, error) { + urlPath := "/parameters/collection-format/query/csv" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("colors", strings.Join(colors, ",")) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Multi - +// If the operation fails it returns an *azcore.ResponseError type. +// - colors - Possible values for colors are [blue,red,green] +// - options - CollectionFormatQueryClientMultiOptions contains the optional parameters for the CollectionFormatQueryClient.Multi +// method. +func (client *CollectionFormatQueryClient) Multi(ctx context.Context, colors []string, options *CollectionFormatQueryClientMultiOptions) (CollectionFormatQueryClientMultiResponse, error) { + var err error + const operationName = "CollectionFormatQueryClient.Multi" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.multiCreateRequest(ctx, colors, options) + if err != nil { + return CollectionFormatQueryClientMultiResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CollectionFormatQueryClientMultiResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return CollectionFormatQueryClientMultiResponse{}, err + } + return CollectionFormatQueryClientMultiResponse{}, nil +} + +// multiCreateRequest creates the Multi request. +func (client *CollectionFormatQueryClient) multiCreateRequest(ctx context.Context, colors []string, _ *CollectionFormatQueryClientMultiOptions) (*policy.Request, error) { + urlPath := "/parameters/collection-format/query/multi" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + for _, qv := range colors { + reqQP.Add("colors", qv) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Pipes - +// If the operation fails it returns an *azcore.ResponseError type. +// - colors - Possible values for colors are [blue,red,green] +// - options - CollectionFormatQueryClientPipesOptions contains the optional parameters for the CollectionFormatQueryClient.Pipes +// method. +func (client *CollectionFormatQueryClient) Pipes(ctx context.Context, colors []string, options *CollectionFormatQueryClientPipesOptions) (CollectionFormatQueryClientPipesResponse, error) { + var err error + const operationName = "CollectionFormatQueryClient.Pipes" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.pipesCreateRequest(ctx, colors, options) + if err != nil { + return CollectionFormatQueryClientPipesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CollectionFormatQueryClientPipesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return CollectionFormatQueryClientPipesResponse{}, err + } + return CollectionFormatQueryClientPipesResponse{}, nil +} + +// pipesCreateRequest creates the Pipes request. +func (client *CollectionFormatQueryClient) pipesCreateRequest(ctx context.Context, colors []string, _ *CollectionFormatQueryClientPipesOptions) (*policy.Request, error) { + urlPath := "/parameters/collection-format/query/pipes" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("colors", strings.Join(colors, "|")) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Ssv - +// If the operation fails it returns an *azcore.ResponseError type. +// - colors - Possible values for colors are [blue,red,green] +// - options - CollectionFormatQueryClientSsvOptions contains the optional parameters for the CollectionFormatQueryClient.Ssv +// method. +func (client *CollectionFormatQueryClient) Ssv(ctx context.Context, colors []string, options *CollectionFormatQueryClientSsvOptions) (CollectionFormatQueryClientSsvResponse, error) { + var err error + const operationName = "CollectionFormatQueryClient.Ssv" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.ssvCreateRequest(ctx, colors, options) + if err != nil { + return CollectionFormatQueryClientSsvResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CollectionFormatQueryClientSsvResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return CollectionFormatQueryClientSsvResponse{}, err + } + return CollectionFormatQueryClientSsvResponse{}, nil +} + +// ssvCreateRequest creates the Ssv request. +func (client *CollectionFormatQueryClient) ssvCreateRequest(ctx context.Context, colors []string, _ *CollectionFormatQueryClientSsvOptions) (*policy.Request, error) { + urlPath := "/parameters/collection-format/query/ssv" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("colors", strings.Join(colors, " ")) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/http-specs/parameters/collectionfmtgroup/zz_options.go b/test/http-specs/parameters/collectionfmtgroup/zz_options.go new file mode 100644 index 000000000000..90aa70d043a9 --- /dev/null +++ b/test/http-specs/parameters/collectionfmtgroup/zz_options.go @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package collectionfmtgroup + +// CollectionFormatHeaderClientCSVOptions contains the optional parameters for the CollectionFormatHeaderClient.CSV method. +type CollectionFormatHeaderClientCSVOptions struct { + // placeholder for future optional parameters +} + +// CollectionFormatQueryClientCSVOptions contains the optional parameters for the CollectionFormatQueryClient.CSV method. +type CollectionFormatQueryClientCSVOptions struct { + // placeholder for future optional parameters +} + +// CollectionFormatQueryClientMultiOptions contains the optional parameters for the CollectionFormatQueryClient.Multi method. +type CollectionFormatQueryClientMultiOptions struct { + // placeholder for future optional parameters +} + +// CollectionFormatQueryClientPipesOptions contains the optional parameters for the CollectionFormatQueryClient.Pipes method. +type CollectionFormatQueryClientPipesOptions struct { + // placeholder for future optional parameters +} + +// CollectionFormatQueryClientSsvOptions contains the optional parameters for the CollectionFormatQueryClient.Ssv method. +type CollectionFormatQueryClientSsvOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/parameters/collectionfmtgroup/zz_responses.go b/test/http-specs/parameters/collectionfmtgroup/zz_responses.go new file mode 100644 index 000000000000..37940b96dc30 --- /dev/null +++ b/test/http-specs/parameters/collectionfmtgroup/zz_responses.go @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package collectionfmtgroup + +// CollectionFormatHeaderClientCSVResponse contains the response from method CollectionFormatHeaderClient.CSV. +type CollectionFormatHeaderClientCSVResponse struct { + // placeholder for future response values +} + +// CollectionFormatQueryClientCSVResponse contains the response from method CollectionFormatQueryClient.CSV. +type CollectionFormatQueryClientCSVResponse struct { + // placeholder for future response values +} + +// CollectionFormatQueryClientMultiResponse contains the response from method CollectionFormatQueryClient.Multi. +type CollectionFormatQueryClientMultiResponse struct { + // placeholder for future response values +} + +// CollectionFormatQueryClientPipesResponse contains the response from method CollectionFormatQueryClient.Pipes. +type CollectionFormatQueryClientPipesResponse struct { + // placeholder for future response values +} + +// CollectionFormatQueryClientSsvResponse contains the response from method CollectionFormatQueryClient.Ssv. +type CollectionFormatQueryClientSsvResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/parameters/collectionfmtgroup/zz_version.go b/test/http-specs/parameters/collectionfmtgroup/zz_version.go new file mode 100644 index 000000000000..776d1412e7b5 --- /dev/null +++ b/test/http-specs/parameters/collectionfmtgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package collectionfmtgroup + +const ( + moduleName = "collectionfmtgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/parameters/pathgroup/LICENSE.txt b/test/http-specs/parameters/pathgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/parameters/pathgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/parameters/pathgroup/fake/zz_internal.go b/test/http-specs/parameters/pathgroup/fake/zz_internal.go new file mode 100644 index 000000000000..53ec711308cc --- /dev/null +++ b/test/http-specs/parameters/pathgroup/fake/zz_internal.go @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "reflect" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getOptional[T any](v T) *T { + if reflect.ValueOf(v).IsZero() { + return nil + } + return &v +} diff --git a/test/http-specs/parameters/pathgroup/fake/zz_path_server.go b/test/http-specs/parameters/pathgroup/fake/zz_path_server.go new file mode 100644 index 000000000000..7c1edb7b8ff1 --- /dev/null +++ b/test/http-specs/parameters/pathgroup/fake/zz_path_server.go @@ -0,0 +1,155 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "pathgroup" + "regexp" + "slices" +) + +// PathServer is a fake server for instances of the pathgroup.PathClient type. +type PathServer struct { + // Normal is the fake for method PathClient.Normal + // HTTP status codes to indicate success: http.StatusNoContent + Normal func(ctx context.Context, name string, options *pathgroup.PathClientNormalOptions) (resp azfake.Responder[pathgroup.PathClientNormalResponse], errResp azfake.ErrorResponder) + + // Optional is the fake for method PathClient.Optional + // HTTP status codes to indicate success: http.StatusNoContent + Optional func(ctx context.Context, options *pathgroup.PathClientOptionalOptions) (resp azfake.Responder[pathgroup.PathClientOptionalResponse], errResp azfake.ErrorResponder) +} + +// NewPathServerTransport creates a new instance of PathServerTransport with the provided implementation. +// The returned PathServerTransport instance is connected to an instance of pathgroup.PathClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewPathServerTransport(srv *PathServer) *PathServerTransport { + return &PathServerTransport{srv: srv} +} + +// PathServerTransport connects instances of pathgroup.PathClient to instances of PathServer. +// Don't use this type directly, use NewPathServerTransport instead. +type PathServerTransport struct { + srv *PathServer +} + +// Do implements the policy.Transporter interface for PathServerTransport. +func (p *PathServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return p.dispatchToMethodFake(req, method) +} + +func (p *PathServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if pathServerTransportInterceptor != nil { + res.resp, res.err, intercepted = pathServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "PathClient.Normal": + res.resp, res.err = p.dispatchNormal(req) + case "PathClient.Optional": + res.resp, res.err = p.dispatchOptional(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (p *PathServerTransport) dispatchNormal(req *http.Request) (*http.Response, error) { + if p.srv.Normal == nil { + return nil, &nonRetriableError{errors.New("fake for method Normal not implemented")} + } + const regexStr = `/parameters/path/normal/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("name")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.Normal(req.Context(), nameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (p *PathServerTransport) dispatchOptional(req *http.Request) (*http.Response, error) { + if p.srv.Optional == nil { + return nil, &nonRetriableError{errors.New("fake for method Optional not implemented")} + } + const regexStr = `/parameters/path/optional(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)?` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + nameUnescaped, err := url.PathUnescape(matches[regex.SubexpIndex("name")]) + if err != nil { + return nil, err + } + nameParam := getOptional(nameUnescaped) + var options *pathgroup.PathClientOptionalOptions + if nameParam != nil { + options = &pathgroup.PathClientOptionalOptions{ + Name: nameParam, + } + } + respr, errRespr := p.srv.Optional(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to PathServerTransport +var pathServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/parameters/pathgroup/go.mod b/test/http-specs/parameters/pathgroup/go.mod new file mode 100644 index 000000000000..1b16bb50cb7f --- /dev/null +++ b/test/http-specs/parameters/pathgroup/go.mod @@ -0,0 +1,17 @@ +module pathgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/parameters/pathgroup/go.sum b/test/http-specs/parameters/pathgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/parameters/pathgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/parameters/pathgroup/path_client_test.go b/test/http-specs/parameters/pathgroup/path_client_test.go new file mode 100644 index 000000000000..acd1a660bafd --- /dev/null +++ b/test/http-specs/parameters/pathgroup/path_client_test.go @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package pathgroup_test + +import ( + "context" + "pathgroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestNormal(t *testing.T) { + client, err := pathgroup.NewPathClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.Normal(context.Background(), "foo", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptional_none(t *testing.T) { + client, err := pathgroup.NewPathClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.Optional(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptional_some(t *testing.T) { + client, err := pathgroup.NewPathClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.Optional(context.Background(), &pathgroup.PathClientOptionalOptions{ + Name: to.Ptr("foo"), + }) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/parameters/pathgroup/testdata/_metadata.json b/test/http-specs/parameters/pathgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/parameters/pathgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/parameters/pathgroup/zz_options.go b/test/http-specs/parameters/pathgroup/zz_options.go new file mode 100644 index 000000000000..b6d36e54c450 --- /dev/null +++ b/test/http-specs/parameters/pathgroup/zz_options.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package pathgroup + +// PathClientNormalOptions contains the optional parameters for the PathClient.Normal method. +type PathClientNormalOptions struct { + // placeholder for future optional parameters +} + +// PathClientOptionalOptions contains the optional parameters for the PathClient.Optional method. +type PathClientOptionalOptions struct { + Name *string +} diff --git a/test/http-specs/parameters/pathgroup/zz_path_client.go b/test/http-specs/parameters/pathgroup/zz_path_client.go new file mode 100644 index 000000000000..ab410c97f185 --- /dev/null +++ b/test/http-specs/parameters/pathgroup/zz_path_client.go @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package pathgroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// PathClient - Test for path parameters cases. +// Don't use this type directly, use NewPathClientWithNoCredential() instead. +type PathClient struct { + internal *azcore.Client + endpoint string +} + +// PathClientOptions contains the optional values for creating a [PathClient]. +type PathClientOptions struct { + azcore.ClientOptions +} + +// NewPathClientWithNoCredential creates a new instance of PathClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewPathClientWithNoCredential(endpoint string, options *PathClientOptions) (*PathClient, error) { + if options == nil { + options = &PathClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &PathClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// Normal - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - PathClientNormalOptions contains the optional parameters for the PathClient.Normal method. +func (client *PathClient) Normal(ctx context.Context, name string, options *PathClientNormalOptions) (PathClientNormalResponse, error) { + var err error + const operationName = "PathClient.Normal" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.normalCreateRequest(ctx, name, options) + if err != nil { + return PathClientNormalResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PathClientNormalResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return PathClientNormalResponse{}, err + } + return PathClientNormalResponse{}, nil +} + +// normalCreateRequest creates the Normal request. +func (client *PathClient) normalCreateRequest(ctx context.Context, name string, _ *PathClientNormalOptions) (*policy.Request, error) { + urlPath := "/parameters/path/normal/{name}" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Optional - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - PathClientOptionalOptions contains the optional parameters for the PathClient.Optional method. +func (client *PathClient) Optional(ctx context.Context, options *PathClientOptionalOptions) (PathClientOptionalResponse, error) { + var err error + const operationName = "PathClient.Optional" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.optionalCreateRequest(ctx, options) + if err != nil { + return PathClientOptionalResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PathClientOptionalResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return PathClientOptionalResponse{}, err + } + return PathClientOptionalResponse{}, nil +} + +// optionalCreateRequest creates the Optional request. +func (client *PathClient) optionalCreateRequest(ctx context.Context, options *PathClientOptionalOptions) (*policy.Request, error) { + urlPath := "/parameters/path/optional{name}" + optionalName := "" + if options != nil && options.Name != nil { + optionalName = *options.Name + } + if len(optionalName) > 0 { + optionalName = "/" + url.PathEscape(optionalName) + } + urlPath = strings.ReplaceAll(urlPath, "{name}", optionalName) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/parameters/pathgroup/zz_responses.go b/test/http-specs/parameters/pathgroup/zz_responses.go new file mode 100644 index 000000000000..a165c5bf4e91 --- /dev/null +++ b/test/http-specs/parameters/pathgroup/zz_responses.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package pathgroup + +// PathClientNormalResponse contains the response from method PathClient.Normal. +type PathClientNormalResponse struct { + // placeholder for future response values +} + +// PathClientOptionalResponse contains the response from method PathClient.Optional. +type PathClientOptionalResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/parameters/pathgroup/zz_version.go b/test/http-specs/parameters/pathgroup/zz_version.go new file mode 100644 index 000000000000..18d150851f4a --- /dev/null +++ b/test/http-specs/parameters/pathgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package pathgroup + +const ( + moduleName = "pathgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/parameters/querygroup/LICENSE.txt b/test/http-specs/parameters/querygroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/parameters/querygroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/parameters/querygroup/fake/zz_internal.go b/test/http-specs/parameters/querygroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/http-specs/parameters/querygroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/http-specs/parameters/querygroup/fake/zz_query_server.go b/test/http-specs/parameters/querygroup/fake/zz_query_server.go new file mode 100644 index 000000000000..83417b2f60ed --- /dev/null +++ b/test/http-specs/parameters/querygroup/fake/zz_query_server.go @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// QueryServer is a fake server for instances of the querygroup.QueryClient type. +type QueryServer struct { + // QueryConstantServer contains the fakes for client QueryConstantClient + QueryConstantServer QueryConstantServer + + // QuerySpecialCharServer contains the fakes for client QuerySpecialCharClient + QuerySpecialCharServer QuerySpecialCharServer +} + +// NewQueryServerTransport creates a new instance of QueryServerTransport with the provided implementation. +// The returned QueryServerTransport instance is connected to an instance of querygroup.QueryClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewQueryServerTransport(srv *QueryServer) *QueryServerTransport { + return &QueryServerTransport{srv: srv} +} + +// QueryServerTransport connects instances of querygroup.QueryClient to instances of QueryServer. +// Don't use this type directly, use NewQueryServerTransport instead. +type QueryServerTransport struct { + srv *QueryServer + trMu sync.Mutex + trQueryConstantServer *QueryConstantServerTransport + trQuerySpecialCharServer *QuerySpecialCharServerTransport +} + +// Do implements the policy.Transporter interface for QueryServerTransport. +func (q *QueryServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return q.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (q *QueryServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "QueryConstantClient": + initServer(&q.trMu, &q.trQueryConstantServer, func() *QueryConstantServerTransport { + return NewQueryConstantServerTransport(&q.srv.QueryConstantServer) + }) + resp, err = q.trQueryConstantServer.Do(req) + case "QuerySpecialCharClient": + initServer(&q.trMu, &q.trQuerySpecialCharServer, func() *QuerySpecialCharServerTransport { + return NewQuerySpecialCharServerTransport(&q.srv.QuerySpecialCharServer) + }) + resp, err = q.trQuerySpecialCharServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to QueryServerTransport +var queryServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/parameters/querygroup/fake/zz_queryconstant_server.go b/test/http-specs/parameters/querygroup/fake/zz_queryconstant_server.go new file mode 100644 index 000000000000..4275a574a29a --- /dev/null +++ b/test/http-specs/parameters/querygroup/fake/zz_queryconstant_server.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "querygroup" + "slices" +) + +// QueryConstantServer is a fake server for instances of the querygroup.QueryConstantClient type. +type QueryConstantServer struct { + // Post is the fake for method QueryConstantClient.Post + // HTTP status codes to indicate success: http.StatusNoContent + Post func(ctx context.Context, options *querygroup.QueryConstantClientPostOptions) (resp azfake.Responder[querygroup.QueryConstantClientPostResponse], errResp azfake.ErrorResponder) +} + +// NewQueryConstantServerTransport creates a new instance of QueryConstantServerTransport with the provided implementation. +// The returned QueryConstantServerTransport instance is connected to an instance of querygroup.QueryConstantClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewQueryConstantServerTransport(srv *QueryConstantServer) *QueryConstantServerTransport { + return &QueryConstantServerTransport{srv: srv} +} + +// QueryConstantServerTransport connects instances of querygroup.QueryConstantClient to instances of QueryConstantServer. +// Don't use this type directly, use NewQueryConstantServerTransport instead. +type QueryConstantServerTransport struct { + srv *QueryConstantServer +} + +// Do implements the policy.Transporter interface for QueryConstantServerTransport. +func (q *QueryConstantServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return q.dispatchToMethodFake(req, method) +} + +func (q *QueryConstantServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if queryConstantServerTransportInterceptor != nil { + res.resp, res.err, intercepted = queryConstantServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "QueryConstantClient.Post": + res.resp, res.err = q.dispatchPost(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (q *QueryConstantServerTransport) dispatchPost(req *http.Request) (*http.Response, error) { + if q.srv.Post == nil { + return nil, &nonRetriableError{errors.New("fake for method Post not implemented")} + } + respr, errRespr := q.srv.Post(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to QueryConstantServerTransport +var queryConstantServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/parameters/querygroup/fake/zz_queryspecialchar_server.go b/test/http-specs/parameters/querygroup/fake/zz_queryspecialchar_server.go new file mode 100644 index 000000000000..d3a0a6202f91 --- /dev/null +++ b/test/http-specs/parameters/querygroup/fake/zz_queryspecialchar_server.go @@ -0,0 +1,102 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "querygroup" + "slices" +) + +// QuerySpecialCharServer is a fake server for instances of the querygroup.QuerySpecialCharClient type. +type QuerySpecialCharServer struct { + // DollarSign is the fake for method QuerySpecialCharClient.DollarSign + // HTTP status codes to indicate success: http.StatusNoContent + DollarSign func(ctx context.Context, filter string, options *querygroup.QuerySpecialCharClientDollarSignOptions) (resp azfake.Responder[querygroup.QuerySpecialCharClientDollarSignResponse], errResp azfake.ErrorResponder) +} + +// NewQuerySpecialCharServerTransport creates a new instance of QuerySpecialCharServerTransport with the provided implementation. +// The returned QuerySpecialCharServerTransport instance is connected to an instance of querygroup.QuerySpecialCharClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewQuerySpecialCharServerTransport(srv *QuerySpecialCharServer) *QuerySpecialCharServerTransport { + return &QuerySpecialCharServerTransport{srv: srv} +} + +// QuerySpecialCharServerTransport connects instances of querygroup.QuerySpecialCharClient to instances of QuerySpecialCharServer. +// Don't use this type directly, use NewQuerySpecialCharServerTransport instead. +type QuerySpecialCharServerTransport struct { + srv *QuerySpecialCharServer +} + +// Do implements the policy.Transporter interface for QuerySpecialCharServerTransport. +func (q *QuerySpecialCharServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return q.dispatchToMethodFake(req, method) +} + +func (q *QuerySpecialCharServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if querySpecialCharServerTransportInterceptor != nil { + res.resp, res.err, intercepted = querySpecialCharServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "QuerySpecialCharClient.DollarSign": + res.resp, res.err = q.dispatchDollarSign(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (q *QuerySpecialCharServerTransport) dispatchDollarSign(req *http.Request) (*http.Response, error) { + if q.srv.DollarSign == nil { + return nil, &nonRetriableError{errors.New("fake for method DollarSign not implemented")} + } + qp := req.URL.Query() + respr, errRespr := q.srv.DollarSign(req.Context(), qp.Get("$filter"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to QuerySpecialCharServerTransport +var querySpecialCharServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/parameters/querygroup/go.mod b/test/http-specs/parameters/querygroup/go.mod new file mode 100644 index 000000000000..6db20f1ee7c9 --- /dev/null +++ b/test/http-specs/parameters/querygroup/go.mod @@ -0,0 +1,17 @@ +module querygroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/parameters/querygroup/go.sum b/test/http-specs/parameters/querygroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/parameters/querygroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/parameters/querygroup/queryconstant_client_test.go b/test/http-specs/parameters/querygroup/queryconstant_client_test.go new file mode 100644 index 000000000000..31e8ae19b636 --- /dev/null +++ b/test/http-specs/parameters/querygroup/queryconstant_client_test.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package querygroup_test + +import ( + "context" + "querygroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestQueryConstantClient_Post(t *testing.T) { + client, err := querygroup.NewQueryClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewQueryConstantClient().Post(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/parameters/querygroup/testdata/_metadata.json b/test/http-specs/parameters/querygroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/parameters/querygroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/parameters/querygroup/zz_options.go b/test/http-specs/parameters/querygroup/zz_options.go new file mode 100644 index 000000000000..c12d9c1405e8 --- /dev/null +++ b/test/http-specs/parameters/querygroup/zz_options.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package querygroup + +// QueryConstantClientPostOptions contains the optional parameters for the QueryConstantClient.Post method. +type QueryConstantClientPostOptions struct { + // placeholder for future optional parameters +} + +// QuerySpecialCharClientDollarSignOptions contains the optional parameters for the QuerySpecialCharClient.DollarSign method. +type QuerySpecialCharClientDollarSignOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/parameters/querygroup/zz_query_client.go b/test/http-specs/parameters/querygroup/zz_query_client.go new file mode 100644 index 000000000000..1852c4f50a33 --- /dev/null +++ b/test/http-specs/parameters/querygroup/zz_query_client.go @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package querygroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// QueryClient - Test for query parameter cases. +// Don't use this type directly, use NewQueryClientWithNoCredential() instead. +type QueryClient struct { + internal *azcore.Client + endpoint string +} + +// QueryClientOptions contains the optional values for creating a [QueryClient]. +type QueryClientOptions struct { + azcore.ClientOptions +} + +// NewQueryClientWithNoCredential creates a new instance of QueryClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewQueryClientWithNoCredential(endpoint string, options *QueryClientOptions) (*QueryClient, error) { + if options == nil { + options = &QueryClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &QueryClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewQueryConstantClient creates a new instance of [QueryConstantClient]. +func (client *QueryClient) NewQueryConstantClient() *QueryConstantClient { + return &QueryConstantClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewQuerySpecialCharClient creates a new instance of [QuerySpecialCharClient]. +func (client *QueryClient) NewQuerySpecialCharClient() *QuerySpecialCharClient { + return &QuerySpecialCharClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/http-specs/parameters/querygroup/zz_queryconstant_client.go b/test/http-specs/parameters/querygroup/zz_queryconstant_client.go new file mode 100644 index 000000000000..f246c303b76f --- /dev/null +++ b/test/http-specs/parameters/querygroup/zz_queryconstant_client.go @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package querygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// QueryConstantClient - Constant query parameter verification +// Don't use this type directly, use [QueryClient.NewQueryConstantClient] instead. +type QueryConstantClient struct { + internal *azcore.Client + endpoint string +} + +// Post - post constant query value +// If the operation fails it returns an *azcore.ResponseError type. +// - options - QueryConstantClientPostOptions contains the optional parameters for the QueryConstantClient.Post method. +func (client *QueryConstantClient) Post(ctx context.Context, options *QueryConstantClientPostOptions) (QueryConstantClientPostResponse, error) { + var err error + const operationName = "QueryConstantClient.Post" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.postCreateRequest(ctx, options) + if err != nil { + return QueryConstantClientPostResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return QueryConstantClientPostResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return QueryConstantClientPostResponse{}, err + } + return QueryConstantClientPostResponse{}, nil +} + +// postCreateRequest creates the Post request. +func (client *QueryConstantClient) postCreateRequest(ctx context.Context, _ *QueryConstantClientPostOptions) (*policy.Request, error) { + urlPath := "/parameters/query/constant" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("queryParam", "constantValue") + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/http-specs/parameters/querygroup/zz_queryspecialchar_client.go b/test/http-specs/parameters/querygroup/zz_queryspecialchar_client.go new file mode 100644 index 000000000000..26da58d65026 --- /dev/null +++ b/test/http-specs/parameters/querygroup/zz_queryspecialchar_client.go @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package querygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// QuerySpecialCharClient - Special char query parameter verification +// Don't use this type directly, use [QueryClient.NewQuerySpecialCharClient] instead. +type QuerySpecialCharClient struct { + internal *azcore.Client + endpoint string +} + +// DollarSign - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - QuerySpecialCharClientDollarSignOptions contains the optional parameters for the QuerySpecialCharClient.DollarSign +// method. +func (client *QuerySpecialCharClient) DollarSign(ctx context.Context, filter string, options *QuerySpecialCharClientDollarSignOptions) (QuerySpecialCharClientDollarSignResponse, error) { + var err error + const operationName = "QuerySpecialCharClient.DollarSign" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.dollarSignCreateRequest(ctx, filter, options) + if err != nil { + return QuerySpecialCharClientDollarSignResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return QuerySpecialCharClientDollarSignResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return QuerySpecialCharClientDollarSignResponse{}, err + } + return QuerySpecialCharClientDollarSignResponse{}, nil +} + +// dollarSignCreateRequest creates the DollarSign request. +func (client *QuerySpecialCharClient) dollarSignCreateRequest(ctx context.Context, filter string, _ *QuerySpecialCharClientDollarSignOptions) (*policy.Request, error) { + urlPath := "/parameters/query/special-char/dollarSign" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("$filter", filter) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/http-specs/parameters/querygroup/zz_responses.go b/test/http-specs/parameters/querygroup/zz_responses.go new file mode 100644 index 000000000000..955bbba03efa --- /dev/null +++ b/test/http-specs/parameters/querygroup/zz_responses.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package querygroup + +// QueryConstantClientPostResponse contains the response from method QueryConstantClient.Post. +type QueryConstantClientPostResponse struct { + // placeholder for future response values +} + +// QuerySpecialCharClientDollarSignResponse contains the response from method QuerySpecialCharClient.DollarSign. +type QuerySpecialCharClientDollarSignResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/parameters/querygroup/zz_version.go b/test/http-specs/parameters/querygroup/zz_version.go new file mode 100644 index 000000000000..90f71609542b --- /dev/null +++ b/test/http-specs/parameters/querygroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package querygroup + +const ( + moduleName = "querygroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/parameters/spreadgroup/LICENSE.txt b/test/http-specs/parameters/spreadgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/parameters/spreadgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/parameters/spreadgroup/fake/zz_internal.go b/test/http-specs/parameters/spreadgroup/fake/zz_internal.go new file mode 100644 index 000000000000..df56a9f6266b --- /dev/null +++ b/test/http-specs/parameters/spreadgroup/fake/zz_internal.go @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getHeaderValue(h http.Header, k string) string { + v := h[k] + if len(v) == 0 { + return "" + } + return v[0] +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/http-specs/parameters/spreadgroup/fake/zz_spread_server.go b/test/http-specs/parameters/spreadgroup/fake/zz_spread_server.go new file mode 100644 index 000000000000..e66c3710edaf --- /dev/null +++ b/test/http-specs/parameters/spreadgroup/fake/zz_spread_server.go @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// SpreadServer is a fake server for instances of the spreadgroup.SpreadClient type. +type SpreadServer struct { + // SpreadAliasServer contains the fakes for client SpreadAliasClient + SpreadAliasServer SpreadAliasServer + + // SpreadModelServer contains the fakes for client SpreadModelClient + SpreadModelServer SpreadModelServer +} + +// NewSpreadServerTransport creates a new instance of SpreadServerTransport with the provided implementation. +// The returned SpreadServerTransport instance is connected to an instance of spreadgroup.SpreadClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSpreadServerTransport(srv *SpreadServer) *SpreadServerTransport { + return &SpreadServerTransport{srv: srv} +} + +// SpreadServerTransport connects instances of spreadgroup.SpreadClient to instances of SpreadServer. +// Don't use this type directly, use NewSpreadServerTransport instead. +type SpreadServerTransport struct { + srv *SpreadServer + trMu sync.Mutex + trSpreadAliasServer *SpreadAliasServerTransport + trSpreadModelServer *SpreadModelServerTransport +} + +// Do implements the policy.Transporter interface for SpreadServerTransport. +func (s *SpreadServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (s *SpreadServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "SpreadAliasClient": + initServer(&s.trMu, &s.trSpreadAliasServer, func() *SpreadAliasServerTransport { + return NewSpreadAliasServerTransport(&s.srv.SpreadAliasServer) + }) + resp, err = s.trSpreadAliasServer.Do(req) + case "SpreadModelClient": + initServer(&s.trMu, &s.trSpreadModelServer, func() *SpreadModelServerTransport { + return NewSpreadModelServerTransport(&s.srv.SpreadModelServer) + }) + resp, err = s.trSpreadModelServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to SpreadServerTransport +var spreadServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/parameters/spreadgroup/fake/zz_spreadalias_server.go b/test/http-specs/parameters/spreadgroup/fake/zz_spreadalias_server.go new file mode 100644 index 000000000000..cc6efdfe7b32 --- /dev/null +++ b/test/http-specs/parameters/spreadgroup/fake/zz_spreadalias_server.go @@ -0,0 +1,289 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" + "spreadgroup" +) + +// SpreadAliasServer is a fake server for instances of the spreadgroup.SpreadAliasClient type. +type SpreadAliasServer struct { + // SpreadAsRequestBody is the fake for method SpreadAliasClient.SpreadAsRequestBody + // HTTP status codes to indicate success: http.StatusNoContent + SpreadAsRequestBody func(ctx context.Context, name string, options *spreadgroup.SpreadAliasClientSpreadAsRequestBodyOptions) (resp azfake.Responder[spreadgroup.SpreadAliasClientSpreadAsRequestBodyResponse], errResp azfake.ErrorResponder) + + // SpreadAsRequestParameter is the fake for method SpreadAliasClient.SpreadAsRequestParameter + // HTTP status codes to indicate success: http.StatusNoContent + SpreadAsRequestParameter func(ctx context.Context, id string, xMSTestHeader string, name string, options *spreadgroup.SpreadAliasClientSpreadAsRequestParameterOptions) (resp azfake.Responder[spreadgroup.SpreadAliasClientSpreadAsRequestParameterResponse], errResp azfake.ErrorResponder) + + // SpreadParameterWithInnerAlias is the fake for method SpreadAliasClient.SpreadParameterWithInnerAlias + // HTTP status codes to indicate success: http.StatusNoContent + SpreadParameterWithInnerAlias func(ctx context.Context, id string, name string, age int32, xMSTestHeader string, options *spreadgroup.SpreadAliasClientSpreadParameterWithInnerAliasOptions) (resp azfake.Responder[spreadgroup.SpreadAliasClientSpreadParameterWithInnerAliasResponse], errResp azfake.ErrorResponder) + + // SpreadParameterWithInnerModel is the fake for method SpreadAliasClient.SpreadParameterWithInnerModel + // HTTP status codes to indicate success: http.StatusNoContent + SpreadParameterWithInnerModel func(ctx context.Context, id string, name string, xMSTestHeader string, options *spreadgroup.SpreadAliasClientSpreadParameterWithInnerModelOptions) (resp azfake.Responder[spreadgroup.SpreadAliasClientSpreadParameterWithInnerModelResponse], errResp azfake.ErrorResponder) + + // SpreadWithMultipleParameters is the fake for method SpreadAliasClient.SpreadWithMultipleParameters + // HTTP status codes to indicate success: http.StatusNoContent + SpreadWithMultipleParameters func(ctx context.Context, id string, xMSTestHeader string, requiredString string, requiredIntList []int32, options *spreadgroup.SpreadAliasClientSpreadWithMultipleParametersOptions) (resp azfake.Responder[spreadgroup.SpreadAliasClientSpreadWithMultipleParametersResponse], errResp azfake.ErrorResponder) +} + +// NewSpreadAliasServerTransport creates a new instance of SpreadAliasServerTransport with the provided implementation. +// The returned SpreadAliasServerTransport instance is connected to an instance of spreadgroup.SpreadAliasClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSpreadAliasServerTransport(srv *SpreadAliasServer) *SpreadAliasServerTransport { + return &SpreadAliasServerTransport{srv: srv} +} + +// SpreadAliasServerTransport connects instances of spreadgroup.SpreadAliasClient to instances of SpreadAliasServer. +// Don't use this type directly, use NewSpreadAliasServerTransport instead. +type SpreadAliasServerTransport struct { + srv *SpreadAliasServer +} + +// Do implements the policy.Transporter interface for SpreadAliasServerTransport. +func (s *SpreadAliasServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *SpreadAliasServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if spreadAliasServerTransportInterceptor != nil { + res.resp, res.err, intercepted = spreadAliasServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SpreadAliasClient.SpreadAsRequestBody": + res.resp, res.err = s.dispatchSpreadAsRequestBody(req) + case "SpreadAliasClient.SpreadAsRequestParameter": + res.resp, res.err = s.dispatchSpreadAsRequestParameter(req) + case "SpreadAliasClient.SpreadParameterWithInnerAlias": + res.resp, res.err = s.dispatchSpreadParameterWithInnerAlias(req) + case "SpreadAliasClient.SpreadParameterWithInnerModel": + res.resp, res.err = s.dispatchSpreadParameterWithInnerModel(req) + case "SpreadAliasClient.SpreadWithMultipleParameters": + res.resp, res.err = s.dispatchSpreadWithMultipleParameters(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *SpreadAliasServerTransport) dispatchSpreadAsRequestBody(req *http.Request) (*http.Response, error) { + if s.srv.SpreadAsRequestBody == nil { + return nil, &nonRetriableError{errors.New("fake for method SpreadAsRequestBody not implemented")} + } + type partialBodyParams struct { + Name string `json:"name"` + } + body, err := server.UnmarshalRequestAsJSON[partialBodyParams](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.SpreadAsRequestBody(req.Context(), body.Name, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpreadAliasServerTransport) dispatchSpreadAsRequestParameter(req *http.Request) (*http.Response, error) { + if s.srv.SpreadAsRequestParameter == nil { + return nil, &nonRetriableError{errors.New("fake for method SpreadAsRequestParameter not implemented")} + } + const regexStr = `/parameters/spread/alias/request-parameter/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + type partialBodyParams struct { + Name string `json:"name"` + } + body, err := server.UnmarshalRequestAsJSON[partialBodyParams](req) + if err != nil { + return nil, err + } + idParam, err := url.PathUnescape(matches[regex.SubexpIndex("id")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.SpreadAsRequestParameter(req.Context(), idParam, getHeaderValue(req.Header, "x-ms-test-header"), body.Name, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpreadAliasServerTransport) dispatchSpreadParameterWithInnerAlias(req *http.Request) (*http.Response, error) { + if s.srv.SpreadParameterWithInnerAlias == nil { + return nil, &nonRetriableError{errors.New("fake for method SpreadParameterWithInnerAlias not implemented")} + } + const regexStr = `/parameters/spread/alias/inner-alias-parameter/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + type partialBodyParams struct { + Name string `json:"name"` + Age int32 `json:"age"` + } + body, err := server.UnmarshalRequestAsJSON[partialBodyParams](req) + if err != nil { + return nil, err + } + idParam, err := url.PathUnescape(matches[regex.SubexpIndex("id")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.SpreadParameterWithInnerAlias(req.Context(), idParam, body.Name, body.Age, getHeaderValue(req.Header, "x-ms-test-header"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpreadAliasServerTransport) dispatchSpreadParameterWithInnerModel(req *http.Request) (*http.Response, error) { + if s.srv.SpreadParameterWithInnerModel == nil { + return nil, &nonRetriableError{errors.New("fake for method SpreadParameterWithInnerModel not implemented")} + } + const regexStr = `/parameters/spread/alias/inner-model-parameter/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + type partialBodyParams struct { + Name string `json:"name"` + } + body, err := server.UnmarshalRequestAsJSON[partialBodyParams](req) + if err != nil { + return nil, err + } + idParam, err := url.PathUnescape(matches[regex.SubexpIndex("id")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.SpreadParameterWithInnerModel(req.Context(), idParam, body.Name, getHeaderValue(req.Header, "x-ms-test-header"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpreadAliasServerTransport) dispatchSpreadWithMultipleParameters(req *http.Request) (*http.Response, error) { + if s.srv.SpreadWithMultipleParameters == nil { + return nil, &nonRetriableError{errors.New("fake for method SpreadWithMultipleParameters not implemented")} + } + const regexStr = `/parameters/spread/alias/multiple-parameters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + type partialBodyParams struct { + RequiredString string `json:"requiredString"` + OptionalInt *int32 `json:"optionalInt"` + RequiredIntList []int32 `json:"requiredIntList"` + OptionalStringList []string `json:"optionalStringList"` + } + body, err := server.UnmarshalRequestAsJSON[partialBodyParams](req) + if err != nil { + return nil, err + } + idParam, err := url.PathUnescape(matches[regex.SubexpIndex("id")]) + if err != nil { + return nil, err + } + var options *spreadgroup.SpreadAliasClientSpreadWithMultipleParametersOptions + if body.OptionalInt != nil || len(body.OptionalStringList) > 0 { + options = &spreadgroup.SpreadAliasClientSpreadWithMultipleParametersOptions{ + OptionalInt: body.OptionalInt, + OptionalStringList: body.OptionalStringList, + } + } + respr, errRespr := s.srv.SpreadWithMultipleParameters(req.Context(), idParam, getHeaderValue(req.Header, "x-ms-test-header"), body.RequiredString, body.RequiredIntList, options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SpreadAliasServerTransport +var spreadAliasServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/parameters/spreadgroup/fake/zz_spreadmodel_server.go b/test/http-specs/parameters/spreadgroup/fake/zz_spreadmodel_server.go new file mode 100644 index 000000000000..00e5b0515869 --- /dev/null +++ b/test/http-specs/parameters/spreadgroup/fake/zz_spreadmodel_server.go @@ -0,0 +1,255 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" + "spreadgroup" +) + +// SpreadModelServer is a fake server for instances of the spreadgroup.SpreadModelClient type. +type SpreadModelServer struct { + // SpreadAsRequestBody is the fake for method SpreadModelClient.SpreadAsRequestBody + // HTTP status codes to indicate success: http.StatusNoContent + SpreadAsRequestBody func(ctx context.Context, name string, options *spreadgroup.SpreadModelClientSpreadAsRequestBodyOptions) (resp azfake.Responder[spreadgroup.SpreadModelClientSpreadAsRequestBodyResponse], errResp azfake.ErrorResponder) + + // SpreadCompositeRequest is the fake for method SpreadModelClient.SpreadCompositeRequest + // HTTP status codes to indicate success: http.StatusNoContent + SpreadCompositeRequest func(ctx context.Context, name string, testHeader string, body spreadgroup.BodyParameter, options *spreadgroup.SpreadModelClientSpreadCompositeRequestOptions) (resp azfake.Responder[spreadgroup.SpreadModelClientSpreadCompositeRequestResponse], errResp azfake.ErrorResponder) + + // SpreadCompositeRequestMix is the fake for method SpreadModelClient.SpreadCompositeRequestMix + // HTTP status codes to indicate success: http.StatusNoContent + SpreadCompositeRequestMix func(ctx context.Context, name string, testHeader string, prop string, options *spreadgroup.SpreadModelClientSpreadCompositeRequestMixOptions) (resp azfake.Responder[spreadgroup.SpreadModelClientSpreadCompositeRequestMixResponse], errResp azfake.ErrorResponder) + + // SpreadCompositeRequestOnlyWithBody is the fake for method SpreadModelClient.SpreadCompositeRequestOnlyWithBody + // HTTP status codes to indicate success: http.StatusNoContent + SpreadCompositeRequestOnlyWithBody func(ctx context.Context, body spreadgroup.BodyParameter, options *spreadgroup.SpreadModelClientSpreadCompositeRequestOnlyWithBodyOptions) (resp azfake.Responder[spreadgroup.SpreadModelClientSpreadCompositeRequestOnlyWithBodyResponse], errResp azfake.ErrorResponder) + + // SpreadCompositeRequestWithoutBody is the fake for method SpreadModelClient.SpreadCompositeRequestWithoutBody + // HTTP status codes to indicate success: http.StatusNoContent + SpreadCompositeRequestWithoutBody func(ctx context.Context, name string, testHeader string, options *spreadgroup.SpreadModelClientSpreadCompositeRequestWithoutBodyOptions) (resp azfake.Responder[spreadgroup.SpreadModelClientSpreadCompositeRequestWithoutBodyResponse], errResp azfake.ErrorResponder) +} + +// NewSpreadModelServerTransport creates a new instance of SpreadModelServerTransport with the provided implementation. +// The returned SpreadModelServerTransport instance is connected to an instance of spreadgroup.SpreadModelClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSpreadModelServerTransport(srv *SpreadModelServer) *SpreadModelServerTransport { + return &SpreadModelServerTransport{srv: srv} +} + +// SpreadModelServerTransport connects instances of spreadgroup.SpreadModelClient to instances of SpreadModelServer. +// Don't use this type directly, use NewSpreadModelServerTransport instead. +type SpreadModelServerTransport struct { + srv *SpreadModelServer +} + +// Do implements the policy.Transporter interface for SpreadModelServerTransport. +func (s *SpreadModelServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *SpreadModelServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if spreadModelServerTransportInterceptor != nil { + res.resp, res.err, intercepted = spreadModelServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SpreadModelClient.SpreadAsRequestBody": + res.resp, res.err = s.dispatchSpreadAsRequestBody(req) + case "SpreadModelClient.SpreadCompositeRequest": + res.resp, res.err = s.dispatchSpreadCompositeRequest(req) + case "SpreadModelClient.SpreadCompositeRequestMix": + res.resp, res.err = s.dispatchSpreadCompositeRequestMix(req) + case "SpreadModelClient.SpreadCompositeRequestOnlyWithBody": + res.resp, res.err = s.dispatchSpreadCompositeRequestOnlyWithBody(req) + case "SpreadModelClient.SpreadCompositeRequestWithoutBody": + res.resp, res.err = s.dispatchSpreadCompositeRequestWithoutBody(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *SpreadModelServerTransport) dispatchSpreadAsRequestBody(req *http.Request) (*http.Response, error) { + if s.srv.SpreadAsRequestBody == nil { + return nil, &nonRetriableError{errors.New("fake for method SpreadAsRequestBody not implemented")} + } + type partialBodyParams struct { + Name string `json:"name"` + } + body, err := server.UnmarshalRequestAsJSON[partialBodyParams](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.SpreadAsRequestBody(req.Context(), body.Name, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpreadModelServerTransport) dispatchSpreadCompositeRequest(req *http.Request) (*http.Response, error) { + if s.srv.SpreadCompositeRequest == nil { + return nil, &nonRetriableError{errors.New("fake for method SpreadCompositeRequest not implemented")} + } + const regexStr = `/parameters/spread/model/composite-request/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[spreadgroup.BodyParameter](req) + if err != nil { + return nil, err + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("name")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.SpreadCompositeRequest(req.Context(), nameParam, getHeaderValue(req.Header, "test-header"), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpreadModelServerTransport) dispatchSpreadCompositeRequestMix(req *http.Request) (*http.Response, error) { + if s.srv.SpreadCompositeRequestMix == nil { + return nil, &nonRetriableError{errors.New("fake for method SpreadCompositeRequestMix not implemented")} + } + const regexStr = `/parameters/spread/model/composite-request-mix/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + type partialBodyParams struct { + Prop string `json:"prop"` + } + body, err := server.UnmarshalRequestAsJSON[partialBodyParams](req) + if err != nil { + return nil, err + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("name")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.SpreadCompositeRequestMix(req.Context(), nameParam, getHeaderValue(req.Header, "test-header"), body.Prop, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpreadModelServerTransport) dispatchSpreadCompositeRequestOnlyWithBody(req *http.Request) (*http.Response, error) { + if s.srv.SpreadCompositeRequestOnlyWithBody == nil { + return nil, &nonRetriableError{errors.New("fake for method SpreadCompositeRequestOnlyWithBody not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[spreadgroup.BodyParameter](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.SpreadCompositeRequestOnlyWithBody(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpreadModelServerTransport) dispatchSpreadCompositeRequestWithoutBody(req *http.Request) (*http.Response, error) { + if s.srv.SpreadCompositeRequestWithoutBody == nil { + return nil, &nonRetriableError{errors.New("fake for method SpreadCompositeRequestWithoutBody not implemented")} + } + const regexStr = `/parameters/spread/model/composite-request-without-body/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("name")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.SpreadCompositeRequestWithoutBody(req.Context(), nameParam, getHeaderValue(req.Header, "test-header"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SpreadModelServerTransport +var spreadModelServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/parameters/spreadgroup/fakes_test.go b/test/http-specs/parameters/spreadgroup/fakes_test.go new file mode 100644 index 000000000000..80dd4aa37415 --- /dev/null +++ b/test/http-specs/parameters/spreadgroup/fakes_test.go @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package spreadgroup_test + +import ( + "context" + "net/http" + "spreadgroup" + "spreadgroup/fake" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/stretchr/testify/require" +) + +func TestFake_SpreadWithMultipleParameters(t *testing.T) { + var ( + idVal = "id" + header = "header" + requiredString = "prop1" + optionalInt = int32(1) + requiredIntList = []int32{1, 2} + optionalStringList = []string{"a", "b"} + ) + server := fake.SpreadAliasServer{ + SpreadWithMultipleParameters: func(ctx context.Context, id string, xMSTestHeader string, requiredString string, requiredIntList []int32, options *spreadgroup.SpreadAliasClientSpreadWithMultipleParametersOptions) (resp azfake.Responder[spreadgroup.SpreadAliasClientSpreadWithMultipleParametersResponse], errResp azfake.ErrorResponder) { + require.EqualValues(t, idVal, id) + require.EqualValues(t, header, xMSTestHeader) + require.EqualValues(t, requiredString, requiredString) + require.EqualValues(t, requiredIntList, requiredIntList) + require.NotNil(t, options) + require.NotNil(t, options.OptionalInt) + require.EqualValues(t, optionalInt, *options.OptionalInt) + require.EqualValues(t, optionalStringList, options.OptionalStringList) + resp.SetResponse(http.StatusNoContent, spreadgroup.SpreadAliasClientSpreadWithMultipleParametersResponse{}, nil) + return + }, + } + client, err := spreadgroup.NewSpreadClientWithNoCredential("http://localhost:3000", &spreadgroup.SpreadClientOptions{ + azcore.ClientOptions{ + Transport: fake.NewSpreadAliasServerTransport(&server), + }, + }) + require.NoError(t, err) + + _, err = client.NewSpreadAliasClient().SpreadWithMultipleParameters(context.Background(), idVal, header, requiredString, requiredIntList, &spreadgroup.SpreadAliasClientSpreadWithMultipleParametersOptions{ + OptionalInt: &optionalInt, + OptionalStringList: optionalStringList, + }) + require.NoError(t, err) +} diff --git a/test/http-specs/parameters/spreadgroup/go.mod b/test/http-specs/parameters/spreadgroup/go.mod new file mode 100644 index 000000000000..87921b7c608a --- /dev/null +++ b/test/http-specs/parameters/spreadgroup/go.mod @@ -0,0 +1,17 @@ +module spreadgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/parameters/spreadgroup/go.sum b/test/http-specs/parameters/spreadgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/parameters/spreadgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/parameters/spreadgroup/spreadalias_client_test.go b/test/http-specs/parameters/spreadgroup/spreadalias_client_test.go new file mode 100644 index 000000000000..63b8caed4605 --- /dev/null +++ b/test/http-specs/parameters/spreadgroup/spreadalias_client_test.go @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package spreadgroup_test + +import ( + "context" + "spreadgroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestSpreadAliasClient_SpreadAsRequestBody(t *testing.T) { + client, err := spreadgroup.NewSpreadClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpreadAliasClient().SpreadAsRequestBody(context.Background(), "foo", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestSpreadAliasClient_SpreadAsRequestParameter(t *testing.T) { + client, err := spreadgroup.NewSpreadClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpreadAliasClient().SpreadAsRequestParameter(context.Background(), "1", "bar", "foo", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestSpreadAliasClient_SpreadWithMultipleParameters(t *testing.T) { + client, err := spreadgroup.NewSpreadClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpreadAliasClient().SpreadWithMultipleParameters(context.Background(), "1", "bar", "foo", []int32{1, 2}, &spreadgroup.SpreadAliasClientSpreadWithMultipleParametersOptions{ + OptionalInt: to.Ptr[int32](1), + OptionalStringList: []string{"foo", "bar"}, + }) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestSpreadAliasClient_SpreadWithInnerAlias(t *testing.T) { + client, err := spreadgroup.NewSpreadClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + _, err = client.NewSpreadAliasClient().SpreadParameterWithInnerAlias(context.Background(), "1", "foo", 1, "bar", nil) + require.NoError(t, err) +} + +func TestSpreadAliasClient_SpreadWithInnerModel(t *testing.T) { + client, err := spreadgroup.NewSpreadClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + _, err = client.NewSpreadAliasClient().SpreadParameterWithInnerModel(context.Background(), "1", "foo", "bar", nil) + require.NoError(t, err) +} diff --git a/test/http-specs/parameters/spreadgroup/spreadmodel_client_test.go b/test/http-specs/parameters/spreadgroup/spreadmodel_client_test.go new file mode 100644 index 000000000000..9e6699325502 --- /dev/null +++ b/test/http-specs/parameters/spreadgroup/spreadmodel_client_test.go @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package spreadgroup_test + +import ( + "context" + "spreadgroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestSpreadModelClient_SpreadAsRequestBody(t *testing.T) { + client, err := spreadgroup.NewSpreadClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpreadModelClient().SpreadAsRequestBody(context.Background(), "foo", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestSpreadModelClient_SpreadCompositeRequest(t *testing.T) { + client, err := spreadgroup.NewSpreadClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpreadModelClient().SpreadCompositeRequest(context.Background(), "foo", "bar", spreadgroup.BodyParameter{ + Name: to.Ptr("foo"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestSpreadModelClient_SpreadCompositeRequestMix(t *testing.T) { + client, err := spreadgroup.NewSpreadClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpreadModelClient().SpreadCompositeRequestMix(context.Background(), "foo", "bar", "foo", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestSpreadModelClient_SpreadCompositeRequestOnlyWithBody(t *testing.T) { + client, err := spreadgroup.NewSpreadClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpreadModelClient().SpreadCompositeRequestOnlyWithBody(context.Background(), spreadgroup.BodyParameter{ + Name: to.Ptr("foo"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestSpreadModelClient_SpreadCompositeRequestWithoutBody(t *testing.T) { + client, err := spreadgroup.NewSpreadClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpreadModelClient().SpreadCompositeRequestWithoutBody(context.Background(), "foo", "bar", nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/parameters/spreadgroup/testdata/_metadata.json b/test/http-specs/parameters/spreadgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/parameters/spreadgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/parameters/spreadgroup/zz_models.go b/test/http-specs/parameters/spreadgroup/zz_models.go new file mode 100644 index 000000000000..5fa2bb5cf39c --- /dev/null +++ b/test/http-specs/parameters/spreadgroup/zz_models.go @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package spreadgroup + +// BodyParameter - This is a simple model. +type BodyParameter struct { + // REQUIRED + Name *string +} diff --git a/test/http-specs/parameters/spreadgroup/zz_models_serde.go b/test/http-specs/parameters/spreadgroup/zz_models_serde.go new file mode 100644 index 000000000000..75944bbbabbc --- /dev/null +++ b/test/http-specs/parameters/spreadgroup/zz_models_serde.go @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package spreadgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type BodyParameter. +func (b BodyParameter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", b.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BodyParameter. +func (b *BodyParameter) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &b.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/http-specs/parameters/spreadgroup/zz_options.go b/test/http-specs/parameters/spreadgroup/zz_options.go new file mode 100644 index 000000000000..0f0120e1ee23 --- /dev/null +++ b/test/http-specs/parameters/spreadgroup/zz_options.go @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package spreadgroup + +// SpreadAliasClientSpreadAsRequestBodyOptions contains the optional parameters for the SpreadAliasClient.SpreadAsRequestBody +// method. +type SpreadAliasClientSpreadAsRequestBodyOptions struct { + // placeholder for future optional parameters +} + +// SpreadAliasClientSpreadAsRequestParameterOptions contains the optional parameters for the SpreadAliasClient.SpreadAsRequestParameter +// method. +type SpreadAliasClientSpreadAsRequestParameterOptions struct { + // placeholder for future optional parameters +} + +// SpreadAliasClientSpreadParameterWithInnerAliasOptions contains the optional parameters for the SpreadAliasClient.SpreadParameterWithInnerAlias +// method. +type SpreadAliasClientSpreadParameterWithInnerAliasOptions struct { + // placeholder for future optional parameters +} + +// SpreadAliasClientSpreadParameterWithInnerModelOptions contains the optional parameters for the SpreadAliasClient.SpreadParameterWithInnerModel +// method. +type SpreadAliasClientSpreadParameterWithInnerModelOptions struct { + // placeholder for future optional parameters +} + +// SpreadAliasClientSpreadWithMultipleParametersOptions contains the optional parameters for the SpreadAliasClient.SpreadWithMultipleParameters +// method. +type SpreadAliasClientSpreadWithMultipleParametersOptions struct { + // optional int + OptionalInt *int32 + + // optional string + OptionalStringList []string +} + +// SpreadModelClientSpreadAsRequestBodyOptions contains the optional parameters for the SpreadModelClient.SpreadAsRequestBody +// method. +type SpreadModelClientSpreadAsRequestBodyOptions struct { + // placeholder for future optional parameters +} + +// SpreadModelClientSpreadCompositeRequestMixOptions contains the optional parameters for the SpreadModelClient.SpreadCompositeRequestMix +// method. +type SpreadModelClientSpreadCompositeRequestMixOptions struct { + // placeholder for future optional parameters +} + +// SpreadModelClientSpreadCompositeRequestOnlyWithBodyOptions contains the optional parameters for the SpreadModelClient.SpreadCompositeRequestOnlyWithBody +// method. +type SpreadModelClientSpreadCompositeRequestOnlyWithBodyOptions struct { + // placeholder for future optional parameters +} + +// SpreadModelClientSpreadCompositeRequestOptions contains the optional parameters for the SpreadModelClient.SpreadCompositeRequest +// method. +type SpreadModelClientSpreadCompositeRequestOptions struct { + // placeholder for future optional parameters +} + +// SpreadModelClientSpreadCompositeRequestWithoutBodyOptions contains the optional parameters for the SpreadModelClient.SpreadCompositeRequestWithoutBody +// method. +type SpreadModelClientSpreadCompositeRequestWithoutBodyOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/parameters/spreadgroup/zz_responses.go b/test/http-specs/parameters/spreadgroup/zz_responses.go new file mode 100644 index 000000000000..f458130106d4 --- /dev/null +++ b/test/http-specs/parameters/spreadgroup/zz_responses.go @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package spreadgroup + +// SpreadAliasClientSpreadAsRequestBodyResponse contains the response from method SpreadAliasClient.SpreadAsRequestBody. +type SpreadAliasClientSpreadAsRequestBodyResponse struct { + // placeholder for future response values +} + +// SpreadAliasClientSpreadAsRequestParameterResponse contains the response from method SpreadAliasClient.SpreadAsRequestParameter. +type SpreadAliasClientSpreadAsRequestParameterResponse struct { + // placeholder for future response values +} + +// SpreadAliasClientSpreadParameterWithInnerAliasResponse contains the response from method SpreadAliasClient.SpreadParameterWithInnerAlias. +type SpreadAliasClientSpreadParameterWithInnerAliasResponse struct { + // placeholder for future response values +} + +// SpreadAliasClientSpreadParameterWithInnerModelResponse contains the response from method SpreadAliasClient.SpreadParameterWithInnerModel. +type SpreadAliasClientSpreadParameterWithInnerModelResponse struct { + // placeholder for future response values +} + +// SpreadAliasClientSpreadWithMultipleParametersResponse contains the response from method SpreadAliasClient.SpreadWithMultipleParameters. +type SpreadAliasClientSpreadWithMultipleParametersResponse struct { + // placeholder for future response values +} + +// SpreadModelClientSpreadAsRequestBodyResponse contains the response from method SpreadModelClient.SpreadAsRequestBody. +type SpreadModelClientSpreadAsRequestBodyResponse struct { + // placeholder for future response values +} + +// SpreadModelClientSpreadCompositeRequestMixResponse contains the response from method SpreadModelClient.SpreadCompositeRequestMix. +type SpreadModelClientSpreadCompositeRequestMixResponse struct { + // placeholder for future response values +} + +// SpreadModelClientSpreadCompositeRequestOnlyWithBodyResponse contains the response from method SpreadModelClient.SpreadCompositeRequestOnlyWithBody. +type SpreadModelClientSpreadCompositeRequestOnlyWithBodyResponse struct { + // placeholder for future response values +} + +// SpreadModelClientSpreadCompositeRequestResponse contains the response from method SpreadModelClient.SpreadCompositeRequest. +type SpreadModelClientSpreadCompositeRequestResponse struct { + // placeholder for future response values +} + +// SpreadModelClientSpreadCompositeRequestWithoutBodyResponse contains the response from method SpreadModelClient.SpreadCompositeRequestWithoutBody. +type SpreadModelClientSpreadCompositeRequestWithoutBodyResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/parameters/spreadgroup/zz_spread_client.go b/test/http-specs/parameters/spreadgroup/zz_spread_client.go new file mode 100644 index 000000000000..082590847fdc --- /dev/null +++ b/test/http-specs/parameters/spreadgroup/zz_spread_client.go @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package spreadgroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// SpreadClient - Test for the spread operator. +// Don't use this type directly, use NewSpreadClientWithNoCredential() instead. +type SpreadClient struct { + internal *azcore.Client + endpoint string +} + +// SpreadClientOptions contains the optional values for creating a [SpreadClient]. +type SpreadClientOptions struct { + azcore.ClientOptions +} + +// NewSpreadClientWithNoCredential creates a new instance of SpreadClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewSpreadClientWithNoCredential(endpoint string, options *SpreadClientOptions) (*SpreadClient, error) { + if options == nil { + options = &SpreadClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &SpreadClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewSpreadAliasClient creates a new instance of [SpreadAliasClient]. +func (client *SpreadClient) NewSpreadAliasClient() *SpreadAliasClient { + return &SpreadAliasClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewSpreadModelClient creates a new instance of [SpreadModelClient]. +func (client *SpreadClient) NewSpreadModelClient() *SpreadModelClient { + return &SpreadModelClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/http-specs/parameters/spreadgroup/zz_spreadalias_client.go b/test/http-specs/parameters/spreadgroup/zz_spreadalias_client.go new file mode 100644 index 000000000000..6c9cc3d7505b --- /dev/null +++ b/test/http-specs/parameters/spreadgroup/zz_spreadalias_client.go @@ -0,0 +1,279 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package spreadgroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// SpreadAliasClient contains the methods for the SpreadAlias group. +// Don't use this type directly, use [SpreadClient.NewSpreadAliasClient] instead. +type SpreadAliasClient struct { + internal *azcore.Client + endpoint string +} + +// SpreadAsRequestBody - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpreadAliasClientSpreadAsRequestBodyOptions contains the optional parameters for the SpreadAliasClient.SpreadAsRequestBody +// method. +func (client *SpreadAliasClient) SpreadAsRequestBody(ctx context.Context, name string, options *SpreadAliasClientSpreadAsRequestBodyOptions) (SpreadAliasClientSpreadAsRequestBodyResponse, error) { + var err error + const operationName = "SpreadAliasClient.SpreadAsRequestBody" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.spreadAsRequestBodyCreateRequest(ctx, name, options) + if err != nil { + return SpreadAliasClientSpreadAsRequestBodyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpreadAliasClientSpreadAsRequestBodyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpreadAliasClientSpreadAsRequestBodyResponse{}, err + } + return SpreadAliasClientSpreadAsRequestBodyResponse{}, nil +} + +// spreadAsRequestBodyCreateRequest creates the SpreadAsRequestBody request. +func (client *SpreadAliasClient) spreadAsRequestBodyCreateRequest(ctx context.Context, name string, _ *SpreadAliasClientSpreadAsRequestBodyOptions) (*policy.Request, error) { + urlPath := "/parameters/spread/alias/request-body" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + body := struct { + Name string `json:"name"` + }{ + Name: name, + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// SpreadAsRequestParameter - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpreadAliasClientSpreadAsRequestParameterOptions contains the optional parameters for the SpreadAliasClient.SpreadAsRequestParameter +// method. +func (client *SpreadAliasClient) SpreadAsRequestParameter(ctx context.Context, id string, xMSTestHeader string, name string, options *SpreadAliasClientSpreadAsRequestParameterOptions) (SpreadAliasClientSpreadAsRequestParameterResponse, error) { + var err error + const operationName = "SpreadAliasClient.SpreadAsRequestParameter" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.spreadAsRequestParameterCreateRequest(ctx, id, xMSTestHeader, name, options) + if err != nil { + return SpreadAliasClientSpreadAsRequestParameterResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpreadAliasClientSpreadAsRequestParameterResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpreadAliasClientSpreadAsRequestParameterResponse{}, err + } + return SpreadAliasClientSpreadAsRequestParameterResponse{}, nil +} + +// spreadAsRequestParameterCreateRequest creates the SpreadAsRequestParameter request. +func (client *SpreadAliasClient) spreadAsRequestParameterCreateRequest(ctx context.Context, id string, xMSTestHeader string, name string, _ *SpreadAliasClientSpreadAsRequestParameterOptions) (*policy.Request, error) { + urlPath := "/parameters/spread/alias/request-parameter/{id}" + if id == "" { + return nil, errors.New("parameter id cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{id}", url.PathEscape(id)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["x-ms-test-header"] = []string{xMSTestHeader} + body := struct { + Name string `json:"name"` + }{ + Name: name, + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// SpreadParameterWithInnerAlias - spread an alias with contains another alias property as body. +// If the operation fails it returns an *azcore.ResponseError type. +// - name - name of the Thing +// - age - age of the Thing +// - options - SpreadAliasClientSpreadParameterWithInnerAliasOptions contains the optional parameters for the SpreadAliasClient.SpreadParameterWithInnerAlias +// method. +func (client *SpreadAliasClient) SpreadParameterWithInnerAlias(ctx context.Context, id string, name string, age int32, xMSTestHeader string, options *SpreadAliasClientSpreadParameterWithInnerAliasOptions) (SpreadAliasClientSpreadParameterWithInnerAliasResponse, error) { + var err error + const operationName = "SpreadAliasClient.SpreadParameterWithInnerAlias" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.spreadParameterWithInnerAliasCreateRequest(ctx, id, name, age, xMSTestHeader, options) + if err != nil { + return SpreadAliasClientSpreadParameterWithInnerAliasResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpreadAliasClientSpreadParameterWithInnerAliasResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpreadAliasClientSpreadParameterWithInnerAliasResponse{}, err + } + return SpreadAliasClientSpreadParameterWithInnerAliasResponse{}, nil +} + +// spreadParameterWithInnerAliasCreateRequest creates the SpreadParameterWithInnerAlias request. +func (client *SpreadAliasClient) spreadParameterWithInnerAliasCreateRequest(ctx context.Context, id string, name string, age int32, xMSTestHeader string, _ *SpreadAliasClientSpreadParameterWithInnerAliasOptions) (*policy.Request, error) { + urlPath := "/parameters/spread/alias/inner-alias-parameter/{id}" + if id == "" { + return nil, errors.New("parameter id cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{id}", url.PathEscape(id)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["x-ms-test-header"] = []string{xMSTestHeader} + body := struct { + Name string `json:"name"` + Age int32 `json:"age"` + }{ + Name: name, + Age: age, + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// SpreadParameterWithInnerModel - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpreadAliasClientSpreadParameterWithInnerModelOptions contains the optional parameters for the SpreadAliasClient.SpreadParameterWithInnerModel +// method. +func (client *SpreadAliasClient) SpreadParameterWithInnerModel(ctx context.Context, id string, name string, xMSTestHeader string, options *SpreadAliasClientSpreadParameterWithInnerModelOptions) (SpreadAliasClientSpreadParameterWithInnerModelResponse, error) { + var err error + const operationName = "SpreadAliasClient.SpreadParameterWithInnerModel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.spreadParameterWithInnerModelCreateRequest(ctx, id, name, xMSTestHeader, options) + if err != nil { + return SpreadAliasClientSpreadParameterWithInnerModelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpreadAliasClientSpreadParameterWithInnerModelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpreadAliasClientSpreadParameterWithInnerModelResponse{}, err + } + return SpreadAliasClientSpreadParameterWithInnerModelResponse{}, nil +} + +// spreadParameterWithInnerModelCreateRequest creates the SpreadParameterWithInnerModel request. +func (client *SpreadAliasClient) spreadParameterWithInnerModelCreateRequest(ctx context.Context, id string, name string, xMSTestHeader string, _ *SpreadAliasClientSpreadParameterWithInnerModelOptions) (*policy.Request, error) { + urlPath := "/parameters/spread/alias/inner-model-parameter/{id}" + if id == "" { + return nil, errors.New("parameter id cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{id}", url.PathEscape(id)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["x-ms-test-header"] = []string{xMSTestHeader} + body := struct { + Name string `json:"name"` + }{ + Name: name, + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// SpreadWithMultipleParameters - +// If the operation fails it returns an *azcore.ResponseError type. +// - requiredString - required string +// - requiredIntList - required int +// - options - SpreadAliasClientSpreadWithMultipleParametersOptions contains the optional parameters for the SpreadAliasClient.SpreadWithMultipleParameters +// method. +func (client *SpreadAliasClient) SpreadWithMultipleParameters(ctx context.Context, id string, xMSTestHeader string, requiredString string, requiredIntList []int32, options *SpreadAliasClientSpreadWithMultipleParametersOptions) (SpreadAliasClientSpreadWithMultipleParametersResponse, error) { + var err error + const operationName = "SpreadAliasClient.SpreadWithMultipleParameters" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.spreadWithMultipleParametersCreateRequest(ctx, id, xMSTestHeader, requiredString, requiredIntList, options) + if err != nil { + return SpreadAliasClientSpreadWithMultipleParametersResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpreadAliasClientSpreadWithMultipleParametersResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpreadAliasClientSpreadWithMultipleParametersResponse{}, err + } + return SpreadAliasClientSpreadWithMultipleParametersResponse{}, nil +} + +// spreadWithMultipleParametersCreateRequest creates the SpreadWithMultipleParameters request. +func (client *SpreadAliasClient) spreadWithMultipleParametersCreateRequest(ctx context.Context, id string, xMSTestHeader string, requiredString string, requiredIntList []int32, options *SpreadAliasClientSpreadWithMultipleParametersOptions) (*policy.Request, error) { + urlPath := "/parameters/spread/alias/multiple-parameters/{id}" + if id == "" { + return nil, errors.New("parameter id cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{id}", url.PathEscape(id)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["x-ms-test-header"] = []string{xMSTestHeader} + body := struct { + RequiredString string `json:"requiredString"` + OptionalInt *int32 `json:"optionalInt"` + RequiredIntList []int32 `json:"requiredIntList"` + OptionalStringList []string `json:"optionalStringList"` + }{ + RequiredString: requiredString, + RequiredIntList: requiredIntList, + } + if options != nil && options.OptionalInt != nil { + body.OptionalInt = options.OptionalInt + } + if options != nil && options.OptionalStringList != nil { + body.OptionalStringList = options.OptionalStringList + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/parameters/spreadgroup/zz_spreadmodel_client.go b/test/http-specs/parameters/spreadgroup/zz_spreadmodel_client.go new file mode 100644 index 000000000000..31aacb872325 --- /dev/null +++ b/test/http-specs/parameters/spreadgroup/zz_spreadmodel_client.go @@ -0,0 +1,239 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package spreadgroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// SpreadModelClient contains the methods for the SpreadModel group. +// Don't use this type directly, use [SpreadClient.NewSpreadModelClient] instead. +type SpreadModelClient struct { + internal *azcore.Client + endpoint string +} + +// SpreadAsRequestBody - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpreadModelClientSpreadAsRequestBodyOptions contains the optional parameters for the SpreadModelClient.SpreadAsRequestBody +// method. +func (client *SpreadModelClient) SpreadAsRequestBody(ctx context.Context, name string, options *SpreadModelClientSpreadAsRequestBodyOptions) (SpreadModelClientSpreadAsRequestBodyResponse, error) { + var err error + const operationName = "SpreadModelClient.SpreadAsRequestBody" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.spreadAsRequestBodyCreateRequest(ctx, name, options) + if err != nil { + return SpreadModelClientSpreadAsRequestBodyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpreadModelClientSpreadAsRequestBodyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpreadModelClientSpreadAsRequestBodyResponse{}, err + } + return SpreadModelClientSpreadAsRequestBodyResponse{}, nil +} + +// spreadAsRequestBodyCreateRequest creates the SpreadAsRequestBody request. +func (client *SpreadModelClient) spreadAsRequestBodyCreateRequest(ctx context.Context, name string, _ *SpreadModelClientSpreadAsRequestBodyOptions) (*policy.Request, error) { + urlPath := "/parameters/spread/model/request-body" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + body := struct { + Name string `json:"name"` + }{ + Name: name, + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// SpreadCompositeRequest - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpreadModelClientSpreadCompositeRequestOptions contains the optional parameters for the SpreadModelClient.SpreadCompositeRequest +// method. +func (client *SpreadModelClient) SpreadCompositeRequest(ctx context.Context, name string, testHeader string, body BodyParameter, options *SpreadModelClientSpreadCompositeRequestOptions) (SpreadModelClientSpreadCompositeRequestResponse, error) { + var err error + const operationName = "SpreadModelClient.SpreadCompositeRequest" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.spreadCompositeRequestCreateRequest(ctx, name, testHeader, body, options) + if err != nil { + return SpreadModelClientSpreadCompositeRequestResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpreadModelClientSpreadCompositeRequestResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpreadModelClientSpreadCompositeRequestResponse{}, err + } + return SpreadModelClientSpreadCompositeRequestResponse{}, nil +} + +// spreadCompositeRequestCreateRequest creates the SpreadCompositeRequest request. +func (client *SpreadModelClient) spreadCompositeRequestCreateRequest(ctx context.Context, name string, testHeader string, body BodyParameter, _ *SpreadModelClientSpreadCompositeRequestOptions) (*policy.Request, error) { + urlPath := "/parameters/spread/model/composite-request/{name}" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["test-header"] = []string{testHeader} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// SpreadCompositeRequestMix - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpreadModelClientSpreadCompositeRequestMixOptions contains the optional parameters for the SpreadModelClient.SpreadCompositeRequestMix +// method. +func (client *SpreadModelClient) SpreadCompositeRequestMix(ctx context.Context, name string, testHeader string, prop string, options *SpreadModelClientSpreadCompositeRequestMixOptions) (SpreadModelClientSpreadCompositeRequestMixResponse, error) { + var err error + const operationName = "SpreadModelClient.SpreadCompositeRequestMix" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.spreadCompositeRequestMixCreateRequest(ctx, name, testHeader, prop, options) + if err != nil { + return SpreadModelClientSpreadCompositeRequestMixResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpreadModelClientSpreadCompositeRequestMixResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpreadModelClientSpreadCompositeRequestMixResponse{}, err + } + return SpreadModelClientSpreadCompositeRequestMixResponse{}, nil +} + +// spreadCompositeRequestMixCreateRequest creates the SpreadCompositeRequestMix request. +func (client *SpreadModelClient) spreadCompositeRequestMixCreateRequest(ctx context.Context, name string, testHeader string, prop string, _ *SpreadModelClientSpreadCompositeRequestMixOptions) (*policy.Request, error) { + urlPath := "/parameters/spread/model/composite-request-mix/{name}" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["test-header"] = []string{testHeader} + body := struct { + Prop string `json:"prop"` + }{ + Prop: prop, + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// SpreadCompositeRequestOnlyWithBody - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpreadModelClientSpreadCompositeRequestOnlyWithBodyOptions contains the optional parameters for the SpreadModelClient.SpreadCompositeRequestOnlyWithBody +// method. +func (client *SpreadModelClient) SpreadCompositeRequestOnlyWithBody(ctx context.Context, body BodyParameter, options *SpreadModelClientSpreadCompositeRequestOnlyWithBodyOptions) (SpreadModelClientSpreadCompositeRequestOnlyWithBodyResponse, error) { + var err error + const operationName = "SpreadModelClient.SpreadCompositeRequestOnlyWithBody" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.spreadCompositeRequestOnlyWithBodyCreateRequest(ctx, body, options) + if err != nil { + return SpreadModelClientSpreadCompositeRequestOnlyWithBodyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpreadModelClientSpreadCompositeRequestOnlyWithBodyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpreadModelClientSpreadCompositeRequestOnlyWithBodyResponse{}, err + } + return SpreadModelClientSpreadCompositeRequestOnlyWithBodyResponse{}, nil +} + +// spreadCompositeRequestOnlyWithBodyCreateRequest creates the SpreadCompositeRequestOnlyWithBody request. +func (client *SpreadModelClient) spreadCompositeRequestOnlyWithBodyCreateRequest(ctx context.Context, body BodyParameter, _ *SpreadModelClientSpreadCompositeRequestOnlyWithBodyOptions) (*policy.Request, error) { + urlPath := "/parameters/spread/model/composite-request-only-with-body" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// SpreadCompositeRequestWithoutBody - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpreadModelClientSpreadCompositeRequestWithoutBodyOptions contains the optional parameters for the SpreadModelClient.SpreadCompositeRequestWithoutBody +// method. +func (client *SpreadModelClient) SpreadCompositeRequestWithoutBody(ctx context.Context, name string, testHeader string, options *SpreadModelClientSpreadCompositeRequestWithoutBodyOptions) (SpreadModelClientSpreadCompositeRequestWithoutBodyResponse, error) { + var err error + const operationName = "SpreadModelClient.SpreadCompositeRequestWithoutBody" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.spreadCompositeRequestWithoutBodyCreateRequest(ctx, name, testHeader, options) + if err != nil { + return SpreadModelClientSpreadCompositeRequestWithoutBodyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpreadModelClientSpreadCompositeRequestWithoutBodyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpreadModelClientSpreadCompositeRequestWithoutBodyResponse{}, err + } + return SpreadModelClientSpreadCompositeRequestWithoutBodyResponse{}, nil +} + +// spreadCompositeRequestWithoutBodyCreateRequest creates the SpreadCompositeRequestWithoutBody request. +func (client *SpreadModelClient) spreadCompositeRequestWithoutBodyCreateRequest(ctx context.Context, name string, testHeader string, _ *SpreadModelClientSpreadCompositeRequestWithoutBodyOptions) (*policy.Request, error) { + urlPath := "/parameters/spread/model/composite-request-without-body/{name}" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["test-header"] = []string{testHeader} + return req, nil +} diff --git a/test/http-specs/parameters/spreadgroup/zz_version.go b/test/http-specs/parameters/spreadgroup/zz_version.go new file mode 100644 index 000000000000..6cfa7c96b622 --- /dev/null +++ b/test/http-specs/parameters/spreadgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package spreadgroup + +const ( + moduleName = "spreadgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/payload/contentneggroup/LICENSE.txt b/test/http-specs/payload/contentneggroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/payload/contentneggroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/payload/contentneggroup/differentbody_client_test.go b/test/http-specs/payload/contentneggroup/differentbody_client_test.go new file mode 100644 index 000000000000..00d4779e5a6e --- /dev/null +++ b/test/http-specs/payload/contentneggroup/differentbody_client_test.go @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package contentneggroup_test + +import ( + "contentneggroup" + "context" + "io" + "os" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestDifferentBodyClient_GetAvatarAsJSON(t *testing.T) { + client, err := contentneggroup.NewContentNegotiationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewContentNegotiationDifferentBodyClient().GetAvatarAsJSON(context.Background(), nil) + require.NoError(t, err) + pngFile, err := os.ReadFile("../../../../node_modules/@typespec/http-specs/assets/image.png") + require.NoError(t, err) + require.EqualValues(t, pngFile, resp.Content) +} + +func TestDifferentBodyClient_GetAvatarAsPNG(t *testing.T) { + client, err := contentneggroup.NewContentNegotiationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewContentNegotiationDifferentBodyClient().GetAvatarAsPNG(context.Background(), nil) + require.NoError(t, err) + pngResp, err := io.ReadAll(resp.Body) + require.NoError(t, err) + pngFile, err := os.ReadFile("../../../../node_modules/@typespec/http-specs/assets/image.png") + require.NoError(t, err) + require.EqualValues(t, pngFile, pngResp) +} diff --git a/test/http-specs/payload/contentneggroup/fake/zz_contentnegotiation_server.go b/test/http-specs/payload/contentneggroup/fake/zz_contentnegotiation_server.go new file mode 100644 index 000000000000..b9d3073f5e34 --- /dev/null +++ b/test/http-specs/payload/contentneggroup/fake/zz_contentnegotiation_server.go @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ContentNegotiationServer is a fake server for instances of the contentneggroup.ContentNegotiationClient type. +type ContentNegotiationServer struct { + // ContentNegotiationDifferentBodyServer contains the fakes for client ContentNegotiationDifferentBodyClient + ContentNegotiationDifferentBodyServer ContentNegotiationDifferentBodyServer + + // ContentNegotiationSameBodyServer contains the fakes for client ContentNegotiationSameBodyClient + ContentNegotiationSameBodyServer ContentNegotiationSameBodyServer +} + +// NewContentNegotiationServerTransport creates a new instance of ContentNegotiationServerTransport with the provided implementation. +// The returned ContentNegotiationServerTransport instance is connected to an instance of contentneggroup.ContentNegotiationClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewContentNegotiationServerTransport(srv *ContentNegotiationServer) *ContentNegotiationServerTransport { + return &ContentNegotiationServerTransport{srv: srv} +} + +// ContentNegotiationServerTransport connects instances of contentneggroup.ContentNegotiationClient to instances of ContentNegotiationServer. +// Don't use this type directly, use NewContentNegotiationServerTransport instead. +type ContentNegotiationServerTransport struct { + srv *ContentNegotiationServer + trMu sync.Mutex + trContentNegotiationDifferentBodyServer *ContentNegotiationDifferentBodyServerTransport + trContentNegotiationSameBodyServer *ContentNegotiationSameBodyServerTransport +} + +// Do implements the policy.Transporter interface for ContentNegotiationServerTransport. +func (c *ContentNegotiationServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (c *ContentNegotiationServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "ContentNegotiationDifferentBodyClient": + initServer(&c.trMu, &c.trContentNegotiationDifferentBodyServer, func() *ContentNegotiationDifferentBodyServerTransport { + return NewContentNegotiationDifferentBodyServerTransport(&c.srv.ContentNegotiationDifferentBodyServer) + }) + resp, err = c.trContentNegotiationDifferentBodyServer.Do(req) + case "ContentNegotiationSameBodyClient": + initServer(&c.trMu, &c.trContentNegotiationSameBodyServer, func() *ContentNegotiationSameBodyServerTransport { + return NewContentNegotiationSameBodyServerTransport(&c.srv.ContentNegotiationSameBodyServer) + }) + resp, err = c.trContentNegotiationSameBodyServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to ContentNegotiationServerTransport +var contentNegotiationServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/contentneggroup/fake/zz_contentnegotiationdifferentbody_server.go b/test/http-specs/payload/contentneggroup/fake/zz_contentnegotiationdifferentbody_server.go new file mode 100644 index 000000000000..adbbb0457212 --- /dev/null +++ b/test/http-specs/payload/contentneggroup/fake/zz_contentnegotiationdifferentbody_server.go @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "contentneggroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// ContentNegotiationDifferentBodyServer is a fake server for instances of the contentneggroup.ContentNegotiationDifferentBodyClient type. +type ContentNegotiationDifferentBodyServer struct { + // GetAvatarAsJSON is the fake for method ContentNegotiationDifferentBodyClient.GetAvatarAsJSON + // HTTP status codes to indicate success: http.StatusOK + GetAvatarAsJSON func(ctx context.Context, options *contentneggroup.ContentNegotiationDifferentBodyClientGetAvatarAsJSONOptions) (resp azfake.Responder[contentneggroup.ContentNegotiationDifferentBodyClientGetAvatarAsJSONResponse], errResp azfake.ErrorResponder) + + // GetAvatarAsPNG is the fake for method ContentNegotiationDifferentBodyClient.GetAvatarAsPNG + // HTTP status codes to indicate success: http.StatusOK + GetAvatarAsPNG func(ctx context.Context, options *contentneggroup.ContentNegotiationDifferentBodyClientGetAvatarAsPNGOptions) (resp azfake.Responder[contentneggroup.ContentNegotiationDifferentBodyClientGetAvatarAsPNGResponse], errResp azfake.ErrorResponder) +} + +// NewContentNegotiationDifferentBodyServerTransport creates a new instance of ContentNegotiationDifferentBodyServerTransport with the provided implementation. +// The returned ContentNegotiationDifferentBodyServerTransport instance is connected to an instance of contentneggroup.ContentNegotiationDifferentBodyClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewContentNegotiationDifferentBodyServerTransport(srv *ContentNegotiationDifferentBodyServer) *ContentNegotiationDifferentBodyServerTransport { + return &ContentNegotiationDifferentBodyServerTransport{srv: srv} +} + +// ContentNegotiationDifferentBodyServerTransport connects instances of contentneggroup.ContentNegotiationDifferentBodyClient to instances of ContentNegotiationDifferentBodyServer. +// Don't use this type directly, use NewContentNegotiationDifferentBodyServerTransport instead. +type ContentNegotiationDifferentBodyServerTransport struct { + srv *ContentNegotiationDifferentBodyServer +} + +// Do implements the policy.Transporter interface for ContentNegotiationDifferentBodyServerTransport. +func (c *ContentNegotiationDifferentBodyServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *ContentNegotiationDifferentBodyServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if contentNegotiationDifferentBodyServerTransportInterceptor != nil { + res.resp, res.err, intercepted = contentNegotiationDifferentBodyServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ContentNegotiationDifferentBodyClient.GetAvatarAsJSON": + res.resp, res.err = c.dispatchGetAvatarAsJSON(req) + case "ContentNegotiationDifferentBodyClient.GetAvatarAsPNG": + res.resp, res.err = c.dispatchGetAvatarAsPNG(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *ContentNegotiationDifferentBodyServerTransport) dispatchGetAvatarAsJSON(req *http.Request) (*http.Response, error) { + if c.srv.GetAvatarAsJSON == nil { + return nil, &nonRetriableError{errors.New("fake for method GetAvatarAsJSON not implemented")} + } + respr, errRespr := c.srv.GetAvatarAsJSON(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).PNGImageAsJSON, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *ContentNegotiationDifferentBodyServerTransport) dispatchGetAvatarAsPNG(req *http.Request) (*http.Response, error) { + if c.srv.GetAvatarAsPNG == nil { + return nil, &nonRetriableError{errors.New("fake for method GetAvatarAsPNG not implemented")} + } + respr, errRespr := c.srv.GetAvatarAsPNG(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, &server.ResponseOptions{ + Body: server.GetResponse(respr).Body, + ContentType: req.Header.Get("Content-Type"), + }) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).ContentType; val != nil { + resp.Header.Set("content-type", "image/png") + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ContentNegotiationDifferentBodyServerTransport +var contentNegotiationDifferentBodyServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/contentneggroup/fake/zz_contentnegotiationsamebody_server.go b/test/http-specs/payload/contentneggroup/fake/zz_contentnegotiationsamebody_server.go new file mode 100644 index 000000000000..5d45d8034bcb --- /dev/null +++ b/test/http-specs/payload/contentneggroup/fake/zz_contentnegotiationsamebody_server.go @@ -0,0 +1,138 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "contentneggroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// ContentNegotiationSameBodyServer is a fake server for instances of the contentneggroup.ContentNegotiationSameBodyClient type. +type ContentNegotiationSameBodyServer struct { + // GetAvatarAsJPEG is the fake for method ContentNegotiationSameBodyClient.GetAvatarAsJPEG + // HTTP status codes to indicate success: http.StatusOK + GetAvatarAsJPEG func(ctx context.Context, options *contentneggroup.ContentNegotiationSameBodyClientGetAvatarAsJPEGOptions) (resp azfake.Responder[contentneggroup.ContentNegotiationSameBodyClientGetAvatarAsJPEGResponse], errResp azfake.ErrorResponder) + + // GetAvatarAsPNG is the fake for method ContentNegotiationSameBodyClient.GetAvatarAsPNG + // HTTP status codes to indicate success: http.StatusOK + GetAvatarAsPNG func(ctx context.Context, options *contentneggroup.ContentNegotiationSameBodyClientGetAvatarAsPNGOptions) (resp azfake.Responder[contentneggroup.ContentNegotiationSameBodyClientGetAvatarAsPNGResponse], errResp azfake.ErrorResponder) +} + +// NewContentNegotiationSameBodyServerTransport creates a new instance of ContentNegotiationSameBodyServerTransport with the provided implementation. +// The returned ContentNegotiationSameBodyServerTransport instance is connected to an instance of contentneggroup.ContentNegotiationSameBodyClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewContentNegotiationSameBodyServerTransport(srv *ContentNegotiationSameBodyServer) *ContentNegotiationSameBodyServerTransport { + return &ContentNegotiationSameBodyServerTransport{srv: srv} +} + +// ContentNegotiationSameBodyServerTransport connects instances of contentneggroup.ContentNegotiationSameBodyClient to instances of ContentNegotiationSameBodyServer. +// Don't use this type directly, use NewContentNegotiationSameBodyServerTransport instead. +type ContentNegotiationSameBodyServerTransport struct { + srv *ContentNegotiationSameBodyServer +} + +// Do implements the policy.Transporter interface for ContentNegotiationSameBodyServerTransport. +func (c *ContentNegotiationSameBodyServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *ContentNegotiationSameBodyServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if contentNegotiationSameBodyServerTransportInterceptor != nil { + res.resp, res.err, intercepted = contentNegotiationSameBodyServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ContentNegotiationSameBodyClient.GetAvatarAsJPEG": + res.resp, res.err = c.dispatchGetAvatarAsJPEG(req) + case "ContentNegotiationSameBodyClient.GetAvatarAsPNG": + res.resp, res.err = c.dispatchGetAvatarAsPNG(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *ContentNegotiationSameBodyServerTransport) dispatchGetAvatarAsJPEG(req *http.Request) (*http.Response, error) { + if c.srv.GetAvatarAsJPEG == nil { + return nil, &nonRetriableError{errors.New("fake for method GetAvatarAsJPEG not implemented")} + } + respr, errRespr := c.srv.GetAvatarAsJPEG(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, &server.ResponseOptions{ + Body: server.GetResponse(respr).Body, + ContentType: req.Header.Get("Content-Type"), + }) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).ContentType; val != nil { + resp.Header.Set("content-type", "image/jpeg") + } + return resp, nil +} + +func (c *ContentNegotiationSameBodyServerTransport) dispatchGetAvatarAsPNG(req *http.Request) (*http.Response, error) { + if c.srv.GetAvatarAsPNG == nil { + return nil, &nonRetriableError{errors.New("fake for method GetAvatarAsPNG not implemented")} + } + respr, errRespr := c.srv.GetAvatarAsPNG(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, &server.ResponseOptions{ + Body: server.GetResponse(respr).Body, + ContentType: req.Header.Get("Content-Type"), + }) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).ContentType; val != nil { + resp.Header.Set("content-type", "image/png") + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ContentNegotiationSameBodyServerTransport +var contentNegotiationSameBodyServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/contentneggroup/fake/zz_internal.go b/test/http-specs/payload/contentneggroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/http-specs/payload/contentneggroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/http-specs/payload/contentneggroup/go.mod b/test/http-specs/payload/contentneggroup/go.mod new file mode 100644 index 000000000000..86d0a55df1dd --- /dev/null +++ b/test/http-specs/payload/contentneggroup/go.mod @@ -0,0 +1,17 @@ +module contentneggroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/payload/contentneggroup/go.sum b/test/http-specs/payload/contentneggroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/payload/contentneggroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/payload/contentneggroup/samebody_client_test.go b/test/http-specs/payload/contentneggroup/samebody_client_test.go new file mode 100644 index 000000000000..e199172a54be --- /dev/null +++ b/test/http-specs/payload/contentneggroup/samebody_client_test.go @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package contentneggroup_test + +import ( + "contentneggroup" + "context" + "io" + "os" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestSameBodyClient_GetAvatarAsJPEG(t *testing.T) { + client, err := contentneggroup.NewContentNegotiationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewContentNegotiationSameBodyClient().GetAvatarAsJPEG(context.Background(), nil) + require.NoError(t, err) + jpgResp, err := io.ReadAll(resp.Body) + require.NoError(t, err) + jpgFile, err := os.ReadFile("../../../../node_modules/@typespec/http-specs/assets/image.jpg") + require.NoError(t, err) + require.EqualValues(t, jpgFile, jpgResp) +} + +func TestSameBodyClient_GetAvatarAsPNG(t *testing.T) { + client, err := contentneggroup.NewContentNegotiationClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewContentNegotiationSameBodyClient().GetAvatarAsPNG(context.Background(), nil) + require.NoError(t, err) + pngResp, err := io.ReadAll(resp.Body) + require.NoError(t, err) + pngFile, err := os.ReadFile("../../../../node_modules/@typespec/http-specs/assets/image.png") + require.NoError(t, err) + require.EqualValues(t, pngFile, pngResp) +} diff --git a/test/http-specs/payload/contentneggroup/testdata/_metadata.json b/test/http-specs/payload/contentneggroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/payload/contentneggroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/payload/contentneggroup/zz_contentnegotiation_client.go b/test/http-specs/payload/contentneggroup/zz_contentnegotiation_client.go new file mode 100644 index 000000000000..099a517f07df --- /dev/null +++ b/test/http-specs/payload/contentneggroup/zz_contentnegotiation_client.go @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package contentneggroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// ContentNegotiationClient - Test describing optionality of the request body. +// Don't use this type directly, use NewContentNegotiationClientWithNoCredential() instead. +type ContentNegotiationClient struct { + internal *azcore.Client + endpoint string +} + +// ContentNegotiationClientOptions contains the optional values for creating a [ContentNegotiationClient]. +type ContentNegotiationClientOptions struct { + azcore.ClientOptions +} + +// NewContentNegotiationClientWithNoCredential creates a new instance of ContentNegotiationClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewContentNegotiationClientWithNoCredential(endpoint string, options *ContentNegotiationClientOptions) (*ContentNegotiationClient, error) { + if options == nil { + options = &ContentNegotiationClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &ContentNegotiationClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewContentNegotiationDifferentBodyClient creates a new instance of [ContentNegotiationDifferentBodyClient]. +func (client *ContentNegotiationClient) NewContentNegotiationDifferentBodyClient() *ContentNegotiationDifferentBodyClient { + return &ContentNegotiationDifferentBodyClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewContentNegotiationSameBodyClient creates a new instance of [ContentNegotiationSameBodyClient]. +func (client *ContentNegotiationClient) NewContentNegotiationSameBodyClient() *ContentNegotiationSameBodyClient { + return &ContentNegotiationSameBodyClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/http-specs/payload/contentneggroup/zz_contentnegotiationdifferentbody_client.go b/test/http-specs/payload/contentneggroup/zz_contentnegotiationdifferentbody_client.go new file mode 100644 index 000000000000..ec86492782ad --- /dev/null +++ b/test/http-specs/payload/contentneggroup/zz_contentnegotiationdifferentbody_client.go @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package contentneggroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ContentNegotiationDifferentBodyClient contains the methods for the ContentNegotiationDifferentBody group. +// Don't use this type directly, use [ContentNegotiationClient.NewContentNegotiationDifferentBodyClient] instead. +type ContentNegotiationDifferentBodyClient struct { + internal *azcore.Client + endpoint string +} + +// GetAvatarAsJSON - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ContentNegotiationDifferentBodyClientGetAvatarAsJSONOptions contains the optional parameters for the ContentNegotiationDifferentBodyClient.GetAvatarAsJSON +// method. +func (client *ContentNegotiationDifferentBodyClient) GetAvatarAsJSON(ctx context.Context, options *ContentNegotiationDifferentBodyClientGetAvatarAsJSONOptions) (ContentNegotiationDifferentBodyClientGetAvatarAsJSONResponse, error) { + var err error + const operationName = "ContentNegotiationDifferentBodyClient.GetAvatarAsJSON" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getAvatarAsJSONCreateRequest(ctx, options) + if err != nil { + return ContentNegotiationDifferentBodyClientGetAvatarAsJSONResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ContentNegotiationDifferentBodyClientGetAvatarAsJSONResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ContentNegotiationDifferentBodyClientGetAvatarAsJSONResponse{}, err + } + resp, err := client.getAvatarAsJSONHandleResponse(httpResp) + return resp, err +} + +// getAvatarAsJSONCreateRequest creates the GetAvatarAsJSON request. +func (client *ContentNegotiationDifferentBodyClient) getAvatarAsJSONCreateRequest(ctx context.Context, _ *ContentNegotiationDifferentBodyClientGetAvatarAsJSONOptions) (*policy.Request, error) { + urlPath := "/content-negotiation/different-body" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["accept"] = []string{"application/json"} + return req, nil +} + +// getAvatarAsJSONHandleResponse handles the GetAvatarAsJSON response. +func (client *ContentNegotiationDifferentBodyClient) getAvatarAsJSONHandleResponse(resp *http.Response) (ContentNegotiationDifferentBodyClientGetAvatarAsJSONResponse, error) { + result := ContentNegotiationDifferentBodyClientGetAvatarAsJSONResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PNGImageAsJSON); err != nil { + return ContentNegotiationDifferentBodyClientGetAvatarAsJSONResponse{}, err + } + return result, nil +} + +// GetAvatarAsPNG - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ContentNegotiationDifferentBodyClientGetAvatarAsPNGOptions contains the optional parameters for the ContentNegotiationDifferentBodyClient.GetAvatarAsPNG +// method. +func (client *ContentNegotiationDifferentBodyClient) GetAvatarAsPNG(ctx context.Context, options *ContentNegotiationDifferentBodyClientGetAvatarAsPNGOptions) (ContentNegotiationDifferentBodyClientGetAvatarAsPNGResponse, error) { + var err error + const operationName = "ContentNegotiationDifferentBodyClient.GetAvatarAsPNG" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getAvatarAsPNGCreateRequest(ctx, options) + if err != nil { + return ContentNegotiationDifferentBodyClientGetAvatarAsPNGResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ContentNegotiationDifferentBodyClientGetAvatarAsPNGResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ContentNegotiationDifferentBodyClientGetAvatarAsPNGResponse{}, err + } + resp, err := client.getAvatarAsPNGHandleResponse(httpResp) + return resp, err +} + +// getAvatarAsPNGCreateRequest creates the GetAvatarAsPNG request. +func (client *ContentNegotiationDifferentBodyClient) getAvatarAsPNGCreateRequest(ctx context.Context, _ *ContentNegotiationDifferentBodyClientGetAvatarAsPNGOptions) (*policy.Request, error) { + urlPath := "/content-negotiation/different-body" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + runtime.SkipBodyDownload(req) + req.Raw().Header["accept"] = []string{"image/png"} + return req, nil +} + +// getAvatarAsPNGHandleResponse handles the GetAvatarAsPNG response. +func (client *ContentNegotiationDifferentBodyClient) getAvatarAsPNGHandleResponse(resp *http.Response) (ContentNegotiationDifferentBodyClientGetAvatarAsPNGResponse, error) { + result := ContentNegotiationDifferentBodyClientGetAvatarAsPNGResponse{Body: resp.Body} + if val := resp.Header.Get("content-type"); val != "" { + result.ContentType = &val + } + return result, nil +} diff --git a/test/http-specs/payload/contentneggroup/zz_contentnegotiationsamebody_client.go b/test/http-specs/payload/contentneggroup/zz_contentnegotiationsamebody_client.go new file mode 100644 index 000000000000..921c0f94739f --- /dev/null +++ b/test/http-specs/payload/contentneggroup/zz_contentnegotiationsamebody_client.go @@ -0,0 +1,114 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package contentneggroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ContentNegotiationSameBodyClient contains the methods for the ContentNegotiationSameBody group. +// Don't use this type directly, use [ContentNegotiationClient.NewContentNegotiationSameBodyClient] instead. +type ContentNegotiationSameBodyClient struct { + internal *azcore.Client + endpoint string +} + +// GetAvatarAsJPEG - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ContentNegotiationSameBodyClientGetAvatarAsJPEGOptions contains the optional parameters for the ContentNegotiationSameBodyClient.GetAvatarAsJPEG +// method. +func (client *ContentNegotiationSameBodyClient) GetAvatarAsJPEG(ctx context.Context, options *ContentNegotiationSameBodyClientGetAvatarAsJPEGOptions) (ContentNegotiationSameBodyClientGetAvatarAsJPEGResponse, error) { + var err error + const operationName = "ContentNegotiationSameBodyClient.GetAvatarAsJPEG" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getAvatarAsJPEGCreateRequest(ctx, options) + if err != nil { + return ContentNegotiationSameBodyClientGetAvatarAsJPEGResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ContentNegotiationSameBodyClientGetAvatarAsJPEGResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ContentNegotiationSameBodyClientGetAvatarAsJPEGResponse{}, err + } + resp, err := client.getAvatarAsJPEGHandleResponse(httpResp) + return resp, err +} + +// getAvatarAsJPEGCreateRequest creates the GetAvatarAsJPEG request. +func (client *ContentNegotiationSameBodyClient) getAvatarAsJPEGCreateRequest(ctx context.Context, _ *ContentNegotiationSameBodyClientGetAvatarAsJPEGOptions) (*policy.Request, error) { + urlPath := "/content-negotiation/same-body" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + runtime.SkipBodyDownload(req) + req.Raw().Header["accept"] = []string{"image/jpeg"} + return req, nil +} + +// getAvatarAsJPEGHandleResponse handles the GetAvatarAsJPEG response. +func (client *ContentNegotiationSameBodyClient) getAvatarAsJPEGHandleResponse(resp *http.Response) (ContentNegotiationSameBodyClientGetAvatarAsJPEGResponse, error) { + result := ContentNegotiationSameBodyClientGetAvatarAsJPEGResponse{Body: resp.Body} + if val := resp.Header.Get("content-type"); val != "" { + result.ContentType = &val + } + return result, nil +} + +// GetAvatarAsPNG - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ContentNegotiationSameBodyClientGetAvatarAsPNGOptions contains the optional parameters for the ContentNegotiationSameBodyClient.GetAvatarAsPNG +// method. +func (client *ContentNegotiationSameBodyClient) GetAvatarAsPNG(ctx context.Context, options *ContentNegotiationSameBodyClientGetAvatarAsPNGOptions) (ContentNegotiationSameBodyClientGetAvatarAsPNGResponse, error) { + var err error + const operationName = "ContentNegotiationSameBodyClient.GetAvatarAsPNG" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getAvatarAsPNGCreateRequest(ctx, options) + if err != nil { + return ContentNegotiationSameBodyClientGetAvatarAsPNGResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ContentNegotiationSameBodyClientGetAvatarAsPNGResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ContentNegotiationSameBodyClientGetAvatarAsPNGResponse{}, err + } + resp, err := client.getAvatarAsPNGHandleResponse(httpResp) + return resp, err +} + +// getAvatarAsPNGCreateRequest creates the GetAvatarAsPNG request. +func (client *ContentNegotiationSameBodyClient) getAvatarAsPNGCreateRequest(ctx context.Context, _ *ContentNegotiationSameBodyClientGetAvatarAsPNGOptions) (*policy.Request, error) { + urlPath := "/content-negotiation/same-body" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + runtime.SkipBodyDownload(req) + req.Raw().Header["accept"] = []string{"image/png"} + return req, nil +} + +// getAvatarAsPNGHandleResponse handles the GetAvatarAsPNG response. +func (client *ContentNegotiationSameBodyClient) getAvatarAsPNGHandleResponse(resp *http.Response) (ContentNegotiationSameBodyClientGetAvatarAsPNGResponse, error) { + result := ContentNegotiationSameBodyClientGetAvatarAsPNGResponse{Body: resp.Body} + if val := resp.Header.Get("content-type"); val != "" { + result.ContentType = &val + } + return result, nil +} diff --git a/test/http-specs/payload/contentneggroup/zz_models.go b/test/http-specs/payload/contentneggroup/zz_models.go new file mode 100644 index 000000000000..70a13a0f5580 --- /dev/null +++ b/test/http-specs/payload/contentneggroup/zz_models.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package contentneggroup + +type PNGImageAsJSON struct { + // REQUIRED + Content []byte +} diff --git a/test/http-specs/payload/contentneggroup/zz_models_serde.go b/test/http-specs/payload/contentneggroup/zz_models_serde.go new file mode 100644 index 000000000000..4f9ece52fd1e --- /dev/null +++ b/test/http-specs/payload/contentneggroup/zz_models_serde.go @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package contentneggroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// MarshalJSON implements the json.Marshaller interface for type PNGImageAsJSON. +func (p PNGImageAsJSON) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateByteArray(objectMap, "content", p.Content, func() any { + return runtime.EncodeByteArray(p.Content, runtime.Base64StdFormat) + }) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PNGImageAsJSON. +func (p *PNGImageAsJSON) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "content": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &p.Content, runtime.Base64StdFormat) + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +func populateByteArray[T any](m map[string]any, k string, b []T, convert func() any) { + if azcore.IsNullValue(b) { + m[k] = nil + } else if len(b) == 0 { + return + } else { + m[k] = convert() + } +} diff --git a/test/http-specs/payload/contentneggroup/zz_options.go b/test/http-specs/payload/contentneggroup/zz_options.go new file mode 100644 index 000000000000..caa5ab4f30b3 --- /dev/null +++ b/test/http-specs/payload/contentneggroup/zz_options.go @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package contentneggroup + +// ContentNegotiationDifferentBodyClientGetAvatarAsJSONOptions contains the optional parameters for the ContentNegotiationDifferentBodyClient.GetAvatarAsJSON +// method. +type ContentNegotiationDifferentBodyClientGetAvatarAsJSONOptions struct { + // placeholder for future optional parameters +} + +// ContentNegotiationDifferentBodyClientGetAvatarAsPNGOptions contains the optional parameters for the ContentNegotiationDifferentBodyClient.GetAvatarAsPNG +// method. +type ContentNegotiationDifferentBodyClientGetAvatarAsPNGOptions struct { + // placeholder for future optional parameters +} + +// ContentNegotiationSameBodyClientGetAvatarAsJPEGOptions contains the optional parameters for the ContentNegotiationSameBodyClient.GetAvatarAsJPEG +// method. +type ContentNegotiationSameBodyClientGetAvatarAsJPEGOptions struct { + // placeholder for future optional parameters +} + +// ContentNegotiationSameBodyClientGetAvatarAsPNGOptions contains the optional parameters for the ContentNegotiationSameBodyClient.GetAvatarAsPNG +// method. +type ContentNegotiationSameBodyClientGetAvatarAsPNGOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/payload/contentneggroup/zz_responses.go b/test/http-specs/payload/contentneggroup/zz_responses.go new file mode 100644 index 000000000000..d6bc14b10537 --- /dev/null +++ b/test/http-specs/payload/contentneggroup/zz_responses.go @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package contentneggroup + +import "io" + +// ContentNegotiationDifferentBodyClientGetAvatarAsJSONResponse contains the response from method ContentNegotiationDifferentBodyClient.GetAvatarAsJSON. +type ContentNegotiationDifferentBodyClientGetAvatarAsJSONResponse struct { + PNGImageAsJSON +} + +// ContentNegotiationDifferentBodyClientGetAvatarAsPNGResponse contains the response from method ContentNegotiationDifferentBodyClient.GetAvatarAsPNG. +type ContentNegotiationDifferentBodyClientGetAvatarAsPNGResponse struct { + // Body contains the streaming response. + Body io.ReadCloser + ContentType *string +} + +// ContentNegotiationSameBodyClientGetAvatarAsJPEGResponse contains the response from method ContentNegotiationSameBodyClient.GetAvatarAsJPEG. +type ContentNegotiationSameBodyClientGetAvatarAsJPEGResponse struct { + // Body contains the streaming response. + Body io.ReadCloser + ContentType *string +} + +// ContentNegotiationSameBodyClientGetAvatarAsPNGResponse contains the response from method ContentNegotiationSameBodyClient.GetAvatarAsPNG. +type ContentNegotiationSameBodyClientGetAvatarAsPNGResponse struct { + // Body contains the streaming response. + Body io.ReadCloser + ContentType *string +} diff --git a/test/http-specs/payload/contentneggroup/zz_version.go b/test/http-specs/payload/contentneggroup/zz_version.go new file mode 100644 index 000000000000..f12b156b5fe6 --- /dev/null +++ b/test/http-specs/payload/contentneggroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package contentneggroup + +const ( + moduleName = "contentneggroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/payload/jmergepatchgroup/LICENSE.txt b/test/http-specs/payload/jmergepatchgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/payload/jmergepatchgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/payload/jmergepatchgroup/fake/zz_internal.go b/test/http-specs/payload/jmergepatchgroup/fake/zz_internal.go new file mode 100644 index 000000000000..705f81eacafe --- /dev/null +++ b/test/http-specs/payload/jmergepatchgroup/fake/zz_internal.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import "net/http" + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} diff --git a/test/http-specs/payload/jmergepatchgroup/fake/zz_jsonmergepatch_server.go b/test/http-specs/payload/jmergepatchgroup/fake/zz_jsonmergepatch_server.go new file mode 100644 index 000000000000..03d3da2bf580 --- /dev/null +++ b/test/http-specs/payload/jmergepatchgroup/fake/zz_jsonmergepatch_server.go @@ -0,0 +1,163 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "jmergepatchgroup" + "net/http" + "slices" +) + +// JSONMergePatchServer is a fake server for instances of the jmergepatchgroup.JSONMergePatchClient type. +type JSONMergePatchServer struct { + // CreateResource is the fake for method JSONMergePatchClient.CreateResource + // HTTP status codes to indicate success: http.StatusOK + CreateResource func(ctx context.Context, body jmergepatchgroup.Resource, options *jmergepatchgroup.JSONMergePatchClientCreateResourceOptions) (resp azfake.Responder[jmergepatchgroup.JSONMergePatchClientCreateResourceResponse], errResp azfake.ErrorResponder) + + // UpdateOptionalResource is the fake for method JSONMergePatchClient.UpdateOptionalResource + // HTTP status codes to indicate success: http.StatusOK + UpdateOptionalResource func(ctx context.Context, body jmergepatchgroup.ResourcePatch, options *jmergepatchgroup.JSONMergePatchClientUpdateOptionalResourceOptions) (resp azfake.Responder[jmergepatchgroup.JSONMergePatchClientUpdateOptionalResourceResponse], errResp azfake.ErrorResponder) + + // UpdateResource is the fake for method JSONMergePatchClient.UpdateResource + // HTTP status codes to indicate success: http.StatusOK + UpdateResource func(ctx context.Context, body jmergepatchgroup.ResourcePatch, options *jmergepatchgroup.JSONMergePatchClientUpdateResourceOptions) (resp azfake.Responder[jmergepatchgroup.JSONMergePatchClientUpdateResourceResponse], errResp azfake.ErrorResponder) +} + +// NewJSONMergePatchServerTransport creates a new instance of JSONMergePatchServerTransport with the provided implementation. +// The returned JSONMergePatchServerTransport instance is connected to an instance of jmergepatchgroup.JSONMergePatchClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewJSONMergePatchServerTransport(srv *JSONMergePatchServer) *JSONMergePatchServerTransport { + return &JSONMergePatchServerTransport{srv: srv} +} + +// JSONMergePatchServerTransport connects instances of jmergepatchgroup.JSONMergePatchClient to instances of JSONMergePatchServer. +// Don't use this type directly, use NewJSONMergePatchServerTransport instead. +type JSONMergePatchServerTransport struct { + srv *JSONMergePatchServer +} + +// Do implements the policy.Transporter interface for JSONMergePatchServerTransport. +func (j *JSONMergePatchServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return j.dispatchToMethodFake(req, method) +} + +func (j *JSONMergePatchServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if jsonMergePatchServerTransportInterceptor != nil { + res.resp, res.err, intercepted = jsonMergePatchServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "JSONMergePatchClient.CreateResource": + res.resp, res.err = j.dispatchCreateResource(req) + case "JSONMergePatchClient.UpdateOptionalResource": + res.resp, res.err = j.dispatchUpdateOptionalResource(req) + case "JSONMergePatchClient.UpdateResource": + res.resp, res.err = j.dispatchUpdateResource(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (j *JSONMergePatchServerTransport) dispatchCreateResource(req *http.Request) (*http.Response, error) { + if j.srv.CreateResource == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateResource not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[jmergepatchgroup.Resource](req) + if err != nil { + return nil, err + } + respr, errRespr := j.srv.CreateResource(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Resource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (j *JSONMergePatchServerTransport) dispatchUpdateOptionalResource(req *http.Request) (*http.Response, error) { + if j.srv.UpdateOptionalResource == nil { + return nil, &nonRetriableError{errors.New("fake for method UpdateOptionalResource not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[jmergepatchgroup.ResourcePatch](req) + if err != nil { + return nil, err + } + respr, errRespr := j.srv.UpdateOptionalResource(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Resource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (j *JSONMergePatchServerTransport) dispatchUpdateResource(req *http.Request) (*http.Response, error) { + if j.srv.UpdateResource == nil { + return nil, &nonRetriableError{errors.New("fake for method UpdateResource not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[jmergepatchgroup.ResourcePatch](req) + if err != nil { + return nil, err + } + respr, errRespr := j.srv.UpdateResource(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Resource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to JSONMergePatchServerTransport +var jsonMergePatchServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/jmergepatchgroup/go.mod b/test/http-specs/payload/jmergepatchgroup/go.mod new file mode 100644 index 000000000000..f9b2b2fe509a --- /dev/null +++ b/test/http-specs/payload/jmergepatchgroup/go.mod @@ -0,0 +1,17 @@ +module jmergepatchgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/payload/jmergepatchgroup/go.sum b/test/http-specs/payload/jmergepatchgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/payload/jmergepatchgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/payload/jmergepatchgroup/jsonmergepatch_client_test.go b/test/http-specs/payload/jmergepatchgroup/jsonmergepatch_client_test.go new file mode 100644 index 000000000000..200353bb3b70 --- /dev/null +++ b/test/http-specs/payload/jmergepatchgroup/jsonmergepatch_client_test.go @@ -0,0 +1,131 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package jmergepatchgroup_test + +import ( + "context" + "jmergepatchgroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestJsonMergePatchClient_CreateResource(t *testing.T) { + client, err := jmergepatchgroup.NewJSONMergePatchClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.CreateResource(context.Background(), jmergepatchgroup.Resource{ + Name: to.Ptr("Madge"), + Description: to.Ptr("desc"), + Map: map[string]*jmergepatchgroup.InnerModel{ + "key": { + Name: to.Ptr("InnerMadge"), + Description: to.Ptr("innerDesc"), + }, + }, + Array: []*jmergepatchgroup.InnerModel{ + { + Name: to.Ptr("InnerMadge"), + Description: to.Ptr("innerDesc"), + }, + }, + IntValue: to.Ptr[int32](1), + FloatValue: to.Ptr[float32](1.25), + InnerModel: &jmergepatchgroup.InnerModel{ + Name: to.Ptr("InnerMadge"), + Description: to.Ptr("innerDesc"), + }, + IntArray: []*int32{ + to.Ptr[int32](1), + to.Ptr[int32](2), + to.Ptr[int32](3), + }, + }, nil) + require.NoError(t, err) + require.Equal(t, jmergepatchgroup.Resource{ + Name: to.Ptr("Madge"), + Description: to.Ptr("desc"), + Map: map[string]*jmergepatchgroup.InnerModel{ + "key": { + Name: to.Ptr("InnerMadge"), + Description: to.Ptr("innerDesc"), + }, + }, + Array: []*jmergepatchgroup.InnerModel{ + { + Name: to.Ptr("InnerMadge"), + Description: to.Ptr("innerDesc"), + }, + }, + IntValue: to.Ptr[int32](1), + FloatValue: to.Ptr[float32](1.25), + InnerModel: &jmergepatchgroup.InnerModel{ + Name: to.Ptr("InnerMadge"), + Description: to.Ptr("innerDesc"), + }, + IntArray: []*int32{ + to.Ptr[int32](1), + to.Ptr[int32](2), + to.Ptr[int32](3), + }, + }, resp.Resource) +} + +func TestJsonMergePatchClient_UpdateOptionalResource(t *testing.T) { + client, err := jmergepatchgroup.NewJSONMergePatchClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.UpdateOptionalResource(context.Background(), + jmergepatchgroup.ResourcePatch{ + Description: azcore.NullValue[*string](), + Map: map[string]*jmergepatchgroup.InnerModel{ + "key": { + Description: azcore.NullValue[*string](), + }, + "key2": nil, + }, + Array: azcore.NullValue[[]*jmergepatchgroup.InnerModel](), + IntValue: azcore.NullValue[*int32](), + FloatValue: azcore.NullValue[*float32](), + InnerModel: azcore.NullValue[*jmergepatchgroup.InnerModel](), + IntArray: azcore.NullValue[[]*int32](), + }, nil) + require.NoError(t, err) + require.Equal(t, jmergepatchgroup.Resource{ + Name: to.Ptr("Madge"), + Map: map[string]*jmergepatchgroup.InnerModel{ + "key": { + Name: to.Ptr("InnerMadge"), + }, + }, + }, resp.Resource) +} + +func TestJsonMergePatchClient_UpdateResource(t *testing.T) { + client, err := jmergepatchgroup.NewJSONMergePatchClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.UpdateResource(context.Background(), jmergepatchgroup.ResourcePatch{ + Description: azcore.NullValue[*string](), + Map: map[string]*jmergepatchgroup.InnerModel{ + "key": { + Description: azcore.NullValue[*string](), + }, + "key2": nil, + }, + Array: azcore.NullValue[[]*jmergepatchgroup.InnerModel](), + IntValue: azcore.NullValue[*int32](), + FloatValue: azcore.NullValue[*float32](), + InnerModel: azcore.NullValue[*jmergepatchgroup.InnerModel](), + IntArray: azcore.NullValue[[]*int32](), + }, nil) + require.NoError(t, err) + require.Equal(t, jmergepatchgroup.Resource{ + Name: to.Ptr("Madge"), + Map: map[string]*jmergepatchgroup.InnerModel{ + "key": { + Name: to.Ptr("InnerMadge"), + }, + }, + }, resp.Resource) +} diff --git a/test/http-specs/payload/jmergepatchgroup/testdata/_metadata.json b/test/http-specs/payload/jmergepatchgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/payload/jmergepatchgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/payload/jmergepatchgroup/zz_jsonmergepatch_client.go b/test/http-specs/payload/jmergepatchgroup/zz_jsonmergepatch_client.go new file mode 100644 index 000000000000..15e0a26fae58 --- /dev/null +++ b/test/http-specs/payload/jmergepatchgroup/zz_jsonmergepatch_client.go @@ -0,0 +1,193 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package jmergepatchgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// JSONMergePatchClient - Test for merge-patch+json content-type +// Don't use this type directly, use NewJSONMergePatchClientWithNoCredential() instead. +type JSONMergePatchClient struct { + internal *azcore.Client + endpoint string +} + +// JSONMergePatchClientOptions contains the optional values for creating a [JSONMergePatchClient]. +type JSONMergePatchClientOptions struct { + azcore.ClientOptions +} + +// NewJSONMergePatchClientWithNoCredential creates a new instance of JSONMergePatchClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewJSONMergePatchClientWithNoCredential(endpoint string, options *JSONMergePatchClientOptions) (*JSONMergePatchClient, error) { + if options == nil { + options = &JSONMergePatchClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &JSONMergePatchClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// CreateResource - Test content-type: application/merge-patch+json with required body +// If the operation fails it returns an *azcore.ResponseError type. +// - options - JSONMergePatchClientCreateResourceOptions contains the optional parameters for the JSONMergePatchClient.CreateResource +// method. +func (client *JSONMergePatchClient) CreateResource(ctx context.Context, body Resource, options *JSONMergePatchClientCreateResourceOptions) (JSONMergePatchClientCreateResourceResponse, error) { + var err error + const operationName = "JSONMergePatchClient.CreateResource" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createResourceCreateRequest(ctx, body, options) + if err != nil { + return JSONMergePatchClientCreateResourceResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return JSONMergePatchClientCreateResourceResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return JSONMergePatchClientCreateResourceResponse{}, err + } + resp, err := client.createResourceHandleResponse(httpResp) + return resp, err +} + +// createResourceCreateRequest creates the CreateResource request. +func (client *JSONMergePatchClient) createResourceCreateRequest(ctx context.Context, body Resource, _ *JSONMergePatchClientCreateResourceOptions) (*policy.Request, error) { + urlPath := "/json-merge-patch/create/resource" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// createResourceHandleResponse handles the CreateResource response. +func (client *JSONMergePatchClient) createResourceHandleResponse(resp *http.Response) (JSONMergePatchClientCreateResourceResponse, error) { + result := JSONMergePatchClientCreateResourceResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Resource); err != nil { + return JSONMergePatchClientCreateResourceResponse{}, err + } + return result, nil +} + +// UpdateOptionalResource - Test content-type: application/merge-patch+json with optional body +// If the operation fails it returns an *azcore.ResponseError type. +// - options - JSONMergePatchClientUpdateOptionalResourceOptions contains the optional parameters for the JSONMergePatchClient.UpdateOptionalResource +// method. +func (client *JSONMergePatchClient) UpdateOptionalResource(ctx context.Context, body ResourcePatch, options *JSONMergePatchClientUpdateOptionalResourceOptions) (JSONMergePatchClientUpdateOptionalResourceResponse, error) { + var err error + const operationName = "JSONMergePatchClient.UpdateOptionalResource" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateOptionalResourceCreateRequest(ctx, body, options) + if err != nil { + return JSONMergePatchClientUpdateOptionalResourceResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return JSONMergePatchClientUpdateOptionalResourceResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return JSONMergePatchClientUpdateOptionalResourceResponse{}, err + } + resp, err := client.updateOptionalResourceHandleResponse(httpResp) + return resp, err +} + +// updateOptionalResourceCreateRequest creates the UpdateOptionalResource request. +func (client *JSONMergePatchClient) updateOptionalResourceCreateRequest(ctx context.Context, body ResourcePatch, _ *JSONMergePatchClientUpdateOptionalResourceOptions) (*policy.Request, error) { + urlPath := "/json-merge-patch/update/resource/optional" + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/merge-patch+json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// updateOptionalResourceHandleResponse handles the UpdateOptionalResource response. +func (client *JSONMergePatchClient) updateOptionalResourceHandleResponse(resp *http.Response) (JSONMergePatchClientUpdateOptionalResourceResponse, error) { + result := JSONMergePatchClientUpdateOptionalResourceResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Resource); err != nil { + return JSONMergePatchClientUpdateOptionalResourceResponse{}, err + } + return result, nil +} + +// UpdateResource - Test content-type: application/merge-patch+json with required body +// If the operation fails it returns an *azcore.ResponseError type. +// - options - JSONMergePatchClientUpdateResourceOptions contains the optional parameters for the JSONMergePatchClient.UpdateResource +// method. +func (client *JSONMergePatchClient) UpdateResource(ctx context.Context, body ResourcePatch, options *JSONMergePatchClientUpdateResourceOptions) (JSONMergePatchClientUpdateResourceResponse, error) { + var err error + const operationName = "JSONMergePatchClient.UpdateResource" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateResourceCreateRequest(ctx, body, options) + if err != nil { + return JSONMergePatchClientUpdateResourceResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return JSONMergePatchClientUpdateResourceResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return JSONMergePatchClientUpdateResourceResponse{}, err + } + resp, err := client.updateResourceHandleResponse(httpResp) + return resp, err +} + +// updateResourceCreateRequest creates the UpdateResource request. +func (client *JSONMergePatchClient) updateResourceCreateRequest(ctx context.Context, body ResourcePatch, _ *JSONMergePatchClientUpdateResourceOptions) (*policy.Request, error) { + urlPath := "/json-merge-patch/update/resource" + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/merge-patch+json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// updateResourceHandleResponse handles the UpdateResource response. +func (client *JSONMergePatchClient) updateResourceHandleResponse(resp *http.Response) (JSONMergePatchClientUpdateResourceResponse, error) { + result := JSONMergePatchClientUpdateResourceResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Resource); err != nil { + return JSONMergePatchClientUpdateResourceResponse{}, err + } + return result, nil +} diff --git a/test/http-specs/payload/jmergepatchgroup/zz_models.go b/test/http-specs/payload/jmergepatchgroup/zz_models.go new file mode 100644 index 000000000000..a090249366ca --- /dev/null +++ b/test/http-specs/payload/jmergepatchgroup/zz_models.go @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package jmergepatchgroup + +// InnerModel - It is the model used by Resource model +type InnerModel struct { + Description *string + Name *string +} + +// Resource - Details about a resource. +type Resource struct { + // REQUIRED + Name *string + Array []*InnerModel + Description *string + FloatValue *float32 + InnerModel *InnerModel + IntArray []*int32 + IntValue *int32 + Map map[string]*InnerModel +} + +// ResourcePatch - Details about a resource for patch operation. +type ResourcePatch struct { + Array []*InnerModel + Description *string + FloatValue *float32 + InnerModel *InnerModel + IntArray []*int32 + IntValue *int32 + Map map[string]*InnerModel +} diff --git a/test/http-specs/payload/jmergepatchgroup/zz_models_serde.go b/test/http-specs/payload/jmergepatchgroup/zz_models_serde.go new file mode 100644 index 000000000000..cc4a873e1f51 --- /dev/null +++ b/test/http-specs/payload/jmergepatchgroup/zz_models_serde.go @@ -0,0 +1,169 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package jmergepatchgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type InnerModel. +func (i InnerModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", i.Description) + populate(objectMap, "name", i.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InnerModel. +func (i *InnerModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &i.Description) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &i.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Resource. +func (r Resource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "array", r.Array) + populate(objectMap, "description", r.Description) + populate(objectMap, "floatValue", r.FloatValue) + populate(objectMap, "innerModel", r.InnerModel) + populate(objectMap, "intArray", r.IntArray) + populate(objectMap, "intValue", r.IntValue) + populate(objectMap, "map", r.Map) + populate(objectMap, "name", r.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Resource. +func (r *Resource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "array": + err = unpopulate(val, "Array", &r.Array) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &r.Description) + delete(rawMsg, key) + case "floatValue": + err = unpopulate(val, "FloatValue", &r.FloatValue) + delete(rawMsg, key) + case "innerModel": + err = unpopulate(val, "InnerModel", &r.InnerModel) + delete(rawMsg, key) + case "intArray": + err = unpopulate(val, "IntArray", &r.IntArray) + delete(rawMsg, key) + case "intValue": + err = unpopulate(val, "IntValue", &r.IntValue) + delete(rawMsg, key) + case "map": + err = unpopulate(val, "Map", &r.Map) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourcePatch. +func (r ResourcePatch) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "array", r.Array) + populate(objectMap, "description", r.Description) + populate(objectMap, "floatValue", r.FloatValue) + populate(objectMap, "innerModel", r.InnerModel) + populate(objectMap, "intArray", r.IntArray) + populate(objectMap, "intValue", r.IntValue) + populate(objectMap, "map", r.Map) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourcePatch. +func (r *ResourcePatch) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "array": + err = unpopulate(val, "Array", &r.Array) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &r.Description) + delete(rawMsg, key) + case "floatValue": + err = unpopulate(val, "FloatValue", &r.FloatValue) + delete(rawMsg, key) + case "innerModel": + err = unpopulate(val, "InnerModel", &r.InnerModel) + delete(rawMsg, key) + case "intArray": + err = unpopulate(val, "IntArray", &r.IntArray) + delete(rawMsg, key) + case "intValue": + err = unpopulate(val, "IntValue", &r.IntValue) + delete(rawMsg, key) + case "map": + err = unpopulate(val, "Map", &r.Map) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/http-specs/payload/jmergepatchgroup/zz_options.go b/test/http-specs/payload/jmergepatchgroup/zz_options.go new file mode 100644 index 000000000000..1b6ba91cb888 --- /dev/null +++ b/test/http-specs/payload/jmergepatchgroup/zz_options.go @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package jmergepatchgroup + +// JSONMergePatchClientCreateResourceOptions contains the optional parameters for the JSONMergePatchClient.CreateResource +// method. +type JSONMergePatchClientCreateResourceOptions struct { + // placeholder for future optional parameters +} + +// JSONMergePatchClientUpdateOptionalResourceOptions contains the optional parameters for the JSONMergePatchClient.UpdateOptionalResource +// method. +type JSONMergePatchClientUpdateOptionalResourceOptions struct { + // placeholder for future optional parameters +} + +// JSONMergePatchClientUpdateResourceOptions contains the optional parameters for the JSONMergePatchClient.UpdateResource +// method. +type JSONMergePatchClientUpdateResourceOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/payload/jmergepatchgroup/zz_responses.go b/test/http-specs/payload/jmergepatchgroup/zz_responses.go new file mode 100644 index 000000000000..96ae297e5327 --- /dev/null +++ b/test/http-specs/payload/jmergepatchgroup/zz_responses.go @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package jmergepatchgroup + +// JSONMergePatchClientCreateResourceResponse contains the response from method JSONMergePatchClient.CreateResource. +type JSONMergePatchClientCreateResourceResponse struct { + // Details about a resource. + Resource +} + +// JSONMergePatchClientUpdateOptionalResourceResponse contains the response from method JSONMergePatchClient.UpdateOptionalResource. +type JSONMergePatchClientUpdateOptionalResourceResponse struct { + // Details about a resource. + Resource +} + +// JSONMergePatchClientUpdateResourceResponse contains the response from method JSONMergePatchClient.UpdateResource. +type JSONMergePatchClientUpdateResourceResponse struct { + // Details about a resource. + Resource +} diff --git a/test/http-specs/payload/jmergepatchgroup/zz_version.go b/test/http-specs/payload/jmergepatchgroup/zz_version.go new file mode 100644 index 000000000000..927be9daaa17 --- /dev/null +++ b/test/http-specs/payload/jmergepatchgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package jmergepatchgroup + +const ( + moduleName = "jmergepatchgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/payload/mediatypegroup/LICENSE.txt b/test/http-specs/payload/mediatypegroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/payload/mediatypegroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/payload/mediatypegroup/fake/zz_internal.go b/test/http-specs/payload/mediatypegroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/http-specs/payload/mediatypegroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/http-specs/payload/mediatypegroup/fake/zz_mediatype_server.go b/test/http-specs/payload/mediatypegroup/fake/zz_mediatype_server.go new file mode 100644 index 000000000000..bfbf37cfce79 --- /dev/null +++ b/test/http-specs/payload/mediatypegroup/fake/zz_mediatype_server.go @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// MediaTypeServer is a fake server for instances of the mediatypegroup.MediaTypeClient type. +type MediaTypeServer struct { + // MediaTypeStringBodyServer contains the fakes for client MediaTypeStringBodyClient + MediaTypeStringBodyServer MediaTypeStringBodyServer +} + +// NewMediaTypeServerTransport creates a new instance of MediaTypeServerTransport with the provided implementation. +// The returned MediaTypeServerTransport instance is connected to an instance of mediatypegroup.MediaTypeClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewMediaTypeServerTransport(srv *MediaTypeServer) *MediaTypeServerTransport { + return &MediaTypeServerTransport{srv: srv} +} + +// MediaTypeServerTransport connects instances of mediatypegroup.MediaTypeClient to instances of MediaTypeServer. +// Don't use this type directly, use NewMediaTypeServerTransport instead. +type MediaTypeServerTransport struct { + srv *MediaTypeServer + trMu sync.Mutex + trMediaTypeStringBodyServer *MediaTypeStringBodyServerTransport +} + +// Do implements the policy.Transporter interface for MediaTypeServerTransport. +func (m *MediaTypeServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (m *MediaTypeServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "MediaTypeStringBodyClient": + initServer(&m.trMu, &m.trMediaTypeStringBodyServer, func() *MediaTypeStringBodyServerTransport { + return NewMediaTypeStringBodyServerTransport(&m.srv.MediaTypeStringBodyServer) + }) + resp, err = m.trMediaTypeStringBodyServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to MediaTypeServerTransport +var mediaTypeServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/mediatypegroup/fake/zz_mediatypestringbody_server.go b/test/http-specs/payload/mediatypegroup/fake/zz_mediatypestringbody_server.go new file mode 100644 index 000000000000..899f49edf526 --- /dev/null +++ b/test/http-specs/payload/mediatypegroup/fake/zz_mediatypestringbody_server.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "mediatypegroup" + "net/http" + "slices" +) + +// MediaTypeStringBodyServer is a fake server for instances of the mediatypegroup.MediaTypeStringBodyClient type. +type MediaTypeStringBodyServer struct { + // GetAsJSON is the fake for method MediaTypeStringBodyClient.GetAsJSON + // HTTP status codes to indicate success: http.StatusOK + GetAsJSON func(ctx context.Context, options *mediatypegroup.MediaTypeStringBodyClientGetAsJSONOptions) (resp azfake.Responder[mediatypegroup.MediaTypeStringBodyClientGetAsJSONResponse], errResp azfake.ErrorResponder) + + // GetAsText is the fake for method MediaTypeStringBodyClient.GetAsText + // HTTP status codes to indicate success: http.StatusOK + GetAsText func(ctx context.Context, options *mediatypegroup.MediaTypeStringBodyClientGetAsTextOptions) (resp azfake.Responder[mediatypegroup.MediaTypeStringBodyClientGetAsTextResponse], errResp azfake.ErrorResponder) + + // SendAsJSON is the fake for method MediaTypeStringBodyClient.SendAsJSON + // HTTP status codes to indicate success: http.StatusOK + SendAsJSON func(ctx context.Context, textParam string, options *mediatypegroup.MediaTypeStringBodyClientSendAsJSONOptions) (resp azfake.Responder[mediatypegroup.MediaTypeStringBodyClientSendAsJSONResponse], errResp azfake.ErrorResponder) + + // SendAsText is the fake for method MediaTypeStringBodyClient.SendAsText + // HTTP status codes to indicate success: http.StatusOK + SendAsText func(ctx context.Context, textParam string, options *mediatypegroup.MediaTypeStringBodyClientSendAsTextOptions) (resp azfake.Responder[mediatypegroup.MediaTypeStringBodyClientSendAsTextResponse], errResp azfake.ErrorResponder) +} + +// NewMediaTypeStringBodyServerTransport creates a new instance of MediaTypeStringBodyServerTransport with the provided implementation. +// The returned MediaTypeStringBodyServerTransport instance is connected to an instance of mediatypegroup.MediaTypeStringBodyClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewMediaTypeStringBodyServerTransport(srv *MediaTypeStringBodyServer) *MediaTypeStringBodyServerTransport { + return &MediaTypeStringBodyServerTransport{srv: srv} +} + +// MediaTypeStringBodyServerTransport connects instances of mediatypegroup.MediaTypeStringBodyClient to instances of MediaTypeStringBodyServer. +// Don't use this type directly, use NewMediaTypeStringBodyServerTransport instead. +type MediaTypeStringBodyServerTransport struct { + srv *MediaTypeStringBodyServer +} + +// Do implements the policy.Transporter interface for MediaTypeStringBodyServerTransport. +func (m *MediaTypeStringBodyServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToMethodFake(req, method) +} + +func (m *MediaTypeStringBodyServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if mediaTypeStringBodyServerTransportInterceptor != nil { + res.resp, res.err, intercepted = mediaTypeStringBodyServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "MediaTypeStringBodyClient.GetAsJSON": + res.resp, res.err = m.dispatchGetAsJSON(req) + case "MediaTypeStringBodyClient.GetAsText": + res.resp, res.err = m.dispatchGetAsText(req) + case "MediaTypeStringBodyClient.SendAsJSON": + res.resp, res.err = m.dispatchSendAsJSON(req) + case "MediaTypeStringBodyClient.SendAsText": + res.resp, res.err = m.dispatchSendAsText(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *MediaTypeStringBodyServerTransport) dispatchGetAsJSON(req *http.Request) (*http.Response, error) { + if m.srv.GetAsJSON == nil { + return nil, &nonRetriableError{errors.New("fake for method GetAsJSON not implemented")} + } + respr, errRespr := m.srv.GetAsJSON(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Value, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *MediaTypeStringBodyServerTransport) dispatchGetAsText(req *http.Request) (*http.Response, error) { + if m.srv.GetAsText == nil { + return nil, &nonRetriableError{errors.New("fake for method GetAsText not implemented")} + } + respr, errRespr := m.srv.GetAsText(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsText(respContent, server.GetResponse(respr).Value, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *MediaTypeStringBodyServerTransport) dispatchSendAsJSON(req *http.Request) (*http.Response, error) { + if m.srv.SendAsJSON == nil { + return nil, &nonRetriableError{errors.New("fake for method SendAsJSON not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[string](req) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.SendAsJSON(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *MediaTypeStringBodyServerTransport) dispatchSendAsText(req *http.Request) (*http.Response, error) { + if m.srv.SendAsText == nil { + return nil, &nonRetriableError{errors.New("fake for method SendAsText not implemented")} + } + body, err := server.UnmarshalRequestAsText(req) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.SendAsText(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to MediaTypeStringBodyServerTransport +var mediaTypeStringBodyServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/mediatypegroup/go.mod b/test/http-specs/payload/mediatypegroup/go.mod new file mode 100644 index 000000000000..6a007bb47b58 --- /dev/null +++ b/test/http-specs/payload/mediatypegroup/go.mod @@ -0,0 +1,17 @@ +module mediatypegroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/payload/mediatypegroup/go.sum b/test/http-specs/payload/mediatypegroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/payload/mediatypegroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/payload/mediatypegroup/stringbody_client_test.go b/test/http-specs/payload/mediatypegroup/stringbody_client_test.go new file mode 100644 index 000000000000..3ecac1a603c0 --- /dev/null +++ b/test/http-specs/payload/mediatypegroup/stringbody_client_test.go @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package mediatypegroup_test + +import ( + "context" + "mediatypegroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestStringBodyClient_GetAsJSON(t *testing.T) { + client, err := mediatypegroup.NewMediaTypeClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewMediaTypeStringBodyClient().GetAsJSON(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.Equal(t, "foo", *resp.Value) +} + +func TestStringBodyClient_GetAsText(t *testing.T) { + client, err := mediatypegroup.NewMediaTypeClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewMediaTypeStringBodyClient().GetAsText(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.Equal(t, "{cat}", *resp.Value) +} + +func TestStringBodyClient_SendAsJSON(t *testing.T) { + client, err := mediatypegroup.NewMediaTypeClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewMediaTypeStringBodyClient().SendAsJSON(context.Background(), "foo", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestStringBodyClient_SendAsText(t *testing.T) { + client, err := mediatypegroup.NewMediaTypeClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewMediaTypeStringBodyClient().SendAsText(context.Background(), "{cat}", nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/mediatypegroup/testdata/_metadata.json b/test/http-specs/payload/mediatypegroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/payload/mediatypegroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/payload/mediatypegroup/zz_mediatype_client.go b/test/http-specs/payload/mediatypegroup/zz_mediatype_client.go new file mode 100644 index 000000000000..005c40b18983 --- /dev/null +++ b/test/http-specs/payload/mediatypegroup/zz_mediatype_client.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package mediatypegroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// MediaTypeClient - Test the payload with different media types and different types of the payload itself. +// Don't use this type directly, use NewMediaTypeClientWithNoCredential() instead. +type MediaTypeClient struct { + internal *azcore.Client + endpoint string +} + +// MediaTypeClientOptions contains the optional values for creating a [MediaTypeClient]. +type MediaTypeClientOptions struct { + azcore.ClientOptions +} + +// NewMediaTypeClientWithNoCredential creates a new instance of MediaTypeClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewMediaTypeClientWithNoCredential(endpoint string, options *MediaTypeClientOptions) (*MediaTypeClient, error) { + if options == nil { + options = &MediaTypeClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &MediaTypeClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewMediaTypeStringBodyClient creates a new instance of [MediaTypeStringBodyClient]. +func (client *MediaTypeClient) NewMediaTypeStringBodyClient() *MediaTypeStringBodyClient { + return &MediaTypeStringBodyClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/http-specs/payload/mediatypegroup/zz_mediatypestringbody_client.go b/test/http-specs/payload/mediatypegroup/zz_mediatypestringbody_client.go new file mode 100644 index 000000000000..3010ac9e7711 --- /dev/null +++ b/test/http-specs/payload/mediatypegroup/zz_mediatypestringbody_client.go @@ -0,0 +1,196 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package mediatypegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming" + "net/http" + "strings" +) + +// MediaTypeStringBodyClient contains the methods for the MediaTypeStringBody group. +// Don't use this type directly, use [MediaTypeClient.NewMediaTypeStringBodyClient] instead. +type MediaTypeStringBodyClient struct { + internal *azcore.Client + endpoint string +} + +// GetAsJSON - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MediaTypeStringBodyClientGetAsJSONOptions contains the optional parameters for the MediaTypeStringBodyClient.GetAsJSON +// method. +func (client *MediaTypeStringBodyClient) GetAsJSON(ctx context.Context, options *MediaTypeStringBodyClientGetAsJSONOptions) (MediaTypeStringBodyClientGetAsJSONResponse, error) { + var err error + const operationName = "MediaTypeStringBodyClient.GetAsJSON" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getAsJSONCreateRequest(ctx, options) + if err != nil { + return MediaTypeStringBodyClientGetAsJSONResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MediaTypeStringBodyClientGetAsJSONResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return MediaTypeStringBodyClientGetAsJSONResponse{}, err + } + resp, err := client.getAsJSONHandleResponse(httpResp) + return resp, err +} + +// getAsJSONCreateRequest creates the GetAsJSON request. +func (client *MediaTypeStringBodyClient) getAsJSONCreateRequest(ctx context.Context, _ *MediaTypeStringBodyClientGetAsJSONOptions) (*policy.Request, error) { + urlPath := "/payload/media-type/string-body/getAsJson" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getAsJSONHandleResponse handles the GetAsJSON response. +func (client *MediaTypeStringBodyClient) getAsJSONHandleResponse(resp *http.Response) (MediaTypeStringBodyClientGetAsJSONResponse, error) { + result := MediaTypeStringBodyClientGetAsJSONResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Value); err != nil { + return MediaTypeStringBodyClientGetAsJSONResponse{}, err + } + return result, nil +} + +// GetAsText - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MediaTypeStringBodyClientGetAsTextOptions contains the optional parameters for the MediaTypeStringBodyClient.GetAsText +// method. +func (client *MediaTypeStringBodyClient) GetAsText(ctx context.Context, options *MediaTypeStringBodyClientGetAsTextOptions) (MediaTypeStringBodyClientGetAsTextResponse, error) { + var err error + const operationName = "MediaTypeStringBodyClient.GetAsText" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getAsTextCreateRequest(ctx, options) + if err != nil { + return MediaTypeStringBodyClientGetAsTextResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MediaTypeStringBodyClientGetAsTextResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return MediaTypeStringBodyClientGetAsTextResponse{}, err + } + resp, err := client.getAsTextHandleResponse(httpResp) + return resp, err +} + +// getAsTextCreateRequest creates the GetAsText request. +func (client *MediaTypeStringBodyClient) getAsTextCreateRequest(ctx context.Context, _ *MediaTypeStringBodyClientGetAsTextOptions) (*policy.Request, error) { + urlPath := "/payload/media-type/string-body/getAsText" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"text/plain"} + return req, nil +} + +// getAsTextHandleResponse handles the GetAsText response. +func (client *MediaTypeStringBodyClient) getAsTextHandleResponse(resp *http.Response) (MediaTypeStringBodyClientGetAsTextResponse, error) { + result := MediaTypeStringBodyClientGetAsTextResponse{} + body, err := runtime.Payload(resp) + if err != nil { + return MediaTypeStringBodyClientGetAsTextResponse{}, err + } + txt := string(body) + result.Value = &txt + return result, nil +} + +// SendAsJSON - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MediaTypeStringBodyClientSendAsJSONOptions contains the optional parameters for the MediaTypeStringBodyClient.SendAsJSON +// method. +func (client *MediaTypeStringBodyClient) SendAsJSON(ctx context.Context, textParam string, options *MediaTypeStringBodyClientSendAsJSONOptions) (MediaTypeStringBodyClientSendAsJSONResponse, error) { + var err error + const operationName = "MediaTypeStringBodyClient.SendAsJSON" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.sendAsJSONCreateRequest(ctx, textParam, options) + if err != nil { + return MediaTypeStringBodyClientSendAsJSONResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MediaTypeStringBodyClientSendAsJSONResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return MediaTypeStringBodyClientSendAsJSONResponse{}, err + } + return MediaTypeStringBodyClientSendAsJSONResponse{}, nil +} + +// sendAsJSONCreateRequest creates the SendAsJSON request. +func (client *MediaTypeStringBodyClient) sendAsJSONCreateRequest(ctx context.Context, textParam string, _ *MediaTypeStringBodyClientSendAsJSONOptions) (*policy.Request, error) { + urlPath := "/payload/media-type/string-body/sendAsJson" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, textParam); err != nil { + return nil, err + } + return req, nil +} + +// SendAsText - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MediaTypeStringBodyClientSendAsTextOptions contains the optional parameters for the MediaTypeStringBodyClient.SendAsText +// method. +func (client *MediaTypeStringBodyClient) SendAsText(ctx context.Context, textParam string, options *MediaTypeStringBodyClientSendAsTextOptions) (MediaTypeStringBodyClientSendAsTextResponse, error) { + var err error + const operationName = "MediaTypeStringBodyClient.SendAsText" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.sendAsTextCreateRequest(ctx, textParam, options) + if err != nil { + return MediaTypeStringBodyClientSendAsTextResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MediaTypeStringBodyClientSendAsTextResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return MediaTypeStringBodyClientSendAsTextResponse{}, err + } + return MediaTypeStringBodyClientSendAsTextResponse{}, nil +} + +// sendAsTextCreateRequest creates the SendAsText request. +func (client *MediaTypeStringBodyClient) sendAsTextCreateRequest(ctx context.Context, textParam string, _ *MediaTypeStringBodyClientSendAsTextOptions) (*policy.Request, error) { + urlPath := "/payload/media-type/string-body/sendAsText" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + body := streaming.NopCloser(strings.NewReader(textParam)) + req.Raw().Header["Content-Type"] = []string{"text/plain"} + if err := req.SetBody(body, "text/plain"); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/mediatypegroup/zz_options.go b/test/http-specs/payload/mediatypegroup/zz_options.go new file mode 100644 index 000000000000..32a984ea859b --- /dev/null +++ b/test/http-specs/payload/mediatypegroup/zz_options.go @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package mediatypegroup + +// MediaTypeStringBodyClientGetAsJSONOptions contains the optional parameters for the MediaTypeStringBodyClient.GetAsJSON +// method. +type MediaTypeStringBodyClientGetAsJSONOptions struct { + // placeholder for future optional parameters +} + +// MediaTypeStringBodyClientGetAsTextOptions contains the optional parameters for the MediaTypeStringBodyClient.GetAsText +// method. +type MediaTypeStringBodyClientGetAsTextOptions struct { + // placeholder for future optional parameters +} + +// MediaTypeStringBodyClientSendAsJSONOptions contains the optional parameters for the MediaTypeStringBodyClient.SendAsJSON +// method. +type MediaTypeStringBodyClientSendAsJSONOptions struct { + // placeholder for future optional parameters +} + +// MediaTypeStringBodyClientSendAsTextOptions contains the optional parameters for the MediaTypeStringBodyClient.SendAsText +// method. +type MediaTypeStringBodyClientSendAsTextOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/payload/mediatypegroup/zz_responses.go b/test/http-specs/payload/mediatypegroup/zz_responses.go new file mode 100644 index 000000000000..b245ba88cf56 --- /dev/null +++ b/test/http-specs/payload/mediatypegroup/zz_responses.go @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package mediatypegroup + +// MediaTypeStringBodyClientGetAsJSONResponse contains the response from method MediaTypeStringBodyClient.GetAsJSON. +type MediaTypeStringBodyClientGetAsJSONResponse struct { + Value *string +} + +// MediaTypeStringBodyClientGetAsTextResponse contains the response from method MediaTypeStringBodyClient.GetAsText. +type MediaTypeStringBodyClientGetAsTextResponse struct { + Value *string +} + +// MediaTypeStringBodyClientSendAsJSONResponse contains the response from method MediaTypeStringBodyClient.SendAsJSON. +type MediaTypeStringBodyClientSendAsJSONResponse struct { + // placeholder for future response values +} + +// MediaTypeStringBodyClientSendAsTextResponse contains the response from method MediaTypeStringBodyClient.SendAsText. +type MediaTypeStringBodyClientSendAsTextResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/payload/mediatypegroup/zz_version.go b/test/http-specs/payload/mediatypegroup/zz_version.go new file mode 100644 index 000000000000..0fad0b86ea80 --- /dev/null +++ b/test/http-specs/payload/mediatypegroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package mediatypegroup + +const ( + moduleName = "mediatypegroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/payload/multipartgroup/LICENSE.txt b/test/http-specs/payload/multipartgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/payload/multipartgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/payload/multipartgroup/fake/zz_internal.go b/test/http-specs/payload/multipartgroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/http-specs/payload/multipartgroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/http-specs/payload/multipartgroup/fake/zz_multipart_server.go b/test/http-specs/payload/multipartgroup/fake/zz_multipart_server.go new file mode 100644 index 000000000000..570b4a0c8d96 --- /dev/null +++ b/test/http-specs/payload/multipartgroup/fake/zz_multipart_server.go @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// MultiPartServer is a fake server for instances of the multipartgroup.MultiPartClient type. +type MultiPartServer struct { + // MultiPartFormDataServer contains the fakes for client MultiPartFormDataClient + MultiPartFormDataServer MultiPartFormDataServer +} + +// NewMultiPartServerTransport creates a new instance of MultiPartServerTransport with the provided implementation. +// The returned MultiPartServerTransport instance is connected to an instance of multipartgroup.MultiPartClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewMultiPartServerTransport(srv *MultiPartServer) *MultiPartServerTransport { + return &MultiPartServerTransport{srv: srv} +} + +// MultiPartServerTransport connects instances of multipartgroup.MultiPartClient to instances of MultiPartServer. +// Don't use this type directly, use NewMultiPartServerTransport instead. +type MultiPartServerTransport struct { + srv *MultiPartServer + trMu sync.Mutex + trMultiPartFormDataServer *MultiPartFormDataServerTransport +} + +// Do implements the policy.Transporter interface for MultiPartServerTransport. +func (m *MultiPartServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (m *MultiPartServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "MultiPartFormDataClient", "MultiPartFormDataFileClient", "MultiPartFormDataHTTPPartsClient", "MultiPartFormDataHTTPPartsContentTypeClient", "MultiPartFormDataHTTPPartsNonStringClient": + initServer(&m.trMu, &m.trMultiPartFormDataServer, func() *MultiPartFormDataServerTransport { + return NewMultiPartFormDataServerTransport(&m.srv.MultiPartFormDataServer) + }) + resp, err = m.trMultiPartFormDataServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to MultiPartServerTransport +var multiPartServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/multipartgroup/fake/zz_multipartformdata_server.go b/test/http-specs/payload/multipartgroup/fake/zz_multipartformdata_server.go new file mode 100644 index 000000000000..7827285137ab --- /dev/null +++ b/test/http-specs/payload/multipartgroup/fake/zz_multipartformdata_server.go @@ -0,0 +1,666 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "io" + "mime" + "mime/multipart" + "multipartgroup" + "net/http" + "slices" + "strings" + "sync" +) + +// MultiPartFormDataServer is a fake server for instances of the multipartgroup.MultiPartFormDataClient type. +type MultiPartFormDataServer struct { + // MultiPartFormDataFileServer contains the fakes for client MultiPartFormDataFileClient + MultiPartFormDataFileServer MultiPartFormDataFileServer + + // MultiPartFormDataHTTPPartsServer contains the fakes for client MultiPartFormDataHTTPPartsClient + MultiPartFormDataHTTPPartsServer MultiPartFormDataHTTPPartsServer + + // AnonymousModel is the fake for method MultiPartFormDataClient.AnonymousModel + // HTTP status codes to indicate success: http.StatusNoContent + AnonymousModel func(ctx context.Context, profileImage io.ReadSeekCloser, options *multipartgroup.MultiPartFormDataClientAnonymousModelOptions) (resp azfake.Responder[multipartgroup.MultiPartFormDataClientAnonymousModelResponse], errResp azfake.ErrorResponder) + + // Basic is the fake for method MultiPartFormDataClient.Basic + // HTTP status codes to indicate success: http.StatusNoContent + Basic func(ctx context.Context, body multipartgroup.MultiPartRequest, options *multipartgroup.MultiPartFormDataClientBasicOptions) (resp azfake.Responder[multipartgroup.MultiPartFormDataClientBasicResponse], errResp azfake.ErrorResponder) + + // BinaryArrayParts is the fake for method MultiPartFormDataClient.BinaryArrayParts + // HTTP status codes to indicate success: http.StatusNoContent + BinaryArrayParts func(ctx context.Context, body multipartgroup.BinaryArrayPartsRequest, options *multipartgroup.MultiPartFormDataClientBinaryArrayPartsOptions) (resp azfake.Responder[multipartgroup.MultiPartFormDataClientBinaryArrayPartsResponse], errResp azfake.ErrorResponder) + + // CheckFileNameAndContentType is the fake for method MultiPartFormDataClient.CheckFileNameAndContentType + // HTTP status codes to indicate success: http.StatusNoContent + CheckFileNameAndContentType func(ctx context.Context, body multipartgroup.MultiPartRequest, options *multipartgroup.MultiPartFormDataClientCheckFileNameAndContentTypeOptions) (resp azfake.Responder[multipartgroup.MultiPartFormDataClientCheckFileNameAndContentTypeResponse], errResp azfake.ErrorResponder) + + // FileArrayAndBasic is the fake for method MultiPartFormDataClient.FileArrayAndBasic + // HTTP status codes to indicate success: http.StatusNoContent + FileArrayAndBasic func(ctx context.Context, body multipartgroup.ComplexPartsRequest, options *multipartgroup.MultiPartFormDataClientFileArrayAndBasicOptions) (resp azfake.Responder[multipartgroup.MultiPartFormDataClientFileArrayAndBasicResponse], errResp azfake.ErrorResponder) + + // JSONPart is the fake for method MultiPartFormDataClient.JSONPart + // HTTP status codes to indicate success: http.StatusNoContent + JSONPart func(ctx context.Context, body multipartgroup.JSONPartRequest, options *multipartgroup.MultiPartFormDataClientJSONPartOptions) (resp azfake.Responder[multipartgroup.MultiPartFormDataClientJSONPartResponse], errResp azfake.ErrorResponder) + + // MultiBinaryParts is the fake for method MultiPartFormDataClient.MultiBinaryParts + // HTTP status codes to indicate success: http.StatusNoContent + MultiBinaryParts func(ctx context.Context, body multipartgroup.MultiBinaryPartsRequest, options *multipartgroup.MultiPartFormDataClientMultiBinaryPartsOptions) (resp azfake.Responder[multipartgroup.MultiPartFormDataClientMultiBinaryPartsResponse], errResp azfake.ErrorResponder) + + // OptionalParts is the fake for method MultiPartFormDataClient.OptionalParts + // HTTP status codes to indicate success: http.StatusNoContent + OptionalParts func(ctx context.Context, body multipartgroup.MultiPartOptionalRequest, options *multipartgroup.MultiPartFormDataClientOptionalPartsOptions) (resp azfake.Responder[multipartgroup.MultiPartFormDataClientOptionalPartsResponse], errResp azfake.ErrorResponder) + + // WithWireName is the fake for method MultiPartFormDataClient.WithWireName + // HTTP status codes to indicate success: http.StatusNoContent + WithWireName func(ctx context.Context, body multipartgroup.MultiPartRequestWithWireName, options *multipartgroup.MultiPartFormDataClientWithWireNameOptions) (resp azfake.Responder[multipartgroup.MultiPartFormDataClientWithWireNameResponse], errResp azfake.ErrorResponder) +} + +// NewMultiPartFormDataServerTransport creates a new instance of MultiPartFormDataServerTransport with the provided implementation. +// The returned MultiPartFormDataServerTransport instance is connected to an instance of multipartgroup.MultiPartFormDataClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewMultiPartFormDataServerTransport(srv *MultiPartFormDataServer) *MultiPartFormDataServerTransport { + return &MultiPartFormDataServerTransport{srv: srv} +} + +// MultiPartFormDataServerTransport connects instances of multipartgroup.MultiPartFormDataClient to instances of MultiPartFormDataServer. +// Don't use this type directly, use NewMultiPartFormDataServerTransport instead. +type MultiPartFormDataServerTransport struct { + srv *MultiPartFormDataServer + trMu sync.Mutex + trMultiPartFormDataFileServer *MultiPartFormDataFileServerTransport + trMultiPartFormDataHTTPPartsServer *MultiPartFormDataHTTPPartsServerTransport +} + +// Do implements the policy.Transporter interface for MultiPartFormDataServerTransport. +func (m *MultiPartFormDataServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + if client := method[:strings.Index(method, ".")]; client != "MultiPartFormDataClient" { + return m.dispatchToClientFake(req, client) + } + return m.dispatchToMethodFake(req, method) +} + +func (m *MultiPartFormDataServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "MultiPartFormDataFileClient": + initServer(&m.trMu, &m.trMultiPartFormDataFileServer, func() *MultiPartFormDataFileServerTransport { + return NewMultiPartFormDataFileServerTransport(&m.srv.MultiPartFormDataFileServer) + }) + resp, err = m.trMultiPartFormDataFileServer.Do(req) + case "MultiPartFormDataHTTPPartsClient", "MultiPartFormDataHTTPPartsContentTypeClient", "MultiPartFormDataHTTPPartsNonStringClient": + initServer(&m.trMu, &m.trMultiPartFormDataHTTPPartsServer, func() *MultiPartFormDataHTTPPartsServerTransport { + return NewMultiPartFormDataHTTPPartsServerTransport(&m.srv.MultiPartFormDataHTTPPartsServer) + }) + resp, err = m.trMultiPartFormDataHTTPPartsServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +func (m *MultiPartFormDataServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if multiPartFormDataServerTransportInterceptor != nil { + res.resp, res.err, intercepted = multiPartFormDataServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "MultiPartFormDataClient.AnonymousModel": + res.resp, res.err = m.dispatchAnonymousModel(req) + case "MultiPartFormDataClient.Basic": + res.resp, res.err = m.dispatchBasic(req) + case "MultiPartFormDataClient.BinaryArrayParts": + res.resp, res.err = m.dispatchBinaryArrayParts(req) + case "MultiPartFormDataClient.CheckFileNameAndContentType": + res.resp, res.err = m.dispatchCheckFileNameAndContentType(req) + case "MultiPartFormDataClient.FileArrayAndBasic": + res.resp, res.err = m.dispatchFileArrayAndBasic(req) + case "MultiPartFormDataClient.JSONPart": + res.resp, res.err = m.dispatchJSONPart(req) + case "MultiPartFormDataClient.MultiBinaryParts": + res.resp, res.err = m.dispatchMultiBinaryParts(req) + case "MultiPartFormDataClient.OptionalParts": + res.resp, res.err = m.dispatchOptionalParts(req) + case "MultiPartFormDataClient.WithWireName": + res.resp, res.err = m.dispatchWithWireName(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *MultiPartFormDataServerTransport) dispatchAnonymousModel(req *http.Request) (*http.Response, error) { + if m.srv.AnonymousModel == nil { + return nil, &nonRetriableError{errors.New("fake for method AnonymousModel not implemented")} + } + _, params, err := mime.ParseMediaType(req.Header.Get("Content-Type")) + if err != nil { + return nil, err + } + reader := multipart.NewReader(req.Body, params["boundary"]) + var profileImage io.ReadSeekCloser + for { + var part *multipart.Part + part, err = reader.NextPart() + if errors.Is(err, io.EOF) { + break + } else if err != nil { + return nil, err + } + var content []byte + switch fn := part.FormName(); fn { + case "profileImage": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + profileImage = streaming.NopCloser(bytes.NewReader(content)) + default: + return nil, fmt.Errorf("unexpected part %s", fn) + } + } + respr, errRespr := m.srv.AnonymousModel(req.Context(), profileImage, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *MultiPartFormDataServerTransport) dispatchBasic(req *http.Request) (*http.Response, error) { + if m.srv.Basic == nil { + return nil, &nonRetriableError{errors.New("fake for method Basic not implemented")} + } + _, params, err := mime.ParseMediaType(req.Header.Get("Content-Type")) + if err != nil { + return nil, err + } + reader := multipart.NewReader(req.Body, params["boundary"]) + var body multipartgroup.MultiPartRequest + for { + var part *multipart.Part + part, err = reader.NextPart() + if errors.Is(err, io.EOF) { + break + } else if err != nil { + return nil, err + } + var content []byte + switch fn := part.FormName(); fn { + case "id": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + body.ID = string(content) + case "profileImage": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + body.ProfileImage.Body = streaming.NopCloser(bytes.NewReader(content)) + body.ProfileImage.ContentType = part.Header.Get("Content-Type") + body.ProfileImage.Filename = part.FileName() + default: + return nil, fmt.Errorf("unexpected part %s", fn) + } + } + respr, errRespr := m.srv.Basic(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *MultiPartFormDataServerTransport) dispatchBinaryArrayParts(req *http.Request) (*http.Response, error) { + if m.srv.BinaryArrayParts == nil { + return nil, &nonRetriableError{errors.New("fake for method BinaryArrayParts not implemented")} + } + _, params, err := mime.ParseMediaType(req.Header.Get("Content-Type")) + if err != nil { + return nil, err + } + reader := multipart.NewReader(req.Body, params["boundary"]) + var body multipartgroup.BinaryArrayPartsRequest + for { + var part *multipart.Part + part, err = reader.NextPart() + if errors.Is(err, io.EOF) { + break + } else if err != nil { + return nil, err + } + var content []byte + switch fn := part.FormName(); fn { + case "id": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + body.ID = string(content) + case "pictures": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + body.Pictures = append(body.Pictures, streaming.MultipartContent{ + Body: streaming.NopCloser(bytes.NewReader(content)), + ContentType: part.Header.Get("Content-Type"), + Filename: part.FileName(), + }) + default: + return nil, fmt.Errorf("unexpected part %s", fn) + } + } + respr, errRespr := m.srv.BinaryArrayParts(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *MultiPartFormDataServerTransport) dispatchCheckFileNameAndContentType(req *http.Request) (*http.Response, error) { + if m.srv.CheckFileNameAndContentType == nil { + return nil, &nonRetriableError{errors.New("fake for method CheckFileNameAndContentType not implemented")} + } + _, params, err := mime.ParseMediaType(req.Header.Get("Content-Type")) + if err != nil { + return nil, err + } + reader := multipart.NewReader(req.Body, params["boundary"]) + var body multipartgroup.MultiPartRequest + for { + var part *multipart.Part + part, err = reader.NextPart() + if errors.Is(err, io.EOF) { + break + } else if err != nil { + return nil, err + } + var content []byte + switch fn := part.FormName(); fn { + case "id": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + body.ID = string(content) + case "profileImage": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + body.ProfileImage.Body = streaming.NopCloser(bytes.NewReader(content)) + body.ProfileImage.ContentType = part.Header.Get("Content-Type") + body.ProfileImage.Filename = part.FileName() + default: + return nil, fmt.Errorf("unexpected part %s", fn) + } + } + respr, errRespr := m.srv.CheckFileNameAndContentType(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *MultiPartFormDataServerTransport) dispatchFileArrayAndBasic(req *http.Request) (*http.Response, error) { + if m.srv.FileArrayAndBasic == nil { + return nil, &nonRetriableError{errors.New("fake for method FileArrayAndBasic not implemented")} + } + _, params, err := mime.ParseMediaType(req.Header.Get("Content-Type")) + if err != nil { + return nil, err + } + reader := multipart.NewReader(req.Body, params["boundary"]) + var body multipartgroup.ComplexPartsRequest + for { + var part *multipart.Part + part, err = reader.NextPart() + if errors.Is(err, io.EOF) { + break + } else if err != nil { + return nil, err + } + var content []byte + switch fn := part.FormName(); fn { + case "address": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + if err = json.Unmarshal(content, &body.Address); err != nil { + return nil, err + } + case "id": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + body.ID = string(content) + case "pictures": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + body.Pictures = append(body.Pictures, streaming.MultipartContent{ + Body: streaming.NopCloser(bytes.NewReader(content)), + ContentType: part.Header.Get("Content-Type"), + Filename: part.FileName(), + }) + case "profileImage": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + body.ProfileImage.Body = streaming.NopCloser(bytes.NewReader(content)) + body.ProfileImage.ContentType = part.Header.Get("Content-Type") + body.ProfileImage.Filename = part.FileName() + default: + return nil, fmt.Errorf("unexpected part %s", fn) + } + } + respr, errRespr := m.srv.FileArrayAndBasic(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *MultiPartFormDataServerTransport) dispatchJSONPart(req *http.Request) (*http.Response, error) { + if m.srv.JSONPart == nil { + return nil, &nonRetriableError{errors.New("fake for method JSONPart not implemented")} + } + _, params, err := mime.ParseMediaType(req.Header.Get("Content-Type")) + if err != nil { + return nil, err + } + reader := multipart.NewReader(req.Body, params["boundary"]) + var body multipartgroup.JSONPartRequest + for { + var part *multipart.Part + part, err = reader.NextPart() + if errors.Is(err, io.EOF) { + break + } else if err != nil { + return nil, err + } + var content []byte + switch fn := part.FormName(); fn { + case "address": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + if err = json.Unmarshal(content, &body.Address); err != nil { + return nil, err + } + case "profileImage": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + body.ProfileImage.Body = streaming.NopCloser(bytes.NewReader(content)) + body.ProfileImage.ContentType = part.Header.Get("Content-Type") + body.ProfileImage.Filename = part.FileName() + default: + return nil, fmt.Errorf("unexpected part %s", fn) + } + } + respr, errRespr := m.srv.JSONPart(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *MultiPartFormDataServerTransport) dispatchMultiBinaryParts(req *http.Request) (*http.Response, error) { + if m.srv.MultiBinaryParts == nil { + return nil, &nonRetriableError{errors.New("fake for method MultiBinaryParts not implemented")} + } + _, params, err := mime.ParseMediaType(req.Header.Get("Content-Type")) + if err != nil { + return nil, err + } + reader := multipart.NewReader(req.Body, params["boundary"]) + var body multipartgroup.MultiBinaryPartsRequest + for { + var part *multipart.Part + part, err = reader.NextPart() + if errors.Is(err, io.EOF) { + break + } else if err != nil { + return nil, err + } + var content []byte + switch fn := part.FormName(); fn { + case "profileImage": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + body.ProfileImage.Body = streaming.NopCloser(bytes.NewReader(content)) + body.ProfileImage.ContentType = part.Header.Get("Content-Type") + body.ProfileImage.Filename = part.FileName() + case "picture": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + body.Picture.Body = streaming.NopCloser(bytes.NewReader(content)) + body.Picture.ContentType = part.Header.Get("Content-Type") + body.Picture.Filename = part.FileName() + default: + return nil, fmt.Errorf("unexpected part %s", fn) + } + } + respr, errRespr := m.srv.MultiBinaryParts(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *MultiPartFormDataServerTransport) dispatchOptionalParts(req *http.Request) (*http.Response, error) { + if m.srv.OptionalParts == nil { + return nil, &nonRetriableError{errors.New("fake for method OptionalParts not implemented")} + } + _, params, err := mime.ParseMediaType(req.Header.Get("Content-Type")) + if err != nil { + return nil, err + } + reader := multipart.NewReader(req.Body, params["boundary"]) + var body multipartgroup.MultiPartOptionalRequest + for { + var part *multipart.Part + part, err = reader.NextPart() + if errors.Is(err, io.EOF) { + break + } else if err != nil { + return nil, err + } + var content []byte + switch fn := part.FormName(); fn { + case "id": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + body.ID = to.Ptr(string(content)) + case "profileImage": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + body.ProfileImage.Body = streaming.NopCloser(bytes.NewReader(content)) + body.ProfileImage.ContentType = part.Header.Get("Content-Type") + body.ProfileImage.Filename = part.FileName() + default: + return nil, fmt.Errorf("unexpected part %s", fn) + } + } + respr, errRespr := m.srv.OptionalParts(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *MultiPartFormDataServerTransport) dispatchWithWireName(req *http.Request) (*http.Response, error) { + if m.srv.WithWireName == nil { + return nil, &nonRetriableError{errors.New("fake for method WithWireName not implemented")} + } + _, params, err := mime.ParseMediaType(req.Header.Get("Content-Type")) + if err != nil { + return nil, err + } + reader := multipart.NewReader(req.Body, params["boundary"]) + var body multipartgroup.MultiPartRequestWithWireName + for { + var part *multipart.Part + part, err = reader.NextPart() + if errors.Is(err, io.EOF) { + break + } else if err != nil { + return nil, err + } + var content []byte + switch fn := part.FormName(); fn { + case "id": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + body.Identifier = string(content) + case "profileImage": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + body.Image.Body = streaming.NopCloser(bytes.NewReader(content)) + body.Image.ContentType = part.Header.Get("Content-Type") + body.Image.Filename = part.FileName() + default: + return nil, fmt.Errorf("unexpected part %s", fn) + } + } + respr, errRespr := m.srv.WithWireName(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to MultiPartFormDataServerTransport +var multiPartFormDataServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/multipartgroup/fake/zz_multipartformdatafile_server.go b/test/http-specs/payload/multipartgroup/fake/zz_multipartformdatafile_server.go new file mode 100644 index 000000000000..7a0d1559334d --- /dev/null +++ b/test/http-specs/payload/multipartgroup/fake/zz_multipartformdatafile_server.go @@ -0,0 +1,242 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "bytes" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming" + "io" + "mime" + "mime/multipart" + "multipartgroup" + "net/http" + "slices" +) + +// MultiPartFormDataFileServer is a fake server for instances of the multipartgroup.MultiPartFormDataFileClient type. +type MultiPartFormDataFileServer struct { + // UploadFileArray is the fake for method MultiPartFormDataFileClient.UploadFileArray + // HTTP status codes to indicate success: http.StatusNoContent + UploadFileArray func(ctx context.Context, files []streaming.MultipartContent, options *multipartgroup.MultiPartFormDataFileClientUploadFileArrayOptions) (resp azfake.Responder[multipartgroup.MultiPartFormDataFileClientUploadFileArrayResponse], errResp azfake.ErrorResponder) + + // UploadFileRequiredFilename is the fake for method MultiPartFormDataFileClient.UploadFileRequiredFilename + // HTTP status codes to indicate success: http.StatusNoContent + UploadFileRequiredFilename func(ctx context.Context, file streaming.MultipartContent, options *multipartgroup.MultiPartFormDataFileClientUploadFileRequiredFilenameOptions) (resp azfake.Responder[multipartgroup.MultiPartFormDataFileClientUploadFileRequiredFilenameResponse], errResp azfake.ErrorResponder) + + // UploadFileSpecificContentType is the fake for method MultiPartFormDataFileClient.UploadFileSpecificContentType + // HTTP status codes to indicate success: http.StatusNoContent + UploadFileSpecificContentType func(ctx context.Context, file streaming.MultipartContent, options *multipartgroup.MultiPartFormDataFileClientUploadFileSpecificContentTypeOptions) (resp azfake.Responder[multipartgroup.MultiPartFormDataFileClientUploadFileSpecificContentTypeResponse], errResp azfake.ErrorResponder) +} + +// NewMultiPartFormDataFileServerTransport creates a new instance of MultiPartFormDataFileServerTransport with the provided implementation. +// The returned MultiPartFormDataFileServerTransport instance is connected to an instance of multipartgroup.MultiPartFormDataFileClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewMultiPartFormDataFileServerTransport(srv *MultiPartFormDataFileServer) *MultiPartFormDataFileServerTransport { + return &MultiPartFormDataFileServerTransport{srv: srv} +} + +// MultiPartFormDataFileServerTransport connects instances of multipartgroup.MultiPartFormDataFileClient to instances of MultiPartFormDataFileServer. +// Don't use this type directly, use NewMultiPartFormDataFileServerTransport instead. +type MultiPartFormDataFileServerTransport struct { + srv *MultiPartFormDataFileServer +} + +// Do implements the policy.Transporter interface for MultiPartFormDataFileServerTransport. +func (m *MultiPartFormDataFileServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToMethodFake(req, method) +} + +func (m *MultiPartFormDataFileServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if multiPartFormDataFileServerTransportInterceptor != nil { + res.resp, res.err, intercepted = multiPartFormDataFileServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "MultiPartFormDataFileClient.UploadFileArray": + res.resp, res.err = m.dispatchUploadFileArray(req) + case "MultiPartFormDataFileClient.UploadFileRequiredFilename": + res.resp, res.err = m.dispatchUploadFileRequiredFilename(req) + case "MultiPartFormDataFileClient.UploadFileSpecificContentType": + res.resp, res.err = m.dispatchUploadFileSpecificContentType(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *MultiPartFormDataFileServerTransport) dispatchUploadFileArray(req *http.Request) (*http.Response, error) { + if m.srv.UploadFileArray == nil { + return nil, &nonRetriableError{errors.New("fake for method UploadFileArray not implemented")} + } + _, params, err := mime.ParseMediaType(req.Header.Get("Content-Type")) + if err != nil { + return nil, err + } + reader := multipart.NewReader(req.Body, params["boundary"]) + var files []streaming.MultipartContent + for { + var part *multipart.Part + part, err = reader.NextPart() + if errors.Is(err, io.EOF) { + break + } else if err != nil { + return nil, err + } + var content []byte + switch fn := part.FormName(); fn { + case "files": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + files = append(files, streaming.MultipartContent{ + Body: streaming.NopCloser(bytes.NewReader(content)), + ContentType: part.Header.Get("Content-Type"), + Filename: part.FileName(), + }) + default: + return nil, fmt.Errorf("unexpected part %s", fn) + } + } + respr, errRespr := m.srv.UploadFileArray(req.Context(), files, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *MultiPartFormDataFileServerTransport) dispatchUploadFileRequiredFilename(req *http.Request) (*http.Response, error) { + if m.srv.UploadFileRequiredFilename == nil { + return nil, &nonRetriableError{errors.New("fake for method UploadFileRequiredFilename not implemented")} + } + _, params, err := mime.ParseMediaType(req.Header.Get("Content-Type")) + if err != nil { + return nil, err + } + reader := multipart.NewReader(req.Body, params["boundary"]) + var file streaming.MultipartContent + for { + var part *multipart.Part + part, err = reader.NextPart() + if errors.Is(err, io.EOF) { + break + } else if err != nil { + return nil, err + } + var content []byte + switch fn := part.FormName(); fn { + case "file": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + file.Body = streaming.NopCloser(bytes.NewReader(content)) + file.ContentType = part.Header.Get("Content-Type") + file.Filename = part.FileName() + default: + return nil, fmt.Errorf("unexpected part %s", fn) + } + } + respr, errRespr := m.srv.UploadFileRequiredFilename(req.Context(), file, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *MultiPartFormDataFileServerTransport) dispatchUploadFileSpecificContentType(req *http.Request) (*http.Response, error) { + if m.srv.UploadFileSpecificContentType == nil { + return nil, &nonRetriableError{errors.New("fake for method UploadFileSpecificContentType not implemented")} + } + _, params, err := mime.ParseMediaType(req.Header.Get("Content-Type")) + if err != nil { + return nil, err + } + reader := multipart.NewReader(req.Body, params["boundary"]) + var file streaming.MultipartContent + for { + var part *multipart.Part + part, err = reader.NextPart() + if errors.Is(err, io.EOF) { + break + } else if err != nil { + return nil, err + } + var content []byte + switch fn := part.FormName(); fn { + case "file": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + file.Body = streaming.NopCloser(bytes.NewReader(content)) + file.ContentType = part.Header.Get("Content-Type") + file.Filename = part.FileName() + default: + return nil, fmt.Errorf("unexpected part %s", fn) + } + } + respr, errRespr := m.srv.UploadFileSpecificContentType(req.Context(), file, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to MultiPartFormDataFileServerTransport +var multiPartFormDataFileServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/multipartgroup/fake/zz_multipartformdatahttpparts_server.go b/test/http-specs/payload/multipartgroup/fake/zz_multipartformdatahttpparts_server.go new file mode 100644 index 000000000000..29fda0bdea05 --- /dev/null +++ b/test/http-specs/payload/multipartgroup/fake/zz_multipartformdatahttpparts_server.go @@ -0,0 +1,203 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming" + "io" + "mime" + "mime/multipart" + "multipartgroup" + "net/http" + "slices" + "strings" + "sync" +) + +// MultiPartFormDataHTTPPartsServer is a fake server for instances of the multipartgroup.MultiPartFormDataHTTPPartsClient type. +type MultiPartFormDataHTTPPartsServer struct { + // MultiPartFormDataHTTPPartsContentTypeServer contains the fakes for client MultiPartFormDataHTTPPartsContentTypeClient + MultiPartFormDataHTTPPartsContentTypeServer MultiPartFormDataHTTPPartsContentTypeServer + + // MultiPartFormDataHTTPPartsNonStringServer contains the fakes for client MultiPartFormDataHTTPPartsNonStringClient + MultiPartFormDataHTTPPartsNonStringServer MultiPartFormDataHTTPPartsNonStringServer + + // JSONArrayAndFileArray is the fake for method MultiPartFormDataHTTPPartsClient.JSONArrayAndFileArray + // HTTP status codes to indicate success: http.StatusNoContent + JSONArrayAndFileArray func(ctx context.Context, body multipartgroup.ComplexHTTPPartsModelRequest, options *multipartgroup.MultiPartFormDataHTTPPartsClientJSONArrayAndFileArrayOptions) (resp azfake.Responder[multipartgroup.MultiPartFormDataHTTPPartsClientJSONArrayAndFileArrayResponse], errResp azfake.ErrorResponder) +} + +// NewMultiPartFormDataHTTPPartsServerTransport creates a new instance of MultiPartFormDataHTTPPartsServerTransport with the provided implementation. +// The returned MultiPartFormDataHTTPPartsServerTransport instance is connected to an instance of multipartgroup.MultiPartFormDataHTTPPartsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewMultiPartFormDataHTTPPartsServerTransport(srv *MultiPartFormDataHTTPPartsServer) *MultiPartFormDataHTTPPartsServerTransport { + return &MultiPartFormDataHTTPPartsServerTransport{srv: srv} +} + +// MultiPartFormDataHTTPPartsServerTransport connects instances of multipartgroup.MultiPartFormDataHTTPPartsClient to instances of MultiPartFormDataHTTPPartsServer. +// Don't use this type directly, use NewMultiPartFormDataHTTPPartsServerTransport instead. +type MultiPartFormDataHTTPPartsServerTransport struct { + srv *MultiPartFormDataHTTPPartsServer + trMu sync.Mutex + trMultiPartFormDataHTTPPartsContentTypeServer *MultiPartFormDataHTTPPartsContentTypeServerTransport + trMultiPartFormDataHTTPPartsNonStringServer *MultiPartFormDataHTTPPartsNonStringServerTransport +} + +// Do implements the policy.Transporter interface for MultiPartFormDataHTTPPartsServerTransport. +func (m *MultiPartFormDataHTTPPartsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + if client := method[:strings.Index(method, ".")]; client != "MultiPartFormDataHTTPPartsClient" { + return m.dispatchToClientFake(req, client) + } + return m.dispatchToMethodFake(req, method) +} + +func (m *MultiPartFormDataHTTPPartsServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "MultiPartFormDataHTTPPartsContentTypeClient": + initServer(&m.trMu, &m.trMultiPartFormDataHTTPPartsContentTypeServer, func() *MultiPartFormDataHTTPPartsContentTypeServerTransport { + return NewMultiPartFormDataHTTPPartsContentTypeServerTransport(&m.srv.MultiPartFormDataHTTPPartsContentTypeServer) + }) + resp, err = m.trMultiPartFormDataHTTPPartsContentTypeServer.Do(req) + case "MultiPartFormDataHTTPPartsNonStringClient": + initServer(&m.trMu, &m.trMultiPartFormDataHTTPPartsNonStringServer, func() *MultiPartFormDataHTTPPartsNonStringServerTransport { + return NewMultiPartFormDataHTTPPartsNonStringServerTransport(&m.srv.MultiPartFormDataHTTPPartsNonStringServer) + }) + resp, err = m.trMultiPartFormDataHTTPPartsNonStringServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +func (m *MultiPartFormDataHTTPPartsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if multiPartFormDataHttpPartsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = multiPartFormDataHttpPartsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "MultiPartFormDataHTTPPartsClient.JSONArrayAndFileArray": + res.resp, res.err = m.dispatchJSONArrayAndFileArray(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *MultiPartFormDataHTTPPartsServerTransport) dispatchJSONArrayAndFileArray(req *http.Request) (*http.Response, error) { + if m.srv.JSONArrayAndFileArray == nil { + return nil, &nonRetriableError{errors.New("fake for method JSONArrayAndFileArray not implemented")} + } + _, params, err := mime.ParseMediaType(req.Header.Get("Content-Type")) + if err != nil { + return nil, err + } + reader := multipart.NewReader(req.Body, params["boundary"]) + var body multipartgroup.ComplexHTTPPartsModelRequest + for { + var part *multipart.Part + part, err = reader.NextPart() + if errors.Is(err, io.EOF) { + break + } else if err != nil { + return nil, err + } + var content []byte + switch fn := part.FormName(); fn { + case "address": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + if err = json.Unmarshal(content, &body.Address); err != nil { + return nil, err + } + case "id": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + body.ID = string(content) + case "pictures": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + body.Pictures = append(body.Pictures, streaming.MultipartContent{ + Body: streaming.NopCloser(bytes.NewReader(content)), + ContentType: part.Header.Get("Content-Type"), + Filename: part.FileName(), + }) + case "previousAddresses": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + if err = json.Unmarshal(content, &body.PreviousAddresses); err != nil { + return nil, err + } + case "profileImage": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + body.ProfileImage.Body = streaming.NopCloser(bytes.NewReader(content)) + body.ProfileImage.ContentType = part.Header.Get("Content-Type") + body.ProfileImage.Filename = part.FileName() + default: + return nil, fmt.Errorf("unexpected part %s", fn) + } + } + respr, errRespr := m.srv.JSONArrayAndFileArray(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to MultiPartFormDataHTTPPartsServerTransport +var multiPartFormDataHttpPartsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/multipartgroup/fake/zz_multipartformdatahttppartscontenttype_server.go b/test/http-specs/payload/multipartgroup/fake/zz_multipartformdatahttppartscontenttype_server.go new file mode 100644 index 000000000000..7cec749ca791 --- /dev/null +++ b/test/http-specs/payload/multipartgroup/fake/zz_multipartformdatahttppartscontenttype_server.go @@ -0,0 +1,240 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "bytes" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming" + "io" + "mime" + "mime/multipart" + "multipartgroup" + "net/http" + "slices" +) + +// MultiPartFormDataHTTPPartsContentTypeServer is a fake server for instances of the multipartgroup.MultiPartFormDataHTTPPartsContentTypeClient type. +type MultiPartFormDataHTTPPartsContentTypeServer struct { + // ImageJPEGContentType is the fake for method MultiPartFormDataHTTPPartsContentTypeClient.ImageJPEGContentType + // HTTP status codes to indicate success: http.StatusNoContent + ImageJPEGContentType func(ctx context.Context, body multipartgroup.FileWithHTTPPartSpecificContentTypeRequest, options *multipartgroup.MultiPartFormDataHTTPPartsContentTypeClientImageJPEGContentTypeOptions) (resp azfake.Responder[multipartgroup.MultiPartFormDataHTTPPartsContentTypeClientImageJPEGContentTypeResponse], errResp azfake.ErrorResponder) + + // OptionalContentType is the fake for method MultiPartFormDataHTTPPartsContentTypeClient.OptionalContentType + // HTTP status codes to indicate success: http.StatusNoContent + OptionalContentType func(ctx context.Context, body multipartgroup.FileWithHTTPPartOptionalContentTypeRequest, options *multipartgroup.MultiPartFormDataHTTPPartsContentTypeClientOptionalContentTypeOptions) (resp azfake.Responder[multipartgroup.MultiPartFormDataHTTPPartsContentTypeClientOptionalContentTypeResponse], errResp azfake.ErrorResponder) + + // RequiredContentType is the fake for method MultiPartFormDataHTTPPartsContentTypeClient.RequiredContentType + // HTTP status codes to indicate success: http.StatusNoContent + RequiredContentType func(ctx context.Context, body multipartgroup.FileWithHTTPPartRequiredContentTypeRequest, options *multipartgroup.MultiPartFormDataHTTPPartsContentTypeClientRequiredContentTypeOptions) (resp azfake.Responder[multipartgroup.MultiPartFormDataHTTPPartsContentTypeClientRequiredContentTypeResponse], errResp azfake.ErrorResponder) +} + +// NewMultiPartFormDataHTTPPartsContentTypeServerTransport creates a new instance of MultiPartFormDataHTTPPartsContentTypeServerTransport with the provided implementation. +// The returned MultiPartFormDataHTTPPartsContentTypeServerTransport instance is connected to an instance of multipartgroup.MultiPartFormDataHTTPPartsContentTypeClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewMultiPartFormDataHTTPPartsContentTypeServerTransport(srv *MultiPartFormDataHTTPPartsContentTypeServer) *MultiPartFormDataHTTPPartsContentTypeServerTransport { + return &MultiPartFormDataHTTPPartsContentTypeServerTransport{srv: srv} +} + +// MultiPartFormDataHTTPPartsContentTypeServerTransport connects instances of multipartgroup.MultiPartFormDataHTTPPartsContentTypeClient to instances of MultiPartFormDataHTTPPartsContentTypeServer. +// Don't use this type directly, use NewMultiPartFormDataHTTPPartsContentTypeServerTransport instead. +type MultiPartFormDataHTTPPartsContentTypeServerTransport struct { + srv *MultiPartFormDataHTTPPartsContentTypeServer +} + +// Do implements the policy.Transporter interface for MultiPartFormDataHTTPPartsContentTypeServerTransport. +func (m *MultiPartFormDataHTTPPartsContentTypeServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToMethodFake(req, method) +} + +func (m *MultiPartFormDataHTTPPartsContentTypeServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if multiPartFormDataHttpPartsContentTypeServerTransportInterceptor != nil { + res.resp, res.err, intercepted = multiPartFormDataHttpPartsContentTypeServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "MultiPartFormDataHTTPPartsContentTypeClient.ImageJPEGContentType": + res.resp, res.err = m.dispatchImageJPEGContentType(req) + case "MultiPartFormDataHTTPPartsContentTypeClient.OptionalContentType": + res.resp, res.err = m.dispatchOptionalContentType(req) + case "MultiPartFormDataHTTPPartsContentTypeClient.RequiredContentType": + res.resp, res.err = m.dispatchRequiredContentType(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *MultiPartFormDataHTTPPartsContentTypeServerTransport) dispatchImageJPEGContentType(req *http.Request) (*http.Response, error) { + if m.srv.ImageJPEGContentType == nil { + return nil, &nonRetriableError{errors.New("fake for method ImageJPEGContentType not implemented")} + } + _, params, err := mime.ParseMediaType(req.Header.Get("Content-Type")) + if err != nil { + return nil, err + } + reader := multipart.NewReader(req.Body, params["boundary"]) + var body multipartgroup.FileWithHTTPPartSpecificContentTypeRequest + for { + var part *multipart.Part + part, err = reader.NextPart() + if errors.Is(err, io.EOF) { + break + } else if err != nil { + return nil, err + } + var content []byte + switch fn := part.FormName(); fn { + case "profileImage": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + body.ProfileImage.Body = streaming.NopCloser(bytes.NewReader(content)) + body.ProfileImage.ContentType = part.Header.Get("Content-Type") + body.ProfileImage.Filename = part.FileName() + default: + return nil, fmt.Errorf("unexpected part %s", fn) + } + } + respr, errRespr := m.srv.ImageJPEGContentType(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *MultiPartFormDataHTTPPartsContentTypeServerTransport) dispatchOptionalContentType(req *http.Request) (*http.Response, error) { + if m.srv.OptionalContentType == nil { + return nil, &nonRetriableError{errors.New("fake for method OptionalContentType not implemented")} + } + _, params, err := mime.ParseMediaType(req.Header.Get("Content-Type")) + if err != nil { + return nil, err + } + reader := multipart.NewReader(req.Body, params["boundary"]) + var body multipartgroup.FileWithHTTPPartOptionalContentTypeRequest + for { + var part *multipart.Part + part, err = reader.NextPart() + if errors.Is(err, io.EOF) { + break + } else if err != nil { + return nil, err + } + var content []byte + switch fn := part.FormName(); fn { + case "profileImage": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + body.ProfileImage.Body = streaming.NopCloser(bytes.NewReader(content)) + body.ProfileImage.ContentType = part.Header.Get("Content-Type") + body.ProfileImage.Filename = part.FileName() + default: + return nil, fmt.Errorf("unexpected part %s", fn) + } + } + respr, errRespr := m.srv.OptionalContentType(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *MultiPartFormDataHTTPPartsContentTypeServerTransport) dispatchRequiredContentType(req *http.Request) (*http.Response, error) { + if m.srv.RequiredContentType == nil { + return nil, &nonRetriableError{errors.New("fake for method RequiredContentType not implemented")} + } + _, params, err := mime.ParseMediaType(req.Header.Get("Content-Type")) + if err != nil { + return nil, err + } + reader := multipart.NewReader(req.Body, params["boundary"]) + var body multipartgroup.FileWithHTTPPartRequiredContentTypeRequest + for { + var part *multipart.Part + part, err = reader.NextPart() + if errors.Is(err, io.EOF) { + break + } else if err != nil { + return nil, err + } + var content []byte + switch fn := part.FormName(); fn { + case "profileImage": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + body.ProfileImage.Body = streaming.NopCloser(bytes.NewReader(content)) + body.ProfileImage.ContentType = part.Header.Get("Content-Type") + body.ProfileImage.Filename = part.FileName() + default: + return nil, fmt.Errorf("unexpected part %s", fn) + } + } + respr, errRespr := m.srv.RequiredContentType(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to MultiPartFormDataHTTPPartsContentTypeServerTransport +var multiPartFormDataHttpPartsContentTypeServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/multipartgroup/fake/zz_multipartformdatahttppartsnonstring_server.go b/test/http-specs/payload/multipartgroup/fake/zz_multipartformdatahttppartsnonstring_server.go new file mode 100644 index 000000000000..f7a0ca3507a0 --- /dev/null +++ b/test/http-specs/payload/multipartgroup/fake/zz_multipartformdatahttppartsnonstring_server.go @@ -0,0 +1,135 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "io" + "mime" + "mime/multipart" + "multipartgroup" + "net/http" + "slices" + "strconv" +) + +// MultiPartFormDataHTTPPartsNonStringServer is a fake server for instances of the multipartgroup.MultiPartFormDataHTTPPartsNonStringClient type. +type MultiPartFormDataHTTPPartsNonStringServer struct { + // Float is the fake for method MultiPartFormDataHTTPPartsNonStringClient.Float + // HTTP status codes to indicate success: http.StatusNoContent + Float func(ctx context.Context, temperature float64, options *multipartgroup.MultiPartFormDataHTTPPartsNonStringClientFloatOptions) (resp azfake.Responder[multipartgroup.MultiPartFormDataHTTPPartsNonStringClientFloatResponse], errResp azfake.ErrorResponder) +} + +// NewMultiPartFormDataHTTPPartsNonStringServerTransport creates a new instance of MultiPartFormDataHTTPPartsNonStringServerTransport with the provided implementation. +// The returned MultiPartFormDataHTTPPartsNonStringServerTransport instance is connected to an instance of multipartgroup.MultiPartFormDataHTTPPartsNonStringClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewMultiPartFormDataHTTPPartsNonStringServerTransport(srv *MultiPartFormDataHTTPPartsNonStringServer) *MultiPartFormDataHTTPPartsNonStringServerTransport { + return &MultiPartFormDataHTTPPartsNonStringServerTransport{srv: srv} +} + +// MultiPartFormDataHTTPPartsNonStringServerTransport connects instances of multipartgroup.MultiPartFormDataHTTPPartsNonStringClient to instances of MultiPartFormDataHTTPPartsNonStringServer. +// Don't use this type directly, use NewMultiPartFormDataHTTPPartsNonStringServerTransport instead. +type MultiPartFormDataHTTPPartsNonStringServerTransport struct { + srv *MultiPartFormDataHTTPPartsNonStringServer +} + +// Do implements the policy.Transporter interface for MultiPartFormDataHTTPPartsNonStringServerTransport. +func (m *MultiPartFormDataHTTPPartsNonStringServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToMethodFake(req, method) +} + +func (m *MultiPartFormDataHTTPPartsNonStringServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if multiPartFormDataHttpPartsNonStringServerTransportInterceptor != nil { + res.resp, res.err, intercepted = multiPartFormDataHttpPartsNonStringServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "MultiPartFormDataHTTPPartsNonStringClient.Float": + res.resp, res.err = m.dispatchFloat(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *MultiPartFormDataHTTPPartsNonStringServerTransport) dispatchFloat(req *http.Request) (*http.Response, error) { + if m.srv.Float == nil { + return nil, &nonRetriableError{errors.New("fake for method Float not implemented")} + } + _, params, err := mime.ParseMediaType(req.Header.Get("Content-Type")) + if err != nil { + return nil, err + } + reader := multipart.NewReader(req.Body, params["boundary"]) + var temperature float64 + for { + var part *multipart.Part + part, err = reader.NextPart() + if errors.Is(err, io.EOF) { + break + } else if err != nil { + return nil, err + } + var content []byte + switch fn := part.FormName(); fn { + case "temperature": + content, err = io.ReadAll(part) + if err != nil { + return nil, err + } + parsed, parseErr := strconv.ParseFloat(string(content), 64) + if parseErr != nil { + return nil, parseErr + } + temperature = float64(parsed) + default: + return nil, fmt.Errorf("unexpected part %s", fn) + } + } + respr, errRespr := m.srv.Float(req.Context(), temperature, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to MultiPartFormDataHTTPPartsNonStringServerTransport +var multiPartFormDataHttpPartsNonStringServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/multipartgroup/fakes_test.go b/test/http-specs/payload/multipartgroup/fakes_test.go new file mode 100644 index 000000000000..8d246c255c1d --- /dev/null +++ b/test/http-specs/payload/multipartgroup/fakes_test.go @@ -0,0 +1,194 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package multipartgroup_test + +import ( + "bytes" + "context" + "multipartgroup" + "multipartgroup/fake" + "net/http" + "os" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func newFakeClient(t *testing.T, transport policy.Transporter) *multipartgroup.MultiPartClient { + t.Helper() + client, err := multipartgroup.NewMultiPartClientWithNoCredential("http://localhost:3000", &multipartgroup.MultiPartClientOptions{ + ClientOptions: azcore.ClientOptions{ + Transport: transport, + }, + }) + require.NoError(t, err) + return client +} + +func TestFakeFormDataClient_Basic(t *testing.T) { + calledBasic := false + srv := fake.MultiPartServer{ + MultiPartFormDataServer: fake.MultiPartFormDataServer{ + Basic: func(ctx context.Context, body multipartgroup.MultiPartRequest, options *multipartgroup.MultiPartFormDataClientBasicOptions) (resp azfake.Responder[multipartgroup.MultiPartFormDataClientBasicResponse], errResp azfake.ErrorResponder) { + require.EqualValues(t, "123", body.ID) + require.NotNil(t, body.ProfileImage.Body) + calledBasic = true + resp.SetResponse(http.StatusNoContent, multipartgroup.MultiPartFormDataClientBasicResponse{}, nil) + return + }, + }, + } + client := newFakeClient(t, fake.NewMultiPartServerTransport(&srv)) + jpgFile, err := os.OpenFile(jpgPath, os.O_RDONLY, 0) + require.NoError(t, err) + defer func() { _ = jpgFile.Close() }() + _, err = client.NewMultiPartFormDataClient().Basic(context.Background(), multipartgroup.MultiPartRequest{ + ID: "123", + ProfileImage: streaming.MultipartContent{ + Body: jpgFile, + }, + }, nil) + require.NoError(t, err) + require.True(t, calledBasic) +} + +func TestFakeFormDataFileClient_UploadFileRequiredFilename(t *testing.T) { + calledUpload := false + srv := fake.MultiPartServer{ + MultiPartFormDataServer: fake.MultiPartFormDataServer{ + MultiPartFormDataFileServer: fake.MultiPartFormDataFileServer{ + UploadFileRequiredFilename: func(ctx context.Context, file streaming.MultipartContent, options *multipartgroup.MultiPartFormDataFileClientUploadFileRequiredFilenameOptions) (resp azfake.Responder[multipartgroup.MultiPartFormDataFileClientUploadFileRequiredFilenameResponse], errResp azfake.ErrorResponder) { + require.NotNil(t, file.Body) + calledUpload = true + resp.SetResponse(http.StatusNoContent, multipartgroup.MultiPartFormDataFileClientUploadFileRequiredFilenameResponse{}, nil) + return + }, + }, + }, + } + client := newFakeClient(t, fake.NewMultiPartServerTransport(&srv)) + pngFile, err := os.OpenFile(pngPath, os.O_RDONLY, 0) + require.NoError(t, err) + defer func() { _ = pngFile.Close() }() + _, err = client.NewMultiPartFormDataClient().NewMultiPartFormDataFileClient().UploadFileRequiredFilename(context.Background(), streaming.MultipartContent{ + Body: pngFile, + Filename: "image.png", + }, nil) + require.NoError(t, err) + require.True(t, calledUpload) +} + +func TestFakeFormDataHTTPPartsClient_JSONArrayAndFileArray(t *testing.T) { + calledJSONArrayAndFileArray := false + srv := fake.MultiPartServer{ + MultiPartFormDataServer: fake.MultiPartFormDataServer{ + MultiPartFormDataHTTPPartsServer: fake.MultiPartFormDataHTTPPartsServer{ + JSONArrayAndFileArray: func(ctx context.Context, body multipartgroup.ComplexHTTPPartsModelRequest, options *multipartgroup.MultiPartFormDataHTTPPartsClientJSONArrayAndFileArrayOptions) (resp azfake.Responder[multipartgroup.MultiPartFormDataHTTPPartsClientJSONArrayAndFileArrayResponse], errResp azfake.ErrorResponder) { + require.EqualValues(t, "123", body.ID) + require.NotNil(t, body.Address.City) + require.EqualValues(t, "X", *body.Address.City) + require.Len(t, body.PreviousAddresses, 2) + require.Len(t, body.Pictures, 2) + require.NotNil(t, body.ProfileImage.Body) + calledJSONArrayAndFileArray = true + resp.SetResponse(http.StatusNoContent, multipartgroup.MultiPartFormDataHTTPPartsClientJSONArrayAndFileArrayResponse{}, nil) + return + }, + }, + }, + } + client := newFakeClient(t, fake.NewMultiPartServerTransport(&srv)) + jpgFile, err := os.OpenFile(jpgPath, os.O_RDONLY, 0) + require.NoError(t, err) + defer func() { _ = jpgFile.Close() }() + pngFile, err := os.ReadFile(pngPath) + require.NoError(t, err) + _, err = client.NewMultiPartFormDataClient().NewMultiPartFormDataHTTPPartsClient().JSONArrayAndFileArray(context.Background(), multipartgroup.ComplexHTTPPartsModelRequest{ + ID: "123", + Address: multipartgroup.Address{ + City: to.Ptr("X"), + }, + ProfileImage: streaming.MultipartContent{ + Body: jpgFile, + ContentType: "application/octet-stream", + Filename: "hello.jpg", + }, + PreviousAddresses: []multipartgroup.Address{ + {City: to.Ptr("Y")}, + {City: to.Ptr("Z")}, + }, + Pictures: []streaming.MultipartContent{ + { + Body: streaming.NopCloser(bytes.NewReader(pngFile)), + ContentType: "application/octet-stream", + Filename: "hello.png", + }, + { + Body: streaming.NopCloser(bytes.NewReader(pngFile)), + ContentType: "application/octet-stream", + Filename: "hello.png", + }, + }, + }, nil) + require.NoError(t, err) + require.True(t, calledJSONArrayAndFileArray) +} + +func TestFakeFormDataHTTPPartsContentTypeClient_RequiredContentType(t *testing.T) { + calledRequiredContentType := false + srv := fake.MultiPartServer{ + MultiPartFormDataServer: fake.MultiPartFormDataServer{ + MultiPartFormDataHTTPPartsServer: fake.MultiPartFormDataHTTPPartsServer{ + MultiPartFormDataHTTPPartsContentTypeServer: fake.MultiPartFormDataHTTPPartsContentTypeServer{ + RequiredContentType: func(ctx context.Context, body multipartgroup.FileWithHTTPPartRequiredContentTypeRequest, options *multipartgroup.MultiPartFormDataHTTPPartsContentTypeClientRequiredContentTypeOptions) (resp azfake.Responder[multipartgroup.MultiPartFormDataHTTPPartsContentTypeClientRequiredContentTypeResponse], errResp azfake.ErrorResponder) { + require.NotNil(t, body.ProfileImage.Body) + calledRequiredContentType = true + resp.SetResponse(http.StatusNoContent, multipartgroup.MultiPartFormDataHTTPPartsContentTypeClientRequiredContentTypeResponse{}, nil) + return + }, + }, + }, + }, + } + client := newFakeClient(t, fake.NewMultiPartServerTransport(&srv)) + jpgFile, err := os.OpenFile(jpgPath, os.O_RDONLY, 0) + require.NoError(t, err) + defer func() { _ = jpgFile.Close() }() + _, err = client.NewMultiPartFormDataClient().NewMultiPartFormDataHTTPPartsClient().NewMultiPartFormDataHTTPPartsContentTypeClient().RequiredContentType(context.Background(), multipartgroup.FileWithHTTPPartRequiredContentTypeRequest{ + ProfileImage: streaming.MultipartContent{ + Body: jpgFile, + ContentType: "application/octet-stream", + Filename: "hello.jpg", + }, + }, nil) + require.NoError(t, err) + require.True(t, calledRequiredContentType) +} + +func TestFakeFormDataHTTPPartsNonStringClient_Float(t *testing.T) { + calledFloat := false + srv := fake.MultiPartServer{ + MultiPartFormDataServer: fake.MultiPartFormDataServer{ + MultiPartFormDataHTTPPartsServer: fake.MultiPartFormDataHTTPPartsServer{ + MultiPartFormDataHTTPPartsNonStringServer: fake.MultiPartFormDataHTTPPartsNonStringServer{ + Float: func(ctx context.Context, temperature float64, options *multipartgroup.MultiPartFormDataHTTPPartsNonStringClientFloatOptions) (resp azfake.Responder[multipartgroup.MultiPartFormDataHTTPPartsNonStringClientFloatResponse], errResp azfake.ErrorResponder) { + require.EqualValues(t, 0.5, temperature) + calledFloat = true + resp.SetResponse(http.StatusNoContent, multipartgroup.MultiPartFormDataHTTPPartsNonStringClientFloatResponse{}, nil) + return + }, + }, + }, + }, + } + client := newFakeClient(t, fake.NewMultiPartServerTransport(&srv)) + _, err := client.NewMultiPartFormDataClient().NewMultiPartFormDataHTTPPartsClient().NewMultiPartFormDataHTTPPartsNonStringClient().Float(context.Background(), 0.5, nil) + require.NoError(t, err) + require.True(t, calledFloat) +} diff --git a/test/http-specs/payload/multipartgroup/formdata_client_test.go b/test/http-specs/payload/multipartgroup/formdata_client_test.go new file mode 100644 index 000000000000..7e0587ad348f --- /dev/null +++ b/test/http-specs/payload/multipartgroup/formdata_client_test.go @@ -0,0 +1,204 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package multipartgroup_test + +import ( + "bytes" + "context" + "io" + "multipartgroup" + "os" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestFormDataClient_AnonymousModel(t *testing.T) { + client := newClient(t) + jpgFile, err := os.OpenFile(jpgPath, os.O_RDONLY, 0) + require.NoError(t, err) + defer func() { _ = jpgFile.Close() }() + resp, err := client.NewMultiPartFormDataClient().AnonymousModel(context.Background(), jpgFile, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestFormDataClient_Basic(t *testing.T) { + client := newClient(t) + jpgFile, err := os.OpenFile(jpgPath, os.O_RDONLY, 0) + require.NoError(t, err) + defer func() { _ = jpgFile.Close() }() + resp, err := client.NewMultiPartFormDataClient().Basic(context.Background(), multipartgroup.MultiPartRequest{ + ID: "123", + ProfileImage: streaming.MultipartContent{ + Body: jpgFile, + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestFormDataClient_BinaryArrayParts(t *testing.T) { + client := newClient(t) + pngFile, err := os.ReadFile(pngPath) + require.NoError(t, err) + resp, err := client.NewMultiPartFormDataClient().BinaryArrayParts(context.Background(), multipartgroup.BinaryArrayPartsRequest{ + ID: "123", + Pictures: []streaming.MultipartContent{ + { + Body: streaming.NopCloser(bytes.NewReader(pngFile)), + }, + { + Body: streaming.NopCloser(bytes.NewReader(pngFile)), + }, + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestFormDataClient_CheckFileNameAndContentType(t *testing.T) { + client := newClient(t) + jpgFile, err := os.OpenFile(jpgPath, os.O_RDONLY, 0) + require.NoError(t, err) + defer func() { _ = jpgFile.Close() }() + resp, err := client.NewMultiPartFormDataClient().CheckFileNameAndContentType(context.Background(), multipartgroup.MultiPartRequest{ + ID: "123", + ProfileImage: streaming.MultipartContent{ + Body: jpgFile, + ContentType: "image/jpg", + Filename: "hello.jpg", + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestFormDataClient_FileArrayAndBasic(t *testing.T) { + client := newClient(t) + jpgFile, err := os.OpenFile(jpgPath, os.O_RDONLY, 0) + require.NoError(t, err) + defer func() { _ = jpgFile.Close() }() + pngFile, err := os.ReadFile(pngPath) + require.NoError(t, err) + resp, err := client.NewMultiPartFormDataClient().FileArrayAndBasic(context.Background(), multipartgroup.ComplexPartsRequest{ + Address: multipartgroup.Address{ + City: to.Ptr("X"), + }, + ID: "123", + Pictures: []streaming.MultipartContent{ + { + Body: streaming.NopCloser(bytes.NewReader(pngFile)), + }, + { + Body: streaming.NopCloser(bytes.NewReader(pngFile)), + }, + }, + ProfileImage: streaming.MultipartContent{Body: jpgFile}, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestFormDataClient_JSONPart(t *testing.T) { + client := newClient(t) + jpgFile, err := os.OpenFile(jpgPath, os.O_RDONLY, 0) + require.NoError(t, err) + defer func() { _ = jpgFile.Close() }() + resp, err := client.NewMultiPartFormDataClient().JSONPart(context.Background(), multipartgroup.JSONPartRequest{ + Address: multipartgroup.Address{ + City: to.Ptr("X"), + }, + ProfileImage: streaming.MultipartContent{ + Body: jpgFile, + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestFormDataClient_MultiBinaryParts(t *testing.T) { + client := newClient(t) + jpgFile, err := os.OpenFile(jpgPath, os.O_RDONLY, 0) + require.NoError(t, err) + defer func() { _ = jpgFile.Close() }() + + // without optional picture + resp, err := client.NewMultiPartFormDataClient().MultiBinaryParts(context.Background(), multipartgroup.MultiBinaryPartsRequest{ + ProfileImage: streaming.MultipartContent{ + Body: jpgFile, + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) + + // with optional picture + _, err = jpgFile.Seek(0, io.SeekStart) + require.NoError(t, err) + pngFile, err := os.OpenFile(pngPath, os.O_RDONLY, 0) + require.NoError(t, err) + defer func() { _ = pngFile.Close() }() + resp, err = client.NewMultiPartFormDataClient().MultiBinaryParts(context.Background(), multipartgroup.MultiBinaryPartsRequest{ + ProfileImage: streaming.MultipartContent{ + Body: jpgFile, + }, + Picture: &streaming.MultipartContent{ + Body: pngFile, + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestFormDataClient_OptionalParts(t *testing.T) { + client := newClient(t) + + // first time with only id + resp, err := client.NewMultiPartFormDataClient().OptionalParts(context.Background(), multipartgroup.MultiPartOptionalRequest{ + ID: to.Ptr("123"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) + + // second time with only profileImage + jpgFile, err := os.OpenFile(jpgPath, os.O_RDONLY, 0) + require.NoError(t, err) + defer func() { _ = jpgFile.Close() }() + resp, err = client.NewMultiPartFormDataClient().OptionalParts(context.Background(), multipartgroup.MultiPartOptionalRequest{ + ProfileImage: &streaming.MultipartContent{ + Body: jpgFile, + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) + + // third time with both id and profileImage + _, err = jpgFile.Seek(0, io.SeekStart) + require.NoError(t, err) + resp, err = client.NewMultiPartFormDataClient().OptionalParts(context.Background(), multipartgroup.MultiPartOptionalRequest{ + ID: to.Ptr("123"), + ProfileImage: &streaming.MultipartContent{ + Body: jpgFile, + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestFormDataClient_WithWireName(t *testing.T) { + client := newClient(t) + jpgFile, err := os.OpenFile(jpgPath, os.O_RDONLY, 0) + require.NoError(t, err) + defer func() { _ = jpgFile.Close() }() + resp, err := client.NewMultiPartFormDataClient().WithWireName(context.Background(), multipartgroup.MultiPartRequestWithWireName{ + Identifier: "123", + Image: streaming.MultipartContent{ + Body: jpgFile, + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/multipartgroup/formdatafile_client_test.go b/test/http-specs/payload/multipartgroup/formdatafile_client_test.go new file mode 100644 index 000000000000..927ff01b9e81 --- /dev/null +++ b/test/http-specs/payload/multipartgroup/formdatafile_client_test.go @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package multipartgroup_test + +import ( + "bytes" + "context" + "os" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming" + "github.com/stretchr/testify/require" +) + +func TestFormDataFileClient_UploadFileArray(t *testing.T) { + client := newClient(t) + pngFile, err := os.ReadFile(pngPath) + require.NoError(t, err) + resp, err := client.NewMultiPartFormDataClient().NewMultiPartFormDataFileClient().UploadFileArray(context.Background(), []streaming.MultipartContent{ + { + Body: streaming.NopCloser(bytes.NewReader(pngFile)), + Filename: "image1.png", + }, + { + Body: streaming.NopCloser(bytes.NewReader(pngFile)), + Filename: "image2.png", + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestFormDataFileClient_UploadFileRequiredFilename(t *testing.T) { + client := newClient(t) + pngFile, err := os.OpenFile(pngPath, os.O_RDONLY, 0) + require.NoError(t, err) + defer func() { _ = pngFile.Close() }() + resp, err := client.NewMultiPartFormDataClient().NewMultiPartFormDataFileClient().UploadFileRequiredFilename(context.Background(), streaming.MultipartContent{ + Body: pngFile, + Filename: "image.png", + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestFormDataFileClient_UploadFileSpecificContentType(t *testing.T) { + client := newClient(t) + pngFile, err := os.OpenFile(pngPath, os.O_RDONLY, 0) + require.NoError(t, err) + defer func() { _ = pngFile.Close() }() + resp, err := client.NewMultiPartFormDataClient().NewMultiPartFormDataFileClient().UploadFileSpecificContentType(context.Background(), streaming.MultipartContent{ + Body: pngFile, + Filename: "image.png", + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/multipartgroup/formdatahttpparts_client_test.go b/test/http-specs/payload/multipartgroup/formdatahttpparts_client_test.go new file mode 100644 index 000000000000..b346a15a5eb2 --- /dev/null +++ b/test/http-specs/payload/multipartgroup/formdatahttpparts_client_test.go @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package multipartgroup_test + +import ( + "bytes" + "context" + "multipartgroup" + "os" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestFormDataHTTPPartsClient_JSONArrayAndFileArray(t *testing.T) { + client := newClient(t) + jpgFile, err := os.OpenFile(jpgPath, os.O_RDONLY, 0) + require.NoError(t, err) + defer func() { _ = jpgFile.Close() }() + pngFile, err := os.ReadFile(pngPath) + require.NoError(t, err) + resp, err := client.NewMultiPartFormDataClient().NewMultiPartFormDataHTTPPartsClient().JSONArrayAndFileArray(context.Background(), multipartgroup.ComplexHTTPPartsModelRequest{ + ID: "123", + Address: multipartgroup.Address{ + City: to.Ptr("X"), + }, + ProfileImage: streaming.MultipartContent{ + Body: jpgFile, + ContentType: "application/octet-stream", + Filename: "hello.jpg", + }, + PreviousAddresses: []multipartgroup.Address{ + {City: to.Ptr("Y")}, + {City: to.Ptr("Z")}, + }, + Pictures: []streaming.MultipartContent{ + { + Body: streaming.NopCloser(bytes.NewReader(pngFile)), + ContentType: "application/octet-stream", + Filename: "hello.png", + }, + { + Body: streaming.NopCloser(bytes.NewReader(pngFile)), + ContentType: "application/octet-stream", + Filename: "hello.png", + }, + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/multipartgroup/formdatahttppartscontenttype_client_test.go b/test/http-specs/payload/multipartgroup/formdatahttppartscontenttype_client_test.go new file mode 100644 index 000000000000..0f422c48c755 --- /dev/null +++ b/test/http-specs/payload/multipartgroup/formdatahttppartscontenttype_client_test.go @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package multipartgroup_test + +import ( + "context" + "multipartgroup" + "os" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming" + "github.com/stretchr/testify/require" +) + +func TestFormDataHTTPPartsContentTypeClient_ImageJPEGContentType(t *testing.T) { + client := newClient(t) + jpgFile, err := os.OpenFile(jpgPath, os.O_RDONLY, 0) + require.NoError(t, err) + defer func() { _ = jpgFile.Close() }() + resp, err := client.NewMultiPartFormDataClient().NewMultiPartFormDataHTTPPartsClient().NewMultiPartFormDataHTTPPartsContentTypeClient().ImageJPEGContentType(context.Background(), multipartgroup.FileWithHTTPPartSpecificContentTypeRequest{ + ProfileImage: streaming.MultipartContent{ + Body: jpgFile, + Filename: "hello.jpg", + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestFormDataHTTPPartsContentTypeClient_OptionalContentType(t *testing.T) { + client := newClient(t) + jpgFile, err := os.OpenFile(jpgPath, os.O_RDONLY, 0) + require.NoError(t, err) + defer func() { _ = jpgFile.Close() }() + resp, err := client.NewMultiPartFormDataClient().NewMultiPartFormDataHTTPPartsClient().NewMultiPartFormDataHTTPPartsContentTypeClient().OptionalContentType(context.Background(), multipartgroup.FileWithHTTPPartOptionalContentTypeRequest{ + ProfileImage: streaming.MultipartContent{ + Body: jpgFile, + Filename: "hello.jpg", + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestFormDataHTTPPartsContentTypeClient_RequiredContentType(t *testing.T) { + client := newClient(t) + jpgFile, err := os.OpenFile(jpgPath, os.O_RDONLY, 0) + require.NoError(t, err) + defer func() { _ = jpgFile.Close() }() + resp, err := client.NewMultiPartFormDataClient().NewMultiPartFormDataHTTPPartsClient().NewMultiPartFormDataHTTPPartsContentTypeClient().RequiredContentType(context.Background(), multipartgroup.FileWithHTTPPartRequiredContentTypeRequest{ + ProfileImage: streaming.MultipartContent{ + Body: jpgFile, + ContentType: "application/octet-stream", + Filename: "hello.jpg", + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/multipartgroup/formdatahttppartsnonstring_client_test.go b/test/http-specs/payload/multipartgroup/formdatahttppartsnonstring_client_test.go new file mode 100644 index 000000000000..12e7970d597a --- /dev/null +++ b/test/http-specs/payload/multipartgroup/formdatahttppartsnonstring_client_test.go @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package multipartgroup_test + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestFormDataHTTPPartsNonStringClient_Float(t *testing.T) { + client := newClient(t) + resp, err := client.NewMultiPartFormDataClient().NewMultiPartFormDataHTTPPartsClient().NewMultiPartFormDataHTTPPartsNonStringClient().Float(context.Background(), 0.5, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/multipartgroup/go.mod b/test/http-specs/payload/multipartgroup/go.mod new file mode 100644 index 000000000000..ac5906bcd250 --- /dev/null +++ b/test/http-specs/payload/multipartgroup/go.mod @@ -0,0 +1,17 @@ +module multipartgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/payload/multipartgroup/go.sum b/test/http-specs/payload/multipartgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/payload/multipartgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/payload/multipartgroup/helpers_test.go b/test/http-specs/payload/multipartgroup/helpers_test.go new file mode 100644 index 000000000000..20c355b2d4d2 --- /dev/null +++ b/test/http-specs/payload/multipartgroup/helpers_test.go @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package multipartgroup_test + +import ( + "multipartgroup" + "testing" + + "github.com/stretchr/testify/require" +) + +const ( + jpgPath = "../../../../node_modules/@typespec/http-specs/assets/image.jpg" + pngPath = "../../../../node_modules/@typespec/http-specs/assets/image.png" +) + +func newClient(t *testing.T) *multipartgroup.MultiPartClient { + t.Helper() + client, err := multipartgroup.NewMultiPartClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + return client +} diff --git a/test/http-specs/payload/multipartgroup/testdata/_metadata.json b/test/http-specs/payload/multipartgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/payload/multipartgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/payload/multipartgroup/zz_models.go b/test/http-specs/payload/multipartgroup/zz_models.go new file mode 100644 index 000000000000..8dfbaae846bd --- /dev/null +++ b/test/http-specs/payload/multipartgroup/zz_models.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multipartgroup + +import "github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming" + +type Address struct { + // REQUIRED + City *string +} + +type BinaryArrayPartsRequest struct { + // REQUIRED + ID string + + // REQUIRED + Pictures []streaming.MultipartContent +} + +type ComplexHTTPPartsModelRequest struct { + // REQUIRED + Address Address + + // REQUIRED + ID string + + // REQUIRED + Pictures []streaming.MultipartContent + + // REQUIRED + PreviousAddresses []Address + + // REQUIRED + ProfileImage streaming.MultipartContent +} + +type ComplexPartsRequest struct { + // REQUIRED + Address Address + + // REQUIRED + ID string + + // REQUIRED + Pictures []streaming.MultipartContent + + // REQUIRED + ProfileImage streaming.MultipartContent +} + +type FileWithHTTPPartOptionalContentTypeRequest struct { + // REQUIRED + ProfileImage streaming.MultipartContent +} + +type FileWithHTTPPartRequiredContentTypeRequest struct { + // REQUIRED + ProfileImage streaming.MultipartContent +} + +type FileWithHTTPPartSpecificContentTypeRequest struct { + // REQUIRED + ProfileImage streaming.MultipartContent +} + +type JSONPartRequest struct { + // REQUIRED + Address Address + + // REQUIRED + ProfileImage streaming.MultipartContent +} + +type MultiBinaryPartsRequest struct { + // REQUIRED + ProfileImage streaming.MultipartContent + Picture *streaming.MultipartContent +} + +type MultiPartOptionalRequest struct { + ID *string + ProfileImage *streaming.MultipartContent +} + +type MultiPartRequest struct { + // REQUIRED + ID string + + // REQUIRED + ProfileImage streaming.MultipartContent +} + +type MultiPartRequestWithWireName struct { + // REQUIRED + Identifier string + + // REQUIRED + Image streaming.MultipartContent +} diff --git a/test/http-specs/payload/multipartgroup/zz_models_serde.go b/test/http-specs/payload/multipartgroup/zz_models_serde.go new file mode 100644 index 000000000000..171df56bdda8 --- /dev/null +++ b/test/http-specs/payload/multipartgroup/zz_models_serde.go @@ -0,0 +1,172 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multipartgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type Address. +func (a Address) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "city", a.City) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Address. +func (a *Address) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "city": + err = unpopulate(val, "City", &a.City) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// toMultipartFormData converts BinaryArrayPartsRequest to multipart/form data. +func (b BinaryArrayPartsRequest) toMultipartFormData() (map[string]any, error) { + objectMap := make(map[string]any) + objectMap["id"] = b.ID + objectMap["pictures"] = b.Pictures + return objectMap, nil +} + +// toMultipartFormData converts ComplexHTTPPartsModelRequest to multipart/form data. +func (c ComplexHTTPPartsModelRequest) toMultipartFormData() (map[string]any, error) { + objectMap := make(map[string]any) + if err := populateMultipartJSON(objectMap, "address", c.Address); err != nil { + return nil, err + } + objectMap["id"] = c.ID + objectMap["pictures"] = c.Pictures + if err := populateMultipartJSON(objectMap, "previousAddresses", c.PreviousAddresses); err != nil { + return nil, err + } + objectMap["profileImage"] = c.ProfileImage + return objectMap, nil +} + +// toMultipartFormData converts ComplexPartsRequest to multipart/form data. +func (c ComplexPartsRequest) toMultipartFormData() (map[string]any, error) { + objectMap := make(map[string]any) + if err := populateMultipartJSON(objectMap, "address", c.Address); err != nil { + return nil, err + } + objectMap["id"] = c.ID + objectMap["pictures"] = c.Pictures + objectMap["profileImage"] = c.ProfileImage + return objectMap, nil +} + +// toMultipartFormData converts FileWithHTTPPartOptionalContentTypeRequest to multipart/form data. +func (f FileWithHTTPPartOptionalContentTypeRequest) toMultipartFormData() (map[string]any, error) { + objectMap := make(map[string]any) + objectMap["profileImage"] = f.ProfileImage + return objectMap, nil +} + +// toMultipartFormData converts FileWithHTTPPartRequiredContentTypeRequest to multipart/form data. +func (f FileWithHTTPPartRequiredContentTypeRequest) toMultipartFormData() (map[string]any, error) { + objectMap := make(map[string]any) + objectMap["profileImage"] = f.ProfileImage + return objectMap, nil +} + +// toMultipartFormData converts FileWithHTTPPartSpecificContentTypeRequest to multipart/form data. +func (f FileWithHTTPPartSpecificContentTypeRequest) toMultipartFormData() (map[string]any, error) { + objectMap := make(map[string]any) + objectMap["profileImage"] = f.ProfileImage + return objectMap, nil +} + +// toMultipartFormData converts JSONPartRequest to multipart/form data. +func (j JSONPartRequest) toMultipartFormData() (map[string]any, error) { + objectMap := make(map[string]any) + if err := populateMultipartJSON(objectMap, "address", j.Address); err != nil { + return nil, err + } + objectMap["profileImage"] = j.ProfileImage + return objectMap, nil +} + +// toMultipartFormData converts MultiBinaryPartsRequest to multipart/form data. +func (m MultiBinaryPartsRequest) toMultipartFormData() (map[string]any, error) { + objectMap := make(map[string]any) + if m.Picture != nil { + objectMap["picture"] = *m.Picture + } + objectMap["profileImage"] = m.ProfileImage + return objectMap, nil +} + +// toMultipartFormData converts MultiPartOptionalRequest to multipart/form data. +func (m MultiPartOptionalRequest) toMultipartFormData() (map[string]any, error) { + objectMap := make(map[string]any) + if m.ID != nil { + objectMap["id"] = *m.ID + } + if m.ProfileImage != nil { + objectMap["profileImage"] = *m.ProfileImage + } + return objectMap, nil +} + +// toMultipartFormData converts MultiPartRequest to multipart/form data. +func (m MultiPartRequest) toMultipartFormData() (map[string]any, error) { + objectMap := make(map[string]any) + objectMap["id"] = m.ID + objectMap["profileImage"] = m.ProfileImage + return objectMap, nil +} + +// toMultipartFormData converts MultiPartRequestWithWireName to multipart/form data. +func (m MultiPartRequestWithWireName) toMultipartFormData() (map[string]any, error) { + objectMap := make(map[string]any) + objectMap["id"] = m.Identifier + objectMap["profileImage"] = m.Image + return objectMap, nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func populateMultipartJSON(m map[string]any, k string, v any) error { + data, err := json.Marshal(v) + if err != nil { + return err + } + m[k] = data + return nil +} diff --git a/test/http-specs/payload/multipartgroup/zz_multipart_client.go b/test/http-specs/payload/multipartgroup/zz_multipart_client.go new file mode 100644 index 000000000000..8071805cfd01 --- /dev/null +++ b/test/http-specs/payload/multipartgroup/zz_multipart_client.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multipartgroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// MultiPartClient - Test for multipart +// Don't use this type directly, use NewMultiPartClientWithNoCredential() instead. +type MultiPartClient struct { + internal *azcore.Client + endpoint string +} + +// MultiPartClientOptions contains the optional values for creating a [MultiPartClient]. +type MultiPartClientOptions struct { + azcore.ClientOptions +} + +// NewMultiPartClientWithNoCredential creates a new instance of MultiPartClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewMultiPartClientWithNoCredential(endpoint string, options *MultiPartClientOptions) (*MultiPartClient, error) { + if options == nil { + options = &MultiPartClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &MultiPartClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewMultiPartFormDataClient creates a new instance of [MultiPartFormDataClient]. +func (client *MultiPartClient) NewMultiPartFormDataClient() *MultiPartFormDataClient { + return &MultiPartFormDataClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/http-specs/payload/multipartgroup/zz_multipartformdata_client.go b/test/http-specs/payload/multipartgroup/zz_multipartformdata_client.go new file mode 100644 index 000000000000..38248789bca8 --- /dev/null +++ b/test/http-specs/payload/multipartgroup/zz_multipartformdata_client.go @@ -0,0 +1,412 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multipartgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "io" + "net/http" +) + +// MultiPartFormDataClient contains the methods for the MultiPartFormData group. +// Don't use this type directly, use [MultiPartClient.NewMultiPartFormDataClient] instead. +type MultiPartFormDataClient struct { + internal *azcore.Client + endpoint string +} + +// NewMultiPartFormDataFileClient creates a new instance of [MultiPartFormDataFileClient]. +func (client *MultiPartFormDataClient) NewMultiPartFormDataFileClient() *MultiPartFormDataFileClient { + return &MultiPartFormDataFileClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewMultiPartFormDataHTTPPartsClient creates a new instance of [MultiPartFormDataHTTPPartsClient]. +func (client *MultiPartFormDataClient) NewMultiPartFormDataHTTPPartsClient() *MultiPartFormDataHTTPPartsClient { + return &MultiPartFormDataHTTPPartsClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// AnonymousModel - Test content-type: multipart/form-data +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MultiPartFormDataClientAnonymousModelOptions contains the optional parameters for the MultiPartFormDataClient.AnonymousModel +// method. +func (client *MultiPartFormDataClient) AnonymousModel(ctx context.Context, profileImage io.ReadSeekCloser, options *MultiPartFormDataClientAnonymousModelOptions) (MultiPartFormDataClientAnonymousModelResponse, error) { + var err error + const operationName = "MultiPartFormDataClient.AnonymousModel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.anonymousModelCreateRequest(ctx, profileImage, options) + if err != nil { + return MultiPartFormDataClientAnonymousModelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MultiPartFormDataClientAnonymousModelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MultiPartFormDataClientAnonymousModelResponse{}, err + } + return MultiPartFormDataClientAnonymousModelResponse{}, nil +} + +// anonymousModelCreateRequest creates the AnonymousModel request. +func (client *MultiPartFormDataClient) anonymousModelCreateRequest(ctx context.Context, profileImage io.ReadSeekCloser, _ *MultiPartFormDataClientAnonymousModelOptions) (*policy.Request, error) { + urlPath := "/multipart/form-data/anonymous-model" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + formData := map[string]any{} + formData["profileImage"] = profileImage + if err := runtime.SetMultipartFormData(req, formData); err != nil { + return nil, err + } + return req, nil +} + +// Basic - Test content-type: multipart/form-data +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MultiPartFormDataClientBasicOptions contains the optional parameters for the MultiPartFormDataClient.Basic method. +func (client *MultiPartFormDataClient) Basic(ctx context.Context, body MultiPartRequest, options *MultiPartFormDataClientBasicOptions) (MultiPartFormDataClientBasicResponse, error) { + var err error + const operationName = "MultiPartFormDataClient.Basic" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.basicCreateRequest(ctx, body, options) + if err != nil { + return MultiPartFormDataClientBasicResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MultiPartFormDataClientBasicResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MultiPartFormDataClientBasicResponse{}, err + } + return MultiPartFormDataClientBasicResponse{}, nil +} + +// basicCreateRequest creates the Basic request. +func (client *MultiPartFormDataClient) basicCreateRequest(ctx context.Context, body MultiPartRequest, _ *MultiPartFormDataClientBasicOptions) (*policy.Request, error) { + urlPath := "/multipart/form-data/mixed-parts" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + formData, err := body.toMultipartFormData() + if err != nil { + return nil, err + } + if err := runtime.SetMultipartFormData(req, formData); err != nil { + return nil, err + } + return req, nil +} + +// BinaryArrayParts - Test content-type: multipart/form-data for scenario contains multi binary parts +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MultiPartFormDataClientBinaryArrayPartsOptions contains the optional parameters for the MultiPartFormDataClient.BinaryArrayParts +// method. +func (client *MultiPartFormDataClient) BinaryArrayParts(ctx context.Context, body BinaryArrayPartsRequest, options *MultiPartFormDataClientBinaryArrayPartsOptions) (MultiPartFormDataClientBinaryArrayPartsResponse, error) { + var err error + const operationName = "MultiPartFormDataClient.BinaryArrayParts" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.binaryArrayPartsCreateRequest(ctx, body, options) + if err != nil { + return MultiPartFormDataClientBinaryArrayPartsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MultiPartFormDataClientBinaryArrayPartsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MultiPartFormDataClientBinaryArrayPartsResponse{}, err + } + return MultiPartFormDataClientBinaryArrayPartsResponse{}, nil +} + +// binaryArrayPartsCreateRequest creates the BinaryArrayParts request. +func (client *MultiPartFormDataClient) binaryArrayPartsCreateRequest(ctx context.Context, body BinaryArrayPartsRequest, _ *MultiPartFormDataClientBinaryArrayPartsOptions) (*policy.Request, error) { + urlPath := "/multipart/form-data/binary-array-parts" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + formData, err := body.toMultipartFormData() + if err != nil { + return nil, err + } + if err := runtime.SetMultipartFormData(req, formData); err != nil { + return nil, err + } + return req, nil +} + +// CheckFileNameAndContentType - Test content-type: multipart/form-data +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MultiPartFormDataClientCheckFileNameAndContentTypeOptions contains the optional parameters for the MultiPartFormDataClient.CheckFileNameAndContentType +// method. +func (client *MultiPartFormDataClient) CheckFileNameAndContentType(ctx context.Context, body MultiPartRequest, options *MultiPartFormDataClientCheckFileNameAndContentTypeOptions) (MultiPartFormDataClientCheckFileNameAndContentTypeResponse, error) { + var err error + const operationName = "MultiPartFormDataClient.CheckFileNameAndContentType" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.checkFileNameAndContentTypeCreateRequest(ctx, body, options) + if err != nil { + return MultiPartFormDataClientCheckFileNameAndContentTypeResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MultiPartFormDataClientCheckFileNameAndContentTypeResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MultiPartFormDataClientCheckFileNameAndContentTypeResponse{}, err + } + return MultiPartFormDataClientCheckFileNameAndContentTypeResponse{}, nil +} + +// checkFileNameAndContentTypeCreateRequest creates the CheckFileNameAndContentType request. +func (client *MultiPartFormDataClient) checkFileNameAndContentTypeCreateRequest(ctx context.Context, body MultiPartRequest, _ *MultiPartFormDataClientCheckFileNameAndContentTypeOptions) (*policy.Request, error) { + urlPath := "/multipart/form-data/check-filename-and-content-type" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + formData, err := body.toMultipartFormData() + if err != nil { + return nil, err + } + if err := runtime.SetMultipartFormData(req, formData); err != nil { + return nil, err + } + return req, nil +} + +// FileArrayAndBasic - Test content-type: multipart/form-data for mixed scenarios +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MultiPartFormDataClientFileArrayAndBasicOptions contains the optional parameters for the MultiPartFormDataClient.FileArrayAndBasic +// method. +func (client *MultiPartFormDataClient) FileArrayAndBasic(ctx context.Context, body ComplexPartsRequest, options *MultiPartFormDataClientFileArrayAndBasicOptions) (MultiPartFormDataClientFileArrayAndBasicResponse, error) { + var err error + const operationName = "MultiPartFormDataClient.FileArrayAndBasic" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.fileArrayAndBasicCreateRequest(ctx, body, options) + if err != nil { + return MultiPartFormDataClientFileArrayAndBasicResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MultiPartFormDataClientFileArrayAndBasicResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MultiPartFormDataClientFileArrayAndBasicResponse{}, err + } + return MultiPartFormDataClientFileArrayAndBasicResponse{}, nil +} + +// fileArrayAndBasicCreateRequest creates the FileArrayAndBasic request. +func (client *MultiPartFormDataClient) fileArrayAndBasicCreateRequest(ctx context.Context, body ComplexPartsRequest, _ *MultiPartFormDataClientFileArrayAndBasicOptions) (*policy.Request, error) { + urlPath := "/multipart/form-data/complex-parts" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + formData, err := body.toMultipartFormData() + if err != nil { + return nil, err + } + if err := runtime.SetMultipartFormData(req, formData); err != nil { + return nil, err + } + return req, nil +} + +// JSONPart - Test content-type: multipart/form-data for scenario contains json part and binary part +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MultiPartFormDataClientJSONPartOptions contains the optional parameters for the MultiPartFormDataClient.JSONPart +// method. +func (client *MultiPartFormDataClient) JSONPart(ctx context.Context, body JSONPartRequest, options *MultiPartFormDataClientJSONPartOptions) (MultiPartFormDataClientJSONPartResponse, error) { + var err error + const operationName = "MultiPartFormDataClient.JSONPart" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.jsonPartCreateRequest(ctx, body, options) + if err != nil { + return MultiPartFormDataClientJSONPartResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MultiPartFormDataClientJSONPartResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MultiPartFormDataClientJSONPartResponse{}, err + } + return MultiPartFormDataClientJSONPartResponse{}, nil +} + +// jsonPartCreateRequest creates the JSONPart request. +func (client *MultiPartFormDataClient) jsonPartCreateRequest(ctx context.Context, body JSONPartRequest, _ *MultiPartFormDataClientJSONPartOptions) (*policy.Request, error) { + urlPath := "/multipart/form-data/json-part" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + formData, err := body.toMultipartFormData() + if err != nil { + return nil, err + } + if err := runtime.SetMultipartFormData(req, formData); err != nil { + return nil, err + } + return req, nil +} + +// MultiBinaryParts - Test content-type: multipart/form-data for scenario contains multi binary parts +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MultiPartFormDataClientMultiBinaryPartsOptions contains the optional parameters for the MultiPartFormDataClient.MultiBinaryParts +// method. +func (client *MultiPartFormDataClient) MultiBinaryParts(ctx context.Context, body MultiBinaryPartsRequest, options *MultiPartFormDataClientMultiBinaryPartsOptions) (MultiPartFormDataClientMultiBinaryPartsResponse, error) { + var err error + const operationName = "MultiPartFormDataClient.MultiBinaryParts" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.multiBinaryPartsCreateRequest(ctx, body, options) + if err != nil { + return MultiPartFormDataClientMultiBinaryPartsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MultiPartFormDataClientMultiBinaryPartsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MultiPartFormDataClientMultiBinaryPartsResponse{}, err + } + return MultiPartFormDataClientMultiBinaryPartsResponse{}, nil +} + +// multiBinaryPartsCreateRequest creates the MultiBinaryParts request. +func (client *MultiPartFormDataClient) multiBinaryPartsCreateRequest(ctx context.Context, body MultiBinaryPartsRequest, _ *MultiPartFormDataClientMultiBinaryPartsOptions) (*policy.Request, error) { + urlPath := "/multipart/form-data/multi-binary-parts" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + formData, err := body.toMultipartFormData() + if err != nil { + return nil, err + } + if err := runtime.SetMultipartFormData(req, formData); err != nil { + return nil, err + } + return req, nil +} + +// OptionalParts - Test content-type: multipart/form-data with optional parts +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MultiPartFormDataClientOptionalPartsOptions contains the optional parameters for the MultiPartFormDataClient.OptionalParts +// method. +func (client *MultiPartFormDataClient) OptionalParts(ctx context.Context, body MultiPartOptionalRequest, options *MultiPartFormDataClientOptionalPartsOptions) (MultiPartFormDataClientOptionalPartsResponse, error) { + var err error + const operationName = "MultiPartFormDataClient.OptionalParts" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.optionalPartsCreateRequest(ctx, body, options) + if err != nil { + return MultiPartFormDataClientOptionalPartsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MultiPartFormDataClientOptionalPartsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MultiPartFormDataClientOptionalPartsResponse{}, err + } + return MultiPartFormDataClientOptionalPartsResponse{}, nil +} + +// optionalPartsCreateRequest creates the OptionalParts request. +func (client *MultiPartFormDataClient) optionalPartsCreateRequest(ctx context.Context, body MultiPartOptionalRequest, _ *MultiPartFormDataClientOptionalPartsOptions) (*policy.Request, error) { + urlPath := "/multipart/form-data/optional-parts" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + formData, err := body.toMultipartFormData() + if err != nil { + return nil, err + } + if err := runtime.SetMultipartFormData(req, formData); err != nil { + return nil, err + } + return req, nil +} + +// WithWireName - Test content-type: multipart/form-data with wire names +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MultiPartFormDataClientWithWireNameOptions contains the optional parameters for the MultiPartFormDataClient.WithWireName +// method. +func (client *MultiPartFormDataClient) WithWireName(ctx context.Context, body MultiPartRequestWithWireName, options *MultiPartFormDataClientWithWireNameOptions) (MultiPartFormDataClientWithWireNameResponse, error) { + var err error + const operationName = "MultiPartFormDataClient.WithWireName" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withWireNameCreateRequest(ctx, body, options) + if err != nil { + return MultiPartFormDataClientWithWireNameResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MultiPartFormDataClientWithWireNameResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MultiPartFormDataClientWithWireNameResponse{}, err + } + return MultiPartFormDataClientWithWireNameResponse{}, nil +} + +// withWireNameCreateRequest creates the WithWireName request. +func (client *MultiPartFormDataClient) withWireNameCreateRequest(ctx context.Context, body MultiPartRequestWithWireName, _ *MultiPartFormDataClientWithWireNameOptions) (*policy.Request, error) { + urlPath := "/multipart/form-data/mixed-parts-with-wire-name" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + formData, err := body.toMultipartFormData() + if err != nil { + return nil, err + } + if err := runtime.SetMultipartFormData(req, formData); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/multipartgroup/zz_multipartformdatafile_client.go b/test/http-specs/payload/multipartgroup/zz_multipartformdatafile_client.go new file mode 100644 index 000000000000..c1b2b260d163 --- /dev/null +++ b/test/http-specs/payload/multipartgroup/zz_multipartformdatafile_client.go @@ -0,0 +1,146 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multipartgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming" + "net/http" +) + +// MultiPartFormDataFileClient contains the methods for the MultiPartFormDataFile group. +// Don't use this type directly, use [MultiPartFormDataClient.NewMultiPartFormDataFileClient] instead. +type MultiPartFormDataFileClient struct { + internal *azcore.Client + endpoint string +} + +// UploadFileArray - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MultiPartFormDataFileClientUploadFileArrayOptions contains the optional parameters for the MultiPartFormDataFileClient.UploadFileArray +// method. +func (client *MultiPartFormDataFileClient) UploadFileArray(ctx context.Context, files []streaming.MultipartContent, options *MultiPartFormDataFileClientUploadFileArrayOptions) (MultiPartFormDataFileClientUploadFileArrayResponse, error) { + var err error + const operationName = "MultiPartFormDataFileClient.UploadFileArray" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.uploadFileArrayCreateRequest(ctx, files, options) + if err != nil { + return MultiPartFormDataFileClientUploadFileArrayResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MultiPartFormDataFileClientUploadFileArrayResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MultiPartFormDataFileClientUploadFileArrayResponse{}, err + } + return MultiPartFormDataFileClientUploadFileArrayResponse{}, nil +} + +// uploadFileArrayCreateRequest creates the UploadFileArray request. +func (client *MultiPartFormDataFileClient) uploadFileArrayCreateRequest(ctx context.Context, files []streaming.MultipartContent, _ *MultiPartFormDataFileClientUploadFileArrayOptions) (*policy.Request, error) { + urlPath := "/multipart/form-data/file/file-array" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + for i := range files { + files[i].ContentType = "image/png" + } + formData := map[string]any{} + formData["files"] = files + if err := runtime.SetMultipartFormData(req, formData); err != nil { + return nil, err + } + return req, nil +} + +// UploadFileRequiredFilename - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MultiPartFormDataFileClientUploadFileRequiredFilenameOptions contains the optional parameters for the MultiPartFormDataFileClient.UploadFileRequiredFilename +// method. +func (client *MultiPartFormDataFileClient) UploadFileRequiredFilename(ctx context.Context, file streaming.MultipartContent, options *MultiPartFormDataFileClientUploadFileRequiredFilenameOptions) (MultiPartFormDataFileClientUploadFileRequiredFilenameResponse, error) { + var err error + const operationName = "MultiPartFormDataFileClient.UploadFileRequiredFilename" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.uploadFileRequiredFilenameCreateRequest(ctx, file, options) + if err != nil { + return MultiPartFormDataFileClientUploadFileRequiredFilenameResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MultiPartFormDataFileClientUploadFileRequiredFilenameResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MultiPartFormDataFileClientUploadFileRequiredFilenameResponse{}, err + } + return MultiPartFormDataFileClientUploadFileRequiredFilenameResponse{}, nil +} + +// uploadFileRequiredFilenameCreateRequest creates the UploadFileRequiredFilename request. +func (client *MultiPartFormDataFileClient) uploadFileRequiredFilenameCreateRequest(ctx context.Context, file streaming.MultipartContent, _ *MultiPartFormDataFileClientUploadFileRequiredFilenameOptions) (*policy.Request, error) { + urlPath := "/multipart/form-data/file/required-filename" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + file.ContentType = "image/png" + formData := map[string]any{} + formData["file"] = file + if err := runtime.SetMultipartFormData(req, formData); err != nil { + return nil, err + } + return req, nil +} + +// UploadFileSpecificContentType - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MultiPartFormDataFileClientUploadFileSpecificContentTypeOptions contains the optional parameters for the MultiPartFormDataFileClient.UploadFileSpecificContentType +// method. +func (client *MultiPartFormDataFileClient) UploadFileSpecificContentType(ctx context.Context, file streaming.MultipartContent, options *MultiPartFormDataFileClientUploadFileSpecificContentTypeOptions) (MultiPartFormDataFileClientUploadFileSpecificContentTypeResponse, error) { + var err error + const operationName = "MultiPartFormDataFileClient.UploadFileSpecificContentType" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.uploadFileSpecificContentTypeCreateRequest(ctx, file, options) + if err != nil { + return MultiPartFormDataFileClientUploadFileSpecificContentTypeResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MultiPartFormDataFileClientUploadFileSpecificContentTypeResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MultiPartFormDataFileClientUploadFileSpecificContentTypeResponse{}, err + } + return MultiPartFormDataFileClientUploadFileSpecificContentTypeResponse{}, nil +} + +// uploadFileSpecificContentTypeCreateRequest creates the UploadFileSpecificContentType request. +func (client *MultiPartFormDataFileClient) uploadFileSpecificContentTypeCreateRequest(ctx context.Context, file streaming.MultipartContent, _ *MultiPartFormDataFileClientUploadFileSpecificContentTypeOptions) (*policy.Request, error) { + urlPath := "/multipart/form-data/file/specific-content-type" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + file.ContentType = "image/png" + formData := map[string]any{} + formData["file"] = file + if err := runtime.SetMultipartFormData(req, formData); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/multipartgroup/zz_multipartformdatahttpparts_client.go b/test/http-specs/payload/multipartgroup/zz_multipartformdatahttpparts_client.go new file mode 100644 index 000000000000..dacce326c178 --- /dev/null +++ b/test/http-specs/payload/multipartgroup/zz_multipartformdatahttpparts_client.go @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multipartgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// MultiPartFormDataHTTPPartsClient contains the methods for the MultiPartFormDataHTTPParts group. +// Don't use this type directly, use [MultiPartFormDataClient.NewMultiPartFormDataHTTPPartsClient] instead. +type MultiPartFormDataHTTPPartsClient struct { + internal *azcore.Client + endpoint string +} + +// NewMultiPartFormDataHTTPPartsContentTypeClient creates a new instance of [MultiPartFormDataHTTPPartsContentTypeClient]. +func (client *MultiPartFormDataHTTPPartsClient) NewMultiPartFormDataHTTPPartsContentTypeClient() *MultiPartFormDataHTTPPartsContentTypeClient { + return &MultiPartFormDataHTTPPartsContentTypeClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewMultiPartFormDataHTTPPartsNonStringClient creates a new instance of [MultiPartFormDataHTTPPartsNonStringClient]. +func (client *MultiPartFormDataHTTPPartsClient) NewMultiPartFormDataHTTPPartsNonStringClient() *MultiPartFormDataHTTPPartsNonStringClient { + return &MultiPartFormDataHTTPPartsNonStringClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// JSONArrayAndFileArray - Test content-type: multipart/form-data for mixed scenarios +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MultiPartFormDataHTTPPartsClientJSONArrayAndFileArrayOptions contains the optional parameters for the MultiPartFormDataHTTPPartsClient.JSONArrayAndFileArray +// method. +func (client *MultiPartFormDataHTTPPartsClient) JSONArrayAndFileArray(ctx context.Context, body ComplexHTTPPartsModelRequest, options *MultiPartFormDataHTTPPartsClientJSONArrayAndFileArrayOptions) (MultiPartFormDataHTTPPartsClientJSONArrayAndFileArrayResponse, error) { + var err error + const operationName = "MultiPartFormDataHTTPPartsClient.JSONArrayAndFileArray" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.jsonArrayAndFileArrayCreateRequest(ctx, body, options) + if err != nil { + return MultiPartFormDataHTTPPartsClientJSONArrayAndFileArrayResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MultiPartFormDataHTTPPartsClientJSONArrayAndFileArrayResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MultiPartFormDataHTTPPartsClientJSONArrayAndFileArrayResponse{}, err + } + return MultiPartFormDataHTTPPartsClientJSONArrayAndFileArrayResponse{}, nil +} + +// jsonArrayAndFileArrayCreateRequest creates the JSONArrayAndFileArray request. +func (client *MultiPartFormDataHTTPPartsClient) jsonArrayAndFileArrayCreateRequest(ctx context.Context, body ComplexHTTPPartsModelRequest, _ *MultiPartFormDataHTTPPartsClientJSONArrayAndFileArrayOptions) (*policy.Request, error) { + urlPath := "/multipart/form-data/complex-parts-with-httppart" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + formData, err := body.toMultipartFormData() + if err != nil { + return nil, err + } + if err := runtime.SetMultipartFormData(req, formData); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/multipartgroup/zz_multipartformdatahttppartscontenttype_client.go b/test/http-specs/payload/multipartgroup/zz_multipartformdatahttppartscontenttype_client.go new file mode 100644 index 000000000000..e3968c41d8c4 --- /dev/null +++ b/test/http-specs/payload/multipartgroup/zz_multipartformdatahttppartscontenttype_client.go @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multipartgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// MultiPartFormDataHTTPPartsContentTypeClient contains the methods for the MultiPartFormDataHTTPPartsContentType group. +// Don't use this type directly, use [MultiPartFormDataHTTPPartsClient.NewMultiPartFormDataHTTPPartsContentTypeClient] instead. +type MultiPartFormDataHTTPPartsContentTypeClient struct { + internal *azcore.Client + endpoint string +} + +// ImageJPEGContentType - Test content-type: multipart/form-data +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MultiPartFormDataHTTPPartsContentTypeClientImageJPEGContentTypeOptions contains the optional parameters for the +// MultiPartFormDataHTTPPartsContentTypeClient.ImageJPEGContentType method. +func (client *MultiPartFormDataHTTPPartsContentTypeClient) ImageJPEGContentType(ctx context.Context, body FileWithHTTPPartSpecificContentTypeRequest, options *MultiPartFormDataHTTPPartsContentTypeClientImageJPEGContentTypeOptions) (MultiPartFormDataHTTPPartsContentTypeClientImageJPEGContentTypeResponse, error) { + var err error + const operationName = "MultiPartFormDataHTTPPartsContentTypeClient.ImageJPEGContentType" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.imageJPEGContentTypeCreateRequest(ctx, body, options) + if err != nil { + return MultiPartFormDataHTTPPartsContentTypeClientImageJPEGContentTypeResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MultiPartFormDataHTTPPartsContentTypeClientImageJPEGContentTypeResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MultiPartFormDataHTTPPartsContentTypeClientImageJPEGContentTypeResponse{}, err + } + return MultiPartFormDataHTTPPartsContentTypeClientImageJPEGContentTypeResponse{}, nil +} + +// imageJPEGContentTypeCreateRequest creates the ImageJPEGContentType request. +func (client *MultiPartFormDataHTTPPartsContentTypeClient) imageJPEGContentTypeCreateRequest(ctx context.Context, body FileWithHTTPPartSpecificContentTypeRequest, _ *MultiPartFormDataHTTPPartsContentTypeClientImageJPEGContentTypeOptions) (*policy.Request, error) { + urlPath := "/multipart/form-data/check-filename-and-specific-content-type-with-httppart" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + body.ProfileImage.ContentType = "image/jpg" + formData, err := body.toMultipartFormData() + if err != nil { + return nil, err + } + if err := runtime.SetMultipartFormData(req, formData); err != nil { + return nil, err + } + return req, nil +} + +// OptionalContentType - Test content-type: multipart/form-data for optional content type +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MultiPartFormDataHTTPPartsContentTypeClientOptionalContentTypeOptions contains the optional parameters for the +// MultiPartFormDataHTTPPartsContentTypeClient.OptionalContentType method. +func (client *MultiPartFormDataHTTPPartsContentTypeClient) OptionalContentType(ctx context.Context, body FileWithHTTPPartOptionalContentTypeRequest, options *MultiPartFormDataHTTPPartsContentTypeClientOptionalContentTypeOptions) (MultiPartFormDataHTTPPartsContentTypeClientOptionalContentTypeResponse, error) { + var err error + const operationName = "MultiPartFormDataHTTPPartsContentTypeClient.OptionalContentType" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.optionalContentTypeCreateRequest(ctx, body, options) + if err != nil { + return MultiPartFormDataHTTPPartsContentTypeClientOptionalContentTypeResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MultiPartFormDataHTTPPartsContentTypeClientOptionalContentTypeResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MultiPartFormDataHTTPPartsContentTypeClientOptionalContentTypeResponse{}, err + } + return MultiPartFormDataHTTPPartsContentTypeClientOptionalContentTypeResponse{}, nil +} + +// optionalContentTypeCreateRequest creates the OptionalContentType request. +func (client *MultiPartFormDataHTTPPartsContentTypeClient) optionalContentTypeCreateRequest(ctx context.Context, body FileWithHTTPPartOptionalContentTypeRequest, _ *MultiPartFormDataHTTPPartsContentTypeClientOptionalContentTypeOptions) (*policy.Request, error) { + urlPath := "/multipart/form-data/file-with-http-part-optional-content-type" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + formData, err := body.toMultipartFormData() + if err != nil { + return nil, err + } + if err := runtime.SetMultipartFormData(req, formData); err != nil { + return nil, err + } + return req, nil +} + +// RequiredContentType - Test content-type: multipart/form-data +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MultiPartFormDataHTTPPartsContentTypeClientRequiredContentTypeOptions contains the optional parameters for the +// MultiPartFormDataHTTPPartsContentTypeClient.RequiredContentType method. +func (client *MultiPartFormDataHTTPPartsContentTypeClient) RequiredContentType(ctx context.Context, body FileWithHTTPPartRequiredContentTypeRequest, options *MultiPartFormDataHTTPPartsContentTypeClientRequiredContentTypeOptions) (MultiPartFormDataHTTPPartsContentTypeClientRequiredContentTypeResponse, error) { + var err error + const operationName = "MultiPartFormDataHTTPPartsContentTypeClient.RequiredContentType" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.requiredContentTypeCreateRequest(ctx, body, options) + if err != nil { + return MultiPartFormDataHTTPPartsContentTypeClientRequiredContentTypeResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MultiPartFormDataHTTPPartsContentTypeClientRequiredContentTypeResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MultiPartFormDataHTTPPartsContentTypeClientRequiredContentTypeResponse{}, err + } + return MultiPartFormDataHTTPPartsContentTypeClientRequiredContentTypeResponse{}, nil +} + +// requiredContentTypeCreateRequest creates the RequiredContentType request. +func (client *MultiPartFormDataHTTPPartsContentTypeClient) requiredContentTypeCreateRequest(ctx context.Context, body FileWithHTTPPartRequiredContentTypeRequest, _ *MultiPartFormDataHTTPPartsContentTypeClientRequiredContentTypeOptions) (*policy.Request, error) { + urlPath := "/multipart/form-data/check-filename-and-required-content-type-with-httppart" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + formData, err := body.toMultipartFormData() + if err != nil { + return nil, err + } + if err := runtime.SetMultipartFormData(req, formData); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/multipartgroup/zz_multipartformdatahttppartsnonstring_client.go b/test/http-specs/payload/multipartgroup/zz_multipartformdatahttppartsnonstring_client.go new file mode 100644 index 000000000000..df9e050f6d39 --- /dev/null +++ b/test/http-specs/payload/multipartgroup/zz_multipartformdatahttppartsnonstring_client.go @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multipartgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// MultiPartFormDataHTTPPartsNonStringClient contains the methods for the MultiPartFormDataHTTPPartsNonString group. +// Don't use this type directly, use [MultiPartFormDataHTTPPartsClient.NewMultiPartFormDataHTTPPartsNonStringClient] instead. +type MultiPartFormDataHTTPPartsNonStringClient struct { + internal *azcore.Client + endpoint string +} + +// Float - Test content-type: multipart/form-data for non string +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MultiPartFormDataHTTPPartsNonStringClientFloatOptions contains the optional parameters for the MultiPartFormDataHTTPPartsNonStringClient.Float +// method. +func (client *MultiPartFormDataHTTPPartsNonStringClient) Float(ctx context.Context, temperature float64, options *MultiPartFormDataHTTPPartsNonStringClientFloatOptions) (MultiPartFormDataHTTPPartsNonStringClientFloatResponse, error) { + var err error + const operationName = "MultiPartFormDataHTTPPartsNonStringClient.Float" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.floatCreateRequest(ctx, temperature, options) + if err != nil { + return MultiPartFormDataHTTPPartsNonStringClientFloatResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MultiPartFormDataHTTPPartsNonStringClientFloatResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MultiPartFormDataHTTPPartsNonStringClientFloatResponse{}, err + } + return MultiPartFormDataHTTPPartsNonStringClientFloatResponse{}, nil +} + +// floatCreateRequest creates the Float request. +func (client *MultiPartFormDataHTTPPartsNonStringClient) floatCreateRequest(ctx context.Context, temperature float64, _ *MultiPartFormDataHTTPPartsNonStringClientFloatOptions) (*policy.Request, error) { + urlPath := "/multipart/form-data/non-string-float" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + formData := map[string]any{} + formData["temperature"] = temperature + if err := runtime.SetMultipartFormData(req, formData); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/multipartgroup/zz_options.go b/test/http-specs/payload/multipartgroup/zz_options.go new file mode 100644 index 000000000000..3b6ef6b186ad --- /dev/null +++ b/test/http-specs/payload/multipartgroup/zz_options.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multipartgroup + +// MultiPartFormDataClientAnonymousModelOptions contains the optional parameters for the MultiPartFormDataClient.AnonymousModel +// method. +type MultiPartFormDataClientAnonymousModelOptions struct { + // placeholder for future optional parameters +} + +// MultiPartFormDataClientBasicOptions contains the optional parameters for the MultiPartFormDataClient.Basic method. +type MultiPartFormDataClientBasicOptions struct { + // placeholder for future optional parameters +} + +// MultiPartFormDataClientBinaryArrayPartsOptions contains the optional parameters for the MultiPartFormDataClient.BinaryArrayParts +// method. +type MultiPartFormDataClientBinaryArrayPartsOptions struct { + // placeholder for future optional parameters +} + +// MultiPartFormDataClientCheckFileNameAndContentTypeOptions contains the optional parameters for the MultiPartFormDataClient.CheckFileNameAndContentType +// method. +type MultiPartFormDataClientCheckFileNameAndContentTypeOptions struct { + // placeholder for future optional parameters +} + +// MultiPartFormDataClientFileArrayAndBasicOptions contains the optional parameters for the MultiPartFormDataClient.FileArrayAndBasic +// method. +type MultiPartFormDataClientFileArrayAndBasicOptions struct { + // placeholder for future optional parameters +} + +// MultiPartFormDataClientJSONPartOptions contains the optional parameters for the MultiPartFormDataClient.JSONPart method. +type MultiPartFormDataClientJSONPartOptions struct { + // placeholder for future optional parameters +} + +// MultiPartFormDataClientMultiBinaryPartsOptions contains the optional parameters for the MultiPartFormDataClient.MultiBinaryParts +// method. +type MultiPartFormDataClientMultiBinaryPartsOptions struct { + // placeholder for future optional parameters +} + +// MultiPartFormDataClientOptionalPartsOptions contains the optional parameters for the MultiPartFormDataClient.OptionalParts +// method. +type MultiPartFormDataClientOptionalPartsOptions struct { + // placeholder for future optional parameters +} + +// MultiPartFormDataClientWithWireNameOptions contains the optional parameters for the MultiPartFormDataClient.WithWireName +// method. +type MultiPartFormDataClientWithWireNameOptions struct { + // placeholder for future optional parameters +} + +// MultiPartFormDataFileClientUploadFileArrayOptions contains the optional parameters for the MultiPartFormDataFileClient.UploadFileArray +// method. +type MultiPartFormDataFileClientUploadFileArrayOptions struct { + // placeholder for future optional parameters +} + +// MultiPartFormDataFileClientUploadFileRequiredFilenameOptions contains the optional parameters for the MultiPartFormDataFileClient.UploadFileRequiredFilename +// method. +type MultiPartFormDataFileClientUploadFileRequiredFilenameOptions struct { + // placeholder for future optional parameters +} + +// MultiPartFormDataFileClientUploadFileSpecificContentTypeOptions contains the optional parameters for the MultiPartFormDataFileClient.UploadFileSpecificContentType +// method. +type MultiPartFormDataFileClientUploadFileSpecificContentTypeOptions struct { + // placeholder for future optional parameters +} + +// MultiPartFormDataHTTPPartsClientJSONArrayAndFileArrayOptions contains the optional parameters for the MultiPartFormDataHTTPPartsClient.JSONArrayAndFileArray +// method. +type MultiPartFormDataHTTPPartsClientJSONArrayAndFileArrayOptions struct { + // placeholder for future optional parameters +} + +// MultiPartFormDataHTTPPartsContentTypeClientImageJPEGContentTypeOptions contains the optional parameters for the MultiPartFormDataHTTPPartsContentTypeClient.ImageJPEGContentType +// method. +type MultiPartFormDataHTTPPartsContentTypeClientImageJPEGContentTypeOptions struct { + // placeholder for future optional parameters +} + +// MultiPartFormDataHTTPPartsContentTypeClientOptionalContentTypeOptions contains the optional parameters for the MultiPartFormDataHTTPPartsContentTypeClient.OptionalContentType +// method. +type MultiPartFormDataHTTPPartsContentTypeClientOptionalContentTypeOptions struct { + // placeholder for future optional parameters +} + +// MultiPartFormDataHTTPPartsContentTypeClientRequiredContentTypeOptions contains the optional parameters for the MultiPartFormDataHTTPPartsContentTypeClient.RequiredContentType +// method. +type MultiPartFormDataHTTPPartsContentTypeClientRequiredContentTypeOptions struct { + // placeholder for future optional parameters +} + +// MultiPartFormDataHTTPPartsNonStringClientFloatOptions contains the optional parameters for the MultiPartFormDataHTTPPartsNonStringClient.Float +// method. +type MultiPartFormDataHTTPPartsNonStringClientFloatOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/payload/multipartgroup/zz_responses.go b/test/http-specs/payload/multipartgroup/zz_responses.go new file mode 100644 index 000000000000..b70f92fd3302 --- /dev/null +++ b/test/http-specs/payload/multipartgroup/zz_responses.go @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multipartgroup + +// MultiPartFormDataClientAnonymousModelResponse contains the response from method MultiPartFormDataClient.AnonymousModel. +type MultiPartFormDataClientAnonymousModelResponse struct { + // placeholder for future response values +} + +// MultiPartFormDataClientBasicResponse contains the response from method MultiPartFormDataClient.Basic. +type MultiPartFormDataClientBasicResponse struct { + // placeholder for future response values +} + +// MultiPartFormDataClientBinaryArrayPartsResponse contains the response from method MultiPartFormDataClient.BinaryArrayParts. +type MultiPartFormDataClientBinaryArrayPartsResponse struct { + // placeholder for future response values +} + +// MultiPartFormDataClientCheckFileNameAndContentTypeResponse contains the response from method MultiPartFormDataClient.CheckFileNameAndContentType. +type MultiPartFormDataClientCheckFileNameAndContentTypeResponse struct { + // placeholder for future response values +} + +// MultiPartFormDataClientFileArrayAndBasicResponse contains the response from method MultiPartFormDataClient.FileArrayAndBasic. +type MultiPartFormDataClientFileArrayAndBasicResponse struct { + // placeholder for future response values +} + +// MultiPartFormDataClientJSONPartResponse contains the response from method MultiPartFormDataClient.JSONPart. +type MultiPartFormDataClientJSONPartResponse struct { + // placeholder for future response values +} + +// MultiPartFormDataClientMultiBinaryPartsResponse contains the response from method MultiPartFormDataClient.MultiBinaryParts. +type MultiPartFormDataClientMultiBinaryPartsResponse struct { + // placeholder for future response values +} + +// MultiPartFormDataClientOptionalPartsResponse contains the response from method MultiPartFormDataClient.OptionalParts. +type MultiPartFormDataClientOptionalPartsResponse struct { + // placeholder for future response values +} + +// MultiPartFormDataClientWithWireNameResponse contains the response from method MultiPartFormDataClient.WithWireName. +type MultiPartFormDataClientWithWireNameResponse struct { + // placeholder for future response values +} + +// MultiPartFormDataFileClientUploadFileArrayResponse contains the response from method MultiPartFormDataFileClient.UploadFileArray. +type MultiPartFormDataFileClientUploadFileArrayResponse struct { + // placeholder for future response values +} + +// MultiPartFormDataFileClientUploadFileRequiredFilenameResponse contains the response from method MultiPartFormDataFileClient.UploadFileRequiredFilename. +type MultiPartFormDataFileClientUploadFileRequiredFilenameResponse struct { + // placeholder for future response values +} + +// MultiPartFormDataFileClientUploadFileSpecificContentTypeResponse contains the response from method MultiPartFormDataFileClient.UploadFileSpecificContentType. +type MultiPartFormDataFileClientUploadFileSpecificContentTypeResponse struct { + // placeholder for future response values +} + +// MultiPartFormDataHTTPPartsClientJSONArrayAndFileArrayResponse contains the response from method MultiPartFormDataHTTPPartsClient.JSONArrayAndFileArray. +type MultiPartFormDataHTTPPartsClientJSONArrayAndFileArrayResponse struct { + // placeholder for future response values +} + +// MultiPartFormDataHTTPPartsContentTypeClientImageJPEGContentTypeResponse contains the response from method MultiPartFormDataHTTPPartsContentTypeClient.ImageJPEGContentType. +type MultiPartFormDataHTTPPartsContentTypeClientImageJPEGContentTypeResponse struct { + // placeholder for future response values +} + +// MultiPartFormDataHTTPPartsContentTypeClientOptionalContentTypeResponse contains the response from method MultiPartFormDataHTTPPartsContentTypeClient.OptionalContentType. +type MultiPartFormDataHTTPPartsContentTypeClientOptionalContentTypeResponse struct { + // placeholder for future response values +} + +// MultiPartFormDataHTTPPartsContentTypeClientRequiredContentTypeResponse contains the response from method MultiPartFormDataHTTPPartsContentTypeClient.RequiredContentType. +type MultiPartFormDataHTTPPartsContentTypeClientRequiredContentTypeResponse struct { + // placeholder for future response values +} + +// MultiPartFormDataHTTPPartsNonStringClientFloatResponse contains the response from method MultiPartFormDataHTTPPartsNonStringClient.Float. +type MultiPartFormDataHTTPPartsNonStringClientFloatResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/payload/multipartgroup/zz_version.go b/test/http-specs/payload/multipartgroup/zz_version.go new file mode 100644 index 000000000000..8b44c1dcd283 --- /dev/null +++ b/test/http-specs/payload/multipartgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package multipartgroup + +const ( + moduleName = "multipartgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/payload/pageablegroup/LICENSE.txt b/test/http-specs/payload/pageablegroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/payload/pageablegroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/payload/pageablegroup/fake/zz_internal.go b/test/http-specs/payload/pageablegroup/fake/zz_internal.go new file mode 100644 index 000000000000..1bd30c238b33 --- /dev/null +++ b/test/http-specs/payload/pageablegroup/fake/zz_internal.go @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "reflect" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getHeaderValue(h http.Header, k string) string { + v := h[k] + if len(v) == 0 { + return "" + } + return v[0] +} + +func getOptional[T any](v T) *T { + if reflect.ValueOf(v).IsZero() { + return nil + } + return &v +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func parseOptional[T any](v string, parse func(v string) (T, error)) (*T, error) { + if v == "" { + return nil, nil + } + t, err := parse(v) + if err != nil { + return nil, err + } + return &t, nil +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/http-specs/payload/pageablegroup/fake/zz_pageable_server.go b/test/http-specs/payload/pageablegroup/fake/zz_pageable_server.go new file mode 100644 index 000000000000..ea399a086534 --- /dev/null +++ b/test/http-specs/payload/pageablegroup/fake/zz_pageable_server.go @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// PageableServer is a fake server for instances of the pageablegroup.PageableClient type. +type PageableServer struct { + // PageablePageSizeServer contains the fakes for client PageablePageSizeClient + PageablePageSizeServer PageablePageSizeServer + + // PageableServerDrivenPaginationServer contains the fakes for client PageableServerDrivenPaginationClient + PageableServerDrivenPaginationServer PageableServerDrivenPaginationServer + + // PageableXMLPaginationServer contains the fakes for client PageableXMLPaginationClient + PageableXMLPaginationServer PageableXMLPaginationServer +} + +// NewPageableServerTransport creates a new instance of PageableServerTransport with the provided implementation. +// The returned PageableServerTransport instance is connected to an instance of pageablegroup.PageableClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewPageableServerTransport(srv *PageableServer) *PageableServerTransport { + return &PageableServerTransport{srv: srv} +} + +// PageableServerTransport connects instances of pageablegroup.PageableClient to instances of PageableServer. +// Don't use this type directly, use NewPageableServerTransport instead. +type PageableServerTransport struct { + srv *PageableServer + trMu sync.Mutex + trPageablePageSizeServer *PageablePageSizeServerTransport + trPageableServerDrivenPaginationServer *PageableServerDrivenPaginationServerTransport + trPageableXMLPaginationServer *PageableXMLPaginationServerTransport +} + +// Do implements the policy.Transporter interface for PageableServerTransport. +func (p *PageableServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return p.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (p *PageableServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "PageablePageSizeClient": + initServer(&p.trMu, &p.trPageablePageSizeServer, func() *PageablePageSizeServerTransport { + return NewPageablePageSizeServerTransport(&p.srv.PageablePageSizeServer) + }) + resp, err = p.trPageablePageSizeServer.Do(req) + case "PageableServerDrivenPaginationClient", "PageableServerDrivenPaginationAlternateInitialVerbClient", "PageableServerDrivenPaginationContinuationTokenClient": + initServer(&p.trMu, &p.trPageableServerDrivenPaginationServer, func() *PageableServerDrivenPaginationServerTransport { + return NewPageableServerDrivenPaginationServerTransport(&p.srv.PageableServerDrivenPaginationServer) + }) + resp, err = p.trPageableServerDrivenPaginationServer.Do(req) + case "PageableXMLPaginationClient": + initServer(&p.trMu, &p.trPageableXMLPaginationServer, func() *PageableXMLPaginationServerTransport { + return NewPageableXMLPaginationServerTransport(&p.srv.PageableXMLPaginationServer) + }) + resp, err = p.trPageableXMLPaginationServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to PageableServerTransport +var pageableServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/pageablegroup/fake/zz_pageablepagesize_server.go b/test/http-specs/payload/pageablegroup/fake/zz_pageablepagesize_server.go new file mode 100644 index 000000000000..1798b4cd248b --- /dev/null +++ b/test/http-specs/payload/pageablegroup/fake/zz_pageablepagesize_server.go @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "pageablegroup" + "slices" + "strconv" +) + +// PageablePageSizeServer is a fake server for instances of the pageablegroup.PageablePageSizeClient type. +type PageablePageSizeServer struct { + // NewListWithPageSizePager is the fake for method PageablePageSizeClient.NewListWithPageSizePager + // HTTP status codes to indicate success: http.StatusOK + NewListWithPageSizePager func(options *pageablegroup.PageablePageSizeClientListWithPageSizeOptions) (resp azfake.PagerResponder[pageablegroup.PageablePageSizeClientListWithPageSizeResponse]) + + // NewListWithoutContinuationPager is the fake for method PageablePageSizeClient.NewListWithoutContinuationPager + // HTTP status codes to indicate success: http.StatusOK + NewListWithoutContinuationPager func(options *pageablegroup.PageablePageSizeClientListWithoutContinuationOptions) (resp azfake.PagerResponder[pageablegroup.PageablePageSizeClientListWithoutContinuationResponse]) +} + +// NewPageablePageSizeServerTransport creates a new instance of PageablePageSizeServerTransport with the provided implementation. +// The returned PageablePageSizeServerTransport instance is connected to an instance of pageablegroup.PageablePageSizeClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewPageablePageSizeServerTransport(srv *PageablePageSizeServer) *PageablePageSizeServerTransport { + return &PageablePageSizeServerTransport{ + srv: srv, + newListWithPageSizePager: newTracker[azfake.PagerResponder[pageablegroup.PageablePageSizeClientListWithPageSizeResponse]](), + newListWithoutContinuationPager: newTracker[azfake.PagerResponder[pageablegroup.PageablePageSizeClientListWithoutContinuationResponse]](), + } +} + +// PageablePageSizeServerTransport connects instances of pageablegroup.PageablePageSizeClient to instances of PageablePageSizeServer. +// Don't use this type directly, use NewPageablePageSizeServerTransport instead. +type PageablePageSizeServerTransport struct { + srv *PageablePageSizeServer + newListWithPageSizePager *tracker[azfake.PagerResponder[pageablegroup.PageablePageSizeClientListWithPageSizeResponse]] + newListWithoutContinuationPager *tracker[azfake.PagerResponder[pageablegroup.PageablePageSizeClientListWithoutContinuationResponse]] +} + +// Do implements the policy.Transporter interface for PageablePageSizeServerTransport. +func (p *PageablePageSizeServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return p.dispatchToMethodFake(req, method) +} + +func (p *PageablePageSizeServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if pageablePageSizeServerTransportInterceptor != nil { + res.resp, res.err, intercepted = pageablePageSizeServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "PageablePageSizeClient.NewListWithPageSizePager": + res.resp, res.err = p.dispatchNewListWithPageSizePager(req) + case "PageablePageSizeClient.NewListWithoutContinuationPager": + res.resp, res.err = p.dispatchNewListWithoutContinuationPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (p *PageablePageSizeServerTransport) dispatchNewListWithPageSizePager(req *http.Request) (*http.Response, error) { + if p.srv.NewListWithPageSizePager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListWithPageSizePager not implemented")} + } + newListWithPageSizePager := p.newListWithPageSizePager.get(req) + if newListWithPageSizePager == nil { + qp := req.URL.Query() + pageSizeParam, err := parseOptional(qp.Get("pageSize"), func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + var options *pageablegroup.PageablePageSizeClientListWithPageSizeOptions + if pageSizeParam != nil { + options = &pageablegroup.PageablePageSizeClientListWithPageSizeOptions{ + PageSize: pageSizeParam, + } + } + resp := p.srv.NewListWithPageSizePager(options) + newListWithPageSizePager = &resp + p.newListWithPageSizePager.add(req, newListWithPageSizePager) + } + resp, err := server.PagerResponderNext(newListWithPageSizePager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newListWithPageSizePager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListWithPageSizePager) { + p.newListWithPageSizePager.remove(req) + } + return resp, nil +} + +func (p *PageablePageSizeServerTransport) dispatchNewListWithoutContinuationPager(req *http.Request) (*http.Response, error) { + if p.srv.NewListWithoutContinuationPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListWithoutContinuationPager not implemented")} + } + newListWithoutContinuationPager := p.newListWithoutContinuationPager.get(req) + if newListWithoutContinuationPager == nil { + resp := p.srv.NewListWithoutContinuationPager(nil) + newListWithoutContinuationPager = &resp + p.newListWithoutContinuationPager.add(req, newListWithoutContinuationPager) + } + resp, err := server.PagerResponderNext(newListWithoutContinuationPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newListWithoutContinuationPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListWithoutContinuationPager) { + p.newListWithoutContinuationPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to PageablePageSizeServerTransport +var pageablePageSizeServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/pageablegroup/fake/zz_pageableserverdrivenpagination_server.go b/test/http-specs/payload/pageablegroup/fake/zz_pageableserverdrivenpagination_server.go new file mode 100644 index 000000000000..c35d760e47e3 --- /dev/null +++ b/test/http-specs/payload/pageablegroup/fake/zz_pageableserverdrivenpagination_server.go @@ -0,0 +1,219 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "pageablegroup" + "slices" + "strings" + "sync" +) + +// PageableServerDrivenPaginationServer is a fake server for instances of the pageablegroup.PageableServerDrivenPaginationClient type. +type PageableServerDrivenPaginationServer struct { + // PageableServerDrivenPaginationAlternateInitialVerbServer contains the fakes for client PageableServerDrivenPaginationAlternateInitialVerbClient + PageableServerDrivenPaginationAlternateInitialVerbServer PageableServerDrivenPaginationAlternateInitialVerbServer + + // PageableServerDrivenPaginationContinuationTokenServer contains the fakes for client PageableServerDrivenPaginationContinuationTokenClient + PageableServerDrivenPaginationContinuationTokenServer PageableServerDrivenPaginationContinuationTokenServer + + // NewLinkPager is the fake for method PageableServerDrivenPaginationClient.NewLinkPager + // HTTP status codes to indicate success: http.StatusOK + NewLinkPager func(options *pageablegroup.PageableServerDrivenPaginationClientLinkOptions) (resp azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationClientLinkResponse]) + + // NewLinkStringPager is the fake for method PageableServerDrivenPaginationClient.NewLinkStringPager + // HTTP status codes to indicate success: http.StatusOK + NewLinkStringPager func(options *pageablegroup.PageableServerDrivenPaginationClientLinkStringOptions) (resp azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationClientLinkStringResponse]) + + // NewNestedLinkPager is the fake for method PageableServerDrivenPaginationClient.NewNestedLinkPager + // HTTP status codes to indicate success: http.StatusOK + NewNestedLinkPager func(options *pageablegroup.PageableServerDrivenPaginationClientNestedLinkOptions) (resp azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationClientNestedLinkResponse]) +} + +// NewPageableServerDrivenPaginationServerTransport creates a new instance of PageableServerDrivenPaginationServerTransport with the provided implementation. +// The returned PageableServerDrivenPaginationServerTransport instance is connected to an instance of pageablegroup.PageableServerDrivenPaginationClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewPageableServerDrivenPaginationServerTransport(srv *PageableServerDrivenPaginationServer) *PageableServerDrivenPaginationServerTransport { + return &PageableServerDrivenPaginationServerTransport{ + srv: srv, + newLinkPager: newTracker[azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationClientLinkResponse]](), + newLinkStringPager: newTracker[azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationClientLinkStringResponse]](), + newNestedLinkPager: newTracker[azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationClientNestedLinkResponse]](), + } +} + +// PageableServerDrivenPaginationServerTransport connects instances of pageablegroup.PageableServerDrivenPaginationClient to instances of PageableServerDrivenPaginationServer. +// Don't use this type directly, use NewPageableServerDrivenPaginationServerTransport instead. +type PageableServerDrivenPaginationServerTransport struct { + srv *PageableServerDrivenPaginationServer + trMu sync.Mutex + trPageableServerDrivenPaginationAlternateInitialVerbServer *PageableServerDrivenPaginationAlternateInitialVerbServerTransport + trPageableServerDrivenPaginationContinuationTokenServer *PageableServerDrivenPaginationContinuationTokenServerTransport + newLinkPager *tracker[azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationClientLinkResponse]] + newLinkStringPager *tracker[azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationClientLinkStringResponse]] + newNestedLinkPager *tracker[azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationClientNestedLinkResponse]] +} + +// Do implements the policy.Transporter interface for PageableServerDrivenPaginationServerTransport. +func (p *PageableServerDrivenPaginationServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + if client := method[:strings.Index(method, ".")]; client != "PageableServerDrivenPaginationClient" { + return p.dispatchToClientFake(req, client) + } + return p.dispatchToMethodFake(req, method) +} + +func (p *PageableServerDrivenPaginationServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "PageableServerDrivenPaginationAlternateInitialVerbClient": + initServer(&p.trMu, &p.trPageableServerDrivenPaginationAlternateInitialVerbServer, func() *PageableServerDrivenPaginationAlternateInitialVerbServerTransport { + return NewPageableServerDrivenPaginationAlternateInitialVerbServerTransport(&p.srv.PageableServerDrivenPaginationAlternateInitialVerbServer) + }) + resp, err = p.trPageableServerDrivenPaginationAlternateInitialVerbServer.Do(req) + case "PageableServerDrivenPaginationContinuationTokenClient": + initServer(&p.trMu, &p.trPageableServerDrivenPaginationContinuationTokenServer, func() *PageableServerDrivenPaginationContinuationTokenServerTransport { + return NewPageableServerDrivenPaginationContinuationTokenServerTransport(&p.srv.PageableServerDrivenPaginationContinuationTokenServer) + }) + resp, err = p.trPageableServerDrivenPaginationContinuationTokenServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +func (p *PageableServerDrivenPaginationServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if pageableServerDrivenPaginationServerTransportInterceptor != nil { + res.resp, res.err, intercepted = pageableServerDrivenPaginationServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "PageableServerDrivenPaginationClient.NewLinkPager": + res.resp, res.err = p.dispatchNewLinkPager(req) + case "PageableServerDrivenPaginationClient.NewLinkStringPager": + res.resp, res.err = p.dispatchNewLinkStringPager(req) + case "PageableServerDrivenPaginationClient.NewNestedLinkPager": + res.resp, res.err = p.dispatchNewNestedLinkPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (p *PageableServerDrivenPaginationServerTransport) dispatchNewLinkPager(req *http.Request) (*http.Response, error) { + if p.srv.NewLinkPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewLinkPager not implemented")} + } + newLinkPager := p.newLinkPager.get(req) + if newLinkPager == nil { + resp := p.srv.NewLinkPager(nil) + newLinkPager = &resp + p.newLinkPager.add(req, newLinkPager) + server.PagerResponderInjectNextLinks(newLinkPager, req, func(page *pageablegroup.PageableServerDrivenPaginationClientLinkResponse, createLink func() string) { + page.Next = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newLinkPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newLinkPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newLinkPager) { + p.newLinkPager.remove(req) + } + return resp, nil +} + +func (p *PageableServerDrivenPaginationServerTransport) dispatchNewLinkStringPager(req *http.Request) (*http.Response, error) { + if p.srv.NewLinkStringPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewLinkStringPager not implemented")} + } + newLinkStringPager := p.newLinkStringPager.get(req) + if newLinkStringPager == nil { + resp := p.srv.NewLinkStringPager(nil) + newLinkStringPager = &resp + p.newLinkStringPager.add(req, newLinkStringPager) + server.PagerResponderInjectNextLinks(newLinkStringPager, req, func(page *pageablegroup.PageableServerDrivenPaginationClientLinkStringResponse, createLink func() string) { + page.Next = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newLinkStringPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newLinkStringPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newLinkStringPager) { + p.newLinkStringPager.remove(req) + } + return resp, nil +} + +func (p *PageableServerDrivenPaginationServerTransport) dispatchNewNestedLinkPager(req *http.Request) (*http.Response, error) { + if p.srv.NewNestedLinkPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewNestedLinkPager not implemented")} + } + newNestedLinkPager := p.newNestedLinkPager.get(req) + if newNestedLinkPager == nil { + resp := p.srv.NewNestedLinkPager(nil) + newNestedLinkPager = &resp + p.newNestedLinkPager.add(req, newNestedLinkPager) + server.PagerResponderInjectNextLinks(newNestedLinkPager, req, func(page *pageablegroup.PageableServerDrivenPaginationClientNestedLinkResponse, createLink func() string) { + page.NestedNext.Next = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newNestedLinkPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newNestedLinkPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newNestedLinkPager) { + p.newNestedLinkPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to PageableServerDrivenPaginationServerTransport +var pageableServerDrivenPaginationServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/pageablegroup/fake/zz_pageableserverdrivenpaginationalternateinitialverb_server.go b/test/http-specs/payload/pageablegroup/fake/zz_pageableserverdrivenpaginationalternateinitialverb_server.go new file mode 100644 index 000000000000..64d05030e91b --- /dev/null +++ b/test/http-specs/payload/pageablegroup/fake/zz_pageableserverdrivenpaginationalternateinitialverb_server.go @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "pageablegroup" + "slices" +) + +// PageableServerDrivenPaginationAlternateInitialVerbServer is a fake server for instances of the pageablegroup.PageableServerDrivenPaginationAlternateInitialVerbClient type. +type PageableServerDrivenPaginationAlternateInitialVerbServer struct { + // NewPostPager is the fake for method PageableServerDrivenPaginationAlternateInitialVerbClient.NewPostPager + // HTTP status codes to indicate success: http.StatusOK + NewPostPager func(body pageablegroup.Filter, options *pageablegroup.PageableServerDrivenPaginationAlternateInitialVerbClientPostOptions) (resp azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationAlternateInitialVerbClientPostResponse]) +} + +// NewPageableServerDrivenPaginationAlternateInitialVerbServerTransport creates a new instance of PageableServerDrivenPaginationAlternateInitialVerbServerTransport with the provided implementation. +// The returned PageableServerDrivenPaginationAlternateInitialVerbServerTransport instance is connected to an instance of pageablegroup.PageableServerDrivenPaginationAlternateInitialVerbClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewPageableServerDrivenPaginationAlternateInitialVerbServerTransport(srv *PageableServerDrivenPaginationAlternateInitialVerbServer) *PageableServerDrivenPaginationAlternateInitialVerbServerTransport { + return &PageableServerDrivenPaginationAlternateInitialVerbServerTransport{ + srv: srv, + newPostPager: newTracker[azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationAlternateInitialVerbClientPostResponse]](), + } +} + +// PageableServerDrivenPaginationAlternateInitialVerbServerTransport connects instances of pageablegroup.PageableServerDrivenPaginationAlternateInitialVerbClient to instances of PageableServerDrivenPaginationAlternateInitialVerbServer. +// Don't use this type directly, use NewPageableServerDrivenPaginationAlternateInitialVerbServerTransport instead. +type PageableServerDrivenPaginationAlternateInitialVerbServerTransport struct { + srv *PageableServerDrivenPaginationAlternateInitialVerbServer + newPostPager *tracker[azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationAlternateInitialVerbClientPostResponse]] +} + +// Do implements the policy.Transporter interface for PageableServerDrivenPaginationAlternateInitialVerbServerTransport. +func (p *PageableServerDrivenPaginationAlternateInitialVerbServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return p.dispatchToMethodFake(req, method) +} + +func (p *PageableServerDrivenPaginationAlternateInitialVerbServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if pageableServerDrivenPaginationAlternateInitialVerbServerTransportInterceptor != nil { + res.resp, res.err, intercepted = pageableServerDrivenPaginationAlternateInitialVerbServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "PageableServerDrivenPaginationAlternateInitialVerbClient.NewPostPager": + res.resp, res.err = p.dispatchNewPostPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (p *PageableServerDrivenPaginationAlternateInitialVerbServerTransport) dispatchNewPostPager(req *http.Request) (*http.Response, error) { + if p.srv.NewPostPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewPostPager not implemented")} + } + newPostPager := p.newPostPager.get(req) + if newPostPager == nil { + body, err := server.UnmarshalRequestAsJSON[pageablegroup.Filter](req) + if err != nil { + return nil, err + } + resp := p.srv.NewPostPager(body, nil) + newPostPager = &resp + p.newPostPager.add(req, newPostPager) + server.PagerResponderInjectNextLinks(newPostPager, req, func(page *pageablegroup.PageableServerDrivenPaginationAlternateInitialVerbClientPostResponse, createLink func() string) { + page.Next = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newPostPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newPostPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newPostPager) { + p.newPostPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to PageableServerDrivenPaginationAlternateInitialVerbServerTransport +var pageableServerDrivenPaginationAlternateInitialVerbServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/pageablegroup/fake/zz_pageableserverdrivenpaginationcontinuationtoken_server.go b/test/http-specs/payload/pageablegroup/fake/zz_pageableserverdrivenpaginationcontinuationtoken_server.go new file mode 100644 index 000000000000..90b3370ab970 --- /dev/null +++ b/test/http-specs/payload/pageablegroup/fake/zz_pageableserverdrivenpaginationcontinuationtoken_server.go @@ -0,0 +1,341 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "pageablegroup" + "slices" +) + +// PageableServerDrivenPaginationContinuationTokenServer is a fake server for instances of the pageablegroup.PageableServerDrivenPaginationContinuationTokenClient type. +type PageableServerDrivenPaginationContinuationTokenServer struct { + // NewRequestHeaderNestedResponseBodyPager is the fake for method PageableServerDrivenPaginationContinuationTokenClient.NewRequestHeaderNestedResponseBodyPager + // HTTP status codes to indicate success: http.StatusOK + NewRequestHeaderNestedResponseBodyPager func(options *pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyOptions) (resp azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyResponse]) + + // NewRequestHeaderResponseBodyPager is the fake for method PageableServerDrivenPaginationContinuationTokenClient.NewRequestHeaderResponseBodyPager + // HTTP status codes to indicate success: http.StatusOK + NewRequestHeaderResponseBodyPager func(options *pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseBodyOptions) (resp azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseBodyResponse]) + + // NewRequestHeaderResponseHeaderPager is the fake for method PageableServerDrivenPaginationContinuationTokenClient.NewRequestHeaderResponseHeaderPager + // HTTP status codes to indicate success: http.StatusOK + NewRequestHeaderResponseHeaderPager func(options *pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseHeaderOptions) (resp azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseHeaderResponse]) + + // NewRequestQueryNestedResponseBodyPager is the fake for method PageableServerDrivenPaginationContinuationTokenClient.NewRequestQueryNestedResponseBodyPager + // HTTP status codes to indicate success: http.StatusOK + NewRequestQueryNestedResponseBodyPager func(options *pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestQueryNestedResponseBodyOptions) (resp azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestQueryNestedResponseBodyResponse]) + + // NewRequestQueryResponseBodyPager is the fake for method PageableServerDrivenPaginationContinuationTokenClient.NewRequestQueryResponseBodyPager + // HTTP status codes to indicate success: http.StatusOK + NewRequestQueryResponseBodyPager func(options *pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseBodyOptions) (resp azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseBodyResponse]) + + // NewRequestQueryResponseHeaderPager is the fake for method PageableServerDrivenPaginationContinuationTokenClient.NewRequestQueryResponseHeaderPager + // HTTP status codes to indicate success: http.StatusOK + NewRequestQueryResponseHeaderPager func(options *pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseHeaderOptions) (resp azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseHeaderResponse]) +} + +// NewPageableServerDrivenPaginationContinuationTokenServerTransport creates a new instance of PageableServerDrivenPaginationContinuationTokenServerTransport with the provided implementation. +// The returned PageableServerDrivenPaginationContinuationTokenServerTransport instance is connected to an instance of pageablegroup.PageableServerDrivenPaginationContinuationTokenClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewPageableServerDrivenPaginationContinuationTokenServerTransport(srv *PageableServerDrivenPaginationContinuationTokenServer) *PageableServerDrivenPaginationContinuationTokenServerTransport { + return &PageableServerDrivenPaginationContinuationTokenServerTransport{ + srv: srv, + newRequestHeaderNestedResponseBodyPager: newTracker[azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyResponse]](), + newRequestHeaderResponseBodyPager: newTracker[azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseBodyResponse]](), + newRequestHeaderResponseHeaderPager: newTracker[azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseHeaderResponse]](), + newRequestQueryNestedResponseBodyPager: newTracker[azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestQueryNestedResponseBodyResponse]](), + newRequestQueryResponseBodyPager: newTracker[azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseBodyResponse]](), + newRequestQueryResponseHeaderPager: newTracker[azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseHeaderResponse]](), + } +} + +// PageableServerDrivenPaginationContinuationTokenServerTransport connects instances of pageablegroup.PageableServerDrivenPaginationContinuationTokenClient to instances of PageableServerDrivenPaginationContinuationTokenServer. +// Don't use this type directly, use NewPageableServerDrivenPaginationContinuationTokenServerTransport instead. +type PageableServerDrivenPaginationContinuationTokenServerTransport struct { + srv *PageableServerDrivenPaginationContinuationTokenServer + newRequestHeaderNestedResponseBodyPager *tracker[azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyResponse]] + newRequestHeaderResponseBodyPager *tracker[azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseBodyResponse]] + newRequestHeaderResponseHeaderPager *tracker[azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseHeaderResponse]] + newRequestQueryNestedResponseBodyPager *tracker[azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestQueryNestedResponseBodyResponse]] + newRequestQueryResponseBodyPager *tracker[azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseBodyResponse]] + newRequestQueryResponseHeaderPager *tracker[azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseHeaderResponse]] +} + +// Do implements the policy.Transporter interface for PageableServerDrivenPaginationContinuationTokenServerTransport. +func (p *PageableServerDrivenPaginationContinuationTokenServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return p.dispatchToMethodFake(req, method) +} + +func (p *PageableServerDrivenPaginationContinuationTokenServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if pageableServerDrivenPaginationContinuationTokenServerTransportInterceptor != nil { + res.resp, res.err, intercepted = pageableServerDrivenPaginationContinuationTokenServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "PageableServerDrivenPaginationContinuationTokenClient.NewRequestHeaderNestedResponseBodyPager": + res.resp, res.err = p.dispatchNewRequestHeaderNestedResponseBodyPager(req) + case "PageableServerDrivenPaginationContinuationTokenClient.NewRequestHeaderResponseBodyPager": + res.resp, res.err = p.dispatchNewRequestHeaderResponseBodyPager(req) + case "PageableServerDrivenPaginationContinuationTokenClient.NewRequestHeaderResponseHeaderPager": + res.resp, res.err = p.dispatchNewRequestHeaderResponseHeaderPager(req) + case "PageableServerDrivenPaginationContinuationTokenClient.NewRequestQueryNestedResponseBodyPager": + res.resp, res.err = p.dispatchNewRequestQueryNestedResponseBodyPager(req) + case "PageableServerDrivenPaginationContinuationTokenClient.NewRequestQueryResponseBodyPager": + res.resp, res.err = p.dispatchNewRequestQueryResponseBodyPager(req) + case "PageableServerDrivenPaginationContinuationTokenClient.NewRequestQueryResponseHeaderPager": + res.resp, res.err = p.dispatchNewRequestQueryResponseHeaderPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (p *PageableServerDrivenPaginationContinuationTokenServerTransport) dispatchNewRequestHeaderNestedResponseBodyPager(req *http.Request) (*http.Response, error) { + if p.srv.NewRequestHeaderNestedResponseBodyPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewRequestHeaderNestedResponseBodyPager not implemented")} + } + newRequestHeaderNestedResponseBodyPager := p.newRequestHeaderNestedResponseBodyPager.get(req) + if newRequestHeaderNestedResponseBodyPager == nil { + qp := req.URL.Query() + tokenParam := getOptional(getHeaderValue(req.Header, "token")) + fooParam := getOptional(getHeaderValue(req.Header, "foo")) + barParam := getOptional(qp.Get("bar")) + var options *pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyOptions + if tokenParam != nil || fooParam != nil || barParam != nil { + options = &pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyOptions{ + Token: tokenParam, + Foo: fooParam, + Bar: barParam, + } + } + resp := p.srv.NewRequestHeaderNestedResponseBodyPager(options) + newRequestHeaderNestedResponseBodyPager = &resp + p.newRequestHeaderNestedResponseBodyPager.add(req, newRequestHeaderNestedResponseBodyPager) + } + resp, err := server.PagerResponderNext(newRequestHeaderNestedResponseBodyPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newRequestHeaderNestedResponseBodyPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newRequestHeaderNestedResponseBodyPager) { + p.newRequestHeaderNestedResponseBodyPager.remove(req) + } + return resp, nil +} + +func (p *PageableServerDrivenPaginationContinuationTokenServerTransport) dispatchNewRequestHeaderResponseBodyPager(req *http.Request) (*http.Response, error) { + if p.srv.NewRequestHeaderResponseBodyPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewRequestHeaderResponseBodyPager not implemented")} + } + newRequestHeaderResponseBodyPager := p.newRequestHeaderResponseBodyPager.get(req) + if newRequestHeaderResponseBodyPager == nil { + qp := req.URL.Query() + tokenParam := getOptional(getHeaderValue(req.Header, "token")) + fooParam := getOptional(getHeaderValue(req.Header, "foo")) + barParam := getOptional(qp.Get("bar")) + var options *pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseBodyOptions + if tokenParam != nil || fooParam != nil || barParam != nil { + options = &pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseBodyOptions{ + Token: tokenParam, + Foo: fooParam, + Bar: barParam, + } + } + resp := p.srv.NewRequestHeaderResponseBodyPager(options) + newRequestHeaderResponseBodyPager = &resp + p.newRequestHeaderResponseBodyPager.add(req, newRequestHeaderResponseBodyPager) + } + resp, err := server.PagerResponderNext(newRequestHeaderResponseBodyPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newRequestHeaderResponseBodyPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newRequestHeaderResponseBodyPager) { + p.newRequestHeaderResponseBodyPager.remove(req) + } + return resp, nil +} + +func (p *PageableServerDrivenPaginationContinuationTokenServerTransport) dispatchNewRequestHeaderResponseHeaderPager(req *http.Request) (*http.Response, error) { + if p.srv.NewRequestHeaderResponseHeaderPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewRequestHeaderResponseHeaderPager not implemented")} + } + newRequestHeaderResponseHeaderPager := p.newRequestHeaderResponseHeaderPager.get(req) + if newRequestHeaderResponseHeaderPager == nil { + qp := req.URL.Query() + tokenParam := getOptional(getHeaderValue(req.Header, "token")) + fooParam := getOptional(getHeaderValue(req.Header, "foo")) + barParam := getOptional(qp.Get("bar")) + var options *pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseHeaderOptions + if tokenParam != nil || fooParam != nil || barParam != nil { + options = &pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseHeaderOptions{ + Token: tokenParam, + Foo: fooParam, + Bar: barParam, + } + } + resp := p.srv.NewRequestHeaderResponseHeaderPager(options) + newRequestHeaderResponseHeaderPager = &resp + p.newRequestHeaderResponseHeaderPager.add(req, newRequestHeaderResponseHeaderPager) + } + resp, err := server.PagerResponderNext(newRequestHeaderResponseHeaderPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newRequestHeaderResponseHeaderPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newRequestHeaderResponseHeaderPager) { + p.newRequestHeaderResponseHeaderPager.remove(req) + } + return resp, nil +} + +func (p *PageableServerDrivenPaginationContinuationTokenServerTransport) dispatchNewRequestQueryNestedResponseBodyPager(req *http.Request) (*http.Response, error) { + if p.srv.NewRequestQueryNestedResponseBodyPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewRequestQueryNestedResponseBodyPager not implemented")} + } + newRequestQueryNestedResponseBodyPager := p.newRequestQueryNestedResponseBodyPager.get(req) + if newRequestQueryNestedResponseBodyPager == nil { + qp := req.URL.Query() + tokenParam := getOptional(qp.Get("token")) + fooParam := getOptional(getHeaderValue(req.Header, "foo")) + barParam := getOptional(qp.Get("bar")) + var options *pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestQueryNestedResponseBodyOptions + if tokenParam != nil || fooParam != nil || barParam != nil { + options = &pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestQueryNestedResponseBodyOptions{ + Token: tokenParam, + Foo: fooParam, + Bar: barParam, + } + } + resp := p.srv.NewRequestQueryNestedResponseBodyPager(options) + newRequestQueryNestedResponseBodyPager = &resp + p.newRequestQueryNestedResponseBodyPager.add(req, newRequestQueryNestedResponseBodyPager) + } + resp, err := server.PagerResponderNext(newRequestQueryNestedResponseBodyPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newRequestQueryNestedResponseBodyPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newRequestQueryNestedResponseBodyPager) { + p.newRequestQueryNestedResponseBodyPager.remove(req) + } + return resp, nil +} + +func (p *PageableServerDrivenPaginationContinuationTokenServerTransport) dispatchNewRequestQueryResponseBodyPager(req *http.Request) (*http.Response, error) { + if p.srv.NewRequestQueryResponseBodyPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewRequestQueryResponseBodyPager not implemented")} + } + newRequestQueryResponseBodyPager := p.newRequestQueryResponseBodyPager.get(req) + if newRequestQueryResponseBodyPager == nil { + qp := req.URL.Query() + tokenParam := getOptional(qp.Get("token")) + fooParam := getOptional(getHeaderValue(req.Header, "foo")) + barParam := getOptional(qp.Get("bar")) + var options *pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseBodyOptions + if tokenParam != nil || fooParam != nil || barParam != nil { + options = &pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseBodyOptions{ + Token: tokenParam, + Foo: fooParam, + Bar: barParam, + } + } + resp := p.srv.NewRequestQueryResponseBodyPager(options) + newRequestQueryResponseBodyPager = &resp + p.newRequestQueryResponseBodyPager.add(req, newRequestQueryResponseBodyPager) + } + resp, err := server.PagerResponderNext(newRequestQueryResponseBodyPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newRequestQueryResponseBodyPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newRequestQueryResponseBodyPager) { + p.newRequestQueryResponseBodyPager.remove(req) + } + return resp, nil +} + +func (p *PageableServerDrivenPaginationContinuationTokenServerTransport) dispatchNewRequestQueryResponseHeaderPager(req *http.Request) (*http.Response, error) { + if p.srv.NewRequestQueryResponseHeaderPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewRequestQueryResponseHeaderPager not implemented")} + } + newRequestQueryResponseHeaderPager := p.newRequestQueryResponseHeaderPager.get(req) + if newRequestQueryResponseHeaderPager == nil { + qp := req.URL.Query() + tokenParam := getOptional(qp.Get("token")) + fooParam := getOptional(getHeaderValue(req.Header, "foo")) + barParam := getOptional(qp.Get("bar")) + var options *pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseHeaderOptions + if tokenParam != nil || fooParam != nil || barParam != nil { + options = &pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseHeaderOptions{ + Token: tokenParam, + Foo: fooParam, + Bar: barParam, + } + } + resp := p.srv.NewRequestQueryResponseHeaderPager(options) + newRequestQueryResponseHeaderPager = &resp + p.newRequestQueryResponseHeaderPager.add(req, newRequestQueryResponseHeaderPager) + } + resp, err := server.PagerResponderNext(newRequestQueryResponseHeaderPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newRequestQueryResponseHeaderPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newRequestQueryResponseHeaderPager) { + p.newRequestQueryResponseHeaderPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to PageableServerDrivenPaginationContinuationTokenServerTransport +var pageableServerDrivenPaginationContinuationTokenServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/pageablegroup/fake/zz_pageablexmlpagination_server.go b/test/http-specs/payload/pageablegroup/fake/zz_pageablexmlpagination_server.go new file mode 100644 index 000000000000..7f5f102e7ddc --- /dev/null +++ b/test/http-specs/payload/pageablegroup/fake/zz_pageablexmlpagination_server.go @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "pageablegroup" + "slices" +) + +// PageableXMLPaginationServer is a fake server for instances of the pageablegroup.PageableXMLPaginationClient type. +type PageableXMLPaginationServer struct { + // NewListWithContinuationPager is the fake for method PageableXMLPaginationClient.NewListWithContinuationPager + // HTTP status codes to indicate success: http.StatusOK + NewListWithContinuationPager func(options *pageablegroup.PageableXMLPaginationClientListWithContinuationOptions) (resp azfake.PagerResponder[pageablegroup.PageableXMLPaginationClientListWithContinuationResponse]) + + // NewListWithNextLinkPager is the fake for method PageableXMLPaginationClient.NewListWithNextLinkPager + // HTTP status codes to indicate success: http.StatusOK + NewListWithNextLinkPager func(options *pageablegroup.PageableXMLPaginationClientListWithNextLinkOptions) (resp azfake.PagerResponder[pageablegroup.PageableXMLPaginationClientListWithNextLinkResponse]) +} + +// NewPageableXMLPaginationServerTransport creates a new instance of PageableXMLPaginationServerTransport with the provided implementation. +// The returned PageableXMLPaginationServerTransport instance is connected to an instance of pageablegroup.PageableXMLPaginationClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewPageableXMLPaginationServerTransport(srv *PageableXMLPaginationServer) *PageableXMLPaginationServerTransport { + return &PageableXMLPaginationServerTransport{ + srv: srv, + newListWithContinuationPager: newTracker[azfake.PagerResponder[pageablegroup.PageableXMLPaginationClientListWithContinuationResponse]](), + newListWithNextLinkPager: newTracker[azfake.PagerResponder[pageablegroup.PageableXMLPaginationClientListWithNextLinkResponse]](), + } +} + +// PageableXMLPaginationServerTransport connects instances of pageablegroup.PageableXMLPaginationClient to instances of PageableXMLPaginationServer. +// Don't use this type directly, use NewPageableXMLPaginationServerTransport instead. +type PageableXMLPaginationServerTransport struct { + srv *PageableXMLPaginationServer + newListWithContinuationPager *tracker[azfake.PagerResponder[pageablegroup.PageableXMLPaginationClientListWithContinuationResponse]] + newListWithNextLinkPager *tracker[azfake.PagerResponder[pageablegroup.PageableXMLPaginationClientListWithNextLinkResponse]] +} + +// Do implements the policy.Transporter interface for PageableXMLPaginationServerTransport. +func (p *PageableXMLPaginationServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return p.dispatchToMethodFake(req, method) +} + +func (p *PageableXMLPaginationServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if pageableXmlPaginationServerTransportInterceptor != nil { + res.resp, res.err, intercepted = pageableXmlPaginationServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "PageableXMLPaginationClient.NewListWithContinuationPager": + res.resp, res.err = p.dispatchNewListWithContinuationPager(req) + case "PageableXMLPaginationClient.NewListWithNextLinkPager": + res.resp, res.err = p.dispatchNewListWithNextLinkPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (p *PageableXMLPaginationServerTransport) dispatchNewListWithContinuationPager(req *http.Request) (*http.Response, error) { + if p.srv.NewListWithContinuationPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListWithContinuationPager not implemented")} + } + newListWithContinuationPager := p.newListWithContinuationPager.get(req) + if newListWithContinuationPager == nil { + qp := req.URL.Query() + markerParam := getOptional(qp.Get("marker")) + var options *pageablegroup.PageableXMLPaginationClientListWithContinuationOptions + if markerParam != nil { + options = &pageablegroup.PageableXMLPaginationClientListWithContinuationOptions{ + Marker: markerParam, + } + } + resp := p.srv.NewListWithContinuationPager(options) + newListWithContinuationPager = &resp + p.newListWithContinuationPager.add(req, newListWithContinuationPager) + } + resp, err := server.PagerResponderNext(newListWithContinuationPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newListWithContinuationPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListWithContinuationPager) { + p.newListWithContinuationPager.remove(req) + } + return resp, nil +} + +func (p *PageableXMLPaginationServerTransport) dispatchNewListWithNextLinkPager(req *http.Request) (*http.Response, error) { + if p.srv.NewListWithNextLinkPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListWithNextLinkPager not implemented")} + } + newListWithNextLinkPager := p.newListWithNextLinkPager.get(req) + if newListWithNextLinkPager == nil { + resp := p.srv.NewListWithNextLinkPager(nil) + newListWithNextLinkPager = &resp + p.newListWithNextLinkPager.add(req, newListWithNextLinkPager) + server.PagerResponderInjectNextLinks(newListWithNextLinkPager, req, func(page *pageablegroup.PageableXMLPaginationClientListWithNextLinkResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListWithNextLinkPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newListWithNextLinkPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListWithNextLinkPager) { + p.newListWithNextLinkPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to PageableXMLPaginationServerTransport +var pageableXmlPaginationServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/pageablegroup/go.mod b/test/http-specs/payload/pageablegroup/go.mod new file mode 100644 index 000000000000..b853b413cda0 --- /dev/null +++ b/test/http-specs/payload/pageablegroup/go.mod @@ -0,0 +1,17 @@ +module pageablegroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/payload/pageablegroup/go.sum b/test/http-specs/payload/pageablegroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/payload/pageablegroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/payload/pageablegroup/pageablepagesize_client_test.go b/test/http-specs/payload/pageablegroup/pageablepagesize_client_test.go new file mode 100644 index 000000000000..3236c603ee89 --- /dev/null +++ b/test/http-specs/payload/pageablegroup/pageablepagesize_client_test.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package pageablegroup_test + +import ( + "context" + "pageablegroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestPageablePageSizeClientNewListWithoutContinuationPager(t *testing.T) { + pageableClient, err := pageablegroup.NewPageableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + pageableSizeClient := pageableClient.NewPageablePageSizeClient() + pager := pageableSizeClient.NewListWithoutContinuationPager(nil) + pageCount := 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + require.Len(t, page.Pets, 4) + pageCount++ + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("1"), + Name: to.Ptr("dog"), + }, + { + ID: to.Ptr("2"), + Name: to.Ptr("cat"), + }, + { + ID: to.Ptr("3"), + Name: to.Ptr("bird"), + }, + { + ID: to.Ptr("4"), + Name: to.Ptr("fish"), + }, + }, page.Pets) + } + require.EqualValues(t, 1, pageCount) +} + +func TestPageablePageSizeClientNewListWithPageSizePager(t *testing.T) { + pageableClient, err := pageablegroup.NewPageableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + pageableSizeClient := pageableClient.NewPageablePageSizeClient() + + // Test with pageSize=2 + pager := pageableSizeClient.NewListWithPageSizePager(&pageablegroup.PageablePageSizeClientListWithPageSizeOptions{ + PageSize: to.Ptr[int32](2), + }) + pageCount := 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + require.Len(t, page.Pets, 2) + pageCount++ + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("1"), + Name: to.Ptr("dog"), + }, + { + ID: to.Ptr("2"), + Name: to.Ptr("cat"), + }, + }, page.Pets) + } + require.EqualValues(t, 1, pageCount) + + // Test with pageSize=4 + pager = pageableSizeClient.NewListWithPageSizePager(&pageablegroup.PageablePageSizeClientListWithPageSizeOptions{ + PageSize: to.Ptr[int32](4), + }) + pageCount = 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + require.Len(t, page.Pets, 4) + pageCount++ + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("1"), + Name: to.Ptr("dog"), + }, + { + ID: to.Ptr("2"), + Name: to.Ptr("cat"), + }, + { + ID: to.Ptr("3"), + Name: to.Ptr("bird"), + }, + { + ID: to.Ptr("4"), + Name: to.Ptr("fish"), + }, + }, page.Pets) + } + require.EqualValues(t, 1, pageCount) +} diff --git a/test/http-specs/payload/pageablegroup/pageableserverdrivenpagination_client_test.go b/test/http-specs/payload/pageablegroup/pageableserverdrivenpagination_client_test.go new file mode 100644 index 000000000000..e84b31f6df02 --- /dev/null +++ b/test/http-specs/payload/pageablegroup/pageableserverdrivenpagination_client_test.go @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package pageablegroup_test + +import ( + "context" + "pageablegroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestNewLinkPager(t *testing.T) { + client, err := pageablegroup.NewPageableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + pager := client.NewPageableServerDrivenPaginationClient().NewLinkPager(nil) + pageCount := 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + require.Len(t, page.Pets, 2) + pageCount++ + switch pageCount { + case 1: + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("1"), + Name: to.Ptr("dog"), + }, + { + ID: to.Ptr("2"), + Name: to.Ptr("cat"), + }, + }, page.Pets) + case 2: + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("3"), + Name: to.Ptr("bird"), + }, + { + ID: to.Ptr("4"), + Name: to.Ptr("fish"), + }, + }, page.Pets) + } + } + require.EqualValues(t, 2, pageCount) +} + +func TestNewLinkStringPager(t *testing.T) { + client, err := pageablegroup.NewPageableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + pager := client.NewPageableServerDrivenPaginationClient().NewLinkStringPager(nil) + pageCount := 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + require.Len(t, page.Pets, 2) + pageCount++ + switch pageCount { + case 1: + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("1"), + Name: to.Ptr("dog"), + }, + { + ID: to.Ptr("2"), + Name: to.Ptr("cat"), + }, + }, page.Pets) + case 2: + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("3"), + Name: to.Ptr("bird"), + }, + { + ID: to.Ptr("4"), + Name: to.Ptr("fish"), + }, + }, page.Pets) + } + } + require.EqualValues(t, 2, pageCount) +} + +func TestNewNestedLinkPager(t *testing.T) { + client, err := pageablegroup.NewPageableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + pageCount := 0 + pager := client.NewPageableServerDrivenPaginationClient().NewNestedLinkPager(&pageablegroup.PageableServerDrivenPaginationClientNestedLinkOptions{}) + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + require.Len(t, page.NestedItems.Pets, 2) + pageCount++ + switch pageCount { + case 1: + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("1"), + Name: to.Ptr("dog"), + }, + { + ID: to.Ptr("2"), + Name: to.Ptr("cat"), + }, + }, page.NestedItems.Pets) + require.Equal(t, "http://localhost:3000/payload/pageable/server-driven-pagination/nested-link/nextPage", *page.NestedNext.Next) + case 2: + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("3"), + Name: to.Ptr("bird"), + }, + { + ID: to.Ptr("4"), + Name: to.Ptr("fish"), + }, + }, page.NestedItems.Pets) + require.Empty(t, page.NestedNext) + } + } + require.EqualValues(t, 2, pageCount) +} diff --git a/test/http-specs/payload/pageablegroup/pageableserverdrivenpaginationalternateinitialverb_client_test.go b/test/http-specs/payload/pageablegroup/pageableserverdrivenpaginationalternateinitialverb_client_test.go new file mode 100644 index 000000000000..08cac584eacd --- /dev/null +++ b/test/http-specs/payload/pageablegroup/pageableserverdrivenpaginationalternateinitialverb_client_test.go @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package pageablegroup_test + +import ( + "context" + "pageablegroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestNewPostPager(t *testing.T) { + client, err := pageablegroup.NewPageableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + pager := client.NewPageableServerDrivenPaginationClient().NewPageableServerDrivenPaginationAlternateInitialVerbClient().NewPostPager(pageablegroup.Filter{ + Filter: to.Ptr("foo eq bar"), + }, nil) + pageCount := 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + require.Len(t, page.Pets, 2) + pageCount++ + switch pageCount { + case 1: + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("1"), + Name: to.Ptr("dog"), + }, + { + ID: to.Ptr("2"), + Name: to.Ptr("cat"), + }, + }, page.Pets) + case 2: + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("3"), + Name: to.Ptr("bird"), + }, + { + ID: to.Ptr("4"), + Name: to.Ptr("fish"), + }, + }, page.Pets) + } + } + require.EqualValues(t, 2, pageCount) +} diff --git a/test/http-specs/payload/pageablegroup/pageableserverdrivenpaginationcontinuationtoken_client_test.go b/test/http-specs/payload/pageablegroup/pageableserverdrivenpaginationcontinuationtoken_client_test.go new file mode 100644 index 000000000000..a5e9a18d92e3 --- /dev/null +++ b/test/http-specs/payload/pageablegroup/pageableserverdrivenpaginationcontinuationtoken_client_test.go @@ -0,0 +1,507 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package pageablegroup_test + +import ( + "context" + "net/http" + "pageablegroup" + "pageablegroup/fake" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestNewRequestHeaderNestedResponseBodyPager(t *testing.T) { + client, err := pageablegroup.NewPageableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + pager := client.NewPageableServerDrivenPaginationClient().NewPageableServerDrivenPaginationContinuationTokenClient().NewRequestHeaderNestedResponseBodyPager(&pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyOptions{ + Bar: to.Ptr("bar"), + Foo: to.Ptr("foo"), + }) + pageCount := 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + pageCount++ + switch pageCount { + case 1: + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("1"), + Name: to.Ptr("dog"), + }, + { + ID: to.Ptr("2"), + Name: to.Ptr("cat"), + }, + }, page.NestedItems.Pets) + case 2: + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("3"), + Name: to.Ptr("bird"), + }, + { + ID: to.Ptr("4"), + Name: to.Ptr("fish"), + }, + }, page.NestedItems.Pets) + default: + t.Fatalf("unexpected page number %d", pageCount) + } + } + require.EqualValues(t, 2, pageCount) + + pager = client.NewPageableServerDrivenPaginationClient().NewPageableServerDrivenPaginationContinuationTokenClient().NewRequestHeaderNestedResponseBodyPager(&pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyOptions{ + Bar: to.Ptr("bar"), + Foo: to.Ptr("foo"), + Token: to.Ptr("page2"), + }) + pageCount = 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + pageCount++ + switch pageCount { + case 1: + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("3"), + Name: to.Ptr("bird"), + }, + { + ID: to.Ptr("4"), + Name: to.Ptr("fish"), + }, + }, page.NestedItems.Pets) + default: + t.Fatalf("unexpected page number %d", pageCount) + } + } + require.EqualValues(t, 1, pageCount) +} + +func TestNewRequestHeaderResponseBodyPager(t *testing.T) { + client, err := pageablegroup.NewPageableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + pager := client.NewPageableServerDrivenPaginationClient().NewPageableServerDrivenPaginationContinuationTokenClient().NewRequestHeaderResponseBodyPager(&pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseBodyOptions{ + Bar: to.Ptr("bar"), + Foo: to.Ptr("foo"), + }) + pageCount := 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + pageCount++ + switch pageCount { + case 1: + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("1"), + Name: to.Ptr("dog"), + }, + { + ID: to.Ptr("2"), + Name: to.Ptr("cat"), + }, + }, page.Pets) + case 2: + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("3"), + Name: to.Ptr("bird"), + }, + { + ID: to.Ptr("4"), + Name: to.Ptr("fish"), + }, + }, page.Pets) + default: + t.Fatalf("unexpected page number %d", pageCount) + } + } + require.EqualValues(t, 2, pageCount) + + pager = client.NewPageableServerDrivenPaginationClient().NewPageableServerDrivenPaginationContinuationTokenClient().NewRequestHeaderResponseBodyPager(&pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseBodyOptions{ + Bar: to.Ptr("bar"), + Foo: to.Ptr("foo"), + Token: to.Ptr("page2"), + }) + pageCount = 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + pageCount++ + switch pageCount { + case 1: + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("3"), + Name: to.Ptr("bird"), + }, + { + ID: to.Ptr("4"), + Name: to.Ptr("fish"), + }, + }, page.Pets) + default: + t.Fatalf("unexpected page number %d", pageCount) + } + } + require.EqualValues(t, 1, pageCount) +} + +func TestNewRequestHeaderResponseHeaderPager(t *testing.T) { + client, err := pageablegroup.NewPageableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + pager := client.NewPageableServerDrivenPaginationClient().NewPageableServerDrivenPaginationContinuationTokenClient().NewRequestHeaderResponseHeaderPager(&pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseHeaderOptions{ + Bar: to.Ptr("bar"), + Foo: to.Ptr("foo"), + }) + pageCount := 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + pageCount++ + switch pageCount { + case 1: + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("1"), + Name: to.Ptr("dog"), + }, + { + ID: to.Ptr("2"), + Name: to.Ptr("cat"), + }, + }, page.Pets) + case 2: + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("3"), + Name: to.Ptr("bird"), + }, + { + ID: to.Ptr("4"), + Name: to.Ptr("fish"), + }, + }, page.Pets) + default: + t.Fatalf("unexpected page number %d", pageCount) + } + } + require.EqualValues(t, 2, pageCount) + + pager = client.NewPageableServerDrivenPaginationClient().NewPageableServerDrivenPaginationContinuationTokenClient().NewRequestHeaderResponseHeaderPager(&pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseHeaderOptions{ + Bar: to.Ptr("bar"), + Foo: to.Ptr("foo"), + Token: to.Ptr("page2"), + }) + pageCount = 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + pageCount++ + switch pageCount { + case 1: + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("3"), + Name: to.Ptr("bird"), + }, + { + ID: to.Ptr("4"), + Name: to.Ptr("fish"), + }, + }, page.Pets) + default: + t.Fatalf("unexpected page number %d", pageCount) + } + } + require.EqualValues(t, 1, pageCount) +} + +func TestNewRequestQueryNestedResponseBodyPager(t *testing.T) { + client, err := pageablegroup.NewPageableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + pager := client.NewPageableServerDrivenPaginationClient().NewPageableServerDrivenPaginationContinuationTokenClient().NewRequestQueryNestedResponseBodyPager(&pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestQueryNestedResponseBodyOptions{ + Bar: to.Ptr("bar"), + Foo: to.Ptr("foo"), + }) + pageCount := 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + pageCount++ + switch pageCount { + case 1: + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("1"), + Name: to.Ptr("dog"), + }, + { + ID: to.Ptr("2"), + Name: to.Ptr("cat"), + }, + }, page.NestedItems.Pets) + case 2: + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("3"), + Name: to.Ptr("bird"), + }, + { + ID: to.Ptr("4"), + Name: to.Ptr("fish"), + }, + }, page.NestedItems.Pets) + default: + t.Fatalf("unexpected page number %d", pageCount) + } + } + require.EqualValues(t, 2, pageCount) + + pager = client.NewPageableServerDrivenPaginationClient().NewPageableServerDrivenPaginationContinuationTokenClient().NewRequestQueryNestedResponseBodyPager(&pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestQueryNestedResponseBodyOptions{ + Bar: to.Ptr("bar"), + Foo: to.Ptr("foo"), + Token: to.Ptr("page2"), + }) + pageCount = 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + pageCount++ + switch pageCount { + case 1: + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("3"), + Name: to.Ptr("bird"), + }, + { + ID: to.Ptr("4"), + Name: to.Ptr("fish"), + }, + }, page.NestedItems.Pets) + default: + t.Fatalf("unexpected page number %d", pageCount) + } + } + require.EqualValues(t, 1, pageCount) +} + +func TestNewRequestQueryResponseBodyPager(t *testing.T) { + client, err := pageablegroup.NewPageableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + pager := client.NewPageableServerDrivenPaginationClient().NewPageableServerDrivenPaginationContinuationTokenClient().NewRequestQueryResponseBodyPager(&pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseBodyOptions{ + Bar: to.Ptr("bar"), + Foo: to.Ptr("foo"), + }) + pageCount := 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + pageCount++ + switch pageCount { + case 1: + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("1"), + Name: to.Ptr("dog"), + }, + { + ID: to.Ptr("2"), + Name: to.Ptr("cat"), + }, + }, page.Pets) + case 2: + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("3"), + Name: to.Ptr("bird"), + }, + { + ID: to.Ptr("4"), + Name: to.Ptr("fish"), + }, + }, page.Pets) + default: + t.Fatalf("unexpected page number %d", pageCount) + } + } + require.EqualValues(t, 2, pageCount) + + pager = client.NewPageableServerDrivenPaginationClient().NewPageableServerDrivenPaginationContinuationTokenClient().NewRequestQueryResponseBodyPager(&pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseBodyOptions{ + Bar: to.Ptr("bar"), + Foo: to.Ptr("foo"), + Token: to.Ptr("page2"), + }) + pageCount = 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + pageCount++ + switch pageCount { + case 1: + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("3"), + Name: to.Ptr("bird"), + }, + { + ID: to.Ptr("4"), + Name: to.Ptr("fish"), + }, + }, page.Pets) + default: + t.Fatalf("unexpected page number %d", pageCount) + } + } + require.EqualValues(t, 1, pageCount) +} + +func TestNewRequestQueryResponseHeaderPager(t *testing.T) { + client, err := pageablegroup.NewPageableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + pager := client.NewPageableServerDrivenPaginationClient().NewPageableServerDrivenPaginationContinuationTokenClient().NewRequestQueryResponseHeaderPager(&pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseHeaderOptions{ + Bar: to.Ptr("bar"), + Foo: to.Ptr("foo"), + }) + pageCount := 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + pageCount++ + switch pageCount { + case 1: + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("1"), + Name: to.Ptr("dog"), + }, + { + ID: to.Ptr("2"), + Name: to.Ptr("cat"), + }, + }, page.Pets) + case 2: + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("3"), + Name: to.Ptr("bird"), + }, + { + ID: to.Ptr("4"), + Name: to.Ptr("fish"), + }, + }, page.Pets) + default: + t.Fatalf("unexpected page number %d", pageCount) + } + } + require.EqualValues(t, 2, pageCount) + + pager = client.NewPageableServerDrivenPaginationClient().NewPageableServerDrivenPaginationContinuationTokenClient().NewRequestQueryResponseHeaderPager(&pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseHeaderOptions{ + Bar: to.Ptr("bar"), + Foo: to.Ptr("foo"), + Token: to.Ptr("page2"), + }) + pageCount = 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + pageCount++ + switch pageCount { + case 1: + require.Equal(t, []*pageablegroup.Pet{ + { + ID: to.Ptr("3"), + Name: to.Ptr("bird"), + }, + { + ID: to.Ptr("4"), + Name: to.Ptr("fish"), + }, + }, page.Pets) + default: + t.Fatalf("unexpected page number %d", pageCount) + } + } + require.EqualValues(t, 1, pageCount) +} + +func TestNewRequestHeaderNestedResponseBodyPager_Fake(t *testing.T) { + srv := fake.PageableServerDrivenPaginationContinuationTokenServer{ + NewRequestHeaderNestedResponseBodyPager: func(options *pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyOptions) azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyResponse] { + require.NotNil(t, options) + require.NotNil(t, options.Bar) + require.Equal(t, "bar", *options.Bar) + require.NotNil(t, options.Foo) + require.Equal(t, "foo", *options.Foo) + pager := azfake.PagerResponder[pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyResponse]{} + pager.AddPage(http.StatusOK, pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyResponse{ + RequestHeaderNestedResponseBodyResponse: pageablegroup.RequestHeaderNestedResponseBodyResponse{ + NestedItems: &pageablegroup.RequestHeaderNestedResponseBodyResponseNestedItems{ + Pets: []*pageablegroup.Pet{ + {ID: to.Ptr("1"), Name: to.Ptr("dog")}, + {ID: to.Ptr("2"), Name: to.Ptr("cat")}, + }, + }, + NestedNext: &pageablegroup.RequestHeaderNestedResponseBodyResponseNestedNext{ + NextToken: to.Ptr("page2"), + }, + }, + }, nil) + pager.AddPage(http.StatusOK, pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyResponse{ + RequestHeaderNestedResponseBodyResponse: pageablegroup.RequestHeaderNestedResponseBodyResponse{ + NestedItems: &pageablegroup.RequestHeaderNestedResponseBodyResponseNestedItems{ + Pets: []*pageablegroup.Pet{ + {ID: to.Ptr("3"), Name: to.Ptr("bird")}, + {ID: to.Ptr("4"), Name: to.Ptr("fish")}, + }, + }, + }, + }, nil) + return pager + }, + } + + client, err := pageablegroup.NewPageableClientWithNoCredential("https://fake.endpoint", &pageablegroup.PageableClientOptions{ + ClientOptions: azcore.ClientOptions{ + Transport: fake.NewPageableServerDrivenPaginationContinuationTokenServerTransport(&srv), + }, + }) + require.NoError(t, err) + + pager := client.NewPageableServerDrivenPaginationClient().NewPageableServerDrivenPaginationContinuationTokenClient().NewRequestHeaderNestedResponseBodyPager(&pageablegroup.PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyOptions{ + Bar: to.Ptr("bar"), + Foo: to.Ptr("foo"), + }) + pageCount := 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + pageCount++ + switch pageCount { + case 1: + require.Equal(t, []*pageablegroup.Pet{ + {ID: to.Ptr("1"), Name: to.Ptr("dog")}, + {ID: to.Ptr("2"), Name: to.Ptr("cat")}, + }, page.NestedItems.Pets) + case 2: + require.Equal(t, []*pageablegroup.Pet{ + {ID: to.Ptr("3"), Name: to.Ptr("bird")}, + {ID: to.Ptr("4"), Name: to.Ptr("fish")}, + }, page.NestedItems.Pets) + default: + t.Fatalf("unexpected page number %d", pageCount) + } + } + require.EqualValues(t, 2, pageCount) +} diff --git a/test/http-specs/payload/pageablegroup/pageablexmlpagination_client_test.go b/test/http-specs/payload/pageablegroup/pageablexmlpagination_client_test.go new file mode 100644 index 000000000000..11929ba67e23 --- /dev/null +++ b/test/http-specs/payload/pageablegroup/pageablexmlpagination_client_test.go @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package pageablegroup_test + +import ( + "context" + "pageablegroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestNewListWithContinuationPager(t *testing.T) { + client, err := pageablegroup.NewPageableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + pager := client.NewPageableXMLPaginationClient().NewListWithContinuationPager(nil) + pageCount := 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + require.Len(t, page.Pets, 2) + pageCount++ + switch pageCount { + case 1: + require.Equal(t, []*pageablegroup.XMLPet{ + { + ID: to.Ptr("1"), + Name: to.Ptr("dog"), + }, + { + ID: to.Ptr("2"), + Name: to.Ptr("cat"), + }, + }, page.Pets) + case 2: + require.Equal(t, []*pageablegroup.XMLPet{ + { + ID: to.Ptr("3"), + Name: to.Ptr("bird"), + }, + { + ID: to.Ptr("4"), + Name: to.Ptr("fish"), + }, + }, page.Pets) + } + } + require.EqualValues(t, 2, pageCount) +} + +func TestNewListWithNextLinkPager(t *testing.T) { + client, err := pageablegroup.NewPageableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + pager := client.NewPageableXMLPaginationClient().NewListWithNextLinkPager(nil) + pageCount := 0 + for pager.More() { + page, err := pager.NextPage(context.Background()) + require.NoError(t, err) + require.Len(t, page.Pets, 2) + pageCount++ + switch pageCount { + case 1: + require.Equal(t, []*pageablegroup.XMLPet{ + { + ID: to.Ptr("1"), + Name: to.Ptr("dog"), + }, + { + ID: to.Ptr("2"), + Name: to.Ptr("cat"), + }, + }, page.Pets) + case 2: + require.Equal(t, []*pageablegroup.XMLPet{ + { + ID: to.Ptr("3"), + Name: to.Ptr("bird"), + }, + { + ID: to.Ptr("4"), + Name: to.Ptr("fish"), + }, + }, page.Pets) + } + } + require.EqualValues(t, 2, pageCount) +} diff --git a/test/http-specs/payload/pageablegroup/testdata/_metadata.json b/test/http-specs/payload/pageablegroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/payload/pageablegroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/payload/pageablegroup/zz_models.go b/test/http-specs/payload/pageablegroup/zz_models.go new file mode 100644 index 000000000000..c058e5705769 --- /dev/null +++ b/test/http-specs/payload/pageablegroup/zz_models.go @@ -0,0 +1,138 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package pageablegroup + +type Filter struct { + // REQUIRED + Filter *string +} + +type LinkResponse struct { + // REQUIRED + Pets []*Pet + Next *string +} + +type LinkStringResponse struct { + // REQUIRED + Pets []*Pet + Next *string +} + +type ListWithPageSizeResponse struct { + // REQUIRED + Pets []*Pet +} + +type ListWithoutContinuationResponse struct { + // REQUIRED + Pets []*Pet +} + +type NestedLinkResponse struct { + // REQUIRED + NestedItems *NestedLinkResponseNestedItems + + // REQUIRED + NestedNext *NestedLinkResponseNestedNext +} + +type NestedLinkResponseNestedItems struct { + // REQUIRED + Pets []*Pet +} + +type NestedLinkResponseNestedNext struct { + Next *string +} + +type Pet struct { + // REQUIRED + ID *string + + // REQUIRED + Name *string +} + +type PostResponse struct { + // REQUIRED + Pets []*Pet + Next *string +} + +type RequestHeaderNestedResponseBodyResponse struct { + // REQUIRED + NestedItems *RequestHeaderNestedResponseBodyResponseNestedItems + NestedNext *RequestHeaderNestedResponseBodyResponseNestedNext +} + +type RequestHeaderNestedResponseBodyResponseNestedItems struct { + // REQUIRED + Pets []*Pet +} + +type RequestHeaderNestedResponseBodyResponseNestedNext struct { + NextToken *string +} + +type RequestHeaderResponseBodyResponse struct { + // REQUIRED + Pets []*Pet + NextToken *string +} + +type RequestHeaderResponseHeaderResponse struct { + // REQUIRED + Pets []*Pet +} + +type RequestQueryNestedResponseBodyResponse struct { + // REQUIRED + NestedItems *RequestQueryNestedResponseBodyResponseNestedItems + NestedNext *RequestQueryNestedResponseBodyResponseNestedNext +} + +type RequestQueryNestedResponseBodyResponseNestedItems struct { + // REQUIRED + Pets []*Pet +} + +type RequestQueryNestedResponseBodyResponseNestedNext struct { + NextToken *string +} + +type RequestQueryResponseBodyResponse struct { + // REQUIRED + Pets []*Pet + NextToken *string +} + +type RequestQueryResponseHeaderResponse struct { + // REQUIRED + Pets []*Pet +} + +// XMLPet - An XML pet item. +type XMLPet struct { + // REQUIRED + ID *string `xml:"Id"` + + // REQUIRED + Name *string `xml:"Name"` +} + +// XMLPetListResult - The XML response for listing pets. +type XMLPetListResult struct { + // REQUIRED + Pets []*XMLPet `xml:"Pets>Pet"` + NextMarker *string `xml:"NextMarker"` +} + +// XMLPetListResultWithNextLink - The XML response for listing pets with next link. +type XMLPetListResultWithNextLink struct { + // REQUIRED + Pets []*XMLPet `xml:"Pets>Pet"` + NextLink *string `xml:"NextLink"` +} diff --git a/test/http-specs/payload/pageablegroup/zz_models_serde.go b/test/http-specs/payload/pageablegroup/zz_models_serde.go new file mode 100644 index 000000000000..57d71554a187 --- /dev/null +++ b/test/http-specs/payload/pageablegroup/zz_models_serde.go @@ -0,0 +1,653 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package pageablegroup + +import ( + "encoding/json" + "encoding/xml" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type Filter. +func (f Filter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "filter", f.Filter) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Filter. +func (f *Filter) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "filter": + err = unpopulate(val, "Filter", &f.Filter) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LinkResponse. +func (l LinkResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "next", l.Next) + populate(objectMap, "pets", l.Pets) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LinkResponse. +func (l *LinkResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "next": + err = unpopulate(val, "Next", &l.Next) + delete(rawMsg, key) + case "pets": + err = unpopulate(val, "Pets", &l.Pets) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LinkStringResponse. +func (l LinkStringResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "next", l.Next) + populate(objectMap, "pets", l.Pets) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LinkStringResponse. +func (l *LinkStringResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "next": + err = unpopulate(val, "Next", &l.Next) + delete(rawMsg, key) + case "pets": + err = unpopulate(val, "Pets", &l.Pets) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ListWithPageSizeResponse. +func (l ListWithPageSizeResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "pets", l.Pets) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ListWithPageSizeResponse. +func (l *ListWithPageSizeResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "pets": + err = unpopulate(val, "Pets", &l.Pets) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ListWithoutContinuationResponse. +func (l ListWithoutContinuationResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "pets", l.Pets) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ListWithoutContinuationResponse. +func (l *ListWithoutContinuationResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "pets": + err = unpopulate(val, "Pets", &l.Pets) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NestedLinkResponse. +func (n NestedLinkResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nestedItems", n.NestedItems) + populate(objectMap, "nestedNext", n.NestedNext) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NestedLinkResponse. +func (n *NestedLinkResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nestedItems": + err = unpopulate(val, "NestedItems", &n.NestedItems) + delete(rawMsg, key) + case "nestedNext": + err = unpopulate(val, "NestedNext", &n.NestedNext) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NestedLinkResponseNestedItems. +func (n NestedLinkResponseNestedItems) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "pets", n.Pets) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NestedLinkResponseNestedItems. +func (n *NestedLinkResponseNestedItems) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "pets": + err = unpopulate(val, "Pets", &n.Pets) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NestedLinkResponseNestedNext. +func (n NestedLinkResponseNestedNext) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "next", n.Next) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NestedLinkResponseNestedNext. +func (n *NestedLinkResponseNestedNext) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "next": + err = unpopulate(val, "Next", &n.Next) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Pet. +func (p Pet) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", p.ID) + populate(objectMap, "name", p.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Pet. +func (p *Pet) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PostResponse. +func (p PostResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "next", p.Next) + populate(objectMap, "pets", p.Pets) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PostResponse. +func (p *PostResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "next": + err = unpopulate(val, "Next", &p.Next) + delete(rawMsg, key) + case "pets": + err = unpopulate(val, "Pets", &p.Pets) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RequestHeaderNestedResponseBodyResponse. +func (r RequestHeaderNestedResponseBodyResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nestedItems", r.NestedItems) + populate(objectMap, "nestedNext", r.NestedNext) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RequestHeaderNestedResponseBodyResponse. +func (r *RequestHeaderNestedResponseBodyResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nestedItems": + err = unpopulate(val, "NestedItems", &r.NestedItems) + delete(rawMsg, key) + case "nestedNext": + err = unpopulate(val, "NestedNext", &r.NestedNext) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RequestHeaderNestedResponseBodyResponseNestedItems. +func (r RequestHeaderNestedResponseBodyResponseNestedItems) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "pets", r.Pets) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RequestHeaderNestedResponseBodyResponseNestedItems. +func (r *RequestHeaderNestedResponseBodyResponseNestedItems) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "pets": + err = unpopulate(val, "Pets", &r.Pets) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RequestHeaderNestedResponseBodyResponseNestedNext. +func (r RequestHeaderNestedResponseBodyResponseNestedNext) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextToken", r.NextToken) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RequestHeaderNestedResponseBodyResponseNestedNext. +func (r *RequestHeaderNestedResponseBodyResponseNestedNext) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextToken": + err = unpopulate(val, "NextToken", &r.NextToken) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RequestHeaderResponseBodyResponse. +func (r RequestHeaderResponseBodyResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextToken", r.NextToken) + populate(objectMap, "pets", r.Pets) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RequestHeaderResponseBodyResponse. +func (r *RequestHeaderResponseBodyResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextToken": + err = unpopulate(val, "NextToken", &r.NextToken) + delete(rawMsg, key) + case "pets": + err = unpopulate(val, "Pets", &r.Pets) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RequestHeaderResponseHeaderResponse. +func (r RequestHeaderResponseHeaderResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "pets", r.Pets) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RequestHeaderResponseHeaderResponse. +func (r *RequestHeaderResponseHeaderResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "pets": + err = unpopulate(val, "Pets", &r.Pets) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RequestQueryNestedResponseBodyResponse. +func (r RequestQueryNestedResponseBodyResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nestedItems", r.NestedItems) + populate(objectMap, "nestedNext", r.NestedNext) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RequestQueryNestedResponseBodyResponse. +func (r *RequestQueryNestedResponseBodyResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nestedItems": + err = unpopulate(val, "NestedItems", &r.NestedItems) + delete(rawMsg, key) + case "nestedNext": + err = unpopulate(val, "NestedNext", &r.NestedNext) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RequestQueryNestedResponseBodyResponseNestedItems. +func (r RequestQueryNestedResponseBodyResponseNestedItems) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "pets", r.Pets) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RequestQueryNestedResponseBodyResponseNestedItems. +func (r *RequestQueryNestedResponseBodyResponseNestedItems) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "pets": + err = unpopulate(val, "Pets", &r.Pets) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RequestQueryNestedResponseBodyResponseNestedNext. +func (r RequestQueryNestedResponseBodyResponseNestedNext) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextToken", r.NextToken) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RequestQueryNestedResponseBodyResponseNestedNext. +func (r *RequestQueryNestedResponseBodyResponseNestedNext) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextToken": + err = unpopulate(val, "NextToken", &r.NextToken) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RequestQueryResponseBodyResponse. +func (r RequestQueryResponseBodyResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextToken", r.NextToken) + populate(objectMap, "pets", r.Pets) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RequestQueryResponseBodyResponse. +func (r *RequestQueryResponseBodyResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextToken": + err = unpopulate(val, "NextToken", &r.NextToken) + delete(rawMsg, key) + case "pets": + err = unpopulate(val, "Pets", &r.Pets) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RequestQueryResponseHeaderResponse. +func (r RequestQueryResponseHeaderResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "pets", r.Pets) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RequestQueryResponseHeaderResponse. +func (r *RequestQueryResponseHeaderResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "pets": + err = unpopulate(val, "Pets", &r.Pets) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalXML implements the xml.Marshaller interface for type XMLPet. +func (x XMLPet) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + start.Name.Local = "Pet" + type alias XMLPet + aux := &struct { + *alias + }{ + alias: (*alias)(&x), + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type XMLPetListResult. +func (x XMLPetListResult) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + start.Name.Local = "PetListResult" + type alias XMLPetListResult + aux := &struct { + *alias + Pets *[]*XMLPet `xml:"Pets>Pet"` + }{ + alias: (*alias)(&x), + } + if x.Pets != nil { + aux.Pets = &x.Pets + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type XMLPetListResultWithNextLink. +func (x XMLPetListResultWithNextLink) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + start.Name.Local = "PetListResult" + type alias XMLPetListResultWithNextLink + aux := &struct { + *alias + Pets *[]*XMLPet `xml:"Pets>Pet"` + }{ + alias: (*alias)(&x), + } + if x.Pets != nil { + aux.Pets = &x.Pets + } + return enc.EncodeElement(aux, start) +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/http-specs/payload/pageablegroup/zz_options.go b/test/http-specs/payload/pageablegroup/zz_options.go new file mode 100644 index 000000000000..ebbc748bf9a7 --- /dev/null +++ b/test/http-specs/payload/pageablegroup/zz_options.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package pageablegroup + +// PageablePageSizeClientListWithPageSizeOptions contains the optional parameters for the PageablePageSizeClient.NewListWithPageSizePager +// method. +type PageablePageSizeClientListWithPageSizeOptions struct { + PageSize *int32 +} + +// PageablePageSizeClientListWithoutContinuationOptions contains the optional parameters for the PageablePageSizeClient.NewListWithoutContinuationPager +// method. +type PageablePageSizeClientListWithoutContinuationOptions struct { + // placeholder for future optional parameters +} + +// PageableServerDrivenPaginationAlternateInitialVerbClientPostOptions contains the optional parameters for the PageableServerDrivenPaginationAlternateInitialVerbClient.NewPostPager +// method. +type PageableServerDrivenPaginationAlternateInitialVerbClientPostOptions struct { + // placeholder for future optional parameters +} + +// PageableServerDrivenPaginationClientLinkOptions contains the optional parameters for the PageableServerDrivenPaginationClient.NewLinkPager +// method. +type PageableServerDrivenPaginationClientLinkOptions struct { + // placeholder for future optional parameters +} + +// PageableServerDrivenPaginationClientLinkStringOptions contains the optional parameters for the PageableServerDrivenPaginationClient.NewLinkStringPager +// method. +type PageableServerDrivenPaginationClientLinkStringOptions struct { + // placeholder for future optional parameters +} + +// PageableServerDrivenPaginationClientNestedLinkOptions contains the optional parameters for the PageableServerDrivenPaginationClient.NewNestedLinkPager +// method. +type PageableServerDrivenPaginationClientNestedLinkOptions struct { + // placeholder for future optional parameters +} + +// PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyOptions contains the optional parameters +// for the PageableServerDrivenPaginationContinuationTokenClient.NewRequestHeaderNestedResponseBodyPager method. +type PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyOptions struct { + Bar *string + Foo *string + Token *string +} + +// PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseBodyOptions contains the optional parameters +// for the PageableServerDrivenPaginationContinuationTokenClient.NewRequestHeaderResponseBodyPager method. +type PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseBodyOptions struct { + Bar *string + Foo *string + Token *string +} + +// PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseHeaderOptions contains the optional parameters +// for the PageableServerDrivenPaginationContinuationTokenClient.NewRequestHeaderResponseHeaderPager method. +type PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseHeaderOptions struct { + Bar *string + Foo *string + Token *string +} + +// PageableServerDrivenPaginationContinuationTokenClientRequestQueryNestedResponseBodyOptions contains the optional parameters +// for the PageableServerDrivenPaginationContinuationTokenClient.NewRequestQueryNestedResponseBodyPager method. +type PageableServerDrivenPaginationContinuationTokenClientRequestQueryNestedResponseBodyOptions struct { + Bar *string + Foo *string + Token *string +} + +// PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseBodyOptions contains the optional parameters for +// the PageableServerDrivenPaginationContinuationTokenClient.NewRequestQueryResponseBodyPager method. +type PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseBodyOptions struct { + Bar *string + Foo *string + Token *string +} + +// PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseHeaderOptions contains the optional parameters +// for the PageableServerDrivenPaginationContinuationTokenClient.NewRequestQueryResponseHeaderPager method. +type PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseHeaderOptions struct { + Bar *string + Foo *string + Token *string +} + +// PageableXMLPaginationClientListWithContinuationOptions contains the optional parameters for the PageableXMLPaginationClient.NewListWithContinuationPager +// method. +type PageableXMLPaginationClientListWithContinuationOptions struct { + Marker *string +} + +// PageableXMLPaginationClientListWithNextLinkOptions contains the optional parameters for the PageableXMLPaginationClient.NewListWithNextLinkPager +// method. +type PageableXMLPaginationClientListWithNextLinkOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/payload/pageablegroup/zz_pageable_client.go b/test/http-specs/payload/pageablegroup/zz_pageable_client.go new file mode 100644 index 000000000000..9807ef6048e0 --- /dev/null +++ b/test/http-specs/payload/pageablegroup/zz_pageable_client.go @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package pageablegroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// PageableClient - Test for pageable payload. +// Don't use this type directly, use NewPageableClientWithNoCredential() instead. +type PageableClient struct { + internal *azcore.Client + endpoint string +} + +// PageableClientOptions contains the optional values for creating a [PageableClient]. +type PageableClientOptions struct { + azcore.ClientOptions +} + +// NewPageableClientWithNoCredential creates a new instance of PageableClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewPageableClientWithNoCredential(endpoint string, options *PageableClientOptions) (*PageableClient, error) { + if options == nil { + options = &PageableClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &PageableClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewPageablePageSizeClient creates a new instance of [PageablePageSizeClient]. +func (client *PageableClient) NewPageablePageSizeClient() *PageablePageSizeClient { + return &PageablePageSizeClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewPageableServerDrivenPaginationClient creates a new instance of [PageableServerDrivenPaginationClient]. +func (client *PageableClient) NewPageableServerDrivenPaginationClient() *PageableServerDrivenPaginationClient { + return &PageableServerDrivenPaginationClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewPageableXMLPaginationClient creates a new instance of [PageableXMLPaginationClient]. +func (client *PageableClient) NewPageableXMLPaginationClient() *PageableXMLPaginationClient { + return &PageableXMLPaginationClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/http-specs/payload/pageablegroup/zz_pageablepagesize_client.go b/test/http-specs/payload/pageablegroup/zz_pageablepagesize_client.go new file mode 100644 index 000000000000..a0080f0d8110 --- /dev/null +++ b/test/http-specs/payload/pageablegroup/zz_pageablepagesize_client.go @@ -0,0 +1,119 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package pageablegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strconv" + "strings" +) + +// PageablePageSizeClient contains the methods for the PageablePageSize group. +// Don't use this type directly, use [PageableClient.NewPageablePageSizeClient] instead. +type PageablePageSizeClient struct { + internal *azcore.Client + endpoint string +} + +// - options - PageablePageSizeClientListWithPageSizeOptions contains the optional parameters for the PageablePageSizeClient.NewListWithPageSizePager +// method. +func (client *PageablePageSizeClient) NewListWithPageSizePager(options *PageablePageSizeClientListWithPageSizeOptions) *runtime.Pager[PageablePageSizeClientListWithPageSizeResponse] { + return runtime.NewPager(runtime.PagingHandler[PageablePageSizeClientListWithPageSizeResponse]{ + More: func(page PageablePageSizeClientListWithPageSizeResponse) bool { + return false + }, + Fetcher: func(ctx context.Context, page *PageablePageSizeClientListWithPageSizeResponse) (PageablePageSizeClientListWithPageSizeResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PageablePageSizeClient.NewListWithPageSizePager") + req, err := client.listWithPageSizeCreateRequest(ctx, options) + if err != nil { + return PageablePageSizeClientListWithPageSizeResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PageablePageSizeClientListWithPageSizeResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PageablePageSizeClientListWithPageSizeResponse{}, runtime.NewResponseError(resp) + } + return client.listWithPageSizeHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listWithPageSizeCreateRequest creates the ListWithPageSize request. +func (client *PageablePageSizeClient) listWithPageSizeCreateRequest(ctx context.Context, options *PageablePageSizeClientListWithPageSizeOptions) (*policy.Request, error) { + urlPath := "/payload/pageable/pagesize/list" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.PageSize != nil { + reqQP.Set("pageSize", strconv.FormatInt(int64(*options.PageSize), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listWithPageSizeHandleResponse handles the ListWithPageSize response. +func (client *PageablePageSizeClient) listWithPageSizeHandleResponse(resp *http.Response) (PageablePageSizeClientListWithPageSizeResponse, error) { + result := PageablePageSizeClientListWithPageSizeResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListWithPageSizeResponse); err != nil { + return PageablePageSizeClientListWithPageSizeResponse{}, err + } + return result, nil +} + +// - options - PageablePageSizeClientListWithoutContinuationOptions contains the optional parameters for the PageablePageSizeClient.NewListWithoutContinuationPager +// method. +func (client *PageablePageSizeClient) NewListWithoutContinuationPager(options *PageablePageSizeClientListWithoutContinuationOptions) *runtime.Pager[PageablePageSizeClientListWithoutContinuationResponse] { + return runtime.NewPager(runtime.PagingHandler[PageablePageSizeClientListWithoutContinuationResponse]{ + More: func(page PageablePageSizeClientListWithoutContinuationResponse) bool { + return false + }, + Fetcher: func(ctx context.Context, page *PageablePageSizeClientListWithoutContinuationResponse) (PageablePageSizeClientListWithoutContinuationResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PageablePageSizeClient.NewListWithoutContinuationPager") + req, err := client.listWithoutContinuationCreateRequest(ctx, options) + if err != nil { + return PageablePageSizeClientListWithoutContinuationResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PageablePageSizeClientListWithoutContinuationResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PageablePageSizeClientListWithoutContinuationResponse{}, runtime.NewResponseError(resp) + } + return client.listWithoutContinuationHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listWithoutContinuationCreateRequest creates the ListWithoutContinuation request. +func (client *PageablePageSizeClient) listWithoutContinuationCreateRequest(ctx context.Context, _ *PageablePageSizeClientListWithoutContinuationOptions) (*policy.Request, error) { + urlPath := "/payload/pageable/pagesize/without-continuation" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listWithoutContinuationHandleResponse handles the ListWithoutContinuation response. +func (client *PageablePageSizeClient) listWithoutContinuationHandleResponse(resp *http.Response) (PageablePageSizeClientListWithoutContinuationResponse, error) { + result := PageablePageSizeClientListWithoutContinuationResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListWithoutContinuationResponse); err != nil { + return PageablePageSizeClientListWithoutContinuationResponse{}, err + } + return result, nil +} diff --git a/test/http-specs/payload/pageablegroup/zz_pageableserverdrivenpagination_client.go b/test/http-specs/payload/pageablegroup/zz_pageableserverdrivenpagination_client.go new file mode 100644 index 000000000000..f6dd865a4577 --- /dev/null +++ b/test/http-specs/payload/pageablegroup/zz_pageableserverdrivenpagination_client.go @@ -0,0 +1,171 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package pageablegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// PageableServerDrivenPaginationClient contains the methods for the PageableServerDrivenPagination group. +// Don't use this type directly, use [PageableClient.NewPageableServerDrivenPaginationClient] instead. +type PageableServerDrivenPaginationClient struct { + internal *azcore.Client + endpoint string +} + +// NewPageableServerDrivenPaginationAlternateInitialVerbClient creates a new instance of [PageableServerDrivenPaginationAlternateInitialVerbClient]. +func (client *PageableServerDrivenPaginationClient) NewPageableServerDrivenPaginationAlternateInitialVerbClient() *PageableServerDrivenPaginationAlternateInitialVerbClient { + return &PageableServerDrivenPaginationAlternateInitialVerbClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewPageableServerDrivenPaginationContinuationTokenClient creates a new instance of [PageableServerDrivenPaginationContinuationTokenClient]. +func (client *PageableServerDrivenPaginationClient) NewPageableServerDrivenPaginationContinuationTokenClient() *PageableServerDrivenPaginationContinuationTokenClient { + return &PageableServerDrivenPaginationContinuationTokenClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// - options - PageableServerDrivenPaginationClientLinkOptions contains the optional parameters for the PageableServerDrivenPaginationClient.NewLinkPager +// method. +func (client *PageableServerDrivenPaginationClient) NewLinkPager(options *PageableServerDrivenPaginationClientLinkOptions) *runtime.Pager[PageableServerDrivenPaginationClientLinkResponse] { + return runtime.NewPager(runtime.PagingHandler[PageableServerDrivenPaginationClientLinkResponse]{ + More: func(page PageableServerDrivenPaginationClientLinkResponse) bool { + return page.Next != nil && len(*page.Next) > 0 + }, + Fetcher: func(ctx context.Context, page *PageableServerDrivenPaginationClientLinkResponse) (PageableServerDrivenPaginationClientLinkResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PageableServerDrivenPaginationClient.NewLinkPager") + nextLink := "" + if page != nil { + nextLink = *page.Next + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.linkCreateRequest(ctx, options) + }, nil) + if err != nil { + return PageableServerDrivenPaginationClientLinkResponse{}, err + } + return client.linkHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// linkCreateRequest creates the Link request. +func (client *PageableServerDrivenPaginationClient) linkCreateRequest(ctx context.Context, _ *PageableServerDrivenPaginationClientLinkOptions) (*policy.Request, error) { + urlPath := "/payload/pageable/server-driven-pagination/link" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// linkHandleResponse handles the Link response. +func (client *PageableServerDrivenPaginationClient) linkHandleResponse(resp *http.Response) (PageableServerDrivenPaginationClientLinkResponse, error) { + result := PageableServerDrivenPaginationClientLinkResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LinkResponse); err != nil { + return PageableServerDrivenPaginationClientLinkResponse{}, err + } + return result, nil +} + +// - options - PageableServerDrivenPaginationClientLinkStringOptions contains the optional parameters for the PageableServerDrivenPaginationClient.NewLinkStringPager +// method. +func (client *PageableServerDrivenPaginationClient) NewLinkStringPager(options *PageableServerDrivenPaginationClientLinkStringOptions) *runtime.Pager[PageableServerDrivenPaginationClientLinkStringResponse] { + return runtime.NewPager(runtime.PagingHandler[PageableServerDrivenPaginationClientLinkStringResponse]{ + More: func(page PageableServerDrivenPaginationClientLinkStringResponse) bool { + return page.Next != nil && len(*page.Next) > 0 + }, + Fetcher: func(ctx context.Context, page *PageableServerDrivenPaginationClientLinkStringResponse) (PageableServerDrivenPaginationClientLinkStringResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PageableServerDrivenPaginationClient.NewLinkStringPager") + nextLink := "" + if page != nil { + nextLink = *page.Next + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.linkStringCreateRequest(ctx, options) + }, nil) + if err != nil { + return PageableServerDrivenPaginationClientLinkStringResponse{}, err + } + return client.linkStringHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// linkStringCreateRequest creates the LinkString request. +func (client *PageableServerDrivenPaginationClient) linkStringCreateRequest(ctx context.Context, _ *PageableServerDrivenPaginationClientLinkStringOptions) (*policy.Request, error) { + urlPath := "/payload/pageable/server-driven-pagination/link-string" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// linkStringHandleResponse handles the LinkString response. +func (client *PageableServerDrivenPaginationClient) linkStringHandleResponse(resp *http.Response) (PageableServerDrivenPaginationClientLinkStringResponse, error) { + result := PageableServerDrivenPaginationClientLinkStringResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LinkStringResponse); err != nil { + return PageableServerDrivenPaginationClientLinkStringResponse{}, err + } + return result, nil +} + +// - options - PageableServerDrivenPaginationClientNestedLinkOptions contains the optional parameters for the PageableServerDrivenPaginationClient.NewNestedLinkPager +// method. +func (client *PageableServerDrivenPaginationClient) NewNestedLinkPager(options *PageableServerDrivenPaginationClientNestedLinkOptions) *runtime.Pager[PageableServerDrivenPaginationClientNestedLinkResponse] { + return runtime.NewPager(runtime.PagingHandler[PageableServerDrivenPaginationClientNestedLinkResponse]{ + More: func(page PageableServerDrivenPaginationClientNestedLinkResponse) bool { + return page.NestedNext != nil && page.NestedNext.Next != nil && len(*page.NestedNext.Next) > 0 + }, + Fetcher: func(ctx context.Context, page *PageableServerDrivenPaginationClientNestedLinkResponse) (PageableServerDrivenPaginationClientNestedLinkResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PageableServerDrivenPaginationClient.NewNestedLinkPager") + nextLink := "" + if page != nil { + nextLink = *page.NestedNext.Next + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.nestedLinkCreateRequest(ctx, options) + }, nil) + if err != nil { + return PageableServerDrivenPaginationClientNestedLinkResponse{}, err + } + return client.nestedLinkHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// nestedLinkCreateRequest creates the NestedLink request. +func (client *PageableServerDrivenPaginationClient) nestedLinkCreateRequest(ctx context.Context, _ *PageableServerDrivenPaginationClientNestedLinkOptions) (*policy.Request, error) { + urlPath := "/payload/pageable/server-driven-pagination/nested-link" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// nestedLinkHandleResponse handles the NestedLink response. +func (client *PageableServerDrivenPaginationClient) nestedLinkHandleResponse(resp *http.Response) (PageableServerDrivenPaginationClientNestedLinkResponse, error) { + result := PageableServerDrivenPaginationClientNestedLinkResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.NestedLinkResponse); err != nil { + return PageableServerDrivenPaginationClientNestedLinkResponse{}, err + } + return result, nil +} diff --git a/test/http-specs/payload/pageablegroup/zz_pageableserverdrivenpaginationalternateinitialverb_client.go b/test/http-specs/payload/pageablegroup/zz_pageableserverdrivenpaginationalternateinitialverb_client.go new file mode 100644 index 000000000000..b5e6a6520878 --- /dev/null +++ b/test/http-specs/payload/pageablegroup/zz_pageableserverdrivenpaginationalternateinitialverb_client.go @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package pageablegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// PageableServerDrivenPaginationAlternateInitialVerbClient - Scenario where the initial request is not a GET request. However +// following the next link always result in a GET request. +// Don't use this type directly, use [PageableServerDrivenPaginationClient.NewPageableServerDrivenPaginationAlternateInitialVerbClient] instead. +type PageableServerDrivenPaginationAlternateInitialVerbClient struct { + internal *azcore.Client + endpoint string +} + +// - options - PageableServerDrivenPaginationAlternateInitialVerbClientPostOptions contains the optional parameters for the +// PageableServerDrivenPaginationAlternateInitialVerbClient.NewPostPager method. +func (client *PageableServerDrivenPaginationAlternateInitialVerbClient) NewPostPager(body Filter, options *PageableServerDrivenPaginationAlternateInitialVerbClientPostOptions) *runtime.Pager[PageableServerDrivenPaginationAlternateInitialVerbClientPostResponse] { + return runtime.NewPager(runtime.PagingHandler[PageableServerDrivenPaginationAlternateInitialVerbClientPostResponse]{ + More: func(page PageableServerDrivenPaginationAlternateInitialVerbClientPostResponse) bool { + return page.Next != nil && len(*page.Next) > 0 + }, + Fetcher: func(ctx context.Context, page *PageableServerDrivenPaginationAlternateInitialVerbClientPostResponse) (PageableServerDrivenPaginationAlternateInitialVerbClientPostResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PageableServerDrivenPaginationAlternateInitialVerbClient.NewPostPager") + nextLink := "" + if page != nil { + nextLink = *page.Next + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.postCreateRequest(ctx, body, options) + }, nil) + if err != nil { + return PageableServerDrivenPaginationAlternateInitialVerbClientPostResponse{}, err + } + return client.postHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// postCreateRequest creates the Post request. +func (client *PageableServerDrivenPaginationAlternateInitialVerbClient) postCreateRequest(ctx context.Context, body Filter, _ *PageableServerDrivenPaginationAlternateInitialVerbClientPostOptions) (*policy.Request, error) { + urlPath := "/payload/pageable/server-driven-pagination/link/initial-post" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// postHandleResponse handles the Post response. +func (client *PageableServerDrivenPaginationAlternateInitialVerbClient) postHandleResponse(resp *http.Response) (PageableServerDrivenPaginationAlternateInitialVerbClientPostResponse, error) { + result := PageableServerDrivenPaginationAlternateInitialVerbClientPostResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PostResponse); err != nil { + return PageableServerDrivenPaginationAlternateInitialVerbClientPostResponse{}, err + } + return result, nil +} diff --git a/test/http-specs/payload/pageablegroup/zz_pageableserverdrivenpaginationcontinuationtoken_client.go b/test/http-specs/payload/pageablegroup/zz_pageableserverdrivenpaginationcontinuationtoken_client.go new file mode 100644 index 000000000000..8747cf4c363b --- /dev/null +++ b/test/http-specs/payload/pageablegroup/zz_pageableserverdrivenpaginationcontinuationtoken_client.go @@ -0,0 +1,412 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package pageablegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// PageableServerDrivenPaginationContinuationTokenClient contains the methods for the PageableServerDrivenPaginationContinuationToken +// group. +// Don't use this type directly, use [PageableServerDrivenPaginationClient.NewPageableServerDrivenPaginationContinuationTokenClient] instead. +type PageableServerDrivenPaginationContinuationTokenClient struct { + internal *azcore.Client + endpoint string +} + +// - options - PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyOptions contains the optional +// parameters for the PageableServerDrivenPaginationContinuationTokenClient.NewRequestHeaderNestedResponseBodyPager method. +func (client *PageableServerDrivenPaginationContinuationTokenClient) NewRequestHeaderNestedResponseBodyPager(options *PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyOptions) *runtime.Pager[PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyResponse] { + return runtime.NewPager(runtime.PagingHandler[PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyResponse]{ + More: func(page PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyResponse) bool { + return page.NestedNext != nil && page.NestedNext.NextToken != nil && len(*page.NestedNext.NextToken) > 0 + }, + Fetcher: func(ctx context.Context, page *PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyResponse) (PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PageableServerDrivenPaginationContinuationTokenClient.NewRequestHeaderNestedResponseBodyPager") + nextOpts := PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyOptions{} + if options != nil { + nextOpts = *options + } + if page != nil && page.NestedNext != nil { + nextOpts.Token = page.NestedNext.NextToken + } + req, err := client.requestHeaderNestedResponseBodyCreateRequest(ctx, &nextOpts) + if err != nil { + return PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyResponse{}, runtime.NewResponseError(resp) + } + return client.requestHeaderNestedResponseBodyHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// requestHeaderNestedResponseBodyCreateRequest creates the RequestHeaderNestedResponseBody request. +func (client *PageableServerDrivenPaginationContinuationTokenClient) requestHeaderNestedResponseBodyCreateRequest(ctx context.Context, options *PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyOptions) (*policy.Request, error) { + urlPath := "/payload/pageable/server-driven-pagination/continuationtoken/request-header-nested-response-body" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Bar != nil { + reqQP.Set("bar", *options.Bar) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.Foo != nil { + req.Raw().Header["foo"] = []string{*options.Foo} + } + if options != nil && options.Token != nil { + req.Raw().Header["token"] = []string{*options.Token} + } + return req, nil +} + +// requestHeaderNestedResponseBodyHandleResponse handles the RequestHeaderNestedResponseBody response. +func (client *PageableServerDrivenPaginationContinuationTokenClient) requestHeaderNestedResponseBodyHandleResponse(resp *http.Response) (PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyResponse, error) { + result := PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RequestHeaderNestedResponseBodyResponse); err != nil { + return PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyResponse{}, err + } + return result, nil +} + +// - options - PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseBodyOptions contains the optional parameters +// for the PageableServerDrivenPaginationContinuationTokenClient.NewRequestHeaderResponseBodyPager method. +func (client *PageableServerDrivenPaginationContinuationTokenClient) NewRequestHeaderResponseBodyPager(options *PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseBodyOptions) *runtime.Pager[PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseBodyResponse] { + return runtime.NewPager(runtime.PagingHandler[PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseBodyResponse]{ + More: func(page PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseBodyResponse) bool { + return page.NextToken != nil && len(*page.NextToken) > 0 + }, + Fetcher: func(ctx context.Context, page *PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseBodyResponse) (PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseBodyResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PageableServerDrivenPaginationContinuationTokenClient.NewRequestHeaderResponseBodyPager") + nextOpts := PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseBodyOptions{} + if options != nil { + nextOpts = *options + } + if page != nil { + nextOpts.Token = page.NextToken + } + req, err := client.requestHeaderResponseBodyCreateRequest(ctx, &nextOpts) + if err != nil { + return PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseBodyResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseBodyResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseBodyResponse{}, runtime.NewResponseError(resp) + } + return client.requestHeaderResponseBodyHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// requestHeaderResponseBodyCreateRequest creates the RequestHeaderResponseBody request. +func (client *PageableServerDrivenPaginationContinuationTokenClient) requestHeaderResponseBodyCreateRequest(ctx context.Context, options *PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseBodyOptions) (*policy.Request, error) { + urlPath := "/payload/pageable/server-driven-pagination/continuationtoken/request-header-response-body" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Bar != nil { + reqQP.Set("bar", *options.Bar) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.Foo != nil { + req.Raw().Header["foo"] = []string{*options.Foo} + } + if options != nil && options.Token != nil { + req.Raw().Header["token"] = []string{*options.Token} + } + return req, nil +} + +// requestHeaderResponseBodyHandleResponse handles the RequestHeaderResponseBody response. +func (client *PageableServerDrivenPaginationContinuationTokenClient) requestHeaderResponseBodyHandleResponse(resp *http.Response) (PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseBodyResponse, error) { + result := PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseBodyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RequestHeaderResponseBodyResponse); err != nil { + return PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseBodyResponse{}, err + } + return result, nil +} + +// - options - PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseHeaderOptions contains the optional +// parameters for the PageableServerDrivenPaginationContinuationTokenClient.NewRequestHeaderResponseHeaderPager method. +func (client *PageableServerDrivenPaginationContinuationTokenClient) NewRequestHeaderResponseHeaderPager(options *PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseHeaderOptions) *runtime.Pager[PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseHeaderResponse] { + return runtime.NewPager(runtime.PagingHandler[PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseHeaderResponse]{ + More: func(page PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseHeaderResponse) bool { + return page.NextToken != nil && len(*page.NextToken) > 0 + }, + Fetcher: func(ctx context.Context, page *PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseHeaderResponse) (PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseHeaderResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PageableServerDrivenPaginationContinuationTokenClient.NewRequestHeaderResponseHeaderPager") + nextOpts := PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseHeaderOptions{} + if options != nil { + nextOpts = *options + } + if page != nil { + nextOpts.Token = page.NextToken + } + req, err := client.requestHeaderResponseHeaderCreateRequest(ctx, &nextOpts) + if err != nil { + return PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseHeaderResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseHeaderResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseHeaderResponse{}, runtime.NewResponseError(resp) + } + return client.requestHeaderResponseHeaderHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// requestHeaderResponseHeaderCreateRequest creates the RequestHeaderResponseHeader request. +func (client *PageableServerDrivenPaginationContinuationTokenClient) requestHeaderResponseHeaderCreateRequest(ctx context.Context, options *PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseHeaderOptions) (*policy.Request, error) { + urlPath := "/payload/pageable/server-driven-pagination/continuationtoken/request-header-response-header" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Bar != nil { + reqQP.Set("bar", *options.Bar) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.Foo != nil { + req.Raw().Header["foo"] = []string{*options.Foo} + } + if options != nil && options.Token != nil { + req.Raw().Header["token"] = []string{*options.Token} + } + return req, nil +} + +// requestHeaderResponseHeaderHandleResponse handles the RequestHeaderResponseHeader response. +func (client *PageableServerDrivenPaginationContinuationTokenClient) requestHeaderResponseHeaderHandleResponse(resp *http.Response) (PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseHeaderResponse, error) { + result := PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseHeaderResponse{} + if val := resp.Header.Get("next-token"); val != "" { + result.NextToken = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.RequestHeaderResponseHeaderResponse); err != nil { + return PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseHeaderResponse{}, err + } + return result, nil +} + +// - options - PageableServerDrivenPaginationContinuationTokenClientRequestQueryNestedResponseBodyOptions contains the optional +// parameters for the PageableServerDrivenPaginationContinuationTokenClient.NewRequestQueryNestedResponseBodyPager method. +func (client *PageableServerDrivenPaginationContinuationTokenClient) NewRequestQueryNestedResponseBodyPager(options *PageableServerDrivenPaginationContinuationTokenClientRequestQueryNestedResponseBodyOptions) *runtime.Pager[PageableServerDrivenPaginationContinuationTokenClientRequestQueryNestedResponseBodyResponse] { + return runtime.NewPager(runtime.PagingHandler[PageableServerDrivenPaginationContinuationTokenClientRequestQueryNestedResponseBodyResponse]{ + More: func(page PageableServerDrivenPaginationContinuationTokenClientRequestQueryNestedResponseBodyResponse) bool { + return page.NestedNext != nil && page.NestedNext.NextToken != nil && len(*page.NestedNext.NextToken) > 0 + }, + Fetcher: func(ctx context.Context, page *PageableServerDrivenPaginationContinuationTokenClientRequestQueryNestedResponseBodyResponse) (PageableServerDrivenPaginationContinuationTokenClientRequestQueryNestedResponseBodyResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PageableServerDrivenPaginationContinuationTokenClient.NewRequestQueryNestedResponseBodyPager") + nextOpts := PageableServerDrivenPaginationContinuationTokenClientRequestQueryNestedResponseBodyOptions{} + if options != nil { + nextOpts = *options + } + if page != nil && page.NestedNext != nil { + nextOpts.Token = page.NestedNext.NextToken + } + req, err := client.requestQueryNestedResponseBodyCreateRequest(ctx, &nextOpts) + if err != nil { + return PageableServerDrivenPaginationContinuationTokenClientRequestQueryNestedResponseBodyResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PageableServerDrivenPaginationContinuationTokenClientRequestQueryNestedResponseBodyResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PageableServerDrivenPaginationContinuationTokenClientRequestQueryNestedResponseBodyResponse{}, runtime.NewResponseError(resp) + } + return client.requestQueryNestedResponseBodyHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// requestQueryNestedResponseBodyCreateRequest creates the RequestQueryNestedResponseBody request. +func (client *PageableServerDrivenPaginationContinuationTokenClient) requestQueryNestedResponseBodyCreateRequest(ctx context.Context, options *PageableServerDrivenPaginationContinuationTokenClientRequestQueryNestedResponseBodyOptions) (*policy.Request, error) { + urlPath := "/payload/pageable/server-driven-pagination/continuationtoken/request-query-nested-response-body" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Bar != nil { + reqQP.Set("bar", *options.Bar) + } + if options != nil && options.Token != nil { + reqQP.Set("token", *options.Token) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.Foo != nil { + req.Raw().Header["foo"] = []string{*options.Foo} + } + return req, nil +} + +// requestQueryNestedResponseBodyHandleResponse handles the RequestQueryNestedResponseBody response. +func (client *PageableServerDrivenPaginationContinuationTokenClient) requestQueryNestedResponseBodyHandleResponse(resp *http.Response) (PageableServerDrivenPaginationContinuationTokenClientRequestQueryNestedResponseBodyResponse, error) { + result := PageableServerDrivenPaginationContinuationTokenClientRequestQueryNestedResponseBodyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RequestQueryNestedResponseBodyResponse); err != nil { + return PageableServerDrivenPaginationContinuationTokenClientRequestQueryNestedResponseBodyResponse{}, err + } + return result, nil +} + +// - options - PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseBodyOptions contains the optional parameters +// for the PageableServerDrivenPaginationContinuationTokenClient.NewRequestQueryResponseBodyPager method. +func (client *PageableServerDrivenPaginationContinuationTokenClient) NewRequestQueryResponseBodyPager(options *PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseBodyOptions) *runtime.Pager[PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseBodyResponse] { + return runtime.NewPager(runtime.PagingHandler[PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseBodyResponse]{ + More: func(page PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseBodyResponse) bool { + return page.NextToken != nil && len(*page.NextToken) > 0 + }, + Fetcher: func(ctx context.Context, page *PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseBodyResponse) (PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseBodyResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PageableServerDrivenPaginationContinuationTokenClient.NewRequestQueryResponseBodyPager") + nextOpts := PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseBodyOptions{} + if options != nil { + nextOpts = *options + } + if page != nil { + nextOpts.Token = page.NextToken + } + req, err := client.requestQueryResponseBodyCreateRequest(ctx, &nextOpts) + if err != nil { + return PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseBodyResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseBodyResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseBodyResponse{}, runtime.NewResponseError(resp) + } + return client.requestQueryResponseBodyHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// requestQueryResponseBodyCreateRequest creates the RequestQueryResponseBody request. +func (client *PageableServerDrivenPaginationContinuationTokenClient) requestQueryResponseBodyCreateRequest(ctx context.Context, options *PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseBodyOptions) (*policy.Request, error) { + urlPath := "/payload/pageable/server-driven-pagination/continuationtoken/request-query-response-body" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Bar != nil { + reqQP.Set("bar", *options.Bar) + } + if options != nil && options.Token != nil { + reqQP.Set("token", *options.Token) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.Foo != nil { + req.Raw().Header["foo"] = []string{*options.Foo} + } + return req, nil +} + +// requestQueryResponseBodyHandleResponse handles the RequestQueryResponseBody response. +func (client *PageableServerDrivenPaginationContinuationTokenClient) requestQueryResponseBodyHandleResponse(resp *http.Response) (PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseBodyResponse, error) { + result := PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseBodyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RequestQueryResponseBodyResponse); err != nil { + return PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseBodyResponse{}, err + } + return result, nil +} + +// - options - PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseHeaderOptions contains the optional +// parameters for the PageableServerDrivenPaginationContinuationTokenClient.NewRequestQueryResponseHeaderPager method. +func (client *PageableServerDrivenPaginationContinuationTokenClient) NewRequestQueryResponseHeaderPager(options *PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseHeaderOptions) *runtime.Pager[PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseHeaderResponse] { + return runtime.NewPager(runtime.PagingHandler[PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseHeaderResponse]{ + More: func(page PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseHeaderResponse) bool { + return page.NextToken != nil && len(*page.NextToken) > 0 + }, + Fetcher: func(ctx context.Context, page *PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseHeaderResponse) (PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseHeaderResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PageableServerDrivenPaginationContinuationTokenClient.NewRequestQueryResponseHeaderPager") + nextOpts := PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseHeaderOptions{} + if options != nil { + nextOpts = *options + } + if page != nil { + nextOpts.Token = page.NextToken + } + req, err := client.requestQueryResponseHeaderCreateRequest(ctx, &nextOpts) + if err != nil { + return PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseHeaderResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseHeaderResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseHeaderResponse{}, runtime.NewResponseError(resp) + } + return client.requestQueryResponseHeaderHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// requestQueryResponseHeaderCreateRequest creates the RequestQueryResponseHeader request. +func (client *PageableServerDrivenPaginationContinuationTokenClient) requestQueryResponseHeaderCreateRequest(ctx context.Context, options *PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseHeaderOptions) (*policy.Request, error) { + urlPath := "/payload/pageable/server-driven-pagination/continuationtoken/request-query-response-header" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Bar != nil { + reqQP.Set("bar", *options.Bar) + } + if options != nil && options.Token != nil { + reqQP.Set("token", *options.Token) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.Foo != nil { + req.Raw().Header["foo"] = []string{*options.Foo} + } + return req, nil +} + +// requestQueryResponseHeaderHandleResponse handles the RequestQueryResponseHeader response. +func (client *PageableServerDrivenPaginationContinuationTokenClient) requestQueryResponseHeaderHandleResponse(resp *http.Response) (PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseHeaderResponse, error) { + result := PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseHeaderResponse{} + if val := resp.Header.Get("next-token"); val != "" { + result.NextToken = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.RequestQueryResponseHeaderResponse); err != nil { + return PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseHeaderResponse{}, err + } + return result, nil +} diff --git a/test/http-specs/payload/pageablegroup/zz_pageablexmlpagination_client.go b/test/http-specs/payload/pageablegroup/zz_pageablexmlpagination_client.go new file mode 100644 index 000000000000..6c9080331f66 --- /dev/null +++ b/test/http-specs/payload/pageablegroup/zz_pageablexmlpagination_client.go @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package pageablegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// PageableXMLPaginationClient contains the methods for the PageableXMLPagination group. +// Don't use this type directly, use [PageableClient.NewPageableXMLPaginationClient] instead. +type PageableXMLPaginationClient struct { + internal *azcore.Client + endpoint string +} + +// - options - PageableXMLPaginationClientListWithContinuationOptions contains the optional parameters for the PageableXMLPaginationClient.NewListWithContinuationPager +// method. +func (client *PageableXMLPaginationClient) NewListWithContinuationPager(options *PageableXMLPaginationClientListWithContinuationOptions) *runtime.Pager[PageableXMLPaginationClientListWithContinuationResponse] { + return runtime.NewPager(runtime.PagingHandler[PageableXMLPaginationClientListWithContinuationResponse]{ + More: func(page PageableXMLPaginationClientListWithContinuationResponse) bool { + return page.NextMarker != nil && len(*page.NextMarker) > 0 + }, + Fetcher: func(ctx context.Context, page *PageableXMLPaginationClientListWithContinuationResponse) (PageableXMLPaginationClientListWithContinuationResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PageableXMLPaginationClient.NewListWithContinuationPager") + nextOpts := PageableXMLPaginationClientListWithContinuationOptions{} + if options != nil { + nextOpts = *options + } + if page != nil { + nextOpts.Marker = page.NextMarker + } + req, err := client.listWithContinuationCreateRequest(ctx, &nextOpts) + if err != nil { + return PageableXMLPaginationClientListWithContinuationResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PageableXMLPaginationClientListWithContinuationResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PageableXMLPaginationClientListWithContinuationResponse{}, runtime.NewResponseError(resp) + } + return client.listWithContinuationHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listWithContinuationCreateRequest creates the ListWithContinuation request. +func (client *PageableXMLPaginationClient) listWithContinuationCreateRequest(ctx context.Context, options *PageableXMLPaginationClientListWithContinuationOptions) (*policy.Request, error) { + urlPath := "/payload/pageable/xml/list-with-continuation" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Marker != nil { + reqQP.Set("marker", *options.Marker) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// listWithContinuationHandleResponse handles the ListWithContinuation response. +func (client *PageableXMLPaginationClient) listWithContinuationHandleResponse(resp *http.Response) (PageableXMLPaginationClientListWithContinuationResponse, error) { + result := PageableXMLPaginationClientListWithContinuationResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.XMLPetListResult); err != nil { + return PageableXMLPaginationClientListWithContinuationResponse{}, err + } + return result, nil +} + +// - options - PageableXMLPaginationClientListWithNextLinkOptions contains the optional parameters for the PageableXMLPaginationClient.NewListWithNextLinkPager +// method. +func (client *PageableXMLPaginationClient) NewListWithNextLinkPager(options *PageableXMLPaginationClientListWithNextLinkOptions) *runtime.Pager[PageableXMLPaginationClientListWithNextLinkResponse] { + return runtime.NewPager(runtime.PagingHandler[PageableXMLPaginationClientListWithNextLinkResponse]{ + More: func(page PageableXMLPaginationClientListWithNextLinkResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PageableXMLPaginationClientListWithNextLinkResponse) (PageableXMLPaginationClientListWithNextLinkResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PageableXMLPaginationClient.NewListWithNextLinkPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listWithNextLinkCreateRequest(ctx, options) + }, nil) + if err != nil { + return PageableXMLPaginationClientListWithNextLinkResponse{}, err + } + return client.listWithNextLinkHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listWithNextLinkCreateRequest creates the ListWithNextLink request. +func (client *PageableXMLPaginationClient) listWithNextLinkCreateRequest(ctx context.Context, _ *PageableXMLPaginationClientListWithNextLinkOptions) (*policy.Request, error) { + urlPath := "/payload/pageable/xml/list-with-next-link" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// listWithNextLinkHandleResponse handles the ListWithNextLink response. +func (client *PageableXMLPaginationClient) listWithNextLinkHandleResponse(resp *http.Response) (PageableXMLPaginationClientListWithNextLinkResponse, error) { + result := PageableXMLPaginationClientListWithNextLinkResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.XMLPetListResultWithNextLink); err != nil { + return PageableXMLPaginationClientListWithNextLinkResponse{}, err + } + return result, nil +} diff --git a/test/http-specs/payload/pageablegroup/zz_responses.go b/test/http-specs/payload/pageablegroup/zz_responses.go new file mode 100644 index 000000000000..bef883b6db66 --- /dev/null +++ b/test/http-specs/payload/pageablegroup/zz_responses.go @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package pageablegroup + +// PageablePageSizeClientListWithPageSizeResponse contains the response from method PageablePageSizeClient.NewListWithPageSizePager. +type PageablePageSizeClientListWithPageSizeResponse struct { + ListWithPageSizeResponse +} + +// PageablePageSizeClientListWithoutContinuationResponse contains the response from method PageablePageSizeClient.NewListWithoutContinuationPager. +type PageablePageSizeClientListWithoutContinuationResponse struct { + ListWithoutContinuationResponse +} + +// PageableServerDrivenPaginationAlternateInitialVerbClientPostResponse contains the response from method PageableServerDrivenPaginationAlternateInitialVerbClient.NewPostPager. +type PageableServerDrivenPaginationAlternateInitialVerbClientPostResponse struct { + PostResponse +} + +// PageableServerDrivenPaginationClientLinkResponse contains the response from method PageableServerDrivenPaginationClient.NewLinkPager. +type PageableServerDrivenPaginationClientLinkResponse struct { + LinkResponse +} + +// PageableServerDrivenPaginationClientLinkStringResponse contains the response from method PageableServerDrivenPaginationClient.NewLinkStringPager. +type PageableServerDrivenPaginationClientLinkStringResponse struct { + LinkStringResponse +} + +// PageableServerDrivenPaginationClientNestedLinkResponse contains the response from method PageableServerDrivenPaginationClient.NewNestedLinkPager. +type PageableServerDrivenPaginationClientNestedLinkResponse struct { + NestedLinkResponse +} + +// PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyResponse contains the response from +// method PageableServerDrivenPaginationContinuationTokenClient.NewRequestHeaderNestedResponseBodyPager. +type PageableServerDrivenPaginationContinuationTokenClientRequestHeaderNestedResponseBodyResponse struct { + RequestHeaderNestedResponseBodyResponse +} + +// PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseBodyResponse contains the response from method +// PageableServerDrivenPaginationContinuationTokenClient.NewRequestHeaderResponseBodyPager. +type PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseBodyResponse struct { + RequestHeaderResponseBodyResponse +} + +// PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseHeaderResponse contains the response from method +// PageableServerDrivenPaginationContinuationTokenClient.NewRequestHeaderResponseHeaderPager. +type PageableServerDrivenPaginationContinuationTokenClientRequestHeaderResponseHeaderResponse struct { + RequestHeaderResponseHeaderResponse + NextToken *string +} + +// PageableServerDrivenPaginationContinuationTokenClientRequestQueryNestedResponseBodyResponse contains the response from +// method PageableServerDrivenPaginationContinuationTokenClient.NewRequestQueryNestedResponseBodyPager. +type PageableServerDrivenPaginationContinuationTokenClientRequestQueryNestedResponseBodyResponse struct { + RequestQueryNestedResponseBodyResponse +} + +// PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseBodyResponse contains the response from method +// PageableServerDrivenPaginationContinuationTokenClient.NewRequestQueryResponseBodyPager. +type PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseBodyResponse struct { + RequestQueryResponseBodyResponse +} + +// PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseHeaderResponse contains the response from method +// PageableServerDrivenPaginationContinuationTokenClient.NewRequestQueryResponseHeaderPager. +type PageableServerDrivenPaginationContinuationTokenClientRequestQueryResponseHeaderResponse struct { + RequestQueryResponseHeaderResponse + NextToken *string +} + +// PageableXMLPaginationClientListWithContinuationResponse contains the response from method PageableXMLPaginationClient.NewListWithContinuationPager. +type PageableXMLPaginationClientListWithContinuationResponse struct { + // The XML response for listing pets. + XMLPetListResult +} + +// PageableXMLPaginationClientListWithNextLinkResponse contains the response from method PageableXMLPaginationClient.NewListWithNextLinkPager. +type PageableXMLPaginationClientListWithNextLinkResponse struct { + // The XML response for listing pets with next link. + XMLPetListResultWithNextLink +} diff --git a/test/http-specs/payload/pageablegroup/zz_version.go b/test/http-specs/payload/pageablegroup/zz_version.go new file mode 100644 index 000000000000..893c5de20824 --- /dev/null +++ b/test/http-specs/payload/pageablegroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package pageablegroup + +const ( + moduleName = "pageablegroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/payload/xmlgroup/LICENSE.txt b/test/http-specs/payload/xmlgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/payload/xmlgroup/fake/zz_internal.go b/test/http-specs/payload/xmlgroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/http-specs/payload/xmlgroup/fake/zz_xml_server.go b/test/http-specs/payload/xmlgroup/fake/zz_xml_server.go new file mode 100644 index 000000000000..68737e82d455 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_xml_server.go @@ -0,0 +1,294 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// XMLServer is a fake server for instances of the xmlgroup.XMLClient type. +type XMLServer struct { + // XMLModelWithArrayOfModelValueServer contains the fakes for client XMLModelWithArrayOfModelValueClient + XMLModelWithArrayOfModelValueServer XMLModelWithArrayOfModelValueServer + + // XMLModelWithAttributesValueServer contains the fakes for client XMLModelWithAttributesValueClient + XMLModelWithAttributesValueServer XMLModelWithAttributesValueServer + + // XMLModelWithDatetimeValueServer contains the fakes for client XMLModelWithDatetimeValueClient + XMLModelWithDatetimeValueServer XMLModelWithDatetimeValueServer + + // XMLModelWithDictionaryValueServer contains the fakes for client XMLModelWithDictionaryValueClient + XMLModelWithDictionaryValueServer XMLModelWithDictionaryValueServer + + // XMLModelWithEmptyArrayValueServer contains the fakes for client XMLModelWithEmptyArrayValueClient + XMLModelWithEmptyArrayValueServer XMLModelWithEmptyArrayValueServer + + // XMLModelWithEncodedNamesValueServer contains the fakes for client XMLModelWithEncodedNamesValueClient + XMLModelWithEncodedNamesValueServer XMLModelWithEncodedNamesValueServer + + // XMLModelWithEnumValueServer contains the fakes for client XMLModelWithEnumValueClient + XMLModelWithEnumValueServer XMLModelWithEnumValueServer + + // XMLModelWithNamespaceOnPropertiesValueServer contains the fakes for client XMLModelWithNamespaceOnPropertiesValueClient + XMLModelWithNamespaceOnPropertiesValueServer XMLModelWithNamespaceOnPropertiesValueServer + + // XMLModelWithNamespaceValueServer contains the fakes for client XMLModelWithNamespaceValueClient + XMLModelWithNamespaceValueServer XMLModelWithNamespaceValueServer + + // XMLModelWithNestedModelValueServer contains the fakes for client XMLModelWithNestedModelValueClient + XMLModelWithNestedModelValueServer XMLModelWithNestedModelValueServer + + // XMLModelWithOptionalFieldValueServer contains the fakes for client XMLModelWithOptionalFieldValueClient + XMLModelWithOptionalFieldValueServer XMLModelWithOptionalFieldValueServer + + // XMLModelWithRenamedArraysValueServer contains the fakes for client XMLModelWithRenamedArraysValueClient + XMLModelWithRenamedArraysValueServer XMLModelWithRenamedArraysValueServer + + // XMLModelWithRenamedAttributeValueServer contains the fakes for client XMLModelWithRenamedAttributeValueClient + XMLModelWithRenamedAttributeValueServer XMLModelWithRenamedAttributeValueServer + + // XMLModelWithRenamedFieldsValueServer contains the fakes for client XMLModelWithRenamedFieldsValueClient + XMLModelWithRenamedFieldsValueServer XMLModelWithRenamedFieldsValueServer + + // XMLModelWithRenamedNestedModelValueServer contains the fakes for client XMLModelWithRenamedNestedModelValueClient + XMLModelWithRenamedNestedModelValueServer XMLModelWithRenamedNestedModelValueServer + + // XMLModelWithRenamedPropertyValueServer contains the fakes for client XMLModelWithRenamedPropertyValueClient + XMLModelWithRenamedPropertyValueServer XMLModelWithRenamedPropertyValueServer + + // XMLModelWithRenamedUnwrappedModelArrayValueServer contains the fakes for client XMLModelWithRenamedUnwrappedModelArrayValueClient + XMLModelWithRenamedUnwrappedModelArrayValueServer XMLModelWithRenamedUnwrappedModelArrayValueServer + + // XMLModelWithRenamedWrappedAndItemModelArrayValueServer contains the fakes for client XMLModelWithRenamedWrappedAndItemModelArrayValueClient + XMLModelWithRenamedWrappedAndItemModelArrayValueServer XMLModelWithRenamedWrappedAndItemModelArrayValueServer + + // XMLModelWithRenamedWrappedModelArrayValueServer contains the fakes for client XMLModelWithRenamedWrappedModelArrayValueClient + XMLModelWithRenamedWrappedModelArrayValueServer XMLModelWithRenamedWrappedModelArrayValueServer + + // XMLModelWithSimpleArraysValueServer contains the fakes for client XMLModelWithSimpleArraysValueClient + XMLModelWithSimpleArraysValueServer XMLModelWithSimpleArraysValueServer + + // XMLModelWithTextValueServer contains the fakes for client XMLModelWithTextValueClient + XMLModelWithTextValueServer XMLModelWithTextValueServer + + // XMLModelWithUnwrappedArrayValueServer contains the fakes for client XMLModelWithUnwrappedArrayValueClient + XMLModelWithUnwrappedArrayValueServer XMLModelWithUnwrappedArrayValueServer + + // XMLModelWithUnwrappedModelArrayValueServer contains the fakes for client XMLModelWithUnwrappedModelArrayValueClient + XMLModelWithUnwrappedModelArrayValueServer XMLModelWithUnwrappedModelArrayValueServer + + // XMLModelWithWrappedPrimitiveCustomItemNamesValueServer contains the fakes for client XMLModelWithWrappedPrimitiveCustomItemNamesValueClient + XMLModelWithWrappedPrimitiveCustomItemNamesValueServer XMLModelWithWrappedPrimitiveCustomItemNamesValueServer + + // XMLSimpleModelValueServer contains the fakes for client XMLSimpleModelValueClient + XMLSimpleModelValueServer XMLSimpleModelValueServer + + // XMLXMLErrorValueServer contains the fakes for client XMLXMLErrorValueClient + XMLXMLErrorValueServer XMLXMLErrorValueServer +} + +// NewXMLServerTransport creates a new instance of XMLServerTransport with the provided implementation. +// The returned XMLServerTransport instance is connected to an instance of xmlgroup.XMLClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMLServerTransport(srv *XMLServer) *XMLServerTransport { + return &XMLServerTransport{srv: srv} +} + +// XMLServerTransport connects instances of xmlgroup.XMLClient to instances of XMLServer. +// Don't use this type directly, use NewXMLServerTransport instead. +type XMLServerTransport struct { + srv *XMLServer + trMu sync.Mutex + trXMLModelWithArrayOfModelValueServer *XMLModelWithArrayOfModelValueServerTransport + trXMLModelWithAttributesValueServer *XMLModelWithAttributesValueServerTransport + trXMLModelWithDatetimeValueServer *XMLModelWithDatetimeValueServerTransport + trXMLModelWithDictionaryValueServer *XMLModelWithDictionaryValueServerTransport + trXMLModelWithEmptyArrayValueServer *XMLModelWithEmptyArrayValueServerTransport + trXMLModelWithEncodedNamesValueServer *XMLModelWithEncodedNamesValueServerTransport + trXMLModelWithEnumValueServer *XMLModelWithEnumValueServerTransport + trXMLModelWithNamespaceOnPropertiesValueServer *XMLModelWithNamespaceOnPropertiesValueServerTransport + trXMLModelWithNamespaceValueServer *XMLModelWithNamespaceValueServerTransport + trXMLModelWithNestedModelValueServer *XMLModelWithNestedModelValueServerTransport + trXMLModelWithOptionalFieldValueServer *XMLModelWithOptionalFieldValueServerTransport + trXMLModelWithRenamedArraysValueServer *XMLModelWithRenamedArraysValueServerTransport + trXMLModelWithRenamedAttributeValueServer *XMLModelWithRenamedAttributeValueServerTransport + trXMLModelWithRenamedFieldsValueServer *XMLModelWithRenamedFieldsValueServerTransport + trXMLModelWithRenamedNestedModelValueServer *XMLModelWithRenamedNestedModelValueServerTransport + trXMLModelWithRenamedPropertyValueServer *XMLModelWithRenamedPropertyValueServerTransport + trXMLModelWithRenamedUnwrappedModelArrayValueServer *XMLModelWithRenamedUnwrappedModelArrayValueServerTransport + trXMLModelWithRenamedWrappedAndItemModelArrayValueServer *XMLModelWithRenamedWrappedAndItemModelArrayValueServerTransport + trXMLModelWithRenamedWrappedModelArrayValueServer *XMLModelWithRenamedWrappedModelArrayValueServerTransport + trXMLModelWithSimpleArraysValueServer *XMLModelWithSimpleArraysValueServerTransport + trXMLModelWithTextValueServer *XMLModelWithTextValueServerTransport + trXMLModelWithUnwrappedArrayValueServer *XMLModelWithUnwrappedArrayValueServerTransport + trXMLModelWithUnwrappedModelArrayValueServer *XMLModelWithUnwrappedModelArrayValueServerTransport + trXMLModelWithWrappedPrimitiveCustomItemNamesValueServer *XMLModelWithWrappedPrimitiveCustomItemNamesValueServerTransport + trXMLSimpleModelValueServer *XMLSimpleModelValueServerTransport + trXMLXMLErrorValueServer *XMLXMLErrorValueServerTransport +} + +// Do implements the policy.Transporter interface for XMLServerTransport. +func (x *XMLServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (x *XMLServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "XMLModelWithArrayOfModelValueClient": + initServer(&x.trMu, &x.trXMLModelWithArrayOfModelValueServer, func() *XMLModelWithArrayOfModelValueServerTransport { + return NewXMLModelWithArrayOfModelValueServerTransport(&x.srv.XMLModelWithArrayOfModelValueServer) + }) + resp, err = x.trXMLModelWithArrayOfModelValueServer.Do(req) + case "XMLModelWithAttributesValueClient": + initServer(&x.trMu, &x.trXMLModelWithAttributesValueServer, func() *XMLModelWithAttributesValueServerTransport { + return NewXMLModelWithAttributesValueServerTransport(&x.srv.XMLModelWithAttributesValueServer) + }) + resp, err = x.trXMLModelWithAttributesValueServer.Do(req) + case "XMLModelWithDatetimeValueClient": + initServer(&x.trMu, &x.trXMLModelWithDatetimeValueServer, func() *XMLModelWithDatetimeValueServerTransport { + return NewXMLModelWithDatetimeValueServerTransport(&x.srv.XMLModelWithDatetimeValueServer) + }) + resp, err = x.trXMLModelWithDatetimeValueServer.Do(req) + case "XMLModelWithDictionaryValueClient": + initServer(&x.trMu, &x.trXMLModelWithDictionaryValueServer, func() *XMLModelWithDictionaryValueServerTransport { + return NewXMLModelWithDictionaryValueServerTransport(&x.srv.XMLModelWithDictionaryValueServer) + }) + resp, err = x.trXMLModelWithDictionaryValueServer.Do(req) + case "XMLModelWithEmptyArrayValueClient": + initServer(&x.trMu, &x.trXMLModelWithEmptyArrayValueServer, func() *XMLModelWithEmptyArrayValueServerTransport { + return NewXMLModelWithEmptyArrayValueServerTransport(&x.srv.XMLModelWithEmptyArrayValueServer) + }) + resp, err = x.trXMLModelWithEmptyArrayValueServer.Do(req) + case "XMLModelWithEncodedNamesValueClient": + initServer(&x.trMu, &x.trXMLModelWithEncodedNamesValueServer, func() *XMLModelWithEncodedNamesValueServerTransport { + return NewXMLModelWithEncodedNamesValueServerTransport(&x.srv.XMLModelWithEncodedNamesValueServer) + }) + resp, err = x.trXMLModelWithEncodedNamesValueServer.Do(req) + case "XMLModelWithEnumValueClient": + initServer(&x.trMu, &x.trXMLModelWithEnumValueServer, func() *XMLModelWithEnumValueServerTransport { + return NewXMLModelWithEnumValueServerTransport(&x.srv.XMLModelWithEnumValueServer) + }) + resp, err = x.trXMLModelWithEnumValueServer.Do(req) + case "XMLModelWithNamespaceOnPropertiesValueClient": + initServer(&x.trMu, &x.trXMLModelWithNamespaceOnPropertiesValueServer, func() *XMLModelWithNamespaceOnPropertiesValueServerTransport { + return NewXMLModelWithNamespaceOnPropertiesValueServerTransport(&x.srv.XMLModelWithNamespaceOnPropertiesValueServer) + }) + resp, err = x.trXMLModelWithNamespaceOnPropertiesValueServer.Do(req) + case "XMLModelWithNamespaceValueClient": + initServer(&x.trMu, &x.trXMLModelWithNamespaceValueServer, func() *XMLModelWithNamespaceValueServerTransport { + return NewXMLModelWithNamespaceValueServerTransport(&x.srv.XMLModelWithNamespaceValueServer) + }) + resp, err = x.trXMLModelWithNamespaceValueServer.Do(req) + case "XMLModelWithNestedModelValueClient": + initServer(&x.trMu, &x.trXMLModelWithNestedModelValueServer, func() *XMLModelWithNestedModelValueServerTransport { + return NewXMLModelWithNestedModelValueServerTransport(&x.srv.XMLModelWithNestedModelValueServer) + }) + resp, err = x.trXMLModelWithNestedModelValueServer.Do(req) + case "XMLModelWithOptionalFieldValueClient": + initServer(&x.trMu, &x.trXMLModelWithOptionalFieldValueServer, func() *XMLModelWithOptionalFieldValueServerTransport { + return NewXMLModelWithOptionalFieldValueServerTransport(&x.srv.XMLModelWithOptionalFieldValueServer) + }) + resp, err = x.trXMLModelWithOptionalFieldValueServer.Do(req) + case "XMLModelWithRenamedArraysValueClient": + initServer(&x.trMu, &x.trXMLModelWithRenamedArraysValueServer, func() *XMLModelWithRenamedArraysValueServerTransport { + return NewXMLModelWithRenamedArraysValueServerTransport(&x.srv.XMLModelWithRenamedArraysValueServer) + }) + resp, err = x.trXMLModelWithRenamedArraysValueServer.Do(req) + case "XMLModelWithRenamedAttributeValueClient": + initServer(&x.trMu, &x.trXMLModelWithRenamedAttributeValueServer, func() *XMLModelWithRenamedAttributeValueServerTransport { + return NewXMLModelWithRenamedAttributeValueServerTransport(&x.srv.XMLModelWithRenamedAttributeValueServer) + }) + resp, err = x.trXMLModelWithRenamedAttributeValueServer.Do(req) + case "XMLModelWithRenamedFieldsValueClient": + initServer(&x.trMu, &x.trXMLModelWithRenamedFieldsValueServer, func() *XMLModelWithRenamedFieldsValueServerTransport { + return NewXMLModelWithRenamedFieldsValueServerTransport(&x.srv.XMLModelWithRenamedFieldsValueServer) + }) + resp, err = x.trXMLModelWithRenamedFieldsValueServer.Do(req) + case "XMLModelWithRenamedNestedModelValueClient": + initServer(&x.trMu, &x.trXMLModelWithRenamedNestedModelValueServer, func() *XMLModelWithRenamedNestedModelValueServerTransport { + return NewXMLModelWithRenamedNestedModelValueServerTransport(&x.srv.XMLModelWithRenamedNestedModelValueServer) + }) + resp, err = x.trXMLModelWithRenamedNestedModelValueServer.Do(req) + case "XMLModelWithRenamedPropertyValueClient": + initServer(&x.trMu, &x.trXMLModelWithRenamedPropertyValueServer, func() *XMLModelWithRenamedPropertyValueServerTransport { + return NewXMLModelWithRenamedPropertyValueServerTransport(&x.srv.XMLModelWithRenamedPropertyValueServer) + }) + resp, err = x.trXMLModelWithRenamedPropertyValueServer.Do(req) + case "XMLModelWithRenamedUnwrappedModelArrayValueClient": + initServer(&x.trMu, &x.trXMLModelWithRenamedUnwrappedModelArrayValueServer, func() *XMLModelWithRenamedUnwrappedModelArrayValueServerTransport { + return NewXMLModelWithRenamedUnwrappedModelArrayValueServerTransport(&x.srv.XMLModelWithRenamedUnwrappedModelArrayValueServer) + }) + resp, err = x.trXMLModelWithRenamedUnwrappedModelArrayValueServer.Do(req) + case "XMLModelWithRenamedWrappedAndItemModelArrayValueClient": + initServer(&x.trMu, &x.trXMLModelWithRenamedWrappedAndItemModelArrayValueServer, func() *XMLModelWithRenamedWrappedAndItemModelArrayValueServerTransport { + return NewXMLModelWithRenamedWrappedAndItemModelArrayValueServerTransport(&x.srv.XMLModelWithRenamedWrappedAndItemModelArrayValueServer) + }) + resp, err = x.trXMLModelWithRenamedWrappedAndItemModelArrayValueServer.Do(req) + case "XMLModelWithRenamedWrappedModelArrayValueClient": + initServer(&x.trMu, &x.trXMLModelWithRenamedWrappedModelArrayValueServer, func() *XMLModelWithRenamedWrappedModelArrayValueServerTransport { + return NewXMLModelWithRenamedWrappedModelArrayValueServerTransport(&x.srv.XMLModelWithRenamedWrappedModelArrayValueServer) + }) + resp, err = x.trXMLModelWithRenamedWrappedModelArrayValueServer.Do(req) + case "XMLModelWithSimpleArraysValueClient": + initServer(&x.trMu, &x.trXMLModelWithSimpleArraysValueServer, func() *XMLModelWithSimpleArraysValueServerTransport { + return NewXMLModelWithSimpleArraysValueServerTransport(&x.srv.XMLModelWithSimpleArraysValueServer) + }) + resp, err = x.trXMLModelWithSimpleArraysValueServer.Do(req) + case "XMLModelWithTextValueClient": + initServer(&x.trMu, &x.trXMLModelWithTextValueServer, func() *XMLModelWithTextValueServerTransport { + return NewXMLModelWithTextValueServerTransport(&x.srv.XMLModelWithTextValueServer) + }) + resp, err = x.trXMLModelWithTextValueServer.Do(req) + case "XMLModelWithUnwrappedArrayValueClient": + initServer(&x.trMu, &x.trXMLModelWithUnwrappedArrayValueServer, func() *XMLModelWithUnwrappedArrayValueServerTransport { + return NewXMLModelWithUnwrappedArrayValueServerTransport(&x.srv.XMLModelWithUnwrappedArrayValueServer) + }) + resp, err = x.trXMLModelWithUnwrappedArrayValueServer.Do(req) + case "XMLModelWithUnwrappedModelArrayValueClient": + initServer(&x.trMu, &x.trXMLModelWithUnwrappedModelArrayValueServer, func() *XMLModelWithUnwrappedModelArrayValueServerTransport { + return NewXMLModelWithUnwrappedModelArrayValueServerTransport(&x.srv.XMLModelWithUnwrappedModelArrayValueServer) + }) + resp, err = x.trXMLModelWithUnwrappedModelArrayValueServer.Do(req) + case "XMLModelWithWrappedPrimitiveCustomItemNamesValueClient": + initServer(&x.trMu, &x.trXMLModelWithWrappedPrimitiveCustomItemNamesValueServer, func() *XMLModelWithWrappedPrimitiveCustomItemNamesValueServerTransport { + return NewXMLModelWithWrappedPrimitiveCustomItemNamesValueServerTransport(&x.srv.XMLModelWithWrappedPrimitiveCustomItemNamesValueServer) + }) + resp, err = x.trXMLModelWithWrappedPrimitiveCustomItemNamesValueServer.Do(req) + case "XMLSimpleModelValueClient": + initServer(&x.trMu, &x.trXMLSimpleModelValueServer, func() *XMLSimpleModelValueServerTransport { + return NewXMLSimpleModelValueServerTransport(&x.srv.XMLSimpleModelValueServer) + }) + resp, err = x.trXMLSimpleModelValueServer.Do(req) + case "XMLXMLErrorValueClient": + initServer(&x.trMu, &x.trXMLXMLErrorValueServer, func() *XMLXMLErrorValueServerTransport { + return NewXMLXMLErrorValueServerTransport(&x.srv.XMLXMLErrorValueServer) + }) + resp, err = x.trXMLXMLErrorValueServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to XMLServerTransport +var xmlServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwitharrayofmodelvalue_server.go b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwitharrayofmodelvalue_server.go new file mode 100644 index 000000000000..205d1ef84418 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwitharrayofmodelvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "xmlgroup" +) + +// XMLModelWithArrayOfModelValueServer is a fake server for instances of the xmlgroup.XMLModelWithArrayOfModelValueClient type. +type XMLModelWithArrayOfModelValueServer struct { + // Get is the fake for method XMLModelWithArrayOfModelValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *xmlgroup.XMLModelWithArrayOfModelValueClientGetOptions) (resp azfake.Responder[xmlgroup.XMLModelWithArrayOfModelValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method XMLModelWithArrayOfModelValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, input xmlgroup.ModelWithArrayOfModel, options *xmlgroup.XMLModelWithArrayOfModelValueClientPutOptions) (resp azfake.Responder[xmlgroup.XMLModelWithArrayOfModelValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewXMLModelWithArrayOfModelValueServerTransport creates a new instance of XMLModelWithArrayOfModelValueServerTransport with the provided implementation. +// The returned XMLModelWithArrayOfModelValueServerTransport instance is connected to an instance of xmlgroup.XMLModelWithArrayOfModelValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMLModelWithArrayOfModelValueServerTransport(srv *XMLModelWithArrayOfModelValueServer) *XMLModelWithArrayOfModelValueServerTransport { + return &XMLModelWithArrayOfModelValueServerTransport{srv: srv} +} + +// XMLModelWithArrayOfModelValueServerTransport connects instances of xmlgroup.XMLModelWithArrayOfModelValueClient to instances of XMLModelWithArrayOfModelValueServer. +// Don't use this type directly, use NewXMLModelWithArrayOfModelValueServerTransport instead. +type XMLModelWithArrayOfModelValueServerTransport struct { + srv *XMLModelWithArrayOfModelValueServer +} + +// Do implements the policy.Transporter interface for XMLModelWithArrayOfModelValueServerTransport. +func (x *XMLModelWithArrayOfModelValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToMethodFake(req, method) +} + +func (x *XMLModelWithArrayOfModelValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if xmlModelWithArrayOfModelValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = xmlModelWithArrayOfModelValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "XMLModelWithArrayOfModelValueClient.Get": + res.resp, res.err = x.dispatchGet(req) + case "XMLModelWithArrayOfModelValueClient.Put": + res.resp, res.err = x.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (x *XMLModelWithArrayOfModelValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if x.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := x.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr).ModelWithArrayOfModel, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (x *XMLModelWithArrayOfModelValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if x.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsXML[xmlgroup.ModelWithArrayOfModel](req) + if err != nil { + return nil, err + } + respr, errRespr := x.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to XMLModelWithArrayOfModelValueServerTransport +var xmlModelWithArrayOfModelValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithattributesvalue_server.go b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithattributesvalue_server.go new file mode 100644 index 000000000000..fee93726fb39 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithattributesvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "xmlgroup" +) + +// XMLModelWithAttributesValueServer is a fake server for instances of the xmlgroup.XMLModelWithAttributesValueClient type. +type XMLModelWithAttributesValueServer struct { + // Get is the fake for method XMLModelWithAttributesValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *xmlgroup.XMLModelWithAttributesValueClientGetOptions) (resp azfake.Responder[xmlgroup.XMLModelWithAttributesValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method XMLModelWithAttributesValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, input xmlgroup.ModelWithAttributes, options *xmlgroup.XMLModelWithAttributesValueClientPutOptions) (resp azfake.Responder[xmlgroup.XMLModelWithAttributesValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewXMLModelWithAttributesValueServerTransport creates a new instance of XMLModelWithAttributesValueServerTransport with the provided implementation. +// The returned XMLModelWithAttributesValueServerTransport instance is connected to an instance of xmlgroup.XMLModelWithAttributesValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMLModelWithAttributesValueServerTransport(srv *XMLModelWithAttributesValueServer) *XMLModelWithAttributesValueServerTransport { + return &XMLModelWithAttributesValueServerTransport{srv: srv} +} + +// XMLModelWithAttributesValueServerTransport connects instances of xmlgroup.XMLModelWithAttributesValueClient to instances of XMLModelWithAttributesValueServer. +// Don't use this type directly, use NewXMLModelWithAttributesValueServerTransport instead. +type XMLModelWithAttributesValueServerTransport struct { + srv *XMLModelWithAttributesValueServer +} + +// Do implements the policy.Transporter interface for XMLModelWithAttributesValueServerTransport. +func (x *XMLModelWithAttributesValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToMethodFake(req, method) +} + +func (x *XMLModelWithAttributesValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if xmlModelWithAttributesValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = xmlModelWithAttributesValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "XMLModelWithAttributesValueClient.Get": + res.resp, res.err = x.dispatchGet(req) + case "XMLModelWithAttributesValueClient.Put": + res.resp, res.err = x.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (x *XMLModelWithAttributesValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if x.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := x.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr).ModelWithAttributes, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (x *XMLModelWithAttributesValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if x.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsXML[xmlgroup.ModelWithAttributes](req) + if err != nil { + return nil, err + } + respr, errRespr := x.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to XMLModelWithAttributesValueServerTransport +var xmlModelWithAttributesValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithdatetimevalue_server.go b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithdatetimevalue_server.go new file mode 100644 index 000000000000..cd568d5d268a --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithdatetimevalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "xmlgroup" +) + +// XMLModelWithDatetimeValueServer is a fake server for instances of the xmlgroup.XMLModelWithDatetimeValueClient type. +type XMLModelWithDatetimeValueServer struct { + // Get is the fake for method XMLModelWithDatetimeValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *xmlgroup.XMLModelWithDatetimeValueClientGetOptions) (resp azfake.Responder[xmlgroup.XMLModelWithDatetimeValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method XMLModelWithDatetimeValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, input xmlgroup.ModelWithDatetime, options *xmlgroup.XMLModelWithDatetimeValueClientPutOptions) (resp azfake.Responder[xmlgroup.XMLModelWithDatetimeValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewXMLModelWithDatetimeValueServerTransport creates a new instance of XMLModelWithDatetimeValueServerTransport with the provided implementation. +// The returned XMLModelWithDatetimeValueServerTransport instance is connected to an instance of xmlgroup.XMLModelWithDatetimeValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMLModelWithDatetimeValueServerTransport(srv *XMLModelWithDatetimeValueServer) *XMLModelWithDatetimeValueServerTransport { + return &XMLModelWithDatetimeValueServerTransport{srv: srv} +} + +// XMLModelWithDatetimeValueServerTransport connects instances of xmlgroup.XMLModelWithDatetimeValueClient to instances of XMLModelWithDatetimeValueServer. +// Don't use this type directly, use NewXMLModelWithDatetimeValueServerTransport instead. +type XMLModelWithDatetimeValueServerTransport struct { + srv *XMLModelWithDatetimeValueServer +} + +// Do implements the policy.Transporter interface for XMLModelWithDatetimeValueServerTransport. +func (x *XMLModelWithDatetimeValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToMethodFake(req, method) +} + +func (x *XMLModelWithDatetimeValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if xmlModelWithDatetimeValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = xmlModelWithDatetimeValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "XMLModelWithDatetimeValueClient.Get": + res.resp, res.err = x.dispatchGet(req) + case "XMLModelWithDatetimeValueClient.Put": + res.resp, res.err = x.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (x *XMLModelWithDatetimeValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if x.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := x.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr).ModelWithDatetime, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (x *XMLModelWithDatetimeValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if x.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsXML[xmlgroup.ModelWithDatetime](req) + if err != nil { + return nil, err + } + respr, errRespr := x.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to XMLModelWithDatetimeValueServerTransport +var xmlModelWithDatetimeValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithdictionaryvalue_server.go b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithdictionaryvalue_server.go new file mode 100644 index 000000000000..fd0a7cb9c881 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithdictionaryvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "xmlgroup" +) + +// XMLModelWithDictionaryValueServer is a fake server for instances of the xmlgroup.XMLModelWithDictionaryValueClient type. +type XMLModelWithDictionaryValueServer struct { + // Get is the fake for method XMLModelWithDictionaryValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *xmlgroup.XMLModelWithDictionaryValueClientGetOptions) (resp azfake.Responder[xmlgroup.XMLModelWithDictionaryValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method XMLModelWithDictionaryValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, input xmlgroup.ModelWithDictionary, options *xmlgroup.XMLModelWithDictionaryValueClientPutOptions) (resp azfake.Responder[xmlgroup.XMLModelWithDictionaryValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewXMLModelWithDictionaryValueServerTransport creates a new instance of XMLModelWithDictionaryValueServerTransport with the provided implementation. +// The returned XMLModelWithDictionaryValueServerTransport instance is connected to an instance of xmlgroup.XMLModelWithDictionaryValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMLModelWithDictionaryValueServerTransport(srv *XMLModelWithDictionaryValueServer) *XMLModelWithDictionaryValueServerTransport { + return &XMLModelWithDictionaryValueServerTransport{srv: srv} +} + +// XMLModelWithDictionaryValueServerTransport connects instances of xmlgroup.XMLModelWithDictionaryValueClient to instances of XMLModelWithDictionaryValueServer. +// Don't use this type directly, use NewXMLModelWithDictionaryValueServerTransport instead. +type XMLModelWithDictionaryValueServerTransport struct { + srv *XMLModelWithDictionaryValueServer +} + +// Do implements the policy.Transporter interface for XMLModelWithDictionaryValueServerTransport. +func (x *XMLModelWithDictionaryValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToMethodFake(req, method) +} + +func (x *XMLModelWithDictionaryValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if xmlModelWithDictionaryValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = xmlModelWithDictionaryValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "XMLModelWithDictionaryValueClient.Get": + res.resp, res.err = x.dispatchGet(req) + case "XMLModelWithDictionaryValueClient.Put": + res.resp, res.err = x.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (x *XMLModelWithDictionaryValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if x.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := x.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr).ModelWithDictionary, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (x *XMLModelWithDictionaryValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if x.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsXML[xmlgroup.ModelWithDictionary](req) + if err != nil { + return nil, err + } + respr, errRespr := x.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to XMLModelWithDictionaryValueServerTransport +var xmlModelWithDictionaryValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithemptyarrayvalue_server.go b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithemptyarrayvalue_server.go new file mode 100644 index 000000000000..3e80787045cc --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithemptyarrayvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "xmlgroup" +) + +// XMLModelWithEmptyArrayValueServer is a fake server for instances of the xmlgroup.XMLModelWithEmptyArrayValueClient type. +type XMLModelWithEmptyArrayValueServer struct { + // Get is the fake for method XMLModelWithEmptyArrayValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *xmlgroup.XMLModelWithEmptyArrayValueClientGetOptions) (resp azfake.Responder[xmlgroup.XMLModelWithEmptyArrayValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method XMLModelWithEmptyArrayValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, input xmlgroup.ModelWithEmptyArray, options *xmlgroup.XMLModelWithEmptyArrayValueClientPutOptions) (resp azfake.Responder[xmlgroup.XMLModelWithEmptyArrayValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewXMLModelWithEmptyArrayValueServerTransport creates a new instance of XMLModelWithEmptyArrayValueServerTransport with the provided implementation. +// The returned XMLModelWithEmptyArrayValueServerTransport instance is connected to an instance of xmlgroup.XMLModelWithEmptyArrayValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMLModelWithEmptyArrayValueServerTransport(srv *XMLModelWithEmptyArrayValueServer) *XMLModelWithEmptyArrayValueServerTransport { + return &XMLModelWithEmptyArrayValueServerTransport{srv: srv} +} + +// XMLModelWithEmptyArrayValueServerTransport connects instances of xmlgroup.XMLModelWithEmptyArrayValueClient to instances of XMLModelWithEmptyArrayValueServer. +// Don't use this type directly, use NewXMLModelWithEmptyArrayValueServerTransport instead. +type XMLModelWithEmptyArrayValueServerTransport struct { + srv *XMLModelWithEmptyArrayValueServer +} + +// Do implements the policy.Transporter interface for XMLModelWithEmptyArrayValueServerTransport. +func (x *XMLModelWithEmptyArrayValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToMethodFake(req, method) +} + +func (x *XMLModelWithEmptyArrayValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if xmlModelWithEmptyArrayValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = xmlModelWithEmptyArrayValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "XMLModelWithEmptyArrayValueClient.Get": + res.resp, res.err = x.dispatchGet(req) + case "XMLModelWithEmptyArrayValueClient.Put": + res.resp, res.err = x.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (x *XMLModelWithEmptyArrayValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if x.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := x.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr).ModelWithEmptyArray, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (x *XMLModelWithEmptyArrayValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if x.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsXML[xmlgroup.ModelWithEmptyArray](req) + if err != nil { + return nil, err + } + respr, errRespr := x.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to XMLModelWithEmptyArrayValueServerTransport +var xmlModelWithEmptyArrayValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithencodednamesvalue_server.go b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithencodednamesvalue_server.go new file mode 100644 index 000000000000..48f72d364084 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithencodednamesvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "xmlgroup" +) + +// XMLModelWithEncodedNamesValueServer is a fake server for instances of the xmlgroup.XMLModelWithEncodedNamesValueClient type. +type XMLModelWithEncodedNamesValueServer struct { + // Get is the fake for method XMLModelWithEncodedNamesValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *xmlgroup.XMLModelWithEncodedNamesValueClientGetOptions) (resp azfake.Responder[xmlgroup.XMLModelWithEncodedNamesValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method XMLModelWithEncodedNamesValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, input xmlgroup.ModelWithEncodedNames, options *xmlgroup.XMLModelWithEncodedNamesValueClientPutOptions) (resp azfake.Responder[xmlgroup.XMLModelWithEncodedNamesValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewXMLModelWithEncodedNamesValueServerTransport creates a new instance of XMLModelWithEncodedNamesValueServerTransport with the provided implementation. +// The returned XMLModelWithEncodedNamesValueServerTransport instance is connected to an instance of xmlgroup.XMLModelWithEncodedNamesValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMLModelWithEncodedNamesValueServerTransport(srv *XMLModelWithEncodedNamesValueServer) *XMLModelWithEncodedNamesValueServerTransport { + return &XMLModelWithEncodedNamesValueServerTransport{srv: srv} +} + +// XMLModelWithEncodedNamesValueServerTransport connects instances of xmlgroup.XMLModelWithEncodedNamesValueClient to instances of XMLModelWithEncodedNamesValueServer. +// Don't use this type directly, use NewXMLModelWithEncodedNamesValueServerTransport instead. +type XMLModelWithEncodedNamesValueServerTransport struct { + srv *XMLModelWithEncodedNamesValueServer +} + +// Do implements the policy.Transporter interface for XMLModelWithEncodedNamesValueServerTransport. +func (x *XMLModelWithEncodedNamesValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToMethodFake(req, method) +} + +func (x *XMLModelWithEncodedNamesValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if xmlModelWithEncodedNamesValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = xmlModelWithEncodedNamesValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "XMLModelWithEncodedNamesValueClient.Get": + res.resp, res.err = x.dispatchGet(req) + case "XMLModelWithEncodedNamesValueClient.Put": + res.resp, res.err = x.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (x *XMLModelWithEncodedNamesValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if x.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := x.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr).ModelWithEncodedNames, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (x *XMLModelWithEncodedNamesValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if x.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsXML[xmlgroup.ModelWithEncodedNames](req) + if err != nil { + return nil, err + } + respr, errRespr := x.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to XMLModelWithEncodedNamesValueServerTransport +var xmlModelWithEncodedNamesValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithenumvalue_server.go b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithenumvalue_server.go new file mode 100644 index 000000000000..8f812d203289 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithenumvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "xmlgroup" +) + +// XMLModelWithEnumValueServer is a fake server for instances of the xmlgroup.XMLModelWithEnumValueClient type. +type XMLModelWithEnumValueServer struct { + // Get is the fake for method XMLModelWithEnumValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *xmlgroup.XMLModelWithEnumValueClientGetOptions) (resp azfake.Responder[xmlgroup.XMLModelWithEnumValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method XMLModelWithEnumValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, input xmlgroup.ModelWithEnum, options *xmlgroup.XMLModelWithEnumValueClientPutOptions) (resp azfake.Responder[xmlgroup.XMLModelWithEnumValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewXMLModelWithEnumValueServerTransport creates a new instance of XMLModelWithEnumValueServerTransport with the provided implementation. +// The returned XMLModelWithEnumValueServerTransport instance is connected to an instance of xmlgroup.XMLModelWithEnumValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMLModelWithEnumValueServerTransport(srv *XMLModelWithEnumValueServer) *XMLModelWithEnumValueServerTransport { + return &XMLModelWithEnumValueServerTransport{srv: srv} +} + +// XMLModelWithEnumValueServerTransport connects instances of xmlgroup.XMLModelWithEnumValueClient to instances of XMLModelWithEnumValueServer. +// Don't use this type directly, use NewXMLModelWithEnumValueServerTransport instead. +type XMLModelWithEnumValueServerTransport struct { + srv *XMLModelWithEnumValueServer +} + +// Do implements the policy.Transporter interface for XMLModelWithEnumValueServerTransport. +func (x *XMLModelWithEnumValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToMethodFake(req, method) +} + +func (x *XMLModelWithEnumValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if xmlModelWithEnumValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = xmlModelWithEnumValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "XMLModelWithEnumValueClient.Get": + res.resp, res.err = x.dispatchGet(req) + case "XMLModelWithEnumValueClient.Put": + res.resp, res.err = x.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (x *XMLModelWithEnumValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if x.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := x.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr).ModelWithEnum, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (x *XMLModelWithEnumValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if x.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsXML[xmlgroup.ModelWithEnum](req) + if err != nil { + return nil, err + } + respr, errRespr := x.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to XMLModelWithEnumValueServerTransport +var xmlModelWithEnumValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithnamespaceonpropertiesvalue_server.go b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithnamespaceonpropertiesvalue_server.go new file mode 100644 index 000000000000..d6db66b10f9b --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithnamespaceonpropertiesvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "xmlgroup" +) + +// XMLModelWithNamespaceOnPropertiesValueServer is a fake server for instances of the xmlgroup.XMLModelWithNamespaceOnPropertiesValueClient type. +type XMLModelWithNamespaceOnPropertiesValueServer struct { + // Get is the fake for method XMLModelWithNamespaceOnPropertiesValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *xmlgroup.XMLModelWithNamespaceOnPropertiesValueClientGetOptions) (resp azfake.Responder[xmlgroup.XMLModelWithNamespaceOnPropertiesValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method XMLModelWithNamespaceOnPropertiesValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, input xmlgroup.ModelWithNamespaceOnProperties, options *xmlgroup.XMLModelWithNamespaceOnPropertiesValueClientPutOptions) (resp azfake.Responder[xmlgroup.XMLModelWithNamespaceOnPropertiesValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewXMLModelWithNamespaceOnPropertiesValueServerTransport creates a new instance of XMLModelWithNamespaceOnPropertiesValueServerTransport with the provided implementation. +// The returned XMLModelWithNamespaceOnPropertiesValueServerTransport instance is connected to an instance of xmlgroup.XMLModelWithNamespaceOnPropertiesValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMLModelWithNamespaceOnPropertiesValueServerTransport(srv *XMLModelWithNamespaceOnPropertiesValueServer) *XMLModelWithNamespaceOnPropertiesValueServerTransport { + return &XMLModelWithNamespaceOnPropertiesValueServerTransport{srv: srv} +} + +// XMLModelWithNamespaceOnPropertiesValueServerTransport connects instances of xmlgroup.XMLModelWithNamespaceOnPropertiesValueClient to instances of XMLModelWithNamespaceOnPropertiesValueServer. +// Don't use this type directly, use NewXMLModelWithNamespaceOnPropertiesValueServerTransport instead. +type XMLModelWithNamespaceOnPropertiesValueServerTransport struct { + srv *XMLModelWithNamespaceOnPropertiesValueServer +} + +// Do implements the policy.Transporter interface for XMLModelWithNamespaceOnPropertiesValueServerTransport. +func (x *XMLModelWithNamespaceOnPropertiesValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToMethodFake(req, method) +} + +func (x *XMLModelWithNamespaceOnPropertiesValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if xmlModelWithNamespaceOnPropertiesValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = xmlModelWithNamespaceOnPropertiesValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "XMLModelWithNamespaceOnPropertiesValueClient.Get": + res.resp, res.err = x.dispatchGet(req) + case "XMLModelWithNamespaceOnPropertiesValueClient.Put": + res.resp, res.err = x.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (x *XMLModelWithNamespaceOnPropertiesValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if x.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := x.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr).ModelWithNamespaceOnProperties, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (x *XMLModelWithNamespaceOnPropertiesValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if x.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsXML[xmlgroup.ModelWithNamespaceOnProperties](req) + if err != nil { + return nil, err + } + respr, errRespr := x.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to XMLModelWithNamespaceOnPropertiesValueServerTransport +var xmlModelWithNamespaceOnPropertiesValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithnamespacevalue_server.go b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithnamespacevalue_server.go new file mode 100644 index 000000000000..3c3259116b14 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithnamespacevalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "xmlgroup" +) + +// XMLModelWithNamespaceValueServer is a fake server for instances of the xmlgroup.XMLModelWithNamespaceValueClient type. +type XMLModelWithNamespaceValueServer struct { + // Get is the fake for method XMLModelWithNamespaceValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *xmlgroup.XMLModelWithNamespaceValueClientGetOptions) (resp azfake.Responder[xmlgroup.XMLModelWithNamespaceValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method XMLModelWithNamespaceValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, input xmlgroup.ModelWithNamespace, options *xmlgroup.XMLModelWithNamespaceValueClientPutOptions) (resp azfake.Responder[xmlgroup.XMLModelWithNamespaceValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewXMLModelWithNamespaceValueServerTransport creates a new instance of XMLModelWithNamespaceValueServerTransport with the provided implementation. +// The returned XMLModelWithNamespaceValueServerTransport instance is connected to an instance of xmlgroup.XMLModelWithNamespaceValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMLModelWithNamespaceValueServerTransport(srv *XMLModelWithNamespaceValueServer) *XMLModelWithNamespaceValueServerTransport { + return &XMLModelWithNamespaceValueServerTransport{srv: srv} +} + +// XMLModelWithNamespaceValueServerTransport connects instances of xmlgroup.XMLModelWithNamespaceValueClient to instances of XMLModelWithNamespaceValueServer. +// Don't use this type directly, use NewXMLModelWithNamespaceValueServerTransport instead. +type XMLModelWithNamespaceValueServerTransport struct { + srv *XMLModelWithNamespaceValueServer +} + +// Do implements the policy.Transporter interface for XMLModelWithNamespaceValueServerTransport. +func (x *XMLModelWithNamespaceValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToMethodFake(req, method) +} + +func (x *XMLModelWithNamespaceValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if xmlModelWithNamespaceValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = xmlModelWithNamespaceValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "XMLModelWithNamespaceValueClient.Get": + res.resp, res.err = x.dispatchGet(req) + case "XMLModelWithNamespaceValueClient.Put": + res.resp, res.err = x.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (x *XMLModelWithNamespaceValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if x.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := x.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr).ModelWithNamespace, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (x *XMLModelWithNamespaceValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if x.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsXML[xmlgroup.ModelWithNamespace](req) + if err != nil { + return nil, err + } + respr, errRespr := x.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to XMLModelWithNamespaceValueServerTransport +var xmlModelWithNamespaceValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithnestedmodelvalue_server.go b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithnestedmodelvalue_server.go new file mode 100644 index 000000000000..a1c47fbf31b3 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithnestedmodelvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "xmlgroup" +) + +// XMLModelWithNestedModelValueServer is a fake server for instances of the xmlgroup.XMLModelWithNestedModelValueClient type. +type XMLModelWithNestedModelValueServer struct { + // Get is the fake for method XMLModelWithNestedModelValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *xmlgroup.XMLModelWithNestedModelValueClientGetOptions) (resp azfake.Responder[xmlgroup.XMLModelWithNestedModelValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method XMLModelWithNestedModelValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, input xmlgroup.ModelWithNestedModel, options *xmlgroup.XMLModelWithNestedModelValueClientPutOptions) (resp azfake.Responder[xmlgroup.XMLModelWithNestedModelValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewXMLModelWithNestedModelValueServerTransport creates a new instance of XMLModelWithNestedModelValueServerTransport with the provided implementation. +// The returned XMLModelWithNestedModelValueServerTransport instance is connected to an instance of xmlgroup.XMLModelWithNestedModelValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMLModelWithNestedModelValueServerTransport(srv *XMLModelWithNestedModelValueServer) *XMLModelWithNestedModelValueServerTransport { + return &XMLModelWithNestedModelValueServerTransport{srv: srv} +} + +// XMLModelWithNestedModelValueServerTransport connects instances of xmlgroup.XMLModelWithNestedModelValueClient to instances of XMLModelWithNestedModelValueServer. +// Don't use this type directly, use NewXMLModelWithNestedModelValueServerTransport instead. +type XMLModelWithNestedModelValueServerTransport struct { + srv *XMLModelWithNestedModelValueServer +} + +// Do implements the policy.Transporter interface for XMLModelWithNestedModelValueServerTransport. +func (x *XMLModelWithNestedModelValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToMethodFake(req, method) +} + +func (x *XMLModelWithNestedModelValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if xmlModelWithNestedModelValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = xmlModelWithNestedModelValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "XMLModelWithNestedModelValueClient.Get": + res.resp, res.err = x.dispatchGet(req) + case "XMLModelWithNestedModelValueClient.Put": + res.resp, res.err = x.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (x *XMLModelWithNestedModelValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if x.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := x.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr).ModelWithNestedModel, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (x *XMLModelWithNestedModelValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if x.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsXML[xmlgroup.ModelWithNestedModel](req) + if err != nil { + return nil, err + } + respr, errRespr := x.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to XMLModelWithNestedModelValueServerTransport +var xmlModelWithNestedModelValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithoptionalfieldvalue_server.go b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithoptionalfieldvalue_server.go new file mode 100644 index 000000000000..ce9018f78c8d --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithoptionalfieldvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "xmlgroup" +) + +// XMLModelWithOptionalFieldValueServer is a fake server for instances of the xmlgroup.XMLModelWithOptionalFieldValueClient type. +type XMLModelWithOptionalFieldValueServer struct { + // Get is the fake for method XMLModelWithOptionalFieldValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *xmlgroup.XMLModelWithOptionalFieldValueClientGetOptions) (resp azfake.Responder[xmlgroup.XMLModelWithOptionalFieldValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method XMLModelWithOptionalFieldValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, input xmlgroup.ModelWithOptionalField, options *xmlgroup.XMLModelWithOptionalFieldValueClientPutOptions) (resp azfake.Responder[xmlgroup.XMLModelWithOptionalFieldValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewXMLModelWithOptionalFieldValueServerTransport creates a new instance of XMLModelWithOptionalFieldValueServerTransport with the provided implementation. +// The returned XMLModelWithOptionalFieldValueServerTransport instance is connected to an instance of xmlgroup.XMLModelWithOptionalFieldValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMLModelWithOptionalFieldValueServerTransport(srv *XMLModelWithOptionalFieldValueServer) *XMLModelWithOptionalFieldValueServerTransport { + return &XMLModelWithOptionalFieldValueServerTransport{srv: srv} +} + +// XMLModelWithOptionalFieldValueServerTransport connects instances of xmlgroup.XMLModelWithOptionalFieldValueClient to instances of XMLModelWithOptionalFieldValueServer. +// Don't use this type directly, use NewXMLModelWithOptionalFieldValueServerTransport instead. +type XMLModelWithOptionalFieldValueServerTransport struct { + srv *XMLModelWithOptionalFieldValueServer +} + +// Do implements the policy.Transporter interface for XMLModelWithOptionalFieldValueServerTransport. +func (x *XMLModelWithOptionalFieldValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToMethodFake(req, method) +} + +func (x *XMLModelWithOptionalFieldValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if xmlModelWithOptionalFieldValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = xmlModelWithOptionalFieldValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "XMLModelWithOptionalFieldValueClient.Get": + res.resp, res.err = x.dispatchGet(req) + case "XMLModelWithOptionalFieldValueClient.Put": + res.resp, res.err = x.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (x *XMLModelWithOptionalFieldValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if x.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := x.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr).ModelWithOptionalField, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (x *XMLModelWithOptionalFieldValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if x.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsXML[xmlgroup.ModelWithOptionalField](req) + if err != nil { + return nil, err + } + respr, errRespr := x.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to XMLModelWithOptionalFieldValueServerTransport +var xmlModelWithOptionalFieldValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedarraysvalue_server.go b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedarraysvalue_server.go new file mode 100644 index 000000000000..02003934789f --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedarraysvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "xmlgroup" +) + +// XMLModelWithRenamedArraysValueServer is a fake server for instances of the xmlgroup.XMLModelWithRenamedArraysValueClient type. +type XMLModelWithRenamedArraysValueServer struct { + // Get is the fake for method XMLModelWithRenamedArraysValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *xmlgroup.XMLModelWithRenamedArraysValueClientGetOptions) (resp azfake.Responder[xmlgroup.XMLModelWithRenamedArraysValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method XMLModelWithRenamedArraysValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, input xmlgroup.ModelWithRenamedArrays, options *xmlgroup.XMLModelWithRenamedArraysValueClientPutOptions) (resp azfake.Responder[xmlgroup.XMLModelWithRenamedArraysValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewXMLModelWithRenamedArraysValueServerTransport creates a new instance of XMLModelWithRenamedArraysValueServerTransport with the provided implementation. +// The returned XMLModelWithRenamedArraysValueServerTransport instance is connected to an instance of xmlgroup.XMLModelWithRenamedArraysValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMLModelWithRenamedArraysValueServerTransport(srv *XMLModelWithRenamedArraysValueServer) *XMLModelWithRenamedArraysValueServerTransport { + return &XMLModelWithRenamedArraysValueServerTransport{srv: srv} +} + +// XMLModelWithRenamedArraysValueServerTransport connects instances of xmlgroup.XMLModelWithRenamedArraysValueClient to instances of XMLModelWithRenamedArraysValueServer. +// Don't use this type directly, use NewXMLModelWithRenamedArraysValueServerTransport instead. +type XMLModelWithRenamedArraysValueServerTransport struct { + srv *XMLModelWithRenamedArraysValueServer +} + +// Do implements the policy.Transporter interface for XMLModelWithRenamedArraysValueServerTransport. +func (x *XMLModelWithRenamedArraysValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToMethodFake(req, method) +} + +func (x *XMLModelWithRenamedArraysValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if xmlModelWithRenamedArraysValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = xmlModelWithRenamedArraysValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "XMLModelWithRenamedArraysValueClient.Get": + res.resp, res.err = x.dispatchGet(req) + case "XMLModelWithRenamedArraysValueClient.Put": + res.resp, res.err = x.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (x *XMLModelWithRenamedArraysValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if x.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := x.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr).ModelWithRenamedArrays, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (x *XMLModelWithRenamedArraysValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if x.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsXML[xmlgroup.ModelWithRenamedArrays](req) + if err != nil { + return nil, err + } + respr, errRespr := x.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to XMLModelWithRenamedArraysValueServerTransport +var xmlModelWithRenamedArraysValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedattributevalue_server.go b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedattributevalue_server.go new file mode 100644 index 000000000000..6bf805643c8c --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedattributevalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "xmlgroup" +) + +// XMLModelWithRenamedAttributeValueServer is a fake server for instances of the xmlgroup.XMLModelWithRenamedAttributeValueClient type. +type XMLModelWithRenamedAttributeValueServer struct { + // Get is the fake for method XMLModelWithRenamedAttributeValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *xmlgroup.XMLModelWithRenamedAttributeValueClientGetOptions) (resp azfake.Responder[xmlgroup.XMLModelWithRenamedAttributeValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method XMLModelWithRenamedAttributeValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, input xmlgroup.ModelWithRenamedAttribute, options *xmlgroup.XMLModelWithRenamedAttributeValueClientPutOptions) (resp azfake.Responder[xmlgroup.XMLModelWithRenamedAttributeValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewXMLModelWithRenamedAttributeValueServerTransport creates a new instance of XMLModelWithRenamedAttributeValueServerTransport with the provided implementation. +// The returned XMLModelWithRenamedAttributeValueServerTransport instance is connected to an instance of xmlgroup.XMLModelWithRenamedAttributeValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMLModelWithRenamedAttributeValueServerTransport(srv *XMLModelWithRenamedAttributeValueServer) *XMLModelWithRenamedAttributeValueServerTransport { + return &XMLModelWithRenamedAttributeValueServerTransport{srv: srv} +} + +// XMLModelWithRenamedAttributeValueServerTransport connects instances of xmlgroup.XMLModelWithRenamedAttributeValueClient to instances of XMLModelWithRenamedAttributeValueServer. +// Don't use this type directly, use NewXMLModelWithRenamedAttributeValueServerTransport instead. +type XMLModelWithRenamedAttributeValueServerTransport struct { + srv *XMLModelWithRenamedAttributeValueServer +} + +// Do implements the policy.Transporter interface for XMLModelWithRenamedAttributeValueServerTransport. +func (x *XMLModelWithRenamedAttributeValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToMethodFake(req, method) +} + +func (x *XMLModelWithRenamedAttributeValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if xmlModelWithRenamedAttributeValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = xmlModelWithRenamedAttributeValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "XMLModelWithRenamedAttributeValueClient.Get": + res.resp, res.err = x.dispatchGet(req) + case "XMLModelWithRenamedAttributeValueClient.Put": + res.resp, res.err = x.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (x *XMLModelWithRenamedAttributeValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if x.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := x.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr).ModelWithRenamedAttribute, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (x *XMLModelWithRenamedAttributeValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if x.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsXML[xmlgroup.ModelWithRenamedAttribute](req) + if err != nil { + return nil, err + } + respr, errRespr := x.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to XMLModelWithRenamedAttributeValueServerTransport +var xmlModelWithRenamedAttributeValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedfieldsvalue_server.go b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedfieldsvalue_server.go new file mode 100644 index 000000000000..7473a2b9b443 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedfieldsvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "xmlgroup" +) + +// XMLModelWithRenamedFieldsValueServer is a fake server for instances of the xmlgroup.XMLModelWithRenamedFieldsValueClient type. +type XMLModelWithRenamedFieldsValueServer struct { + // Get is the fake for method XMLModelWithRenamedFieldsValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *xmlgroup.XMLModelWithRenamedFieldsValueClientGetOptions) (resp azfake.Responder[xmlgroup.XMLModelWithRenamedFieldsValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method XMLModelWithRenamedFieldsValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, input xmlgroup.ModelWithRenamedFields, options *xmlgroup.XMLModelWithRenamedFieldsValueClientPutOptions) (resp azfake.Responder[xmlgroup.XMLModelWithRenamedFieldsValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewXMLModelWithRenamedFieldsValueServerTransport creates a new instance of XMLModelWithRenamedFieldsValueServerTransport with the provided implementation. +// The returned XMLModelWithRenamedFieldsValueServerTransport instance is connected to an instance of xmlgroup.XMLModelWithRenamedFieldsValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMLModelWithRenamedFieldsValueServerTransport(srv *XMLModelWithRenamedFieldsValueServer) *XMLModelWithRenamedFieldsValueServerTransport { + return &XMLModelWithRenamedFieldsValueServerTransport{srv: srv} +} + +// XMLModelWithRenamedFieldsValueServerTransport connects instances of xmlgroup.XMLModelWithRenamedFieldsValueClient to instances of XMLModelWithRenamedFieldsValueServer. +// Don't use this type directly, use NewXMLModelWithRenamedFieldsValueServerTransport instead. +type XMLModelWithRenamedFieldsValueServerTransport struct { + srv *XMLModelWithRenamedFieldsValueServer +} + +// Do implements the policy.Transporter interface for XMLModelWithRenamedFieldsValueServerTransport. +func (x *XMLModelWithRenamedFieldsValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToMethodFake(req, method) +} + +func (x *XMLModelWithRenamedFieldsValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if xmlModelWithRenamedFieldsValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = xmlModelWithRenamedFieldsValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "XMLModelWithRenamedFieldsValueClient.Get": + res.resp, res.err = x.dispatchGet(req) + case "XMLModelWithRenamedFieldsValueClient.Put": + res.resp, res.err = x.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (x *XMLModelWithRenamedFieldsValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if x.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := x.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr).ModelWithRenamedFields, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (x *XMLModelWithRenamedFieldsValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if x.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsXML[xmlgroup.ModelWithRenamedFields](req) + if err != nil { + return nil, err + } + respr, errRespr := x.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to XMLModelWithRenamedFieldsValueServerTransport +var xmlModelWithRenamedFieldsValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamednestedmodelvalue_server.go b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamednestedmodelvalue_server.go new file mode 100644 index 000000000000..468f24d4fd5e --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamednestedmodelvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "xmlgroup" +) + +// XMLModelWithRenamedNestedModelValueServer is a fake server for instances of the xmlgroup.XMLModelWithRenamedNestedModelValueClient type. +type XMLModelWithRenamedNestedModelValueServer struct { + // Get is the fake for method XMLModelWithRenamedNestedModelValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *xmlgroup.XMLModelWithRenamedNestedModelValueClientGetOptions) (resp azfake.Responder[xmlgroup.XMLModelWithRenamedNestedModelValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method XMLModelWithRenamedNestedModelValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, input xmlgroup.ModelWithRenamedNestedModel, options *xmlgroup.XMLModelWithRenamedNestedModelValueClientPutOptions) (resp azfake.Responder[xmlgroup.XMLModelWithRenamedNestedModelValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewXMLModelWithRenamedNestedModelValueServerTransport creates a new instance of XMLModelWithRenamedNestedModelValueServerTransport with the provided implementation. +// The returned XMLModelWithRenamedNestedModelValueServerTransport instance is connected to an instance of xmlgroup.XMLModelWithRenamedNestedModelValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMLModelWithRenamedNestedModelValueServerTransport(srv *XMLModelWithRenamedNestedModelValueServer) *XMLModelWithRenamedNestedModelValueServerTransport { + return &XMLModelWithRenamedNestedModelValueServerTransport{srv: srv} +} + +// XMLModelWithRenamedNestedModelValueServerTransport connects instances of xmlgroup.XMLModelWithRenamedNestedModelValueClient to instances of XMLModelWithRenamedNestedModelValueServer. +// Don't use this type directly, use NewXMLModelWithRenamedNestedModelValueServerTransport instead. +type XMLModelWithRenamedNestedModelValueServerTransport struct { + srv *XMLModelWithRenamedNestedModelValueServer +} + +// Do implements the policy.Transporter interface for XMLModelWithRenamedNestedModelValueServerTransport. +func (x *XMLModelWithRenamedNestedModelValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToMethodFake(req, method) +} + +func (x *XMLModelWithRenamedNestedModelValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if xmlModelWithRenamedNestedModelValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = xmlModelWithRenamedNestedModelValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "XMLModelWithRenamedNestedModelValueClient.Get": + res.resp, res.err = x.dispatchGet(req) + case "XMLModelWithRenamedNestedModelValueClient.Put": + res.resp, res.err = x.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (x *XMLModelWithRenamedNestedModelValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if x.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := x.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr).ModelWithRenamedNestedModel, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (x *XMLModelWithRenamedNestedModelValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if x.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsXML[xmlgroup.ModelWithRenamedNestedModel](req) + if err != nil { + return nil, err + } + respr, errRespr := x.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to XMLModelWithRenamedNestedModelValueServerTransport +var xmlModelWithRenamedNestedModelValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedpropertyvalue_server.go b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedpropertyvalue_server.go new file mode 100644 index 000000000000..b2a7df358d1a --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedpropertyvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "xmlgroup" +) + +// XMLModelWithRenamedPropertyValueServer is a fake server for instances of the xmlgroup.XMLModelWithRenamedPropertyValueClient type. +type XMLModelWithRenamedPropertyValueServer struct { + // Get is the fake for method XMLModelWithRenamedPropertyValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *xmlgroup.XMLModelWithRenamedPropertyValueClientGetOptions) (resp azfake.Responder[xmlgroup.XMLModelWithRenamedPropertyValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method XMLModelWithRenamedPropertyValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, input xmlgroup.ModelWithRenamedProperty, options *xmlgroup.XMLModelWithRenamedPropertyValueClientPutOptions) (resp azfake.Responder[xmlgroup.XMLModelWithRenamedPropertyValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewXMLModelWithRenamedPropertyValueServerTransport creates a new instance of XMLModelWithRenamedPropertyValueServerTransport with the provided implementation. +// The returned XMLModelWithRenamedPropertyValueServerTransport instance is connected to an instance of xmlgroup.XMLModelWithRenamedPropertyValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMLModelWithRenamedPropertyValueServerTransport(srv *XMLModelWithRenamedPropertyValueServer) *XMLModelWithRenamedPropertyValueServerTransport { + return &XMLModelWithRenamedPropertyValueServerTransport{srv: srv} +} + +// XMLModelWithRenamedPropertyValueServerTransport connects instances of xmlgroup.XMLModelWithRenamedPropertyValueClient to instances of XMLModelWithRenamedPropertyValueServer. +// Don't use this type directly, use NewXMLModelWithRenamedPropertyValueServerTransport instead. +type XMLModelWithRenamedPropertyValueServerTransport struct { + srv *XMLModelWithRenamedPropertyValueServer +} + +// Do implements the policy.Transporter interface for XMLModelWithRenamedPropertyValueServerTransport. +func (x *XMLModelWithRenamedPropertyValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToMethodFake(req, method) +} + +func (x *XMLModelWithRenamedPropertyValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if xmlModelWithRenamedPropertyValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = xmlModelWithRenamedPropertyValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "XMLModelWithRenamedPropertyValueClient.Get": + res.resp, res.err = x.dispatchGet(req) + case "XMLModelWithRenamedPropertyValueClient.Put": + res.resp, res.err = x.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (x *XMLModelWithRenamedPropertyValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if x.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := x.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr).ModelWithRenamedProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (x *XMLModelWithRenamedPropertyValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if x.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsXML[xmlgroup.ModelWithRenamedProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := x.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to XMLModelWithRenamedPropertyValueServerTransport +var xmlModelWithRenamedPropertyValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedunwrappedmodelarrayvalue_server.go b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedunwrappedmodelarrayvalue_server.go new file mode 100644 index 000000000000..ba217976a327 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedunwrappedmodelarrayvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "xmlgroup" +) + +// XMLModelWithRenamedUnwrappedModelArrayValueServer is a fake server for instances of the xmlgroup.XMLModelWithRenamedUnwrappedModelArrayValueClient type. +type XMLModelWithRenamedUnwrappedModelArrayValueServer struct { + // Get is the fake for method XMLModelWithRenamedUnwrappedModelArrayValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *xmlgroup.XMLModelWithRenamedUnwrappedModelArrayValueClientGetOptions) (resp azfake.Responder[xmlgroup.XMLModelWithRenamedUnwrappedModelArrayValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method XMLModelWithRenamedUnwrappedModelArrayValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, input xmlgroup.ModelWithRenamedUnwrappedModelArray, options *xmlgroup.XMLModelWithRenamedUnwrappedModelArrayValueClientPutOptions) (resp azfake.Responder[xmlgroup.XMLModelWithRenamedUnwrappedModelArrayValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewXMLModelWithRenamedUnwrappedModelArrayValueServerTransport creates a new instance of XMLModelWithRenamedUnwrappedModelArrayValueServerTransport with the provided implementation. +// The returned XMLModelWithRenamedUnwrappedModelArrayValueServerTransport instance is connected to an instance of xmlgroup.XMLModelWithRenamedUnwrappedModelArrayValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMLModelWithRenamedUnwrappedModelArrayValueServerTransport(srv *XMLModelWithRenamedUnwrappedModelArrayValueServer) *XMLModelWithRenamedUnwrappedModelArrayValueServerTransport { + return &XMLModelWithRenamedUnwrappedModelArrayValueServerTransport{srv: srv} +} + +// XMLModelWithRenamedUnwrappedModelArrayValueServerTransport connects instances of xmlgroup.XMLModelWithRenamedUnwrappedModelArrayValueClient to instances of XMLModelWithRenamedUnwrappedModelArrayValueServer. +// Don't use this type directly, use NewXMLModelWithRenamedUnwrappedModelArrayValueServerTransport instead. +type XMLModelWithRenamedUnwrappedModelArrayValueServerTransport struct { + srv *XMLModelWithRenamedUnwrappedModelArrayValueServer +} + +// Do implements the policy.Transporter interface for XMLModelWithRenamedUnwrappedModelArrayValueServerTransport. +func (x *XMLModelWithRenamedUnwrappedModelArrayValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToMethodFake(req, method) +} + +func (x *XMLModelWithRenamedUnwrappedModelArrayValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if xmlModelWithRenamedUnwrappedModelArrayValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = xmlModelWithRenamedUnwrappedModelArrayValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "XMLModelWithRenamedUnwrappedModelArrayValueClient.Get": + res.resp, res.err = x.dispatchGet(req) + case "XMLModelWithRenamedUnwrappedModelArrayValueClient.Put": + res.resp, res.err = x.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (x *XMLModelWithRenamedUnwrappedModelArrayValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if x.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := x.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr).ModelWithRenamedUnwrappedModelArray, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (x *XMLModelWithRenamedUnwrappedModelArrayValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if x.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsXML[xmlgroup.ModelWithRenamedUnwrappedModelArray](req) + if err != nil { + return nil, err + } + respr, errRespr := x.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to XMLModelWithRenamedUnwrappedModelArrayValueServerTransport +var xmlModelWithRenamedUnwrappedModelArrayValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedwrappedanditemmodelarrayvalue_server.go b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedwrappedanditemmodelarrayvalue_server.go new file mode 100644 index 000000000000..e2e6c747513d --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedwrappedanditemmodelarrayvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "xmlgroup" +) + +// XMLModelWithRenamedWrappedAndItemModelArrayValueServer is a fake server for instances of the xmlgroup.XMLModelWithRenamedWrappedAndItemModelArrayValueClient type. +type XMLModelWithRenamedWrappedAndItemModelArrayValueServer struct { + // Get is the fake for method XMLModelWithRenamedWrappedAndItemModelArrayValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *xmlgroup.XMLModelWithRenamedWrappedAndItemModelArrayValueClientGetOptions) (resp azfake.Responder[xmlgroup.XMLModelWithRenamedWrappedAndItemModelArrayValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method XMLModelWithRenamedWrappedAndItemModelArrayValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, input xmlgroup.ModelWithRenamedWrappedAndItemModelArray, options *xmlgroup.XMLModelWithRenamedWrappedAndItemModelArrayValueClientPutOptions) (resp azfake.Responder[xmlgroup.XMLModelWithRenamedWrappedAndItemModelArrayValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewXMLModelWithRenamedWrappedAndItemModelArrayValueServerTransport creates a new instance of XMLModelWithRenamedWrappedAndItemModelArrayValueServerTransport with the provided implementation. +// The returned XMLModelWithRenamedWrappedAndItemModelArrayValueServerTransport instance is connected to an instance of xmlgroup.XMLModelWithRenamedWrappedAndItemModelArrayValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMLModelWithRenamedWrappedAndItemModelArrayValueServerTransport(srv *XMLModelWithRenamedWrappedAndItemModelArrayValueServer) *XMLModelWithRenamedWrappedAndItemModelArrayValueServerTransport { + return &XMLModelWithRenamedWrappedAndItemModelArrayValueServerTransport{srv: srv} +} + +// XMLModelWithRenamedWrappedAndItemModelArrayValueServerTransport connects instances of xmlgroup.XMLModelWithRenamedWrappedAndItemModelArrayValueClient to instances of XMLModelWithRenamedWrappedAndItemModelArrayValueServer. +// Don't use this type directly, use NewXMLModelWithRenamedWrappedAndItemModelArrayValueServerTransport instead. +type XMLModelWithRenamedWrappedAndItemModelArrayValueServerTransport struct { + srv *XMLModelWithRenamedWrappedAndItemModelArrayValueServer +} + +// Do implements the policy.Transporter interface for XMLModelWithRenamedWrappedAndItemModelArrayValueServerTransport. +func (x *XMLModelWithRenamedWrappedAndItemModelArrayValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToMethodFake(req, method) +} + +func (x *XMLModelWithRenamedWrappedAndItemModelArrayValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if xmlModelWithRenamedWrappedAndItemModelArrayValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = xmlModelWithRenamedWrappedAndItemModelArrayValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "XMLModelWithRenamedWrappedAndItemModelArrayValueClient.Get": + res.resp, res.err = x.dispatchGet(req) + case "XMLModelWithRenamedWrappedAndItemModelArrayValueClient.Put": + res.resp, res.err = x.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (x *XMLModelWithRenamedWrappedAndItemModelArrayValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if x.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := x.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr).ModelWithRenamedWrappedAndItemModelArray, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (x *XMLModelWithRenamedWrappedAndItemModelArrayValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if x.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsXML[xmlgroup.ModelWithRenamedWrappedAndItemModelArray](req) + if err != nil { + return nil, err + } + respr, errRespr := x.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to XMLModelWithRenamedWrappedAndItemModelArrayValueServerTransport +var xmlModelWithRenamedWrappedAndItemModelArrayValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedwrappedmodelarrayvalue_server.go b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedwrappedmodelarrayvalue_server.go new file mode 100644 index 000000000000..dd876bb75885 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithrenamedwrappedmodelarrayvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "xmlgroup" +) + +// XMLModelWithRenamedWrappedModelArrayValueServer is a fake server for instances of the xmlgroup.XMLModelWithRenamedWrappedModelArrayValueClient type. +type XMLModelWithRenamedWrappedModelArrayValueServer struct { + // Get is the fake for method XMLModelWithRenamedWrappedModelArrayValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *xmlgroup.XMLModelWithRenamedWrappedModelArrayValueClientGetOptions) (resp azfake.Responder[xmlgroup.XMLModelWithRenamedWrappedModelArrayValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method XMLModelWithRenamedWrappedModelArrayValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, input xmlgroup.ModelWithRenamedWrappedModelArray, options *xmlgroup.XMLModelWithRenamedWrappedModelArrayValueClientPutOptions) (resp azfake.Responder[xmlgroup.XMLModelWithRenamedWrappedModelArrayValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewXMLModelWithRenamedWrappedModelArrayValueServerTransport creates a new instance of XMLModelWithRenamedWrappedModelArrayValueServerTransport with the provided implementation. +// The returned XMLModelWithRenamedWrappedModelArrayValueServerTransport instance is connected to an instance of xmlgroup.XMLModelWithRenamedWrappedModelArrayValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMLModelWithRenamedWrappedModelArrayValueServerTransport(srv *XMLModelWithRenamedWrappedModelArrayValueServer) *XMLModelWithRenamedWrappedModelArrayValueServerTransport { + return &XMLModelWithRenamedWrappedModelArrayValueServerTransport{srv: srv} +} + +// XMLModelWithRenamedWrappedModelArrayValueServerTransport connects instances of xmlgroup.XMLModelWithRenamedWrappedModelArrayValueClient to instances of XMLModelWithRenamedWrappedModelArrayValueServer. +// Don't use this type directly, use NewXMLModelWithRenamedWrappedModelArrayValueServerTransport instead. +type XMLModelWithRenamedWrappedModelArrayValueServerTransport struct { + srv *XMLModelWithRenamedWrappedModelArrayValueServer +} + +// Do implements the policy.Transporter interface for XMLModelWithRenamedWrappedModelArrayValueServerTransport. +func (x *XMLModelWithRenamedWrappedModelArrayValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToMethodFake(req, method) +} + +func (x *XMLModelWithRenamedWrappedModelArrayValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if xmlModelWithRenamedWrappedModelArrayValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = xmlModelWithRenamedWrappedModelArrayValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "XMLModelWithRenamedWrappedModelArrayValueClient.Get": + res.resp, res.err = x.dispatchGet(req) + case "XMLModelWithRenamedWrappedModelArrayValueClient.Put": + res.resp, res.err = x.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (x *XMLModelWithRenamedWrappedModelArrayValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if x.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := x.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr).ModelWithRenamedWrappedModelArray, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (x *XMLModelWithRenamedWrappedModelArrayValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if x.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsXML[xmlgroup.ModelWithRenamedWrappedModelArray](req) + if err != nil { + return nil, err + } + respr, errRespr := x.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to XMLModelWithRenamedWrappedModelArrayValueServerTransport +var xmlModelWithRenamedWrappedModelArrayValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithsimplearraysvalue_server.go b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithsimplearraysvalue_server.go new file mode 100644 index 000000000000..8f441196f2c4 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithsimplearraysvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "xmlgroup" +) + +// XMLModelWithSimpleArraysValueServer is a fake server for instances of the xmlgroup.XMLModelWithSimpleArraysValueClient type. +type XMLModelWithSimpleArraysValueServer struct { + // Get is the fake for method XMLModelWithSimpleArraysValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *xmlgroup.XMLModelWithSimpleArraysValueClientGetOptions) (resp azfake.Responder[xmlgroup.XMLModelWithSimpleArraysValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method XMLModelWithSimpleArraysValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, input xmlgroup.ModelWithSimpleArrays, options *xmlgroup.XMLModelWithSimpleArraysValueClientPutOptions) (resp azfake.Responder[xmlgroup.XMLModelWithSimpleArraysValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewXMLModelWithSimpleArraysValueServerTransport creates a new instance of XMLModelWithSimpleArraysValueServerTransport with the provided implementation. +// The returned XMLModelWithSimpleArraysValueServerTransport instance is connected to an instance of xmlgroup.XMLModelWithSimpleArraysValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMLModelWithSimpleArraysValueServerTransport(srv *XMLModelWithSimpleArraysValueServer) *XMLModelWithSimpleArraysValueServerTransport { + return &XMLModelWithSimpleArraysValueServerTransport{srv: srv} +} + +// XMLModelWithSimpleArraysValueServerTransport connects instances of xmlgroup.XMLModelWithSimpleArraysValueClient to instances of XMLModelWithSimpleArraysValueServer. +// Don't use this type directly, use NewXMLModelWithSimpleArraysValueServerTransport instead. +type XMLModelWithSimpleArraysValueServerTransport struct { + srv *XMLModelWithSimpleArraysValueServer +} + +// Do implements the policy.Transporter interface for XMLModelWithSimpleArraysValueServerTransport. +func (x *XMLModelWithSimpleArraysValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToMethodFake(req, method) +} + +func (x *XMLModelWithSimpleArraysValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if xmlModelWithSimpleArraysValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = xmlModelWithSimpleArraysValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "XMLModelWithSimpleArraysValueClient.Get": + res.resp, res.err = x.dispatchGet(req) + case "XMLModelWithSimpleArraysValueClient.Put": + res.resp, res.err = x.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (x *XMLModelWithSimpleArraysValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if x.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := x.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr).ModelWithSimpleArrays, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (x *XMLModelWithSimpleArraysValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if x.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsXML[xmlgroup.ModelWithSimpleArrays](req) + if err != nil { + return nil, err + } + respr, errRespr := x.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to XMLModelWithSimpleArraysValueServerTransport +var xmlModelWithSimpleArraysValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithtextvalue_server.go b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithtextvalue_server.go new file mode 100644 index 000000000000..fb33683022a5 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithtextvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "xmlgroup" +) + +// XMLModelWithTextValueServer is a fake server for instances of the xmlgroup.XMLModelWithTextValueClient type. +type XMLModelWithTextValueServer struct { + // Get is the fake for method XMLModelWithTextValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *xmlgroup.XMLModelWithTextValueClientGetOptions) (resp azfake.Responder[xmlgroup.XMLModelWithTextValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method XMLModelWithTextValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, input xmlgroup.ModelWithText, options *xmlgroup.XMLModelWithTextValueClientPutOptions) (resp azfake.Responder[xmlgroup.XMLModelWithTextValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewXMLModelWithTextValueServerTransport creates a new instance of XMLModelWithTextValueServerTransport with the provided implementation. +// The returned XMLModelWithTextValueServerTransport instance is connected to an instance of xmlgroup.XMLModelWithTextValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMLModelWithTextValueServerTransport(srv *XMLModelWithTextValueServer) *XMLModelWithTextValueServerTransport { + return &XMLModelWithTextValueServerTransport{srv: srv} +} + +// XMLModelWithTextValueServerTransport connects instances of xmlgroup.XMLModelWithTextValueClient to instances of XMLModelWithTextValueServer. +// Don't use this type directly, use NewXMLModelWithTextValueServerTransport instead. +type XMLModelWithTextValueServerTransport struct { + srv *XMLModelWithTextValueServer +} + +// Do implements the policy.Transporter interface for XMLModelWithTextValueServerTransport. +func (x *XMLModelWithTextValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToMethodFake(req, method) +} + +func (x *XMLModelWithTextValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if xmlModelWithTextValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = xmlModelWithTextValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "XMLModelWithTextValueClient.Get": + res.resp, res.err = x.dispatchGet(req) + case "XMLModelWithTextValueClient.Put": + res.resp, res.err = x.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (x *XMLModelWithTextValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if x.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := x.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr).ModelWithText, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (x *XMLModelWithTextValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if x.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsXML[xmlgroup.ModelWithText](req) + if err != nil { + return nil, err + } + respr, errRespr := x.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to XMLModelWithTextValueServerTransport +var xmlModelWithTextValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithunwrappedarrayvalue_server.go b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithunwrappedarrayvalue_server.go new file mode 100644 index 000000000000..c9cb22116075 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithunwrappedarrayvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "xmlgroup" +) + +// XMLModelWithUnwrappedArrayValueServer is a fake server for instances of the xmlgroup.XMLModelWithUnwrappedArrayValueClient type. +type XMLModelWithUnwrappedArrayValueServer struct { + // Get is the fake for method XMLModelWithUnwrappedArrayValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *xmlgroup.XMLModelWithUnwrappedArrayValueClientGetOptions) (resp azfake.Responder[xmlgroup.XMLModelWithUnwrappedArrayValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method XMLModelWithUnwrappedArrayValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, input xmlgroup.ModelWithUnwrappedArray, options *xmlgroup.XMLModelWithUnwrappedArrayValueClientPutOptions) (resp azfake.Responder[xmlgroup.XMLModelWithUnwrappedArrayValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewXMLModelWithUnwrappedArrayValueServerTransport creates a new instance of XMLModelWithUnwrappedArrayValueServerTransport with the provided implementation. +// The returned XMLModelWithUnwrappedArrayValueServerTransport instance is connected to an instance of xmlgroup.XMLModelWithUnwrappedArrayValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMLModelWithUnwrappedArrayValueServerTransport(srv *XMLModelWithUnwrappedArrayValueServer) *XMLModelWithUnwrappedArrayValueServerTransport { + return &XMLModelWithUnwrappedArrayValueServerTransport{srv: srv} +} + +// XMLModelWithUnwrappedArrayValueServerTransport connects instances of xmlgroup.XMLModelWithUnwrappedArrayValueClient to instances of XMLModelWithUnwrappedArrayValueServer. +// Don't use this type directly, use NewXMLModelWithUnwrappedArrayValueServerTransport instead. +type XMLModelWithUnwrappedArrayValueServerTransport struct { + srv *XMLModelWithUnwrappedArrayValueServer +} + +// Do implements the policy.Transporter interface for XMLModelWithUnwrappedArrayValueServerTransport. +func (x *XMLModelWithUnwrappedArrayValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToMethodFake(req, method) +} + +func (x *XMLModelWithUnwrappedArrayValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if xmlModelWithUnwrappedArrayValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = xmlModelWithUnwrappedArrayValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "XMLModelWithUnwrappedArrayValueClient.Get": + res.resp, res.err = x.dispatchGet(req) + case "XMLModelWithUnwrappedArrayValueClient.Put": + res.resp, res.err = x.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (x *XMLModelWithUnwrappedArrayValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if x.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := x.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr).ModelWithUnwrappedArray, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (x *XMLModelWithUnwrappedArrayValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if x.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsXML[xmlgroup.ModelWithUnwrappedArray](req) + if err != nil { + return nil, err + } + respr, errRespr := x.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to XMLModelWithUnwrappedArrayValueServerTransport +var xmlModelWithUnwrappedArrayValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithunwrappedmodelarrayvalue_server.go b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithunwrappedmodelarrayvalue_server.go new file mode 100644 index 000000000000..c3604c30b380 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithunwrappedmodelarrayvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "xmlgroup" +) + +// XMLModelWithUnwrappedModelArrayValueServer is a fake server for instances of the xmlgroup.XMLModelWithUnwrappedModelArrayValueClient type. +type XMLModelWithUnwrappedModelArrayValueServer struct { + // Get is the fake for method XMLModelWithUnwrappedModelArrayValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *xmlgroup.XMLModelWithUnwrappedModelArrayValueClientGetOptions) (resp azfake.Responder[xmlgroup.XMLModelWithUnwrappedModelArrayValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method XMLModelWithUnwrappedModelArrayValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, input xmlgroup.ModelWithUnwrappedModelArray, options *xmlgroup.XMLModelWithUnwrappedModelArrayValueClientPutOptions) (resp azfake.Responder[xmlgroup.XMLModelWithUnwrappedModelArrayValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewXMLModelWithUnwrappedModelArrayValueServerTransport creates a new instance of XMLModelWithUnwrappedModelArrayValueServerTransport with the provided implementation. +// The returned XMLModelWithUnwrappedModelArrayValueServerTransport instance is connected to an instance of xmlgroup.XMLModelWithUnwrappedModelArrayValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMLModelWithUnwrappedModelArrayValueServerTransport(srv *XMLModelWithUnwrappedModelArrayValueServer) *XMLModelWithUnwrappedModelArrayValueServerTransport { + return &XMLModelWithUnwrappedModelArrayValueServerTransport{srv: srv} +} + +// XMLModelWithUnwrappedModelArrayValueServerTransport connects instances of xmlgroup.XMLModelWithUnwrappedModelArrayValueClient to instances of XMLModelWithUnwrappedModelArrayValueServer. +// Don't use this type directly, use NewXMLModelWithUnwrappedModelArrayValueServerTransport instead. +type XMLModelWithUnwrappedModelArrayValueServerTransport struct { + srv *XMLModelWithUnwrappedModelArrayValueServer +} + +// Do implements the policy.Transporter interface for XMLModelWithUnwrappedModelArrayValueServerTransport. +func (x *XMLModelWithUnwrappedModelArrayValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToMethodFake(req, method) +} + +func (x *XMLModelWithUnwrappedModelArrayValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if xmlModelWithUnwrappedModelArrayValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = xmlModelWithUnwrappedModelArrayValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "XMLModelWithUnwrappedModelArrayValueClient.Get": + res.resp, res.err = x.dispatchGet(req) + case "XMLModelWithUnwrappedModelArrayValueClient.Put": + res.resp, res.err = x.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (x *XMLModelWithUnwrappedModelArrayValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if x.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := x.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr).ModelWithUnwrappedModelArray, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (x *XMLModelWithUnwrappedModelArrayValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if x.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsXML[xmlgroup.ModelWithUnwrappedModelArray](req) + if err != nil { + return nil, err + } + respr, errRespr := x.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to XMLModelWithUnwrappedModelArrayValueServerTransport +var xmlModelWithUnwrappedModelArrayValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithwrappedprimitivecustomitemnamesvalue_server.go b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithwrappedprimitivecustomitemnamesvalue_server.go new file mode 100644 index 000000000000..6fff257f885f --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_xmlmodelwithwrappedprimitivecustomitemnamesvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "xmlgroup" +) + +// XMLModelWithWrappedPrimitiveCustomItemNamesValueServer is a fake server for instances of the xmlgroup.XMLModelWithWrappedPrimitiveCustomItemNamesValueClient type. +type XMLModelWithWrappedPrimitiveCustomItemNamesValueServer struct { + // Get is the fake for method XMLModelWithWrappedPrimitiveCustomItemNamesValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *xmlgroup.XMLModelWithWrappedPrimitiveCustomItemNamesValueClientGetOptions) (resp azfake.Responder[xmlgroup.XMLModelWithWrappedPrimitiveCustomItemNamesValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method XMLModelWithWrappedPrimitiveCustomItemNamesValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, input xmlgroup.ModelWithWrappedPrimitiveCustomItemNames, options *xmlgroup.XMLModelWithWrappedPrimitiveCustomItemNamesValueClientPutOptions) (resp azfake.Responder[xmlgroup.XMLModelWithWrappedPrimitiveCustomItemNamesValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewXMLModelWithWrappedPrimitiveCustomItemNamesValueServerTransport creates a new instance of XMLModelWithWrappedPrimitiveCustomItemNamesValueServerTransport with the provided implementation. +// The returned XMLModelWithWrappedPrimitiveCustomItemNamesValueServerTransport instance is connected to an instance of xmlgroup.XMLModelWithWrappedPrimitiveCustomItemNamesValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMLModelWithWrappedPrimitiveCustomItemNamesValueServerTransport(srv *XMLModelWithWrappedPrimitiveCustomItemNamesValueServer) *XMLModelWithWrappedPrimitiveCustomItemNamesValueServerTransport { + return &XMLModelWithWrappedPrimitiveCustomItemNamesValueServerTransport{srv: srv} +} + +// XMLModelWithWrappedPrimitiveCustomItemNamesValueServerTransport connects instances of xmlgroup.XMLModelWithWrappedPrimitiveCustomItemNamesValueClient to instances of XMLModelWithWrappedPrimitiveCustomItemNamesValueServer. +// Don't use this type directly, use NewXMLModelWithWrappedPrimitiveCustomItemNamesValueServerTransport instead. +type XMLModelWithWrappedPrimitiveCustomItemNamesValueServerTransport struct { + srv *XMLModelWithWrappedPrimitiveCustomItemNamesValueServer +} + +// Do implements the policy.Transporter interface for XMLModelWithWrappedPrimitiveCustomItemNamesValueServerTransport. +func (x *XMLModelWithWrappedPrimitiveCustomItemNamesValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToMethodFake(req, method) +} + +func (x *XMLModelWithWrappedPrimitiveCustomItemNamesValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if xmlModelWithWrappedPrimitiveCustomItemNamesValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = xmlModelWithWrappedPrimitiveCustomItemNamesValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "XMLModelWithWrappedPrimitiveCustomItemNamesValueClient.Get": + res.resp, res.err = x.dispatchGet(req) + case "XMLModelWithWrappedPrimitiveCustomItemNamesValueClient.Put": + res.resp, res.err = x.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (x *XMLModelWithWrappedPrimitiveCustomItemNamesValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if x.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := x.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr).ModelWithWrappedPrimitiveCustomItemNames, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (x *XMLModelWithWrappedPrimitiveCustomItemNamesValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if x.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsXML[xmlgroup.ModelWithWrappedPrimitiveCustomItemNames](req) + if err != nil { + return nil, err + } + respr, errRespr := x.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to XMLModelWithWrappedPrimitiveCustomItemNamesValueServerTransport +var xmlModelWithWrappedPrimitiveCustomItemNamesValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/xmlgroup/fake/zz_xmlsimplemodelvalue_server.go b/test/http-specs/payload/xmlgroup/fake/zz_xmlsimplemodelvalue_server.go new file mode 100644 index 000000000000..f1ded677c6c5 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_xmlsimplemodelvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "xmlgroup" +) + +// XMLSimpleModelValueServer is a fake server for instances of the xmlgroup.XMLSimpleModelValueClient type. +type XMLSimpleModelValueServer struct { + // Get is the fake for method XMLSimpleModelValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *xmlgroup.XMLSimpleModelValueClientGetOptions) (resp azfake.Responder[xmlgroup.XMLSimpleModelValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method XMLSimpleModelValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, input xmlgroup.SimpleModel, options *xmlgroup.XMLSimpleModelValueClientPutOptions) (resp azfake.Responder[xmlgroup.XMLSimpleModelValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewXMLSimpleModelValueServerTransport creates a new instance of XMLSimpleModelValueServerTransport with the provided implementation. +// The returned XMLSimpleModelValueServerTransport instance is connected to an instance of xmlgroup.XMLSimpleModelValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMLSimpleModelValueServerTransport(srv *XMLSimpleModelValueServer) *XMLSimpleModelValueServerTransport { + return &XMLSimpleModelValueServerTransport{srv: srv} +} + +// XMLSimpleModelValueServerTransport connects instances of xmlgroup.XMLSimpleModelValueClient to instances of XMLSimpleModelValueServer. +// Don't use this type directly, use NewXMLSimpleModelValueServerTransport instead. +type XMLSimpleModelValueServerTransport struct { + srv *XMLSimpleModelValueServer +} + +// Do implements the policy.Transporter interface for XMLSimpleModelValueServerTransport. +func (x *XMLSimpleModelValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToMethodFake(req, method) +} + +func (x *XMLSimpleModelValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if xmlSimpleModelValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = xmlSimpleModelValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "XMLSimpleModelValueClient.Get": + res.resp, res.err = x.dispatchGet(req) + case "XMLSimpleModelValueClient.Put": + res.resp, res.err = x.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (x *XMLSimpleModelValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if x.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := x.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr).SimpleModel, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (x *XMLSimpleModelValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if x.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsXML[xmlgroup.SimpleModel](req) + if err != nil { + return nil, err + } + respr, errRespr := x.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to XMLSimpleModelValueServerTransport +var xmlSimpleModelValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/xmlgroup/fake/zz_xmlxmlerrorvalue_server.go b/test/http-specs/payload/xmlgroup/fake/zz_xmlxmlerrorvalue_server.go new file mode 100644 index 000000000000..619719d00923 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/fake/zz_xmlxmlerrorvalue_server.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "xmlgroup" +) + +// XMLXMLErrorValueServer is a fake server for instances of the xmlgroup.XMLXMLErrorValueClient type. +type XMLXMLErrorValueServer struct { + // Get is the fake for method XMLXMLErrorValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *xmlgroup.XMLXMLErrorValueClientGetOptions) (resp azfake.Responder[xmlgroup.XMLXMLErrorValueClientGetResponse], errResp azfake.ErrorResponder) +} + +// NewXMLXMLErrorValueServerTransport creates a new instance of XMLXMLErrorValueServerTransport with the provided implementation. +// The returned XMLXMLErrorValueServerTransport instance is connected to an instance of xmlgroup.XMLXMLErrorValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewXMLXMLErrorValueServerTransport(srv *XMLXMLErrorValueServer) *XMLXMLErrorValueServerTransport { + return &XMLXMLErrorValueServerTransport{srv: srv} +} + +// XMLXMLErrorValueServerTransport connects instances of xmlgroup.XMLXMLErrorValueClient to instances of XMLXMLErrorValueServer. +// Don't use this type directly, use NewXMLXMLErrorValueServerTransport instead. +type XMLXMLErrorValueServerTransport struct { + srv *XMLXMLErrorValueServer +} + +// Do implements the policy.Transporter interface for XMLXMLErrorValueServerTransport. +func (x *XMLXMLErrorValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return x.dispatchToMethodFake(req, method) +} + +func (x *XMLXMLErrorValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if xmlxmlErrorValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = xmlxmlErrorValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "XMLXMLErrorValueClient.Get": + res.resp, res.err = x.dispatchGet(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (x *XMLXMLErrorValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if x.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := x.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr).SimpleModel, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to XMLXMLErrorValueServerTransport +var xmlxmlErrorValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/payload/xmlgroup/go.mod b/test/http-specs/payload/xmlgroup/go.mod new file mode 100644 index 000000000000..8dda02ca8dd9 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/go.mod @@ -0,0 +1,17 @@ +module xmlgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/payload/xmlgroup/go.sum b/test/http-specs/payload/xmlgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/payload/xmlgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/payload/xmlgroup/testdata/_metadata.json b/test/http-specs/payload/xmlgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/payload/xmlgroup/xmlmodelwitharrayofmodelvalue_client_test.go b/test/http-specs/payload/xmlgroup/xmlmodelwitharrayofmodelvalue_client_test.go new file mode 100644 index 000000000000..ee897b014e4f --- /dev/null +++ b/test/http-specs/payload/xmlgroup/xmlmodelwitharrayofmodelvalue_client_test.go @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package xmlgroup_test + +import ( + "context" + "testing" + "xmlgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestXMLModelWithArrayOfModelValueClient_Get(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithArrayOfModelValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, xmlgroup.ModelWithArrayOfModel{ + Items: []xmlgroup.SimpleModel{ + { + Name: to.Ptr("foo"), + Age: to.Ptr[int32](123), + }, + { + Name: to.Ptr("bar"), + Age: to.Ptr[int32](456), + }, + }, + }, resp.ModelWithArrayOfModel) +} + +func TestXMLModelWithArrayOfModelValueClient_Put(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithArrayOfModelValueClient().Put(context.Background(), xmlgroup.ModelWithArrayOfModel{ + Items: []xmlgroup.SimpleModel{ + { + Name: to.Ptr("foo"), + Age: to.Ptr[int32](123), + }, + { + Name: to.Ptr("bar"), + Age: to.Ptr[int32](456), + }, + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/xmlgroup/xmlmodelwithattributesvalue_client_test.go b/test/http-specs/payload/xmlgroup/xmlmodelwithattributesvalue_client_test.go new file mode 100644 index 000000000000..2a38a81ec682 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/xmlmodelwithattributesvalue_client_test.go @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package xmlgroup_test + +import ( + "context" + "testing" + "xmlgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestXMLModelWithAttributesValueClient_Get(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithAttributesValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, xmlgroup.ModelWithAttributes{ + Id1: to.Ptr[int32](123), + Id2: to.Ptr("foo"), + Enabled: to.Ptr(true), + }, resp.ModelWithAttributes) +} + +func TestXMLModelWithAttributesValueClient_Put(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithAttributesValueClient().Put(context.Background(), xmlgroup.ModelWithAttributes{ + Id1: to.Ptr[int32](123), + Id2: to.Ptr("foo"), + Enabled: to.Ptr(true), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/xmlgroup/xmlmodelwithdatetimevalue_client_test.go b/test/http-specs/payload/xmlgroup/xmlmodelwithdatetimevalue_client_test.go new file mode 100644 index 000000000000..bb4f83d07d78 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/xmlmodelwithdatetimevalue_client_test.go @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package xmlgroup_test + +import ( + "context" + "testing" + "time" + "xmlgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestXMLModelWithDatetimeValueClient_Get(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithDatetimeValueClient().Get(context.Background(), nil) + require.NoError(t, err) + rfc3339 := time.Date(2022, 8, 26, 18, 38, 0, 0, time.UTC) + rfc7231 := time.Date(2022, 8, 26, 14, 38, 0, 0, time.UTC) + require.NotNil(t, resp.RFC3339) + require.True(t, rfc3339.Equal(*resp.RFC3339)) + require.NotNil(t, resp.RFC7231) + require.True(t, rfc7231.Equal(*resp.RFC7231)) +} + +func TestXMLModelWithDatetimeValueClient_Put(t *testing.T) { + t.Skip("Go's datetime.RFC1123 marshals as 'UTC' but the mock server expects 'GMT'") + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + rfc3339 := time.Date(2022, 8, 26, 18, 38, 0, 0, time.UTC) + rfc7231 := time.Date(2022, 8, 26, 14, 38, 0, 0, time.UTC) + resp, err := client.NewXMLModelWithDatetimeValueClient().Put(context.Background(), xmlgroup.ModelWithDatetime{ + RFC3339: to.Ptr(rfc3339), + RFC7231: to.Ptr(rfc7231), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/xmlgroup/xmlmodelwithdictionaryvalue_client_test.go b/test/http-specs/payload/xmlgroup/xmlmodelwithdictionaryvalue_client_test.go new file mode 100644 index 000000000000..147067d2c628 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/xmlmodelwithdictionaryvalue_client_test.go @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package xmlgroup_test + +import ( + "context" + "testing" + "xmlgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestXMLModelWithDictionaryValueClient_Get(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithDictionaryValueClient().Get(context.Background(), nil) + require.NoError(t, err) + // TODO: xml helper for maps lower-cases keys :( + require.EqualValues(t, xmlgroup.ModelWithDictionary{ + Metadata: map[string]*string{ + "color": to.Ptr("blue"), + "count": to.Ptr("123"), + "enabled": to.Ptr("false"), + }, + }, resp.ModelWithDictionary) +} + +func TestXMLModelWithDictionaryValueClient_Put(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithDictionaryValueClient().Put(context.Background(), xmlgroup.ModelWithDictionary{ + Metadata: map[string]*string{ + "Color": to.Ptr("blue"), + "Count": to.Ptr("123"), + "Enabled": to.Ptr("false"), + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/xmlgroup/xmlmodelwithemptyarrayvalue_client_test.go b/test/http-specs/payload/xmlgroup/xmlmodelwithemptyarrayvalue_client_test.go new file mode 100644 index 000000000000..c7edffa1e3df --- /dev/null +++ b/test/http-specs/payload/xmlgroup/xmlmodelwithemptyarrayvalue_client_test.go @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package xmlgroup_test + +import ( + "context" + "testing" + "xmlgroup" + + "github.com/stretchr/testify/require" +) + +func TestXMLModelWithEmptyArrayValueClient_Get(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithEmptyArrayValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, xmlgroup.ModelWithEmptyArray{}, resp.ModelWithEmptyArray) +} + +func TestXMLModelWithEmptyArrayValueClient_Put(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithEmptyArrayValueClient().Put(context.Background(), xmlgroup.ModelWithEmptyArray{ + Items: []xmlgroup.SimpleModel{}, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/xmlgroup/xmlmodelwithencodednamesvalue_client_test.go b/test/http-specs/payload/xmlgroup/xmlmodelwithencodednamesvalue_client_test.go new file mode 100644 index 000000000000..f6dd1ccedf67 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/xmlmodelwithencodednamesvalue_client_test.go @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package xmlgroup_test + +import ( + "context" + "testing" + "xmlgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestXMLModelWithEncodedNamesValueClient_Get(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithEncodedNamesValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.Equal(t, xmlgroup.ModelWithEncodedNames{ + Colors: []string{"red", "green", "blue"}, + ModelData: &xmlgroup.SimpleModel{ + Age: to.Ptr(int32(123)), + Name: to.Ptr("foo"), + }, + }, resp.ModelWithEncodedNames) +} + +func TestXMLModelWithEncodedNamesValueClient_Put(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithEncodedNamesValueClient().Put(context.Background(), xmlgroup.ModelWithEncodedNames{ + Colors: []string{"red", "green", "blue"}, + ModelData: &xmlgroup.SimpleModel{ + Age: to.Ptr(int32(123)), + Name: to.Ptr("foo"), + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/xmlgroup/xmlmodelwithenumvalue_client_test.go b/test/http-specs/payload/xmlgroup/xmlmodelwithenumvalue_client_test.go new file mode 100644 index 000000000000..df6fdb892758 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/xmlmodelwithenumvalue_client_test.go @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package xmlgroup_test + +import ( + "context" + "testing" + "xmlgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestXMLModelWithEnumValueClient_Get(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithEnumValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, xmlgroup.ModelWithEnum{ + Status: to.Ptr(xmlgroup.StatusSuccess), + }, resp.ModelWithEnum) +} + +func TestXMLModelWithEnumValueClient_Put(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithEnumValueClient().Put(context.Background(), xmlgroup.ModelWithEnum{ + Status: to.Ptr(xmlgroup.StatusSuccess), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/xmlgroup/xmlmodelwithnamespaceonpropertiesvalue_client_test.go b/test/http-specs/payload/xmlgroup/xmlmodelwithnamespaceonpropertiesvalue_client_test.go new file mode 100644 index 000000000000..faa980f0cc1c --- /dev/null +++ b/test/http-specs/payload/xmlgroup/xmlmodelwithnamespaceonpropertiesvalue_client_test.go @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package xmlgroup_test + +import ( + "context" + "testing" + "xmlgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestXMLModelWithNamespaceOnPropertiesValueClient_Get(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithNamespaceOnPropertiesValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, xmlgroup.ModelWithNamespaceOnProperties{ + ID: to.Ptr[int32](123), + Title: to.Ptr("The Great Gatsby"), + Author: to.Ptr("F. Scott Fitzgerald"), + }, resp.ModelWithNamespaceOnProperties) +} + +func TestXMLModelWithNamespaceOnPropertiesValueClient_Put(t *testing.T) { + t.Skip("codegen bug: no XML namespace serde generated, server expects namespace-prefixed XML") + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithNamespaceOnPropertiesValueClient().Put(context.Background(), xmlgroup.ModelWithNamespaceOnProperties{ + ID: to.Ptr[int32](123), + Title: to.Ptr("The Great Gatsby"), + Author: to.Ptr("F. Scott Fitzgerald"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/xmlgroup/xmlmodelwithnamespacevalue_client_test.go b/test/http-specs/payload/xmlgroup/xmlmodelwithnamespacevalue_client_test.go new file mode 100644 index 000000000000..9d9fb76796c0 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/xmlmodelwithnamespacevalue_client_test.go @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package xmlgroup_test + +import ( + "context" + "testing" + "xmlgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestXMLModelWithNamespaceValueClient_Get(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithNamespaceValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, xmlgroup.ModelWithNamespace{ + ID: to.Ptr[int32](123), + Title: to.Ptr("The Great Gatsby"), + }, resp.ModelWithNamespace) +} + +func TestXMLModelWithNamespaceValueClient_Put(t *testing.T) { + t.Skip("codegen bug: no XML namespace serde generated, server expects namespace-prefixed XML") + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithNamespaceValueClient().Put(context.Background(), xmlgroup.ModelWithNamespace{ + ID: to.Ptr[int32](123), + Title: to.Ptr("The Great Gatsby"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/xmlgroup/xmlmodelwithnestedmodelvalue_client_test.go b/test/http-specs/payload/xmlgroup/xmlmodelwithnestedmodelvalue_client_test.go new file mode 100644 index 000000000000..43aeb934128b --- /dev/null +++ b/test/http-specs/payload/xmlgroup/xmlmodelwithnestedmodelvalue_client_test.go @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package xmlgroup_test + +import ( + "context" + "testing" + "xmlgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestXMLModelWithNestedModelValueClient_Get(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithNestedModelValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, xmlgroup.ModelWithNestedModel{ + Nested: &xmlgroup.SimpleModel{ + Name: to.Ptr("foo"), + Age: to.Ptr[int32](123), + }, + }, resp.ModelWithNestedModel) +} + +func TestXMLModelWithNestedModelValueClient_Put(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithNestedModelValueClient().Put(context.Background(), xmlgroup.ModelWithNestedModel{ + Nested: &xmlgroup.SimpleModel{ + Name: to.Ptr("foo"), + Age: to.Ptr[int32](123), + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/xmlgroup/xmlmodelwithoptionalfieldvalue_client_test.go b/test/http-specs/payload/xmlgroup/xmlmodelwithoptionalfieldvalue_client_test.go new file mode 100644 index 000000000000..ba23beedcff5 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/xmlmodelwithoptionalfieldvalue_client_test.go @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package xmlgroup_test + +import ( + "context" + "testing" + "xmlgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestXMLModelWithOptionalFieldValueClient_Get(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithOptionalFieldValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, xmlgroup.ModelWithOptionalField{ + Item: to.Ptr("widget"), + }, resp.ModelWithOptionalField) +} + +func TestXMLModelWithOptionalFieldValueClient_Put(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithOptionalFieldValueClient().Put(context.Background(), xmlgroup.ModelWithOptionalField{ + Item: to.Ptr("widget"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/xmlgroup/xmlmodelwithrenamedarraysvalue_client_test.go b/test/http-specs/payload/xmlgroup/xmlmodelwithrenamedarraysvalue_client_test.go new file mode 100644 index 000000000000..5a64f38239a0 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/xmlmodelwithrenamedarraysvalue_client_test.go @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package xmlgroup_test + +import ( + "context" + "testing" + "xmlgroup" + + "github.com/stretchr/testify/require" +) + +func TestXMLModelWithRenamedArraysValueClient_Get(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithRenamedArraysValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.Equal(t, xmlgroup.ModelWithRenamedArrays{ + Colors: []string{"red", "green", "blue"}, + Counts: []int32{1, 2}, + }, resp.ModelWithRenamedArrays) +} + +func TestXMLModelWithRenamedArraysValueClient_Put(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithRenamedArraysValueClient().Put(context.Background(), xmlgroup.ModelWithRenamedArrays{ + Colors: []string{"red", "green", "blue"}, + Counts: []int32{1, 2}, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/xmlgroup/xmlmodelwithrenamedattributevalue_client_test.go b/test/http-specs/payload/xmlgroup/xmlmodelwithrenamedattributevalue_client_test.go new file mode 100644 index 000000000000..3941f2f0c444 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/xmlmodelwithrenamedattributevalue_client_test.go @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package xmlgroup_test + +import ( + "context" + "testing" + "xmlgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestXMLModelWithRenamedAttributeValueClient_Get(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithRenamedAttributeValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, xmlgroup.ModelWithRenamedAttribute{ + ID: to.Ptr[int32](123), + Title: to.Ptr("The Great Gatsby"), + Author: to.Ptr("F. Scott Fitzgerald"), + }, resp.ModelWithRenamedAttribute) +} + +func TestXMLModelWithRenamedAttributeValueClient_Put(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithRenamedAttributeValueClient().Put(context.Background(), xmlgroup.ModelWithRenamedAttribute{ + ID: to.Ptr[int32](123), + Title: to.Ptr("The Great Gatsby"), + Author: to.Ptr("F. Scott Fitzgerald"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/xmlgroup/xmlmodelwithrenamedfieldsvalue_client_test.go b/test/http-specs/payload/xmlgroup/xmlmodelwithrenamedfieldsvalue_client_test.go new file mode 100644 index 000000000000..723ad55e2377 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/xmlmodelwithrenamedfieldsvalue_client_test.go @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package xmlgroup_test + +import ( + "context" + "testing" + "xmlgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestXMLModelWithRenamedFieldsValueClient_Get(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithRenamedFieldsValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, xmlgroup.ModelWithRenamedFields{ + InputData: &xmlgroup.SimpleModel{ + Name: to.Ptr("foo"), + Age: to.Ptr[int32](123), + }, + OutputData: &xmlgroup.SimpleModel{ + Name: to.Ptr("bar"), + Age: to.Ptr[int32](456), + }, + }, resp.ModelWithRenamedFields) +} + +func TestXMLModelWithRenamedFieldsValueClient_Put(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithRenamedFieldsValueClient().Put(context.Background(), xmlgroup.ModelWithRenamedFields{ + InputData: &xmlgroup.SimpleModel{ + Name: to.Ptr("foo"), + Age: to.Ptr[int32](123), + }, + OutputData: &xmlgroup.SimpleModel{ + Name: to.Ptr("bar"), + Age: to.Ptr[int32](456), + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/xmlgroup/xmlmodelwithrenamednestedmodelvalue_client_test.go b/test/http-specs/payload/xmlgroup/xmlmodelwithrenamednestedmodelvalue_client_test.go new file mode 100644 index 000000000000..89a06315cfa9 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/xmlmodelwithrenamednestedmodelvalue_client_test.go @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package xmlgroup_test + +import ( + "context" + "testing" + "xmlgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestXMLModelWithRenamedNestedModelValueClient_Get(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithRenamedNestedModelValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, xmlgroup.ModelWithRenamedNestedModel{ + Author: &xmlgroup.Author{ + Name: to.Ptr("foo"), + }, + }, resp.ModelWithRenamedNestedModel) +} + +func TestXMLModelWithRenamedNestedModelValueClient_Put(t *testing.T) { + t.Skip("codegen bug: Author.MarshalXML overrides element name to 'XmlAuthor' instead of using field tag 'author'") + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithRenamedNestedModelValueClient().Put(context.Background(), xmlgroup.ModelWithRenamedNestedModel{ + Author: &xmlgroup.Author{ + Name: to.Ptr("foo"), + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/xmlgroup/xmlmodelwithrenamedpropertyvalue_client_test.go b/test/http-specs/payload/xmlgroup/xmlmodelwithrenamedpropertyvalue_client_test.go new file mode 100644 index 000000000000..213cd81d291b --- /dev/null +++ b/test/http-specs/payload/xmlgroup/xmlmodelwithrenamedpropertyvalue_client_test.go @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package xmlgroup_test + +import ( + "context" + "testing" + "xmlgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestXMLModelWithRenamedPropertyValueClient_Get(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithRenamedPropertyValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, xmlgroup.ModelWithRenamedProperty{ + Title: to.Ptr("foo"), + Author: to.Ptr("bar"), + }, resp.ModelWithRenamedProperty) +} + +func TestXMLModelWithRenamedPropertyValueClient_Put(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithRenamedPropertyValueClient().Put(context.Background(), xmlgroup.ModelWithRenamedProperty{ + Title: to.Ptr("foo"), + Author: to.Ptr("bar"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/xmlgroup/xmlmodelwithrenamedunwrappedmodelarrayvalue_client_test.go b/test/http-specs/payload/xmlgroup/xmlmodelwithrenamedunwrappedmodelarrayvalue_client_test.go new file mode 100644 index 000000000000..c069538fa1a5 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/xmlmodelwithrenamedunwrappedmodelarrayvalue_client_test.go @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package xmlgroup_test + +import ( + "context" + "testing" + "xmlgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestXMLModelWithRenamedUnwrappedModelArrayValueClient_Get(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithRenamedUnwrappedModelArrayValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, xmlgroup.ModelWithRenamedUnwrappedModelArray{ + Items: []xmlgroup.SimpleModel{ + { + Name: to.Ptr("foo"), + Age: to.Ptr[int32](123), + }, + { + Name: to.Ptr("bar"), + Age: to.Ptr[int32](456), + }, + }, + }, resp.ModelWithRenamedUnwrappedModelArray) +} + +func TestXMLModelWithRenamedUnwrappedModelArrayValueClient_Put(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithRenamedUnwrappedModelArrayValueClient().Put(context.Background(), xmlgroup.ModelWithRenamedUnwrappedModelArray{ + Items: []xmlgroup.SimpleModel{ + { + Name: to.Ptr("foo"), + Age: to.Ptr[int32](123), + }, + { + Name: to.Ptr("bar"), + Age: to.Ptr[int32](456), + }, + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/xmlgroup/xmlmodelwithrenamedwrappedanditemmodelarrayvalue_client_test.go b/test/http-specs/payload/xmlgroup/xmlmodelwithrenamedwrappedanditemmodelarrayvalue_client_test.go new file mode 100644 index 000000000000..ebfba5a9739d --- /dev/null +++ b/test/http-specs/payload/xmlgroup/xmlmodelwithrenamedwrappedanditemmodelarrayvalue_client_test.go @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package xmlgroup_test + +import ( + "context" + "testing" + "xmlgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestXMLModelWithRenamedWrappedAndItemModelArrayValueClient_Get(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithRenamedWrappedAndItemModelArrayValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, xmlgroup.ModelWithRenamedWrappedAndItemModelArray{ + Books: []xmlgroup.Book{ + { + Title: to.Ptr("The Great Gatsby"), + }, + { + Title: to.Ptr("Les Miserables"), + }, + }, + }, resp.ModelWithRenamedWrappedAndItemModelArray) +} + +func TestXMLModelWithRenamedWrappedAndItemModelArrayValueClient_Put(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithRenamedWrappedAndItemModelArrayValueClient().Put(context.Background(), xmlgroup.ModelWithRenamedWrappedAndItemModelArray{ + Books: []xmlgroup.Book{ + { + Title: to.Ptr("The Great Gatsby"), + }, + { + Title: to.Ptr("Les Miserables"), + }, + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/xmlgroup/xmlmodelwithrenamedwrappedmodelarrayvalue_client_test.go b/test/http-specs/payload/xmlgroup/xmlmodelwithrenamedwrappedmodelarrayvalue_client_test.go new file mode 100644 index 000000000000..d1c97373117f --- /dev/null +++ b/test/http-specs/payload/xmlgroup/xmlmodelwithrenamedwrappedmodelarrayvalue_client_test.go @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package xmlgroup_test + +import ( + "context" + "testing" + "xmlgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestXMLModelWithRenamedWrappedModelArrayValueClient_Get(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithRenamedWrappedModelArrayValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, xmlgroup.ModelWithRenamedWrappedModelArray{ + Items: []xmlgroup.SimpleModel{ + { + Name: to.Ptr("foo"), + Age: to.Ptr[int32](123), + }, + { + Name: to.Ptr("bar"), + Age: to.Ptr[int32](456), + }, + }, + }, resp.ModelWithRenamedWrappedModelArray) +} + +func TestXMLModelWithRenamedWrappedModelArrayValueClient_Put(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithRenamedWrappedModelArrayValueClient().Put(context.Background(), xmlgroup.ModelWithRenamedWrappedModelArray{ + Items: []xmlgroup.SimpleModel{ + { + Name: to.Ptr("foo"), + Age: to.Ptr[int32](123), + }, + { + Name: to.Ptr("bar"), + Age: to.Ptr[int32](456), + }, + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/xmlgroup/xmlmodelwithsimplearraysvalue_client_test.go b/test/http-specs/payload/xmlgroup/xmlmodelwithsimplearraysvalue_client_test.go new file mode 100644 index 000000000000..d28006e59a4c --- /dev/null +++ b/test/http-specs/payload/xmlgroup/xmlmodelwithsimplearraysvalue_client_test.go @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package xmlgroup_test + +import ( + "context" + "testing" + "xmlgroup" + + "github.com/stretchr/testify/require" +) + +func TestXMLModelWithSimpleArraysValueClient_Get(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithSimpleArraysValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, xmlgroup.ModelWithSimpleArrays{ + Colors: []string{"red", "green", "blue"}, + Counts: []int32{1, 2}, + }, resp.ModelWithSimpleArrays) +} + +func TestXMLModelWithSimpleArraysValueClient_Put(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithSimpleArraysValueClient().Put(context.Background(), xmlgroup.ModelWithSimpleArrays{ + Colors: []string{"red", "green", "blue"}, + Counts: []int32{1, 2}, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/xmlgroup/xmlmodelwithtextvalue_client_test.go b/test/http-specs/payload/xmlgroup/xmlmodelwithtextvalue_client_test.go new file mode 100644 index 000000000000..fd2a90109a71 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/xmlmodelwithtextvalue_client_test.go @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package xmlgroup_test + +import ( + "context" + "testing" + "xmlgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestXMLModelWithTextValueClient_Get(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithTextValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, xmlgroup.ModelWithText{ + Language: to.Ptr("foo"), + Content: to.Ptr("\n This is some text.\n"), + }, resp.ModelWithText) +} + +func TestXMLModelWithTextValueClient_Put(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithTextValueClient().Put(context.Background(), xmlgroup.ModelWithText{ + Language: to.Ptr("foo"), + Content: to.Ptr("This is some text."), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/xmlgroup/xmlmodelwithunwrappedarrayvalue_client_test.go b/test/http-specs/payload/xmlgroup/xmlmodelwithunwrappedarrayvalue_client_test.go new file mode 100644 index 000000000000..d606e77ed998 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/xmlmodelwithunwrappedarrayvalue_client_test.go @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package xmlgroup_test + +import ( + "context" + "testing" + "xmlgroup" + + "github.com/stretchr/testify/require" +) + +func TestXMLModelWithUnwrappedArrayValueClient_Get(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithUnwrappedArrayValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, xmlgroup.ModelWithUnwrappedArray{ + Colors: []string{"red", "green", "blue"}, + Counts: []int32{1, 2}, + }, resp.ModelWithUnwrappedArray) +} + +func TestXMLModelWithUnwrappedArrayValueClient_Put(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithUnwrappedArrayValueClient().Put(context.Background(), xmlgroup.ModelWithUnwrappedArray{ + Colors: []string{"red", "green", "blue"}, + Counts: []int32{1, 2}, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/xmlgroup/xmlmodelwithunwrappedmodelarrayvalue_client_test.go b/test/http-specs/payload/xmlgroup/xmlmodelwithunwrappedmodelarrayvalue_client_test.go new file mode 100644 index 000000000000..3313bead7b31 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/xmlmodelwithunwrappedmodelarrayvalue_client_test.go @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package xmlgroup_test + +import ( + "context" + "testing" + "xmlgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestXMLModelWithUnwrappedModelArrayValueClient_Get(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithUnwrappedModelArrayValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, xmlgroup.ModelWithUnwrappedModelArray{ + Items: []xmlgroup.SimpleModel{ + { + Name: to.Ptr("foo"), + Age: to.Ptr[int32](123), + }, + { + Name: to.Ptr("bar"), + Age: to.Ptr[int32](456), + }, + }, + }, resp.ModelWithUnwrappedModelArray) +} + +func TestXMLModelWithUnwrappedModelArrayValueClient_Put(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithUnwrappedModelArrayValueClient().Put(context.Background(), xmlgroup.ModelWithUnwrappedModelArray{ + Items: []xmlgroup.SimpleModel{ + { + Name: to.Ptr("foo"), + Age: to.Ptr[int32](123), + }, + { + Name: to.Ptr("bar"), + Age: to.Ptr[int32](456), + }, + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/xmlgroup/xmlmodelwithwrappedprimitivecustomitemnamesvalue_client_test.go b/test/http-specs/payload/xmlgroup/xmlmodelwithwrappedprimitivecustomitemnamesvalue_client_test.go new file mode 100644 index 000000000000..ec1507ca425b --- /dev/null +++ b/test/http-specs/payload/xmlgroup/xmlmodelwithwrappedprimitivecustomitemnamesvalue_client_test.go @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package xmlgroup_test + +import ( + "context" + "testing" + "xmlgroup" + + "github.com/stretchr/testify/require" +) + +func TestXMLModelWithWrappedPrimitiveCustomItemNamesValueClient_Get(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithWrappedPrimitiveCustomItemNamesValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.Equal(t, xmlgroup.ModelWithWrappedPrimitiveCustomItemNames{ + Tags: []string{"fiction", "classic"}, + }, resp.ModelWithWrappedPrimitiveCustomItemNames) +} + +func TestXMLModelWithWrappedPrimitiveCustomItemNamesValueClient_Put(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLModelWithWrappedPrimitiveCustomItemNamesValueClient().Put(context.Background(), xmlgroup.ModelWithWrappedPrimitiveCustomItemNames{ + Tags: []string{"fiction", "classic"}, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/xmlgroup/xmlsimplemodelvalue_client_test.go b/test/http-specs/payload/xmlgroup/xmlsimplemodelvalue_client_test.go new file mode 100644 index 000000000000..c205d59e75d6 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/xmlsimplemodelvalue_client_test.go @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package xmlgroup_test + +import ( + "context" + "testing" + "xmlgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestXMLSimpleModelValueClient_Get(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLSimpleModelValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, xmlgroup.SimpleModel{ + Age: to.Ptr[int32](123), + Name: to.Ptr("foo"), + }, resp.SimpleModel) +} + +func TestXMLSimpleModelValueClient_Put(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLSimpleModelValueClient().Put(context.Background(), xmlgroup.SimpleModel{ + Age: to.Ptr[int32](123), + Name: to.Ptr("foo"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/xmlgroup/xmlxmlerrorvalue_client_test.go b/test/http-specs/payload/xmlgroup/xmlxmlerrorvalue_client_test.go new file mode 100644 index 000000000000..449425ca3fd6 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/xmlxmlerrorvalue_client_test.go @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package xmlgroup_test + +import ( + "context" + "net/http" + "testing" + "xmlgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/stretchr/testify/require" +) + +func TestXMLXMLErrorValueClient_Get(t *testing.T) { + client, err := xmlgroup.NewXMLClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewXMLXMLErrorValueClient().Get(context.Background(), nil) + var respErr *azcore.ResponseError + require.Error(t, err) + require.ErrorAs(t, err, &respErr) + require.EqualValues(t, http.StatusBadRequest, respErr.StatusCode) + require.EqualValues(t, "400", respErr.ErrorCode) + require.Zero(t, resp) +} diff --git a/test/http-specs/payload/xmlgroup/zz_constants.go b/test/http-specs/payload/xmlgroup/zz_constants.go new file mode 100644 index 000000000000..f66ab2808322 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_constants.go @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +// Status - Status values for the model with enum. +type Status string + +const ( + // StatusError - Error status. + StatusError Status = "error" + // StatusPending - Pending status. + StatusPending Status = "pending" + // StatusSuccess - Success status. + StatusSuccess Status = "success" +) + +// PossibleStatusValues returns the possible values for the Status const type. +func PossibleStatusValues() []Status { + return []Status{ + StatusError, + StatusPending, + StatusSuccess, + } +} diff --git a/test/http-specs/payload/xmlgroup/zz_models.go b/test/http-specs/payload/xmlgroup/zz_models.go new file mode 100644 index 000000000000..1aa049245d2e --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_models.go @@ -0,0 +1,228 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import "time" + +// Author model with a custom XML name. +type Author struct { + // REQUIRED + Name *string `xml:"name"` +} + +// Book model with a custom XML name. +type Book struct { + // REQUIRED + Title *string `xml:"title"` +} + +// ModelWithArrayOfModel - §4.1 — Contains an array of models. +type ModelWithArrayOfModel struct { + // REQUIRED + Items []SimpleModel `xml:"items>SimpleModel"` +} + +// ModelWithAttributes - §5.1 — Contains fields that are XML attributes. +type ModelWithAttributes struct { + // REQUIRED + Enabled *bool `xml:"enabled"` + + // REQUIRED + Id1 *int32 `xml:"id1,attr"` + + // REQUIRED + Id2 *string `xml:"id2,attr"` +} + +// ModelWithDatetime - Contains datetime properties with different encodings. +type ModelWithDatetime struct { + // REQUIRED; DateTime value with rfc3339 encoding. + RFC3339 *time.Time `xml:"rfc3339"` + + // REQUIRED; DateTime value with rfc7231 encoding. + RFC7231 *time.Time `xml:"rfc7231"` +} + +// ModelWithDictionary - Contains a dictionary of key value pairs. +type ModelWithDictionary struct { + // REQUIRED + Metadata map[string]*string `xml:"metadata"` +} + +// ModelWithEmptyArray - Contains an array of models that's supposed to be sent/received as an empty XML element. +type ModelWithEmptyArray struct { + // REQUIRED + Items []SimpleModel `xml:"items>SimpleModel"` +} + +// ModelWithEncodedNames - Uses encodedName instead of Xml.Name which is functionally equivalent. +type ModelWithEncodedNames struct { + // REQUIRED + Colors []string `xml:"PossibleColors>string"` + + // REQUIRED + ModelData *SimpleModel `xml:"SimpleModelData"` +} + +// ModelWithEnum - Contains a single property with an enum value. +type ModelWithEnum struct { + // REQUIRED + Status *Status `xml:"status"` +} + +// ModelWithNamespace - §6.1, §7.1 — Contains fields with XML namespace on the model. +type ModelWithNamespace struct { + // REQUIRED + ID *int32 `xml:"id"` + + // REQUIRED + Title *string `xml:"title"` +} + +// ModelWithNamespaceOnProperties - §6.2, §7.2 — Contains fields with different XML namespaces on individual properties. +type ModelWithNamespaceOnProperties struct { + // REQUIRED + Author *string `xml:"author"` + + // REQUIRED + ID *int32 `xml:"id"` + + // REQUIRED + Title *string `xml:"title"` +} + +// ModelWithNestedModel - §2.1 — Contains a property that references another model. +type ModelWithNestedModel struct { + // REQUIRED + Nested *SimpleModel `xml:"nested"` +} + +// ModelWithOptionalField - Contains an optional field. +type ModelWithOptionalField struct { + // REQUIRED + Item *string `xml:"item"` + Value *int32 `xml:"value"` +} + +// ModelWithRenamedArrays - §3.3, §3.4 — Contains fields of wrapped and unwrapped arrays of primitive types that have different +// XML representations. +type ModelWithRenamedArrays struct { + // REQUIRED + Colors []string `xml:"Colors"` + + // REQUIRED + Counts []int32 `xml:"Counts>int32"` +} + +// ModelWithRenamedAttribute - §5.2 — Contains a renamed XML attribute. +type ModelWithRenamedAttribute struct { + // REQUIRED + Author *string `xml:"author"` + + // REQUIRED + ID *int32 `xml:"xml-id,attr"` + + // REQUIRED + Title *string `xml:"title"` +} + +// ModelWithRenamedFields - §1.3, §2.3 — Contains fields of the same type that have different XML representation. +type ModelWithRenamedFields struct { + // REQUIRED + InputData *SimpleModel `xml:"InputData"` + + // REQUIRED + OutputData *SimpleModel `xml:"OutputData"` +} + +// ModelWithRenamedNestedModel - §2.2 — Contains a property whose type has +type ModelWithRenamedNestedModel struct { + // REQUIRED + Author *Author `xml:"author"` +} + +// ModelWithRenamedProperty - §1.2 — Contains a scalar property with a custom XML name. +type ModelWithRenamedProperty struct { + // REQUIRED + Author *string `xml:"author"` + + // REQUIRED + Title *string `xml:"renamedTitle"` +} + +// ModelWithRenamedUnwrappedModelArray - §4.4 — Contains an unwrapped array of models with a custom item name. +type ModelWithRenamedUnwrappedModelArray struct { + // REQUIRED + Items []SimpleModel `xml:"ModelItem"` +} + +// ModelWithRenamedWrappedAndItemModelArray - §4.5 — Contains a wrapped array of models with custom wrapper and item names. +type ModelWithRenamedWrappedAndItemModelArray struct { + // REQUIRED + Books []Book `xml:"AllBooks>XmlBook"` +} + +// ModelWithRenamedWrappedModelArray - §4.3 — Contains a wrapped array of models with a custom wrapper name. +type ModelWithRenamedWrappedModelArray struct { + // REQUIRED + Items []SimpleModel `xml:"AllItems>SimpleModel"` +} + +// ModelWithSimpleArrays - §3.1 — Contains fields of arrays of primitive types. +type ModelWithSimpleArrays struct { + // REQUIRED + Colors []string `xml:"colors>string"` + + // REQUIRED + Counts []int32 `xml:"counts>int32"` +} + +// ModelWithText - §8.1 — Contains an attribute and text. +type ModelWithText struct { + // REQUIRED + Content *string `xml:",chardata"` + + // REQUIRED + Language *string `xml:"language,attr"` +} + +// ModelWithUnwrappedArray - §3.2 — Contains fields of wrapped and unwrapped arrays of primitive types. +type ModelWithUnwrappedArray struct { + // REQUIRED + Colors []string `xml:"colors"` + + // REQUIRED + Counts []int32 `xml:"counts>int32"` +} + +// ModelWithUnwrappedModelArray - §4.2 — Contains an unwrapped array of models. +type ModelWithUnwrappedModelArray struct { + // REQUIRED + Items []SimpleModel `xml:"items"` +} + +// ModelWithWrappedPrimitiveCustomItemNames - §3.5 — Contains a wrapped primitive array with custom wrapper and item names. +type ModelWithWrappedPrimitiveCustomItemNames struct { + // REQUIRED + Tags []string `xml:"ItemsTags>ItemName"` +} + +// SimpleModel - §1.1 — Contains fields of primitive types. +type SimpleModel struct { + // REQUIRED + Age *int32 `xml:"age"` + + // REQUIRED + Name *string `xml:"name"` +} + +// XMLErrorBody - The body of an XML error response. +type XMLErrorBody struct { + // REQUIRED + Code *int32 + + // REQUIRED + Message *string +} diff --git a/test/http-specs/payload/xmlgroup/zz_models_serde.go b/test/http-specs/payload/xmlgroup/zz_models_serde.go new file mode 100644 index 000000000000..268e5f759f76 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_models_serde.go @@ -0,0 +1,346 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "encoding/json" + "encoding/xml" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalXML implements the xml.Marshaller interface for type Author. +func (a Author) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + start.Name.Local = "XmlAuthor" + type alias Author + aux := &struct { + *alias + }{ + alias: (*alias)(&a), + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type Book. +func (b Book) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + start.Name.Local = "XmlBook" + type alias Book + aux := &struct { + *alias + }{ + alias: (*alias)(&b), + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type ModelWithArrayOfModel. +func (m ModelWithArrayOfModel) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + type alias ModelWithArrayOfModel + aux := &struct { + *alias + Items *[]SimpleModel `xml:"items>SimpleModel"` + }{ + alias: (*alias)(&m), + } + if m.Items != nil { + aux.Items = &m.Items + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type ModelWithDatetime. +func (m ModelWithDatetime) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + type alias ModelWithDatetime + aux := &struct { + *alias + RFC3339 *datetime.RFC3339 `xml:"rfc3339"` + RFC7231 *datetime.RFC7231 `xml:"rfc7231"` + }{ + alias: (*alias)(&m), + RFC3339: (*datetime.RFC3339)(m.RFC3339), + RFC7231: (*datetime.RFC7231)(m.RFC7231), + } + return enc.EncodeElement(aux, start) +} + +// UnmarshalXML implements the xml.Unmarshaller interface for type ModelWithDatetime. +func (m *ModelWithDatetime) UnmarshalXML(dec *xml.Decoder, start xml.StartElement) error { + type alias ModelWithDatetime + aux := &struct { + *alias + RFC3339 *datetime.RFC3339 `xml:"rfc3339"` + RFC7231 *datetime.RFC7231 `xml:"rfc7231"` + }{ + alias: (*alias)(m), + } + if err := dec.DecodeElement(aux, &start); err != nil { + return err + } + if aux.RFC3339 != nil && !(*time.Time)(aux.RFC3339).IsZero() { + m.RFC3339 = (*time.Time)(aux.RFC3339) + } + if aux.RFC7231 != nil && !(*time.Time)(aux.RFC7231).IsZero() { + m.RFC7231 = (*time.Time)(aux.RFC7231) + } + return nil +} + +// MarshalXML implements the xml.Marshaller interface for type ModelWithDictionary. +func (m ModelWithDictionary) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + type alias ModelWithDictionary + aux := &struct { + *alias + Metadata additionalProperties `xml:"metadata"` + }{ + alias: (*alias)(&m), + } + aux.Metadata = (additionalProperties)(m.Metadata) + return enc.EncodeElement(aux, start) +} + +// UnmarshalXML implements the xml.Unmarshaller interface for type ModelWithDictionary. +func (m *ModelWithDictionary) UnmarshalXML(dec *xml.Decoder, start xml.StartElement) error { + type alias ModelWithDictionary + aux := &struct { + *alias + Metadata additionalProperties `xml:"metadata"` + }{ + alias: (*alias)(m), + } + if err := dec.DecodeElement(aux, &start); err != nil { + return err + } + m.Metadata = (map[string]*string)(aux.Metadata) + return nil +} + +// MarshalXML implements the xml.Marshaller interface for type ModelWithEmptyArray. +func (m ModelWithEmptyArray) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + type alias ModelWithEmptyArray + aux := &struct { + *alias + Items *[]SimpleModel `xml:"items>SimpleModel"` + }{ + alias: (*alias)(&m), + } + if m.Items != nil { + aux.Items = &m.Items + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type ModelWithEncodedNames. +func (m ModelWithEncodedNames) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + start.Name.Local = "ModelWithEncodedNamesSrc" + type alias ModelWithEncodedNames + aux := &struct { + *alias + Colors *[]string `xml:"PossibleColors>string"` + }{ + alias: (*alias)(&m), + } + if m.Colors != nil { + aux.Colors = &m.Colors + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type ModelWithRenamedArrays. +func (m ModelWithRenamedArrays) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + type alias ModelWithRenamedArrays + aux := &struct { + *alias + Colors *[]string `xml:"Colors"` + Counts *[]int32 `xml:"Counts>int32"` + }{ + alias: (*alias)(&m), + } + if m.Colors != nil { + aux.Colors = &m.Colors + } + if m.Counts != nil { + aux.Counts = &m.Counts + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type ModelWithRenamedFields. +func (m ModelWithRenamedFields) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + start.Name.Local = "ModelWithRenamedFieldsSrc" + type alias ModelWithRenamedFields + aux := &struct { + *alias + }{ + alias: (*alias)(&m), + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type ModelWithRenamedUnwrappedModelArray. +func (m ModelWithRenamedUnwrappedModelArray) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + type alias ModelWithRenamedUnwrappedModelArray + aux := &struct { + *alias + Items *[]SimpleModel `xml:"ModelItem"` + }{ + alias: (*alias)(&m), + } + if m.Items != nil { + aux.Items = &m.Items + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type ModelWithRenamedWrappedAndItemModelArray. +func (m ModelWithRenamedWrappedAndItemModelArray) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + type alias ModelWithRenamedWrappedAndItemModelArray + aux := &struct { + *alias + Books *[]Book `xml:"AllBooks>XmlBook"` + }{ + alias: (*alias)(&m), + } + if m.Books != nil { + aux.Books = &m.Books + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type ModelWithRenamedWrappedModelArray. +func (m ModelWithRenamedWrappedModelArray) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + type alias ModelWithRenamedWrappedModelArray + aux := &struct { + *alias + Items *[]SimpleModel `xml:"AllItems>SimpleModel"` + }{ + alias: (*alias)(&m), + } + if m.Items != nil { + aux.Items = &m.Items + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type ModelWithSimpleArrays. +func (m ModelWithSimpleArrays) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + type alias ModelWithSimpleArrays + aux := &struct { + *alias + Colors *[]string `xml:"colors>string"` + Counts *[]int32 `xml:"counts>int32"` + }{ + alias: (*alias)(&m), + } + if m.Colors != nil { + aux.Colors = &m.Colors + } + if m.Counts != nil { + aux.Counts = &m.Counts + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type ModelWithUnwrappedArray. +func (m ModelWithUnwrappedArray) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + type alias ModelWithUnwrappedArray + aux := &struct { + *alias + Colors *[]string `xml:"colors"` + Counts *[]int32 `xml:"counts>int32"` + }{ + alias: (*alias)(&m), + } + if m.Colors != nil { + aux.Colors = &m.Colors + } + if m.Counts != nil { + aux.Counts = &m.Counts + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type ModelWithUnwrappedModelArray. +func (m ModelWithUnwrappedModelArray) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + type alias ModelWithUnwrappedModelArray + aux := &struct { + *alias + Items *[]SimpleModel `xml:"items"` + }{ + alias: (*alias)(&m), + } + if m.Items != nil { + aux.Items = &m.Items + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type ModelWithWrappedPrimitiveCustomItemNames. +func (m ModelWithWrappedPrimitiveCustomItemNames) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + type alias ModelWithWrappedPrimitiveCustomItemNames + aux := &struct { + *alias + Tags *[]string `xml:"ItemsTags>ItemName"` + }{ + alias: (*alias)(&m), + } + if m.Tags != nil { + aux.Tags = &m.Tags + } + return enc.EncodeElement(aux, start) +} + +// MarshalJSON implements the json.Marshaller interface for type XMLErrorBody. +func (x XMLErrorBody) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", x.Code) + populate(objectMap, "message", x.Message) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type XMLErrorBody. +func (x *XMLErrorBody) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", x, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "code": + err = unpopulate(val, "Code", &x.Code) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &x.Message) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", x, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/http-specs/payload/xmlgroup/zz_options.go b/test/http-specs/payload/xmlgroup/zz_options.go new file mode 100644 index 000000000000..194b9e9e6ed6 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_options.go @@ -0,0 +1,304 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +// XMLModelWithArrayOfModelValueClientGetOptions contains the optional parameters for the XMLModelWithArrayOfModelValueClient.Get +// method. +type XMLModelWithArrayOfModelValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithArrayOfModelValueClientPutOptions contains the optional parameters for the XMLModelWithArrayOfModelValueClient.Put +// method. +type XMLModelWithArrayOfModelValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithAttributesValueClientGetOptions contains the optional parameters for the XMLModelWithAttributesValueClient.Get +// method. +type XMLModelWithAttributesValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithAttributesValueClientPutOptions contains the optional parameters for the XMLModelWithAttributesValueClient.Put +// method. +type XMLModelWithAttributesValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithDatetimeValueClientGetOptions contains the optional parameters for the XMLModelWithDatetimeValueClient.Get +// method. +type XMLModelWithDatetimeValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithDatetimeValueClientPutOptions contains the optional parameters for the XMLModelWithDatetimeValueClient.Put +// method. +type XMLModelWithDatetimeValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithDictionaryValueClientGetOptions contains the optional parameters for the XMLModelWithDictionaryValueClient.Get +// method. +type XMLModelWithDictionaryValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithDictionaryValueClientPutOptions contains the optional parameters for the XMLModelWithDictionaryValueClient.Put +// method. +type XMLModelWithDictionaryValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithEmptyArrayValueClientGetOptions contains the optional parameters for the XMLModelWithEmptyArrayValueClient.Get +// method. +type XMLModelWithEmptyArrayValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithEmptyArrayValueClientPutOptions contains the optional parameters for the XMLModelWithEmptyArrayValueClient.Put +// method. +type XMLModelWithEmptyArrayValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithEncodedNamesValueClientGetOptions contains the optional parameters for the XMLModelWithEncodedNamesValueClient.Get +// method. +type XMLModelWithEncodedNamesValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithEncodedNamesValueClientPutOptions contains the optional parameters for the XMLModelWithEncodedNamesValueClient.Put +// method. +type XMLModelWithEncodedNamesValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithEnumValueClientGetOptions contains the optional parameters for the XMLModelWithEnumValueClient.Get method. +type XMLModelWithEnumValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithEnumValueClientPutOptions contains the optional parameters for the XMLModelWithEnumValueClient.Put method. +type XMLModelWithEnumValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithNamespaceOnPropertiesValueClientGetOptions contains the optional parameters for the XMLModelWithNamespaceOnPropertiesValueClient.Get +// method. +type XMLModelWithNamespaceOnPropertiesValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithNamespaceOnPropertiesValueClientPutOptions contains the optional parameters for the XMLModelWithNamespaceOnPropertiesValueClient.Put +// method. +type XMLModelWithNamespaceOnPropertiesValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithNamespaceValueClientGetOptions contains the optional parameters for the XMLModelWithNamespaceValueClient.Get +// method. +type XMLModelWithNamespaceValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithNamespaceValueClientPutOptions contains the optional parameters for the XMLModelWithNamespaceValueClient.Put +// method. +type XMLModelWithNamespaceValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithNestedModelValueClientGetOptions contains the optional parameters for the XMLModelWithNestedModelValueClient.Get +// method. +type XMLModelWithNestedModelValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithNestedModelValueClientPutOptions contains the optional parameters for the XMLModelWithNestedModelValueClient.Put +// method. +type XMLModelWithNestedModelValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithOptionalFieldValueClientGetOptions contains the optional parameters for the XMLModelWithOptionalFieldValueClient.Get +// method. +type XMLModelWithOptionalFieldValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithOptionalFieldValueClientPutOptions contains the optional parameters for the XMLModelWithOptionalFieldValueClient.Put +// method. +type XMLModelWithOptionalFieldValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithRenamedArraysValueClientGetOptions contains the optional parameters for the XMLModelWithRenamedArraysValueClient.Get +// method. +type XMLModelWithRenamedArraysValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithRenamedArraysValueClientPutOptions contains the optional parameters for the XMLModelWithRenamedArraysValueClient.Put +// method. +type XMLModelWithRenamedArraysValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithRenamedAttributeValueClientGetOptions contains the optional parameters for the XMLModelWithRenamedAttributeValueClient.Get +// method. +type XMLModelWithRenamedAttributeValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithRenamedAttributeValueClientPutOptions contains the optional parameters for the XMLModelWithRenamedAttributeValueClient.Put +// method. +type XMLModelWithRenamedAttributeValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithRenamedFieldsValueClientGetOptions contains the optional parameters for the XMLModelWithRenamedFieldsValueClient.Get +// method. +type XMLModelWithRenamedFieldsValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithRenamedFieldsValueClientPutOptions contains the optional parameters for the XMLModelWithRenamedFieldsValueClient.Put +// method. +type XMLModelWithRenamedFieldsValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithRenamedNestedModelValueClientGetOptions contains the optional parameters for the XMLModelWithRenamedNestedModelValueClient.Get +// method. +type XMLModelWithRenamedNestedModelValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithRenamedNestedModelValueClientPutOptions contains the optional parameters for the XMLModelWithRenamedNestedModelValueClient.Put +// method. +type XMLModelWithRenamedNestedModelValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithRenamedPropertyValueClientGetOptions contains the optional parameters for the XMLModelWithRenamedPropertyValueClient.Get +// method. +type XMLModelWithRenamedPropertyValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithRenamedPropertyValueClientPutOptions contains the optional parameters for the XMLModelWithRenamedPropertyValueClient.Put +// method. +type XMLModelWithRenamedPropertyValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithRenamedUnwrappedModelArrayValueClientGetOptions contains the optional parameters for the XMLModelWithRenamedUnwrappedModelArrayValueClient.Get +// method. +type XMLModelWithRenamedUnwrappedModelArrayValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithRenamedUnwrappedModelArrayValueClientPutOptions contains the optional parameters for the XMLModelWithRenamedUnwrappedModelArrayValueClient.Put +// method. +type XMLModelWithRenamedUnwrappedModelArrayValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithRenamedWrappedAndItemModelArrayValueClientGetOptions contains the optional parameters for the XMLModelWithRenamedWrappedAndItemModelArrayValueClient.Get +// method. +type XMLModelWithRenamedWrappedAndItemModelArrayValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithRenamedWrappedAndItemModelArrayValueClientPutOptions contains the optional parameters for the XMLModelWithRenamedWrappedAndItemModelArrayValueClient.Put +// method. +type XMLModelWithRenamedWrappedAndItemModelArrayValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithRenamedWrappedModelArrayValueClientGetOptions contains the optional parameters for the XMLModelWithRenamedWrappedModelArrayValueClient.Get +// method. +type XMLModelWithRenamedWrappedModelArrayValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithRenamedWrappedModelArrayValueClientPutOptions contains the optional parameters for the XMLModelWithRenamedWrappedModelArrayValueClient.Put +// method. +type XMLModelWithRenamedWrappedModelArrayValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithSimpleArraysValueClientGetOptions contains the optional parameters for the XMLModelWithSimpleArraysValueClient.Get +// method. +type XMLModelWithSimpleArraysValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithSimpleArraysValueClientPutOptions contains the optional parameters for the XMLModelWithSimpleArraysValueClient.Put +// method. +type XMLModelWithSimpleArraysValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithTextValueClientGetOptions contains the optional parameters for the XMLModelWithTextValueClient.Get method. +type XMLModelWithTextValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithTextValueClientPutOptions contains the optional parameters for the XMLModelWithTextValueClient.Put method. +type XMLModelWithTextValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithUnwrappedArrayValueClientGetOptions contains the optional parameters for the XMLModelWithUnwrappedArrayValueClient.Get +// method. +type XMLModelWithUnwrappedArrayValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithUnwrappedArrayValueClientPutOptions contains the optional parameters for the XMLModelWithUnwrappedArrayValueClient.Put +// method. +type XMLModelWithUnwrappedArrayValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithUnwrappedModelArrayValueClientGetOptions contains the optional parameters for the XMLModelWithUnwrappedModelArrayValueClient.Get +// method. +type XMLModelWithUnwrappedModelArrayValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithUnwrappedModelArrayValueClientPutOptions contains the optional parameters for the XMLModelWithUnwrappedModelArrayValueClient.Put +// method. +type XMLModelWithUnwrappedModelArrayValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithWrappedPrimitiveCustomItemNamesValueClientGetOptions contains the optional parameters for the XMLModelWithWrappedPrimitiveCustomItemNamesValueClient.Get +// method. +type XMLModelWithWrappedPrimitiveCustomItemNamesValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// XMLModelWithWrappedPrimitiveCustomItemNamesValueClientPutOptions contains the optional parameters for the XMLModelWithWrappedPrimitiveCustomItemNamesValueClient.Put +// method. +type XMLModelWithWrappedPrimitiveCustomItemNamesValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// XMLSimpleModelValueClientGetOptions contains the optional parameters for the XMLSimpleModelValueClient.Get method. +type XMLSimpleModelValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// XMLSimpleModelValueClientPutOptions contains the optional parameters for the XMLSimpleModelValueClient.Put method. +type XMLSimpleModelValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// XMLXMLErrorValueClientGetOptions contains the optional parameters for the XMLXMLErrorValueClient.Get method. +type XMLXMLErrorValueClientGetOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/payload/xmlgroup/zz_responses.go b/test/http-specs/payload/xmlgroup/zz_responses.go new file mode 100644 index 000000000000..38ebcd2dbbd1 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_responses.go @@ -0,0 +1,286 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +// XMLModelWithArrayOfModelValueClientGetResponse contains the response from method XMLModelWithArrayOfModelValueClient.Get. +type XMLModelWithArrayOfModelValueClientGetResponse struct { + // §4.1 — Contains an array of models. + ModelWithArrayOfModel +} + +// XMLModelWithArrayOfModelValueClientPutResponse contains the response from method XMLModelWithArrayOfModelValueClient.Put. +type XMLModelWithArrayOfModelValueClientPutResponse struct { + // placeholder for future response values +} + +// XMLModelWithAttributesValueClientGetResponse contains the response from method XMLModelWithAttributesValueClient.Get. +type XMLModelWithAttributesValueClientGetResponse struct { + // §5.1 — Contains fields that are XML attributes. + ModelWithAttributes +} + +// XMLModelWithAttributesValueClientPutResponse contains the response from method XMLModelWithAttributesValueClient.Put. +type XMLModelWithAttributesValueClientPutResponse struct { + // placeholder for future response values +} + +// XMLModelWithDatetimeValueClientGetResponse contains the response from method XMLModelWithDatetimeValueClient.Get. +type XMLModelWithDatetimeValueClientGetResponse struct { + // Contains datetime properties with different encodings. + ModelWithDatetime +} + +// XMLModelWithDatetimeValueClientPutResponse contains the response from method XMLModelWithDatetimeValueClient.Put. +type XMLModelWithDatetimeValueClientPutResponse struct { + // placeholder for future response values +} + +// XMLModelWithDictionaryValueClientGetResponse contains the response from method XMLModelWithDictionaryValueClient.Get. +type XMLModelWithDictionaryValueClientGetResponse struct { + // Contains a dictionary of key value pairs. + ModelWithDictionary +} + +// XMLModelWithDictionaryValueClientPutResponse contains the response from method XMLModelWithDictionaryValueClient.Put. +type XMLModelWithDictionaryValueClientPutResponse struct { + // placeholder for future response values +} + +// XMLModelWithEmptyArrayValueClientGetResponse contains the response from method XMLModelWithEmptyArrayValueClient.Get. +type XMLModelWithEmptyArrayValueClientGetResponse struct { + // Contains an array of models that's supposed to be sent/received as an empty XML element. + ModelWithEmptyArray +} + +// XMLModelWithEmptyArrayValueClientPutResponse contains the response from method XMLModelWithEmptyArrayValueClient.Put. +type XMLModelWithEmptyArrayValueClientPutResponse struct { + // placeholder for future response values +} + +// XMLModelWithEncodedNamesValueClientGetResponse contains the response from method XMLModelWithEncodedNamesValueClient.Get. +type XMLModelWithEncodedNamesValueClientGetResponse struct { + // Uses encodedName instead of Xml.Name which is functionally equivalent. + ModelWithEncodedNames +} + +// XMLModelWithEncodedNamesValueClientPutResponse contains the response from method XMLModelWithEncodedNamesValueClient.Put. +type XMLModelWithEncodedNamesValueClientPutResponse struct { + // placeholder for future response values +} + +// XMLModelWithEnumValueClientGetResponse contains the response from method XMLModelWithEnumValueClient.Get. +type XMLModelWithEnumValueClientGetResponse struct { + // Contains a single property with an enum value. + ModelWithEnum +} + +// XMLModelWithEnumValueClientPutResponse contains the response from method XMLModelWithEnumValueClient.Put. +type XMLModelWithEnumValueClientPutResponse struct { + // placeholder for future response values +} + +// XMLModelWithNamespaceOnPropertiesValueClientGetResponse contains the response from method XMLModelWithNamespaceOnPropertiesValueClient.Get. +type XMLModelWithNamespaceOnPropertiesValueClientGetResponse struct { + // §6.2, §7.2 — Contains fields with different XML namespaces on individual properties. + ModelWithNamespaceOnProperties +} + +// XMLModelWithNamespaceOnPropertiesValueClientPutResponse contains the response from method XMLModelWithNamespaceOnPropertiesValueClient.Put. +type XMLModelWithNamespaceOnPropertiesValueClientPutResponse struct { + // placeholder for future response values +} + +// XMLModelWithNamespaceValueClientGetResponse contains the response from method XMLModelWithNamespaceValueClient.Get. +type XMLModelWithNamespaceValueClientGetResponse struct { + // §6.1, §7.1 — Contains fields with XML namespace on the model. + ModelWithNamespace +} + +// XMLModelWithNamespaceValueClientPutResponse contains the response from method XMLModelWithNamespaceValueClient.Put. +type XMLModelWithNamespaceValueClientPutResponse struct { + // placeholder for future response values +} + +// XMLModelWithNestedModelValueClientGetResponse contains the response from method XMLModelWithNestedModelValueClient.Get. +type XMLModelWithNestedModelValueClientGetResponse struct { + // §2.1 — Contains a property that references another model. + ModelWithNestedModel +} + +// XMLModelWithNestedModelValueClientPutResponse contains the response from method XMLModelWithNestedModelValueClient.Put. +type XMLModelWithNestedModelValueClientPutResponse struct { + // placeholder for future response values +} + +// XMLModelWithOptionalFieldValueClientGetResponse contains the response from method XMLModelWithOptionalFieldValueClient.Get. +type XMLModelWithOptionalFieldValueClientGetResponse struct { + // Contains an optional field. + ModelWithOptionalField +} + +// XMLModelWithOptionalFieldValueClientPutResponse contains the response from method XMLModelWithOptionalFieldValueClient.Put. +type XMLModelWithOptionalFieldValueClientPutResponse struct { + // placeholder for future response values +} + +// XMLModelWithRenamedArraysValueClientGetResponse contains the response from method XMLModelWithRenamedArraysValueClient.Get. +type XMLModelWithRenamedArraysValueClientGetResponse struct { + // §3.3, §3.4 — Contains fields of wrapped and unwrapped arrays of primitive types that have different XML representations. + ModelWithRenamedArrays +} + +// XMLModelWithRenamedArraysValueClientPutResponse contains the response from method XMLModelWithRenamedArraysValueClient.Put. +type XMLModelWithRenamedArraysValueClientPutResponse struct { + // placeholder for future response values +} + +// XMLModelWithRenamedAttributeValueClientGetResponse contains the response from method XMLModelWithRenamedAttributeValueClient.Get. +type XMLModelWithRenamedAttributeValueClientGetResponse struct { + // §5.2 — Contains a renamed XML attribute. + ModelWithRenamedAttribute +} + +// XMLModelWithRenamedAttributeValueClientPutResponse contains the response from method XMLModelWithRenamedAttributeValueClient.Put. +type XMLModelWithRenamedAttributeValueClientPutResponse struct { + // placeholder for future response values +} + +// XMLModelWithRenamedFieldsValueClientGetResponse contains the response from method XMLModelWithRenamedFieldsValueClient.Get. +type XMLModelWithRenamedFieldsValueClientGetResponse struct { + // §1.3, §2.3 — Contains fields of the same type that have different XML representation. + ModelWithRenamedFields +} + +// XMLModelWithRenamedFieldsValueClientPutResponse contains the response from method XMLModelWithRenamedFieldsValueClient.Put. +type XMLModelWithRenamedFieldsValueClientPutResponse struct { + // placeholder for future response values +} + +// XMLModelWithRenamedNestedModelValueClientGetResponse contains the response from method XMLModelWithRenamedNestedModelValueClient.Get. +type XMLModelWithRenamedNestedModelValueClientGetResponse struct { + // §2.2 — Contains a property whose type has + ModelWithRenamedNestedModel +} + +// XMLModelWithRenamedNestedModelValueClientPutResponse contains the response from method XMLModelWithRenamedNestedModelValueClient.Put. +type XMLModelWithRenamedNestedModelValueClientPutResponse struct { + // placeholder for future response values +} + +// XMLModelWithRenamedPropertyValueClientGetResponse contains the response from method XMLModelWithRenamedPropertyValueClient.Get. +type XMLModelWithRenamedPropertyValueClientGetResponse struct { + // §1.2 — Contains a scalar property with a custom XML name. + ModelWithRenamedProperty +} + +// XMLModelWithRenamedPropertyValueClientPutResponse contains the response from method XMLModelWithRenamedPropertyValueClient.Put. +type XMLModelWithRenamedPropertyValueClientPutResponse struct { + // placeholder for future response values +} + +// XMLModelWithRenamedUnwrappedModelArrayValueClientGetResponse contains the response from method XMLModelWithRenamedUnwrappedModelArrayValueClient.Get. +type XMLModelWithRenamedUnwrappedModelArrayValueClientGetResponse struct { + // §4.4 — Contains an unwrapped array of models with a custom item name. + ModelWithRenamedUnwrappedModelArray +} + +// XMLModelWithRenamedUnwrappedModelArrayValueClientPutResponse contains the response from method XMLModelWithRenamedUnwrappedModelArrayValueClient.Put. +type XMLModelWithRenamedUnwrappedModelArrayValueClientPutResponse struct { + // placeholder for future response values +} + +// XMLModelWithRenamedWrappedAndItemModelArrayValueClientGetResponse contains the response from method XMLModelWithRenamedWrappedAndItemModelArrayValueClient.Get. +type XMLModelWithRenamedWrappedAndItemModelArrayValueClientGetResponse struct { + // §4.5 — Contains a wrapped array of models with custom wrapper and item names. + ModelWithRenamedWrappedAndItemModelArray +} + +// XMLModelWithRenamedWrappedAndItemModelArrayValueClientPutResponse contains the response from method XMLModelWithRenamedWrappedAndItemModelArrayValueClient.Put. +type XMLModelWithRenamedWrappedAndItemModelArrayValueClientPutResponse struct { + // placeholder for future response values +} + +// XMLModelWithRenamedWrappedModelArrayValueClientGetResponse contains the response from method XMLModelWithRenamedWrappedModelArrayValueClient.Get. +type XMLModelWithRenamedWrappedModelArrayValueClientGetResponse struct { + // §4.3 — Contains a wrapped array of models with a custom wrapper name. + ModelWithRenamedWrappedModelArray +} + +// XMLModelWithRenamedWrappedModelArrayValueClientPutResponse contains the response from method XMLModelWithRenamedWrappedModelArrayValueClient.Put. +type XMLModelWithRenamedWrappedModelArrayValueClientPutResponse struct { + // placeholder for future response values +} + +// XMLModelWithSimpleArraysValueClientGetResponse contains the response from method XMLModelWithSimpleArraysValueClient.Get. +type XMLModelWithSimpleArraysValueClientGetResponse struct { + // §3.1 — Contains fields of arrays of primitive types. + ModelWithSimpleArrays +} + +// XMLModelWithSimpleArraysValueClientPutResponse contains the response from method XMLModelWithSimpleArraysValueClient.Put. +type XMLModelWithSimpleArraysValueClientPutResponse struct { + // placeholder for future response values +} + +// XMLModelWithTextValueClientGetResponse contains the response from method XMLModelWithTextValueClient.Get. +type XMLModelWithTextValueClientGetResponse struct { + // §8.1 — Contains an attribute and text. + ModelWithText +} + +// XMLModelWithTextValueClientPutResponse contains the response from method XMLModelWithTextValueClient.Put. +type XMLModelWithTextValueClientPutResponse struct { + // placeholder for future response values +} + +// XMLModelWithUnwrappedArrayValueClientGetResponse contains the response from method XMLModelWithUnwrappedArrayValueClient.Get. +type XMLModelWithUnwrappedArrayValueClientGetResponse struct { + // §3.2 — Contains fields of wrapped and unwrapped arrays of primitive types. + ModelWithUnwrappedArray +} + +// XMLModelWithUnwrappedArrayValueClientPutResponse contains the response from method XMLModelWithUnwrappedArrayValueClient.Put. +type XMLModelWithUnwrappedArrayValueClientPutResponse struct { + // placeholder for future response values +} + +// XMLModelWithUnwrappedModelArrayValueClientGetResponse contains the response from method XMLModelWithUnwrappedModelArrayValueClient.Get. +type XMLModelWithUnwrappedModelArrayValueClientGetResponse struct { + // §4.2 — Contains an unwrapped array of models. + ModelWithUnwrappedModelArray +} + +// XMLModelWithUnwrappedModelArrayValueClientPutResponse contains the response from method XMLModelWithUnwrappedModelArrayValueClient.Put. +type XMLModelWithUnwrappedModelArrayValueClientPutResponse struct { + // placeholder for future response values +} + +// XMLModelWithWrappedPrimitiveCustomItemNamesValueClientGetResponse contains the response from method XMLModelWithWrappedPrimitiveCustomItemNamesValueClient.Get. +type XMLModelWithWrappedPrimitiveCustomItemNamesValueClientGetResponse struct { + // §3.5 — Contains a wrapped primitive array with custom wrapper and item names. + ModelWithWrappedPrimitiveCustomItemNames +} + +// XMLModelWithWrappedPrimitiveCustomItemNamesValueClientPutResponse contains the response from method XMLModelWithWrappedPrimitiveCustomItemNamesValueClient.Put. +type XMLModelWithWrappedPrimitiveCustomItemNamesValueClientPutResponse struct { + // placeholder for future response values +} + +// XMLSimpleModelValueClientGetResponse contains the response from method XMLSimpleModelValueClient.Get. +type XMLSimpleModelValueClientGetResponse struct { + // §1.1 — Contains fields of primitive types. + SimpleModel +} + +// XMLSimpleModelValueClientPutResponse contains the response from method XMLSimpleModelValueClient.Put. +type XMLSimpleModelValueClientPutResponse struct { + // placeholder for future response values +} + +// XMLXMLErrorValueClientGetResponse contains the response from method XMLXMLErrorValueClient.Get. +type XMLXMLErrorValueClientGetResponse struct { + // §1.1 — Contains fields of primitive types. + SimpleModel +} diff --git a/test/http-specs/payload/xmlgroup/zz_version.go b/test/http-specs/payload/xmlgroup/zz_version.go new file mode 100644 index 000000000000..3e5a49d618bc --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package xmlgroup + +const ( + moduleName = "xmlgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/payload/xmlgroup/zz_xml_client.go b/test/http-specs/payload/xmlgroup/zz_xml_client.go new file mode 100644 index 000000000000..2b609fcd99f1 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xml_client.go @@ -0,0 +1,248 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// XMLClient - Sends and receives bodies in XML format. +// Don't use this type directly, use NewXMLClientWithNoCredential() instead. +type XMLClient struct { + internal *azcore.Client + endpoint string +} + +// XMLClientOptions contains the optional values for creating a [XMLClient]. +type XMLClientOptions struct { + azcore.ClientOptions +} + +// NewXMLClientWithNoCredential creates a new instance of XMLClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewXMLClientWithNoCredential(endpoint string, options *XMLClientOptions) (*XMLClient, error) { + if options == nil { + options = &XMLClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &XMLClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewXMLModelWithArrayOfModelValueClient creates a new instance of [XMLModelWithArrayOfModelValueClient]. +func (client *XMLClient) NewXMLModelWithArrayOfModelValueClient() *XMLModelWithArrayOfModelValueClient { + return &XMLModelWithArrayOfModelValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewXMLModelWithAttributesValueClient creates a new instance of [XMLModelWithAttributesValueClient]. +func (client *XMLClient) NewXMLModelWithAttributesValueClient() *XMLModelWithAttributesValueClient { + return &XMLModelWithAttributesValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewXMLModelWithDatetimeValueClient creates a new instance of [XMLModelWithDatetimeValueClient]. +func (client *XMLClient) NewXMLModelWithDatetimeValueClient() *XMLModelWithDatetimeValueClient { + return &XMLModelWithDatetimeValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewXMLModelWithDictionaryValueClient creates a new instance of [XMLModelWithDictionaryValueClient]. +func (client *XMLClient) NewXMLModelWithDictionaryValueClient() *XMLModelWithDictionaryValueClient { + return &XMLModelWithDictionaryValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewXMLModelWithEmptyArrayValueClient creates a new instance of [XMLModelWithEmptyArrayValueClient]. +func (client *XMLClient) NewXMLModelWithEmptyArrayValueClient() *XMLModelWithEmptyArrayValueClient { + return &XMLModelWithEmptyArrayValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewXMLModelWithEncodedNamesValueClient creates a new instance of [XMLModelWithEncodedNamesValueClient]. +func (client *XMLClient) NewXMLModelWithEncodedNamesValueClient() *XMLModelWithEncodedNamesValueClient { + return &XMLModelWithEncodedNamesValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewXMLModelWithEnumValueClient creates a new instance of [XMLModelWithEnumValueClient]. +func (client *XMLClient) NewXMLModelWithEnumValueClient() *XMLModelWithEnumValueClient { + return &XMLModelWithEnumValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewXMLModelWithNamespaceOnPropertiesValueClient creates a new instance of [XMLModelWithNamespaceOnPropertiesValueClient]. +func (client *XMLClient) NewXMLModelWithNamespaceOnPropertiesValueClient() *XMLModelWithNamespaceOnPropertiesValueClient { + return &XMLModelWithNamespaceOnPropertiesValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewXMLModelWithNamespaceValueClient creates a new instance of [XMLModelWithNamespaceValueClient]. +func (client *XMLClient) NewXMLModelWithNamespaceValueClient() *XMLModelWithNamespaceValueClient { + return &XMLModelWithNamespaceValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewXMLModelWithNestedModelValueClient creates a new instance of [XMLModelWithNestedModelValueClient]. +func (client *XMLClient) NewXMLModelWithNestedModelValueClient() *XMLModelWithNestedModelValueClient { + return &XMLModelWithNestedModelValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewXMLModelWithOptionalFieldValueClient creates a new instance of [XMLModelWithOptionalFieldValueClient]. +func (client *XMLClient) NewXMLModelWithOptionalFieldValueClient() *XMLModelWithOptionalFieldValueClient { + return &XMLModelWithOptionalFieldValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewXMLModelWithRenamedArraysValueClient creates a new instance of [XMLModelWithRenamedArraysValueClient]. +func (client *XMLClient) NewXMLModelWithRenamedArraysValueClient() *XMLModelWithRenamedArraysValueClient { + return &XMLModelWithRenamedArraysValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewXMLModelWithRenamedAttributeValueClient creates a new instance of [XMLModelWithRenamedAttributeValueClient]. +func (client *XMLClient) NewXMLModelWithRenamedAttributeValueClient() *XMLModelWithRenamedAttributeValueClient { + return &XMLModelWithRenamedAttributeValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewXMLModelWithRenamedFieldsValueClient creates a new instance of [XMLModelWithRenamedFieldsValueClient]. +func (client *XMLClient) NewXMLModelWithRenamedFieldsValueClient() *XMLModelWithRenamedFieldsValueClient { + return &XMLModelWithRenamedFieldsValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewXMLModelWithRenamedNestedModelValueClient creates a new instance of [XMLModelWithRenamedNestedModelValueClient]. +func (client *XMLClient) NewXMLModelWithRenamedNestedModelValueClient() *XMLModelWithRenamedNestedModelValueClient { + return &XMLModelWithRenamedNestedModelValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewXMLModelWithRenamedPropertyValueClient creates a new instance of [XMLModelWithRenamedPropertyValueClient]. +func (client *XMLClient) NewXMLModelWithRenamedPropertyValueClient() *XMLModelWithRenamedPropertyValueClient { + return &XMLModelWithRenamedPropertyValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewXMLModelWithRenamedUnwrappedModelArrayValueClient creates a new instance of [XMLModelWithRenamedUnwrappedModelArrayValueClient]. +func (client *XMLClient) NewXMLModelWithRenamedUnwrappedModelArrayValueClient() *XMLModelWithRenamedUnwrappedModelArrayValueClient { + return &XMLModelWithRenamedUnwrappedModelArrayValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewXMLModelWithRenamedWrappedAndItemModelArrayValueClient creates a new instance of [XMLModelWithRenamedWrappedAndItemModelArrayValueClient]. +func (client *XMLClient) NewXMLModelWithRenamedWrappedAndItemModelArrayValueClient() *XMLModelWithRenamedWrappedAndItemModelArrayValueClient { + return &XMLModelWithRenamedWrappedAndItemModelArrayValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewXMLModelWithRenamedWrappedModelArrayValueClient creates a new instance of [XMLModelWithRenamedWrappedModelArrayValueClient]. +func (client *XMLClient) NewXMLModelWithRenamedWrappedModelArrayValueClient() *XMLModelWithRenamedWrappedModelArrayValueClient { + return &XMLModelWithRenamedWrappedModelArrayValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewXMLModelWithSimpleArraysValueClient creates a new instance of [XMLModelWithSimpleArraysValueClient]. +func (client *XMLClient) NewXMLModelWithSimpleArraysValueClient() *XMLModelWithSimpleArraysValueClient { + return &XMLModelWithSimpleArraysValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewXMLModelWithTextValueClient creates a new instance of [XMLModelWithTextValueClient]. +func (client *XMLClient) NewXMLModelWithTextValueClient() *XMLModelWithTextValueClient { + return &XMLModelWithTextValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewXMLModelWithUnwrappedArrayValueClient creates a new instance of [XMLModelWithUnwrappedArrayValueClient]. +func (client *XMLClient) NewXMLModelWithUnwrappedArrayValueClient() *XMLModelWithUnwrappedArrayValueClient { + return &XMLModelWithUnwrappedArrayValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewXMLModelWithUnwrappedModelArrayValueClient creates a new instance of [XMLModelWithUnwrappedModelArrayValueClient]. +func (client *XMLClient) NewXMLModelWithUnwrappedModelArrayValueClient() *XMLModelWithUnwrappedModelArrayValueClient { + return &XMLModelWithUnwrappedModelArrayValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewXMLModelWithWrappedPrimitiveCustomItemNamesValueClient creates a new instance of [XMLModelWithWrappedPrimitiveCustomItemNamesValueClient]. +func (client *XMLClient) NewXMLModelWithWrappedPrimitiveCustomItemNamesValueClient() *XMLModelWithWrappedPrimitiveCustomItemNamesValueClient { + return &XMLModelWithWrappedPrimitiveCustomItemNamesValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewXMLSimpleModelValueClient creates a new instance of [XMLSimpleModelValueClient]. +func (client *XMLClient) NewXMLSimpleModelValueClient() *XMLSimpleModelValueClient { + return &XMLSimpleModelValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewXMLXMLErrorValueClient creates a new instance of [XMLXMLErrorValueClient]. +func (client *XMLClient) NewXMLXMLErrorValueClient() *XMLXMLErrorValueClient { + return &XMLXMLErrorValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/http-specs/payload/xmlgroup/zz_xml_helper.go b/test/http-specs/payload/xmlgroup/zz_xml_helper.go new file mode 100644 index 000000000000..5f6a6ae8018d --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xml_helper.go @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "encoding/xml" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "io" + "strings" +) + +type additionalProperties map[string]*string + +// MarshalXML implements the xml.Marshaler interface for additionalProperties. +func (ap additionalProperties) MarshalXML(e *xml.Encoder, start xml.StartElement) error { + if err := e.EncodeToken(start); err != nil { + return err + } + for k, v := range ap { + err := e.EncodeToken(xml.StartElement{ + Name: xml.Name{ + Local: k, + }, + }) + if err != nil { + return err + } + if v != nil { + err = e.EncodeToken(xml.CharData(*v)) + if err != nil { + return err + } + } + err = e.EncodeToken(xml.EndElement{ + Name: xml.Name{ + Local: k, + }, + }) + if err != nil { + return err + } + } + return e.EncodeToken(xml.EndElement{ + Name: start.Name, + }) +} + +// UnmarshalXML implements the xml.Unmarshaler interface for additionalProperties. +func (ap *additionalProperties) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { + tokName := "" + tokValue := "" + for { + t, err := d.Token() + if errors.Is(err, io.EOF) { + break + } else if err != nil { + return err + } + switch tt := t.(type) { + case xml.StartElement: + tokName = strings.ToLower(tt.Name.Local) + tokValue = "" + case xml.CharData: + if tokName == "" { + continue + } + tokValue = string(tt) + case xml.EndElement: + if tokName == "" { + continue + } + if *ap == nil { + *ap = additionalProperties{} + } + (*ap)[tokName] = to.Ptr(tokValue) + tokName = "" + } + } + return nil +} diff --git a/test/http-specs/payload/xmlgroup/zz_xmlmodelwitharrayofmodelvalue_client.go b/test/http-specs/payload/xmlgroup/zz_xmlmodelwitharrayofmodelvalue_client.go new file mode 100644 index 000000000000..77b99ad4cc2b --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xmlmodelwitharrayofmodelvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// XMLModelWithArrayOfModelValueClient - §4.1 — Operations for the ModelWithArrayOfModel type. +// Don't use this type directly, use [XMLClient.NewXMLModelWithArrayOfModelValueClient] instead. +type XMLModelWithArrayOfModelValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithArrayOfModelValueClientGetOptions contains the optional parameters for the XMLModelWithArrayOfModelValueClient.Get +// method. +func (client *XMLModelWithArrayOfModelValueClient) Get(ctx context.Context, options *XMLModelWithArrayOfModelValueClientGetOptions) (XMLModelWithArrayOfModelValueClientGetResponse, error) { + var err error + const operationName = "XMLModelWithArrayOfModelValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return XMLModelWithArrayOfModelValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithArrayOfModelValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithArrayOfModelValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *XMLModelWithArrayOfModelValueClient) getCreateRequest(ctx context.Context, _ *XMLModelWithArrayOfModelValueClientGetOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithArrayOfModel" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *XMLModelWithArrayOfModelValueClient) getHandleResponse(resp *http.Response) (XMLModelWithArrayOfModelValueClientGetResponse, error) { + result := XMLModelWithArrayOfModelValueClientGetResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.ModelWithArrayOfModel); err != nil { + return XMLModelWithArrayOfModelValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithArrayOfModelValueClientPutOptions contains the optional parameters for the XMLModelWithArrayOfModelValueClient.Put +// method. +func (client *XMLModelWithArrayOfModelValueClient) Put(ctx context.Context, input ModelWithArrayOfModel, options *XMLModelWithArrayOfModelValueClientPutOptions) (XMLModelWithArrayOfModelValueClientPutResponse, error) { + var err error + const operationName = "XMLModelWithArrayOfModelValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, input, options) + if err != nil { + return XMLModelWithArrayOfModelValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithArrayOfModelValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithArrayOfModelValueClientPutResponse{}, err + } + return XMLModelWithArrayOfModelValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *XMLModelWithArrayOfModelValueClient) putCreateRequest(ctx context.Context, input ModelWithArrayOfModel, _ *XMLModelWithArrayOfModelValueClientPutOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithArrayOfModel" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/xmlgroup/zz_xmlmodelwithattributesvalue_client.go b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithattributesvalue_client.go new file mode 100644 index 000000000000..826f38747092 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithattributesvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// XMLModelWithAttributesValueClient - §5.1 — Operations for the ModelWithAttributes type. +// Don't use this type directly, use [XMLClient.NewXMLModelWithAttributesValueClient] instead. +type XMLModelWithAttributesValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithAttributesValueClientGetOptions contains the optional parameters for the XMLModelWithAttributesValueClient.Get +// method. +func (client *XMLModelWithAttributesValueClient) Get(ctx context.Context, options *XMLModelWithAttributesValueClientGetOptions) (XMLModelWithAttributesValueClientGetResponse, error) { + var err error + const operationName = "XMLModelWithAttributesValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return XMLModelWithAttributesValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithAttributesValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithAttributesValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *XMLModelWithAttributesValueClient) getCreateRequest(ctx context.Context, _ *XMLModelWithAttributesValueClientGetOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithAttributes" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *XMLModelWithAttributesValueClient) getHandleResponse(resp *http.Response) (XMLModelWithAttributesValueClientGetResponse, error) { + result := XMLModelWithAttributesValueClientGetResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.ModelWithAttributes); err != nil { + return XMLModelWithAttributesValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithAttributesValueClientPutOptions contains the optional parameters for the XMLModelWithAttributesValueClient.Put +// method. +func (client *XMLModelWithAttributesValueClient) Put(ctx context.Context, input ModelWithAttributes, options *XMLModelWithAttributesValueClientPutOptions) (XMLModelWithAttributesValueClientPutResponse, error) { + var err error + const operationName = "XMLModelWithAttributesValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, input, options) + if err != nil { + return XMLModelWithAttributesValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithAttributesValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithAttributesValueClientPutResponse{}, err + } + return XMLModelWithAttributesValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *XMLModelWithAttributesValueClient) putCreateRequest(ctx context.Context, input ModelWithAttributes, _ *XMLModelWithAttributesValueClientPutOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithAttributes" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/xmlgroup/zz_xmlmodelwithdatetimevalue_client.go b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithdatetimevalue_client.go new file mode 100644 index 000000000000..dace0b960560 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithdatetimevalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// XMLModelWithDatetimeValueClient - Operations for the ModelWithDatetime type. +// Don't use this type directly, use [XMLClient.NewXMLModelWithDatetimeValueClient] instead. +type XMLModelWithDatetimeValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithDatetimeValueClientGetOptions contains the optional parameters for the XMLModelWithDatetimeValueClient.Get +// method. +func (client *XMLModelWithDatetimeValueClient) Get(ctx context.Context, options *XMLModelWithDatetimeValueClientGetOptions) (XMLModelWithDatetimeValueClientGetResponse, error) { + var err error + const operationName = "XMLModelWithDatetimeValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return XMLModelWithDatetimeValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithDatetimeValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithDatetimeValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *XMLModelWithDatetimeValueClient) getCreateRequest(ctx context.Context, _ *XMLModelWithDatetimeValueClientGetOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithDatetime" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *XMLModelWithDatetimeValueClient) getHandleResponse(resp *http.Response) (XMLModelWithDatetimeValueClientGetResponse, error) { + result := XMLModelWithDatetimeValueClientGetResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.ModelWithDatetime); err != nil { + return XMLModelWithDatetimeValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithDatetimeValueClientPutOptions contains the optional parameters for the XMLModelWithDatetimeValueClient.Put +// method. +func (client *XMLModelWithDatetimeValueClient) Put(ctx context.Context, input ModelWithDatetime, options *XMLModelWithDatetimeValueClientPutOptions) (XMLModelWithDatetimeValueClientPutResponse, error) { + var err error + const operationName = "XMLModelWithDatetimeValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, input, options) + if err != nil { + return XMLModelWithDatetimeValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithDatetimeValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithDatetimeValueClientPutResponse{}, err + } + return XMLModelWithDatetimeValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *XMLModelWithDatetimeValueClient) putCreateRequest(ctx context.Context, input ModelWithDatetime, _ *XMLModelWithDatetimeValueClientPutOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithDatetime" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/xmlgroup/zz_xmlmodelwithdictionaryvalue_client.go b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithdictionaryvalue_client.go new file mode 100644 index 000000000000..90d29345b8b9 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithdictionaryvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// XMLModelWithDictionaryValueClient - Operations for the ModelWithDictionary type. +// Don't use this type directly, use [XMLClient.NewXMLModelWithDictionaryValueClient] instead. +type XMLModelWithDictionaryValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithDictionaryValueClientGetOptions contains the optional parameters for the XMLModelWithDictionaryValueClient.Get +// method. +func (client *XMLModelWithDictionaryValueClient) Get(ctx context.Context, options *XMLModelWithDictionaryValueClientGetOptions) (XMLModelWithDictionaryValueClientGetResponse, error) { + var err error + const operationName = "XMLModelWithDictionaryValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return XMLModelWithDictionaryValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithDictionaryValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithDictionaryValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *XMLModelWithDictionaryValueClient) getCreateRequest(ctx context.Context, _ *XMLModelWithDictionaryValueClientGetOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithDictionary" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *XMLModelWithDictionaryValueClient) getHandleResponse(resp *http.Response) (XMLModelWithDictionaryValueClientGetResponse, error) { + result := XMLModelWithDictionaryValueClientGetResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.ModelWithDictionary); err != nil { + return XMLModelWithDictionaryValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithDictionaryValueClientPutOptions contains the optional parameters for the XMLModelWithDictionaryValueClient.Put +// method. +func (client *XMLModelWithDictionaryValueClient) Put(ctx context.Context, input ModelWithDictionary, options *XMLModelWithDictionaryValueClientPutOptions) (XMLModelWithDictionaryValueClientPutResponse, error) { + var err error + const operationName = "XMLModelWithDictionaryValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, input, options) + if err != nil { + return XMLModelWithDictionaryValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithDictionaryValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithDictionaryValueClientPutResponse{}, err + } + return XMLModelWithDictionaryValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *XMLModelWithDictionaryValueClient) putCreateRequest(ctx context.Context, input ModelWithDictionary, _ *XMLModelWithDictionaryValueClientPutOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithDictionary" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/xmlgroup/zz_xmlmodelwithemptyarrayvalue_client.go b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithemptyarrayvalue_client.go new file mode 100644 index 000000000000..8a199bd419d6 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithemptyarrayvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// XMLModelWithEmptyArrayValueClient - Operations for the ModelWithEmptyArray type. +// Don't use this type directly, use [XMLClient.NewXMLModelWithEmptyArrayValueClient] instead. +type XMLModelWithEmptyArrayValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithEmptyArrayValueClientGetOptions contains the optional parameters for the XMLModelWithEmptyArrayValueClient.Get +// method. +func (client *XMLModelWithEmptyArrayValueClient) Get(ctx context.Context, options *XMLModelWithEmptyArrayValueClientGetOptions) (XMLModelWithEmptyArrayValueClientGetResponse, error) { + var err error + const operationName = "XMLModelWithEmptyArrayValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return XMLModelWithEmptyArrayValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithEmptyArrayValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithEmptyArrayValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *XMLModelWithEmptyArrayValueClient) getCreateRequest(ctx context.Context, _ *XMLModelWithEmptyArrayValueClientGetOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithEmptyArray" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *XMLModelWithEmptyArrayValueClient) getHandleResponse(resp *http.Response) (XMLModelWithEmptyArrayValueClientGetResponse, error) { + result := XMLModelWithEmptyArrayValueClientGetResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.ModelWithEmptyArray); err != nil { + return XMLModelWithEmptyArrayValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithEmptyArrayValueClientPutOptions contains the optional parameters for the XMLModelWithEmptyArrayValueClient.Put +// method. +func (client *XMLModelWithEmptyArrayValueClient) Put(ctx context.Context, input ModelWithEmptyArray, options *XMLModelWithEmptyArrayValueClientPutOptions) (XMLModelWithEmptyArrayValueClientPutResponse, error) { + var err error + const operationName = "XMLModelWithEmptyArrayValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, input, options) + if err != nil { + return XMLModelWithEmptyArrayValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithEmptyArrayValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithEmptyArrayValueClientPutResponse{}, err + } + return XMLModelWithEmptyArrayValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *XMLModelWithEmptyArrayValueClient) putCreateRequest(ctx context.Context, input ModelWithEmptyArray, _ *XMLModelWithEmptyArrayValueClientPutOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithEmptyArray" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/xmlgroup/zz_xmlmodelwithencodednamesvalue_client.go b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithencodednamesvalue_client.go new file mode 100644 index 000000000000..c94cfcff88e4 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithencodednamesvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// XMLModelWithEncodedNamesValueClient - Operations for the ModelWithEncodedNames type. +// Don't use this type directly, use [XMLClient.NewXMLModelWithEncodedNamesValueClient] instead. +type XMLModelWithEncodedNamesValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithEncodedNamesValueClientGetOptions contains the optional parameters for the XMLModelWithEncodedNamesValueClient.Get +// method. +func (client *XMLModelWithEncodedNamesValueClient) Get(ctx context.Context, options *XMLModelWithEncodedNamesValueClientGetOptions) (XMLModelWithEncodedNamesValueClientGetResponse, error) { + var err error + const operationName = "XMLModelWithEncodedNamesValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return XMLModelWithEncodedNamesValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithEncodedNamesValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithEncodedNamesValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *XMLModelWithEncodedNamesValueClient) getCreateRequest(ctx context.Context, _ *XMLModelWithEncodedNamesValueClientGetOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithEncodedNames" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *XMLModelWithEncodedNamesValueClient) getHandleResponse(resp *http.Response) (XMLModelWithEncodedNamesValueClientGetResponse, error) { + result := XMLModelWithEncodedNamesValueClientGetResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.ModelWithEncodedNames); err != nil { + return XMLModelWithEncodedNamesValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithEncodedNamesValueClientPutOptions contains the optional parameters for the XMLModelWithEncodedNamesValueClient.Put +// method. +func (client *XMLModelWithEncodedNamesValueClient) Put(ctx context.Context, input ModelWithEncodedNames, options *XMLModelWithEncodedNamesValueClientPutOptions) (XMLModelWithEncodedNamesValueClientPutResponse, error) { + var err error + const operationName = "XMLModelWithEncodedNamesValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, input, options) + if err != nil { + return XMLModelWithEncodedNamesValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithEncodedNamesValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithEncodedNamesValueClientPutResponse{}, err + } + return XMLModelWithEncodedNamesValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *XMLModelWithEncodedNamesValueClient) putCreateRequest(ctx context.Context, input ModelWithEncodedNames, _ *XMLModelWithEncodedNamesValueClientPutOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithEncodedNames" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/xmlgroup/zz_xmlmodelwithenumvalue_client.go b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithenumvalue_client.go new file mode 100644 index 000000000000..aac409686abb --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithenumvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// XMLModelWithEnumValueClient - Operations for the ModelWithEnum type. +// Don't use this type directly, use [XMLClient.NewXMLModelWithEnumValueClient] instead. +type XMLModelWithEnumValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithEnumValueClientGetOptions contains the optional parameters for the XMLModelWithEnumValueClient.Get +// method. +func (client *XMLModelWithEnumValueClient) Get(ctx context.Context, options *XMLModelWithEnumValueClientGetOptions) (XMLModelWithEnumValueClientGetResponse, error) { + var err error + const operationName = "XMLModelWithEnumValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return XMLModelWithEnumValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithEnumValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithEnumValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *XMLModelWithEnumValueClient) getCreateRequest(ctx context.Context, _ *XMLModelWithEnumValueClientGetOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithEnum" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *XMLModelWithEnumValueClient) getHandleResponse(resp *http.Response) (XMLModelWithEnumValueClientGetResponse, error) { + result := XMLModelWithEnumValueClientGetResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.ModelWithEnum); err != nil { + return XMLModelWithEnumValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithEnumValueClientPutOptions contains the optional parameters for the XMLModelWithEnumValueClient.Put +// method. +func (client *XMLModelWithEnumValueClient) Put(ctx context.Context, input ModelWithEnum, options *XMLModelWithEnumValueClientPutOptions) (XMLModelWithEnumValueClientPutResponse, error) { + var err error + const operationName = "XMLModelWithEnumValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, input, options) + if err != nil { + return XMLModelWithEnumValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithEnumValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithEnumValueClientPutResponse{}, err + } + return XMLModelWithEnumValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *XMLModelWithEnumValueClient) putCreateRequest(ctx context.Context, input ModelWithEnum, _ *XMLModelWithEnumValueClientPutOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithEnum" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/xmlgroup/zz_xmlmodelwithnamespaceonpropertiesvalue_client.go b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithnamespaceonpropertiesvalue_client.go new file mode 100644 index 000000000000..ccf15dbe4f82 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithnamespaceonpropertiesvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// XMLModelWithNamespaceOnPropertiesValueClient - §6.2, §7.2 — Operations for the ModelWithNamespaceOnProperties type. +// Don't use this type directly, use [XMLClient.NewXMLModelWithNamespaceOnPropertiesValueClient] instead. +type XMLModelWithNamespaceOnPropertiesValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithNamespaceOnPropertiesValueClientGetOptions contains the optional parameters for the XMLModelWithNamespaceOnPropertiesValueClient.Get +// method. +func (client *XMLModelWithNamespaceOnPropertiesValueClient) Get(ctx context.Context, options *XMLModelWithNamespaceOnPropertiesValueClientGetOptions) (XMLModelWithNamespaceOnPropertiesValueClientGetResponse, error) { + var err error + const operationName = "XMLModelWithNamespaceOnPropertiesValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return XMLModelWithNamespaceOnPropertiesValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithNamespaceOnPropertiesValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithNamespaceOnPropertiesValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *XMLModelWithNamespaceOnPropertiesValueClient) getCreateRequest(ctx context.Context, _ *XMLModelWithNamespaceOnPropertiesValueClientGetOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithNamespaceOnProperties" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *XMLModelWithNamespaceOnPropertiesValueClient) getHandleResponse(resp *http.Response) (XMLModelWithNamespaceOnPropertiesValueClientGetResponse, error) { + result := XMLModelWithNamespaceOnPropertiesValueClientGetResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.ModelWithNamespaceOnProperties); err != nil { + return XMLModelWithNamespaceOnPropertiesValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithNamespaceOnPropertiesValueClientPutOptions contains the optional parameters for the XMLModelWithNamespaceOnPropertiesValueClient.Put +// method. +func (client *XMLModelWithNamespaceOnPropertiesValueClient) Put(ctx context.Context, input ModelWithNamespaceOnProperties, options *XMLModelWithNamespaceOnPropertiesValueClientPutOptions) (XMLModelWithNamespaceOnPropertiesValueClientPutResponse, error) { + var err error + const operationName = "XMLModelWithNamespaceOnPropertiesValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, input, options) + if err != nil { + return XMLModelWithNamespaceOnPropertiesValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithNamespaceOnPropertiesValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithNamespaceOnPropertiesValueClientPutResponse{}, err + } + return XMLModelWithNamespaceOnPropertiesValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *XMLModelWithNamespaceOnPropertiesValueClient) putCreateRequest(ctx context.Context, input ModelWithNamespaceOnProperties, _ *XMLModelWithNamespaceOnPropertiesValueClientPutOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithNamespaceOnProperties" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/xmlgroup/zz_xmlmodelwithnamespacevalue_client.go b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithnamespacevalue_client.go new file mode 100644 index 000000000000..3c34e34f4910 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithnamespacevalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// XMLModelWithNamespaceValueClient - §6.1, §7.1 — Operations for the ModelWithNamespace type. +// Don't use this type directly, use [XMLClient.NewXMLModelWithNamespaceValueClient] instead. +type XMLModelWithNamespaceValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithNamespaceValueClientGetOptions contains the optional parameters for the XMLModelWithNamespaceValueClient.Get +// method. +func (client *XMLModelWithNamespaceValueClient) Get(ctx context.Context, options *XMLModelWithNamespaceValueClientGetOptions) (XMLModelWithNamespaceValueClientGetResponse, error) { + var err error + const operationName = "XMLModelWithNamespaceValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return XMLModelWithNamespaceValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithNamespaceValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithNamespaceValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *XMLModelWithNamespaceValueClient) getCreateRequest(ctx context.Context, _ *XMLModelWithNamespaceValueClientGetOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithNamespace" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *XMLModelWithNamespaceValueClient) getHandleResponse(resp *http.Response) (XMLModelWithNamespaceValueClientGetResponse, error) { + result := XMLModelWithNamespaceValueClientGetResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.ModelWithNamespace); err != nil { + return XMLModelWithNamespaceValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithNamespaceValueClientPutOptions contains the optional parameters for the XMLModelWithNamespaceValueClient.Put +// method. +func (client *XMLModelWithNamespaceValueClient) Put(ctx context.Context, input ModelWithNamespace, options *XMLModelWithNamespaceValueClientPutOptions) (XMLModelWithNamespaceValueClientPutResponse, error) { + var err error + const operationName = "XMLModelWithNamespaceValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, input, options) + if err != nil { + return XMLModelWithNamespaceValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithNamespaceValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithNamespaceValueClientPutResponse{}, err + } + return XMLModelWithNamespaceValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *XMLModelWithNamespaceValueClient) putCreateRequest(ctx context.Context, input ModelWithNamespace, _ *XMLModelWithNamespaceValueClientPutOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithNamespace" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/xmlgroup/zz_xmlmodelwithnestedmodelvalue_client.go b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithnestedmodelvalue_client.go new file mode 100644 index 000000000000..72ccad5ececa --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithnestedmodelvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// XMLModelWithNestedModelValueClient - §2.1 — Operations for the ModelWithNestedModel type. +// Don't use this type directly, use [XMLClient.NewXMLModelWithNestedModelValueClient] instead. +type XMLModelWithNestedModelValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithNestedModelValueClientGetOptions contains the optional parameters for the XMLModelWithNestedModelValueClient.Get +// method. +func (client *XMLModelWithNestedModelValueClient) Get(ctx context.Context, options *XMLModelWithNestedModelValueClientGetOptions) (XMLModelWithNestedModelValueClientGetResponse, error) { + var err error + const operationName = "XMLModelWithNestedModelValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return XMLModelWithNestedModelValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithNestedModelValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithNestedModelValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *XMLModelWithNestedModelValueClient) getCreateRequest(ctx context.Context, _ *XMLModelWithNestedModelValueClientGetOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithNestedModel" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *XMLModelWithNestedModelValueClient) getHandleResponse(resp *http.Response) (XMLModelWithNestedModelValueClientGetResponse, error) { + result := XMLModelWithNestedModelValueClientGetResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.ModelWithNestedModel); err != nil { + return XMLModelWithNestedModelValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithNestedModelValueClientPutOptions contains the optional parameters for the XMLModelWithNestedModelValueClient.Put +// method. +func (client *XMLModelWithNestedModelValueClient) Put(ctx context.Context, input ModelWithNestedModel, options *XMLModelWithNestedModelValueClientPutOptions) (XMLModelWithNestedModelValueClientPutResponse, error) { + var err error + const operationName = "XMLModelWithNestedModelValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, input, options) + if err != nil { + return XMLModelWithNestedModelValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithNestedModelValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithNestedModelValueClientPutResponse{}, err + } + return XMLModelWithNestedModelValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *XMLModelWithNestedModelValueClient) putCreateRequest(ctx context.Context, input ModelWithNestedModel, _ *XMLModelWithNestedModelValueClientPutOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithNestedModel" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/xmlgroup/zz_xmlmodelwithoptionalfieldvalue_client.go b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithoptionalfieldvalue_client.go new file mode 100644 index 000000000000..a259faa53883 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithoptionalfieldvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// XMLModelWithOptionalFieldValueClient - Operations for the ModelWithOptionalField type. +// Don't use this type directly, use [XMLClient.NewXMLModelWithOptionalFieldValueClient] instead. +type XMLModelWithOptionalFieldValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithOptionalFieldValueClientGetOptions contains the optional parameters for the XMLModelWithOptionalFieldValueClient.Get +// method. +func (client *XMLModelWithOptionalFieldValueClient) Get(ctx context.Context, options *XMLModelWithOptionalFieldValueClientGetOptions) (XMLModelWithOptionalFieldValueClientGetResponse, error) { + var err error + const operationName = "XMLModelWithOptionalFieldValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return XMLModelWithOptionalFieldValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithOptionalFieldValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithOptionalFieldValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *XMLModelWithOptionalFieldValueClient) getCreateRequest(ctx context.Context, _ *XMLModelWithOptionalFieldValueClientGetOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithOptionalField" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *XMLModelWithOptionalFieldValueClient) getHandleResponse(resp *http.Response) (XMLModelWithOptionalFieldValueClientGetResponse, error) { + result := XMLModelWithOptionalFieldValueClientGetResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.ModelWithOptionalField); err != nil { + return XMLModelWithOptionalFieldValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithOptionalFieldValueClientPutOptions contains the optional parameters for the XMLModelWithOptionalFieldValueClient.Put +// method. +func (client *XMLModelWithOptionalFieldValueClient) Put(ctx context.Context, input ModelWithOptionalField, options *XMLModelWithOptionalFieldValueClientPutOptions) (XMLModelWithOptionalFieldValueClientPutResponse, error) { + var err error + const operationName = "XMLModelWithOptionalFieldValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, input, options) + if err != nil { + return XMLModelWithOptionalFieldValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithOptionalFieldValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithOptionalFieldValueClientPutResponse{}, err + } + return XMLModelWithOptionalFieldValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *XMLModelWithOptionalFieldValueClient) putCreateRequest(ctx context.Context, input ModelWithOptionalField, _ *XMLModelWithOptionalFieldValueClientPutOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithOptionalField" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedarraysvalue_client.go b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedarraysvalue_client.go new file mode 100644 index 000000000000..4ae33dd9f98e --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedarraysvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// XMLModelWithRenamedArraysValueClient - §3.3, §3.4 — Operations for the ModelWithRenamedArrays type. +// Don't use this type directly, use [XMLClient.NewXMLModelWithRenamedArraysValueClient] instead. +type XMLModelWithRenamedArraysValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithRenamedArraysValueClientGetOptions contains the optional parameters for the XMLModelWithRenamedArraysValueClient.Get +// method. +func (client *XMLModelWithRenamedArraysValueClient) Get(ctx context.Context, options *XMLModelWithRenamedArraysValueClientGetOptions) (XMLModelWithRenamedArraysValueClientGetResponse, error) { + var err error + const operationName = "XMLModelWithRenamedArraysValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return XMLModelWithRenamedArraysValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithRenamedArraysValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithRenamedArraysValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *XMLModelWithRenamedArraysValueClient) getCreateRequest(ctx context.Context, _ *XMLModelWithRenamedArraysValueClientGetOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithRenamedArrays" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *XMLModelWithRenamedArraysValueClient) getHandleResponse(resp *http.Response) (XMLModelWithRenamedArraysValueClientGetResponse, error) { + result := XMLModelWithRenamedArraysValueClientGetResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.ModelWithRenamedArrays); err != nil { + return XMLModelWithRenamedArraysValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithRenamedArraysValueClientPutOptions contains the optional parameters for the XMLModelWithRenamedArraysValueClient.Put +// method. +func (client *XMLModelWithRenamedArraysValueClient) Put(ctx context.Context, input ModelWithRenamedArrays, options *XMLModelWithRenamedArraysValueClientPutOptions) (XMLModelWithRenamedArraysValueClientPutResponse, error) { + var err error + const operationName = "XMLModelWithRenamedArraysValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, input, options) + if err != nil { + return XMLModelWithRenamedArraysValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithRenamedArraysValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithRenamedArraysValueClientPutResponse{}, err + } + return XMLModelWithRenamedArraysValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *XMLModelWithRenamedArraysValueClient) putCreateRequest(ctx context.Context, input ModelWithRenamedArrays, _ *XMLModelWithRenamedArraysValueClientPutOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithRenamedArrays" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedattributevalue_client.go b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedattributevalue_client.go new file mode 100644 index 000000000000..cf5c331f0b1a --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedattributevalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// XMLModelWithRenamedAttributeValueClient - §5.2 — Operations for the ModelWithRenamedAttribute type. +// Don't use this type directly, use [XMLClient.NewXMLModelWithRenamedAttributeValueClient] instead. +type XMLModelWithRenamedAttributeValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithRenamedAttributeValueClientGetOptions contains the optional parameters for the XMLModelWithRenamedAttributeValueClient.Get +// method. +func (client *XMLModelWithRenamedAttributeValueClient) Get(ctx context.Context, options *XMLModelWithRenamedAttributeValueClientGetOptions) (XMLModelWithRenamedAttributeValueClientGetResponse, error) { + var err error + const operationName = "XMLModelWithRenamedAttributeValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return XMLModelWithRenamedAttributeValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithRenamedAttributeValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithRenamedAttributeValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *XMLModelWithRenamedAttributeValueClient) getCreateRequest(ctx context.Context, _ *XMLModelWithRenamedAttributeValueClientGetOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithRenamedAttribute" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *XMLModelWithRenamedAttributeValueClient) getHandleResponse(resp *http.Response) (XMLModelWithRenamedAttributeValueClientGetResponse, error) { + result := XMLModelWithRenamedAttributeValueClientGetResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.ModelWithRenamedAttribute); err != nil { + return XMLModelWithRenamedAttributeValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithRenamedAttributeValueClientPutOptions contains the optional parameters for the XMLModelWithRenamedAttributeValueClient.Put +// method. +func (client *XMLModelWithRenamedAttributeValueClient) Put(ctx context.Context, input ModelWithRenamedAttribute, options *XMLModelWithRenamedAttributeValueClientPutOptions) (XMLModelWithRenamedAttributeValueClientPutResponse, error) { + var err error + const operationName = "XMLModelWithRenamedAttributeValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, input, options) + if err != nil { + return XMLModelWithRenamedAttributeValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithRenamedAttributeValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithRenamedAttributeValueClientPutResponse{}, err + } + return XMLModelWithRenamedAttributeValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *XMLModelWithRenamedAttributeValueClient) putCreateRequest(ctx context.Context, input ModelWithRenamedAttribute, _ *XMLModelWithRenamedAttributeValueClientPutOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithRenamedAttribute" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedfieldsvalue_client.go b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedfieldsvalue_client.go new file mode 100644 index 000000000000..bc2adb393f9e --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedfieldsvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// XMLModelWithRenamedFieldsValueClient - §1.3, §2.3 — Operations for the ModelWithRenamedFields type. +// Don't use this type directly, use [XMLClient.NewXMLModelWithRenamedFieldsValueClient] instead. +type XMLModelWithRenamedFieldsValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithRenamedFieldsValueClientGetOptions contains the optional parameters for the XMLModelWithRenamedFieldsValueClient.Get +// method. +func (client *XMLModelWithRenamedFieldsValueClient) Get(ctx context.Context, options *XMLModelWithRenamedFieldsValueClientGetOptions) (XMLModelWithRenamedFieldsValueClientGetResponse, error) { + var err error + const operationName = "XMLModelWithRenamedFieldsValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return XMLModelWithRenamedFieldsValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithRenamedFieldsValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithRenamedFieldsValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *XMLModelWithRenamedFieldsValueClient) getCreateRequest(ctx context.Context, _ *XMLModelWithRenamedFieldsValueClientGetOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithRenamedFields" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *XMLModelWithRenamedFieldsValueClient) getHandleResponse(resp *http.Response) (XMLModelWithRenamedFieldsValueClientGetResponse, error) { + result := XMLModelWithRenamedFieldsValueClientGetResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.ModelWithRenamedFields); err != nil { + return XMLModelWithRenamedFieldsValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithRenamedFieldsValueClientPutOptions contains the optional parameters for the XMLModelWithRenamedFieldsValueClient.Put +// method. +func (client *XMLModelWithRenamedFieldsValueClient) Put(ctx context.Context, input ModelWithRenamedFields, options *XMLModelWithRenamedFieldsValueClientPutOptions) (XMLModelWithRenamedFieldsValueClientPutResponse, error) { + var err error + const operationName = "XMLModelWithRenamedFieldsValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, input, options) + if err != nil { + return XMLModelWithRenamedFieldsValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithRenamedFieldsValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithRenamedFieldsValueClientPutResponse{}, err + } + return XMLModelWithRenamedFieldsValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *XMLModelWithRenamedFieldsValueClient) putCreateRequest(ctx context.Context, input ModelWithRenamedFields, _ *XMLModelWithRenamedFieldsValueClientPutOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithRenamedFields" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamednestedmodelvalue_client.go b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamednestedmodelvalue_client.go new file mode 100644 index 000000000000..022ee4bbdf2d --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamednestedmodelvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// XMLModelWithRenamedNestedModelValueClient - §2.2 — Operations for the ModelWithRenamedNestedModel type. +// Don't use this type directly, use [XMLClient.NewXMLModelWithRenamedNestedModelValueClient] instead. +type XMLModelWithRenamedNestedModelValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithRenamedNestedModelValueClientGetOptions contains the optional parameters for the XMLModelWithRenamedNestedModelValueClient.Get +// method. +func (client *XMLModelWithRenamedNestedModelValueClient) Get(ctx context.Context, options *XMLModelWithRenamedNestedModelValueClientGetOptions) (XMLModelWithRenamedNestedModelValueClientGetResponse, error) { + var err error + const operationName = "XMLModelWithRenamedNestedModelValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return XMLModelWithRenamedNestedModelValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithRenamedNestedModelValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithRenamedNestedModelValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *XMLModelWithRenamedNestedModelValueClient) getCreateRequest(ctx context.Context, _ *XMLModelWithRenamedNestedModelValueClientGetOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithRenamedNestedModel" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *XMLModelWithRenamedNestedModelValueClient) getHandleResponse(resp *http.Response) (XMLModelWithRenamedNestedModelValueClientGetResponse, error) { + result := XMLModelWithRenamedNestedModelValueClientGetResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.ModelWithRenamedNestedModel); err != nil { + return XMLModelWithRenamedNestedModelValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithRenamedNestedModelValueClientPutOptions contains the optional parameters for the XMLModelWithRenamedNestedModelValueClient.Put +// method. +func (client *XMLModelWithRenamedNestedModelValueClient) Put(ctx context.Context, input ModelWithRenamedNestedModel, options *XMLModelWithRenamedNestedModelValueClientPutOptions) (XMLModelWithRenamedNestedModelValueClientPutResponse, error) { + var err error + const operationName = "XMLModelWithRenamedNestedModelValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, input, options) + if err != nil { + return XMLModelWithRenamedNestedModelValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithRenamedNestedModelValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithRenamedNestedModelValueClientPutResponse{}, err + } + return XMLModelWithRenamedNestedModelValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *XMLModelWithRenamedNestedModelValueClient) putCreateRequest(ctx context.Context, input ModelWithRenamedNestedModel, _ *XMLModelWithRenamedNestedModelValueClientPutOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithRenamedNestedModel" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedpropertyvalue_client.go b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedpropertyvalue_client.go new file mode 100644 index 000000000000..8f0bbeabcdcb --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedpropertyvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// XMLModelWithRenamedPropertyValueClient - §1.2 — Operations for the ModelWithRenamedProperty type. +// Don't use this type directly, use [XMLClient.NewXMLModelWithRenamedPropertyValueClient] instead. +type XMLModelWithRenamedPropertyValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithRenamedPropertyValueClientGetOptions contains the optional parameters for the XMLModelWithRenamedPropertyValueClient.Get +// method. +func (client *XMLModelWithRenamedPropertyValueClient) Get(ctx context.Context, options *XMLModelWithRenamedPropertyValueClientGetOptions) (XMLModelWithRenamedPropertyValueClientGetResponse, error) { + var err error + const operationName = "XMLModelWithRenamedPropertyValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return XMLModelWithRenamedPropertyValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithRenamedPropertyValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithRenamedPropertyValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *XMLModelWithRenamedPropertyValueClient) getCreateRequest(ctx context.Context, _ *XMLModelWithRenamedPropertyValueClientGetOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithRenamedProperty" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *XMLModelWithRenamedPropertyValueClient) getHandleResponse(resp *http.Response) (XMLModelWithRenamedPropertyValueClientGetResponse, error) { + result := XMLModelWithRenamedPropertyValueClientGetResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.ModelWithRenamedProperty); err != nil { + return XMLModelWithRenamedPropertyValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithRenamedPropertyValueClientPutOptions contains the optional parameters for the XMLModelWithRenamedPropertyValueClient.Put +// method. +func (client *XMLModelWithRenamedPropertyValueClient) Put(ctx context.Context, input ModelWithRenamedProperty, options *XMLModelWithRenamedPropertyValueClientPutOptions) (XMLModelWithRenamedPropertyValueClientPutResponse, error) { + var err error + const operationName = "XMLModelWithRenamedPropertyValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, input, options) + if err != nil { + return XMLModelWithRenamedPropertyValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithRenamedPropertyValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithRenamedPropertyValueClientPutResponse{}, err + } + return XMLModelWithRenamedPropertyValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *XMLModelWithRenamedPropertyValueClient) putCreateRequest(ctx context.Context, input ModelWithRenamedProperty, _ *XMLModelWithRenamedPropertyValueClientPutOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithRenamedProperty" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedunwrappedmodelarrayvalue_client.go b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedunwrappedmodelarrayvalue_client.go new file mode 100644 index 000000000000..f6390450021e --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedunwrappedmodelarrayvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// XMLModelWithRenamedUnwrappedModelArrayValueClient - §4.4 — Operations for the ModelWithRenamedUnwrappedModelArray type. +// Don't use this type directly, use [XMLClient.NewXMLModelWithRenamedUnwrappedModelArrayValueClient] instead. +type XMLModelWithRenamedUnwrappedModelArrayValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithRenamedUnwrappedModelArrayValueClientGetOptions contains the optional parameters for the XMLModelWithRenamedUnwrappedModelArrayValueClient.Get +// method. +func (client *XMLModelWithRenamedUnwrappedModelArrayValueClient) Get(ctx context.Context, options *XMLModelWithRenamedUnwrappedModelArrayValueClientGetOptions) (XMLModelWithRenamedUnwrappedModelArrayValueClientGetResponse, error) { + var err error + const operationName = "XMLModelWithRenamedUnwrappedModelArrayValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return XMLModelWithRenamedUnwrappedModelArrayValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithRenamedUnwrappedModelArrayValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithRenamedUnwrappedModelArrayValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *XMLModelWithRenamedUnwrappedModelArrayValueClient) getCreateRequest(ctx context.Context, _ *XMLModelWithRenamedUnwrappedModelArrayValueClientGetOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithRenamedUnwrappedModelArray" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *XMLModelWithRenamedUnwrappedModelArrayValueClient) getHandleResponse(resp *http.Response) (XMLModelWithRenamedUnwrappedModelArrayValueClientGetResponse, error) { + result := XMLModelWithRenamedUnwrappedModelArrayValueClientGetResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.ModelWithRenamedUnwrappedModelArray); err != nil { + return XMLModelWithRenamedUnwrappedModelArrayValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithRenamedUnwrappedModelArrayValueClientPutOptions contains the optional parameters for the XMLModelWithRenamedUnwrappedModelArrayValueClient.Put +// method. +func (client *XMLModelWithRenamedUnwrappedModelArrayValueClient) Put(ctx context.Context, input ModelWithRenamedUnwrappedModelArray, options *XMLModelWithRenamedUnwrappedModelArrayValueClientPutOptions) (XMLModelWithRenamedUnwrappedModelArrayValueClientPutResponse, error) { + var err error + const operationName = "XMLModelWithRenamedUnwrappedModelArrayValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, input, options) + if err != nil { + return XMLModelWithRenamedUnwrappedModelArrayValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithRenamedUnwrappedModelArrayValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithRenamedUnwrappedModelArrayValueClientPutResponse{}, err + } + return XMLModelWithRenamedUnwrappedModelArrayValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *XMLModelWithRenamedUnwrappedModelArrayValueClient) putCreateRequest(ctx context.Context, input ModelWithRenamedUnwrappedModelArray, _ *XMLModelWithRenamedUnwrappedModelArrayValueClientPutOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithRenamedUnwrappedModelArray" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedwrappedanditemmodelarrayvalue_client.go b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedwrappedanditemmodelarrayvalue_client.go new file mode 100644 index 000000000000..56db5ef41078 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedwrappedanditemmodelarrayvalue_client.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// XMLModelWithRenamedWrappedAndItemModelArrayValueClient - §4.5 — Operations for the ModelWithRenamedWrappedAndItemModelArray +// type. +// Don't use this type directly, use [XMLClient.NewXMLModelWithRenamedWrappedAndItemModelArrayValueClient] instead. +type XMLModelWithRenamedWrappedAndItemModelArrayValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithRenamedWrappedAndItemModelArrayValueClientGetOptions contains the optional parameters for the XMLModelWithRenamedWrappedAndItemModelArrayValueClient.Get +// method. +func (client *XMLModelWithRenamedWrappedAndItemModelArrayValueClient) Get(ctx context.Context, options *XMLModelWithRenamedWrappedAndItemModelArrayValueClientGetOptions) (XMLModelWithRenamedWrappedAndItemModelArrayValueClientGetResponse, error) { + var err error + const operationName = "XMLModelWithRenamedWrappedAndItemModelArrayValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return XMLModelWithRenamedWrappedAndItemModelArrayValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithRenamedWrappedAndItemModelArrayValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithRenamedWrappedAndItemModelArrayValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *XMLModelWithRenamedWrappedAndItemModelArrayValueClient) getCreateRequest(ctx context.Context, _ *XMLModelWithRenamedWrappedAndItemModelArrayValueClientGetOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithRenamedWrappedAndItemModelArray" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *XMLModelWithRenamedWrappedAndItemModelArrayValueClient) getHandleResponse(resp *http.Response) (XMLModelWithRenamedWrappedAndItemModelArrayValueClientGetResponse, error) { + result := XMLModelWithRenamedWrappedAndItemModelArrayValueClientGetResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.ModelWithRenamedWrappedAndItemModelArray); err != nil { + return XMLModelWithRenamedWrappedAndItemModelArrayValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithRenamedWrappedAndItemModelArrayValueClientPutOptions contains the optional parameters for the XMLModelWithRenamedWrappedAndItemModelArrayValueClient.Put +// method. +func (client *XMLModelWithRenamedWrappedAndItemModelArrayValueClient) Put(ctx context.Context, input ModelWithRenamedWrappedAndItemModelArray, options *XMLModelWithRenamedWrappedAndItemModelArrayValueClientPutOptions) (XMLModelWithRenamedWrappedAndItemModelArrayValueClientPutResponse, error) { + var err error + const operationName = "XMLModelWithRenamedWrappedAndItemModelArrayValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, input, options) + if err != nil { + return XMLModelWithRenamedWrappedAndItemModelArrayValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithRenamedWrappedAndItemModelArrayValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithRenamedWrappedAndItemModelArrayValueClientPutResponse{}, err + } + return XMLModelWithRenamedWrappedAndItemModelArrayValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *XMLModelWithRenamedWrappedAndItemModelArrayValueClient) putCreateRequest(ctx context.Context, input ModelWithRenamedWrappedAndItemModelArray, _ *XMLModelWithRenamedWrappedAndItemModelArrayValueClientPutOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithRenamedWrappedAndItemModelArray" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedwrappedmodelarrayvalue_client.go b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedwrappedmodelarrayvalue_client.go new file mode 100644 index 000000000000..4c5bbd848ed9 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithrenamedwrappedmodelarrayvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// XMLModelWithRenamedWrappedModelArrayValueClient - §4.3 — Operations for the ModelWithRenamedWrappedModelArray type. +// Don't use this type directly, use [XMLClient.NewXMLModelWithRenamedWrappedModelArrayValueClient] instead. +type XMLModelWithRenamedWrappedModelArrayValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithRenamedWrappedModelArrayValueClientGetOptions contains the optional parameters for the XMLModelWithRenamedWrappedModelArrayValueClient.Get +// method. +func (client *XMLModelWithRenamedWrappedModelArrayValueClient) Get(ctx context.Context, options *XMLModelWithRenamedWrappedModelArrayValueClientGetOptions) (XMLModelWithRenamedWrappedModelArrayValueClientGetResponse, error) { + var err error + const operationName = "XMLModelWithRenamedWrappedModelArrayValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return XMLModelWithRenamedWrappedModelArrayValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithRenamedWrappedModelArrayValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithRenamedWrappedModelArrayValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *XMLModelWithRenamedWrappedModelArrayValueClient) getCreateRequest(ctx context.Context, _ *XMLModelWithRenamedWrappedModelArrayValueClientGetOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithRenamedWrappedModelArray" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *XMLModelWithRenamedWrappedModelArrayValueClient) getHandleResponse(resp *http.Response) (XMLModelWithRenamedWrappedModelArrayValueClientGetResponse, error) { + result := XMLModelWithRenamedWrappedModelArrayValueClientGetResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.ModelWithRenamedWrappedModelArray); err != nil { + return XMLModelWithRenamedWrappedModelArrayValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithRenamedWrappedModelArrayValueClientPutOptions contains the optional parameters for the XMLModelWithRenamedWrappedModelArrayValueClient.Put +// method. +func (client *XMLModelWithRenamedWrappedModelArrayValueClient) Put(ctx context.Context, input ModelWithRenamedWrappedModelArray, options *XMLModelWithRenamedWrappedModelArrayValueClientPutOptions) (XMLModelWithRenamedWrappedModelArrayValueClientPutResponse, error) { + var err error + const operationName = "XMLModelWithRenamedWrappedModelArrayValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, input, options) + if err != nil { + return XMLModelWithRenamedWrappedModelArrayValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithRenamedWrappedModelArrayValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithRenamedWrappedModelArrayValueClientPutResponse{}, err + } + return XMLModelWithRenamedWrappedModelArrayValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *XMLModelWithRenamedWrappedModelArrayValueClient) putCreateRequest(ctx context.Context, input ModelWithRenamedWrappedModelArray, _ *XMLModelWithRenamedWrappedModelArrayValueClientPutOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithRenamedWrappedModelArray" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/xmlgroup/zz_xmlmodelwithsimplearraysvalue_client.go b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithsimplearraysvalue_client.go new file mode 100644 index 000000000000..6c4295dc34b8 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithsimplearraysvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// XMLModelWithSimpleArraysValueClient - §3.1 — Operations for the ModelWithSimpleArrays type. +// Don't use this type directly, use [XMLClient.NewXMLModelWithSimpleArraysValueClient] instead. +type XMLModelWithSimpleArraysValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithSimpleArraysValueClientGetOptions contains the optional parameters for the XMLModelWithSimpleArraysValueClient.Get +// method. +func (client *XMLModelWithSimpleArraysValueClient) Get(ctx context.Context, options *XMLModelWithSimpleArraysValueClientGetOptions) (XMLModelWithSimpleArraysValueClientGetResponse, error) { + var err error + const operationName = "XMLModelWithSimpleArraysValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return XMLModelWithSimpleArraysValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithSimpleArraysValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithSimpleArraysValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *XMLModelWithSimpleArraysValueClient) getCreateRequest(ctx context.Context, _ *XMLModelWithSimpleArraysValueClientGetOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithSimpleArrays" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *XMLModelWithSimpleArraysValueClient) getHandleResponse(resp *http.Response) (XMLModelWithSimpleArraysValueClientGetResponse, error) { + result := XMLModelWithSimpleArraysValueClientGetResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.ModelWithSimpleArrays); err != nil { + return XMLModelWithSimpleArraysValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithSimpleArraysValueClientPutOptions contains the optional parameters for the XMLModelWithSimpleArraysValueClient.Put +// method. +func (client *XMLModelWithSimpleArraysValueClient) Put(ctx context.Context, input ModelWithSimpleArrays, options *XMLModelWithSimpleArraysValueClientPutOptions) (XMLModelWithSimpleArraysValueClientPutResponse, error) { + var err error + const operationName = "XMLModelWithSimpleArraysValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, input, options) + if err != nil { + return XMLModelWithSimpleArraysValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithSimpleArraysValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithSimpleArraysValueClientPutResponse{}, err + } + return XMLModelWithSimpleArraysValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *XMLModelWithSimpleArraysValueClient) putCreateRequest(ctx context.Context, input ModelWithSimpleArrays, _ *XMLModelWithSimpleArraysValueClientPutOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithSimpleArrays" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/xmlgroup/zz_xmlmodelwithtextvalue_client.go b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithtextvalue_client.go new file mode 100644 index 000000000000..d5667e19fa8b --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithtextvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// XMLModelWithTextValueClient - §8.1 — Operations for the ModelWithText type. +// Don't use this type directly, use [XMLClient.NewXMLModelWithTextValueClient] instead. +type XMLModelWithTextValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithTextValueClientGetOptions contains the optional parameters for the XMLModelWithTextValueClient.Get +// method. +func (client *XMLModelWithTextValueClient) Get(ctx context.Context, options *XMLModelWithTextValueClientGetOptions) (XMLModelWithTextValueClientGetResponse, error) { + var err error + const operationName = "XMLModelWithTextValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return XMLModelWithTextValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithTextValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithTextValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *XMLModelWithTextValueClient) getCreateRequest(ctx context.Context, _ *XMLModelWithTextValueClientGetOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithText" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *XMLModelWithTextValueClient) getHandleResponse(resp *http.Response) (XMLModelWithTextValueClientGetResponse, error) { + result := XMLModelWithTextValueClientGetResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.ModelWithText); err != nil { + return XMLModelWithTextValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithTextValueClientPutOptions contains the optional parameters for the XMLModelWithTextValueClient.Put +// method. +func (client *XMLModelWithTextValueClient) Put(ctx context.Context, input ModelWithText, options *XMLModelWithTextValueClientPutOptions) (XMLModelWithTextValueClientPutResponse, error) { + var err error + const operationName = "XMLModelWithTextValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, input, options) + if err != nil { + return XMLModelWithTextValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithTextValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithTextValueClientPutResponse{}, err + } + return XMLModelWithTextValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *XMLModelWithTextValueClient) putCreateRequest(ctx context.Context, input ModelWithText, _ *XMLModelWithTextValueClientPutOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithText" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/xmlgroup/zz_xmlmodelwithunwrappedarrayvalue_client.go b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithunwrappedarrayvalue_client.go new file mode 100644 index 000000000000..5f2ed63929d8 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithunwrappedarrayvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// XMLModelWithUnwrappedArrayValueClient - §3.2 — Operations for the ModelWithUnwrappedArray type. +// Don't use this type directly, use [XMLClient.NewXMLModelWithUnwrappedArrayValueClient] instead. +type XMLModelWithUnwrappedArrayValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithUnwrappedArrayValueClientGetOptions contains the optional parameters for the XMLModelWithUnwrappedArrayValueClient.Get +// method. +func (client *XMLModelWithUnwrappedArrayValueClient) Get(ctx context.Context, options *XMLModelWithUnwrappedArrayValueClientGetOptions) (XMLModelWithUnwrappedArrayValueClientGetResponse, error) { + var err error + const operationName = "XMLModelWithUnwrappedArrayValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return XMLModelWithUnwrappedArrayValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithUnwrappedArrayValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithUnwrappedArrayValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *XMLModelWithUnwrappedArrayValueClient) getCreateRequest(ctx context.Context, _ *XMLModelWithUnwrappedArrayValueClientGetOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithUnwrappedArray" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *XMLModelWithUnwrappedArrayValueClient) getHandleResponse(resp *http.Response) (XMLModelWithUnwrappedArrayValueClientGetResponse, error) { + result := XMLModelWithUnwrappedArrayValueClientGetResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.ModelWithUnwrappedArray); err != nil { + return XMLModelWithUnwrappedArrayValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithUnwrappedArrayValueClientPutOptions contains the optional parameters for the XMLModelWithUnwrappedArrayValueClient.Put +// method. +func (client *XMLModelWithUnwrappedArrayValueClient) Put(ctx context.Context, input ModelWithUnwrappedArray, options *XMLModelWithUnwrappedArrayValueClientPutOptions) (XMLModelWithUnwrappedArrayValueClientPutResponse, error) { + var err error + const operationName = "XMLModelWithUnwrappedArrayValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, input, options) + if err != nil { + return XMLModelWithUnwrappedArrayValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithUnwrappedArrayValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithUnwrappedArrayValueClientPutResponse{}, err + } + return XMLModelWithUnwrappedArrayValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *XMLModelWithUnwrappedArrayValueClient) putCreateRequest(ctx context.Context, input ModelWithUnwrappedArray, _ *XMLModelWithUnwrappedArrayValueClientPutOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithUnwrappedArray" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/xmlgroup/zz_xmlmodelwithunwrappedmodelarrayvalue_client.go b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithunwrappedmodelarrayvalue_client.go new file mode 100644 index 000000000000..b7f0ee3b3f9a --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithunwrappedmodelarrayvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// XMLModelWithUnwrappedModelArrayValueClient - §4.2 — Operations for the ModelWithUnwrappedModelArray type. +// Don't use this type directly, use [XMLClient.NewXMLModelWithUnwrappedModelArrayValueClient] instead. +type XMLModelWithUnwrappedModelArrayValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithUnwrappedModelArrayValueClientGetOptions contains the optional parameters for the XMLModelWithUnwrappedModelArrayValueClient.Get +// method. +func (client *XMLModelWithUnwrappedModelArrayValueClient) Get(ctx context.Context, options *XMLModelWithUnwrappedModelArrayValueClientGetOptions) (XMLModelWithUnwrappedModelArrayValueClientGetResponse, error) { + var err error + const operationName = "XMLModelWithUnwrappedModelArrayValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return XMLModelWithUnwrappedModelArrayValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithUnwrappedModelArrayValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithUnwrappedModelArrayValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *XMLModelWithUnwrappedModelArrayValueClient) getCreateRequest(ctx context.Context, _ *XMLModelWithUnwrappedModelArrayValueClientGetOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithUnwrappedModelArray" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *XMLModelWithUnwrappedModelArrayValueClient) getHandleResponse(resp *http.Response) (XMLModelWithUnwrappedModelArrayValueClientGetResponse, error) { + result := XMLModelWithUnwrappedModelArrayValueClientGetResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.ModelWithUnwrappedModelArray); err != nil { + return XMLModelWithUnwrappedModelArrayValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithUnwrappedModelArrayValueClientPutOptions contains the optional parameters for the XMLModelWithUnwrappedModelArrayValueClient.Put +// method. +func (client *XMLModelWithUnwrappedModelArrayValueClient) Put(ctx context.Context, input ModelWithUnwrappedModelArray, options *XMLModelWithUnwrappedModelArrayValueClientPutOptions) (XMLModelWithUnwrappedModelArrayValueClientPutResponse, error) { + var err error + const operationName = "XMLModelWithUnwrappedModelArrayValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, input, options) + if err != nil { + return XMLModelWithUnwrappedModelArrayValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithUnwrappedModelArrayValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithUnwrappedModelArrayValueClientPutResponse{}, err + } + return XMLModelWithUnwrappedModelArrayValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *XMLModelWithUnwrappedModelArrayValueClient) putCreateRequest(ctx context.Context, input ModelWithUnwrappedModelArray, _ *XMLModelWithUnwrappedModelArrayValueClientPutOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithUnwrappedModelArray" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/xmlgroup/zz_xmlmodelwithwrappedprimitivecustomitemnamesvalue_client.go b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithwrappedprimitivecustomitemnamesvalue_client.go new file mode 100644 index 000000000000..6085e5d41b77 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xmlmodelwithwrappedprimitivecustomitemnamesvalue_client.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// XMLModelWithWrappedPrimitiveCustomItemNamesValueClient - §3.5 — Operations for the ModelWithWrappedPrimitiveCustomItemNames +// type. +// Don't use this type directly, use [XMLClient.NewXMLModelWithWrappedPrimitiveCustomItemNamesValueClient] instead. +type XMLModelWithWrappedPrimitiveCustomItemNamesValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithWrappedPrimitiveCustomItemNamesValueClientGetOptions contains the optional parameters for the XMLModelWithWrappedPrimitiveCustomItemNamesValueClient.Get +// method. +func (client *XMLModelWithWrappedPrimitiveCustomItemNamesValueClient) Get(ctx context.Context, options *XMLModelWithWrappedPrimitiveCustomItemNamesValueClientGetOptions) (XMLModelWithWrappedPrimitiveCustomItemNamesValueClientGetResponse, error) { + var err error + const operationName = "XMLModelWithWrappedPrimitiveCustomItemNamesValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return XMLModelWithWrappedPrimitiveCustomItemNamesValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithWrappedPrimitiveCustomItemNamesValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithWrappedPrimitiveCustomItemNamesValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *XMLModelWithWrappedPrimitiveCustomItemNamesValueClient) getCreateRequest(ctx context.Context, _ *XMLModelWithWrappedPrimitiveCustomItemNamesValueClientGetOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithWrappedPrimitiveCustomItemNames" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *XMLModelWithWrappedPrimitiveCustomItemNamesValueClient) getHandleResponse(resp *http.Response) (XMLModelWithWrappedPrimitiveCustomItemNamesValueClientGetResponse, error) { + result := XMLModelWithWrappedPrimitiveCustomItemNamesValueClientGetResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.ModelWithWrappedPrimitiveCustomItemNames); err != nil { + return XMLModelWithWrappedPrimitiveCustomItemNamesValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLModelWithWrappedPrimitiveCustomItemNamesValueClientPutOptions contains the optional parameters for the XMLModelWithWrappedPrimitiveCustomItemNamesValueClient.Put +// method. +func (client *XMLModelWithWrappedPrimitiveCustomItemNamesValueClient) Put(ctx context.Context, input ModelWithWrappedPrimitiveCustomItemNames, options *XMLModelWithWrappedPrimitiveCustomItemNamesValueClientPutOptions) (XMLModelWithWrappedPrimitiveCustomItemNamesValueClientPutResponse, error) { + var err error + const operationName = "XMLModelWithWrappedPrimitiveCustomItemNamesValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, input, options) + if err != nil { + return XMLModelWithWrappedPrimitiveCustomItemNamesValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLModelWithWrappedPrimitiveCustomItemNamesValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return XMLModelWithWrappedPrimitiveCustomItemNamesValueClientPutResponse{}, err + } + return XMLModelWithWrappedPrimitiveCustomItemNamesValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *XMLModelWithWrappedPrimitiveCustomItemNamesValueClient) putCreateRequest(ctx context.Context, input ModelWithWrappedPrimitiveCustomItemNames, _ *XMLModelWithWrappedPrimitiveCustomItemNamesValueClientPutOptions) (*policy.Request, error) { + urlPath := "/payload/xml/modelWithWrappedPrimitiveCustomItemNames" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/xmlgroup/zz_xmlsimplemodelvalue_client.go b/test/http-specs/payload/xmlgroup/zz_xmlsimplemodelvalue_client.go new file mode 100644 index 000000000000..409c7c234fd9 --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xmlsimplemodelvalue_client.go @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// XMLSimpleModelValueClient - §1.1 — Operations for the SimpleModel type. +// Don't use this type directly, use [XMLClient.NewXMLSimpleModelValueClient] instead. +type XMLSimpleModelValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLSimpleModelValueClientGetOptions contains the optional parameters for the XMLSimpleModelValueClient.Get method. +func (client *XMLSimpleModelValueClient) Get(ctx context.Context, options *XMLSimpleModelValueClientGetOptions) (XMLSimpleModelValueClientGetResponse, error) { + var err error + const operationName = "XMLSimpleModelValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return XMLSimpleModelValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLSimpleModelValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return XMLSimpleModelValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *XMLSimpleModelValueClient) getCreateRequest(ctx context.Context, _ *XMLSimpleModelValueClientGetOptions) (*policy.Request, error) { + urlPath := "/payload/xml/simpleModel" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *XMLSimpleModelValueClient) getHandleResponse(resp *http.Response) (XMLSimpleModelValueClientGetResponse, error) { + result := XMLSimpleModelValueClientGetResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.SimpleModel); err != nil { + return XMLSimpleModelValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLSimpleModelValueClientPutOptions contains the optional parameters for the XMLSimpleModelValueClient.Put method. +func (client *XMLSimpleModelValueClient) Put(ctx context.Context, input SimpleModel, options *XMLSimpleModelValueClientPutOptions) (XMLSimpleModelValueClientPutResponse, error) { + var err error + const operationName = "XMLSimpleModelValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, input, options) + if err != nil { + return XMLSimpleModelValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLSimpleModelValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return XMLSimpleModelValueClientPutResponse{}, err + } + return XMLSimpleModelValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *XMLSimpleModelValueClient) putCreateRequest(ctx context.Context, input SimpleModel, _ *XMLSimpleModelValueClientPutOptions) (*policy.Request, error) { + urlPath := "/payload/xml/simpleModel" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/payload/xmlgroup/zz_xmlxmlerrorvalue_client.go b/test/http-specs/payload/xmlgroup/zz_xmlxmlerrorvalue_client.go new file mode 100644 index 000000000000..fd227f80348b --- /dev/null +++ b/test/http-specs/payload/xmlgroup/zz_xmlxmlerrorvalue_client.go @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package xmlgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// XMLXMLErrorValueClient - Operations that return an error response in XML format. +// Don't use this type directly, use [XMLClient.NewXMLXMLErrorValueClient] instead. +type XMLXMLErrorValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - XMLXMLErrorValueClientGetOptions contains the optional parameters for the XMLXMLErrorValueClient.Get method. +func (client *XMLXMLErrorValueClient) Get(ctx context.Context, options *XMLXMLErrorValueClientGetOptions) (XMLXMLErrorValueClientGetResponse, error) { + var err error + const operationName = "XMLXMLErrorValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return XMLXMLErrorValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return XMLXMLErrorValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return XMLXMLErrorValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *XMLXMLErrorValueClient) getCreateRequest(ctx context.Context, _ *XMLXMLErrorValueClientGetOptions) (*policy.Request, error) { + urlPath := "/payload/xml/error" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *XMLXMLErrorValueClient) getHandleResponse(resp *http.Response) (XMLXMLErrorValueClientGetResponse, error) { + result := XMLXMLErrorValueClientGetResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.SimpleModel); err != nil { + return XMLXMLErrorValueClientGetResponse{}, err + } + return result, nil +} diff --git a/test/http-specs/serialization/encoded-name/jsongroup/LICENSE.txt b/test/http-specs/serialization/encoded-name/jsongroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/serialization/encoded-name/jsongroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/serialization/encoded-name/jsongroup/fake/zz_internal.go b/test/http-specs/serialization/encoded-name/jsongroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/http-specs/serialization/encoded-name/jsongroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/http-specs/serialization/encoded-name/jsongroup/fake/zz_json_server.go b/test/http-specs/serialization/encoded-name/jsongroup/fake/zz_json_server.go new file mode 100644 index 000000000000..fd14879fd495 --- /dev/null +++ b/test/http-specs/serialization/encoded-name/jsongroup/fake/zz_json_server.go @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// JSONServer is a fake server for instances of the jsongroup.JSONClient type. +type JSONServer struct { + // JSONPropertyServer contains the fakes for client JSONPropertyClient + JSONPropertyServer JSONPropertyServer +} + +// NewJSONServerTransport creates a new instance of JSONServerTransport with the provided implementation. +// The returned JSONServerTransport instance is connected to an instance of jsongroup.JSONClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewJSONServerTransport(srv *JSONServer) *JSONServerTransport { + return &JSONServerTransport{srv: srv} +} + +// JSONServerTransport connects instances of jsongroup.JSONClient to instances of JSONServer. +// Don't use this type directly, use NewJSONServerTransport instead. +type JSONServerTransport struct { + srv *JSONServer + trMu sync.Mutex + trJSONPropertyServer *JSONPropertyServerTransport +} + +// Do implements the policy.Transporter interface for JSONServerTransport. +func (j *JSONServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return j.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (j *JSONServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "JSONPropertyClient": + initServer(&j.trMu, &j.trJSONPropertyServer, func() *JSONPropertyServerTransport { + return NewJSONPropertyServerTransport(&j.srv.JSONPropertyServer) + }) + resp, err = j.trJSONPropertyServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to JSONServerTransport +var jsonServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/serialization/encoded-name/jsongroup/fake/zz_jsonproperty_server.go b/test/http-specs/serialization/encoded-name/jsongroup/fake/zz_jsonproperty_server.go new file mode 100644 index 000000000000..63f6f336939e --- /dev/null +++ b/test/http-specs/serialization/encoded-name/jsongroup/fake/zz_jsonproperty_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "jsongroup" + "net/http" + "slices" +) + +// JSONPropertyServer is a fake server for instances of the jsongroup.JSONPropertyClient type. +type JSONPropertyServer struct { + // Get is the fake for method JSONPropertyClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *jsongroup.JSONPropertyClientGetOptions) (resp azfake.Responder[jsongroup.JSONPropertyClientGetResponse], errResp azfake.ErrorResponder) + + // Send is the fake for method JSONPropertyClient.Send + // HTTP status codes to indicate success: http.StatusNoContent + Send func(ctx context.Context, body jsongroup.JSONEncodedNameModel, options *jsongroup.JSONPropertyClientSendOptions) (resp azfake.Responder[jsongroup.JSONPropertyClientSendResponse], errResp azfake.ErrorResponder) +} + +// NewJSONPropertyServerTransport creates a new instance of JSONPropertyServerTransport with the provided implementation. +// The returned JSONPropertyServerTransport instance is connected to an instance of jsongroup.JSONPropertyClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewJSONPropertyServerTransport(srv *JSONPropertyServer) *JSONPropertyServerTransport { + return &JSONPropertyServerTransport{srv: srv} +} + +// JSONPropertyServerTransport connects instances of jsongroup.JSONPropertyClient to instances of JSONPropertyServer. +// Don't use this type directly, use NewJSONPropertyServerTransport instead. +type JSONPropertyServerTransport struct { + srv *JSONPropertyServer +} + +// Do implements the policy.Transporter interface for JSONPropertyServerTransport. +func (j *JSONPropertyServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return j.dispatchToMethodFake(req, method) +} + +func (j *JSONPropertyServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if jsonPropertyServerTransportInterceptor != nil { + res.resp, res.err, intercepted = jsonPropertyServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "JSONPropertyClient.Get": + res.resp, res.err = j.dispatchGet(req) + case "JSONPropertyClient.Send": + res.resp, res.err = j.dispatchSend(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (j *JSONPropertyServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if j.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := j.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).JSONEncodedNameModel, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (j *JSONPropertyServerTransport) dispatchSend(req *http.Request) (*http.Response, error) { + if j.srv.Send == nil { + return nil, &nonRetriableError{errors.New("fake for method Send not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[jsongroup.JSONEncodedNameModel](req) + if err != nil { + return nil, err + } + respr, errRespr := j.srv.Send(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to JSONPropertyServerTransport +var jsonPropertyServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/serialization/encoded-name/jsongroup/go.mod b/test/http-specs/serialization/encoded-name/jsongroup/go.mod new file mode 100644 index 000000000000..1b7c5211ffd6 --- /dev/null +++ b/test/http-specs/serialization/encoded-name/jsongroup/go.mod @@ -0,0 +1,17 @@ +module jsongroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/serialization/encoded-name/jsongroup/go.sum b/test/http-specs/serialization/encoded-name/jsongroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/serialization/encoded-name/jsongroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/serialization/encoded-name/jsongroup/jsongroup_test.go b/test/http-specs/serialization/encoded-name/jsongroup/jsongroup_test.go new file mode 100644 index 000000000000..5589fc6183ec --- /dev/null +++ b/test/http-specs/serialization/encoded-name/jsongroup/jsongroup_test.go @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package jsongroup_test + +import ( + "context" + "jsongroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestJSONClientGet(t *testing.T) { + client, err := jsongroup.NewJSONClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewJSONPropertyClient().Get(context.Background(), nil) + require.NoError(t, err) + require.True(t, *resp.DefaultName) +} + +func TestJSONClientSend(t *testing.T) { + client, err := jsongroup.NewJSONClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + _, err = client.NewJSONPropertyClient().Send(context.Background(), jsongroup.JSONEncodedNameModel{DefaultName: to.Ptr(true)}, nil) + require.NoError(t, err) +} diff --git a/test/http-specs/serialization/encoded-name/jsongroup/testdata/_metadata.json b/test/http-specs/serialization/encoded-name/jsongroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/serialization/encoded-name/jsongroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/serialization/encoded-name/jsongroup/zz_json_client.go b/test/http-specs/serialization/encoded-name/jsongroup/zz_json_client.go new file mode 100644 index 000000000000..a288a6c28c1c --- /dev/null +++ b/test/http-specs/serialization/encoded-name/jsongroup/zz_json_client.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package jsongroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// JSONClient - Encoded names +// Don't use this type directly, use NewJSONClientWithNoCredential() instead. +type JSONClient struct { + internal *azcore.Client + endpoint string +} + +// JSONClientOptions contains the optional values for creating a [JSONClient]. +type JSONClientOptions struct { + azcore.ClientOptions +} + +// NewJSONClientWithNoCredential creates a new instance of JSONClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewJSONClientWithNoCredential(endpoint string, options *JSONClientOptions) (*JSONClient, error) { + if options == nil { + options = &JSONClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &JSONClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewJSONPropertyClient creates a new instance of [JSONPropertyClient]. +func (client *JSONClient) NewJSONPropertyClient() *JSONPropertyClient { + return &JSONPropertyClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/http-specs/serialization/encoded-name/jsongroup/zz_jsonproperty_client.go b/test/http-specs/serialization/encoded-name/jsongroup/zz_jsonproperty_client.go new file mode 100644 index 000000000000..a75ef739cf9d --- /dev/null +++ b/test/http-specs/serialization/encoded-name/jsongroup/zz_jsonproperty_client.go @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package jsongroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// JSONPropertyClient contains the methods for the JSONProperty group. +// Don't use this type directly, use [JSONClient.NewJSONPropertyClient] instead. +type JSONPropertyClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - JSONPropertyClientGetOptions contains the optional parameters for the JSONPropertyClient.Get method. +func (client *JSONPropertyClient) Get(ctx context.Context, options *JSONPropertyClientGetOptions) (JSONPropertyClientGetResponse, error) { + var err error + const operationName = "JSONPropertyClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return JSONPropertyClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return JSONPropertyClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return JSONPropertyClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *JSONPropertyClient) getCreateRequest(ctx context.Context, _ *JSONPropertyClientGetOptions) (*policy.Request, error) { + urlPath := "/serialization/encoded-name/json/property" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *JSONPropertyClient) getHandleResponse(resp *http.Response) (JSONPropertyClientGetResponse, error) { + result := JSONPropertyClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.JSONEncodedNameModel); err != nil { + return JSONPropertyClientGetResponse{}, err + } + return result, nil +} + +// Send - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - JSONPropertyClientSendOptions contains the optional parameters for the JSONPropertyClient.Send method. +func (client *JSONPropertyClient) Send(ctx context.Context, body JSONEncodedNameModel, options *JSONPropertyClientSendOptions) (JSONPropertyClientSendResponse, error) { + var err error + const operationName = "JSONPropertyClient.Send" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.sendCreateRequest(ctx, body, options) + if err != nil { + return JSONPropertyClientSendResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return JSONPropertyClientSendResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return JSONPropertyClientSendResponse{}, err + } + return JSONPropertyClientSendResponse{}, nil +} + +// sendCreateRequest creates the Send request. +func (client *JSONPropertyClient) sendCreateRequest(ctx context.Context, body JSONEncodedNameModel, _ *JSONPropertyClientSendOptions) (*policy.Request, error) { + urlPath := "/serialization/encoded-name/json/property" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/serialization/encoded-name/jsongroup/zz_models.go b/test/http-specs/serialization/encoded-name/jsongroup/zz_models.go new file mode 100644 index 000000000000..055999abebbd --- /dev/null +++ b/test/http-specs/serialization/encoded-name/jsongroup/zz_models.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package jsongroup + +type JSONEncodedNameModel struct { + // REQUIRED; Pass in true + DefaultName *bool +} diff --git a/test/http-specs/serialization/encoded-name/jsongroup/zz_models_serde.go b/test/http-specs/serialization/encoded-name/jsongroup/zz_models_serde.go new file mode 100644 index 000000000000..3a24912d8cf0 --- /dev/null +++ b/test/http-specs/serialization/encoded-name/jsongroup/zz_models_serde.go @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package jsongroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type JSONEncodedNameModel. +func (j JSONEncodedNameModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "wireName", j.DefaultName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JSONEncodedNameModel. +func (j *JSONEncodedNameModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", j, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "wireName": + err = unpopulate(val, "DefaultName", &j.DefaultName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", j, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/http-specs/serialization/encoded-name/jsongroup/zz_options.go b/test/http-specs/serialization/encoded-name/jsongroup/zz_options.go new file mode 100644 index 000000000000..35cf4d6d0998 --- /dev/null +++ b/test/http-specs/serialization/encoded-name/jsongroup/zz_options.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package jsongroup + +// JSONPropertyClientGetOptions contains the optional parameters for the JSONPropertyClient.Get method. +type JSONPropertyClientGetOptions struct { + // placeholder for future optional parameters +} + +// JSONPropertyClientSendOptions contains the optional parameters for the JSONPropertyClient.Send method. +type JSONPropertyClientSendOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/serialization/encoded-name/jsongroup/zz_responses.go b/test/http-specs/serialization/encoded-name/jsongroup/zz_responses.go new file mode 100644 index 000000000000..a0706befb205 --- /dev/null +++ b/test/http-specs/serialization/encoded-name/jsongroup/zz_responses.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package jsongroup + +// JSONPropertyClientGetResponse contains the response from method JSONPropertyClient.Get. +type JSONPropertyClientGetResponse struct { + JSONEncodedNameModel +} + +// JSONPropertyClientSendResponse contains the response from method JSONPropertyClient.Send. +type JSONPropertyClientSendResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/serialization/encoded-name/jsongroup/zz_version.go b/test/http-specs/serialization/encoded-name/jsongroup/zz_version.go new file mode 100644 index 000000000000..fac47ac077f9 --- /dev/null +++ b/test/http-specs/serialization/encoded-name/jsongroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package jsongroup + +const ( + moduleName = "jsongroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/server/endpoint/noendpointgroup/LICENSE.txt b/test/http-specs/server/endpoint/noendpointgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/server/endpoint/noendpointgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/server/endpoint/noendpointgroup/fake/zz_internal.go b/test/http-specs/server/endpoint/noendpointgroup/fake/zz_internal.go new file mode 100644 index 000000000000..705f81eacafe --- /dev/null +++ b/test/http-specs/server/endpoint/noendpointgroup/fake/zz_internal.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import "net/http" + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} diff --git a/test/http-specs/server/endpoint/noendpointgroup/fake/zz_notdefined_server.go b/test/http-specs/server/endpoint/noendpointgroup/fake/zz_notdefined_server.go new file mode 100644 index 000000000000..f560d952b3f4 --- /dev/null +++ b/test/http-specs/server/endpoint/noendpointgroup/fake/zz_notdefined_server.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "noendpointgroup" + "slices" +) + +// NotDefinedServer is a fake server for instances of the noendpointgroup.NotDefinedClient type. +type NotDefinedServer struct { + // Valid is the fake for method NotDefinedClient.Valid + // HTTP status codes to indicate success: http.StatusOK + Valid func(ctx context.Context, options *noendpointgroup.NotDefinedClientValidOptions) (resp azfake.Responder[noendpointgroup.NotDefinedClientValidResponse], errResp azfake.ErrorResponder) +} + +// NewNotDefinedServerTransport creates a new instance of NotDefinedServerTransport with the provided implementation. +// The returned NotDefinedServerTransport instance is connected to an instance of noendpointgroup.NotDefinedClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewNotDefinedServerTransport(srv *NotDefinedServer) *NotDefinedServerTransport { + return &NotDefinedServerTransport{srv: srv} +} + +// NotDefinedServerTransport connects instances of noendpointgroup.NotDefinedClient to instances of NotDefinedServer. +// Don't use this type directly, use NewNotDefinedServerTransport instead. +type NotDefinedServerTransport struct { + srv *NotDefinedServer +} + +// Do implements the policy.Transporter interface for NotDefinedServerTransport. +func (n *NotDefinedServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return n.dispatchToMethodFake(req, method) +} + +func (n *NotDefinedServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if notDefinedServerTransportInterceptor != nil { + res.resp, res.err, intercepted = notDefinedServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "NotDefinedClient.Valid": + res.resp, res.err = n.dispatchValid(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (n *NotDefinedServerTransport) dispatchValid(req *http.Request) (*http.Response, error) { + if n.srv.Valid == nil { + return nil, &nonRetriableError{errors.New("fake for method Valid not implemented")} + } + respr, errRespr := n.srv.Valid(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to NotDefinedServerTransport +var notDefinedServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/server/endpoint/noendpointgroup/go.mod b/test/http-specs/server/endpoint/noendpointgroup/go.mod new file mode 100644 index 000000000000..db9baad83298 --- /dev/null +++ b/test/http-specs/server/endpoint/noendpointgroup/go.mod @@ -0,0 +1,17 @@ +module noendpointgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/server/endpoint/noendpointgroup/go.sum b/test/http-specs/server/endpoint/noendpointgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/server/endpoint/noendpointgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/server/endpoint/noendpointgroup/notdefined_client_test.go b/test/http-specs/server/endpoint/noendpointgroup/notdefined_client_test.go new file mode 100644 index 000000000000..a9ca37265f0a --- /dev/null +++ b/test/http-specs/server/endpoint/noendpointgroup/notdefined_client_test.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package noendpointgroup_test + +import ( + "context" + "noendpointgroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestNotDefinedClient_Valid(t *testing.T) { + client, err := noendpointgroup.NewNotDefinedClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.Valid(context.Background(), nil) + require.NoError(t, err) + require.True(t, resp.Success) +} diff --git a/test/http-specs/server/endpoint/noendpointgroup/testdata/_metadata.json b/test/http-specs/server/endpoint/noendpointgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/server/endpoint/noendpointgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/server/endpoint/noendpointgroup/zz_notdefined_client.go b/test/http-specs/server/endpoint/noendpointgroup/zz_notdefined_client.go new file mode 100644 index 000000000000..d304321ffb3d --- /dev/null +++ b/test/http-specs/server/endpoint/noendpointgroup/zz_notdefined_client.go @@ -0,0 +1,76 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package noendpointgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// NotDefinedClient - Illustrates server doesn't define endpoint. Client should automatically add an endpoint to let user +// pass in. +// Don't use this type directly, use NewNotDefinedClientWithNoCredential() instead. +type NotDefinedClient struct { + internal *azcore.Client + endpoint string +} + +// NotDefinedClientOptions contains the optional values for creating a [NotDefinedClient]. +type NotDefinedClientOptions struct { + azcore.ClientOptions +} + +// NewNotDefinedClientWithNoCredential creates a new instance of NotDefinedClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewNotDefinedClientWithNoCredential(endpoint string, options *NotDefinedClientOptions) (*NotDefinedClient, error) { + if options == nil { + options = &NotDefinedClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &NotDefinedClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// - options - NotDefinedClientValidOptions contains the optional parameters for the NotDefinedClient.Valid method. +func (client *NotDefinedClient) Valid(ctx context.Context, options *NotDefinedClientValidOptions) (NotDefinedClientValidResponse, error) { + var err error + const operationName = "NotDefinedClient.Valid" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.validCreateRequest(ctx, options) + if err != nil { + return NotDefinedClientValidResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NotDefinedClientValidResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NotDefinedClientValidResponse{}, err + } + return NotDefinedClientValidResponse{Success: httpResp.StatusCode >= 200 && httpResp.StatusCode < 300}, nil +} + +// validCreateRequest creates the Valid request. +func (client *NotDefinedClient) validCreateRequest(ctx context.Context, _ *NotDefinedClientValidOptions) (*policy.Request, error) { + urlPath := "/server/endpoint/not-defined/valid" + req, err := runtime.NewRequest(ctx, http.MethodHead, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/server/endpoint/noendpointgroup/zz_options.go b/test/http-specs/server/endpoint/noendpointgroup/zz_options.go new file mode 100644 index 000000000000..a1d90e39e549 --- /dev/null +++ b/test/http-specs/server/endpoint/noendpointgroup/zz_options.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package noendpointgroup + +// NotDefinedClientValidOptions contains the optional parameters for the NotDefinedClient.Valid method. +type NotDefinedClientValidOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/server/endpoint/noendpointgroup/zz_responses.go b/test/http-specs/server/endpoint/noendpointgroup/zz_responses.go new file mode 100644 index 000000000000..c36b8f5c93ad --- /dev/null +++ b/test/http-specs/server/endpoint/noendpointgroup/zz_responses.go @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package noendpointgroup + +// NotDefinedClientValidResponse contains the response from method NotDefinedClient.Valid. +type NotDefinedClientValidResponse struct { + // Success indicates if the operation succeeded or failed. + Success bool +} diff --git a/test/http-specs/server/endpoint/noendpointgroup/zz_version.go b/test/http-specs/server/endpoint/noendpointgroup/zz_version.go new file mode 100644 index 000000000000..805372f4ee30 --- /dev/null +++ b/test/http-specs/server/endpoint/noendpointgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package noendpointgroup + +const ( + moduleName = "noendpointgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/server/path/multiplegroup/LICENSE.txt b/test/http-specs/server/path/multiplegroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/server/path/multiplegroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/server/path/multiplegroup/fake/zz_internal.go b/test/http-specs/server/path/multiplegroup/fake/zz_internal.go new file mode 100644 index 000000000000..705f81eacafe --- /dev/null +++ b/test/http-specs/server/path/multiplegroup/fake/zz_internal.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import "net/http" + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} diff --git a/test/http-specs/server/path/multiplegroup/fake/zz_multiple_server.go b/test/http-specs/server/path/multiplegroup/fake/zz_multiple_server.go new file mode 100644 index 000000000000..dd45494c4729 --- /dev/null +++ b/test/http-specs/server/path/multiplegroup/fake/zz_multiple_server.go @@ -0,0 +1,138 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "multiplegroup" + "net/http" + "net/url" + "regexp" + "slices" +) + +// MultipleServer is a fake server for instances of the multiplegroup.MultipleClient type. +type MultipleServer struct { + // NoOperationParams is the fake for method MultipleClient.NoOperationParams + // HTTP status codes to indicate success: http.StatusNoContent + NoOperationParams func(ctx context.Context, options *multiplegroup.MultipleClientNoOperationParamsOptions) (resp azfake.Responder[multiplegroup.MultipleClientNoOperationParamsResponse], errResp azfake.ErrorResponder) + + // WithOperationPathParam is the fake for method MultipleClient.WithOperationPathParam + // HTTP status codes to indicate success: http.StatusNoContent + WithOperationPathParam func(ctx context.Context, keyword string, options *multiplegroup.MultipleClientWithOperationPathParamOptions) (resp azfake.Responder[multiplegroup.MultipleClientWithOperationPathParamResponse], errResp azfake.ErrorResponder) +} + +// NewMultipleServerTransport creates a new instance of MultipleServerTransport with the provided implementation. +// The returned MultipleServerTransport instance is connected to an instance of multiplegroup.MultipleClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewMultipleServerTransport(srv *MultipleServer) *MultipleServerTransport { + return &MultipleServerTransport{srv: srv} +} + +// MultipleServerTransport connects instances of multiplegroup.MultipleClient to instances of MultipleServer. +// Don't use this type directly, use NewMultipleServerTransport instead. +type MultipleServerTransport struct { + srv *MultipleServer +} + +// Do implements the policy.Transporter interface for MultipleServerTransport. +func (m *MultipleServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToMethodFake(req, method) +} + +func (m *MultipleServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if multipleServerTransportInterceptor != nil { + res.resp, res.err, intercepted = multipleServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "MultipleClient.NoOperationParams": + res.resp, res.err = m.dispatchNoOperationParams(req) + case "MultipleClient.WithOperationPathParam": + res.resp, res.err = m.dispatchWithOperationPathParam(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *MultipleServerTransport) dispatchNoOperationParams(req *http.Request) (*http.Response, error) { + if m.srv.NoOperationParams == nil { + return nil, &nonRetriableError{errors.New("fake for method NoOperationParams not implemented")} + } + respr, errRespr := m.srv.NoOperationParams(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *MultipleServerTransport) dispatchWithOperationPathParam(req *http.Request) (*http.Response, error) { + if m.srv.WithOperationPathParam == nil { + return nil, &nonRetriableError{errors.New("fake for method WithOperationPathParam not implemented")} + } + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + keywordParam, err := url.PathUnescape(matches[regex.SubexpIndex("keyword")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.WithOperationPathParam(req.Context(), keywordParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to MultipleServerTransport +var multipleServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/server/path/multiplegroup/go.mod b/test/http-specs/server/path/multiplegroup/go.mod new file mode 100644 index 000000000000..219e1174726c --- /dev/null +++ b/test/http-specs/server/path/multiplegroup/go.mod @@ -0,0 +1,17 @@ +module multiplegroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/server/path/multiplegroup/go.sum b/test/http-specs/server/path/multiplegroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/server/path/multiplegroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/server/path/multiplegroup/multiple_client_test.go b/test/http-specs/server/path/multiplegroup/multiple_client_test.go new file mode 100644 index 000000000000..736132632866 --- /dev/null +++ b/test/http-specs/server/path/multiplegroup/multiple_client_test.go @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package multiplegroup_test + +import ( + "context" + "multiplegroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestMultipleClient_NoOperationParams(t *testing.T) { + client, err := multiplegroup.NewMultipleClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NoOperationParams(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestMultipleClient_WithOperationPathParam(t *testing.T) { + client, err := multiplegroup.NewMultipleClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.WithOperationPathParam(context.Background(), "test", nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/server/path/multiplegroup/testdata/_metadata.json b/test/http-specs/server/path/multiplegroup/testdata/_metadata.json new file mode 100644 index 000000000000..ed75cca830cf --- /dev/null +++ b/test/http-specs/server/path/multiplegroup/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Server.Path.Multiple": "v1.0" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/server/path/multiplegroup/zz_multiple_client.go b/test/http-specs/server/path/multiplegroup/zz_multiple_client.go new file mode 100644 index 000000000000..459e94ad1bf5 --- /dev/null +++ b/test/http-specs/server/path/multiplegroup/zz_multiple_client.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multiplegroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// MultipleClient contains the methods for the Multiple group. +// Don't use this type directly, use NewMultipleClientWithNoCredential() instead. +type MultipleClient struct { + internal *azcore.Client + endpoint string +} + +// MultipleClientOptions contains the optional values for creating a [MultipleClient]. +type MultipleClientOptions struct { + azcore.ClientOptions +} + +// NewMultipleClientWithNoCredential creates a new instance of MultipleClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewMultipleClientWithNoCredential(endpoint string, options *MultipleClientOptions) (*MultipleClient, error) { + if options == nil { + options = &MultipleClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{ + APIVersion: runtime.APIVersionOptions{ + Location: runtime.APIVersionLocationPath, + }, + }, &options.ClientOptions) + if err != nil { + return nil, err + } + apiVersion := "v1.0" + if options.APIVersion != "" { + apiVersion = options.APIVersion + } + host := "server/path/multiple/{apiVersion}" + host = strings.ReplaceAll(host, "{apiVersion}", apiVersion) + endpoint = runtime.JoinPaths(endpoint, host) + client := &MultipleClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NoOperationParams - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MultipleClientNoOperationParamsOptions contains the optional parameters for the MultipleClient.NoOperationParams +// method. +func (client *MultipleClient) NoOperationParams(ctx context.Context, options *MultipleClientNoOperationParamsOptions) (MultipleClientNoOperationParamsResponse, error) { + var err error + const operationName = "MultipleClient.NoOperationParams" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.noOperationParamsCreateRequest(ctx, options) + if err != nil { + return MultipleClientNoOperationParamsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MultipleClientNoOperationParamsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MultipleClientNoOperationParamsResponse{}, err + } + return MultipleClientNoOperationParamsResponse{}, nil +} + +// noOperationParamsCreateRequest creates the NoOperationParams request. +func (client *MultipleClient) noOperationParamsCreateRequest(ctx context.Context, _ *MultipleClientNoOperationParamsOptions) (*policy.Request, error) { + req, err := runtime.NewRequest(ctx, http.MethodGet, client.endpoint) + if err != nil { + return nil, err + } + return req, nil +} + +// WithOperationPathParam - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MultipleClientWithOperationPathParamOptions contains the optional parameters for the MultipleClient.WithOperationPathParam +// method. +func (client *MultipleClient) WithOperationPathParam(ctx context.Context, keyword string, options *MultipleClientWithOperationPathParamOptions) (MultipleClientWithOperationPathParamResponse, error) { + var err error + const operationName = "MultipleClient.WithOperationPathParam" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withOperationPathParamCreateRequest(ctx, keyword, options) + if err != nil { + return MultipleClientWithOperationPathParamResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MultipleClientWithOperationPathParamResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MultipleClientWithOperationPathParamResponse{}, err + } + return MultipleClientWithOperationPathParamResponse{}, nil +} + +// withOperationPathParamCreateRequest creates the WithOperationPathParam request. +func (client *MultipleClient) withOperationPathParamCreateRequest(ctx context.Context, keyword string, _ *MultipleClientWithOperationPathParamOptions) (*policy.Request, error) { + urlPath := "/{keyword}" + if keyword == "" { + return nil, errors.New("parameter keyword cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{keyword}", url.PathEscape(keyword)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/server/path/multiplegroup/zz_options.go b/test/http-specs/server/path/multiplegroup/zz_options.go new file mode 100644 index 000000000000..c46fef070c4b --- /dev/null +++ b/test/http-specs/server/path/multiplegroup/zz_options.go @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multiplegroup + +// MultipleClientNoOperationParamsOptions contains the optional parameters for the MultipleClient.NoOperationParams method. +type MultipleClientNoOperationParamsOptions struct { + // placeholder for future optional parameters +} + +// MultipleClientWithOperationPathParamOptions contains the optional parameters for the MultipleClient.WithOperationPathParam +// method. +type MultipleClientWithOperationPathParamOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/server/path/multiplegroup/zz_responses.go b/test/http-specs/server/path/multiplegroup/zz_responses.go new file mode 100644 index 000000000000..e3f74bbdb286 --- /dev/null +++ b/test/http-specs/server/path/multiplegroup/zz_responses.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package multiplegroup + +// MultipleClientNoOperationParamsResponse contains the response from method MultipleClient.NoOperationParams. +type MultipleClientNoOperationParamsResponse struct { + // placeholder for future response values +} + +// MultipleClientWithOperationPathParamResponse contains the response from method MultipleClient.WithOperationPathParam. +type MultipleClientWithOperationPathParamResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/server/path/multiplegroup/zz_version.go b/test/http-specs/server/path/multiplegroup/zz_version.go new file mode 100644 index 000000000000..d77071768c4e --- /dev/null +++ b/test/http-specs/server/path/multiplegroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package multiplegroup + +const ( + moduleName = "multiplegroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/server/path/singlegroup/LICENSE.txt b/test/http-specs/server/path/singlegroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/server/path/singlegroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/server/path/singlegroup/fake/zz_internal.go b/test/http-specs/server/path/singlegroup/fake/zz_internal.go new file mode 100644 index 000000000000..705f81eacafe --- /dev/null +++ b/test/http-specs/server/path/singlegroup/fake/zz_internal.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import "net/http" + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} diff --git a/test/http-specs/server/path/singlegroup/fake/zz_single_server.go b/test/http-specs/server/path/singlegroup/fake/zz_single_server.go new file mode 100644 index 000000000000..de8c726cbd79 --- /dev/null +++ b/test/http-specs/server/path/singlegroup/fake/zz_single_server.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "singlegroup" + "slices" +) + +// SingleServer is a fake server for instances of the singlegroup.SingleClient type. +type SingleServer struct { + // MyOp is the fake for method SingleClient.MyOp + // HTTP status codes to indicate success: http.StatusOK + MyOp func(ctx context.Context, options *singlegroup.SingleClientMyOpOptions) (resp azfake.Responder[singlegroup.SingleClientMyOpResponse], errResp azfake.ErrorResponder) +} + +// NewSingleServerTransport creates a new instance of SingleServerTransport with the provided implementation. +// The returned SingleServerTransport instance is connected to an instance of singlegroup.SingleClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSingleServerTransport(srv *SingleServer) *SingleServerTransport { + return &SingleServerTransport{srv: srv} +} + +// SingleServerTransport connects instances of singlegroup.SingleClient to instances of SingleServer. +// Don't use this type directly, use NewSingleServerTransport instead. +type SingleServerTransport struct { + srv *SingleServer +} + +// Do implements the policy.Transporter interface for SingleServerTransport. +func (s *SingleServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *SingleServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if singleServerTransportInterceptor != nil { + res.resp, res.err, intercepted = singleServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SingleClient.MyOp": + res.resp, res.err = s.dispatchMyOp(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *SingleServerTransport) dispatchMyOp(req *http.Request) (*http.Response, error) { + if s.srv.MyOp == nil { + return nil, &nonRetriableError{errors.New("fake for method MyOp not implemented")} + } + respr, errRespr := s.srv.MyOp(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SingleServerTransport +var singleServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/server/path/singlegroup/go.mod b/test/http-specs/server/path/singlegroup/go.mod new file mode 100644 index 000000000000..11fbf5d2b699 --- /dev/null +++ b/test/http-specs/server/path/singlegroup/go.mod @@ -0,0 +1,17 @@ +module singlegroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/server/path/singlegroup/go.sum b/test/http-specs/server/path/singlegroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/server/path/singlegroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/server/path/singlegroup/single_client_test.go b/test/http-specs/server/path/singlegroup/single_client_test.go new file mode 100644 index 000000000000..8ed181a7a8e9 --- /dev/null +++ b/test/http-specs/server/path/singlegroup/single_client_test.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package singlegroup_test + +import ( + "context" + "singlegroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestSingleClient_MyOp(t *testing.T) { + client, err := singlegroup.NewSingleClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.MyOp(context.Background(), nil) + require.NoError(t, err) + require.True(t, resp.Success) +} diff --git a/test/http-specs/server/path/singlegroup/testdata/_metadata.json b/test/http-specs/server/path/singlegroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/server/path/singlegroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/server/path/singlegroup/zz_options.go b/test/http-specs/server/path/singlegroup/zz_options.go new file mode 100644 index 000000000000..d5d77c9db2ca --- /dev/null +++ b/test/http-specs/server/path/singlegroup/zz_options.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package singlegroup + +// SingleClientMyOpOptions contains the optional parameters for the SingleClient.MyOp method. +type SingleClientMyOpOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/server/path/singlegroup/zz_responses.go b/test/http-specs/server/path/singlegroup/zz_responses.go new file mode 100644 index 000000000000..429e53a96581 --- /dev/null +++ b/test/http-specs/server/path/singlegroup/zz_responses.go @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package singlegroup + +// SingleClientMyOpResponse contains the response from method SingleClient.MyOp. +type SingleClientMyOpResponse struct { + // Success indicates if the operation succeeded or failed. + Success bool +} diff --git a/test/http-specs/server/path/singlegroup/zz_single_client.go b/test/http-specs/server/path/singlegroup/zz_single_client.go new file mode 100644 index 000000000000..6e8a99d9e8b5 --- /dev/null +++ b/test/http-specs/server/path/singlegroup/zz_single_client.go @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package singlegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// SingleClient - Illustrates server with a single path parameter @server +// Don't use this type directly, use NewSingleClientWithNoCredential() instead. +type SingleClient struct { + internal *azcore.Client + endpoint string +} + +// SingleClientOptions contains the optional values for creating a [SingleClient]. +type SingleClientOptions struct { + azcore.ClientOptions +} + +// NewSingleClientWithNoCredential creates a new instance of SingleClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewSingleClientWithNoCredential(endpoint string, options *SingleClientOptions) (*SingleClient, error) { + if options == nil { + options = &SingleClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &SingleClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// - options - SingleClientMyOpOptions contains the optional parameters for the SingleClient.MyOp method. +func (client *SingleClient) MyOp(ctx context.Context, options *SingleClientMyOpOptions) (SingleClientMyOpResponse, error) { + var err error + const operationName = "SingleClient.MyOp" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.myOpCreateRequest(ctx, options) + if err != nil { + return SingleClientMyOpResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SingleClientMyOpResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SingleClientMyOpResponse{}, err + } + return SingleClientMyOpResponse{Success: httpResp.StatusCode >= 200 && httpResp.StatusCode < 300}, nil +} + +// myOpCreateRequest creates the MyOp request. +func (client *SingleClient) myOpCreateRequest(ctx context.Context, _ *SingleClientMyOpOptions) (*policy.Request, error) { + urlPath := "/server/path/single/myOp" + req, err := runtime.NewRequest(ctx, http.MethodHead, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/server/path/singlegroup/zz_version.go b/test/http-specs/server/path/singlegroup/zz_version.go new file mode 100644 index 000000000000..1fea00720f49 --- /dev/null +++ b/test/http-specs/server/path/singlegroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package singlegroup + +const ( + moduleName = "singlegroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/server/versions/unversionedgroup/LICENSE.txt b/test/http-specs/server/versions/unversionedgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/server/versions/unversionedgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/server/versions/unversionedgroup/fake/zz_internal.go b/test/http-specs/server/versions/unversionedgroup/fake/zz_internal.go new file mode 100644 index 000000000000..705f81eacafe --- /dev/null +++ b/test/http-specs/server/versions/unversionedgroup/fake/zz_internal.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import "net/http" + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} diff --git a/test/http-specs/server/versions/unversionedgroup/fake/zz_notversioned_server.go b/test/http-specs/server/versions/unversionedgroup/fake/zz_notversioned_server.go new file mode 100644 index 000000000000..c669367332eb --- /dev/null +++ b/test/http-specs/server/versions/unversionedgroup/fake/zz_notversioned_server.go @@ -0,0 +1,164 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" + "unversionedgroup" +) + +// NotVersionedServer is a fake server for instances of the unversionedgroup.NotVersionedClient type. +type NotVersionedServer struct { + // WithPathAPIVersion is the fake for method NotVersionedClient.WithPathAPIVersion + // HTTP status codes to indicate success: http.StatusOK + WithPathAPIVersion func(ctx context.Context, apiVersion string, options *unversionedgroup.NotVersionedClientWithPathAPIVersionOptions) (resp azfake.Responder[unversionedgroup.NotVersionedClientWithPathAPIVersionResponse], errResp azfake.ErrorResponder) + + // WithQueryAPIVersion is the fake for method NotVersionedClient.WithQueryAPIVersion + // HTTP status codes to indicate success: http.StatusOK + WithQueryAPIVersion func(ctx context.Context, apiVersion string, options *unversionedgroup.NotVersionedClientWithQueryAPIVersionOptions) (resp azfake.Responder[unversionedgroup.NotVersionedClientWithQueryAPIVersionResponse], errResp azfake.ErrorResponder) + + // WithoutAPIVersion is the fake for method NotVersionedClient.WithoutAPIVersion + // HTTP status codes to indicate success: http.StatusOK + WithoutAPIVersion func(ctx context.Context, options *unversionedgroup.NotVersionedClientWithoutAPIVersionOptions) (resp azfake.Responder[unversionedgroup.NotVersionedClientWithoutAPIVersionResponse], errResp azfake.ErrorResponder) +} + +// NewNotVersionedServerTransport creates a new instance of NotVersionedServerTransport with the provided implementation. +// The returned NotVersionedServerTransport instance is connected to an instance of unversionedgroup.NotVersionedClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewNotVersionedServerTransport(srv *NotVersionedServer) *NotVersionedServerTransport { + return &NotVersionedServerTransport{srv: srv} +} + +// NotVersionedServerTransport connects instances of unversionedgroup.NotVersionedClient to instances of NotVersionedServer. +// Don't use this type directly, use NewNotVersionedServerTransport instead. +type NotVersionedServerTransport struct { + srv *NotVersionedServer +} + +// Do implements the policy.Transporter interface for NotVersionedServerTransport. +func (n *NotVersionedServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return n.dispatchToMethodFake(req, method) +} + +func (n *NotVersionedServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if notVersionedServerTransportInterceptor != nil { + res.resp, res.err, intercepted = notVersionedServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "NotVersionedClient.WithPathAPIVersion": + res.resp, res.err = n.dispatchWithPathAPIVersion(req) + case "NotVersionedClient.WithQueryAPIVersion": + res.resp, res.err = n.dispatchWithQueryAPIVersion(req) + case "NotVersionedClient.WithoutAPIVersion": + res.resp, res.err = n.dispatchWithoutAPIVersion(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (n *NotVersionedServerTransport) dispatchWithPathAPIVersion(req *http.Request) (*http.Response, error) { + if n.srv.WithPathAPIVersion == nil { + return nil, &nonRetriableError{errors.New("fake for method WithPathAPIVersion not implemented")} + } + const regexStr = `/server/versions/not-versioned/with-path-api-version/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + apiVersionParam, err := url.PathUnescape(matches[regex.SubexpIndex("apiVersion")]) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.WithPathAPIVersion(req.Context(), apiVersionParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NotVersionedServerTransport) dispatchWithQueryAPIVersion(req *http.Request) (*http.Response, error) { + if n.srv.WithQueryAPIVersion == nil { + return nil, &nonRetriableError{errors.New("fake for method WithQueryAPIVersion not implemented")} + } + qp := req.URL.Query() + respr, errRespr := n.srv.WithQueryAPIVersion(req.Context(), qp.Get("api-version"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NotVersionedServerTransport) dispatchWithoutAPIVersion(req *http.Request) (*http.Response, error) { + if n.srv.WithoutAPIVersion == nil { + return nil, &nonRetriableError{errors.New("fake for method WithoutAPIVersion not implemented")} + } + respr, errRespr := n.srv.WithoutAPIVersion(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to NotVersionedServerTransport +var notVersionedServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/server/versions/unversionedgroup/go.mod b/test/http-specs/server/versions/unversionedgroup/go.mod new file mode 100644 index 000000000000..89daf5655f85 --- /dev/null +++ b/test/http-specs/server/versions/unversionedgroup/go.mod @@ -0,0 +1,17 @@ +module unversionedgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/server/versions/unversionedgroup/go.sum b/test/http-specs/server/versions/unversionedgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/server/versions/unversionedgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/server/versions/unversionedgroup/notversioned_client_test.go b/test/http-specs/server/versions/unversionedgroup/notversioned_client_test.go new file mode 100644 index 000000000000..413accca05ff --- /dev/null +++ b/test/http-specs/server/versions/unversionedgroup/notversioned_client_test.go @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package unversionedgroup_test + +import ( + "context" + "testing" + "unversionedgroup" + + "github.com/stretchr/testify/require" +) + +func TestNotVersionedClient_WithPathAPIVersion(t *testing.T) { + client, err := unversionedgroup.NewNotVersionedClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.WithPathAPIVersion(context.Background(), "v1.0", nil) + require.NoError(t, err) + require.True(t, resp.Success) +} + +func TestNotVersionedClient_WithQueryAPIVersion(t *testing.T) { + client, err := unversionedgroup.NewNotVersionedClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.WithQueryAPIVersion(context.Background(), "v1.0", nil) + require.NoError(t, err) + require.True(t, resp.Success) +} + +func TestNotVersionedClient_WithoutAPIVersion(t *testing.T) { + client, err := unversionedgroup.NewNotVersionedClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.WithoutAPIVersion(context.Background(), nil) + require.NoError(t, err) + require.True(t, resp.Success) +} diff --git a/test/http-specs/server/versions/unversionedgroup/testdata/_metadata.json b/test/http-specs/server/versions/unversionedgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/server/versions/unversionedgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/server/versions/unversionedgroup/zz_notversioned_client.go b/test/http-specs/server/versions/unversionedgroup/zz_notversioned_client.go new file mode 100644 index 000000000000..752e5235cb85 --- /dev/null +++ b/test/http-specs/server/versions/unversionedgroup/zz_notversioned_client.go @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package unversionedgroup + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// NotVersionedClient - Illustrates not-versioned server. +// Don't use this type directly, use NewNotVersionedClientWithNoCredential() instead. +type NotVersionedClient struct { + internal *azcore.Client + endpoint string +} + +// NotVersionedClientOptions contains the optional values for creating a [NotVersionedClient]. +type NotVersionedClientOptions struct { + azcore.ClientOptions +} + +// NewNotVersionedClientWithNoCredential creates a new instance of NotVersionedClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewNotVersionedClientWithNoCredential(endpoint string, options *NotVersionedClientOptions) (*NotVersionedClient, error) { + if options == nil { + options = &NotVersionedClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &NotVersionedClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// - options - NotVersionedClientWithPathAPIVersionOptions contains the optional parameters for the NotVersionedClient.WithPathAPIVersion +// method. +func (client *NotVersionedClient) WithPathAPIVersion(ctx context.Context, apiVersion string, options *NotVersionedClientWithPathAPIVersionOptions) (NotVersionedClientWithPathAPIVersionResponse, error) { + var err error + const operationName = "NotVersionedClient.WithPathAPIVersion" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withPathAPIVersionCreateRequest(ctx, apiVersion, options) + if err != nil { + return NotVersionedClientWithPathAPIVersionResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NotVersionedClientWithPathAPIVersionResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NotVersionedClientWithPathAPIVersionResponse{}, err + } + return NotVersionedClientWithPathAPIVersionResponse{Success: httpResp.StatusCode >= 200 && httpResp.StatusCode < 300}, nil +} + +// withPathAPIVersionCreateRequest creates the WithPathAPIVersion request. +func (client *NotVersionedClient) withPathAPIVersionCreateRequest(ctx context.Context, apiVersion string, _ *NotVersionedClientWithPathAPIVersionOptions) (*policy.Request, error) { + urlPath := "/server/versions/not-versioned/with-path-api-version/{apiVersion}" + if apiVersion == "" { + return nil, errors.New("parameter apiVersion cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{apiVersion}", url.PathEscape(apiVersion)) + req, err := runtime.NewRequest(ctx, http.MethodHead, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// - options - NotVersionedClientWithQueryAPIVersionOptions contains the optional parameters for the NotVersionedClient.WithQueryAPIVersion +// method. +func (client *NotVersionedClient) WithQueryAPIVersion(ctx context.Context, apiVersion string, options *NotVersionedClientWithQueryAPIVersionOptions) (NotVersionedClientWithQueryAPIVersionResponse, error) { + var err error + const operationName = "NotVersionedClient.WithQueryAPIVersion" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withQueryAPIVersionCreateRequest(ctx, apiVersion, options) + if err != nil { + return NotVersionedClientWithQueryAPIVersionResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NotVersionedClientWithQueryAPIVersionResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NotVersionedClientWithQueryAPIVersionResponse{}, err + } + return NotVersionedClientWithQueryAPIVersionResponse{Success: httpResp.StatusCode >= 200 && httpResp.StatusCode < 300}, nil +} + +// withQueryAPIVersionCreateRequest creates the WithQueryAPIVersion request. +func (client *NotVersionedClient) withQueryAPIVersionCreateRequest(ctx context.Context, apiVersion string, _ *NotVersionedClientWithQueryAPIVersionOptions) (*policy.Request, error) { + urlPath := "/server/versions/not-versioned/with-query-api-version" + req, err := runtime.NewRequest(ctx, http.MethodHead, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", apiVersion) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// - options - NotVersionedClientWithoutAPIVersionOptions contains the optional parameters for the NotVersionedClient.WithoutAPIVersion +// method. +func (client *NotVersionedClient) WithoutAPIVersion(ctx context.Context, options *NotVersionedClientWithoutAPIVersionOptions) (NotVersionedClientWithoutAPIVersionResponse, error) { + var err error + const operationName = "NotVersionedClient.WithoutAPIVersion" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withoutAPIVersionCreateRequest(ctx, options) + if err != nil { + return NotVersionedClientWithoutAPIVersionResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NotVersionedClientWithoutAPIVersionResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NotVersionedClientWithoutAPIVersionResponse{}, err + } + return NotVersionedClientWithoutAPIVersionResponse{Success: httpResp.StatusCode >= 200 && httpResp.StatusCode < 300}, nil +} + +// withoutAPIVersionCreateRequest creates the WithoutAPIVersion request. +func (client *NotVersionedClient) withoutAPIVersionCreateRequest(ctx context.Context, _ *NotVersionedClientWithoutAPIVersionOptions) (*policy.Request, error) { + urlPath := "/server/versions/not-versioned/without-api-version" + req, err := runtime.NewRequest(ctx, http.MethodHead, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/server/versions/unversionedgroup/zz_options.go b/test/http-specs/server/versions/unversionedgroup/zz_options.go new file mode 100644 index 000000000000..866577f96915 --- /dev/null +++ b/test/http-specs/server/versions/unversionedgroup/zz_options.go @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package unversionedgroup + +// NotVersionedClientWithPathAPIVersionOptions contains the optional parameters for the NotVersionedClient.WithPathAPIVersion +// method. +type NotVersionedClientWithPathAPIVersionOptions struct { + // placeholder for future optional parameters +} + +// NotVersionedClientWithQueryAPIVersionOptions contains the optional parameters for the NotVersionedClient.WithQueryAPIVersion +// method. +type NotVersionedClientWithQueryAPIVersionOptions struct { + // placeholder for future optional parameters +} + +// NotVersionedClientWithoutAPIVersionOptions contains the optional parameters for the NotVersionedClient.WithoutAPIVersion +// method. +type NotVersionedClientWithoutAPIVersionOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/server/versions/unversionedgroup/zz_responses.go b/test/http-specs/server/versions/unversionedgroup/zz_responses.go new file mode 100644 index 000000000000..bcd9af2cd8c9 --- /dev/null +++ b/test/http-specs/server/versions/unversionedgroup/zz_responses.go @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package unversionedgroup + +// NotVersionedClientWithPathAPIVersionResponse contains the response from method NotVersionedClient.WithPathAPIVersion. +type NotVersionedClientWithPathAPIVersionResponse struct { + // Success indicates if the operation succeeded or failed. + Success bool +} + +// NotVersionedClientWithQueryAPIVersionResponse contains the response from method NotVersionedClient.WithQueryAPIVersion. +type NotVersionedClientWithQueryAPIVersionResponse struct { + // Success indicates if the operation succeeded or failed. + Success bool +} + +// NotVersionedClientWithoutAPIVersionResponse contains the response from method NotVersionedClient.WithoutAPIVersion. +type NotVersionedClientWithoutAPIVersionResponse struct { + // Success indicates if the operation succeeded or failed. + Success bool +} diff --git a/test/http-specs/server/versions/unversionedgroup/zz_version.go b/test/http-specs/server/versions/unversionedgroup/zz_version.go new file mode 100644 index 000000000000..aa6f18a6f6c7 --- /dev/null +++ b/test/http-specs/server/versions/unversionedgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package unversionedgroup + +const ( + moduleName = "unversionedgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/server/versions/versionedgroup/LICENSE.txt b/test/http-specs/server/versions/versionedgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/server/versions/versionedgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/server/versions/versionedgroup/fake/zz_internal.go b/test/http-specs/server/versions/versionedgroup/fake/zz_internal.go new file mode 100644 index 000000000000..705f81eacafe --- /dev/null +++ b/test/http-specs/server/versions/versionedgroup/fake/zz_internal.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import "net/http" + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} diff --git a/test/http-specs/server/versions/versionedgroup/fake/zz_versioned_server.go b/test/http-specs/server/versions/versionedgroup/fake/zz_versioned_server.go new file mode 100644 index 000000000000..989d85ac74ae --- /dev/null +++ b/test/http-specs/server/versions/versionedgroup/fake/zz_versioned_server.go @@ -0,0 +1,176 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "versionedgroup" +) + +// VersionedServer is a fake server for instances of the versionedgroup.VersionedClient type. +type VersionedServer struct { + // WithPathAPIVersion is the fake for method VersionedClient.WithPathAPIVersion + // HTTP status codes to indicate success: http.StatusOK + WithPathAPIVersion func(ctx context.Context, options *versionedgroup.VersionedClientWithPathAPIVersionOptions) (resp azfake.Responder[versionedgroup.VersionedClientWithPathAPIVersionResponse], errResp azfake.ErrorResponder) + + // WithQueryAPIVersion is the fake for method VersionedClient.WithQueryAPIVersion + // HTTP status codes to indicate success: http.StatusOK + WithQueryAPIVersion func(ctx context.Context, options *versionedgroup.VersionedClientWithQueryAPIVersionOptions) (resp azfake.Responder[versionedgroup.VersionedClientWithQueryAPIVersionResponse], errResp azfake.ErrorResponder) + + // WithQueryOldAPIVersion is the fake for method VersionedClient.WithQueryOldAPIVersion + // HTTP status codes to indicate success: http.StatusOK + WithQueryOldAPIVersion func(ctx context.Context, options *versionedgroup.VersionedClientWithQueryOldAPIVersionOptions) (resp azfake.Responder[versionedgroup.VersionedClientWithQueryOldAPIVersionResponse], errResp azfake.ErrorResponder) + + // WithoutAPIVersion is the fake for method VersionedClient.WithoutAPIVersion + // HTTP status codes to indicate success: http.StatusOK + WithoutAPIVersion func(ctx context.Context, options *versionedgroup.VersionedClientWithoutAPIVersionOptions) (resp azfake.Responder[versionedgroup.VersionedClientWithoutAPIVersionResponse], errResp azfake.ErrorResponder) +} + +// NewVersionedServerTransport creates a new instance of VersionedServerTransport with the provided implementation. +// The returned VersionedServerTransport instance is connected to an instance of versionedgroup.VersionedClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewVersionedServerTransport(srv *VersionedServer) *VersionedServerTransport { + return &VersionedServerTransport{srv: srv} +} + +// VersionedServerTransport connects instances of versionedgroup.VersionedClient to instances of VersionedServer. +// Don't use this type directly, use NewVersionedServerTransport instead. +type VersionedServerTransport struct { + srv *VersionedServer +} + +// Do implements the policy.Transporter interface for VersionedServerTransport. +func (v *VersionedServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *VersionedServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if versionedServerTransportInterceptor != nil { + res.resp, res.err, intercepted = versionedServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "VersionedClient.WithPathAPIVersion": + res.resp, res.err = v.dispatchWithPathAPIVersion(req) + case "VersionedClient.WithQueryAPIVersion": + res.resp, res.err = v.dispatchWithQueryAPIVersion(req) + case "VersionedClient.WithQueryOldAPIVersion": + res.resp, res.err = v.dispatchWithQueryOldAPIVersion(req) + case "VersionedClient.WithoutAPIVersion": + res.resp, res.err = v.dispatchWithoutAPIVersion(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *VersionedServerTransport) dispatchWithPathAPIVersion(req *http.Request) (*http.Response, error) { + if v.srv.WithPathAPIVersion == nil { + return nil, &nonRetriableError{errors.New("fake for method WithPathAPIVersion not implemented")} + } + respr, errRespr := v.srv.WithPathAPIVersion(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *VersionedServerTransport) dispatchWithQueryAPIVersion(req *http.Request) (*http.Response, error) { + if v.srv.WithQueryAPIVersion == nil { + return nil, &nonRetriableError{errors.New("fake for method WithQueryAPIVersion not implemented")} + } + respr, errRespr := v.srv.WithQueryAPIVersion(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *VersionedServerTransport) dispatchWithQueryOldAPIVersion(req *http.Request) (*http.Response, error) { + if v.srv.WithQueryOldAPIVersion == nil { + return nil, &nonRetriableError{errors.New("fake for method WithQueryOldAPIVersion not implemented")} + } + respr, errRespr := v.srv.WithQueryOldAPIVersion(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *VersionedServerTransport) dispatchWithoutAPIVersion(req *http.Request) (*http.Response, error) { + if v.srv.WithoutAPIVersion == nil { + return nil, &nonRetriableError{errors.New("fake for method WithoutAPIVersion not implemented")} + } + respr, errRespr := v.srv.WithoutAPIVersion(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to VersionedServerTransport +var versionedServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/server/versions/versionedgroup/go.mod b/test/http-specs/server/versions/versionedgroup/go.mod new file mode 100644 index 000000000000..c38d3e6e7bb2 --- /dev/null +++ b/test/http-specs/server/versions/versionedgroup/go.mod @@ -0,0 +1,17 @@ +module versionedgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/server/versions/versionedgroup/go.sum b/test/http-specs/server/versions/versionedgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/server/versions/versionedgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/server/versions/versionedgroup/testdata/_metadata.json b/test/http-specs/server/versions/versionedgroup/testdata/_metadata.json new file mode 100644 index 000000000000..760e16416a32 --- /dev/null +++ b/test/http-specs/server/versions/versionedgroup/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Server.Versions.Versioned": "2022-12-01-preview" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/server/versions/versionedgroup/versioned_client_test.go b/test/http-specs/server/versions/versionedgroup/versioned_client_test.go new file mode 100644 index 000000000000..63376c7f34fd --- /dev/null +++ b/test/http-specs/server/versions/versionedgroup/versioned_client_test.go @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package versionedgroup_test + +import ( + "context" + "testing" + "versionedgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/stretchr/testify/require" +) + +func TestVersionedClient_WithPathAPIVersion(t *testing.T) { + client, err := versionedgroup.NewVersionedClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.WithPathAPIVersion(context.Background(), nil) + require.NoError(t, err) + require.True(t, resp.Success) +} + +func TestVersionedClient_WithQueryAPIVersion(t *testing.T) { + client, err := versionedgroup.NewVersionedClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.WithQueryAPIVersion(context.Background(), nil) + require.NoError(t, err) + require.True(t, resp.Success) +} + +func TestVersionedClient_WithQueryOldAPIVersion(t *testing.T) { + client, err := versionedgroup.NewVersionedClientWithNoCredential("http://localhost:3000", &versionedgroup.VersionedClientOptions{ + azcore.ClientOptions{ + APIVersion: "2021-01-01-preview", + }, + }) + require.NoError(t, err) + resp, err := client.WithQueryOldAPIVersion(context.Background(), nil) + require.NoError(t, err) + require.True(t, resp.Success) +} + +func TestVersionedClient_WithoutAPIVersion(t *testing.T) { + client, err := versionedgroup.NewVersionedClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.WithoutAPIVersion(context.Background(), nil) + require.NoError(t, err) + require.True(t, resp.Success) +} diff --git a/test/http-specs/server/versions/versionedgroup/zz_constants.go b/test/http-specs/server/versions/versionedgroup/zz_constants.go new file mode 100644 index 000000000000..2e1fe2dfc439 --- /dev/null +++ b/test/http-specs/server/versions/versionedgroup/zz_constants.go @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package versionedgroup + +const ( + version20221201Preview string = "2022-12-01-preview" +) diff --git a/test/http-specs/server/versions/versionedgroup/zz_options.go b/test/http-specs/server/versions/versionedgroup/zz_options.go new file mode 100644 index 000000000000..47636bc1c383 --- /dev/null +++ b/test/http-specs/server/versions/versionedgroup/zz_options.go @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package versionedgroup + +// VersionedClientWithPathAPIVersionOptions contains the optional parameters for the VersionedClient.WithPathAPIVersion method. +type VersionedClientWithPathAPIVersionOptions struct { + // placeholder for future optional parameters +} + +// VersionedClientWithQueryAPIVersionOptions contains the optional parameters for the VersionedClient.WithQueryAPIVersion +// method. +type VersionedClientWithQueryAPIVersionOptions struct { + // placeholder for future optional parameters +} + +// VersionedClientWithQueryOldAPIVersionOptions contains the optional parameters for the VersionedClient.WithQueryOldAPIVersion +// method. +type VersionedClientWithQueryOldAPIVersionOptions struct { + // placeholder for future optional parameters +} + +// VersionedClientWithoutAPIVersionOptions contains the optional parameters for the VersionedClient.WithoutAPIVersion method. +type VersionedClientWithoutAPIVersionOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/server/versions/versionedgroup/zz_responses.go b/test/http-specs/server/versions/versionedgroup/zz_responses.go new file mode 100644 index 000000000000..c63845160fcc --- /dev/null +++ b/test/http-specs/server/versions/versionedgroup/zz_responses.go @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package versionedgroup + +// VersionedClientWithPathAPIVersionResponse contains the response from method VersionedClient.WithPathAPIVersion. +type VersionedClientWithPathAPIVersionResponse struct { + // Success indicates if the operation succeeded or failed. + Success bool +} + +// VersionedClientWithQueryAPIVersionResponse contains the response from method VersionedClient.WithQueryAPIVersion. +type VersionedClientWithQueryAPIVersionResponse struct { + // Success indicates if the operation succeeded or failed. + Success bool +} + +// VersionedClientWithQueryOldAPIVersionResponse contains the response from method VersionedClient.WithQueryOldAPIVersion. +type VersionedClientWithQueryOldAPIVersionResponse struct { + // Success indicates if the operation succeeded or failed. + Success bool +} + +// VersionedClientWithoutAPIVersionResponse contains the response from method VersionedClient.WithoutAPIVersion. +type VersionedClientWithoutAPIVersionResponse struct { + // Success indicates if the operation succeeded or failed. + Success bool +} diff --git a/test/http-specs/server/versions/versionedgroup/zz_version.go b/test/http-specs/server/versions/versionedgroup/zz_version.go new file mode 100644 index 000000000000..e2030df5bb73 --- /dev/null +++ b/test/http-specs/server/versions/versionedgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package versionedgroup + +const ( + moduleName = "versionedgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/server/versions/versionedgroup/zz_versioned_client.go b/test/http-specs/server/versions/versionedgroup/zz_versioned_client.go new file mode 100644 index 000000000000..55749b7995dc --- /dev/null +++ b/test/http-specs/server/versions/versionedgroup/zz_versioned_client.go @@ -0,0 +1,191 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package versionedgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// VersionedClient - Illustrates versioned server. +// Don't use this type directly, use NewVersionedClientWithNoCredential() instead. +// +// Generated from API version 2022-12-01-preview +type VersionedClient struct { + internal *azcore.Client + endpoint string +} + +// VersionedClientOptions contains the optional values for creating a [VersionedClient]. +type VersionedClientOptions struct { + azcore.ClientOptions +} + +// NewVersionedClientWithNoCredential creates a new instance of VersionedClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewVersionedClientWithNoCredential(endpoint string, options *VersionedClientOptions) (*VersionedClient, error) { + if options == nil { + options = &VersionedClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{ + APIVersion: runtime.APIVersionOptions{ + Name: "api-version", + Location: runtime.APIVersionLocationQueryParam, + }, + }, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &VersionedClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// - options - VersionedClientWithPathAPIVersionOptions contains the optional parameters for the VersionedClient.WithPathAPIVersion +// method. +func (client *VersionedClient) WithPathAPIVersion(ctx context.Context, options *VersionedClientWithPathAPIVersionOptions) (VersionedClientWithPathAPIVersionResponse, error) { + var err error + const operationName = "VersionedClient.WithPathAPIVersion" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withPathAPIVersionCreateRequest(ctx, options) + if err != nil { + return VersionedClientWithPathAPIVersionResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VersionedClientWithPathAPIVersionResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VersionedClientWithPathAPIVersionResponse{}, err + } + return VersionedClientWithPathAPIVersionResponse{Success: httpResp.StatusCode >= 200 && httpResp.StatusCode < 300}, nil +} + +// withPathAPIVersionCreateRequest creates the WithPathAPIVersion request. +func (client *VersionedClient) withPathAPIVersionCreateRequest(ctx context.Context, _ *VersionedClientWithPathAPIVersionOptions) (*policy.Request, error) { + urlPath := "/server/versions/versioned/with-path-api-version/{apiVersion}" + urlPath = strings.ReplaceAll(urlPath, "{apiVersion}", url.PathEscape(version20221201Preview)) + req, err := runtime.NewRequest(ctx, http.MethodHead, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// - options - VersionedClientWithQueryAPIVersionOptions contains the optional parameters for the VersionedClient.WithQueryAPIVersion +// method. +func (client *VersionedClient) WithQueryAPIVersion(ctx context.Context, options *VersionedClientWithQueryAPIVersionOptions) (VersionedClientWithQueryAPIVersionResponse, error) { + var err error + const operationName = "VersionedClient.WithQueryAPIVersion" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withQueryAPIVersionCreateRequest(ctx, options) + if err != nil { + return VersionedClientWithQueryAPIVersionResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VersionedClientWithQueryAPIVersionResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VersionedClientWithQueryAPIVersionResponse{}, err + } + return VersionedClientWithQueryAPIVersionResponse{Success: httpResp.StatusCode >= 200 && httpResp.StatusCode < 300}, nil +} + +// withQueryAPIVersionCreateRequest creates the WithQueryAPIVersion request. +func (client *VersionedClient) withQueryAPIVersionCreateRequest(ctx context.Context, _ *VersionedClientWithQueryAPIVersionOptions) (*policy.Request, error) { + urlPath := "/server/versions/versioned/with-query-api-version" + req, err := runtime.NewRequest(ctx, http.MethodHead, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20221201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// - options - VersionedClientWithQueryOldAPIVersionOptions contains the optional parameters for the VersionedClient.WithQueryOldAPIVersion +// method. +func (client *VersionedClient) WithQueryOldAPIVersion(ctx context.Context, options *VersionedClientWithQueryOldAPIVersionOptions) (VersionedClientWithQueryOldAPIVersionResponse, error) { + var err error + const operationName = "VersionedClient.WithQueryOldAPIVersion" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withQueryOldAPIVersionCreateRequest(ctx, options) + if err != nil { + return VersionedClientWithQueryOldAPIVersionResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VersionedClientWithQueryOldAPIVersionResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VersionedClientWithQueryOldAPIVersionResponse{}, err + } + return VersionedClientWithQueryOldAPIVersionResponse{Success: httpResp.StatusCode >= 200 && httpResp.StatusCode < 300}, nil +} + +// withQueryOldAPIVersionCreateRequest creates the WithQueryOldAPIVersion request. +func (client *VersionedClient) withQueryOldAPIVersionCreateRequest(ctx context.Context, _ *VersionedClientWithQueryOldAPIVersionOptions) (*policy.Request, error) { + urlPath := "/server/versions/versioned/with-query-old-api-version" + req, err := runtime.NewRequest(ctx, http.MethodHead, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20221201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// - options - VersionedClientWithoutAPIVersionOptions contains the optional parameters for the VersionedClient.WithoutAPIVersion +// method. +func (client *VersionedClient) WithoutAPIVersion(ctx context.Context, options *VersionedClientWithoutAPIVersionOptions) (VersionedClientWithoutAPIVersionResponse, error) { + var err error + const operationName = "VersionedClient.WithoutAPIVersion" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withoutAPIVersionCreateRequest(ctx, options) + if err != nil { + return VersionedClientWithoutAPIVersionResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VersionedClientWithoutAPIVersionResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VersionedClientWithoutAPIVersionResponse{}, err + } + return VersionedClientWithoutAPIVersionResponse{Success: httpResp.StatusCode >= 200 && httpResp.StatusCode < 300}, nil +} + +// withoutAPIVersionCreateRequest creates the WithoutAPIVersion request. +func (client *VersionedClient) withoutAPIVersionCreateRequest(ctx context.Context, _ *VersionedClientWithoutAPIVersionOptions) (*policy.Request, error) { + urlPath := "/server/versions/versioned/without-api-version" + req, err := runtime.NewRequest(ctx, http.MethodHead, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/special-headers/condreqgroup/LICENSE.txt b/test/http-specs/special-headers/condreqgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/special-headers/condreqgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/special-headers/condreqgroup/conditionalrequest_client_test.go b/test/http-specs/special-headers/condreqgroup/conditionalrequest_client_test.go new file mode 100644 index 000000000000..914d9c6528dc --- /dev/null +++ b/test/http-specs/special-headers/condreqgroup/conditionalrequest_client_test.go @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package condreqgroup_test + +import ( + "condreqgroup" + "context" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestConditionalRequestClient_HeadIfModifiedSince(t *testing.T) { + client, err := condreqgroup.NewConditionalRequestClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + since := time.Date(2022, time.August, 26, 14, 38, 0, 0, time.UTC) + resp, err := client.HeadIfModifiedSince(context.Background(), &condreqgroup.ConditionalRequestClientHeadIfModifiedSinceOptions{ + IfModifiedSince: &since, + }) + require.NoError(t, err) + require.True(t, resp.Success) +} + +func TestConditionalRequestClient_PostIfMatch(t *testing.T) { + client, err := condreqgroup.NewConditionalRequestClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.PostIfMatch(context.Background(), &condreqgroup.ConditionalRequestClientPostIfMatchOptions{ + IfMatch: to.Ptr(`"valid"`), + }) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestConditionalRequestClient_PostIfNoneMatch(t *testing.T) { + client, err := condreqgroup.NewConditionalRequestClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.PostIfNoneMatch(context.Background(), &condreqgroup.ConditionalRequestClientPostIfNoneMatchOptions{ + IfNoneMatch: to.Ptr(`"invalid"`), + }) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestConditionalRequestClient_PostIfUnmodifiedSince(t *testing.T) { + client, err := condreqgroup.NewConditionalRequestClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + since := time.Date(2022, time.August, 26, 14, 38, 0, 0, time.UTC) + resp, err := client.PostIfUnmodifiedSince(context.Background(), &condreqgroup.ConditionalRequestClientPostIfUnmodifiedSinceOptions{ + IfUnmodifiedSince: &since, + }) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/special-headers/condreqgroup/fake/zz_conditionalrequest_server.go b/test/http-specs/special-headers/condreqgroup/fake/zz_conditionalrequest_server.go new file mode 100644 index 000000000000..9ff575f6ca2e --- /dev/null +++ b/test/http-specs/special-headers/condreqgroup/fake/zz_conditionalrequest_server.go @@ -0,0 +1,211 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "condreqgroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "time" +) + +// ConditionalRequestServer is a fake server for instances of the condreqgroup.ConditionalRequestClient type. +type ConditionalRequestServer struct { + // HeadIfModifiedSince is the fake for method ConditionalRequestClient.HeadIfModifiedSince + // HTTP status codes to indicate success: http.StatusNoContent + HeadIfModifiedSince func(ctx context.Context, options *condreqgroup.ConditionalRequestClientHeadIfModifiedSinceOptions) (resp azfake.Responder[condreqgroup.ConditionalRequestClientHeadIfModifiedSinceResponse], errResp azfake.ErrorResponder) + + // PostIfMatch is the fake for method ConditionalRequestClient.PostIfMatch + // HTTP status codes to indicate success: http.StatusNoContent + PostIfMatch func(ctx context.Context, options *condreqgroup.ConditionalRequestClientPostIfMatchOptions) (resp azfake.Responder[condreqgroup.ConditionalRequestClientPostIfMatchResponse], errResp azfake.ErrorResponder) + + // PostIfNoneMatch is the fake for method ConditionalRequestClient.PostIfNoneMatch + // HTTP status codes to indicate success: http.StatusNoContent + PostIfNoneMatch func(ctx context.Context, options *condreqgroup.ConditionalRequestClientPostIfNoneMatchOptions) (resp azfake.Responder[condreqgroup.ConditionalRequestClientPostIfNoneMatchResponse], errResp azfake.ErrorResponder) + + // PostIfUnmodifiedSince is the fake for method ConditionalRequestClient.PostIfUnmodifiedSince + // HTTP status codes to indicate success: http.StatusNoContent + PostIfUnmodifiedSince func(ctx context.Context, options *condreqgroup.ConditionalRequestClientPostIfUnmodifiedSinceOptions) (resp azfake.Responder[condreqgroup.ConditionalRequestClientPostIfUnmodifiedSinceResponse], errResp azfake.ErrorResponder) +} + +// NewConditionalRequestServerTransport creates a new instance of ConditionalRequestServerTransport with the provided implementation. +// The returned ConditionalRequestServerTransport instance is connected to an instance of condreqgroup.ConditionalRequestClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewConditionalRequestServerTransport(srv *ConditionalRequestServer) *ConditionalRequestServerTransport { + return &ConditionalRequestServerTransport{srv: srv} +} + +// ConditionalRequestServerTransport connects instances of condreqgroup.ConditionalRequestClient to instances of ConditionalRequestServer. +// Don't use this type directly, use NewConditionalRequestServerTransport instead. +type ConditionalRequestServerTransport struct { + srv *ConditionalRequestServer +} + +// Do implements the policy.Transporter interface for ConditionalRequestServerTransport. +func (c *ConditionalRequestServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *ConditionalRequestServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if conditionalRequestServerTransportInterceptor != nil { + res.resp, res.err, intercepted = conditionalRequestServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ConditionalRequestClient.HeadIfModifiedSince": + res.resp, res.err = c.dispatchHeadIfModifiedSince(req) + case "ConditionalRequestClient.PostIfMatch": + res.resp, res.err = c.dispatchPostIfMatch(req) + case "ConditionalRequestClient.PostIfNoneMatch": + res.resp, res.err = c.dispatchPostIfNoneMatch(req) + case "ConditionalRequestClient.PostIfUnmodifiedSince": + res.resp, res.err = c.dispatchPostIfUnmodifiedSince(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *ConditionalRequestServerTransport) dispatchHeadIfModifiedSince(req *http.Request) (*http.Response, error) { + if c.srv.HeadIfModifiedSince == nil { + return nil, &nonRetriableError{errors.New("fake for method HeadIfModifiedSince not implemented")} + } + ifModifiedSinceParam, err := parseOptional(getHeaderValue(req.Header, "If-Modified-Since"), func(v string) (time.Time, error) { return time.Parse(time.RFC1123, v) }) + if err != nil { + return nil, err + } + var options *condreqgroup.ConditionalRequestClientHeadIfModifiedSinceOptions + if ifModifiedSinceParam != nil { + options = &condreqgroup.ConditionalRequestClientHeadIfModifiedSinceOptions{ + IfModifiedSince: ifModifiedSinceParam, + } + } + respr, errRespr := c.srv.HeadIfModifiedSince(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *ConditionalRequestServerTransport) dispatchPostIfMatch(req *http.Request) (*http.Response, error) { + if c.srv.PostIfMatch == nil { + return nil, &nonRetriableError{errors.New("fake for method PostIfMatch not implemented")} + } + ifMatchParam := getOptional(getHeaderValue(req.Header, "If-Match")) + var options *condreqgroup.ConditionalRequestClientPostIfMatchOptions + if ifMatchParam != nil { + options = &condreqgroup.ConditionalRequestClientPostIfMatchOptions{ + IfMatch: ifMatchParam, + } + } + respr, errRespr := c.srv.PostIfMatch(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *ConditionalRequestServerTransport) dispatchPostIfNoneMatch(req *http.Request) (*http.Response, error) { + if c.srv.PostIfNoneMatch == nil { + return nil, &nonRetriableError{errors.New("fake for method PostIfNoneMatch not implemented")} + } + ifNoneMatchParam := getOptional(getHeaderValue(req.Header, "If-None-Match")) + var options *condreqgroup.ConditionalRequestClientPostIfNoneMatchOptions + if ifNoneMatchParam != nil { + options = &condreqgroup.ConditionalRequestClientPostIfNoneMatchOptions{ + IfNoneMatch: ifNoneMatchParam, + } + } + respr, errRespr := c.srv.PostIfNoneMatch(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *ConditionalRequestServerTransport) dispatchPostIfUnmodifiedSince(req *http.Request) (*http.Response, error) { + if c.srv.PostIfUnmodifiedSince == nil { + return nil, &nonRetriableError{errors.New("fake for method PostIfUnmodifiedSince not implemented")} + } + ifUnmodifiedSinceParam, err := parseOptional(getHeaderValue(req.Header, "If-Unmodified-Since"), func(v string) (time.Time, error) { return time.Parse(time.RFC1123, v) }) + if err != nil { + return nil, err + } + var options *condreqgroup.ConditionalRequestClientPostIfUnmodifiedSinceOptions + if ifUnmodifiedSinceParam != nil { + options = &condreqgroup.ConditionalRequestClientPostIfUnmodifiedSinceOptions{ + IfUnmodifiedSince: ifUnmodifiedSinceParam, + } + } + respr, errRespr := c.srv.PostIfUnmodifiedSince(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ConditionalRequestServerTransport +var conditionalRequestServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/special-headers/condreqgroup/fake/zz_internal.go b/test/http-specs/special-headers/condreqgroup/fake/zz_internal.go new file mode 100644 index 000000000000..ea412051f8be --- /dev/null +++ b/test/http-specs/special-headers/condreqgroup/fake/zz_internal.go @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "reflect" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getHeaderValue(h http.Header, k string) string { + v := h[k] + if len(v) == 0 { + return "" + } + return v[0] +} + +func getOptional[T any](v T) *T { + if reflect.ValueOf(v).IsZero() { + return nil + } + return &v +} + +func parseOptional[T any](v string, parse func(v string) (T, error)) (*T, error) { + if v == "" { + return nil, nil + } + t, err := parse(v) + if err != nil { + return nil, err + } + return &t, nil +} diff --git a/test/http-specs/special-headers/condreqgroup/go.mod b/test/http-specs/special-headers/condreqgroup/go.mod new file mode 100644 index 000000000000..286399a29895 --- /dev/null +++ b/test/http-specs/special-headers/condreqgroup/go.mod @@ -0,0 +1,17 @@ +module condreqgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/special-headers/condreqgroup/go.sum b/test/http-specs/special-headers/condreqgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/special-headers/condreqgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/special-headers/condreqgroup/testdata/_metadata.json b/test/http-specs/special-headers/condreqgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/special-headers/condreqgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/special-headers/condreqgroup/zz_conditionalrequest_client.go b/test/http-specs/special-headers/condreqgroup/zz_conditionalrequest_client.go new file mode 100644 index 000000000000..a6e5aef11bde --- /dev/null +++ b/test/http-specs/special-headers/condreqgroup/zz_conditionalrequest_client.go @@ -0,0 +1,195 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package condreqgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "net/http" +) + +// ConditionalRequestClient - Illustrates conditional request headers +// Don't use this type directly, use NewConditionalRequestClientWithNoCredential() instead. +type ConditionalRequestClient struct { + internal *azcore.Client + endpoint string +} + +// ConditionalRequestClientOptions contains the optional values for creating a [ConditionalRequestClient]. +type ConditionalRequestClientOptions struct { + azcore.ClientOptions +} + +// NewConditionalRequestClientWithNoCredential creates a new instance of ConditionalRequestClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewConditionalRequestClientWithNoCredential(endpoint string, options *ConditionalRequestClientOptions) (*ConditionalRequestClient, error) { + if options == nil { + options = &ConditionalRequestClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &ConditionalRequestClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// HeadIfModifiedSince - Check when only If-Modified-Since in header is defined. +// - options - ConditionalRequestClientHeadIfModifiedSinceOptions contains the optional parameters for the ConditionalRequestClient.HeadIfModifiedSince +// method. +func (client *ConditionalRequestClient) HeadIfModifiedSince(ctx context.Context, options *ConditionalRequestClientHeadIfModifiedSinceOptions) (ConditionalRequestClientHeadIfModifiedSinceResponse, error) { + var err error + const operationName = "ConditionalRequestClient.HeadIfModifiedSince" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.headIfModifiedSinceCreateRequest(ctx, options) + if err != nil { + return ConditionalRequestClientHeadIfModifiedSinceResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ConditionalRequestClientHeadIfModifiedSinceResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ConditionalRequestClientHeadIfModifiedSinceResponse{}, err + } + return ConditionalRequestClientHeadIfModifiedSinceResponse{Success: httpResp.StatusCode >= 200 && httpResp.StatusCode < 300}, nil +} + +// headIfModifiedSinceCreateRequest creates the HeadIfModifiedSince request. +func (client *ConditionalRequestClient) headIfModifiedSinceCreateRequest(ctx context.Context, options *ConditionalRequestClientHeadIfModifiedSinceOptions) (*policy.Request, error) { + urlPath := "/special-headers/conditional-request/if-modified-since" + req, err := runtime.NewRequest(ctx, http.MethodHead, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + return req, nil +} + +// PostIfMatch - Check when only If-Match in header is defined. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ConditionalRequestClientPostIfMatchOptions contains the optional parameters for the ConditionalRequestClient.PostIfMatch +// method. +func (client *ConditionalRequestClient) PostIfMatch(ctx context.Context, options *ConditionalRequestClientPostIfMatchOptions) (ConditionalRequestClientPostIfMatchResponse, error) { + var err error + const operationName = "ConditionalRequestClient.PostIfMatch" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.postIfMatchCreateRequest(ctx, options) + if err != nil { + return ConditionalRequestClientPostIfMatchResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ConditionalRequestClientPostIfMatchResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ConditionalRequestClientPostIfMatchResponse{}, err + } + return ConditionalRequestClientPostIfMatchResponse{}, nil +} + +// postIfMatchCreateRequest creates the PostIfMatch request. +func (client *ConditionalRequestClient) postIfMatchCreateRequest(ctx context.Context, options *ConditionalRequestClientPostIfMatchOptions) (*policy.Request, error) { + urlPath := "/special-headers/conditional-request/if-match" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{*options.IfMatch} + } + return req, nil +} + +// PostIfNoneMatch - Check when only If-None-Match in header is defined. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ConditionalRequestClientPostIfNoneMatchOptions contains the optional parameters for the ConditionalRequestClient.PostIfNoneMatch +// method. +func (client *ConditionalRequestClient) PostIfNoneMatch(ctx context.Context, options *ConditionalRequestClientPostIfNoneMatchOptions) (ConditionalRequestClientPostIfNoneMatchResponse, error) { + var err error + const operationName = "ConditionalRequestClient.PostIfNoneMatch" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.postIfNoneMatchCreateRequest(ctx, options) + if err != nil { + return ConditionalRequestClientPostIfNoneMatchResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ConditionalRequestClientPostIfNoneMatchResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ConditionalRequestClientPostIfNoneMatchResponse{}, err + } + return ConditionalRequestClientPostIfNoneMatchResponse{}, nil +} + +// postIfNoneMatchCreateRequest creates the PostIfNoneMatch request. +func (client *ConditionalRequestClient) postIfNoneMatchCreateRequest(ctx context.Context, options *ConditionalRequestClientPostIfNoneMatchOptions) (*policy.Request, error) { + urlPath := "/special-headers/conditional-request/if-none-match" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{*options.IfNoneMatch} + } + return req, nil +} + +// PostIfUnmodifiedSince - Check when only If-Unmodified-Since in header is defined. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ConditionalRequestClientPostIfUnmodifiedSinceOptions contains the optional parameters for the ConditionalRequestClient.PostIfUnmodifiedSince +// method. +func (client *ConditionalRequestClient) PostIfUnmodifiedSince(ctx context.Context, options *ConditionalRequestClientPostIfUnmodifiedSinceOptions) (ConditionalRequestClientPostIfUnmodifiedSinceResponse, error) { + var err error + const operationName = "ConditionalRequestClient.PostIfUnmodifiedSince" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.postIfUnmodifiedSinceCreateRequest(ctx, options) + if err != nil { + return ConditionalRequestClientPostIfUnmodifiedSinceResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ConditionalRequestClientPostIfUnmodifiedSinceResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ConditionalRequestClientPostIfUnmodifiedSinceResponse{}, err + } + return ConditionalRequestClientPostIfUnmodifiedSinceResponse{}, nil +} + +// postIfUnmodifiedSinceCreateRequest creates the PostIfUnmodifiedSince request. +func (client *ConditionalRequestClient) postIfUnmodifiedSinceCreateRequest(ctx context.Context, options *ConditionalRequestClientPostIfUnmodifiedSinceOptions) (*policy.Request, error) { + urlPath := "/special-headers/conditional-request/if-unmodified-since" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + return req, nil +} diff --git a/test/http-specs/special-headers/condreqgroup/zz_options.go b/test/http-specs/special-headers/condreqgroup/zz_options.go new file mode 100644 index 000000000000..ec80e533e103 --- /dev/null +++ b/test/http-specs/special-headers/condreqgroup/zz_options.go @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package condreqgroup + +import "time" + +// ConditionalRequestClientHeadIfModifiedSinceOptions contains the optional parameters for the ConditionalRequestClient.HeadIfModifiedSince +// method. +type ConditionalRequestClientHeadIfModifiedSinceOptions struct { + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // been modified since the specified time. + IfModifiedSince *time.Time +} + +// ConditionalRequestClientPostIfMatchOptions contains the optional parameters for the ConditionalRequestClient.PostIfMatch +// method. +type ConditionalRequestClientPostIfMatchOptions struct { + // The request should only proceed if an entity matches this string. + IfMatch *string +} + +// ConditionalRequestClientPostIfNoneMatchOptions contains the optional parameters for the ConditionalRequestClient.PostIfNoneMatch +// method. +type ConditionalRequestClientPostIfNoneMatchOptions struct { + // The request should only proceed if no entity matches this string. + IfNoneMatch *string +} + +// ConditionalRequestClientPostIfUnmodifiedSinceOptions contains the optional parameters for the ConditionalRequestClient.PostIfUnmodifiedSince +// method. +type ConditionalRequestClientPostIfUnmodifiedSinceOptions struct { + // A timestamp indicating the last modified time of the resource known to the + // client. The operation will be performed only if the resource on the service has + // not been modified since the specified time. + IfUnmodifiedSince *time.Time +} diff --git a/test/http-specs/special-headers/condreqgroup/zz_responses.go b/test/http-specs/special-headers/condreqgroup/zz_responses.go new file mode 100644 index 000000000000..e6f9fb2791ec --- /dev/null +++ b/test/http-specs/special-headers/condreqgroup/zz_responses.go @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package condreqgroup + +// ConditionalRequestClientHeadIfModifiedSinceResponse contains the response from method ConditionalRequestClient.HeadIfModifiedSince. +type ConditionalRequestClientHeadIfModifiedSinceResponse struct { + // Success indicates if the operation succeeded or failed. + Success bool +} + +// ConditionalRequestClientPostIfMatchResponse contains the response from method ConditionalRequestClient.PostIfMatch. +type ConditionalRequestClientPostIfMatchResponse struct { + // placeholder for future response values +} + +// ConditionalRequestClientPostIfNoneMatchResponse contains the response from method ConditionalRequestClient.PostIfNoneMatch. +type ConditionalRequestClientPostIfNoneMatchResponse struct { + // placeholder for future response values +} + +// ConditionalRequestClientPostIfUnmodifiedSinceResponse contains the response from method ConditionalRequestClient.PostIfUnmodifiedSince. +type ConditionalRequestClientPostIfUnmodifiedSinceResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/special-headers/condreqgroup/zz_version.go b/test/http-specs/special-headers/condreqgroup/zz_version.go new file mode 100644 index 000000000000..b076defb7cac --- /dev/null +++ b/test/http-specs/special-headers/condreqgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package condreqgroup + +const ( + moduleName = "condreqgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/specialwordsgroup/LICENSE.txt b/test/http-specs/specialwordsgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/specialwordsgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/specialwordsgroup/extensiblestrings_client_test.go b/test/http-specs/specialwordsgroup/extensiblestrings_client_test.go new file mode 100644 index 000000000000..66274540ad87 --- /dev/null +++ b/test/http-specs/specialwordsgroup/extensiblestrings_client_test.go @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package specialwordsgroup_test + +import ( + "context" + "specialwordsgroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestExtensibleStringsClient_PutExtensibleStringValue(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsExtensibleStringsClient().PutExtensibleStringValue(context.Background(), specialwordsgroup.ExtensibleStringClass, nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, specialwordsgroup.ExtensibleStringClass, *resp.Value) +} diff --git a/test/http-specs/specialwordsgroup/fake/zz_internal.go b/test/http-specs/specialwordsgroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/http-specs/specialwordsgroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/http-specs/specialwordsgroup/fake/zz_specialwords_server.go b/test/http-specs/specialwordsgroup/fake/zz_specialwords_server.go new file mode 100644 index 000000000000..17e6c947705b --- /dev/null +++ b/test/http-specs/specialwordsgroup/fake/zz_specialwords_server.go @@ -0,0 +1,114 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// SpecialWordsServer is a fake server for instances of the specialwordsgroup.SpecialWordsClient type. +type SpecialWordsServer struct { + // SpecialWordsExtensibleStringsServer contains the fakes for client SpecialWordsExtensibleStringsClient + SpecialWordsExtensibleStringsServer SpecialWordsExtensibleStringsServer + + // SpecialWordsModelPropertiesServer contains the fakes for client SpecialWordsModelPropertiesClient + SpecialWordsModelPropertiesServer SpecialWordsModelPropertiesServer + + // SpecialWordsModelsServer contains the fakes for client SpecialWordsModelsClient + SpecialWordsModelsServer SpecialWordsModelsServer + + // SpecialWordsOperationsServer contains the fakes for client SpecialWordsOperationsClient + SpecialWordsOperationsServer SpecialWordsOperationsServer + + // SpecialWordsParametersServer contains the fakes for client SpecialWordsParametersClient + SpecialWordsParametersServer SpecialWordsParametersServer + + // SpecialWordsReservedOperationBodyParamsServer contains the fakes for client SpecialWordsReservedOperationBodyParamsClient + SpecialWordsReservedOperationBodyParamsServer SpecialWordsReservedOperationBodyParamsServer +} + +// NewSpecialWordsServerTransport creates a new instance of SpecialWordsServerTransport with the provided implementation. +// The returned SpecialWordsServerTransport instance is connected to an instance of specialwordsgroup.SpecialWordsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSpecialWordsServerTransport(srv *SpecialWordsServer) *SpecialWordsServerTransport { + return &SpecialWordsServerTransport{srv: srv} +} + +// SpecialWordsServerTransport connects instances of specialwordsgroup.SpecialWordsClient to instances of SpecialWordsServer. +// Don't use this type directly, use NewSpecialWordsServerTransport instead. +type SpecialWordsServerTransport struct { + srv *SpecialWordsServer + trMu sync.Mutex + trSpecialWordsExtensibleStringsServer *SpecialWordsExtensibleStringsServerTransport + trSpecialWordsModelPropertiesServer *SpecialWordsModelPropertiesServerTransport + trSpecialWordsModelsServer *SpecialWordsModelsServerTransport + trSpecialWordsOperationsServer *SpecialWordsOperationsServerTransport + trSpecialWordsParametersServer *SpecialWordsParametersServerTransport + trSpecialWordsReservedOperationBodyParamsServer *SpecialWordsReservedOperationBodyParamsServerTransport +} + +// Do implements the policy.Transporter interface for SpecialWordsServerTransport. +func (s *SpecialWordsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (s *SpecialWordsServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "SpecialWordsExtensibleStringsClient": + initServer(&s.trMu, &s.trSpecialWordsExtensibleStringsServer, func() *SpecialWordsExtensibleStringsServerTransport { + return NewSpecialWordsExtensibleStringsServerTransport(&s.srv.SpecialWordsExtensibleStringsServer) + }) + resp, err = s.trSpecialWordsExtensibleStringsServer.Do(req) + case "SpecialWordsModelPropertiesClient": + initServer(&s.trMu, &s.trSpecialWordsModelPropertiesServer, func() *SpecialWordsModelPropertiesServerTransport { + return NewSpecialWordsModelPropertiesServerTransport(&s.srv.SpecialWordsModelPropertiesServer) + }) + resp, err = s.trSpecialWordsModelPropertiesServer.Do(req) + case "SpecialWordsModelsClient": + initServer(&s.trMu, &s.trSpecialWordsModelsServer, func() *SpecialWordsModelsServerTransport { + return NewSpecialWordsModelsServerTransport(&s.srv.SpecialWordsModelsServer) + }) + resp, err = s.trSpecialWordsModelsServer.Do(req) + case "SpecialWordsOperationsClient": + initServer(&s.trMu, &s.trSpecialWordsOperationsServer, func() *SpecialWordsOperationsServerTransport { + return NewSpecialWordsOperationsServerTransport(&s.srv.SpecialWordsOperationsServer) + }) + resp, err = s.trSpecialWordsOperationsServer.Do(req) + case "SpecialWordsParametersClient": + initServer(&s.trMu, &s.trSpecialWordsParametersServer, func() *SpecialWordsParametersServerTransport { + return NewSpecialWordsParametersServerTransport(&s.srv.SpecialWordsParametersServer) + }) + resp, err = s.trSpecialWordsParametersServer.Do(req) + case "SpecialWordsReservedOperationBodyParamsClient": + initServer(&s.trMu, &s.trSpecialWordsReservedOperationBodyParamsServer, func() *SpecialWordsReservedOperationBodyParamsServerTransport { + return NewSpecialWordsReservedOperationBodyParamsServerTransport(&s.srv.SpecialWordsReservedOperationBodyParamsServer) + }) + resp, err = s.trSpecialWordsReservedOperationBodyParamsServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to SpecialWordsServerTransport +var specialWordsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/specialwordsgroup/fake/zz_specialwordsextensiblestrings_server.go b/test/http-specs/specialwordsgroup/fake/zz_specialwordsextensiblestrings_server.go new file mode 100644 index 000000000000..17c519b87e59 --- /dev/null +++ b/test/http-specs/specialwordsgroup/fake/zz_specialwordsextensiblestrings_server.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "specialwordsgroup" +) + +// SpecialWordsExtensibleStringsServer is a fake server for instances of the specialwordsgroup.SpecialWordsExtensibleStringsClient type. +type SpecialWordsExtensibleStringsServer struct { + // PutExtensibleStringValue is the fake for method SpecialWordsExtensibleStringsClient.PutExtensibleStringValue + // HTTP status codes to indicate success: http.StatusOK + PutExtensibleStringValue func(ctx context.Context, body specialwordsgroup.ExtensibleString, options *specialwordsgroup.SpecialWordsExtensibleStringsClientPutExtensibleStringValueOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsExtensibleStringsClientPutExtensibleStringValueResponse], errResp azfake.ErrorResponder) +} + +// NewSpecialWordsExtensibleStringsServerTransport creates a new instance of SpecialWordsExtensibleStringsServerTransport with the provided implementation. +// The returned SpecialWordsExtensibleStringsServerTransport instance is connected to an instance of specialwordsgroup.SpecialWordsExtensibleStringsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSpecialWordsExtensibleStringsServerTransport(srv *SpecialWordsExtensibleStringsServer) *SpecialWordsExtensibleStringsServerTransport { + return &SpecialWordsExtensibleStringsServerTransport{srv: srv} +} + +// SpecialWordsExtensibleStringsServerTransport connects instances of specialwordsgroup.SpecialWordsExtensibleStringsClient to instances of SpecialWordsExtensibleStringsServer. +// Don't use this type directly, use NewSpecialWordsExtensibleStringsServerTransport instead. +type SpecialWordsExtensibleStringsServerTransport struct { + srv *SpecialWordsExtensibleStringsServer +} + +// Do implements the policy.Transporter interface for SpecialWordsExtensibleStringsServerTransport. +func (s *SpecialWordsExtensibleStringsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *SpecialWordsExtensibleStringsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if specialWordsExtensibleStringsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = specialWordsExtensibleStringsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SpecialWordsExtensibleStringsClient.PutExtensibleStringValue": + res.resp, res.err = s.dispatchPutExtensibleStringValue(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *SpecialWordsExtensibleStringsServerTransport) dispatchPutExtensibleStringValue(req *http.Request) (*http.Response, error) { + if s.srv.PutExtensibleStringValue == nil { + return nil, &nonRetriableError{errors.New("fake for method PutExtensibleStringValue not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.ExtensibleString](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.PutExtensibleStringValue(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Value, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SpecialWordsExtensibleStringsServerTransport +var specialWordsExtensibleStringsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/specialwordsgroup/fake/zz_specialwordsmodelproperties_server.go b/test/http-specs/specialwordsgroup/fake/zz_specialwordsmodelproperties_server.go new file mode 100644 index 000000000000..44da541e199d --- /dev/null +++ b/test/http-specs/specialwordsgroup/fake/zz_specialwordsmodelproperties_server.go @@ -0,0 +1,163 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "specialwordsgroup" +) + +// SpecialWordsModelPropertiesServer is a fake server for instances of the specialwordsgroup.SpecialWordsModelPropertiesClient type. +type SpecialWordsModelPropertiesServer struct { + // DictMethods is the fake for method SpecialWordsModelPropertiesClient.DictMethods + // HTTP status codes to indicate success: http.StatusNoContent + DictMethods func(ctx context.Context, body specialwordsgroup.DictMethods, options *specialwordsgroup.SpecialWordsModelPropertiesClientDictMethodsOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelPropertiesClientDictMethodsResponse], errResp azfake.ErrorResponder) + + // SameAsModel is the fake for method SpecialWordsModelPropertiesClient.SameAsModel + // HTTP status codes to indicate success: http.StatusNoContent + SameAsModel func(ctx context.Context, body specialwordsgroup.SameAsModel, options *specialwordsgroup.SpecialWordsModelPropertiesClientSameAsModelOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelPropertiesClientSameAsModelResponse], errResp azfake.ErrorResponder) + + // WithList is the fake for method SpecialWordsModelPropertiesClient.WithList + // HTTP status codes to indicate success: http.StatusNoContent + WithList func(ctx context.Context, body specialwordsgroup.ModelWithList, options *specialwordsgroup.SpecialWordsModelPropertiesClientWithListOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelPropertiesClientWithListResponse], errResp azfake.ErrorResponder) +} + +// NewSpecialWordsModelPropertiesServerTransport creates a new instance of SpecialWordsModelPropertiesServerTransport with the provided implementation. +// The returned SpecialWordsModelPropertiesServerTransport instance is connected to an instance of specialwordsgroup.SpecialWordsModelPropertiesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSpecialWordsModelPropertiesServerTransport(srv *SpecialWordsModelPropertiesServer) *SpecialWordsModelPropertiesServerTransport { + return &SpecialWordsModelPropertiesServerTransport{srv: srv} +} + +// SpecialWordsModelPropertiesServerTransport connects instances of specialwordsgroup.SpecialWordsModelPropertiesClient to instances of SpecialWordsModelPropertiesServer. +// Don't use this type directly, use NewSpecialWordsModelPropertiesServerTransport instead. +type SpecialWordsModelPropertiesServerTransport struct { + srv *SpecialWordsModelPropertiesServer +} + +// Do implements the policy.Transporter interface for SpecialWordsModelPropertiesServerTransport. +func (s *SpecialWordsModelPropertiesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *SpecialWordsModelPropertiesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if specialWordsModelPropertiesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = specialWordsModelPropertiesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SpecialWordsModelPropertiesClient.DictMethods": + res.resp, res.err = s.dispatchDictMethods(req) + case "SpecialWordsModelPropertiesClient.SameAsModel": + res.resp, res.err = s.dispatchSameAsModel(req) + case "SpecialWordsModelPropertiesClient.WithList": + res.resp, res.err = s.dispatchWithList(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *SpecialWordsModelPropertiesServerTransport) dispatchDictMethods(req *http.Request) (*http.Response, error) { + if s.srv.DictMethods == nil { + return nil, &nonRetriableError{errors.New("fake for method DictMethods not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.DictMethods](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.DictMethods(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelPropertiesServerTransport) dispatchSameAsModel(req *http.Request) (*http.Response, error) { + if s.srv.SameAsModel == nil { + return nil, &nonRetriableError{errors.New("fake for method SameAsModel not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.SameAsModel](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.SameAsModel(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelPropertiesServerTransport) dispatchWithList(req *http.Request) (*http.Response, error) { + if s.srv.WithList == nil { + return nil, &nonRetriableError{errors.New("fake for method WithList not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.ModelWithList](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithList(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SpecialWordsModelPropertiesServerTransport +var specialWordsModelPropertiesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/specialwordsgroup/fake/zz_specialwordsmodels_server.go b/test/http-specs/specialwordsgroup/fake/zz_specialwordsmodels_server.go new file mode 100644 index 000000000000..21c807380380 --- /dev/null +++ b/test/http-specs/specialwordsgroup/fake/zz_specialwordsmodels_server.go @@ -0,0 +1,1033 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "specialwordsgroup" +) + +// SpecialWordsModelsServer is a fake server for instances of the specialwordsgroup.SpecialWordsModelsClient type. +type SpecialWordsModelsServer struct { + // WithAnd is the fake for method SpecialWordsModelsClient.WithAnd + // HTTP status codes to indicate success: http.StatusNoContent + WithAnd func(ctx context.Context, body specialwordsgroup.And, options *specialwordsgroup.SpecialWordsModelsClientWithAndOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithAndResponse], errResp azfake.ErrorResponder) + + // WithAs is the fake for method SpecialWordsModelsClient.WithAs + // HTTP status codes to indicate success: http.StatusNoContent + WithAs func(ctx context.Context, body specialwordsgroup.As, options *specialwordsgroup.SpecialWordsModelsClientWithAsOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithAsResponse], errResp azfake.ErrorResponder) + + // WithAssert is the fake for method SpecialWordsModelsClient.WithAssert + // HTTP status codes to indicate success: http.StatusNoContent + WithAssert func(ctx context.Context, body specialwordsgroup.Assert, options *specialwordsgroup.SpecialWordsModelsClientWithAssertOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithAssertResponse], errResp azfake.ErrorResponder) + + // WithAsync is the fake for method SpecialWordsModelsClient.WithAsync + // HTTP status codes to indicate success: http.StatusNoContent + WithAsync func(ctx context.Context, body specialwordsgroup.Async, options *specialwordsgroup.SpecialWordsModelsClientWithAsyncOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithAsyncResponse], errResp azfake.ErrorResponder) + + // WithAwait is the fake for method SpecialWordsModelsClient.WithAwait + // HTTP status codes to indicate success: http.StatusNoContent + WithAwait func(ctx context.Context, body specialwordsgroup.Await, options *specialwordsgroup.SpecialWordsModelsClientWithAwaitOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithAwaitResponse], errResp azfake.ErrorResponder) + + // WithBreak is the fake for method SpecialWordsModelsClient.WithBreak + // HTTP status codes to indicate success: http.StatusNoContent + WithBreak func(ctx context.Context, body specialwordsgroup.Break, options *specialwordsgroup.SpecialWordsModelsClientWithBreakOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithBreakResponse], errResp azfake.ErrorResponder) + + // WithClass is the fake for method SpecialWordsModelsClient.WithClass + // HTTP status codes to indicate success: http.StatusNoContent + WithClass func(ctx context.Context, body specialwordsgroup.Class, options *specialwordsgroup.SpecialWordsModelsClientWithClassOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithClassResponse], errResp azfake.ErrorResponder) + + // WithConstructor is the fake for method SpecialWordsModelsClient.WithConstructor + // HTTP status codes to indicate success: http.StatusNoContent + WithConstructor func(ctx context.Context, body specialwordsgroup.Constructor, options *specialwordsgroup.SpecialWordsModelsClientWithConstructorOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithConstructorResponse], errResp azfake.ErrorResponder) + + // WithContinue is the fake for method SpecialWordsModelsClient.WithContinue + // HTTP status codes to indicate success: http.StatusNoContent + WithContinue func(ctx context.Context, body specialwordsgroup.Continue, options *specialwordsgroup.SpecialWordsModelsClientWithContinueOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithContinueResponse], errResp azfake.ErrorResponder) + + // WithDef is the fake for method SpecialWordsModelsClient.WithDef + // HTTP status codes to indicate success: http.StatusNoContent + WithDef func(ctx context.Context, body specialwordsgroup.Def, options *specialwordsgroup.SpecialWordsModelsClientWithDefOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithDefResponse], errResp azfake.ErrorResponder) + + // WithDel is the fake for method SpecialWordsModelsClient.WithDel + // HTTP status codes to indicate success: http.StatusNoContent + WithDel func(ctx context.Context, body specialwordsgroup.Del, options *specialwordsgroup.SpecialWordsModelsClientWithDelOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithDelResponse], errResp azfake.ErrorResponder) + + // WithElif is the fake for method SpecialWordsModelsClient.WithElif + // HTTP status codes to indicate success: http.StatusNoContent + WithElif func(ctx context.Context, body specialwordsgroup.Elif, options *specialwordsgroup.SpecialWordsModelsClientWithElifOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithElifResponse], errResp azfake.ErrorResponder) + + // WithElse is the fake for method SpecialWordsModelsClient.WithElse + // HTTP status codes to indicate success: http.StatusNoContent + WithElse func(ctx context.Context, body specialwordsgroup.Else, options *specialwordsgroup.SpecialWordsModelsClientWithElseOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithElseResponse], errResp azfake.ErrorResponder) + + // WithExcept is the fake for method SpecialWordsModelsClient.WithExcept + // HTTP status codes to indicate success: http.StatusNoContent + WithExcept func(ctx context.Context, body specialwordsgroup.Except, options *specialwordsgroup.SpecialWordsModelsClientWithExceptOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithExceptResponse], errResp azfake.ErrorResponder) + + // WithExec is the fake for method SpecialWordsModelsClient.WithExec + // HTTP status codes to indicate success: http.StatusNoContent + WithExec func(ctx context.Context, body specialwordsgroup.Exec, options *specialwordsgroup.SpecialWordsModelsClientWithExecOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithExecResponse], errResp azfake.ErrorResponder) + + // WithFinally is the fake for method SpecialWordsModelsClient.WithFinally + // HTTP status codes to indicate success: http.StatusNoContent + WithFinally func(ctx context.Context, body specialwordsgroup.Finally, options *specialwordsgroup.SpecialWordsModelsClientWithFinallyOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithFinallyResponse], errResp azfake.ErrorResponder) + + // WithFor is the fake for method SpecialWordsModelsClient.WithFor + // HTTP status codes to indicate success: http.StatusNoContent + WithFor func(ctx context.Context, body specialwordsgroup.For, options *specialwordsgroup.SpecialWordsModelsClientWithForOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithForResponse], errResp azfake.ErrorResponder) + + // WithFrom is the fake for method SpecialWordsModelsClient.WithFrom + // HTTP status codes to indicate success: http.StatusNoContent + WithFrom func(ctx context.Context, body specialwordsgroup.From, options *specialwordsgroup.SpecialWordsModelsClientWithFromOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithFromResponse], errResp azfake.ErrorResponder) + + // WithGlobal is the fake for method SpecialWordsModelsClient.WithGlobal + // HTTP status codes to indicate success: http.StatusNoContent + WithGlobal func(ctx context.Context, body specialwordsgroup.Global, options *specialwordsgroup.SpecialWordsModelsClientWithGlobalOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithGlobalResponse], errResp azfake.ErrorResponder) + + // WithIf is the fake for method SpecialWordsModelsClient.WithIf + // HTTP status codes to indicate success: http.StatusNoContent + WithIf func(ctx context.Context, body specialwordsgroup.If, options *specialwordsgroup.SpecialWordsModelsClientWithIfOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithIfResponse], errResp azfake.ErrorResponder) + + // WithImport is the fake for method SpecialWordsModelsClient.WithImport + // HTTP status codes to indicate success: http.StatusNoContent + WithImport func(ctx context.Context, body specialwordsgroup.Import, options *specialwordsgroup.SpecialWordsModelsClientWithImportOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithImportResponse], errResp azfake.ErrorResponder) + + // WithIn is the fake for method SpecialWordsModelsClient.WithIn + // HTTP status codes to indicate success: http.StatusNoContent + WithIn func(ctx context.Context, body specialwordsgroup.In, options *specialwordsgroup.SpecialWordsModelsClientWithInOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithInResponse], errResp azfake.ErrorResponder) + + // WithIs is the fake for method SpecialWordsModelsClient.WithIs + // HTTP status codes to indicate success: http.StatusNoContent + WithIs func(ctx context.Context, body specialwordsgroup.Is, options *specialwordsgroup.SpecialWordsModelsClientWithIsOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithIsResponse], errResp azfake.ErrorResponder) + + // WithLambda is the fake for method SpecialWordsModelsClient.WithLambda + // HTTP status codes to indicate success: http.StatusNoContent + WithLambda func(ctx context.Context, body specialwordsgroup.Lambda, options *specialwordsgroup.SpecialWordsModelsClientWithLambdaOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithLambdaResponse], errResp azfake.ErrorResponder) + + // WithNot is the fake for method SpecialWordsModelsClient.WithNot + // HTTP status codes to indicate success: http.StatusNoContent + WithNot func(ctx context.Context, body specialwordsgroup.Not, options *specialwordsgroup.SpecialWordsModelsClientWithNotOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithNotResponse], errResp azfake.ErrorResponder) + + // WithOr is the fake for method SpecialWordsModelsClient.WithOr + // HTTP status codes to indicate success: http.StatusNoContent + WithOr func(ctx context.Context, body specialwordsgroup.Or, options *specialwordsgroup.SpecialWordsModelsClientWithOrOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithOrResponse], errResp azfake.ErrorResponder) + + // WithPass is the fake for method SpecialWordsModelsClient.WithPass + // HTTP status codes to indicate success: http.StatusNoContent + WithPass func(ctx context.Context, body specialwordsgroup.Pass, options *specialwordsgroup.SpecialWordsModelsClientWithPassOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithPassResponse], errResp azfake.ErrorResponder) + + // WithRaise is the fake for method SpecialWordsModelsClient.WithRaise + // HTTP status codes to indicate success: http.StatusNoContent + WithRaise func(ctx context.Context, body specialwordsgroup.Raise, options *specialwordsgroup.SpecialWordsModelsClientWithRaiseOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithRaiseResponse], errResp azfake.ErrorResponder) + + // WithReturn is the fake for method SpecialWordsModelsClient.WithReturn + // HTTP status codes to indicate success: http.StatusNoContent + WithReturn func(ctx context.Context, body specialwordsgroup.Return, options *specialwordsgroup.SpecialWordsModelsClientWithReturnOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithReturnResponse], errResp azfake.ErrorResponder) + + // WithTry is the fake for method SpecialWordsModelsClient.WithTry + // HTTP status codes to indicate success: http.StatusNoContent + WithTry func(ctx context.Context, body specialwordsgroup.Try, options *specialwordsgroup.SpecialWordsModelsClientWithTryOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithTryResponse], errResp azfake.ErrorResponder) + + // WithWhile is the fake for method SpecialWordsModelsClient.WithWhile + // HTTP status codes to indicate success: http.StatusNoContent + WithWhile func(ctx context.Context, body specialwordsgroup.While, options *specialwordsgroup.SpecialWordsModelsClientWithWhileOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithWhileResponse], errResp azfake.ErrorResponder) + + // WithWith is the fake for method SpecialWordsModelsClient.WithWith + // HTTP status codes to indicate success: http.StatusNoContent + WithWith func(ctx context.Context, body specialwordsgroup.With, options *specialwordsgroup.SpecialWordsModelsClientWithWithOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithWithResponse], errResp azfake.ErrorResponder) + + // WithYield is the fake for method SpecialWordsModelsClient.WithYield + // HTTP status codes to indicate success: http.StatusNoContent + WithYield func(ctx context.Context, body specialwordsgroup.Yield, options *specialwordsgroup.SpecialWordsModelsClientWithYieldOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsModelsClientWithYieldResponse], errResp azfake.ErrorResponder) +} + +// NewSpecialWordsModelsServerTransport creates a new instance of SpecialWordsModelsServerTransport with the provided implementation. +// The returned SpecialWordsModelsServerTransport instance is connected to an instance of specialwordsgroup.SpecialWordsModelsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSpecialWordsModelsServerTransport(srv *SpecialWordsModelsServer) *SpecialWordsModelsServerTransport { + return &SpecialWordsModelsServerTransport{srv: srv} +} + +// SpecialWordsModelsServerTransport connects instances of specialwordsgroup.SpecialWordsModelsClient to instances of SpecialWordsModelsServer. +// Don't use this type directly, use NewSpecialWordsModelsServerTransport instead. +type SpecialWordsModelsServerTransport struct { + srv *SpecialWordsModelsServer +} + +// Do implements the policy.Transporter interface for SpecialWordsModelsServerTransport. +func (s *SpecialWordsModelsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *SpecialWordsModelsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if specialWordsModelsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = specialWordsModelsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SpecialWordsModelsClient.WithAnd": + res.resp, res.err = s.dispatchWithAnd(req) + case "SpecialWordsModelsClient.WithAs": + res.resp, res.err = s.dispatchWithAs(req) + case "SpecialWordsModelsClient.WithAssert": + res.resp, res.err = s.dispatchWithAssert(req) + case "SpecialWordsModelsClient.WithAsync": + res.resp, res.err = s.dispatchWithAsync(req) + case "SpecialWordsModelsClient.WithAwait": + res.resp, res.err = s.dispatchWithAwait(req) + case "SpecialWordsModelsClient.WithBreak": + res.resp, res.err = s.dispatchWithBreak(req) + case "SpecialWordsModelsClient.WithClass": + res.resp, res.err = s.dispatchWithClass(req) + case "SpecialWordsModelsClient.WithConstructor": + res.resp, res.err = s.dispatchWithConstructor(req) + case "SpecialWordsModelsClient.WithContinue": + res.resp, res.err = s.dispatchWithContinue(req) + case "SpecialWordsModelsClient.WithDef": + res.resp, res.err = s.dispatchWithDef(req) + case "SpecialWordsModelsClient.WithDel": + res.resp, res.err = s.dispatchWithDel(req) + case "SpecialWordsModelsClient.WithElif": + res.resp, res.err = s.dispatchWithElif(req) + case "SpecialWordsModelsClient.WithElse": + res.resp, res.err = s.dispatchWithElse(req) + case "SpecialWordsModelsClient.WithExcept": + res.resp, res.err = s.dispatchWithExcept(req) + case "SpecialWordsModelsClient.WithExec": + res.resp, res.err = s.dispatchWithExec(req) + case "SpecialWordsModelsClient.WithFinally": + res.resp, res.err = s.dispatchWithFinally(req) + case "SpecialWordsModelsClient.WithFor": + res.resp, res.err = s.dispatchWithFor(req) + case "SpecialWordsModelsClient.WithFrom": + res.resp, res.err = s.dispatchWithFrom(req) + case "SpecialWordsModelsClient.WithGlobal": + res.resp, res.err = s.dispatchWithGlobal(req) + case "SpecialWordsModelsClient.WithIf": + res.resp, res.err = s.dispatchWithIf(req) + case "SpecialWordsModelsClient.WithImport": + res.resp, res.err = s.dispatchWithImport(req) + case "SpecialWordsModelsClient.WithIn": + res.resp, res.err = s.dispatchWithIn(req) + case "SpecialWordsModelsClient.WithIs": + res.resp, res.err = s.dispatchWithIs(req) + case "SpecialWordsModelsClient.WithLambda": + res.resp, res.err = s.dispatchWithLambda(req) + case "SpecialWordsModelsClient.WithNot": + res.resp, res.err = s.dispatchWithNot(req) + case "SpecialWordsModelsClient.WithOr": + res.resp, res.err = s.dispatchWithOr(req) + case "SpecialWordsModelsClient.WithPass": + res.resp, res.err = s.dispatchWithPass(req) + case "SpecialWordsModelsClient.WithRaise": + res.resp, res.err = s.dispatchWithRaise(req) + case "SpecialWordsModelsClient.WithReturn": + res.resp, res.err = s.dispatchWithReturn(req) + case "SpecialWordsModelsClient.WithTry": + res.resp, res.err = s.dispatchWithTry(req) + case "SpecialWordsModelsClient.WithWhile": + res.resp, res.err = s.dispatchWithWhile(req) + case "SpecialWordsModelsClient.WithWith": + res.resp, res.err = s.dispatchWithWith(req) + case "SpecialWordsModelsClient.WithYield": + res.resp, res.err = s.dispatchWithYield(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithAnd(req *http.Request) (*http.Response, error) { + if s.srv.WithAnd == nil { + return nil, &nonRetriableError{errors.New("fake for method WithAnd not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.And](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithAnd(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithAs(req *http.Request) (*http.Response, error) { + if s.srv.WithAs == nil { + return nil, &nonRetriableError{errors.New("fake for method WithAs not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.As](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithAs(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithAssert(req *http.Request) (*http.Response, error) { + if s.srv.WithAssert == nil { + return nil, &nonRetriableError{errors.New("fake for method WithAssert not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.Assert](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithAssert(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithAsync(req *http.Request) (*http.Response, error) { + if s.srv.WithAsync == nil { + return nil, &nonRetriableError{errors.New("fake for method WithAsync not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.Async](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithAsync(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithAwait(req *http.Request) (*http.Response, error) { + if s.srv.WithAwait == nil { + return nil, &nonRetriableError{errors.New("fake for method WithAwait not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.Await](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithAwait(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithBreak(req *http.Request) (*http.Response, error) { + if s.srv.WithBreak == nil { + return nil, &nonRetriableError{errors.New("fake for method WithBreak not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.Break](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithBreak(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithClass(req *http.Request) (*http.Response, error) { + if s.srv.WithClass == nil { + return nil, &nonRetriableError{errors.New("fake for method WithClass not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.Class](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithClass(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithConstructor(req *http.Request) (*http.Response, error) { + if s.srv.WithConstructor == nil { + return nil, &nonRetriableError{errors.New("fake for method WithConstructor not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.Constructor](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithConstructor(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithContinue(req *http.Request) (*http.Response, error) { + if s.srv.WithContinue == nil { + return nil, &nonRetriableError{errors.New("fake for method WithContinue not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.Continue](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithContinue(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithDef(req *http.Request) (*http.Response, error) { + if s.srv.WithDef == nil { + return nil, &nonRetriableError{errors.New("fake for method WithDef not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.Def](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithDef(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithDel(req *http.Request) (*http.Response, error) { + if s.srv.WithDel == nil { + return nil, &nonRetriableError{errors.New("fake for method WithDel not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.Del](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithDel(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithElif(req *http.Request) (*http.Response, error) { + if s.srv.WithElif == nil { + return nil, &nonRetriableError{errors.New("fake for method WithElif not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.Elif](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithElif(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithElse(req *http.Request) (*http.Response, error) { + if s.srv.WithElse == nil { + return nil, &nonRetriableError{errors.New("fake for method WithElse not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.Else](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithElse(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithExcept(req *http.Request) (*http.Response, error) { + if s.srv.WithExcept == nil { + return nil, &nonRetriableError{errors.New("fake for method WithExcept not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.Except](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithExcept(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithExec(req *http.Request) (*http.Response, error) { + if s.srv.WithExec == nil { + return nil, &nonRetriableError{errors.New("fake for method WithExec not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.Exec](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithExec(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithFinally(req *http.Request) (*http.Response, error) { + if s.srv.WithFinally == nil { + return nil, &nonRetriableError{errors.New("fake for method WithFinally not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.Finally](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithFinally(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithFor(req *http.Request) (*http.Response, error) { + if s.srv.WithFor == nil { + return nil, &nonRetriableError{errors.New("fake for method WithFor not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.For](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithFor(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithFrom(req *http.Request) (*http.Response, error) { + if s.srv.WithFrom == nil { + return nil, &nonRetriableError{errors.New("fake for method WithFrom not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.From](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithFrom(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithGlobal(req *http.Request) (*http.Response, error) { + if s.srv.WithGlobal == nil { + return nil, &nonRetriableError{errors.New("fake for method WithGlobal not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.Global](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithGlobal(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithIf(req *http.Request) (*http.Response, error) { + if s.srv.WithIf == nil { + return nil, &nonRetriableError{errors.New("fake for method WithIf not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.If](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithIf(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithImport(req *http.Request) (*http.Response, error) { + if s.srv.WithImport == nil { + return nil, &nonRetriableError{errors.New("fake for method WithImport not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.Import](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithImport(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithIn(req *http.Request) (*http.Response, error) { + if s.srv.WithIn == nil { + return nil, &nonRetriableError{errors.New("fake for method WithIn not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.In](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithIn(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithIs(req *http.Request) (*http.Response, error) { + if s.srv.WithIs == nil { + return nil, &nonRetriableError{errors.New("fake for method WithIs not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.Is](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithIs(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithLambda(req *http.Request) (*http.Response, error) { + if s.srv.WithLambda == nil { + return nil, &nonRetriableError{errors.New("fake for method WithLambda not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.Lambda](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithLambda(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithNot(req *http.Request) (*http.Response, error) { + if s.srv.WithNot == nil { + return nil, &nonRetriableError{errors.New("fake for method WithNot not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.Not](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithNot(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithOr(req *http.Request) (*http.Response, error) { + if s.srv.WithOr == nil { + return nil, &nonRetriableError{errors.New("fake for method WithOr not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.Or](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithOr(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithPass(req *http.Request) (*http.Response, error) { + if s.srv.WithPass == nil { + return nil, &nonRetriableError{errors.New("fake for method WithPass not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.Pass](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithPass(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithRaise(req *http.Request) (*http.Response, error) { + if s.srv.WithRaise == nil { + return nil, &nonRetriableError{errors.New("fake for method WithRaise not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.Raise](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithRaise(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithReturn(req *http.Request) (*http.Response, error) { + if s.srv.WithReturn == nil { + return nil, &nonRetriableError{errors.New("fake for method WithReturn not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.Return](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithReturn(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithTry(req *http.Request) (*http.Response, error) { + if s.srv.WithTry == nil { + return nil, &nonRetriableError{errors.New("fake for method WithTry not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.Try](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithTry(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithWhile(req *http.Request) (*http.Response, error) { + if s.srv.WithWhile == nil { + return nil, &nonRetriableError{errors.New("fake for method WithWhile not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.While](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithWhile(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithWith(req *http.Request) (*http.Response, error) { + if s.srv.WithWith == nil { + return nil, &nonRetriableError{errors.New("fake for method WithWith not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.With](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithWith(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsModelsServerTransport) dispatchWithYield(req *http.Request) (*http.Response, error) { + if s.srv.WithYield == nil { + return nil, &nonRetriableError{errors.New("fake for method WithYield not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[specialwordsgroup.Yield](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithYield(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SpecialWordsModelsServerTransport +var specialWordsModelsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/specialwordsgroup/fake/zz_specialwordsoperations_server.go b/test/http-specs/specialwordsgroup/fake/zz_specialwordsoperations_server.go new file mode 100644 index 000000000000..eefc215562d5 --- /dev/null +++ b/test/http-specs/specialwordsgroup/fake/zz_specialwordsoperations_server.go @@ -0,0 +1,901 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "specialwordsgroup" +) + +// SpecialWordsOperationsServer is a fake server for instances of the specialwordsgroup.SpecialWordsOperationsClient type. +type SpecialWordsOperationsServer struct { + // And is the fake for method SpecialWordsOperationsClient.And + // HTTP status codes to indicate success: http.StatusNoContent + And func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientAndOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientAndResponse], errResp azfake.ErrorResponder) + + // As is the fake for method SpecialWordsOperationsClient.As + // HTTP status codes to indicate success: http.StatusNoContent + As func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientAsOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientAsResponse], errResp azfake.ErrorResponder) + + // Assert is the fake for method SpecialWordsOperationsClient.Assert + // HTTP status codes to indicate success: http.StatusNoContent + Assert func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientAssertOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientAssertResponse], errResp azfake.ErrorResponder) + + // Async is the fake for method SpecialWordsOperationsClient.Async + // HTTP status codes to indicate success: http.StatusNoContent + Async func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientAsyncOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientAsyncResponse], errResp azfake.ErrorResponder) + + // Await is the fake for method SpecialWordsOperationsClient.Await + // HTTP status codes to indicate success: http.StatusNoContent + Await func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientAwaitOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientAwaitResponse], errResp azfake.ErrorResponder) + + // Break is the fake for method SpecialWordsOperationsClient.Break + // HTTP status codes to indicate success: http.StatusNoContent + Break func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientBreakOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientBreakResponse], errResp azfake.ErrorResponder) + + // Class is the fake for method SpecialWordsOperationsClient.Class + // HTTP status codes to indicate success: http.StatusNoContent + Class func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientClassOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientClassResponse], errResp azfake.ErrorResponder) + + // Constructor is the fake for method SpecialWordsOperationsClient.Constructor + // HTTP status codes to indicate success: http.StatusNoContent + Constructor func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientConstructorOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientConstructorResponse], errResp azfake.ErrorResponder) + + // Continue is the fake for method SpecialWordsOperationsClient.Continue + // HTTP status codes to indicate success: http.StatusNoContent + Continue func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientContinueOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientContinueResponse], errResp azfake.ErrorResponder) + + // Def is the fake for method SpecialWordsOperationsClient.Def + // HTTP status codes to indicate success: http.StatusNoContent + Def func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientDefOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientDefResponse], errResp azfake.ErrorResponder) + + // Del is the fake for method SpecialWordsOperationsClient.Del + // HTTP status codes to indicate success: http.StatusNoContent + Del func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientDelOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientDelResponse], errResp azfake.ErrorResponder) + + // Elif is the fake for method SpecialWordsOperationsClient.Elif + // HTTP status codes to indicate success: http.StatusNoContent + Elif func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientElifOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientElifResponse], errResp azfake.ErrorResponder) + + // Else is the fake for method SpecialWordsOperationsClient.Else + // HTTP status codes to indicate success: http.StatusNoContent + Else func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientElseOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientElseResponse], errResp azfake.ErrorResponder) + + // Except is the fake for method SpecialWordsOperationsClient.Except + // HTTP status codes to indicate success: http.StatusNoContent + Except func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientExceptOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientExceptResponse], errResp azfake.ErrorResponder) + + // Exec is the fake for method SpecialWordsOperationsClient.Exec + // HTTP status codes to indicate success: http.StatusNoContent + Exec func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientExecOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientExecResponse], errResp azfake.ErrorResponder) + + // Finally is the fake for method SpecialWordsOperationsClient.Finally + // HTTP status codes to indicate success: http.StatusNoContent + Finally func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientFinallyOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientFinallyResponse], errResp azfake.ErrorResponder) + + // For is the fake for method SpecialWordsOperationsClient.For + // HTTP status codes to indicate success: http.StatusNoContent + For func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientForOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientForResponse], errResp azfake.ErrorResponder) + + // From is the fake for method SpecialWordsOperationsClient.From + // HTTP status codes to indicate success: http.StatusNoContent + From func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientFromOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientFromResponse], errResp azfake.ErrorResponder) + + // Global is the fake for method SpecialWordsOperationsClient.Global + // HTTP status codes to indicate success: http.StatusNoContent + Global func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientGlobalOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientGlobalResponse], errResp azfake.ErrorResponder) + + // If is the fake for method SpecialWordsOperationsClient.If + // HTTP status codes to indicate success: http.StatusNoContent + If func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientIfOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientIfResponse], errResp azfake.ErrorResponder) + + // Import is the fake for method SpecialWordsOperationsClient.Import + // HTTP status codes to indicate success: http.StatusNoContent + Import func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientImportOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientImportResponse], errResp azfake.ErrorResponder) + + // In is the fake for method SpecialWordsOperationsClient.In + // HTTP status codes to indicate success: http.StatusNoContent + In func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientInOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientInResponse], errResp azfake.ErrorResponder) + + // Is is the fake for method SpecialWordsOperationsClient.Is + // HTTP status codes to indicate success: http.StatusNoContent + Is func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientIsOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientIsResponse], errResp azfake.ErrorResponder) + + // Lambda is the fake for method SpecialWordsOperationsClient.Lambda + // HTTP status codes to indicate success: http.StatusNoContent + Lambda func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientLambdaOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientLambdaResponse], errResp azfake.ErrorResponder) + + // Not is the fake for method SpecialWordsOperationsClient.Not + // HTTP status codes to indicate success: http.StatusNoContent + Not func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientNotOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientNotResponse], errResp azfake.ErrorResponder) + + // Or is the fake for method SpecialWordsOperationsClient.Or + // HTTP status codes to indicate success: http.StatusNoContent + Or func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientOrOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientOrResponse], errResp azfake.ErrorResponder) + + // Pass is the fake for method SpecialWordsOperationsClient.Pass + // HTTP status codes to indicate success: http.StatusNoContent + Pass func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientPassOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientPassResponse], errResp azfake.ErrorResponder) + + // Raise is the fake for method SpecialWordsOperationsClient.Raise + // HTTP status codes to indicate success: http.StatusNoContent + Raise func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientRaiseOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientRaiseResponse], errResp azfake.ErrorResponder) + + // Return is the fake for method SpecialWordsOperationsClient.Return + // HTTP status codes to indicate success: http.StatusNoContent + Return func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientReturnOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientReturnResponse], errResp azfake.ErrorResponder) + + // Try is the fake for method SpecialWordsOperationsClient.Try + // HTTP status codes to indicate success: http.StatusNoContent + Try func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientTryOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientTryResponse], errResp azfake.ErrorResponder) + + // While is the fake for method SpecialWordsOperationsClient.While + // HTTP status codes to indicate success: http.StatusNoContent + While func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientWhileOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientWhileResponse], errResp azfake.ErrorResponder) + + // With is the fake for method SpecialWordsOperationsClient.With + // HTTP status codes to indicate success: http.StatusNoContent + With func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientWithOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientWithResponse], errResp azfake.ErrorResponder) + + // Yield is the fake for method SpecialWordsOperationsClient.Yield + // HTTP status codes to indicate success: http.StatusNoContent + Yield func(ctx context.Context, options *specialwordsgroup.SpecialWordsOperationsClientYieldOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsOperationsClientYieldResponse], errResp azfake.ErrorResponder) +} + +// NewSpecialWordsOperationsServerTransport creates a new instance of SpecialWordsOperationsServerTransport with the provided implementation. +// The returned SpecialWordsOperationsServerTransport instance is connected to an instance of specialwordsgroup.SpecialWordsOperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSpecialWordsOperationsServerTransport(srv *SpecialWordsOperationsServer) *SpecialWordsOperationsServerTransport { + return &SpecialWordsOperationsServerTransport{srv: srv} +} + +// SpecialWordsOperationsServerTransport connects instances of specialwordsgroup.SpecialWordsOperationsClient to instances of SpecialWordsOperationsServer. +// Don't use this type directly, use NewSpecialWordsOperationsServerTransport instead. +type SpecialWordsOperationsServerTransport struct { + srv *SpecialWordsOperationsServer +} + +// Do implements the policy.Transporter interface for SpecialWordsOperationsServerTransport. +func (s *SpecialWordsOperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *SpecialWordsOperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if specialWordsOperationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = specialWordsOperationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SpecialWordsOperationsClient.And": + res.resp, res.err = s.dispatchAnd(req) + case "SpecialWordsOperationsClient.As": + res.resp, res.err = s.dispatchAs(req) + case "SpecialWordsOperationsClient.Assert": + res.resp, res.err = s.dispatchAssert(req) + case "SpecialWordsOperationsClient.Async": + res.resp, res.err = s.dispatchAsync(req) + case "SpecialWordsOperationsClient.Await": + res.resp, res.err = s.dispatchAwait(req) + case "SpecialWordsOperationsClient.Break": + res.resp, res.err = s.dispatchBreak(req) + case "SpecialWordsOperationsClient.Class": + res.resp, res.err = s.dispatchClass(req) + case "SpecialWordsOperationsClient.Constructor": + res.resp, res.err = s.dispatchConstructor(req) + case "SpecialWordsOperationsClient.Continue": + res.resp, res.err = s.dispatchContinue(req) + case "SpecialWordsOperationsClient.Def": + res.resp, res.err = s.dispatchDef(req) + case "SpecialWordsOperationsClient.Del": + res.resp, res.err = s.dispatchDel(req) + case "SpecialWordsOperationsClient.Elif": + res.resp, res.err = s.dispatchElif(req) + case "SpecialWordsOperationsClient.Else": + res.resp, res.err = s.dispatchElse(req) + case "SpecialWordsOperationsClient.Except": + res.resp, res.err = s.dispatchExcept(req) + case "SpecialWordsOperationsClient.Exec": + res.resp, res.err = s.dispatchExec(req) + case "SpecialWordsOperationsClient.Finally": + res.resp, res.err = s.dispatchFinally(req) + case "SpecialWordsOperationsClient.For": + res.resp, res.err = s.dispatchFor(req) + case "SpecialWordsOperationsClient.From": + res.resp, res.err = s.dispatchFrom(req) + case "SpecialWordsOperationsClient.Global": + res.resp, res.err = s.dispatchGlobal(req) + case "SpecialWordsOperationsClient.If": + res.resp, res.err = s.dispatchIf(req) + case "SpecialWordsOperationsClient.Import": + res.resp, res.err = s.dispatchImport(req) + case "SpecialWordsOperationsClient.In": + res.resp, res.err = s.dispatchIn(req) + case "SpecialWordsOperationsClient.Is": + res.resp, res.err = s.dispatchIs(req) + case "SpecialWordsOperationsClient.Lambda": + res.resp, res.err = s.dispatchLambda(req) + case "SpecialWordsOperationsClient.Not": + res.resp, res.err = s.dispatchNot(req) + case "SpecialWordsOperationsClient.Or": + res.resp, res.err = s.dispatchOr(req) + case "SpecialWordsOperationsClient.Pass": + res.resp, res.err = s.dispatchPass(req) + case "SpecialWordsOperationsClient.Raise": + res.resp, res.err = s.dispatchRaise(req) + case "SpecialWordsOperationsClient.Return": + res.resp, res.err = s.dispatchReturn(req) + case "SpecialWordsOperationsClient.Try": + res.resp, res.err = s.dispatchTry(req) + case "SpecialWordsOperationsClient.While": + res.resp, res.err = s.dispatchWhile(req) + case "SpecialWordsOperationsClient.With": + res.resp, res.err = s.dispatchWith(req) + case "SpecialWordsOperationsClient.Yield": + res.resp, res.err = s.dispatchYield(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *SpecialWordsOperationsServerTransport) dispatchAnd(req *http.Request) (*http.Response, error) { + if s.srv.And == nil { + return nil, &nonRetriableError{errors.New("fake for method And not implemented")} + } + respr, errRespr := s.srv.And(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchAs(req *http.Request) (*http.Response, error) { + if s.srv.As == nil { + return nil, &nonRetriableError{errors.New("fake for method As not implemented")} + } + respr, errRespr := s.srv.As(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchAssert(req *http.Request) (*http.Response, error) { + if s.srv.Assert == nil { + return nil, &nonRetriableError{errors.New("fake for method Assert not implemented")} + } + respr, errRespr := s.srv.Assert(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchAsync(req *http.Request) (*http.Response, error) { + if s.srv.Async == nil { + return nil, &nonRetriableError{errors.New("fake for method Async not implemented")} + } + respr, errRespr := s.srv.Async(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchAwait(req *http.Request) (*http.Response, error) { + if s.srv.Await == nil { + return nil, &nonRetriableError{errors.New("fake for method Await not implemented")} + } + respr, errRespr := s.srv.Await(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchBreak(req *http.Request) (*http.Response, error) { + if s.srv.Break == nil { + return nil, &nonRetriableError{errors.New("fake for method Break not implemented")} + } + respr, errRespr := s.srv.Break(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchClass(req *http.Request) (*http.Response, error) { + if s.srv.Class == nil { + return nil, &nonRetriableError{errors.New("fake for method Class not implemented")} + } + respr, errRespr := s.srv.Class(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchConstructor(req *http.Request) (*http.Response, error) { + if s.srv.Constructor == nil { + return nil, &nonRetriableError{errors.New("fake for method Constructor not implemented")} + } + respr, errRespr := s.srv.Constructor(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchContinue(req *http.Request) (*http.Response, error) { + if s.srv.Continue == nil { + return nil, &nonRetriableError{errors.New("fake for method Continue not implemented")} + } + respr, errRespr := s.srv.Continue(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchDef(req *http.Request) (*http.Response, error) { + if s.srv.Def == nil { + return nil, &nonRetriableError{errors.New("fake for method Def not implemented")} + } + respr, errRespr := s.srv.Def(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchDel(req *http.Request) (*http.Response, error) { + if s.srv.Del == nil { + return nil, &nonRetriableError{errors.New("fake for method Del not implemented")} + } + respr, errRespr := s.srv.Del(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchElif(req *http.Request) (*http.Response, error) { + if s.srv.Elif == nil { + return nil, &nonRetriableError{errors.New("fake for method Elif not implemented")} + } + respr, errRespr := s.srv.Elif(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchElse(req *http.Request) (*http.Response, error) { + if s.srv.Else == nil { + return nil, &nonRetriableError{errors.New("fake for method Else not implemented")} + } + respr, errRespr := s.srv.Else(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchExcept(req *http.Request) (*http.Response, error) { + if s.srv.Except == nil { + return nil, &nonRetriableError{errors.New("fake for method Except not implemented")} + } + respr, errRespr := s.srv.Except(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchExec(req *http.Request) (*http.Response, error) { + if s.srv.Exec == nil { + return nil, &nonRetriableError{errors.New("fake for method Exec not implemented")} + } + respr, errRespr := s.srv.Exec(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchFinally(req *http.Request) (*http.Response, error) { + if s.srv.Finally == nil { + return nil, &nonRetriableError{errors.New("fake for method Finally not implemented")} + } + respr, errRespr := s.srv.Finally(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchFor(req *http.Request) (*http.Response, error) { + if s.srv.For == nil { + return nil, &nonRetriableError{errors.New("fake for method For not implemented")} + } + respr, errRespr := s.srv.For(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchFrom(req *http.Request) (*http.Response, error) { + if s.srv.From == nil { + return nil, &nonRetriableError{errors.New("fake for method From not implemented")} + } + respr, errRespr := s.srv.From(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchGlobal(req *http.Request) (*http.Response, error) { + if s.srv.Global == nil { + return nil, &nonRetriableError{errors.New("fake for method Global not implemented")} + } + respr, errRespr := s.srv.Global(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchIf(req *http.Request) (*http.Response, error) { + if s.srv.If == nil { + return nil, &nonRetriableError{errors.New("fake for method If not implemented")} + } + respr, errRespr := s.srv.If(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchImport(req *http.Request) (*http.Response, error) { + if s.srv.Import == nil { + return nil, &nonRetriableError{errors.New("fake for method Import not implemented")} + } + respr, errRespr := s.srv.Import(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchIn(req *http.Request) (*http.Response, error) { + if s.srv.In == nil { + return nil, &nonRetriableError{errors.New("fake for method In not implemented")} + } + respr, errRespr := s.srv.In(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchIs(req *http.Request) (*http.Response, error) { + if s.srv.Is == nil { + return nil, &nonRetriableError{errors.New("fake for method Is not implemented")} + } + respr, errRespr := s.srv.Is(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchLambda(req *http.Request) (*http.Response, error) { + if s.srv.Lambda == nil { + return nil, &nonRetriableError{errors.New("fake for method Lambda not implemented")} + } + respr, errRespr := s.srv.Lambda(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchNot(req *http.Request) (*http.Response, error) { + if s.srv.Not == nil { + return nil, &nonRetriableError{errors.New("fake for method Not not implemented")} + } + respr, errRespr := s.srv.Not(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchOr(req *http.Request) (*http.Response, error) { + if s.srv.Or == nil { + return nil, &nonRetriableError{errors.New("fake for method Or not implemented")} + } + respr, errRespr := s.srv.Or(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchPass(req *http.Request) (*http.Response, error) { + if s.srv.Pass == nil { + return nil, &nonRetriableError{errors.New("fake for method Pass not implemented")} + } + respr, errRespr := s.srv.Pass(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchRaise(req *http.Request) (*http.Response, error) { + if s.srv.Raise == nil { + return nil, &nonRetriableError{errors.New("fake for method Raise not implemented")} + } + respr, errRespr := s.srv.Raise(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchReturn(req *http.Request) (*http.Response, error) { + if s.srv.Return == nil { + return nil, &nonRetriableError{errors.New("fake for method Return not implemented")} + } + respr, errRespr := s.srv.Return(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchTry(req *http.Request) (*http.Response, error) { + if s.srv.Try == nil { + return nil, &nonRetriableError{errors.New("fake for method Try not implemented")} + } + respr, errRespr := s.srv.Try(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchWhile(req *http.Request) (*http.Response, error) { + if s.srv.While == nil { + return nil, &nonRetriableError{errors.New("fake for method While not implemented")} + } + respr, errRespr := s.srv.While(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchWith(req *http.Request) (*http.Response, error) { + if s.srv.With == nil { + return nil, &nonRetriableError{errors.New("fake for method With not implemented")} + } + respr, errRespr := s.srv.With(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsOperationsServerTransport) dispatchYield(req *http.Request) (*http.Response, error) { + if s.srv.Yield == nil { + return nil, &nonRetriableError{errors.New("fake for method Yield not implemented")} + } + respr, errRespr := s.srv.Yield(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SpecialWordsOperationsServerTransport +var specialWordsOperationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/specialwordsgroup/fake/zz_specialwordsparameters_server.go b/test/http-specs/specialwordsgroup/fake/zz_specialwordsparameters_server.go new file mode 100644 index 000000000000..fa3a19445a6b --- /dev/null +++ b/test/http-specs/specialwordsgroup/fake/zz_specialwordsparameters_server.go @@ -0,0 +1,960 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "specialwordsgroup" +) + +// SpecialWordsParametersServer is a fake server for instances of the specialwordsgroup.SpecialWordsParametersClient type. +type SpecialWordsParametersServer struct { + // WithAnd is the fake for method SpecialWordsParametersClient.WithAnd + // HTTP status codes to indicate success: http.StatusNoContent + WithAnd func(ctx context.Context, and string, options *specialwordsgroup.SpecialWordsParametersClientWithAndOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithAndResponse], errResp azfake.ErrorResponder) + + // WithAs is the fake for method SpecialWordsParametersClient.WithAs + // HTTP status codes to indicate success: http.StatusNoContent + WithAs func(ctx context.Context, as string, options *specialwordsgroup.SpecialWordsParametersClientWithAsOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithAsResponse], errResp azfake.ErrorResponder) + + // WithAssert is the fake for method SpecialWordsParametersClient.WithAssert + // HTTP status codes to indicate success: http.StatusNoContent + WithAssert func(ctx context.Context, assert string, options *specialwordsgroup.SpecialWordsParametersClientWithAssertOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithAssertResponse], errResp azfake.ErrorResponder) + + // WithAsync is the fake for method SpecialWordsParametersClient.WithAsync + // HTTP status codes to indicate success: http.StatusNoContent + WithAsync func(ctx context.Context, async string, options *specialwordsgroup.SpecialWordsParametersClientWithAsyncOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithAsyncResponse], errResp azfake.ErrorResponder) + + // WithAwait is the fake for method SpecialWordsParametersClient.WithAwait + // HTTP status codes to indicate success: http.StatusNoContent + WithAwait func(ctx context.Context, await string, options *specialwordsgroup.SpecialWordsParametersClientWithAwaitOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithAwaitResponse], errResp azfake.ErrorResponder) + + // WithBreak is the fake for method SpecialWordsParametersClient.WithBreak + // HTTP status codes to indicate success: http.StatusNoContent + WithBreak func(ctx context.Context, breakParam string, options *specialwordsgroup.SpecialWordsParametersClientWithBreakOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithBreakResponse], errResp azfake.ErrorResponder) + + // WithCancellationToken is the fake for method SpecialWordsParametersClient.WithCancellationToken + // HTTP status codes to indicate success: http.StatusNoContent + WithCancellationToken func(ctx context.Context, cancellationToken string, options *specialwordsgroup.SpecialWordsParametersClientWithCancellationTokenOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithCancellationTokenResponse], errResp azfake.ErrorResponder) + + // WithClass is the fake for method SpecialWordsParametersClient.WithClass + // HTTP status codes to indicate success: http.StatusNoContent + WithClass func(ctx context.Context, class string, options *specialwordsgroup.SpecialWordsParametersClientWithClassOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithClassResponse], errResp azfake.ErrorResponder) + + // WithConstructor is the fake for method SpecialWordsParametersClient.WithConstructor + // HTTP status codes to indicate success: http.StatusNoContent + WithConstructor func(ctx context.Context, constructor string, options *specialwordsgroup.SpecialWordsParametersClientWithConstructorOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithConstructorResponse], errResp azfake.ErrorResponder) + + // WithContinue is the fake for method SpecialWordsParametersClient.WithContinue + // HTTP status codes to indicate success: http.StatusNoContent + WithContinue func(ctx context.Context, continueParam string, options *specialwordsgroup.SpecialWordsParametersClientWithContinueOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithContinueResponse], errResp azfake.ErrorResponder) + + // WithDef is the fake for method SpecialWordsParametersClient.WithDef + // HTTP status codes to indicate success: http.StatusNoContent + WithDef func(ctx context.Context, def string, options *specialwordsgroup.SpecialWordsParametersClientWithDefOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithDefResponse], errResp azfake.ErrorResponder) + + // WithDel is the fake for method SpecialWordsParametersClient.WithDel + // HTTP status codes to indicate success: http.StatusNoContent + WithDel func(ctx context.Context, del string, options *specialwordsgroup.SpecialWordsParametersClientWithDelOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithDelResponse], errResp azfake.ErrorResponder) + + // WithElif is the fake for method SpecialWordsParametersClient.WithElif + // HTTP status codes to indicate success: http.StatusNoContent + WithElif func(ctx context.Context, elif string, options *specialwordsgroup.SpecialWordsParametersClientWithElifOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithElifResponse], errResp azfake.ErrorResponder) + + // WithElse is the fake for method SpecialWordsParametersClient.WithElse + // HTTP status codes to indicate success: http.StatusNoContent + WithElse func(ctx context.Context, elseParam string, options *specialwordsgroup.SpecialWordsParametersClientWithElseOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithElseResponse], errResp azfake.ErrorResponder) + + // WithExcept is the fake for method SpecialWordsParametersClient.WithExcept + // HTTP status codes to indicate success: http.StatusNoContent + WithExcept func(ctx context.Context, except string, options *specialwordsgroup.SpecialWordsParametersClientWithExceptOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithExceptResponse], errResp azfake.ErrorResponder) + + // WithExec is the fake for method SpecialWordsParametersClient.WithExec + // HTTP status codes to indicate success: http.StatusNoContent + WithExec func(ctx context.Context, execParam string, options *specialwordsgroup.SpecialWordsParametersClientWithExecOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithExecResponse], errResp azfake.ErrorResponder) + + // WithFinally is the fake for method SpecialWordsParametersClient.WithFinally + // HTTP status codes to indicate success: http.StatusNoContent + WithFinally func(ctx context.Context, finally string, options *specialwordsgroup.SpecialWordsParametersClientWithFinallyOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithFinallyResponse], errResp azfake.ErrorResponder) + + // WithFor is the fake for method SpecialWordsParametersClient.WithFor + // HTTP status codes to indicate success: http.StatusNoContent + WithFor func(ctx context.Context, forParam string, options *specialwordsgroup.SpecialWordsParametersClientWithForOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithForResponse], errResp azfake.ErrorResponder) + + // WithFrom is the fake for method SpecialWordsParametersClient.WithFrom + // HTTP status codes to indicate success: http.StatusNoContent + WithFrom func(ctx context.Context, from string, options *specialwordsgroup.SpecialWordsParametersClientWithFromOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithFromResponse], errResp azfake.ErrorResponder) + + // WithGlobal is the fake for method SpecialWordsParametersClient.WithGlobal + // HTTP status codes to indicate success: http.StatusNoContent + WithGlobal func(ctx context.Context, global string, options *specialwordsgroup.SpecialWordsParametersClientWithGlobalOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithGlobalResponse], errResp azfake.ErrorResponder) + + // WithIf is the fake for method SpecialWordsParametersClient.WithIf + // HTTP status codes to indicate success: http.StatusNoContent + WithIf func(ctx context.Context, ifParam string, options *specialwordsgroup.SpecialWordsParametersClientWithIfOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithIfResponse], errResp azfake.ErrorResponder) + + // WithImport is the fake for method SpecialWordsParametersClient.WithImport + // HTTP status codes to indicate success: http.StatusNoContent + WithImport func(ctx context.Context, importParam string, options *specialwordsgroup.SpecialWordsParametersClientWithImportOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithImportResponse], errResp azfake.ErrorResponder) + + // WithIn is the fake for method SpecialWordsParametersClient.WithIn + // HTTP status codes to indicate success: http.StatusNoContent + WithIn func(ctx context.Context, in string, options *specialwordsgroup.SpecialWordsParametersClientWithInOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithInResponse], errResp azfake.ErrorResponder) + + // WithIs is the fake for method SpecialWordsParametersClient.WithIs + // HTTP status codes to indicate success: http.StatusNoContent + WithIs func(ctx context.Context, is string, options *specialwordsgroup.SpecialWordsParametersClientWithIsOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithIsResponse], errResp azfake.ErrorResponder) + + // WithLambda is the fake for method SpecialWordsParametersClient.WithLambda + // HTTP status codes to indicate success: http.StatusNoContent + WithLambda func(ctx context.Context, lambda string, options *specialwordsgroup.SpecialWordsParametersClientWithLambdaOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithLambdaResponse], errResp azfake.ErrorResponder) + + // WithNot is the fake for method SpecialWordsParametersClient.WithNot + // HTTP status codes to indicate success: http.StatusNoContent + WithNot func(ctx context.Context, not string, options *specialwordsgroup.SpecialWordsParametersClientWithNotOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithNotResponse], errResp azfake.ErrorResponder) + + // WithOr is the fake for method SpecialWordsParametersClient.WithOr + // HTTP status codes to indicate success: http.StatusNoContent + WithOr func(ctx context.Context, or string, options *specialwordsgroup.SpecialWordsParametersClientWithOrOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithOrResponse], errResp azfake.ErrorResponder) + + // WithPass is the fake for method SpecialWordsParametersClient.WithPass + // HTTP status codes to indicate success: http.StatusNoContent + WithPass func(ctx context.Context, pass string, options *specialwordsgroup.SpecialWordsParametersClientWithPassOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithPassResponse], errResp azfake.ErrorResponder) + + // WithRaise is the fake for method SpecialWordsParametersClient.WithRaise + // HTTP status codes to indicate success: http.StatusNoContent + WithRaise func(ctx context.Context, raise string, options *specialwordsgroup.SpecialWordsParametersClientWithRaiseOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithRaiseResponse], errResp azfake.ErrorResponder) + + // WithReturn is the fake for method SpecialWordsParametersClient.WithReturn + // HTTP status codes to indicate success: http.StatusNoContent + WithReturn func(ctx context.Context, returnParam string, options *specialwordsgroup.SpecialWordsParametersClientWithReturnOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithReturnResponse], errResp azfake.ErrorResponder) + + // WithTry is the fake for method SpecialWordsParametersClient.WithTry + // HTTP status codes to indicate success: http.StatusNoContent + WithTry func(ctx context.Context, try string, options *specialwordsgroup.SpecialWordsParametersClientWithTryOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithTryResponse], errResp azfake.ErrorResponder) + + // WithWhile is the fake for method SpecialWordsParametersClient.WithWhile + // HTTP status codes to indicate success: http.StatusNoContent + WithWhile func(ctx context.Context, while string, options *specialwordsgroup.SpecialWordsParametersClientWithWhileOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithWhileResponse], errResp azfake.ErrorResponder) + + // WithWith is the fake for method SpecialWordsParametersClient.WithWith + // HTTP status codes to indicate success: http.StatusNoContent + WithWith func(ctx context.Context, with string, options *specialwordsgroup.SpecialWordsParametersClientWithWithOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithWithResponse], errResp azfake.ErrorResponder) + + // WithYield is the fake for method SpecialWordsParametersClient.WithYield + // HTTP status codes to indicate success: http.StatusNoContent + WithYield func(ctx context.Context, yield string, options *specialwordsgroup.SpecialWordsParametersClientWithYieldOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsParametersClientWithYieldResponse], errResp azfake.ErrorResponder) +} + +// NewSpecialWordsParametersServerTransport creates a new instance of SpecialWordsParametersServerTransport with the provided implementation. +// The returned SpecialWordsParametersServerTransport instance is connected to an instance of specialwordsgroup.SpecialWordsParametersClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSpecialWordsParametersServerTransport(srv *SpecialWordsParametersServer) *SpecialWordsParametersServerTransport { + return &SpecialWordsParametersServerTransport{srv: srv} +} + +// SpecialWordsParametersServerTransport connects instances of specialwordsgroup.SpecialWordsParametersClient to instances of SpecialWordsParametersServer. +// Don't use this type directly, use NewSpecialWordsParametersServerTransport instead. +type SpecialWordsParametersServerTransport struct { + srv *SpecialWordsParametersServer +} + +// Do implements the policy.Transporter interface for SpecialWordsParametersServerTransport. +func (s *SpecialWordsParametersServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *SpecialWordsParametersServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if specialWordsParametersServerTransportInterceptor != nil { + res.resp, res.err, intercepted = specialWordsParametersServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SpecialWordsParametersClient.WithAnd": + res.resp, res.err = s.dispatchWithAnd(req) + case "SpecialWordsParametersClient.WithAs": + res.resp, res.err = s.dispatchWithAs(req) + case "SpecialWordsParametersClient.WithAssert": + res.resp, res.err = s.dispatchWithAssert(req) + case "SpecialWordsParametersClient.WithAsync": + res.resp, res.err = s.dispatchWithAsync(req) + case "SpecialWordsParametersClient.WithAwait": + res.resp, res.err = s.dispatchWithAwait(req) + case "SpecialWordsParametersClient.WithBreak": + res.resp, res.err = s.dispatchWithBreak(req) + case "SpecialWordsParametersClient.WithCancellationToken": + res.resp, res.err = s.dispatchWithCancellationToken(req) + case "SpecialWordsParametersClient.WithClass": + res.resp, res.err = s.dispatchWithClass(req) + case "SpecialWordsParametersClient.WithConstructor": + res.resp, res.err = s.dispatchWithConstructor(req) + case "SpecialWordsParametersClient.WithContinue": + res.resp, res.err = s.dispatchWithContinue(req) + case "SpecialWordsParametersClient.WithDef": + res.resp, res.err = s.dispatchWithDef(req) + case "SpecialWordsParametersClient.WithDel": + res.resp, res.err = s.dispatchWithDel(req) + case "SpecialWordsParametersClient.WithElif": + res.resp, res.err = s.dispatchWithElif(req) + case "SpecialWordsParametersClient.WithElse": + res.resp, res.err = s.dispatchWithElse(req) + case "SpecialWordsParametersClient.WithExcept": + res.resp, res.err = s.dispatchWithExcept(req) + case "SpecialWordsParametersClient.WithExec": + res.resp, res.err = s.dispatchWithExec(req) + case "SpecialWordsParametersClient.WithFinally": + res.resp, res.err = s.dispatchWithFinally(req) + case "SpecialWordsParametersClient.WithFor": + res.resp, res.err = s.dispatchWithFor(req) + case "SpecialWordsParametersClient.WithFrom": + res.resp, res.err = s.dispatchWithFrom(req) + case "SpecialWordsParametersClient.WithGlobal": + res.resp, res.err = s.dispatchWithGlobal(req) + case "SpecialWordsParametersClient.WithIf": + res.resp, res.err = s.dispatchWithIf(req) + case "SpecialWordsParametersClient.WithImport": + res.resp, res.err = s.dispatchWithImport(req) + case "SpecialWordsParametersClient.WithIn": + res.resp, res.err = s.dispatchWithIn(req) + case "SpecialWordsParametersClient.WithIs": + res.resp, res.err = s.dispatchWithIs(req) + case "SpecialWordsParametersClient.WithLambda": + res.resp, res.err = s.dispatchWithLambda(req) + case "SpecialWordsParametersClient.WithNot": + res.resp, res.err = s.dispatchWithNot(req) + case "SpecialWordsParametersClient.WithOr": + res.resp, res.err = s.dispatchWithOr(req) + case "SpecialWordsParametersClient.WithPass": + res.resp, res.err = s.dispatchWithPass(req) + case "SpecialWordsParametersClient.WithRaise": + res.resp, res.err = s.dispatchWithRaise(req) + case "SpecialWordsParametersClient.WithReturn": + res.resp, res.err = s.dispatchWithReturn(req) + case "SpecialWordsParametersClient.WithTry": + res.resp, res.err = s.dispatchWithTry(req) + case "SpecialWordsParametersClient.WithWhile": + res.resp, res.err = s.dispatchWithWhile(req) + case "SpecialWordsParametersClient.WithWith": + res.resp, res.err = s.dispatchWithWith(req) + case "SpecialWordsParametersClient.WithYield": + res.resp, res.err = s.dispatchWithYield(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithAnd(req *http.Request) (*http.Response, error) { + if s.srv.WithAnd == nil { + return nil, &nonRetriableError{errors.New("fake for method WithAnd not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithAnd(req.Context(), qp.Get("and"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithAs(req *http.Request) (*http.Response, error) { + if s.srv.WithAs == nil { + return nil, &nonRetriableError{errors.New("fake for method WithAs not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithAs(req.Context(), qp.Get("as"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithAssert(req *http.Request) (*http.Response, error) { + if s.srv.WithAssert == nil { + return nil, &nonRetriableError{errors.New("fake for method WithAssert not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithAssert(req.Context(), qp.Get("assert"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithAsync(req *http.Request) (*http.Response, error) { + if s.srv.WithAsync == nil { + return nil, &nonRetriableError{errors.New("fake for method WithAsync not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithAsync(req.Context(), qp.Get("async"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithAwait(req *http.Request) (*http.Response, error) { + if s.srv.WithAwait == nil { + return nil, &nonRetriableError{errors.New("fake for method WithAwait not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithAwait(req.Context(), qp.Get("await"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithBreak(req *http.Request) (*http.Response, error) { + if s.srv.WithBreak == nil { + return nil, &nonRetriableError{errors.New("fake for method WithBreak not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithBreak(req.Context(), qp.Get("break"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithCancellationToken(req *http.Request) (*http.Response, error) { + if s.srv.WithCancellationToken == nil { + return nil, &nonRetriableError{errors.New("fake for method WithCancellationToken not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithCancellationToken(req.Context(), qp.Get("cancellationToken"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithClass(req *http.Request) (*http.Response, error) { + if s.srv.WithClass == nil { + return nil, &nonRetriableError{errors.New("fake for method WithClass not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithClass(req.Context(), qp.Get("class"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithConstructor(req *http.Request) (*http.Response, error) { + if s.srv.WithConstructor == nil { + return nil, &nonRetriableError{errors.New("fake for method WithConstructor not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithConstructor(req.Context(), qp.Get("constructor"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithContinue(req *http.Request) (*http.Response, error) { + if s.srv.WithContinue == nil { + return nil, &nonRetriableError{errors.New("fake for method WithContinue not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithContinue(req.Context(), qp.Get("continue"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithDef(req *http.Request) (*http.Response, error) { + if s.srv.WithDef == nil { + return nil, &nonRetriableError{errors.New("fake for method WithDef not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithDef(req.Context(), qp.Get("def"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithDel(req *http.Request) (*http.Response, error) { + if s.srv.WithDel == nil { + return nil, &nonRetriableError{errors.New("fake for method WithDel not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithDel(req.Context(), qp.Get("del"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithElif(req *http.Request) (*http.Response, error) { + if s.srv.WithElif == nil { + return nil, &nonRetriableError{errors.New("fake for method WithElif not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithElif(req.Context(), qp.Get("elif"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithElse(req *http.Request) (*http.Response, error) { + if s.srv.WithElse == nil { + return nil, &nonRetriableError{errors.New("fake for method WithElse not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithElse(req.Context(), qp.Get("else"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithExcept(req *http.Request) (*http.Response, error) { + if s.srv.WithExcept == nil { + return nil, &nonRetriableError{errors.New("fake for method WithExcept not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithExcept(req.Context(), qp.Get("except"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithExec(req *http.Request) (*http.Response, error) { + if s.srv.WithExec == nil { + return nil, &nonRetriableError{errors.New("fake for method WithExec not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithExec(req.Context(), qp.Get("exec"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithFinally(req *http.Request) (*http.Response, error) { + if s.srv.WithFinally == nil { + return nil, &nonRetriableError{errors.New("fake for method WithFinally not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithFinally(req.Context(), qp.Get("finally"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithFor(req *http.Request) (*http.Response, error) { + if s.srv.WithFor == nil { + return nil, &nonRetriableError{errors.New("fake for method WithFor not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithFor(req.Context(), qp.Get("for"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithFrom(req *http.Request) (*http.Response, error) { + if s.srv.WithFrom == nil { + return nil, &nonRetriableError{errors.New("fake for method WithFrom not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithFrom(req.Context(), qp.Get("from"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithGlobal(req *http.Request) (*http.Response, error) { + if s.srv.WithGlobal == nil { + return nil, &nonRetriableError{errors.New("fake for method WithGlobal not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithGlobal(req.Context(), qp.Get("global"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithIf(req *http.Request) (*http.Response, error) { + if s.srv.WithIf == nil { + return nil, &nonRetriableError{errors.New("fake for method WithIf not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithIf(req.Context(), qp.Get("if"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithImport(req *http.Request) (*http.Response, error) { + if s.srv.WithImport == nil { + return nil, &nonRetriableError{errors.New("fake for method WithImport not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithImport(req.Context(), qp.Get("import"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithIn(req *http.Request) (*http.Response, error) { + if s.srv.WithIn == nil { + return nil, &nonRetriableError{errors.New("fake for method WithIn not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithIn(req.Context(), qp.Get("in"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithIs(req *http.Request) (*http.Response, error) { + if s.srv.WithIs == nil { + return nil, &nonRetriableError{errors.New("fake for method WithIs not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithIs(req.Context(), qp.Get("is"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithLambda(req *http.Request) (*http.Response, error) { + if s.srv.WithLambda == nil { + return nil, &nonRetriableError{errors.New("fake for method WithLambda not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithLambda(req.Context(), qp.Get("lambda"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithNot(req *http.Request) (*http.Response, error) { + if s.srv.WithNot == nil { + return nil, &nonRetriableError{errors.New("fake for method WithNot not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithNot(req.Context(), qp.Get("not"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithOr(req *http.Request) (*http.Response, error) { + if s.srv.WithOr == nil { + return nil, &nonRetriableError{errors.New("fake for method WithOr not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithOr(req.Context(), qp.Get("or"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithPass(req *http.Request) (*http.Response, error) { + if s.srv.WithPass == nil { + return nil, &nonRetriableError{errors.New("fake for method WithPass not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithPass(req.Context(), qp.Get("pass"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithRaise(req *http.Request) (*http.Response, error) { + if s.srv.WithRaise == nil { + return nil, &nonRetriableError{errors.New("fake for method WithRaise not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithRaise(req.Context(), qp.Get("raise"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithReturn(req *http.Request) (*http.Response, error) { + if s.srv.WithReturn == nil { + return nil, &nonRetriableError{errors.New("fake for method WithReturn not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithReturn(req.Context(), qp.Get("return"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithTry(req *http.Request) (*http.Response, error) { + if s.srv.WithTry == nil { + return nil, &nonRetriableError{errors.New("fake for method WithTry not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithTry(req.Context(), qp.Get("try"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithWhile(req *http.Request) (*http.Response, error) { + if s.srv.WithWhile == nil { + return nil, &nonRetriableError{errors.New("fake for method WithWhile not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithWhile(req.Context(), qp.Get("while"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithWith(req *http.Request) (*http.Response, error) { + if s.srv.WithWith == nil { + return nil, &nonRetriableError{errors.New("fake for method WithWith not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithWith(req.Context(), qp.Get("with"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SpecialWordsParametersServerTransport) dispatchWithYield(req *http.Request) (*http.Response, error) { + if s.srv.WithYield == nil { + return nil, &nonRetriableError{errors.New("fake for method WithYield not implemented")} + } + qp := req.URL.Query() + respr, errRespr := s.srv.WithYield(req.Context(), qp.Get("yield"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SpecialWordsParametersServerTransport +var specialWordsParametersServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/specialwordsgroup/fake/zz_specialwordsreservedoperationbodyparams_server.go b/test/http-specs/specialwordsgroup/fake/zz_specialwordsreservedoperationbodyparams_server.go new file mode 100644 index 000000000000..e931901419f0 --- /dev/null +++ b/test/http-specs/specialwordsgroup/fake/zz_specialwordsreservedoperationbodyparams_server.go @@ -0,0 +1,108 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "specialwordsgroup" +) + +// SpecialWordsReservedOperationBodyParamsServer is a fake server for instances of the specialwordsgroup.SpecialWordsReservedOperationBodyParamsClient type. +type SpecialWordsReservedOperationBodyParamsServer struct { + // WithItems is the fake for method SpecialWordsReservedOperationBodyParamsClient.WithItems + // HTTP status codes to indicate success: http.StatusNoContent + WithItems func(ctx context.Context, items []string, options *specialwordsgroup.SpecialWordsReservedOperationBodyParamsClientWithItemsOptions) (resp azfake.Responder[specialwordsgroup.SpecialWordsReservedOperationBodyParamsClientWithItemsResponse], errResp azfake.ErrorResponder) +} + +// NewSpecialWordsReservedOperationBodyParamsServerTransport creates a new instance of SpecialWordsReservedOperationBodyParamsServerTransport with the provided implementation. +// The returned SpecialWordsReservedOperationBodyParamsServerTransport instance is connected to an instance of specialwordsgroup.SpecialWordsReservedOperationBodyParamsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSpecialWordsReservedOperationBodyParamsServerTransport(srv *SpecialWordsReservedOperationBodyParamsServer) *SpecialWordsReservedOperationBodyParamsServerTransport { + return &SpecialWordsReservedOperationBodyParamsServerTransport{srv: srv} +} + +// SpecialWordsReservedOperationBodyParamsServerTransport connects instances of specialwordsgroup.SpecialWordsReservedOperationBodyParamsClient to instances of SpecialWordsReservedOperationBodyParamsServer. +// Don't use this type directly, use NewSpecialWordsReservedOperationBodyParamsServerTransport instead. +type SpecialWordsReservedOperationBodyParamsServerTransport struct { + srv *SpecialWordsReservedOperationBodyParamsServer +} + +// Do implements the policy.Transporter interface for SpecialWordsReservedOperationBodyParamsServerTransport. +func (s *SpecialWordsReservedOperationBodyParamsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *SpecialWordsReservedOperationBodyParamsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if specialWordsReservedOperationBodyParamsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = specialWordsReservedOperationBodyParamsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SpecialWordsReservedOperationBodyParamsClient.WithItems": + res.resp, res.err = s.dispatchWithItems(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *SpecialWordsReservedOperationBodyParamsServerTransport) dispatchWithItems(req *http.Request) (*http.Response, error) { + if s.srv.WithItems == nil { + return nil, &nonRetriableError{errors.New("fake for method WithItems not implemented")} + } + type partialBodyParams struct { + Items []string `json:"items"` + } + body, err := server.UnmarshalRequestAsJSON[partialBodyParams](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithItems(req.Context(), body.Items, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SpecialWordsReservedOperationBodyParamsServerTransport +var specialWordsReservedOperationBodyParamsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/specialwordsgroup/go.mod b/test/http-specs/specialwordsgroup/go.mod new file mode 100644 index 000000000000..e119e1facc96 --- /dev/null +++ b/test/http-specs/specialwordsgroup/go.mod @@ -0,0 +1,17 @@ +module specialwordsgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/specialwordsgroup/go.sum b/test/http-specs/specialwordsgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/specialwordsgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/specialwordsgroup/modelproperties_client_test.go b/test/http-specs/specialwordsgroup/modelproperties_client_test.go new file mode 100644 index 000000000000..3c9f44bef4be --- /dev/null +++ b/test/http-specs/specialwordsgroup/modelproperties_client_test.go @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package specialwordsgroup_test + +import ( + "context" + "specialwordsgroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestModelPropertiesClient_SameAsModel(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelPropertiesClient().SameAsModel(context.Background(), specialwordsgroup.SameAsModel{ + SameAsModel: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelPropertiesClient_DictMethods(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelPropertiesClient().DictMethods(context.Background(), specialwordsgroup.DictMethods{ + Clear: to.Ptr("ok"), + Copy: to.Ptr("ok"), + Get: to.Ptr("ok"), + Items: to.Ptr("ok"), + Keys: to.Ptr("ok"), + Pop: to.Ptr("ok"), + Popitem: to.Ptr("ok"), + Setdefault: to.Ptr("ok"), + Update: to.Ptr("ok"), + Values: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelPropertiesClient_WithList(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelPropertiesClient().WithList(context.Background(), specialwordsgroup.ModelWithList{ + List: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/specialwordsgroup/models_client_test.go b/test/http-specs/specialwordsgroup/models_client_test.go new file mode 100644 index 000000000000..9a1fc3256f3f --- /dev/null +++ b/test/http-specs/specialwordsgroup/models_client_test.go @@ -0,0 +1,343 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package specialwordsgroup_test + +import ( + "context" + "specialwordsgroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestModelsClient_WithAnd(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithAnd(context.Background(), specialwordsgroup.And{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithAs(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithAs(context.Background(), specialwordsgroup.As{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithAssert(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithAssert(context.Background(), specialwordsgroup.Assert{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithAsync(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithAsync(context.Background(), specialwordsgroup.Async{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithAwait(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithAwait(context.Background(), specialwordsgroup.Await{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithBreak(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithBreak(context.Background(), specialwordsgroup.Break{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithClass(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithClass(context.Background(), specialwordsgroup.Class{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithConstructor(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithConstructor(context.Background(), specialwordsgroup.Constructor{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithContinue(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithContinue(context.Background(), specialwordsgroup.Continue{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithDef(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithDef(context.Background(), specialwordsgroup.Def{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithDel(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithDel(context.Background(), specialwordsgroup.Del{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithElif(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithElif(context.Background(), specialwordsgroup.Elif{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithElse(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithElse(context.Background(), specialwordsgroup.Else{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithExcept(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithExcept(context.Background(), specialwordsgroup.Except{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithExec(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithExec(context.Background(), specialwordsgroup.Exec{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithFinally(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithFinally(context.Background(), specialwordsgroup.Finally{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithFor(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithFor(context.Background(), specialwordsgroup.For{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithFrom(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithFrom(context.Background(), specialwordsgroup.From{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithGlobal(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithGlobal(context.Background(), specialwordsgroup.Global{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithIf(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithIf(context.Background(), specialwordsgroup.If{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithImport(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithImport(context.Background(), specialwordsgroup.Import{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithIn(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithIn(context.Background(), specialwordsgroup.In{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithIs(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithIs(context.Background(), specialwordsgroup.Is{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithLambda(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithLambda(context.Background(), specialwordsgroup.Lambda{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithNot(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithNot(context.Background(), specialwordsgroup.Not{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithOr(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithOr(context.Background(), specialwordsgroup.Or{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithPass(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithPass(context.Background(), specialwordsgroup.Pass{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithRaise(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithRaise(context.Background(), specialwordsgroup.Raise{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithReturn(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithReturn(context.Background(), specialwordsgroup.Return{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithTry(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithTry(context.Background(), specialwordsgroup.Try{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithWhile(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithWhile(context.Background(), specialwordsgroup.While{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithWith(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithWith(context.Background(), specialwordsgroup.With{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelsClient_WithYield(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsModelsClient().WithYield(context.Background(), specialwordsgroup.Yield{ + Name: to.Ptr("ok"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/specialwordsgroup/operations_client_test.go b/test/http-specs/specialwordsgroup/operations_client_test.go new file mode 100644 index 000000000000..1c02200ceaa8 --- /dev/null +++ b/test/http-specs/specialwordsgroup/operations_client_test.go @@ -0,0 +1,276 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package specialwordsgroup_test + +import ( + "context" + "specialwordsgroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestOperationsClient_And(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().And(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_As(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().As(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_Assert(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().Assert(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_Async(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().Async(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_Await(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().Await(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_Break(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().Break(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_Class(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().Class(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_Constructor(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().Constructor(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_Continue(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().Continue(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_Def(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().Def(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_Del(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().Del(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_Elif(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().Elif(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_Else(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().Else(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_Except(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().Except(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_Exec(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().Exec(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_Finally(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().Finally(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_For(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().For(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_From(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().From(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_Global(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().Global(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_If(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().If(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_Import(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().Import(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_In(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().In(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_Is(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().Is(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_Lambda(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().Lambda(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_Not(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().Not(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_Or(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().Or(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_Pass(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().Pass(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_Raise(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().Raise(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_Return(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().Return(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_Try(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().Try(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_While(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().While(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_With(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().With(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOperationsClient_Yield(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsOperationsClient().Yield(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/specialwordsgroup/parameters_client_test.go b/test/http-specs/specialwordsgroup/parameters_client_test.go new file mode 100644 index 000000000000..072f82a452aa --- /dev/null +++ b/test/http-specs/specialwordsgroup/parameters_client_test.go @@ -0,0 +1,284 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package specialwordsgroup_test + +import ( + "context" + "specialwordsgroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestParametersClient_WithAnd(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithAnd(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithAs(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithAs(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithAssert(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithAssert(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithAsync(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithAsync(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithAwait(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithAwait(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithBreak(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithBreak(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithCancellationToken(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithCancellationToken(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithClass(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithClass(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithConstructor(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithConstructor(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithContinue(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithContinue(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithDef(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithDef(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithDel(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithDel(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithElif(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithElif(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithElse(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithElse(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithExcept(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithExcept(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithExec(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithExec(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithFinally(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithFinally(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithFor(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithFor(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithFrom(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithFrom(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithGlobal(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithGlobal(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithIf(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithIf(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithImport(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithImport(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithIn(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithIn(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithIs(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithIs(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithLambda(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithLambda(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithNot(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithNot(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithOr(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithOr(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithPass(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithPass(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithRaise(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithRaise(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithReturn(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithReturn(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithTry(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithTry(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithWhile(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithWhile(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithWith(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithWith(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestParametersClient_WithYield(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsParametersClient().WithYield(context.Background(), "ok", nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/specialwordsgroup/reservedoperationbodyparams_client_test.go b/test/http-specs/specialwordsgroup/reservedoperationbodyparams_client_test.go new file mode 100644 index 000000000000..e4a22848798c --- /dev/null +++ b/test/http-specs/specialwordsgroup/reservedoperationbodyparams_client_test.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package specialwordsgroup_test + +import ( + "context" + "specialwordsgroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestReservedOperationBodyParamsClient_WithItems(t *testing.T) { + client, err := specialwordsgroup.NewSpecialWordsClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewSpecialWordsReservedOperationBodyParamsClient().WithItems(context.Background(), []string{"item"}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/specialwordsgroup/testdata/_metadata.json b/test/http-specs/specialwordsgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/specialwordsgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/specialwordsgroup/zz_constants.go b/test/http-specs/specialwordsgroup/zz_constants.go new file mode 100644 index 000000000000..a568bcaebd9a --- /dev/null +++ b/test/http-specs/specialwordsgroup/zz_constants.go @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package specialwordsgroup + +// ExtensibleString - Verify enum member names that are special words using extensible enum (union). +type ExtensibleString string + +const ( + ExtensibleStringAnd ExtensibleString = "and" + ExtensibleStringAs ExtensibleString = "as" + ExtensibleStringAssert ExtensibleString = "assert" + ExtensibleStringAsync ExtensibleString = "async" + ExtensibleStringAwait ExtensibleString = "await" + ExtensibleStringBreak ExtensibleString = "break" + ExtensibleStringClass ExtensibleString = "class" + ExtensibleStringConstructor ExtensibleString = "constructor" + ExtensibleStringContinue ExtensibleString = "continue" + ExtensibleStringDef ExtensibleString = "def" + ExtensibleStringDel ExtensibleString = "del" + ExtensibleStringElif ExtensibleString = "elif" + ExtensibleStringElse ExtensibleString = "else" + ExtensibleStringExcept ExtensibleString = "except" + ExtensibleStringExec ExtensibleString = "exec" + ExtensibleStringFinally ExtensibleString = "finally" + ExtensibleStringFor ExtensibleString = "for" + ExtensibleStringFrom ExtensibleString = "from" + ExtensibleStringGlobal ExtensibleString = "global" + ExtensibleStringIf ExtensibleString = "if" + ExtensibleStringImport ExtensibleString = "import" + ExtensibleStringIn ExtensibleString = "in" + ExtensibleStringIs ExtensibleString = "is" + ExtensibleStringLambda ExtensibleString = "lambda" + ExtensibleStringNot ExtensibleString = "not" + ExtensibleStringOr ExtensibleString = "or" + ExtensibleStringPass ExtensibleString = "pass" + ExtensibleStringRaise ExtensibleString = "raise" + ExtensibleStringReturn ExtensibleString = "return" + ExtensibleStringTry ExtensibleString = "try" + ExtensibleStringWhile ExtensibleString = "while" + ExtensibleStringWith ExtensibleString = "with" + ExtensibleStringYield ExtensibleString = "yield" +) + +// PossibleExtensibleStringValues returns the possible values for the ExtensibleString const type. +func PossibleExtensibleStringValues() []ExtensibleString { + return []ExtensibleString{ + ExtensibleStringAnd, + ExtensibleStringAs, + ExtensibleStringAssert, + ExtensibleStringAsync, + ExtensibleStringAwait, + ExtensibleStringBreak, + ExtensibleStringClass, + ExtensibleStringConstructor, + ExtensibleStringContinue, + ExtensibleStringDef, + ExtensibleStringDel, + ExtensibleStringElif, + ExtensibleStringElse, + ExtensibleStringExcept, + ExtensibleStringExec, + ExtensibleStringFinally, + ExtensibleStringFor, + ExtensibleStringFrom, + ExtensibleStringGlobal, + ExtensibleStringIf, + ExtensibleStringImport, + ExtensibleStringIn, + ExtensibleStringIs, + ExtensibleStringLambda, + ExtensibleStringNot, + ExtensibleStringOr, + ExtensibleStringPass, + ExtensibleStringRaise, + ExtensibleStringReturn, + ExtensibleStringTry, + ExtensibleStringWhile, + ExtensibleStringWith, + ExtensibleStringYield, + } +} diff --git a/test/http-specs/specialwordsgroup/zz_models.go b/test/http-specs/specialwordsgroup/zz_models.go new file mode 100644 index 000000000000..f90712695e39 --- /dev/null +++ b/test/http-specs/specialwordsgroup/zz_models.go @@ -0,0 +1,212 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package specialwordsgroup + +type And struct { + // REQUIRED + Name *string +} + +type As struct { + // REQUIRED + Name *string +} + +type Assert struct { + // REQUIRED + Name *string +} + +type Async struct { + // REQUIRED + Name *string +} + +type Await struct { + // REQUIRED + Name *string +} + +type Break struct { + // REQUIRED + Name *string +} + +type Class struct { + // REQUIRED + Name *string +} + +type Constructor struct { + // REQUIRED + Name *string +} + +type Continue struct { + // REQUIRED + Name *string +} + +type Def struct { + // REQUIRED + Name *string +} + +type Del struct { + // REQUIRED + Name *string +} + +type DictMethods struct { + // REQUIRED + Clear *string + + // REQUIRED + Copy *string + + // REQUIRED + Get *string + + // REQUIRED + Items *string + + // REQUIRED + Keys *string + + // REQUIRED + Pop *string + + // REQUIRED + Popitem *string + + // REQUIRED + Setdefault *string + + // REQUIRED + Update *string + + // REQUIRED + Values *string +} + +type Elif struct { + // REQUIRED + Name *string +} + +type Else struct { + // REQUIRED + Name *string +} + +type Except struct { + // REQUIRED + Name *string +} + +type Exec struct { + // REQUIRED + Name *string +} + +type Finally struct { + // REQUIRED + Name *string +} + +type For struct { + // REQUIRED + Name *string +} + +type From struct { + // REQUIRED + Name *string +} + +type Global struct { + // REQUIRED + Name *string +} + +type If struct { + // REQUIRED + Name *string +} + +type Import struct { + // REQUIRED + Name *string +} + +type In struct { + // REQUIRED + Name *string +} + +type Is struct { + // REQUIRED + Name *string +} + +type Lambda struct { + // REQUIRED + Name *string +} + +type ModelWithList struct { + // REQUIRED + List *string +} + +type Not struct { + // REQUIRED + Name *string +} + +type Or struct { + // REQUIRED + Name *string +} + +type Pass struct { + // REQUIRED + Name *string +} + +type Raise struct { + // REQUIRED + Name *string +} + +type Return struct { + // REQUIRED + Name *string +} + +type SameAsModel struct { + // REQUIRED + SameAsModel *string +} + +type Try struct { + // REQUIRED + Name *string +} + +type While struct { + // REQUIRED + Name *string +} + +type With struct { + // REQUIRED + Name *string +} + +type Yield struct { + // REQUIRED + Name *string +} diff --git a/test/http-specs/specialwordsgroup/zz_models_serde.go b/test/http-specs/specialwordsgroup/zz_models_serde.go new file mode 100644 index 000000000000..63791292aab2 --- /dev/null +++ b/test/http-specs/specialwordsgroup/zz_models_serde.go @@ -0,0 +1,1040 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package specialwordsgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type And. +func (a And) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", a.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type And. +func (a *And) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type As. +func (a As) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", a.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type As. +func (a *As) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Assert. +func (a Assert) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", a.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Assert. +func (a *Assert) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Async. +func (a Async) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", a.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Async. +func (a *Async) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Await. +func (a Await) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", a.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Await. +func (a *Await) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Break. +func (b Break) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", b.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Break. +func (b *Break) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &b.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Class. +func (c Class) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", c.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Class. +func (c *Class) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Constructor. +func (c Constructor) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", c.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Constructor. +func (c *Constructor) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Continue. +func (c Continue) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", c.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Continue. +func (c *Continue) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Def. +func (d Def) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", d.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Def. +func (d *Def) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Del. +func (d Del) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", d.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Del. +func (d *Del) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DictMethods. +func (d DictMethods) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clear", d.Clear) + populate(objectMap, "copy", d.Copy) + populate(objectMap, "get", d.Get) + populate(objectMap, "items", d.Items) + populate(objectMap, "keys", d.Keys) + populate(objectMap, "pop", d.Pop) + populate(objectMap, "popitem", d.Popitem) + populate(objectMap, "setdefault", d.Setdefault) + populate(objectMap, "update", d.Update) + populate(objectMap, "values", d.Values) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DictMethods. +func (d *DictMethods) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "clear": + err = unpopulate(val, "Clear", &d.Clear) + delete(rawMsg, key) + case "copy": + err = unpopulate(val, "Copy", &d.Copy) + delete(rawMsg, key) + case "get": + err = unpopulate(val, "Get", &d.Get) + delete(rawMsg, key) + case "items": + err = unpopulate(val, "Items", &d.Items) + delete(rawMsg, key) + case "keys": + err = unpopulate(val, "Keys", &d.Keys) + delete(rawMsg, key) + case "pop": + err = unpopulate(val, "Pop", &d.Pop) + delete(rawMsg, key) + case "popitem": + err = unpopulate(val, "Popitem", &d.Popitem) + delete(rawMsg, key) + case "setdefault": + err = unpopulate(val, "Setdefault", &d.Setdefault) + delete(rawMsg, key) + case "update": + err = unpopulate(val, "Update", &d.Update) + delete(rawMsg, key) + case "values": + err = unpopulate(val, "Values", &d.Values) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Elif. +func (e Elif) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", e.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Elif. +func (e *Elif) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &e.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Else. +func (e Else) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", e.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Else. +func (e *Else) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &e.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Except. +func (e Except) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", e.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Except. +func (e *Except) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &e.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Exec. +func (e Exec) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", e.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Exec. +func (e *Exec) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &e.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Finally. +func (f Finally) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", f.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Finally. +func (f *Finally) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &f.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type For. +func (f For) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", f.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type For. +func (f *For) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &f.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type From. +func (f From) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", f.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type From. +func (f *From) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &f.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Global. +func (g Global) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", g.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Global. +func (g *Global) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &g.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type If. +func (i If) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", i.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type If. +func (i *If) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &i.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Import. +func (i Import) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", i.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Import. +func (i *Import) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &i.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type In. +func (i In) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", i.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type In. +func (i *In) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &i.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Is. +func (i Is) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", i.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Is. +func (i *Is) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &i.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Lambda. +func (l Lambda) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", l.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Lambda. +func (l *Lambda) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &l.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ModelWithList. +func (m ModelWithList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "list", m.List) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ModelWithList. +func (m *ModelWithList) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "list": + err = unpopulate(val, "List", &m.List) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Not. +func (n Not) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", n.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Not. +func (n *Not) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &n.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Or. +func (o Or) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", o.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Or. +func (o *Or) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Pass. +func (p Pass) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", p.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Pass. +func (p *Pass) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Raise. +func (r Raise) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", r.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Raise. +func (r *Raise) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Return. +func (r Return) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", r.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Return. +func (r *Return) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SameAsModel. +func (s SameAsModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "SameAsModel", s.SameAsModel) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SameAsModel. +func (s *SameAsModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "SameAsModel": + err = unpopulate(val, "SameAsModel", &s.SameAsModel) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Try. +func (t Try) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", t.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Try. +func (t *Try) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &t.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type While. +func (w While) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", w.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type While. +func (w *While) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &w.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type With. +func (w With) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", w.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type With. +func (w *With) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &w.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Yield. +func (y Yield) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", y.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Yield. +func (y *Yield) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", y, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &y.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", y, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/http-specs/specialwordsgroup/zz_options.go b/test/http-specs/specialwordsgroup/zz_options.go new file mode 100644 index 000000000000..e8123aba2eb7 --- /dev/null +++ b/test/http-specs/specialwordsgroup/zz_options.go @@ -0,0 +1,587 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package specialwordsgroup + +// SpecialWordsExtensibleStringsClientPutExtensibleStringValueOptions contains the optional parameters for the SpecialWordsExtensibleStringsClient.PutExtensibleStringValue +// method. +type SpecialWordsExtensibleStringsClientPutExtensibleStringValueOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelPropertiesClientDictMethodsOptions contains the optional parameters for the SpecialWordsModelPropertiesClient.DictMethods +// method. +type SpecialWordsModelPropertiesClientDictMethodsOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelPropertiesClientSameAsModelOptions contains the optional parameters for the SpecialWordsModelPropertiesClient.SameAsModel +// method. +type SpecialWordsModelPropertiesClientSameAsModelOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelPropertiesClientWithListOptions contains the optional parameters for the SpecialWordsModelPropertiesClient.WithList +// method. +type SpecialWordsModelPropertiesClientWithListOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithAndOptions contains the optional parameters for the SpecialWordsModelsClient.WithAnd method. +type SpecialWordsModelsClientWithAndOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithAsOptions contains the optional parameters for the SpecialWordsModelsClient.WithAs method. +type SpecialWordsModelsClientWithAsOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithAssertOptions contains the optional parameters for the SpecialWordsModelsClient.WithAssert +// method. +type SpecialWordsModelsClientWithAssertOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithAsyncOptions contains the optional parameters for the SpecialWordsModelsClient.WithAsync method. +type SpecialWordsModelsClientWithAsyncOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithAwaitOptions contains the optional parameters for the SpecialWordsModelsClient.WithAwait method. +type SpecialWordsModelsClientWithAwaitOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithBreakOptions contains the optional parameters for the SpecialWordsModelsClient.WithBreak method. +type SpecialWordsModelsClientWithBreakOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithClassOptions contains the optional parameters for the SpecialWordsModelsClient.WithClass method. +type SpecialWordsModelsClientWithClassOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithConstructorOptions contains the optional parameters for the SpecialWordsModelsClient.WithConstructor +// method. +type SpecialWordsModelsClientWithConstructorOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithContinueOptions contains the optional parameters for the SpecialWordsModelsClient.WithContinue +// method. +type SpecialWordsModelsClientWithContinueOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithDefOptions contains the optional parameters for the SpecialWordsModelsClient.WithDef method. +type SpecialWordsModelsClientWithDefOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithDelOptions contains the optional parameters for the SpecialWordsModelsClient.WithDel method. +type SpecialWordsModelsClientWithDelOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithElifOptions contains the optional parameters for the SpecialWordsModelsClient.WithElif method. +type SpecialWordsModelsClientWithElifOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithElseOptions contains the optional parameters for the SpecialWordsModelsClient.WithElse method. +type SpecialWordsModelsClientWithElseOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithExceptOptions contains the optional parameters for the SpecialWordsModelsClient.WithExcept +// method. +type SpecialWordsModelsClientWithExceptOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithExecOptions contains the optional parameters for the SpecialWordsModelsClient.WithExec method. +type SpecialWordsModelsClientWithExecOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithFinallyOptions contains the optional parameters for the SpecialWordsModelsClient.WithFinally +// method. +type SpecialWordsModelsClientWithFinallyOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithForOptions contains the optional parameters for the SpecialWordsModelsClient.WithFor method. +type SpecialWordsModelsClientWithForOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithFromOptions contains the optional parameters for the SpecialWordsModelsClient.WithFrom method. +type SpecialWordsModelsClientWithFromOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithGlobalOptions contains the optional parameters for the SpecialWordsModelsClient.WithGlobal +// method. +type SpecialWordsModelsClientWithGlobalOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithIfOptions contains the optional parameters for the SpecialWordsModelsClient.WithIf method. +type SpecialWordsModelsClientWithIfOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithImportOptions contains the optional parameters for the SpecialWordsModelsClient.WithImport +// method. +type SpecialWordsModelsClientWithImportOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithInOptions contains the optional parameters for the SpecialWordsModelsClient.WithIn method. +type SpecialWordsModelsClientWithInOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithIsOptions contains the optional parameters for the SpecialWordsModelsClient.WithIs method. +type SpecialWordsModelsClientWithIsOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithLambdaOptions contains the optional parameters for the SpecialWordsModelsClient.WithLambda +// method. +type SpecialWordsModelsClientWithLambdaOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithNotOptions contains the optional parameters for the SpecialWordsModelsClient.WithNot method. +type SpecialWordsModelsClientWithNotOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithOrOptions contains the optional parameters for the SpecialWordsModelsClient.WithOr method. +type SpecialWordsModelsClientWithOrOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithPassOptions contains the optional parameters for the SpecialWordsModelsClient.WithPass method. +type SpecialWordsModelsClientWithPassOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithRaiseOptions contains the optional parameters for the SpecialWordsModelsClient.WithRaise method. +type SpecialWordsModelsClientWithRaiseOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithReturnOptions contains the optional parameters for the SpecialWordsModelsClient.WithReturn +// method. +type SpecialWordsModelsClientWithReturnOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithTryOptions contains the optional parameters for the SpecialWordsModelsClient.WithTry method. +type SpecialWordsModelsClientWithTryOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithWhileOptions contains the optional parameters for the SpecialWordsModelsClient.WithWhile method. +type SpecialWordsModelsClientWithWhileOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithWithOptions contains the optional parameters for the SpecialWordsModelsClient.WithWith method. +type SpecialWordsModelsClientWithWithOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsModelsClientWithYieldOptions contains the optional parameters for the SpecialWordsModelsClient.WithYield method. +type SpecialWordsModelsClientWithYieldOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientAndOptions contains the optional parameters for the SpecialWordsOperationsClient.And method. +type SpecialWordsOperationsClientAndOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientAsOptions contains the optional parameters for the SpecialWordsOperationsClient.As method. +type SpecialWordsOperationsClientAsOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientAssertOptions contains the optional parameters for the SpecialWordsOperationsClient.Assert +// method. +type SpecialWordsOperationsClientAssertOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientAsyncOptions contains the optional parameters for the SpecialWordsOperationsClient.Async method. +type SpecialWordsOperationsClientAsyncOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientAwaitOptions contains the optional parameters for the SpecialWordsOperationsClient.Await method. +type SpecialWordsOperationsClientAwaitOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientBreakOptions contains the optional parameters for the SpecialWordsOperationsClient.Break method. +type SpecialWordsOperationsClientBreakOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientClassOptions contains the optional parameters for the SpecialWordsOperationsClient.Class method. +type SpecialWordsOperationsClientClassOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientConstructorOptions contains the optional parameters for the SpecialWordsOperationsClient.Constructor +// method. +type SpecialWordsOperationsClientConstructorOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientContinueOptions contains the optional parameters for the SpecialWordsOperationsClient.Continue +// method. +type SpecialWordsOperationsClientContinueOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientDefOptions contains the optional parameters for the SpecialWordsOperationsClient.Def method. +type SpecialWordsOperationsClientDefOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientDelOptions contains the optional parameters for the SpecialWordsOperationsClient.Del method. +type SpecialWordsOperationsClientDelOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientElifOptions contains the optional parameters for the SpecialWordsOperationsClient.Elif method. +type SpecialWordsOperationsClientElifOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientElseOptions contains the optional parameters for the SpecialWordsOperationsClient.Else method. +type SpecialWordsOperationsClientElseOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientExceptOptions contains the optional parameters for the SpecialWordsOperationsClient.Except +// method. +type SpecialWordsOperationsClientExceptOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientExecOptions contains the optional parameters for the SpecialWordsOperationsClient.Exec method. +type SpecialWordsOperationsClientExecOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientFinallyOptions contains the optional parameters for the SpecialWordsOperationsClient.Finally +// method. +type SpecialWordsOperationsClientFinallyOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientForOptions contains the optional parameters for the SpecialWordsOperationsClient.For method. +type SpecialWordsOperationsClientForOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientFromOptions contains the optional parameters for the SpecialWordsOperationsClient.From method. +type SpecialWordsOperationsClientFromOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientGlobalOptions contains the optional parameters for the SpecialWordsOperationsClient.Global +// method. +type SpecialWordsOperationsClientGlobalOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientIfOptions contains the optional parameters for the SpecialWordsOperationsClient.If method. +type SpecialWordsOperationsClientIfOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientImportOptions contains the optional parameters for the SpecialWordsOperationsClient.Import +// method. +type SpecialWordsOperationsClientImportOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientInOptions contains the optional parameters for the SpecialWordsOperationsClient.In method. +type SpecialWordsOperationsClientInOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientIsOptions contains the optional parameters for the SpecialWordsOperationsClient.Is method. +type SpecialWordsOperationsClientIsOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientLambdaOptions contains the optional parameters for the SpecialWordsOperationsClient.Lambda +// method. +type SpecialWordsOperationsClientLambdaOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientNotOptions contains the optional parameters for the SpecialWordsOperationsClient.Not method. +type SpecialWordsOperationsClientNotOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientOrOptions contains the optional parameters for the SpecialWordsOperationsClient.Or method. +type SpecialWordsOperationsClientOrOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientPassOptions contains the optional parameters for the SpecialWordsOperationsClient.Pass method. +type SpecialWordsOperationsClientPassOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientRaiseOptions contains the optional parameters for the SpecialWordsOperationsClient.Raise method. +type SpecialWordsOperationsClientRaiseOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientReturnOptions contains the optional parameters for the SpecialWordsOperationsClient.Return +// method. +type SpecialWordsOperationsClientReturnOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientTryOptions contains the optional parameters for the SpecialWordsOperationsClient.Try method. +type SpecialWordsOperationsClientTryOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientWhileOptions contains the optional parameters for the SpecialWordsOperationsClient.While method. +type SpecialWordsOperationsClientWhileOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientWithOptions contains the optional parameters for the SpecialWordsOperationsClient.With method. +type SpecialWordsOperationsClientWithOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsOperationsClientYieldOptions contains the optional parameters for the SpecialWordsOperationsClient.Yield method. +type SpecialWordsOperationsClientYieldOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithAndOptions contains the optional parameters for the SpecialWordsParametersClient.WithAnd +// method. +type SpecialWordsParametersClientWithAndOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithAsOptions contains the optional parameters for the SpecialWordsParametersClient.WithAs +// method. +type SpecialWordsParametersClientWithAsOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithAssertOptions contains the optional parameters for the SpecialWordsParametersClient.WithAssert +// method. +type SpecialWordsParametersClientWithAssertOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithAsyncOptions contains the optional parameters for the SpecialWordsParametersClient.WithAsync +// method. +type SpecialWordsParametersClientWithAsyncOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithAwaitOptions contains the optional parameters for the SpecialWordsParametersClient.WithAwait +// method. +type SpecialWordsParametersClientWithAwaitOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithBreakOptions contains the optional parameters for the SpecialWordsParametersClient.WithBreak +// method. +type SpecialWordsParametersClientWithBreakOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithCancellationTokenOptions contains the optional parameters for the SpecialWordsParametersClient.WithCancellationToken +// method. +type SpecialWordsParametersClientWithCancellationTokenOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithClassOptions contains the optional parameters for the SpecialWordsParametersClient.WithClass +// method. +type SpecialWordsParametersClientWithClassOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithConstructorOptions contains the optional parameters for the SpecialWordsParametersClient.WithConstructor +// method. +type SpecialWordsParametersClientWithConstructorOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithContinueOptions contains the optional parameters for the SpecialWordsParametersClient.WithContinue +// method. +type SpecialWordsParametersClientWithContinueOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithDefOptions contains the optional parameters for the SpecialWordsParametersClient.WithDef +// method. +type SpecialWordsParametersClientWithDefOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithDelOptions contains the optional parameters for the SpecialWordsParametersClient.WithDel +// method. +type SpecialWordsParametersClientWithDelOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithElifOptions contains the optional parameters for the SpecialWordsParametersClient.WithElif +// method. +type SpecialWordsParametersClientWithElifOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithElseOptions contains the optional parameters for the SpecialWordsParametersClient.WithElse +// method. +type SpecialWordsParametersClientWithElseOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithExceptOptions contains the optional parameters for the SpecialWordsParametersClient.WithExcept +// method. +type SpecialWordsParametersClientWithExceptOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithExecOptions contains the optional parameters for the SpecialWordsParametersClient.WithExec +// method. +type SpecialWordsParametersClientWithExecOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithFinallyOptions contains the optional parameters for the SpecialWordsParametersClient.WithFinally +// method. +type SpecialWordsParametersClientWithFinallyOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithForOptions contains the optional parameters for the SpecialWordsParametersClient.WithFor +// method. +type SpecialWordsParametersClientWithForOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithFromOptions contains the optional parameters for the SpecialWordsParametersClient.WithFrom +// method. +type SpecialWordsParametersClientWithFromOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithGlobalOptions contains the optional parameters for the SpecialWordsParametersClient.WithGlobal +// method. +type SpecialWordsParametersClientWithGlobalOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithIfOptions contains the optional parameters for the SpecialWordsParametersClient.WithIf +// method. +type SpecialWordsParametersClientWithIfOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithImportOptions contains the optional parameters for the SpecialWordsParametersClient.WithImport +// method. +type SpecialWordsParametersClientWithImportOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithInOptions contains the optional parameters for the SpecialWordsParametersClient.WithIn +// method. +type SpecialWordsParametersClientWithInOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithIsOptions contains the optional parameters for the SpecialWordsParametersClient.WithIs +// method. +type SpecialWordsParametersClientWithIsOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithLambdaOptions contains the optional parameters for the SpecialWordsParametersClient.WithLambda +// method. +type SpecialWordsParametersClientWithLambdaOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithNotOptions contains the optional parameters for the SpecialWordsParametersClient.WithNot +// method. +type SpecialWordsParametersClientWithNotOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithOrOptions contains the optional parameters for the SpecialWordsParametersClient.WithOr +// method. +type SpecialWordsParametersClientWithOrOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithPassOptions contains the optional parameters for the SpecialWordsParametersClient.WithPass +// method. +type SpecialWordsParametersClientWithPassOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithRaiseOptions contains the optional parameters for the SpecialWordsParametersClient.WithRaise +// method. +type SpecialWordsParametersClientWithRaiseOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithReturnOptions contains the optional parameters for the SpecialWordsParametersClient.WithReturn +// method. +type SpecialWordsParametersClientWithReturnOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithTryOptions contains the optional parameters for the SpecialWordsParametersClient.WithTry +// method. +type SpecialWordsParametersClientWithTryOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithWhileOptions contains the optional parameters for the SpecialWordsParametersClient.WithWhile +// method. +type SpecialWordsParametersClientWithWhileOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithWithOptions contains the optional parameters for the SpecialWordsParametersClient.WithWith +// method. +type SpecialWordsParametersClientWithWithOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsParametersClientWithYieldOptions contains the optional parameters for the SpecialWordsParametersClient.WithYield +// method. +type SpecialWordsParametersClientWithYieldOptions struct { + // placeholder for future optional parameters +} + +// SpecialWordsReservedOperationBodyParamsClientWithItemsOptions contains the optional parameters for the SpecialWordsReservedOperationBodyParamsClient.WithItems +// method. +type SpecialWordsReservedOperationBodyParamsClientWithItemsOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/specialwordsgroup/zz_responses.go b/test/http-specs/specialwordsgroup/zz_responses.go new file mode 100644 index 000000000000..e003ad2322c6 --- /dev/null +++ b/test/http-specs/specialwordsgroup/zz_responses.go @@ -0,0 +1,530 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package specialwordsgroup + +// SpecialWordsExtensibleStringsClientPutExtensibleStringValueResponse contains the response from method SpecialWordsExtensibleStringsClient.PutExtensibleStringValue. +type SpecialWordsExtensibleStringsClientPutExtensibleStringValueResponse struct { + Value *ExtensibleString +} + +// SpecialWordsModelPropertiesClientDictMethodsResponse contains the response from method SpecialWordsModelPropertiesClient.DictMethods. +type SpecialWordsModelPropertiesClientDictMethodsResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelPropertiesClientSameAsModelResponse contains the response from method SpecialWordsModelPropertiesClient.SameAsModel. +type SpecialWordsModelPropertiesClientSameAsModelResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelPropertiesClientWithListResponse contains the response from method SpecialWordsModelPropertiesClient.WithList. +type SpecialWordsModelPropertiesClientWithListResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithAndResponse contains the response from method SpecialWordsModelsClient.WithAnd. +type SpecialWordsModelsClientWithAndResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithAsResponse contains the response from method SpecialWordsModelsClient.WithAs. +type SpecialWordsModelsClientWithAsResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithAssertResponse contains the response from method SpecialWordsModelsClient.WithAssert. +type SpecialWordsModelsClientWithAssertResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithAsyncResponse contains the response from method SpecialWordsModelsClient.WithAsync. +type SpecialWordsModelsClientWithAsyncResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithAwaitResponse contains the response from method SpecialWordsModelsClient.WithAwait. +type SpecialWordsModelsClientWithAwaitResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithBreakResponse contains the response from method SpecialWordsModelsClient.WithBreak. +type SpecialWordsModelsClientWithBreakResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithClassResponse contains the response from method SpecialWordsModelsClient.WithClass. +type SpecialWordsModelsClientWithClassResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithConstructorResponse contains the response from method SpecialWordsModelsClient.WithConstructor. +type SpecialWordsModelsClientWithConstructorResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithContinueResponse contains the response from method SpecialWordsModelsClient.WithContinue. +type SpecialWordsModelsClientWithContinueResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithDefResponse contains the response from method SpecialWordsModelsClient.WithDef. +type SpecialWordsModelsClientWithDefResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithDelResponse contains the response from method SpecialWordsModelsClient.WithDel. +type SpecialWordsModelsClientWithDelResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithElifResponse contains the response from method SpecialWordsModelsClient.WithElif. +type SpecialWordsModelsClientWithElifResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithElseResponse contains the response from method SpecialWordsModelsClient.WithElse. +type SpecialWordsModelsClientWithElseResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithExceptResponse contains the response from method SpecialWordsModelsClient.WithExcept. +type SpecialWordsModelsClientWithExceptResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithExecResponse contains the response from method SpecialWordsModelsClient.WithExec. +type SpecialWordsModelsClientWithExecResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithFinallyResponse contains the response from method SpecialWordsModelsClient.WithFinally. +type SpecialWordsModelsClientWithFinallyResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithForResponse contains the response from method SpecialWordsModelsClient.WithFor. +type SpecialWordsModelsClientWithForResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithFromResponse contains the response from method SpecialWordsModelsClient.WithFrom. +type SpecialWordsModelsClientWithFromResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithGlobalResponse contains the response from method SpecialWordsModelsClient.WithGlobal. +type SpecialWordsModelsClientWithGlobalResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithIfResponse contains the response from method SpecialWordsModelsClient.WithIf. +type SpecialWordsModelsClientWithIfResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithImportResponse contains the response from method SpecialWordsModelsClient.WithImport. +type SpecialWordsModelsClientWithImportResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithInResponse contains the response from method SpecialWordsModelsClient.WithIn. +type SpecialWordsModelsClientWithInResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithIsResponse contains the response from method SpecialWordsModelsClient.WithIs. +type SpecialWordsModelsClientWithIsResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithLambdaResponse contains the response from method SpecialWordsModelsClient.WithLambda. +type SpecialWordsModelsClientWithLambdaResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithNotResponse contains the response from method SpecialWordsModelsClient.WithNot. +type SpecialWordsModelsClientWithNotResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithOrResponse contains the response from method SpecialWordsModelsClient.WithOr. +type SpecialWordsModelsClientWithOrResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithPassResponse contains the response from method SpecialWordsModelsClient.WithPass. +type SpecialWordsModelsClientWithPassResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithRaiseResponse contains the response from method SpecialWordsModelsClient.WithRaise. +type SpecialWordsModelsClientWithRaiseResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithReturnResponse contains the response from method SpecialWordsModelsClient.WithReturn. +type SpecialWordsModelsClientWithReturnResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithTryResponse contains the response from method SpecialWordsModelsClient.WithTry. +type SpecialWordsModelsClientWithTryResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithWhileResponse contains the response from method SpecialWordsModelsClient.WithWhile. +type SpecialWordsModelsClientWithWhileResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithWithResponse contains the response from method SpecialWordsModelsClient.WithWith. +type SpecialWordsModelsClientWithWithResponse struct { + // placeholder for future response values +} + +// SpecialWordsModelsClientWithYieldResponse contains the response from method SpecialWordsModelsClient.WithYield. +type SpecialWordsModelsClientWithYieldResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientAndResponse contains the response from method SpecialWordsOperationsClient.And. +type SpecialWordsOperationsClientAndResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientAsResponse contains the response from method SpecialWordsOperationsClient.As. +type SpecialWordsOperationsClientAsResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientAssertResponse contains the response from method SpecialWordsOperationsClient.Assert. +type SpecialWordsOperationsClientAssertResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientAsyncResponse contains the response from method SpecialWordsOperationsClient.Async. +type SpecialWordsOperationsClientAsyncResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientAwaitResponse contains the response from method SpecialWordsOperationsClient.Await. +type SpecialWordsOperationsClientAwaitResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientBreakResponse contains the response from method SpecialWordsOperationsClient.Break. +type SpecialWordsOperationsClientBreakResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientClassResponse contains the response from method SpecialWordsOperationsClient.Class. +type SpecialWordsOperationsClientClassResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientConstructorResponse contains the response from method SpecialWordsOperationsClient.Constructor. +type SpecialWordsOperationsClientConstructorResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientContinueResponse contains the response from method SpecialWordsOperationsClient.Continue. +type SpecialWordsOperationsClientContinueResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientDefResponse contains the response from method SpecialWordsOperationsClient.Def. +type SpecialWordsOperationsClientDefResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientDelResponse contains the response from method SpecialWordsOperationsClient.Del. +type SpecialWordsOperationsClientDelResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientElifResponse contains the response from method SpecialWordsOperationsClient.Elif. +type SpecialWordsOperationsClientElifResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientElseResponse contains the response from method SpecialWordsOperationsClient.Else. +type SpecialWordsOperationsClientElseResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientExceptResponse contains the response from method SpecialWordsOperationsClient.Except. +type SpecialWordsOperationsClientExceptResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientExecResponse contains the response from method SpecialWordsOperationsClient.Exec. +type SpecialWordsOperationsClientExecResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientFinallyResponse contains the response from method SpecialWordsOperationsClient.Finally. +type SpecialWordsOperationsClientFinallyResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientForResponse contains the response from method SpecialWordsOperationsClient.For. +type SpecialWordsOperationsClientForResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientFromResponse contains the response from method SpecialWordsOperationsClient.From. +type SpecialWordsOperationsClientFromResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientGlobalResponse contains the response from method SpecialWordsOperationsClient.Global. +type SpecialWordsOperationsClientGlobalResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientIfResponse contains the response from method SpecialWordsOperationsClient.If. +type SpecialWordsOperationsClientIfResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientImportResponse contains the response from method SpecialWordsOperationsClient.Import. +type SpecialWordsOperationsClientImportResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientInResponse contains the response from method SpecialWordsOperationsClient.In. +type SpecialWordsOperationsClientInResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientIsResponse contains the response from method SpecialWordsOperationsClient.Is. +type SpecialWordsOperationsClientIsResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientLambdaResponse contains the response from method SpecialWordsOperationsClient.Lambda. +type SpecialWordsOperationsClientLambdaResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientNotResponse contains the response from method SpecialWordsOperationsClient.Not. +type SpecialWordsOperationsClientNotResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientOrResponse contains the response from method SpecialWordsOperationsClient.Or. +type SpecialWordsOperationsClientOrResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientPassResponse contains the response from method SpecialWordsOperationsClient.Pass. +type SpecialWordsOperationsClientPassResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientRaiseResponse contains the response from method SpecialWordsOperationsClient.Raise. +type SpecialWordsOperationsClientRaiseResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientReturnResponse contains the response from method SpecialWordsOperationsClient.Return. +type SpecialWordsOperationsClientReturnResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientTryResponse contains the response from method SpecialWordsOperationsClient.Try. +type SpecialWordsOperationsClientTryResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientWhileResponse contains the response from method SpecialWordsOperationsClient.While. +type SpecialWordsOperationsClientWhileResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientWithResponse contains the response from method SpecialWordsOperationsClient.With. +type SpecialWordsOperationsClientWithResponse struct { + // placeholder for future response values +} + +// SpecialWordsOperationsClientYieldResponse contains the response from method SpecialWordsOperationsClient.Yield. +type SpecialWordsOperationsClientYieldResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithAndResponse contains the response from method SpecialWordsParametersClient.WithAnd. +type SpecialWordsParametersClientWithAndResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithAsResponse contains the response from method SpecialWordsParametersClient.WithAs. +type SpecialWordsParametersClientWithAsResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithAssertResponse contains the response from method SpecialWordsParametersClient.WithAssert. +type SpecialWordsParametersClientWithAssertResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithAsyncResponse contains the response from method SpecialWordsParametersClient.WithAsync. +type SpecialWordsParametersClientWithAsyncResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithAwaitResponse contains the response from method SpecialWordsParametersClient.WithAwait. +type SpecialWordsParametersClientWithAwaitResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithBreakResponse contains the response from method SpecialWordsParametersClient.WithBreak. +type SpecialWordsParametersClientWithBreakResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithCancellationTokenResponse contains the response from method SpecialWordsParametersClient.WithCancellationToken. +type SpecialWordsParametersClientWithCancellationTokenResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithClassResponse contains the response from method SpecialWordsParametersClient.WithClass. +type SpecialWordsParametersClientWithClassResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithConstructorResponse contains the response from method SpecialWordsParametersClient.WithConstructor. +type SpecialWordsParametersClientWithConstructorResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithContinueResponse contains the response from method SpecialWordsParametersClient.WithContinue. +type SpecialWordsParametersClientWithContinueResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithDefResponse contains the response from method SpecialWordsParametersClient.WithDef. +type SpecialWordsParametersClientWithDefResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithDelResponse contains the response from method SpecialWordsParametersClient.WithDel. +type SpecialWordsParametersClientWithDelResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithElifResponse contains the response from method SpecialWordsParametersClient.WithElif. +type SpecialWordsParametersClientWithElifResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithElseResponse contains the response from method SpecialWordsParametersClient.WithElse. +type SpecialWordsParametersClientWithElseResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithExceptResponse contains the response from method SpecialWordsParametersClient.WithExcept. +type SpecialWordsParametersClientWithExceptResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithExecResponse contains the response from method SpecialWordsParametersClient.WithExec. +type SpecialWordsParametersClientWithExecResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithFinallyResponse contains the response from method SpecialWordsParametersClient.WithFinally. +type SpecialWordsParametersClientWithFinallyResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithForResponse contains the response from method SpecialWordsParametersClient.WithFor. +type SpecialWordsParametersClientWithForResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithFromResponse contains the response from method SpecialWordsParametersClient.WithFrom. +type SpecialWordsParametersClientWithFromResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithGlobalResponse contains the response from method SpecialWordsParametersClient.WithGlobal. +type SpecialWordsParametersClientWithGlobalResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithIfResponse contains the response from method SpecialWordsParametersClient.WithIf. +type SpecialWordsParametersClientWithIfResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithImportResponse contains the response from method SpecialWordsParametersClient.WithImport. +type SpecialWordsParametersClientWithImportResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithInResponse contains the response from method SpecialWordsParametersClient.WithIn. +type SpecialWordsParametersClientWithInResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithIsResponse contains the response from method SpecialWordsParametersClient.WithIs. +type SpecialWordsParametersClientWithIsResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithLambdaResponse contains the response from method SpecialWordsParametersClient.WithLambda. +type SpecialWordsParametersClientWithLambdaResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithNotResponse contains the response from method SpecialWordsParametersClient.WithNot. +type SpecialWordsParametersClientWithNotResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithOrResponse contains the response from method SpecialWordsParametersClient.WithOr. +type SpecialWordsParametersClientWithOrResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithPassResponse contains the response from method SpecialWordsParametersClient.WithPass. +type SpecialWordsParametersClientWithPassResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithRaiseResponse contains the response from method SpecialWordsParametersClient.WithRaise. +type SpecialWordsParametersClientWithRaiseResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithReturnResponse contains the response from method SpecialWordsParametersClient.WithReturn. +type SpecialWordsParametersClientWithReturnResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithTryResponse contains the response from method SpecialWordsParametersClient.WithTry. +type SpecialWordsParametersClientWithTryResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithWhileResponse contains the response from method SpecialWordsParametersClient.WithWhile. +type SpecialWordsParametersClientWithWhileResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithWithResponse contains the response from method SpecialWordsParametersClient.WithWith. +type SpecialWordsParametersClientWithWithResponse struct { + // placeholder for future response values +} + +// SpecialWordsParametersClientWithYieldResponse contains the response from method SpecialWordsParametersClient.WithYield. +type SpecialWordsParametersClientWithYieldResponse struct { + // placeholder for future response values +} + +// SpecialWordsReservedOperationBodyParamsClientWithItemsResponse contains the response from method SpecialWordsReservedOperationBodyParamsClient.WithItems. +type SpecialWordsReservedOperationBodyParamsClientWithItemsResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/specialwordsgroup/zz_specialwords_client.go b/test/http-specs/specialwordsgroup/zz_specialwords_client.go new file mode 100644 index 000000000000..3236e3d214ea --- /dev/null +++ b/test/http-specs/specialwordsgroup/zz_specialwords_client.go @@ -0,0 +1,125 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package specialwordsgroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// SpecialWordsClient - Scenarios to verify that reserved words can be used in service and generators will handle it appropriately. +// Current list of special words +// ```txt +// and +// as +// assert +// async +// await +// break +// class +// constructor +// continue +// def +// del +// elif +// else +// except +// exec +// finally +// for +// from +// global +// if +// import +// in +// is +// lambda +// list +// not +// or +// pass +// raise +// return +// try +// while +// with +// yield +// ``` +// Don't use this type directly, use NewSpecialWordsClientWithNoCredential() instead. +type SpecialWordsClient struct { + internal *azcore.Client + endpoint string +} + +// SpecialWordsClientOptions contains the optional values for creating a [SpecialWordsClient]. +type SpecialWordsClientOptions struct { + azcore.ClientOptions +} + +// NewSpecialWordsClientWithNoCredential creates a new instance of SpecialWordsClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewSpecialWordsClientWithNoCredential(endpoint string, options *SpecialWordsClientOptions) (*SpecialWordsClient, error) { + if options == nil { + options = &SpecialWordsClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &SpecialWordsClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewSpecialWordsExtensibleStringsClient creates a new instance of [SpecialWordsExtensibleStringsClient]. +func (client *SpecialWordsClient) NewSpecialWordsExtensibleStringsClient() *SpecialWordsExtensibleStringsClient { + return &SpecialWordsExtensibleStringsClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewSpecialWordsModelPropertiesClient creates a new instance of [SpecialWordsModelPropertiesClient]. +func (client *SpecialWordsClient) NewSpecialWordsModelPropertiesClient() *SpecialWordsModelPropertiesClient { + return &SpecialWordsModelPropertiesClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewSpecialWordsModelsClient creates a new instance of [SpecialWordsModelsClient]. +func (client *SpecialWordsClient) NewSpecialWordsModelsClient() *SpecialWordsModelsClient { + return &SpecialWordsModelsClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewSpecialWordsOperationsClient creates a new instance of [SpecialWordsOperationsClient]. +func (client *SpecialWordsClient) NewSpecialWordsOperationsClient() *SpecialWordsOperationsClient { + return &SpecialWordsOperationsClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewSpecialWordsParametersClient creates a new instance of [SpecialWordsParametersClient]. +func (client *SpecialWordsClient) NewSpecialWordsParametersClient() *SpecialWordsParametersClient { + return &SpecialWordsParametersClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewSpecialWordsReservedOperationBodyParamsClient creates a new instance of [SpecialWordsReservedOperationBodyParamsClient]. +func (client *SpecialWordsClient) NewSpecialWordsReservedOperationBodyParamsClient() *SpecialWordsReservedOperationBodyParamsClient { + return &SpecialWordsReservedOperationBodyParamsClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/http-specs/specialwordsgroup/zz_specialwordsextensiblestrings_client.go b/test/http-specs/specialwordsgroup/zz_specialwordsextensiblestrings_client.go new file mode 100644 index 000000000000..4c2bde81d7ec --- /dev/null +++ b/test/http-specs/specialwordsgroup/zz_specialwordsextensiblestrings_client.go @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package specialwordsgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// SpecialWordsExtensibleStringsClient - Verify enum member names that are special words. +// Don't use this type directly, use [SpecialWordsClient.NewSpecialWordsExtensibleStringsClient] instead. +type SpecialWordsExtensibleStringsClient struct { + internal *azcore.Client + endpoint string +} + +// PutExtensibleStringValue - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsExtensibleStringsClientPutExtensibleStringValueOptions contains the optional parameters for the SpecialWordsExtensibleStringsClient.PutExtensibleStringValue +// method. +func (client *SpecialWordsExtensibleStringsClient) PutExtensibleStringValue(ctx context.Context, body ExtensibleString, options *SpecialWordsExtensibleStringsClientPutExtensibleStringValueOptions) (SpecialWordsExtensibleStringsClientPutExtensibleStringValueResponse, error) { + var err error + const operationName = "SpecialWordsExtensibleStringsClient.PutExtensibleStringValue" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putExtensibleStringValueCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsExtensibleStringsClientPutExtensibleStringValueResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsExtensibleStringsClientPutExtensibleStringValueResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsExtensibleStringsClientPutExtensibleStringValueResponse{}, err + } + resp, err := client.putExtensibleStringValueHandleResponse(httpResp) + return resp, err +} + +// putExtensibleStringValueCreateRequest creates the PutExtensibleStringValue request. +func (client *SpecialWordsExtensibleStringsClient) putExtensibleStringValueCreateRequest(ctx context.Context, body ExtensibleString, _ *SpecialWordsExtensibleStringsClientPutExtensibleStringValueOptions) (*policy.Request, error) { + urlPath := "/special-words/extensible-strings/string" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// putExtensibleStringValueHandleResponse handles the PutExtensibleStringValue response. +func (client *SpecialWordsExtensibleStringsClient) putExtensibleStringValueHandleResponse(resp *http.Response) (SpecialWordsExtensibleStringsClientPutExtensibleStringValueResponse, error) { + result := SpecialWordsExtensibleStringsClientPutExtensibleStringValueResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Value); err != nil { + return SpecialWordsExtensibleStringsClientPutExtensibleStringValueResponse{}, err + } + return result, nil +} diff --git a/test/http-specs/specialwordsgroup/zz_specialwordsmodelproperties_client.go b/test/http-specs/specialwordsgroup/zz_specialwordsmodelproperties_client.go new file mode 100644 index 000000000000..79053b1c889d --- /dev/null +++ b/test/http-specs/specialwordsgroup/zz_specialwordsmodelproperties_client.go @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package specialwordsgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// SpecialWordsModelPropertiesClient - Verify model names +// Don't use this type directly, use [SpecialWordsClient.NewSpecialWordsModelPropertiesClient] instead. +type SpecialWordsModelPropertiesClient struct { + internal *azcore.Client + endpoint string +} + +// DictMethods - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelPropertiesClientDictMethodsOptions contains the optional parameters for the SpecialWordsModelPropertiesClient.DictMethods +// method. +func (client *SpecialWordsModelPropertiesClient) DictMethods(ctx context.Context, body DictMethods, options *SpecialWordsModelPropertiesClientDictMethodsOptions) (SpecialWordsModelPropertiesClientDictMethodsResponse, error) { + var err error + const operationName = "SpecialWordsModelPropertiesClient.DictMethods" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.dictMethodsCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelPropertiesClientDictMethodsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelPropertiesClientDictMethodsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelPropertiesClientDictMethodsResponse{}, err + } + return SpecialWordsModelPropertiesClientDictMethodsResponse{}, nil +} + +// dictMethodsCreateRequest creates the DictMethods request. +func (client *SpecialWordsModelPropertiesClient) dictMethodsCreateRequest(ctx context.Context, body DictMethods, _ *SpecialWordsModelPropertiesClientDictMethodsOptions) (*policy.Request, error) { + urlPath := "/special-words/model-properties/dict-methods" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// SameAsModel - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelPropertiesClientSameAsModelOptions contains the optional parameters for the SpecialWordsModelPropertiesClient.SameAsModel +// method. +func (client *SpecialWordsModelPropertiesClient) SameAsModel(ctx context.Context, body SameAsModel, options *SpecialWordsModelPropertiesClientSameAsModelOptions) (SpecialWordsModelPropertiesClientSameAsModelResponse, error) { + var err error + const operationName = "SpecialWordsModelPropertiesClient.SameAsModel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.sameAsModelCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelPropertiesClientSameAsModelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelPropertiesClientSameAsModelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelPropertiesClientSameAsModelResponse{}, err + } + return SpecialWordsModelPropertiesClientSameAsModelResponse{}, nil +} + +// sameAsModelCreateRequest creates the SameAsModel request. +func (client *SpecialWordsModelPropertiesClient) sameAsModelCreateRequest(ctx context.Context, body SameAsModel, _ *SpecialWordsModelPropertiesClientSameAsModelOptions) (*policy.Request, error) { + urlPath := "/special-words/model-properties/same-as-model" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithList - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelPropertiesClientWithListOptions contains the optional parameters for the SpecialWordsModelPropertiesClient.WithList +// method. +func (client *SpecialWordsModelPropertiesClient) WithList(ctx context.Context, body ModelWithList, options *SpecialWordsModelPropertiesClientWithListOptions) (SpecialWordsModelPropertiesClientWithListResponse, error) { + var err error + const operationName = "SpecialWordsModelPropertiesClient.WithList" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withListCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelPropertiesClientWithListResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelPropertiesClientWithListResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelPropertiesClientWithListResponse{}, err + } + return SpecialWordsModelPropertiesClientWithListResponse{}, nil +} + +// withListCreateRequest creates the WithList request. +func (client *SpecialWordsModelPropertiesClient) withListCreateRequest(ctx context.Context, body ModelWithList, _ *SpecialWordsModelPropertiesClientWithListOptions) (*policy.Request, error) { + urlPath := "/special-words/model-properties/list" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/specialwordsgroup/zz_specialwordsmodels_client.go b/test/http-specs/specialwordsgroup/zz_specialwordsmodels_client.go new file mode 100644 index 000000000000..1f706c249e28 --- /dev/null +++ b/test/http-specs/specialwordsgroup/zz_specialwordsmodels_client.go @@ -0,0 +1,1307 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package specialwordsgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// SpecialWordsModelsClient - Verify model names +// Don't use this type directly, use [SpecialWordsClient.NewSpecialWordsModelsClient] instead. +type SpecialWordsModelsClient struct { + internal *azcore.Client + endpoint string +} + +// WithAnd - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithAndOptions contains the optional parameters for the SpecialWordsModelsClient.WithAnd +// method. +func (client *SpecialWordsModelsClient) WithAnd(ctx context.Context, body And, options *SpecialWordsModelsClientWithAndOptions) (SpecialWordsModelsClientWithAndResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithAnd" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withAndCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithAndResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithAndResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithAndResponse{}, err + } + return SpecialWordsModelsClientWithAndResponse{}, nil +} + +// withAndCreateRequest creates the WithAnd request. +func (client *SpecialWordsModelsClient) withAndCreateRequest(ctx context.Context, body And, _ *SpecialWordsModelsClientWithAndOptions) (*policy.Request, error) { + urlPath := "/special-words/models/and" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithAs - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithAsOptions contains the optional parameters for the SpecialWordsModelsClient.WithAs +// method. +func (client *SpecialWordsModelsClient) WithAs(ctx context.Context, body As, options *SpecialWordsModelsClientWithAsOptions) (SpecialWordsModelsClientWithAsResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithAs" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withAsCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithAsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithAsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithAsResponse{}, err + } + return SpecialWordsModelsClientWithAsResponse{}, nil +} + +// withAsCreateRequest creates the WithAs request. +func (client *SpecialWordsModelsClient) withAsCreateRequest(ctx context.Context, body As, _ *SpecialWordsModelsClientWithAsOptions) (*policy.Request, error) { + urlPath := "/special-words/models/as" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithAssert - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithAssertOptions contains the optional parameters for the SpecialWordsModelsClient.WithAssert +// method. +func (client *SpecialWordsModelsClient) WithAssert(ctx context.Context, body Assert, options *SpecialWordsModelsClientWithAssertOptions) (SpecialWordsModelsClientWithAssertResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithAssert" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withAssertCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithAssertResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithAssertResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithAssertResponse{}, err + } + return SpecialWordsModelsClientWithAssertResponse{}, nil +} + +// withAssertCreateRequest creates the WithAssert request. +func (client *SpecialWordsModelsClient) withAssertCreateRequest(ctx context.Context, body Assert, _ *SpecialWordsModelsClientWithAssertOptions) (*policy.Request, error) { + urlPath := "/special-words/models/assert" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithAsync - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithAsyncOptions contains the optional parameters for the SpecialWordsModelsClient.WithAsync +// method. +func (client *SpecialWordsModelsClient) WithAsync(ctx context.Context, body Async, options *SpecialWordsModelsClientWithAsyncOptions) (SpecialWordsModelsClientWithAsyncResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithAsync" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withAsyncCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithAsyncResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithAsyncResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithAsyncResponse{}, err + } + return SpecialWordsModelsClientWithAsyncResponse{}, nil +} + +// withAsyncCreateRequest creates the WithAsync request. +func (client *SpecialWordsModelsClient) withAsyncCreateRequest(ctx context.Context, body Async, _ *SpecialWordsModelsClientWithAsyncOptions) (*policy.Request, error) { + urlPath := "/special-words/models/async" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithAwait - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithAwaitOptions contains the optional parameters for the SpecialWordsModelsClient.WithAwait +// method. +func (client *SpecialWordsModelsClient) WithAwait(ctx context.Context, body Await, options *SpecialWordsModelsClientWithAwaitOptions) (SpecialWordsModelsClientWithAwaitResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithAwait" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withAwaitCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithAwaitResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithAwaitResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithAwaitResponse{}, err + } + return SpecialWordsModelsClientWithAwaitResponse{}, nil +} + +// withAwaitCreateRequest creates the WithAwait request. +func (client *SpecialWordsModelsClient) withAwaitCreateRequest(ctx context.Context, body Await, _ *SpecialWordsModelsClientWithAwaitOptions) (*policy.Request, error) { + urlPath := "/special-words/models/await" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithBreak - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithBreakOptions contains the optional parameters for the SpecialWordsModelsClient.WithBreak +// method. +func (client *SpecialWordsModelsClient) WithBreak(ctx context.Context, body Break, options *SpecialWordsModelsClientWithBreakOptions) (SpecialWordsModelsClientWithBreakResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithBreak" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withBreakCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithBreakResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithBreakResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithBreakResponse{}, err + } + return SpecialWordsModelsClientWithBreakResponse{}, nil +} + +// withBreakCreateRequest creates the WithBreak request. +func (client *SpecialWordsModelsClient) withBreakCreateRequest(ctx context.Context, body Break, _ *SpecialWordsModelsClientWithBreakOptions) (*policy.Request, error) { + urlPath := "/special-words/models/break" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithClass - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithClassOptions contains the optional parameters for the SpecialWordsModelsClient.WithClass +// method. +func (client *SpecialWordsModelsClient) WithClass(ctx context.Context, body Class, options *SpecialWordsModelsClientWithClassOptions) (SpecialWordsModelsClientWithClassResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithClass" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withClassCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithClassResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithClassResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithClassResponse{}, err + } + return SpecialWordsModelsClientWithClassResponse{}, nil +} + +// withClassCreateRequest creates the WithClass request. +func (client *SpecialWordsModelsClient) withClassCreateRequest(ctx context.Context, body Class, _ *SpecialWordsModelsClientWithClassOptions) (*policy.Request, error) { + urlPath := "/special-words/models/class" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithConstructor - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithConstructorOptions contains the optional parameters for the SpecialWordsModelsClient.WithConstructor +// method. +func (client *SpecialWordsModelsClient) WithConstructor(ctx context.Context, body Constructor, options *SpecialWordsModelsClientWithConstructorOptions) (SpecialWordsModelsClientWithConstructorResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithConstructor" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withConstructorCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithConstructorResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithConstructorResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithConstructorResponse{}, err + } + return SpecialWordsModelsClientWithConstructorResponse{}, nil +} + +// withConstructorCreateRequest creates the WithConstructor request. +func (client *SpecialWordsModelsClient) withConstructorCreateRequest(ctx context.Context, body Constructor, _ *SpecialWordsModelsClientWithConstructorOptions) (*policy.Request, error) { + urlPath := "/special-words/models/constructor" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithContinue - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithContinueOptions contains the optional parameters for the SpecialWordsModelsClient.WithContinue +// method. +func (client *SpecialWordsModelsClient) WithContinue(ctx context.Context, body Continue, options *SpecialWordsModelsClientWithContinueOptions) (SpecialWordsModelsClientWithContinueResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithContinue" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withContinueCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithContinueResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithContinueResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithContinueResponse{}, err + } + return SpecialWordsModelsClientWithContinueResponse{}, nil +} + +// withContinueCreateRequest creates the WithContinue request. +func (client *SpecialWordsModelsClient) withContinueCreateRequest(ctx context.Context, body Continue, _ *SpecialWordsModelsClientWithContinueOptions) (*policy.Request, error) { + urlPath := "/special-words/models/continue" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithDef - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithDefOptions contains the optional parameters for the SpecialWordsModelsClient.WithDef +// method. +func (client *SpecialWordsModelsClient) WithDef(ctx context.Context, body Def, options *SpecialWordsModelsClientWithDefOptions) (SpecialWordsModelsClientWithDefResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithDef" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withDefCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithDefResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithDefResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithDefResponse{}, err + } + return SpecialWordsModelsClientWithDefResponse{}, nil +} + +// withDefCreateRequest creates the WithDef request. +func (client *SpecialWordsModelsClient) withDefCreateRequest(ctx context.Context, body Def, _ *SpecialWordsModelsClientWithDefOptions) (*policy.Request, error) { + urlPath := "/special-words/models/def" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithDel - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithDelOptions contains the optional parameters for the SpecialWordsModelsClient.WithDel +// method. +func (client *SpecialWordsModelsClient) WithDel(ctx context.Context, body Del, options *SpecialWordsModelsClientWithDelOptions) (SpecialWordsModelsClientWithDelResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithDel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withDelCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithDelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithDelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithDelResponse{}, err + } + return SpecialWordsModelsClientWithDelResponse{}, nil +} + +// withDelCreateRequest creates the WithDel request. +func (client *SpecialWordsModelsClient) withDelCreateRequest(ctx context.Context, body Del, _ *SpecialWordsModelsClientWithDelOptions) (*policy.Request, error) { + urlPath := "/special-words/models/del" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithElif - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithElifOptions contains the optional parameters for the SpecialWordsModelsClient.WithElif +// method. +func (client *SpecialWordsModelsClient) WithElif(ctx context.Context, body Elif, options *SpecialWordsModelsClientWithElifOptions) (SpecialWordsModelsClientWithElifResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithElif" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withElifCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithElifResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithElifResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithElifResponse{}, err + } + return SpecialWordsModelsClientWithElifResponse{}, nil +} + +// withElifCreateRequest creates the WithElif request. +func (client *SpecialWordsModelsClient) withElifCreateRequest(ctx context.Context, body Elif, _ *SpecialWordsModelsClientWithElifOptions) (*policy.Request, error) { + urlPath := "/special-words/models/elif" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithElse - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithElseOptions contains the optional parameters for the SpecialWordsModelsClient.WithElse +// method. +func (client *SpecialWordsModelsClient) WithElse(ctx context.Context, body Else, options *SpecialWordsModelsClientWithElseOptions) (SpecialWordsModelsClientWithElseResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithElse" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withElseCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithElseResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithElseResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithElseResponse{}, err + } + return SpecialWordsModelsClientWithElseResponse{}, nil +} + +// withElseCreateRequest creates the WithElse request. +func (client *SpecialWordsModelsClient) withElseCreateRequest(ctx context.Context, body Else, _ *SpecialWordsModelsClientWithElseOptions) (*policy.Request, error) { + urlPath := "/special-words/models/else" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithExcept - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithExceptOptions contains the optional parameters for the SpecialWordsModelsClient.WithExcept +// method. +func (client *SpecialWordsModelsClient) WithExcept(ctx context.Context, body Except, options *SpecialWordsModelsClientWithExceptOptions) (SpecialWordsModelsClientWithExceptResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithExcept" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withExceptCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithExceptResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithExceptResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithExceptResponse{}, err + } + return SpecialWordsModelsClientWithExceptResponse{}, nil +} + +// withExceptCreateRequest creates the WithExcept request. +func (client *SpecialWordsModelsClient) withExceptCreateRequest(ctx context.Context, body Except, _ *SpecialWordsModelsClientWithExceptOptions) (*policy.Request, error) { + urlPath := "/special-words/models/except" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithExec - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithExecOptions contains the optional parameters for the SpecialWordsModelsClient.WithExec +// method. +func (client *SpecialWordsModelsClient) WithExec(ctx context.Context, body Exec, options *SpecialWordsModelsClientWithExecOptions) (SpecialWordsModelsClientWithExecResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithExec" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withExecCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithExecResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithExecResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithExecResponse{}, err + } + return SpecialWordsModelsClientWithExecResponse{}, nil +} + +// withExecCreateRequest creates the WithExec request. +func (client *SpecialWordsModelsClient) withExecCreateRequest(ctx context.Context, body Exec, _ *SpecialWordsModelsClientWithExecOptions) (*policy.Request, error) { + urlPath := "/special-words/models/exec" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithFinally - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithFinallyOptions contains the optional parameters for the SpecialWordsModelsClient.WithFinally +// method. +func (client *SpecialWordsModelsClient) WithFinally(ctx context.Context, body Finally, options *SpecialWordsModelsClientWithFinallyOptions) (SpecialWordsModelsClientWithFinallyResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithFinally" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withFinallyCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithFinallyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithFinallyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithFinallyResponse{}, err + } + return SpecialWordsModelsClientWithFinallyResponse{}, nil +} + +// withFinallyCreateRequest creates the WithFinally request. +func (client *SpecialWordsModelsClient) withFinallyCreateRequest(ctx context.Context, body Finally, _ *SpecialWordsModelsClientWithFinallyOptions) (*policy.Request, error) { + urlPath := "/special-words/models/finally" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithFor - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithForOptions contains the optional parameters for the SpecialWordsModelsClient.WithFor +// method. +func (client *SpecialWordsModelsClient) WithFor(ctx context.Context, body For, options *SpecialWordsModelsClientWithForOptions) (SpecialWordsModelsClientWithForResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithFor" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withForCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithForResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithForResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithForResponse{}, err + } + return SpecialWordsModelsClientWithForResponse{}, nil +} + +// withForCreateRequest creates the WithFor request. +func (client *SpecialWordsModelsClient) withForCreateRequest(ctx context.Context, body For, _ *SpecialWordsModelsClientWithForOptions) (*policy.Request, error) { + urlPath := "/special-words/models/for" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithFrom - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithFromOptions contains the optional parameters for the SpecialWordsModelsClient.WithFrom +// method. +func (client *SpecialWordsModelsClient) WithFrom(ctx context.Context, body From, options *SpecialWordsModelsClientWithFromOptions) (SpecialWordsModelsClientWithFromResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithFrom" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withFromCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithFromResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithFromResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithFromResponse{}, err + } + return SpecialWordsModelsClientWithFromResponse{}, nil +} + +// withFromCreateRequest creates the WithFrom request. +func (client *SpecialWordsModelsClient) withFromCreateRequest(ctx context.Context, body From, _ *SpecialWordsModelsClientWithFromOptions) (*policy.Request, error) { + urlPath := "/special-words/models/from" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithGlobal - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithGlobalOptions contains the optional parameters for the SpecialWordsModelsClient.WithGlobal +// method. +func (client *SpecialWordsModelsClient) WithGlobal(ctx context.Context, body Global, options *SpecialWordsModelsClientWithGlobalOptions) (SpecialWordsModelsClientWithGlobalResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithGlobal" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withGlobalCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithGlobalResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithGlobalResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithGlobalResponse{}, err + } + return SpecialWordsModelsClientWithGlobalResponse{}, nil +} + +// withGlobalCreateRequest creates the WithGlobal request. +func (client *SpecialWordsModelsClient) withGlobalCreateRequest(ctx context.Context, body Global, _ *SpecialWordsModelsClientWithGlobalOptions) (*policy.Request, error) { + urlPath := "/special-words/models/global" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithIf - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithIfOptions contains the optional parameters for the SpecialWordsModelsClient.WithIf +// method. +func (client *SpecialWordsModelsClient) WithIf(ctx context.Context, body If, options *SpecialWordsModelsClientWithIfOptions) (SpecialWordsModelsClientWithIfResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithIf" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withIfCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithIfResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithIfResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithIfResponse{}, err + } + return SpecialWordsModelsClientWithIfResponse{}, nil +} + +// withIfCreateRequest creates the WithIf request. +func (client *SpecialWordsModelsClient) withIfCreateRequest(ctx context.Context, body If, _ *SpecialWordsModelsClientWithIfOptions) (*policy.Request, error) { + urlPath := "/special-words/models/if" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithImport - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithImportOptions contains the optional parameters for the SpecialWordsModelsClient.WithImport +// method. +func (client *SpecialWordsModelsClient) WithImport(ctx context.Context, body Import, options *SpecialWordsModelsClientWithImportOptions) (SpecialWordsModelsClientWithImportResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithImport" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withImportCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithImportResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithImportResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithImportResponse{}, err + } + return SpecialWordsModelsClientWithImportResponse{}, nil +} + +// withImportCreateRequest creates the WithImport request. +func (client *SpecialWordsModelsClient) withImportCreateRequest(ctx context.Context, body Import, _ *SpecialWordsModelsClientWithImportOptions) (*policy.Request, error) { + urlPath := "/special-words/models/import" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithIn - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithInOptions contains the optional parameters for the SpecialWordsModelsClient.WithIn +// method. +func (client *SpecialWordsModelsClient) WithIn(ctx context.Context, body In, options *SpecialWordsModelsClientWithInOptions) (SpecialWordsModelsClientWithInResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithIn" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withInCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithInResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithInResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithInResponse{}, err + } + return SpecialWordsModelsClientWithInResponse{}, nil +} + +// withInCreateRequest creates the WithIn request. +func (client *SpecialWordsModelsClient) withInCreateRequest(ctx context.Context, body In, _ *SpecialWordsModelsClientWithInOptions) (*policy.Request, error) { + urlPath := "/special-words/models/in" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithIs - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithIsOptions contains the optional parameters for the SpecialWordsModelsClient.WithIs +// method. +func (client *SpecialWordsModelsClient) WithIs(ctx context.Context, body Is, options *SpecialWordsModelsClientWithIsOptions) (SpecialWordsModelsClientWithIsResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithIs" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withIsCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithIsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithIsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithIsResponse{}, err + } + return SpecialWordsModelsClientWithIsResponse{}, nil +} + +// withIsCreateRequest creates the WithIs request. +func (client *SpecialWordsModelsClient) withIsCreateRequest(ctx context.Context, body Is, _ *SpecialWordsModelsClientWithIsOptions) (*policy.Request, error) { + urlPath := "/special-words/models/is" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithLambda - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithLambdaOptions contains the optional parameters for the SpecialWordsModelsClient.WithLambda +// method. +func (client *SpecialWordsModelsClient) WithLambda(ctx context.Context, body Lambda, options *SpecialWordsModelsClientWithLambdaOptions) (SpecialWordsModelsClientWithLambdaResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithLambda" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withLambdaCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithLambdaResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithLambdaResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithLambdaResponse{}, err + } + return SpecialWordsModelsClientWithLambdaResponse{}, nil +} + +// withLambdaCreateRequest creates the WithLambda request. +func (client *SpecialWordsModelsClient) withLambdaCreateRequest(ctx context.Context, body Lambda, _ *SpecialWordsModelsClientWithLambdaOptions) (*policy.Request, error) { + urlPath := "/special-words/models/lambda" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithNot - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithNotOptions contains the optional parameters for the SpecialWordsModelsClient.WithNot +// method. +func (client *SpecialWordsModelsClient) WithNot(ctx context.Context, body Not, options *SpecialWordsModelsClientWithNotOptions) (SpecialWordsModelsClientWithNotResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithNot" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withNotCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithNotResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithNotResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithNotResponse{}, err + } + return SpecialWordsModelsClientWithNotResponse{}, nil +} + +// withNotCreateRequest creates the WithNot request. +func (client *SpecialWordsModelsClient) withNotCreateRequest(ctx context.Context, body Not, _ *SpecialWordsModelsClientWithNotOptions) (*policy.Request, error) { + urlPath := "/special-words/models/not" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithOr - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithOrOptions contains the optional parameters for the SpecialWordsModelsClient.WithOr +// method. +func (client *SpecialWordsModelsClient) WithOr(ctx context.Context, body Or, options *SpecialWordsModelsClientWithOrOptions) (SpecialWordsModelsClientWithOrResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithOr" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withOrCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithOrResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithOrResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithOrResponse{}, err + } + return SpecialWordsModelsClientWithOrResponse{}, nil +} + +// withOrCreateRequest creates the WithOr request. +func (client *SpecialWordsModelsClient) withOrCreateRequest(ctx context.Context, body Or, _ *SpecialWordsModelsClientWithOrOptions) (*policy.Request, error) { + urlPath := "/special-words/models/or" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithPass - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithPassOptions contains the optional parameters for the SpecialWordsModelsClient.WithPass +// method. +func (client *SpecialWordsModelsClient) WithPass(ctx context.Context, body Pass, options *SpecialWordsModelsClientWithPassOptions) (SpecialWordsModelsClientWithPassResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithPass" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withPassCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithPassResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithPassResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithPassResponse{}, err + } + return SpecialWordsModelsClientWithPassResponse{}, nil +} + +// withPassCreateRequest creates the WithPass request. +func (client *SpecialWordsModelsClient) withPassCreateRequest(ctx context.Context, body Pass, _ *SpecialWordsModelsClientWithPassOptions) (*policy.Request, error) { + urlPath := "/special-words/models/pass" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithRaise - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithRaiseOptions contains the optional parameters for the SpecialWordsModelsClient.WithRaise +// method. +func (client *SpecialWordsModelsClient) WithRaise(ctx context.Context, body Raise, options *SpecialWordsModelsClientWithRaiseOptions) (SpecialWordsModelsClientWithRaiseResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithRaise" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withRaiseCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithRaiseResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithRaiseResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithRaiseResponse{}, err + } + return SpecialWordsModelsClientWithRaiseResponse{}, nil +} + +// withRaiseCreateRequest creates the WithRaise request. +func (client *SpecialWordsModelsClient) withRaiseCreateRequest(ctx context.Context, body Raise, _ *SpecialWordsModelsClientWithRaiseOptions) (*policy.Request, error) { + urlPath := "/special-words/models/raise" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithReturn - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithReturnOptions contains the optional parameters for the SpecialWordsModelsClient.WithReturn +// method. +func (client *SpecialWordsModelsClient) WithReturn(ctx context.Context, body Return, options *SpecialWordsModelsClientWithReturnOptions) (SpecialWordsModelsClientWithReturnResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithReturn" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withReturnCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithReturnResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithReturnResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithReturnResponse{}, err + } + return SpecialWordsModelsClientWithReturnResponse{}, nil +} + +// withReturnCreateRequest creates the WithReturn request. +func (client *SpecialWordsModelsClient) withReturnCreateRequest(ctx context.Context, body Return, _ *SpecialWordsModelsClientWithReturnOptions) (*policy.Request, error) { + urlPath := "/special-words/models/return" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithTry - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithTryOptions contains the optional parameters for the SpecialWordsModelsClient.WithTry +// method. +func (client *SpecialWordsModelsClient) WithTry(ctx context.Context, body Try, options *SpecialWordsModelsClientWithTryOptions) (SpecialWordsModelsClientWithTryResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithTry" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withTryCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithTryResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithTryResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithTryResponse{}, err + } + return SpecialWordsModelsClientWithTryResponse{}, nil +} + +// withTryCreateRequest creates the WithTry request. +func (client *SpecialWordsModelsClient) withTryCreateRequest(ctx context.Context, body Try, _ *SpecialWordsModelsClientWithTryOptions) (*policy.Request, error) { + urlPath := "/special-words/models/try" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithWhile - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithWhileOptions contains the optional parameters for the SpecialWordsModelsClient.WithWhile +// method. +func (client *SpecialWordsModelsClient) WithWhile(ctx context.Context, body While, options *SpecialWordsModelsClientWithWhileOptions) (SpecialWordsModelsClientWithWhileResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithWhile" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withWhileCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithWhileResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithWhileResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithWhileResponse{}, err + } + return SpecialWordsModelsClientWithWhileResponse{}, nil +} + +// withWhileCreateRequest creates the WithWhile request. +func (client *SpecialWordsModelsClient) withWhileCreateRequest(ctx context.Context, body While, _ *SpecialWordsModelsClientWithWhileOptions) (*policy.Request, error) { + urlPath := "/special-words/models/while" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithWith - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithWithOptions contains the optional parameters for the SpecialWordsModelsClient.WithWith +// method. +func (client *SpecialWordsModelsClient) WithWith(ctx context.Context, body With, options *SpecialWordsModelsClientWithWithOptions) (SpecialWordsModelsClientWithWithResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithWith" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withWithCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithWithResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithWithResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithWithResponse{}, err + } + return SpecialWordsModelsClientWithWithResponse{}, nil +} + +// withWithCreateRequest creates the WithWith request. +func (client *SpecialWordsModelsClient) withWithCreateRequest(ctx context.Context, body With, _ *SpecialWordsModelsClientWithWithOptions) (*policy.Request, error) { + urlPath := "/special-words/models/with" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithYield - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsModelsClientWithYieldOptions contains the optional parameters for the SpecialWordsModelsClient.WithYield +// method. +func (client *SpecialWordsModelsClient) WithYield(ctx context.Context, body Yield, options *SpecialWordsModelsClientWithYieldOptions) (SpecialWordsModelsClientWithYieldResponse, error) { + var err error + const operationName = "SpecialWordsModelsClient.WithYield" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withYieldCreateRequest(ctx, body, options) + if err != nil { + return SpecialWordsModelsClientWithYieldResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsModelsClientWithYieldResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsModelsClientWithYieldResponse{}, err + } + return SpecialWordsModelsClientWithYieldResponse{}, nil +} + +// withYieldCreateRequest creates the WithYield request. +func (client *SpecialWordsModelsClient) withYieldCreateRequest(ctx context.Context, body Yield, _ *SpecialWordsModelsClientWithYieldOptions) (*policy.Request, error) { + urlPath := "/special-words/models/yield" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/specialwordsgroup/zz_specialwordsoperations_client.go b/test/http-specs/specialwordsgroup/zz_specialwordsoperations_client.go new file mode 100644 index 000000000000..afe59be18c14 --- /dev/null +++ b/test/http-specs/specialwordsgroup/zz_specialwordsoperations_client.go @@ -0,0 +1,1175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package specialwordsgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// SpecialWordsOperationsClient - Test reserved words as operation name. +// Don't use this type directly, use [SpecialWordsClient.NewSpecialWordsOperationsClient] instead. +type SpecialWordsOperationsClient struct { + internal *azcore.Client + endpoint string +} + +// And - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientAndOptions contains the optional parameters for the SpecialWordsOperationsClient.And +// method. +func (client *SpecialWordsOperationsClient) And(ctx context.Context, options *SpecialWordsOperationsClientAndOptions) (SpecialWordsOperationsClientAndResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.And" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.andCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientAndResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientAndResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientAndResponse{}, err + } + return SpecialWordsOperationsClientAndResponse{}, nil +} + +// andCreateRequest creates the And request. +func (client *SpecialWordsOperationsClient) andCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientAndOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/and" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// As - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientAsOptions contains the optional parameters for the SpecialWordsOperationsClient.As +// method. +func (client *SpecialWordsOperationsClient) As(ctx context.Context, options *SpecialWordsOperationsClientAsOptions) (SpecialWordsOperationsClientAsResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.As" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.asCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientAsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientAsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientAsResponse{}, err + } + return SpecialWordsOperationsClientAsResponse{}, nil +} + +// asCreateRequest creates the As request. +func (client *SpecialWordsOperationsClient) asCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientAsOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/as" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Assert - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientAssertOptions contains the optional parameters for the SpecialWordsOperationsClient.Assert +// method. +func (client *SpecialWordsOperationsClient) Assert(ctx context.Context, options *SpecialWordsOperationsClientAssertOptions) (SpecialWordsOperationsClientAssertResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.Assert" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.assertCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientAssertResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientAssertResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientAssertResponse{}, err + } + return SpecialWordsOperationsClientAssertResponse{}, nil +} + +// assertCreateRequest creates the Assert request. +func (client *SpecialWordsOperationsClient) assertCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientAssertOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/assert" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Async - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientAsyncOptions contains the optional parameters for the SpecialWordsOperationsClient.Async +// method. +func (client *SpecialWordsOperationsClient) Async(ctx context.Context, options *SpecialWordsOperationsClientAsyncOptions) (SpecialWordsOperationsClientAsyncResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.Async" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.asyncCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientAsyncResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientAsyncResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientAsyncResponse{}, err + } + return SpecialWordsOperationsClientAsyncResponse{}, nil +} + +// asyncCreateRequest creates the Async request. +func (client *SpecialWordsOperationsClient) asyncCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientAsyncOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/async" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Await - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientAwaitOptions contains the optional parameters for the SpecialWordsOperationsClient.Await +// method. +func (client *SpecialWordsOperationsClient) Await(ctx context.Context, options *SpecialWordsOperationsClientAwaitOptions) (SpecialWordsOperationsClientAwaitResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.Await" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.awaitCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientAwaitResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientAwaitResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientAwaitResponse{}, err + } + return SpecialWordsOperationsClientAwaitResponse{}, nil +} + +// awaitCreateRequest creates the Await request. +func (client *SpecialWordsOperationsClient) awaitCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientAwaitOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/await" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Break - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientBreakOptions contains the optional parameters for the SpecialWordsOperationsClient.Break +// method. +func (client *SpecialWordsOperationsClient) Break(ctx context.Context, options *SpecialWordsOperationsClientBreakOptions) (SpecialWordsOperationsClientBreakResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.Break" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.breakCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientBreakResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientBreakResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientBreakResponse{}, err + } + return SpecialWordsOperationsClientBreakResponse{}, nil +} + +// breakCreateRequest creates the Break request. +func (client *SpecialWordsOperationsClient) breakCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientBreakOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/break" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Class - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientClassOptions contains the optional parameters for the SpecialWordsOperationsClient.Class +// method. +func (client *SpecialWordsOperationsClient) Class(ctx context.Context, options *SpecialWordsOperationsClientClassOptions) (SpecialWordsOperationsClientClassResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.Class" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.classCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientClassResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientClassResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientClassResponse{}, err + } + return SpecialWordsOperationsClientClassResponse{}, nil +} + +// classCreateRequest creates the Class request. +func (client *SpecialWordsOperationsClient) classCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientClassOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/class" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Constructor - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientConstructorOptions contains the optional parameters for the SpecialWordsOperationsClient.Constructor +// method. +func (client *SpecialWordsOperationsClient) Constructor(ctx context.Context, options *SpecialWordsOperationsClientConstructorOptions) (SpecialWordsOperationsClientConstructorResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.Constructor" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.constructorCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientConstructorResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientConstructorResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientConstructorResponse{}, err + } + return SpecialWordsOperationsClientConstructorResponse{}, nil +} + +// constructorCreateRequest creates the Constructor request. +func (client *SpecialWordsOperationsClient) constructorCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientConstructorOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/constructor" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Continue - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientContinueOptions contains the optional parameters for the SpecialWordsOperationsClient.Continue +// method. +func (client *SpecialWordsOperationsClient) Continue(ctx context.Context, options *SpecialWordsOperationsClientContinueOptions) (SpecialWordsOperationsClientContinueResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.Continue" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.continueCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientContinueResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientContinueResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientContinueResponse{}, err + } + return SpecialWordsOperationsClientContinueResponse{}, nil +} + +// continueCreateRequest creates the Continue request. +func (client *SpecialWordsOperationsClient) continueCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientContinueOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/continue" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Def - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientDefOptions contains the optional parameters for the SpecialWordsOperationsClient.Def +// method. +func (client *SpecialWordsOperationsClient) Def(ctx context.Context, options *SpecialWordsOperationsClientDefOptions) (SpecialWordsOperationsClientDefResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.Def" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.defCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientDefResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientDefResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientDefResponse{}, err + } + return SpecialWordsOperationsClientDefResponse{}, nil +} + +// defCreateRequest creates the Def request. +func (client *SpecialWordsOperationsClient) defCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientDefOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/def" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Del - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientDelOptions contains the optional parameters for the SpecialWordsOperationsClient.Del +// method. +func (client *SpecialWordsOperationsClient) Del(ctx context.Context, options *SpecialWordsOperationsClientDelOptions) (SpecialWordsOperationsClientDelResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.Del" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.delCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientDelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientDelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientDelResponse{}, err + } + return SpecialWordsOperationsClientDelResponse{}, nil +} + +// delCreateRequest creates the Del request. +func (client *SpecialWordsOperationsClient) delCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientDelOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/del" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Elif - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientElifOptions contains the optional parameters for the SpecialWordsOperationsClient.Elif +// method. +func (client *SpecialWordsOperationsClient) Elif(ctx context.Context, options *SpecialWordsOperationsClientElifOptions) (SpecialWordsOperationsClientElifResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.Elif" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.elifCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientElifResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientElifResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientElifResponse{}, err + } + return SpecialWordsOperationsClientElifResponse{}, nil +} + +// elifCreateRequest creates the Elif request. +func (client *SpecialWordsOperationsClient) elifCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientElifOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/elif" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Else - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientElseOptions contains the optional parameters for the SpecialWordsOperationsClient.Else +// method. +func (client *SpecialWordsOperationsClient) Else(ctx context.Context, options *SpecialWordsOperationsClientElseOptions) (SpecialWordsOperationsClientElseResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.Else" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.elseCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientElseResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientElseResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientElseResponse{}, err + } + return SpecialWordsOperationsClientElseResponse{}, nil +} + +// elseCreateRequest creates the Else request. +func (client *SpecialWordsOperationsClient) elseCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientElseOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/else" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Except - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientExceptOptions contains the optional parameters for the SpecialWordsOperationsClient.Except +// method. +func (client *SpecialWordsOperationsClient) Except(ctx context.Context, options *SpecialWordsOperationsClientExceptOptions) (SpecialWordsOperationsClientExceptResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.Except" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.exceptCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientExceptResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientExceptResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientExceptResponse{}, err + } + return SpecialWordsOperationsClientExceptResponse{}, nil +} + +// exceptCreateRequest creates the Except request. +func (client *SpecialWordsOperationsClient) exceptCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientExceptOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/except" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Exec - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientExecOptions contains the optional parameters for the SpecialWordsOperationsClient.Exec +// method. +func (client *SpecialWordsOperationsClient) Exec(ctx context.Context, options *SpecialWordsOperationsClientExecOptions) (SpecialWordsOperationsClientExecResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.Exec" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.execCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientExecResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientExecResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientExecResponse{}, err + } + return SpecialWordsOperationsClientExecResponse{}, nil +} + +// execCreateRequest creates the Exec request. +func (client *SpecialWordsOperationsClient) execCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientExecOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/exec" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Finally - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientFinallyOptions contains the optional parameters for the SpecialWordsOperationsClient.Finally +// method. +func (client *SpecialWordsOperationsClient) Finally(ctx context.Context, options *SpecialWordsOperationsClientFinallyOptions) (SpecialWordsOperationsClientFinallyResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.Finally" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.finallyCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientFinallyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientFinallyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientFinallyResponse{}, err + } + return SpecialWordsOperationsClientFinallyResponse{}, nil +} + +// finallyCreateRequest creates the Finally request. +func (client *SpecialWordsOperationsClient) finallyCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientFinallyOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/finally" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// For - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientForOptions contains the optional parameters for the SpecialWordsOperationsClient.For +// method. +func (client *SpecialWordsOperationsClient) For(ctx context.Context, options *SpecialWordsOperationsClientForOptions) (SpecialWordsOperationsClientForResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.For" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.forCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientForResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientForResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientForResponse{}, err + } + return SpecialWordsOperationsClientForResponse{}, nil +} + +// forCreateRequest creates the For request. +func (client *SpecialWordsOperationsClient) forCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientForOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/for" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// From - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientFromOptions contains the optional parameters for the SpecialWordsOperationsClient.From +// method. +func (client *SpecialWordsOperationsClient) From(ctx context.Context, options *SpecialWordsOperationsClientFromOptions) (SpecialWordsOperationsClientFromResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.From" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.fromCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientFromResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientFromResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientFromResponse{}, err + } + return SpecialWordsOperationsClientFromResponse{}, nil +} + +// fromCreateRequest creates the From request. +func (client *SpecialWordsOperationsClient) fromCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientFromOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/from" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Global - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientGlobalOptions contains the optional parameters for the SpecialWordsOperationsClient.Global +// method. +func (client *SpecialWordsOperationsClient) Global(ctx context.Context, options *SpecialWordsOperationsClientGlobalOptions) (SpecialWordsOperationsClientGlobalResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.Global" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.globalCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientGlobalResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientGlobalResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientGlobalResponse{}, err + } + return SpecialWordsOperationsClientGlobalResponse{}, nil +} + +// globalCreateRequest creates the Global request. +func (client *SpecialWordsOperationsClient) globalCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientGlobalOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/global" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// If - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientIfOptions contains the optional parameters for the SpecialWordsOperationsClient.If +// method. +func (client *SpecialWordsOperationsClient) If(ctx context.Context, options *SpecialWordsOperationsClientIfOptions) (SpecialWordsOperationsClientIfResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.If" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.ifCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientIfResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientIfResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientIfResponse{}, err + } + return SpecialWordsOperationsClientIfResponse{}, nil +} + +// ifCreateRequest creates the If request. +func (client *SpecialWordsOperationsClient) ifCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientIfOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/if" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Import - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientImportOptions contains the optional parameters for the SpecialWordsOperationsClient.Import +// method. +func (client *SpecialWordsOperationsClient) Import(ctx context.Context, options *SpecialWordsOperationsClientImportOptions) (SpecialWordsOperationsClientImportResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.Import" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.importCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientImportResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientImportResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientImportResponse{}, err + } + return SpecialWordsOperationsClientImportResponse{}, nil +} + +// importCreateRequest creates the Import request. +func (client *SpecialWordsOperationsClient) importCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientImportOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/import" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// In - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientInOptions contains the optional parameters for the SpecialWordsOperationsClient.In +// method. +func (client *SpecialWordsOperationsClient) In(ctx context.Context, options *SpecialWordsOperationsClientInOptions) (SpecialWordsOperationsClientInResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.In" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.inCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientInResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientInResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientInResponse{}, err + } + return SpecialWordsOperationsClientInResponse{}, nil +} + +// inCreateRequest creates the In request. +func (client *SpecialWordsOperationsClient) inCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientInOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/in" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Is - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientIsOptions contains the optional parameters for the SpecialWordsOperationsClient.Is +// method. +func (client *SpecialWordsOperationsClient) Is(ctx context.Context, options *SpecialWordsOperationsClientIsOptions) (SpecialWordsOperationsClientIsResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.Is" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.isCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientIsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientIsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientIsResponse{}, err + } + return SpecialWordsOperationsClientIsResponse{}, nil +} + +// isCreateRequest creates the Is request. +func (client *SpecialWordsOperationsClient) isCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientIsOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/is" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Lambda - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientLambdaOptions contains the optional parameters for the SpecialWordsOperationsClient.Lambda +// method. +func (client *SpecialWordsOperationsClient) Lambda(ctx context.Context, options *SpecialWordsOperationsClientLambdaOptions) (SpecialWordsOperationsClientLambdaResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.Lambda" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.lambdaCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientLambdaResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientLambdaResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientLambdaResponse{}, err + } + return SpecialWordsOperationsClientLambdaResponse{}, nil +} + +// lambdaCreateRequest creates the Lambda request. +func (client *SpecialWordsOperationsClient) lambdaCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientLambdaOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/lambda" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Not - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientNotOptions contains the optional parameters for the SpecialWordsOperationsClient.Not +// method. +func (client *SpecialWordsOperationsClient) Not(ctx context.Context, options *SpecialWordsOperationsClientNotOptions) (SpecialWordsOperationsClientNotResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.Not" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.notCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientNotResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientNotResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientNotResponse{}, err + } + return SpecialWordsOperationsClientNotResponse{}, nil +} + +// notCreateRequest creates the Not request. +func (client *SpecialWordsOperationsClient) notCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientNotOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/not" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Or - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientOrOptions contains the optional parameters for the SpecialWordsOperationsClient.Or +// method. +func (client *SpecialWordsOperationsClient) Or(ctx context.Context, options *SpecialWordsOperationsClientOrOptions) (SpecialWordsOperationsClientOrResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.Or" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.orCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientOrResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientOrResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientOrResponse{}, err + } + return SpecialWordsOperationsClientOrResponse{}, nil +} + +// orCreateRequest creates the Or request. +func (client *SpecialWordsOperationsClient) orCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientOrOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/or" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Pass - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientPassOptions contains the optional parameters for the SpecialWordsOperationsClient.Pass +// method. +func (client *SpecialWordsOperationsClient) Pass(ctx context.Context, options *SpecialWordsOperationsClientPassOptions) (SpecialWordsOperationsClientPassResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.Pass" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.passCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientPassResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientPassResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientPassResponse{}, err + } + return SpecialWordsOperationsClientPassResponse{}, nil +} + +// passCreateRequest creates the Pass request. +func (client *SpecialWordsOperationsClient) passCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientPassOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/pass" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Raise - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientRaiseOptions contains the optional parameters for the SpecialWordsOperationsClient.Raise +// method. +func (client *SpecialWordsOperationsClient) Raise(ctx context.Context, options *SpecialWordsOperationsClientRaiseOptions) (SpecialWordsOperationsClientRaiseResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.Raise" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.raiseCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientRaiseResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientRaiseResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientRaiseResponse{}, err + } + return SpecialWordsOperationsClientRaiseResponse{}, nil +} + +// raiseCreateRequest creates the Raise request. +func (client *SpecialWordsOperationsClient) raiseCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientRaiseOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/raise" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Return - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientReturnOptions contains the optional parameters for the SpecialWordsOperationsClient.Return +// method. +func (client *SpecialWordsOperationsClient) Return(ctx context.Context, options *SpecialWordsOperationsClientReturnOptions) (SpecialWordsOperationsClientReturnResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.Return" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.returnCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientReturnResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientReturnResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientReturnResponse{}, err + } + return SpecialWordsOperationsClientReturnResponse{}, nil +} + +// returnCreateRequest creates the Return request. +func (client *SpecialWordsOperationsClient) returnCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientReturnOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/return" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Try - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientTryOptions contains the optional parameters for the SpecialWordsOperationsClient.Try +// method. +func (client *SpecialWordsOperationsClient) Try(ctx context.Context, options *SpecialWordsOperationsClientTryOptions) (SpecialWordsOperationsClientTryResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.Try" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.tryCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientTryResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientTryResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientTryResponse{}, err + } + return SpecialWordsOperationsClientTryResponse{}, nil +} + +// tryCreateRequest creates the Try request. +func (client *SpecialWordsOperationsClient) tryCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientTryOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/try" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// While - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientWhileOptions contains the optional parameters for the SpecialWordsOperationsClient.While +// method. +func (client *SpecialWordsOperationsClient) While(ctx context.Context, options *SpecialWordsOperationsClientWhileOptions) (SpecialWordsOperationsClientWhileResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.While" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.whileCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientWhileResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientWhileResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientWhileResponse{}, err + } + return SpecialWordsOperationsClientWhileResponse{}, nil +} + +// whileCreateRequest creates the While request. +func (client *SpecialWordsOperationsClient) whileCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientWhileOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/while" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// With - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientWithOptions contains the optional parameters for the SpecialWordsOperationsClient.With +// method. +func (client *SpecialWordsOperationsClient) With(ctx context.Context, options *SpecialWordsOperationsClientWithOptions) (SpecialWordsOperationsClientWithResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.With" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientWithResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientWithResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientWithResponse{}, err + } + return SpecialWordsOperationsClientWithResponse{}, nil +} + +// withCreateRequest creates the With request. +func (client *SpecialWordsOperationsClient) withCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientWithOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/with" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// Yield - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsOperationsClientYieldOptions contains the optional parameters for the SpecialWordsOperationsClient.Yield +// method. +func (client *SpecialWordsOperationsClient) Yield(ctx context.Context, options *SpecialWordsOperationsClientYieldOptions) (SpecialWordsOperationsClientYieldResponse, error) { + var err error + const operationName = "SpecialWordsOperationsClient.Yield" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.yieldCreateRequest(ctx, options) + if err != nil { + return SpecialWordsOperationsClientYieldResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsOperationsClientYieldResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsOperationsClientYieldResponse{}, err + } + return SpecialWordsOperationsClientYieldResponse{}, nil +} + +// yieldCreateRequest creates the Yield request. +func (client *SpecialWordsOperationsClient) yieldCreateRequest(ctx context.Context, _ *SpecialWordsOperationsClientYieldOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/yield" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/specialwordsgroup/zz_specialwordsparameters_client.go b/test/http-specs/specialwordsgroup/zz_specialwordsparameters_client.go new file mode 100644 index 000000000000..c600cc84af09 --- /dev/null +++ b/test/http-specs/specialwordsgroup/zz_specialwordsparameters_client.go @@ -0,0 +1,1313 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package specialwordsgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// SpecialWordsParametersClient - Verify reserved words as parameter name. +// Don't use this type directly, use [SpecialWordsClient.NewSpecialWordsParametersClient] instead. +type SpecialWordsParametersClient struct { + internal *azcore.Client + endpoint string +} + +// WithAnd - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithAndOptions contains the optional parameters for the SpecialWordsParametersClient.WithAnd +// method. +func (client *SpecialWordsParametersClient) WithAnd(ctx context.Context, and string, options *SpecialWordsParametersClientWithAndOptions) (SpecialWordsParametersClientWithAndResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithAnd" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withAndCreateRequest(ctx, and, options) + if err != nil { + return SpecialWordsParametersClientWithAndResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithAndResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithAndResponse{}, err + } + return SpecialWordsParametersClientWithAndResponse{}, nil +} + +// withAndCreateRequest creates the WithAnd request. +func (client *SpecialWordsParametersClient) withAndCreateRequest(ctx context.Context, and string, _ *SpecialWordsParametersClientWithAndOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/and" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("and", and) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithAs - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithAsOptions contains the optional parameters for the SpecialWordsParametersClient.WithAs +// method. +func (client *SpecialWordsParametersClient) WithAs(ctx context.Context, as string, options *SpecialWordsParametersClientWithAsOptions) (SpecialWordsParametersClientWithAsResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithAs" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withAsCreateRequest(ctx, as, options) + if err != nil { + return SpecialWordsParametersClientWithAsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithAsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithAsResponse{}, err + } + return SpecialWordsParametersClientWithAsResponse{}, nil +} + +// withAsCreateRequest creates the WithAs request. +func (client *SpecialWordsParametersClient) withAsCreateRequest(ctx context.Context, as string, _ *SpecialWordsParametersClientWithAsOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/as" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("as", as) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithAssert - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithAssertOptions contains the optional parameters for the SpecialWordsParametersClient.WithAssert +// method. +func (client *SpecialWordsParametersClient) WithAssert(ctx context.Context, assert string, options *SpecialWordsParametersClientWithAssertOptions) (SpecialWordsParametersClientWithAssertResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithAssert" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withAssertCreateRequest(ctx, assert, options) + if err != nil { + return SpecialWordsParametersClientWithAssertResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithAssertResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithAssertResponse{}, err + } + return SpecialWordsParametersClientWithAssertResponse{}, nil +} + +// withAssertCreateRequest creates the WithAssert request. +func (client *SpecialWordsParametersClient) withAssertCreateRequest(ctx context.Context, assert string, _ *SpecialWordsParametersClientWithAssertOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/assert" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("assert", assert) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithAsync - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithAsyncOptions contains the optional parameters for the SpecialWordsParametersClient.WithAsync +// method. +func (client *SpecialWordsParametersClient) WithAsync(ctx context.Context, async string, options *SpecialWordsParametersClientWithAsyncOptions) (SpecialWordsParametersClientWithAsyncResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithAsync" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withAsyncCreateRequest(ctx, async, options) + if err != nil { + return SpecialWordsParametersClientWithAsyncResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithAsyncResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithAsyncResponse{}, err + } + return SpecialWordsParametersClientWithAsyncResponse{}, nil +} + +// withAsyncCreateRequest creates the WithAsync request. +func (client *SpecialWordsParametersClient) withAsyncCreateRequest(ctx context.Context, async string, _ *SpecialWordsParametersClientWithAsyncOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/async" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("async", async) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithAwait - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithAwaitOptions contains the optional parameters for the SpecialWordsParametersClient.WithAwait +// method. +func (client *SpecialWordsParametersClient) WithAwait(ctx context.Context, await string, options *SpecialWordsParametersClientWithAwaitOptions) (SpecialWordsParametersClientWithAwaitResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithAwait" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withAwaitCreateRequest(ctx, await, options) + if err != nil { + return SpecialWordsParametersClientWithAwaitResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithAwaitResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithAwaitResponse{}, err + } + return SpecialWordsParametersClientWithAwaitResponse{}, nil +} + +// withAwaitCreateRequest creates the WithAwait request. +func (client *SpecialWordsParametersClient) withAwaitCreateRequest(ctx context.Context, await string, _ *SpecialWordsParametersClientWithAwaitOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/await" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("await", await) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithBreak - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithBreakOptions contains the optional parameters for the SpecialWordsParametersClient.WithBreak +// method. +func (client *SpecialWordsParametersClient) WithBreak(ctx context.Context, breakParam string, options *SpecialWordsParametersClientWithBreakOptions) (SpecialWordsParametersClientWithBreakResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithBreak" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withBreakCreateRequest(ctx, breakParam, options) + if err != nil { + return SpecialWordsParametersClientWithBreakResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithBreakResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithBreakResponse{}, err + } + return SpecialWordsParametersClientWithBreakResponse{}, nil +} + +// withBreakCreateRequest creates the WithBreak request. +func (client *SpecialWordsParametersClient) withBreakCreateRequest(ctx context.Context, breakParam string, _ *SpecialWordsParametersClientWithBreakOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/break" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("break", breakParam) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithCancellationToken - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithCancellationTokenOptions contains the optional parameters for the SpecialWordsParametersClient.WithCancellationToken +// method. +func (client *SpecialWordsParametersClient) WithCancellationToken(ctx context.Context, cancellationToken string, options *SpecialWordsParametersClientWithCancellationTokenOptions) (SpecialWordsParametersClientWithCancellationTokenResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithCancellationToken" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withCancellationTokenCreateRequest(ctx, cancellationToken, options) + if err != nil { + return SpecialWordsParametersClientWithCancellationTokenResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithCancellationTokenResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithCancellationTokenResponse{}, err + } + return SpecialWordsParametersClientWithCancellationTokenResponse{}, nil +} + +// withCancellationTokenCreateRequest creates the WithCancellationToken request. +func (client *SpecialWordsParametersClient) withCancellationTokenCreateRequest(ctx context.Context, cancellationToken string, _ *SpecialWordsParametersClientWithCancellationTokenOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/cancellationToken" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("cancellationToken", cancellationToken) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithClass - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithClassOptions contains the optional parameters for the SpecialWordsParametersClient.WithClass +// method. +func (client *SpecialWordsParametersClient) WithClass(ctx context.Context, class string, options *SpecialWordsParametersClientWithClassOptions) (SpecialWordsParametersClientWithClassResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithClass" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withClassCreateRequest(ctx, class, options) + if err != nil { + return SpecialWordsParametersClientWithClassResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithClassResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithClassResponse{}, err + } + return SpecialWordsParametersClientWithClassResponse{}, nil +} + +// withClassCreateRequest creates the WithClass request. +func (client *SpecialWordsParametersClient) withClassCreateRequest(ctx context.Context, class string, _ *SpecialWordsParametersClientWithClassOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/class" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("class", class) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithConstructor - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithConstructorOptions contains the optional parameters for the SpecialWordsParametersClient.WithConstructor +// method. +func (client *SpecialWordsParametersClient) WithConstructor(ctx context.Context, constructor string, options *SpecialWordsParametersClientWithConstructorOptions) (SpecialWordsParametersClientWithConstructorResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithConstructor" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withConstructorCreateRequest(ctx, constructor, options) + if err != nil { + return SpecialWordsParametersClientWithConstructorResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithConstructorResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithConstructorResponse{}, err + } + return SpecialWordsParametersClientWithConstructorResponse{}, nil +} + +// withConstructorCreateRequest creates the WithConstructor request. +func (client *SpecialWordsParametersClient) withConstructorCreateRequest(ctx context.Context, constructor string, _ *SpecialWordsParametersClientWithConstructorOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/constructor" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("constructor", constructor) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithContinue - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithContinueOptions contains the optional parameters for the SpecialWordsParametersClient.WithContinue +// method. +func (client *SpecialWordsParametersClient) WithContinue(ctx context.Context, continueParam string, options *SpecialWordsParametersClientWithContinueOptions) (SpecialWordsParametersClientWithContinueResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithContinue" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withContinueCreateRequest(ctx, continueParam, options) + if err != nil { + return SpecialWordsParametersClientWithContinueResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithContinueResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithContinueResponse{}, err + } + return SpecialWordsParametersClientWithContinueResponse{}, nil +} + +// withContinueCreateRequest creates the WithContinue request. +func (client *SpecialWordsParametersClient) withContinueCreateRequest(ctx context.Context, continueParam string, _ *SpecialWordsParametersClientWithContinueOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/continue" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("continue", continueParam) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithDef - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithDefOptions contains the optional parameters for the SpecialWordsParametersClient.WithDef +// method. +func (client *SpecialWordsParametersClient) WithDef(ctx context.Context, def string, options *SpecialWordsParametersClientWithDefOptions) (SpecialWordsParametersClientWithDefResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithDef" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withDefCreateRequest(ctx, def, options) + if err != nil { + return SpecialWordsParametersClientWithDefResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithDefResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithDefResponse{}, err + } + return SpecialWordsParametersClientWithDefResponse{}, nil +} + +// withDefCreateRequest creates the WithDef request. +func (client *SpecialWordsParametersClient) withDefCreateRequest(ctx context.Context, def string, _ *SpecialWordsParametersClientWithDefOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/def" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("def", def) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithDel - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithDelOptions contains the optional parameters for the SpecialWordsParametersClient.WithDel +// method. +func (client *SpecialWordsParametersClient) WithDel(ctx context.Context, del string, options *SpecialWordsParametersClientWithDelOptions) (SpecialWordsParametersClientWithDelResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithDel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withDelCreateRequest(ctx, del, options) + if err != nil { + return SpecialWordsParametersClientWithDelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithDelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithDelResponse{}, err + } + return SpecialWordsParametersClientWithDelResponse{}, nil +} + +// withDelCreateRequest creates the WithDel request. +func (client *SpecialWordsParametersClient) withDelCreateRequest(ctx context.Context, del string, _ *SpecialWordsParametersClientWithDelOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/del" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("del", del) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithElif - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithElifOptions contains the optional parameters for the SpecialWordsParametersClient.WithElif +// method. +func (client *SpecialWordsParametersClient) WithElif(ctx context.Context, elif string, options *SpecialWordsParametersClientWithElifOptions) (SpecialWordsParametersClientWithElifResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithElif" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withElifCreateRequest(ctx, elif, options) + if err != nil { + return SpecialWordsParametersClientWithElifResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithElifResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithElifResponse{}, err + } + return SpecialWordsParametersClientWithElifResponse{}, nil +} + +// withElifCreateRequest creates the WithElif request. +func (client *SpecialWordsParametersClient) withElifCreateRequest(ctx context.Context, elif string, _ *SpecialWordsParametersClientWithElifOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/elif" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("elif", elif) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithElse - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithElseOptions contains the optional parameters for the SpecialWordsParametersClient.WithElse +// method. +func (client *SpecialWordsParametersClient) WithElse(ctx context.Context, elseParam string, options *SpecialWordsParametersClientWithElseOptions) (SpecialWordsParametersClientWithElseResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithElse" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withElseCreateRequest(ctx, elseParam, options) + if err != nil { + return SpecialWordsParametersClientWithElseResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithElseResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithElseResponse{}, err + } + return SpecialWordsParametersClientWithElseResponse{}, nil +} + +// withElseCreateRequest creates the WithElse request. +func (client *SpecialWordsParametersClient) withElseCreateRequest(ctx context.Context, elseParam string, _ *SpecialWordsParametersClientWithElseOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/else" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("else", elseParam) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithExcept - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithExceptOptions contains the optional parameters for the SpecialWordsParametersClient.WithExcept +// method. +func (client *SpecialWordsParametersClient) WithExcept(ctx context.Context, except string, options *SpecialWordsParametersClientWithExceptOptions) (SpecialWordsParametersClientWithExceptResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithExcept" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withExceptCreateRequest(ctx, except, options) + if err != nil { + return SpecialWordsParametersClientWithExceptResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithExceptResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithExceptResponse{}, err + } + return SpecialWordsParametersClientWithExceptResponse{}, nil +} + +// withExceptCreateRequest creates the WithExcept request. +func (client *SpecialWordsParametersClient) withExceptCreateRequest(ctx context.Context, except string, _ *SpecialWordsParametersClientWithExceptOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/except" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("except", except) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithExec - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithExecOptions contains the optional parameters for the SpecialWordsParametersClient.WithExec +// method. +func (client *SpecialWordsParametersClient) WithExec(ctx context.Context, execParam string, options *SpecialWordsParametersClientWithExecOptions) (SpecialWordsParametersClientWithExecResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithExec" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withExecCreateRequest(ctx, execParam, options) + if err != nil { + return SpecialWordsParametersClientWithExecResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithExecResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithExecResponse{}, err + } + return SpecialWordsParametersClientWithExecResponse{}, nil +} + +// withExecCreateRequest creates the WithExec request. +func (client *SpecialWordsParametersClient) withExecCreateRequest(ctx context.Context, execParam string, _ *SpecialWordsParametersClientWithExecOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/exec" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("exec", execParam) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithFinally - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithFinallyOptions contains the optional parameters for the SpecialWordsParametersClient.WithFinally +// method. +func (client *SpecialWordsParametersClient) WithFinally(ctx context.Context, finally string, options *SpecialWordsParametersClientWithFinallyOptions) (SpecialWordsParametersClientWithFinallyResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithFinally" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withFinallyCreateRequest(ctx, finally, options) + if err != nil { + return SpecialWordsParametersClientWithFinallyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithFinallyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithFinallyResponse{}, err + } + return SpecialWordsParametersClientWithFinallyResponse{}, nil +} + +// withFinallyCreateRequest creates the WithFinally request. +func (client *SpecialWordsParametersClient) withFinallyCreateRequest(ctx context.Context, finally string, _ *SpecialWordsParametersClientWithFinallyOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/finally" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("finally", finally) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithFor - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithForOptions contains the optional parameters for the SpecialWordsParametersClient.WithFor +// method. +func (client *SpecialWordsParametersClient) WithFor(ctx context.Context, forParam string, options *SpecialWordsParametersClientWithForOptions) (SpecialWordsParametersClientWithForResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithFor" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withForCreateRequest(ctx, forParam, options) + if err != nil { + return SpecialWordsParametersClientWithForResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithForResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithForResponse{}, err + } + return SpecialWordsParametersClientWithForResponse{}, nil +} + +// withForCreateRequest creates the WithFor request. +func (client *SpecialWordsParametersClient) withForCreateRequest(ctx context.Context, forParam string, _ *SpecialWordsParametersClientWithForOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/for" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("for", forParam) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithFrom - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithFromOptions contains the optional parameters for the SpecialWordsParametersClient.WithFrom +// method. +func (client *SpecialWordsParametersClient) WithFrom(ctx context.Context, from string, options *SpecialWordsParametersClientWithFromOptions) (SpecialWordsParametersClientWithFromResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithFrom" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withFromCreateRequest(ctx, from, options) + if err != nil { + return SpecialWordsParametersClientWithFromResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithFromResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithFromResponse{}, err + } + return SpecialWordsParametersClientWithFromResponse{}, nil +} + +// withFromCreateRequest creates the WithFrom request. +func (client *SpecialWordsParametersClient) withFromCreateRequest(ctx context.Context, from string, _ *SpecialWordsParametersClientWithFromOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/from" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("from", from) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithGlobal - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithGlobalOptions contains the optional parameters for the SpecialWordsParametersClient.WithGlobal +// method. +func (client *SpecialWordsParametersClient) WithGlobal(ctx context.Context, global string, options *SpecialWordsParametersClientWithGlobalOptions) (SpecialWordsParametersClientWithGlobalResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithGlobal" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withGlobalCreateRequest(ctx, global, options) + if err != nil { + return SpecialWordsParametersClientWithGlobalResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithGlobalResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithGlobalResponse{}, err + } + return SpecialWordsParametersClientWithGlobalResponse{}, nil +} + +// withGlobalCreateRequest creates the WithGlobal request. +func (client *SpecialWordsParametersClient) withGlobalCreateRequest(ctx context.Context, global string, _ *SpecialWordsParametersClientWithGlobalOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/global" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("global", global) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithIf - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithIfOptions contains the optional parameters for the SpecialWordsParametersClient.WithIf +// method. +func (client *SpecialWordsParametersClient) WithIf(ctx context.Context, ifParam string, options *SpecialWordsParametersClientWithIfOptions) (SpecialWordsParametersClientWithIfResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithIf" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withIfCreateRequest(ctx, ifParam, options) + if err != nil { + return SpecialWordsParametersClientWithIfResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithIfResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithIfResponse{}, err + } + return SpecialWordsParametersClientWithIfResponse{}, nil +} + +// withIfCreateRequest creates the WithIf request. +func (client *SpecialWordsParametersClient) withIfCreateRequest(ctx context.Context, ifParam string, _ *SpecialWordsParametersClientWithIfOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/if" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("if", ifParam) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithImport - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithImportOptions contains the optional parameters for the SpecialWordsParametersClient.WithImport +// method. +func (client *SpecialWordsParametersClient) WithImport(ctx context.Context, importParam string, options *SpecialWordsParametersClientWithImportOptions) (SpecialWordsParametersClientWithImportResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithImport" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withImportCreateRequest(ctx, importParam, options) + if err != nil { + return SpecialWordsParametersClientWithImportResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithImportResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithImportResponse{}, err + } + return SpecialWordsParametersClientWithImportResponse{}, nil +} + +// withImportCreateRequest creates the WithImport request. +func (client *SpecialWordsParametersClient) withImportCreateRequest(ctx context.Context, importParam string, _ *SpecialWordsParametersClientWithImportOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/import" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("import", importParam) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithIn - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithInOptions contains the optional parameters for the SpecialWordsParametersClient.WithIn +// method. +func (client *SpecialWordsParametersClient) WithIn(ctx context.Context, in string, options *SpecialWordsParametersClientWithInOptions) (SpecialWordsParametersClientWithInResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithIn" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withInCreateRequest(ctx, in, options) + if err != nil { + return SpecialWordsParametersClientWithInResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithInResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithInResponse{}, err + } + return SpecialWordsParametersClientWithInResponse{}, nil +} + +// withInCreateRequest creates the WithIn request. +func (client *SpecialWordsParametersClient) withInCreateRequest(ctx context.Context, in string, _ *SpecialWordsParametersClientWithInOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/in" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("in", in) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithIs - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithIsOptions contains the optional parameters for the SpecialWordsParametersClient.WithIs +// method. +func (client *SpecialWordsParametersClient) WithIs(ctx context.Context, is string, options *SpecialWordsParametersClientWithIsOptions) (SpecialWordsParametersClientWithIsResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithIs" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withIsCreateRequest(ctx, is, options) + if err != nil { + return SpecialWordsParametersClientWithIsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithIsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithIsResponse{}, err + } + return SpecialWordsParametersClientWithIsResponse{}, nil +} + +// withIsCreateRequest creates the WithIs request. +func (client *SpecialWordsParametersClient) withIsCreateRequest(ctx context.Context, is string, _ *SpecialWordsParametersClientWithIsOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/is" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("is", is) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithLambda - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithLambdaOptions contains the optional parameters for the SpecialWordsParametersClient.WithLambda +// method. +func (client *SpecialWordsParametersClient) WithLambda(ctx context.Context, lambda string, options *SpecialWordsParametersClientWithLambdaOptions) (SpecialWordsParametersClientWithLambdaResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithLambda" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withLambdaCreateRequest(ctx, lambda, options) + if err != nil { + return SpecialWordsParametersClientWithLambdaResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithLambdaResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithLambdaResponse{}, err + } + return SpecialWordsParametersClientWithLambdaResponse{}, nil +} + +// withLambdaCreateRequest creates the WithLambda request. +func (client *SpecialWordsParametersClient) withLambdaCreateRequest(ctx context.Context, lambda string, _ *SpecialWordsParametersClientWithLambdaOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/lambda" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("lambda", lambda) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithNot - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithNotOptions contains the optional parameters for the SpecialWordsParametersClient.WithNot +// method. +func (client *SpecialWordsParametersClient) WithNot(ctx context.Context, not string, options *SpecialWordsParametersClientWithNotOptions) (SpecialWordsParametersClientWithNotResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithNot" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withNotCreateRequest(ctx, not, options) + if err != nil { + return SpecialWordsParametersClientWithNotResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithNotResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithNotResponse{}, err + } + return SpecialWordsParametersClientWithNotResponse{}, nil +} + +// withNotCreateRequest creates the WithNot request. +func (client *SpecialWordsParametersClient) withNotCreateRequest(ctx context.Context, not string, _ *SpecialWordsParametersClientWithNotOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/not" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("not", not) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithOr - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithOrOptions contains the optional parameters for the SpecialWordsParametersClient.WithOr +// method. +func (client *SpecialWordsParametersClient) WithOr(ctx context.Context, or string, options *SpecialWordsParametersClientWithOrOptions) (SpecialWordsParametersClientWithOrResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithOr" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withOrCreateRequest(ctx, or, options) + if err != nil { + return SpecialWordsParametersClientWithOrResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithOrResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithOrResponse{}, err + } + return SpecialWordsParametersClientWithOrResponse{}, nil +} + +// withOrCreateRequest creates the WithOr request. +func (client *SpecialWordsParametersClient) withOrCreateRequest(ctx context.Context, or string, _ *SpecialWordsParametersClientWithOrOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/or" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("or", or) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithPass - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithPassOptions contains the optional parameters for the SpecialWordsParametersClient.WithPass +// method. +func (client *SpecialWordsParametersClient) WithPass(ctx context.Context, pass string, options *SpecialWordsParametersClientWithPassOptions) (SpecialWordsParametersClientWithPassResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithPass" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withPassCreateRequest(ctx, pass, options) + if err != nil { + return SpecialWordsParametersClientWithPassResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithPassResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithPassResponse{}, err + } + return SpecialWordsParametersClientWithPassResponse{}, nil +} + +// withPassCreateRequest creates the WithPass request. +func (client *SpecialWordsParametersClient) withPassCreateRequest(ctx context.Context, pass string, _ *SpecialWordsParametersClientWithPassOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/pass" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("pass", pass) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithRaise - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithRaiseOptions contains the optional parameters for the SpecialWordsParametersClient.WithRaise +// method. +func (client *SpecialWordsParametersClient) WithRaise(ctx context.Context, raise string, options *SpecialWordsParametersClientWithRaiseOptions) (SpecialWordsParametersClientWithRaiseResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithRaise" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withRaiseCreateRequest(ctx, raise, options) + if err != nil { + return SpecialWordsParametersClientWithRaiseResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithRaiseResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithRaiseResponse{}, err + } + return SpecialWordsParametersClientWithRaiseResponse{}, nil +} + +// withRaiseCreateRequest creates the WithRaise request. +func (client *SpecialWordsParametersClient) withRaiseCreateRequest(ctx context.Context, raise string, _ *SpecialWordsParametersClientWithRaiseOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/raise" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("raise", raise) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithReturn - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithReturnOptions contains the optional parameters for the SpecialWordsParametersClient.WithReturn +// method. +func (client *SpecialWordsParametersClient) WithReturn(ctx context.Context, returnParam string, options *SpecialWordsParametersClientWithReturnOptions) (SpecialWordsParametersClientWithReturnResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithReturn" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withReturnCreateRequest(ctx, returnParam, options) + if err != nil { + return SpecialWordsParametersClientWithReturnResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithReturnResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithReturnResponse{}, err + } + return SpecialWordsParametersClientWithReturnResponse{}, nil +} + +// withReturnCreateRequest creates the WithReturn request. +func (client *SpecialWordsParametersClient) withReturnCreateRequest(ctx context.Context, returnParam string, _ *SpecialWordsParametersClientWithReturnOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/return" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("return", returnParam) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithTry - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithTryOptions contains the optional parameters for the SpecialWordsParametersClient.WithTry +// method. +func (client *SpecialWordsParametersClient) WithTry(ctx context.Context, try string, options *SpecialWordsParametersClientWithTryOptions) (SpecialWordsParametersClientWithTryResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithTry" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withTryCreateRequest(ctx, try, options) + if err != nil { + return SpecialWordsParametersClientWithTryResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithTryResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithTryResponse{}, err + } + return SpecialWordsParametersClientWithTryResponse{}, nil +} + +// withTryCreateRequest creates the WithTry request. +func (client *SpecialWordsParametersClient) withTryCreateRequest(ctx context.Context, try string, _ *SpecialWordsParametersClientWithTryOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/try" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("try", try) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithWhile - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithWhileOptions contains the optional parameters for the SpecialWordsParametersClient.WithWhile +// method. +func (client *SpecialWordsParametersClient) WithWhile(ctx context.Context, while string, options *SpecialWordsParametersClientWithWhileOptions) (SpecialWordsParametersClientWithWhileResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithWhile" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withWhileCreateRequest(ctx, while, options) + if err != nil { + return SpecialWordsParametersClientWithWhileResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithWhileResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithWhileResponse{}, err + } + return SpecialWordsParametersClientWithWhileResponse{}, nil +} + +// withWhileCreateRequest creates the WithWhile request. +func (client *SpecialWordsParametersClient) withWhileCreateRequest(ctx context.Context, while string, _ *SpecialWordsParametersClientWithWhileOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/while" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("while", while) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithWith - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithWithOptions contains the optional parameters for the SpecialWordsParametersClient.WithWith +// method. +func (client *SpecialWordsParametersClient) WithWith(ctx context.Context, with string, options *SpecialWordsParametersClientWithWithOptions) (SpecialWordsParametersClientWithWithResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithWith" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withWithCreateRequest(ctx, with, options) + if err != nil { + return SpecialWordsParametersClientWithWithResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithWithResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithWithResponse{}, err + } + return SpecialWordsParametersClientWithWithResponse{}, nil +} + +// withWithCreateRequest creates the WithWith request. +func (client *SpecialWordsParametersClient) withWithCreateRequest(ctx context.Context, with string, _ *SpecialWordsParametersClientWithWithOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/with" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("with", with) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// WithYield - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsParametersClientWithYieldOptions contains the optional parameters for the SpecialWordsParametersClient.WithYield +// method. +func (client *SpecialWordsParametersClient) WithYield(ctx context.Context, yield string, options *SpecialWordsParametersClientWithYieldOptions) (SpecialWordsParametersClientWithYieldResponse, error) { + var err error + const operationName = "SpecialWordsParametersClient.WithYield" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withYieldCreateRequest(ctx, yield, options) + if err != nil { + return SpecialWordsParametersClientWithYieldResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsParametersClientWithYieldResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsParametersClientWithYieldResponse{}, err + } + return SpecialWordsParametersClientWithYieldResponse{}, nil +} + +// withYieldCreateRequest creates the WithYield request. +func (client *SpecialWordsParametersClient) withYieldCreateRequest(ctx context.Context, yield string, _ *SpecialWordsParametersClientWithYieldOptions) (*policy.Request, error) { + urlPath := "/special-words/parameters/yield" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("yield", yield) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/http-specs/specialwordsgroup/zz_specialwordsreservedoperationbodyparams_client.go b/test/http-specs/specialwordsgroup/zz_specialwordsreservedoperationbodyparams_client.go new file mode 100644 index 000000000000..7d3312b98c79 --- /dev/null +++ b/test/http-specs/specialwordsgroup/zz_specialwordsreservedoperationbodyparams_client.go @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package specialwordsgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// SpecialWordsReservedOperationBodyParamsClient - Verify that operation parameters whose names match Python Mapping protocol +// methods +// (e.g., items, keys, values) are sent with the original name on the wire, not mangled. +// Don't use this type directly, use [SpecialWordsClient.NewSpecialWordsReservedOperationBodyParamsClient] instead. +type SpecialWordsReservedOperationBodyParamsClient struct { + internal *azcore.Client + endpoint string +} + +// WithItems - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SpecialWordsReservedOperationBodyParamsClientWithItemsOptions contains the optional parameters for the SpecialWordsReservedOperationBodyParamsClient.WithItems +// method. +func (client *SpecialWordsReservedOperationBodyParamsClient) WithItems(ctx context.Context, items []string, options *SpecialWordsReservedOperationBodyParamsClientWithItemsOptions) (SpecialWordsReservedOperationBodyParamsClientWithItemsResponse, error) { + var err error + const operationName = "SpecialWordsReservedOperationBodyParamsClient.WithItems" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withItemsCreateRequest(ctx, items, options) + if err != nil { + return SpecialWordsReservedOperationBodyParamsClientWithItemsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SpecialWordsReservedOperationBodyParamsClientWithItemsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SpecialWordsReservedOperationBodyParamsClientWithItemsResponse{}, err + } + return SpecialWordsReservedOperationBodyParamsClientWithItemsResponse{}, nil +} + +// withItemsCreateRequest creates the WithItems request. +func (client *SpecialWordsReservedOperationBodyParamsClient) withItemsCreateRequest(ctx context.Context, items []string, _ *SpecialWordsReservedOperationBodyParamsClientWithItemsOptions) (*policy.Request, error) { + urlPath := "/special-words/operations/body-param-reserved" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + body := struct { + Items []string `json:"items"` + }{ + Items: items, + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/specialwordsgroup/zz_version.go b/test/http-specs/specialwordsgroup/zz_version.go new file mode 100644 index 000000000000..3b8ef7eeebc0 --- /dev/null +++ b/test/http-specs/specialwordsgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package specialwordsgroup + +const ( + moduleName = "specialwordsgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/type/arraygroup/LICENSE.txt b/test/http-specs/type/arraygroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/type/arraygroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/type/arraygroup/arraygroup_test.go b/test/http-specs/type/arraygroup/arraygroup_test.go new file mode 100644 index 000000000000..3ca192357951 --- /dev/null +++ b/test/http-specs/type/arraygroup/arraygroup_test.go @@ -0,0 +1,251 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package arraygroup_test + +import ( + "arraygroup" + "context" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestBooleanValueClientGet(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayBooleanValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.Equal(t, []bool{true, false}, resp.BoolArray) +} + +func TestBooleanValueClientPut(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayBooleanValueClient().Put(context.Background(), []bool{true, false}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestDatetimeValueClientGet(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayDatetimeValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, []time.Time{time.Date(2022, time.August, 26, 18, 38, 0, 0, time.UTC)}, resp.TimeArray) +} + +func TestDatetimeValueClientPut(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayDatetimeValueClient().Put(context.Background(), []time.Time{time.Date(2022, time.August, 26, 18, 38, 0, 0, time.UTC)}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestDurationValueClientGet(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayDurationValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, []string{"P123DT22H14M12.011S"}, resp.StringArray) +} + +func TestDurationValueClientPut(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayDurationValueClient().Put(context.Background(), []string{"P123DT22H14M12.011S"}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestFloat32ValueClientGet(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayFloat32ValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, []float32{43.125}, resp.Float32Array) +} + +func TestFloat32ValueClientPut(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayFloat32ValueClient().Put(context.Background(), []float32{43.125}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestInt32ValueClientGet(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayInt32ValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, []int32{1, 2}, resp.Int32Array) +} + +func TestInt32ValueClientPut(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayInt32ValueClient().Put(context.Background(), []int32{1, 2}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestInt64ValueClientGet(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayInt64ValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, []int64{9007199254740991, -9007199254740991}, resp.Int64Array) +} + +func TestInt64ValueClientPut(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayInt64ValueClient().Put(context.Background(), []int64{9007199254740991, -9007199254740991}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelValueClientGet(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayModelValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, []arraygroup.InnerModel{ + { + Property: to.Ptr("hello"), + }, + { + Property: to.Ptr("world"), + }, + }, resp.InnerModelArray) +} + +func TestModelValueClientPut(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayModelValueClient().Put(context.Background(), []arraygroup.InnerModel{ + { + Property: to.Ptr("hello"), + }, + { + Property: to.Ptr("world"), + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} +func TestNullableBooleanValueClientGet(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayNullableBooleanValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, []*bool{to.Ptr(true), nil, to.Ptr(false)}, resp.BoolArray) +} + +func TestNullableBooleanValueClientPut(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayNullableBooleanValueClient().Put(context.Background(), []*bool{to.Ptr(true), nil, to.Ptr(false)}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestNullableFloatValueClientGet(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayNullableFloatValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, []*float32{to.Ptr[float32](1.25), nil, to.Ptr[float32](3)}, resp.Float32Array) +} + +func TestNullableFloatValueClientPut(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayNullableFloatValueClient().Put(context.Background(), []*float32{to.Ptr[float32](1.25), nil, to.Ptr[float32](3)}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestNullableInt32ValueClientGet(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayNullableInt32ValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, []*int32{to.Ptr[int32](1), nil, to.Ptr[int32](3)}, resp.Int32Array) +} + +func TestNullableInt32ValueClientPut(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayNullableInt32ValueClient().Put(context.Background(), []*int32{to.Ptr[int32](1), nil, to.Ptr[int32](3)}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestNullableModelValueClientGet(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayNullableModelValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, []*arraygroup.InnerModel{{Property: to.Ptr("hello")}, nil, {Property: to.Ptr("world")}}, resp.InnerModelArray) +} + +func TestNullableModelValueClientPut(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayNullableModelValueClient().Put(context.Background(), []*arraygroup.InnerModel{{Property: to.Ptr("hello")}, nil, {Property: to.Ptr("world")}}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestNullableStringValueClientGet(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayNullableStringValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, []*string{to.Ptr("hello"), nil, to.Ptr("world")}, resp.StringArray) +} + +func TestNullableStringValueClientPut(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayNullableStringValueClient().Put(context.Background(), []*string{to.Ptr("hello"), nil, to.Ptr("world")}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestStringValueClientGet(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayStringValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, []string{"hello", ""}, resp.StringArray) +} + +func TestStringValueClientPut(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayStringValueClient().Put(context.Background(), []string{"hello", ""}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestUnknownValueClientGet(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayUnknownValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, []any{float64(1), "hello", nil}, resp.InterfaceArray) +} + +func TestUnknownValueClientPut(t *testing.T) { + client, err := arraygroup.NewArrayClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewArrayUnknownValueClient().Put(context.Background(), []any{float64(1), "hello", nil}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/arraygroup/fake/zz_array_server.go b/test/http-specs/type/arraygroup/fake/zz_array_server.go new file mode 100644 index 000000000000..1aad8909b509 --- /dev/null +++ b/test/http-specs/type/arraygroup/fake/zz_array_server.go @@ -0,0 +1,186 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ArrayServer is a fake server for instances of the arraygroup.ArrayClient type. +type ArrayServer struct { + // ArrayBooleanValueServer contains the fakes for client ArrayBooleanValueClient + ArrayBooleanValueServer ArrayBooleanValueServer + + // ArrayDatetimeValueServer contains the fakes for client ArrayDatetimeValueClient + ArrayDatetimeValueServer ArrayDatetimeValueServer + + // ArrayDurationValueServer contains the fakes for client ArrayDurationValueClient + ArrayDurationValueServer ArrayDurationValueServer + + // ArrayFloat32ValueServer contains the fakes for client ArrayFloat32ValueClient + ArrayFloat32ValueServer ArrayFloat32ValueServer + + // ArrayInt32ValueServer contains the fakes for client ArrayInt32ValueClient + ArrayInt32ValueServer ArrayInt32ValueServer + + // ArrayInt64ValueServer contains the fakes for client ArrayInt64ValueClient + ArrayInt64ValueServer ArrayInt64ValueServer + + // ArrayModelValueServer contains the fakes for client ArrayModelValueClient + ArrayModelValueServer ArrayModelValueServer + + // ArrayNullableBooleanValueServer contains the fakes for client ArrayNullableBooleanValueClient + ArrayNullableBooleanValueServer ArrayNullableBooleanValueServer + + // ArrayNullableFloatValueServer contains the fakes for client ArrayNullableFloatValueClient + ArrayNullableFloatValueServer ArrayNullableFloatValueServer + + // ArrayNullableInt32ValueServer contains the fakes for client ArrayNullableInt32ValueClient + ArrayNullableInt32ValueServer ArrayNullableInt32ValueServer + + // ArrayNullableModelValueServer contains the fakes for client ArrayNullableModelValueClient + ArrayNullableModelValueServer ArrayNullableModelValueServer + + // ArrayNullableStringValueServer contains the fakes for client ArrayNullableStringValueClient + ArrayNullableStringValueServer ArrayNullableStringValueServer + + // ArrayStringValueServer contains the fakes for client ArrayStringValueClient + ArrayStringValueServer ArrayStringValueServer + + // ArrayUnknownValueServer contains the fakes for client ArrayUnknownValueClient + ArrayUnknownValueServer ArrayUnknownValueServer +} + +// NewArrayServerTransport creates a new instance of ArrayServerTransport with the provided implementation. +// The returned ArrayServerTransport instance is connected to an instance of arraygroup.ArrayClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewArrayServerTransport(srv *ArrayServer) *ArrayServerTransport { + return &ArrayServerTransport{srv: srv} +} + +// ArrayServerTransport connects instances of arraygroup.ArrayClient to instances of ArrayServer. +// Don't use this type directly, use NewArrayServerTransport instead. +type ArrayServerTransport struct { + srv *ArrayServer + trMu sync.Mutex + trArrayBooleanValueServer *ArrayBooleanValueServerTransport + trArrayDatetimeValueServer *ArrayDatetimeValueServerTransport + trArrayDurationValueServer *ArrayDurationValueServerTransport + trArrayFloat32ValueServer *ArrayFloat32ValueServerTransport + trArrayInt32ValueServer *ArrayInt32ValueServerTransport + trArrayInt64ValueServer *ArrayInt64ValueServerTransport + trArrayModelValueServer *ArrayModelValueServerTransport + trArrayNullableBooleanValueServer *ArrayNullableBooleanValueServerTransport + trArrayNullableFloatValueServer *ArrayNullableFloatValueServerTransport + trArrayNullableInt32ValueServer *ArrayNullableInt32ValueServerTransport + trArrayNullableModelValueServer *ArrayNullableModelValueServerTransport + trArrayNullableStringValueServer *ArrayNullableStringValueServerTransport + trArrayStringValueServer *ArrayStringValueServerTransport + trArrayUnknownValueServer *ArrayUnknownValueServerTransport +} + +// Do implements the policy.Transporter interface for ArrayServerTransport. +func (a *ArrayServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (a *ArrayServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "ArrayBooleanValueClient": + initServer(&a.trMu, &a.trArrayBooleanValueServer, func() *ArrayBooleanValueServerTransport { + return NewArrayBooleanValueServerTransport(&a.srv.ArrayBooleanValueServer) + }) + resp, err = a.trArrayBooleanValueServer.Do(req) + case "ArrayDatetimeValueClient": + initServer(&a.trMu, &a.trArrayDatetimeValueServer, func() *ArrayDatetimeValueServerTransport { + return NewArrayDatetimeValueServerTransport(&a.srv.ArrayDatetimeValueServer) + }) + resp, err = a.trArrayDatetimeValueServer.Do(req) + case "ArrayDurationValueClient": + initServer(&a.trMu, &a.trArrayDurationValueServer, func() *ArrayDurationValueServerTransport { + return NewArrayDurationValueServerTransport(&a.srv.ArrayDurationValueServer) + }) + resp, err = a.trArrayDurationValueServer.Do(req) + case "ArrayFloat32ValueClient": + initServer(&a.trMu, &a.trArrayFloat32ValueServer, func() *ArrayFloat32ValueServerTransport { + return NewArrayFloat32ValueServerTransport(&a.srv.ArrayFloat32ValueServer) + }) + resp, err = a.trArrayFloat32ValueServer.Do(req) + case "ArrayInt32ValueClient": + initServer(&a.trMu, &a.trArrayInt32ValueServer, func() *ArrayInt32ValueServerTransport { + return NewArrayInt32ValueServerTransport(&a.srv.ArrayInt32ValueServer) + }) + resp, err = a.trArrayInt32ValueServer.Do(req) + case "ArrayInt64ValueClient": + initServer(&a.trMu, &a.trArrayInt64ValueServer, func() *ArrayInt64ValueServerTransport { + return NewArrayInt64ValueServerTransport(&a.srv.ArrayInt64ValueServer) + }) + resp, err = a.trArrayInt64ValueServer.Do(req) + case "ArrayModelValueClient": + initServer(&a.trMu, &a.trArrayModelValueServer, func() *ArrayModelValueServerTransport { + return NewArrayModelValueServerTransport(&a.srv.ArrayModelValueServer) + }) + resp, err = a.trArrayModelValueServer.Do(req) + case "ArrayNullableBooleanValueClient": + initServer(&a.trMu, &a.trArrayNullableBooleanValueServer, func() *ArrayNullableBooleanValueServerTransport { + return NewArrayNullableBooleanValueServerTransport(&a.srv.ArrayNullableBooleanValueServer) + }) + resp, err = a.trArrayNullableBooleanValueServer.Do(req) + case "ArrayNullableFloatValueClient": + initServer(&a.trMu, &a.trArrayNullableFloatValueServer, func() *ArrayNullableFloatValueServerTransport { + return NewArrayNullableFloatValueServerTransport(&a.srv.ArrayNullableFloatValueServer) + }) + resp, err = a.trArrayNullableFloatValueServer.Do(req) + case "ArrayNullableInt32ValueClient": + initServer(&a.trMu, &a.trArrayNullableInt32ValueServer, func() *ArrayNullableInt32ValueServerTransport { + return NewArrayNullableInt32ValueServerTransport(&a.srv.ArrayNullableInt32ValueServer) + }) + resp, err = a.trArrayNullableInt32ValueServer.Do(req) + case "ArrayNullableModelValueClient": + initServer(&a.trMu, &a.trArrayNullableModelValueServer, func() *ArrayNullableModelValueServerTransport { + return NewArrayNullableModelValueServerTransport(&a.srv.ArrayNullableModelValueServer) + }) + resp, err = a.trArrayNullableModelValueServer.Do(req) + case "ArrayNullableStringValueClient": + initServer(&a.trMu, &a.trArrayNullableStringValueServer, func() *ArrayNullableStringValueServerTransport { + return NewArrayNullableStringValueServerTransport(&a.srv.ArrayNullableStringValueServer) + }) + resp, err = a.trArrayNullableStringValueServer.Do(req) + case "ArrayStringValueClient": + initServer(&a.trMu, &a.trArrayStringValueServer, func() *ArrayStringValueServerTransport { + return NewArrayStringValueServerTransport(&a.srv.ArrayStringValueServer) + }) + resp, err = a.trArrayStringValueServer.Do(req) + case "ArrayUnknownValueClient": + initServer(&a.trMu, &a.trArrayUnknownValueServer, func() *ArrayUnknownValueServerTransport { + return NewArrayUnknownValueServerTransport(&a.srv.ArrayUnknownValueServer) + }) + resp, err = a.trArrayUnknownValueServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to ArrayServerTransport +var arrayServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/arraygroup/fake/zz_arraybooleanvalue_server.go b/test/http-specs/type/arraygroup/fake/zz_arraybooleanvalue_server.go new file mode 100644 index 000000000000..bfc4cb7cdf12 --- /dev/null +++ b/test/http-specs/type/arraygroup/fake/zz_arraybooleanvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "arraygroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// ArrayBooleanValueServer is a fake server for instances of the arraygroup.ArrayBooleanValueClient type. +type ArrayBooleanValueServer struct { + // Get is the fake for method ArrayBooleanValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *arraygroup.ArrayBooleanValueClientGetOptions) (resp azfake.Responder[arraygroup.ArrayBooleanValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ArrayBooleanValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body []bool, options *arraygroup.ArrayBooleanValueClientPutOptions) (resp azfake.Responder[arraygroup.ArrayBooleanValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewArrayBooleanValueServerTransport creates a new instance of ArrayBooleanValueServerTransport with the provided implementation. +// The returned ArrayBooleanValueServerTransport instance is connected to an instance of arraygroup.ArrayBooleanValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewArrayBooleanValueServerTransport(srv *ArrayBooleanValueServer) *ArrayBooleanValueServerTransport { + return &ArrayBooleanValueServerTransport{srv: srv} +} + +// ArrayBooleanValueServerTransport connects instances of arraygroup.ArrayBooleanValueClient to instances of ArrayBooleanValueServer. +// Don't use this type directly, use NewArrayBooleanValueServerTransport instead. +type ArrayBooleanValueServerTransport struct { + srv *ArrayBooleanValueServer +} + +// Do implements the policy.Transporter interface for ArrayBooleanValueServerTransport. +func (a *ArrayBooleanValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *ArrayBooleanValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if arrayBooleanValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = arrayBooleanValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ArrayBooleanValueClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "ArrayBooleanValueClient.Put": + res.resp, res.err = a.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *ArrayBooleanValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := a.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BoolArray, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *ArrayBooleanValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if a.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[[]bool](req) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ArrayBooleanValueServerTransport +var arrayBooleanValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/arraygroup/fake/zz_arraydatetimevalue_server.go b/test/http-specs/type/arraygroup/fake/zz_arraydatetimevalue_server.go new file mode 100644 index 000000000000..b3c7fd02cbaa --- /dev/null +++ b/test/http-specs/type/arraygroup/fake/zz_arraydatetimevalue_server.go @@ -0,0 +1,131 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "arraygroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "time" +) + +// ArrayDatetimeValueServer is a fake server for instances of the arraygroup.ArrayDatetimeValueClient type. +type ArrayDatetimeValueServer struct { + // Get is the fake for method ArrayDatetimeValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *arraygroup.ArrayDatetimeValueClientGetOptions) (resp azfake.Responder[arraygroup.ArrayDatetimeValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ArrayDatetimeValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body []time.Time, options *arraygroup.ArrayDatetimeValueClientPutOptions) (resp azfake.Responder[arraygroup.ArrayDatetimeValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewArrayDatetimeValueServerTransport creates a new instance of ArrayDatetimeValueServerTransport with the provided implementation. +// The returned ArrayDatetimeValueServerTransport instance is connected to an instance of arraygroup.ArrayDatetimeValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewArrayDatetimeValueServerTransport(srv *ArrayDatetimeValueServer) *ArrayDatetimeValueServerTransport { + return &ArrayDatetimeValueServerTransport{srv: srv} +} + +// ArrayDatetimeValueServerTransport connects instances of arraygroup.ArrayDatetimeValueClient to instances of ArrayDatetimeValueServer. +// Don't use this type directly, use NewArrayDatetimeValueServerTransport instead. +type ArrayDatetimeValueServerTransport struct { + srv *ArrayDatetimeValueServer +} + +// Do implements the policy.Transporter interface for ArrayDatetimeValueServerTransport. +func (a *ArrayDatetimeValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *ArrayDatetimeValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if arrayDatetimeValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = arrayDatetimeValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ArrayDatetimeValueClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "ArrayDatetimeValueClient.Put": + res.resp, res.err = a.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *ArrayDatetimeValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := a.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).TimeArray, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *ArrayDatetimeValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if a.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[[]time.Time](req) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ArrayDatetimeValueServerTransport +var arrayDatetimeValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/arraygroup/fake/zz_arraydurationvalue_server.go b/test/http-specs/type/arraygroup/fake/zz_arraydurationvalue_server.go new file mode 100644 index 000000000000..ec84ed45c637 --- /dev/null +++ b/test/http-specs/type/arraygroup/fake/zz_arraydurationvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "arraygroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// ArrayDurationValueServer is a fake server for instances of the arraygroup.ArrayDurationValueClient type. +type ArrayDurationValueServer struct { + // Get is the fake for method ArrayDurationValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *arraygroup.ArrayDurationValueClientGetOptions) (resp azfake.Responder[arraygroup.ArrayDurationValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ArrayDurationValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body []string, options *arraygroup.ArrayDurationValueClientPutOptions) (resp azfake.Responder[arraygroup.ArrayDurationValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewArrayDurationValueServerTransport creates a new instance of ArrayDurationValueServerTransport with the provided implementation. +// The returned ArrayDurationValueServerTransport instance is connected to an instance of arraygroup.ArrayDurationValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewArrayDurationValueServerTransport(srv *ArrayDurationValueServer) *ArrayDurationValueServerTransport { + return &ArrayDurationValueServerTransport{srv: srv} +} + +// ArrayDurationValueServerTransport connects instances of arraygroup.ArrayDurationValueClient to instances of ArrayDurationValueServer. +// Don't use this type directly, use NewArrayDurationValueServerTransport instead. +type ArrayDurationValueServerTransport struct { + srv *ArrayDurationValueServer +} + +// Do implements the policy.Transporter interface for ArrayDurationValueServerTransport. +func (a *ArrayDurationValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *ArrayDurationValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if arrayDurationValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = arrayDurationValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ArrayDurationValueClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "ArrayDurationValueClient.Put": + res.resp, res.err = a.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *ArrayDurationValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := a.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).StringArray, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *ArrayDurationValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if a.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[[]string](req) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ArrayDurationValueServerTransport +var arrayDurationValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/arraygroup/fake/zz_arrayfloat32value_server.go b/test/http-specs/type/arraygroup/fake/zz_arrayfloat32value_server.go new file mode 100644 index 000000000000..d3764db8df8f --- /dev/null +++ b/test/http-specs/type/arraygroup/fake/zz_arrayfloat32value_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "arraygroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// ArrayFloat32ValueServer is a fake server for instances of the arraygroup.ArrayFloat32ValueClient type. +type ArrayFloat32ValueServer struct { + // Get is the fake for method ArrayFloat32ValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *arraygroup.ArrayFloat32ValueClientGetOptions) (resp azfake.Responder[arraygroup.ArrayFloat32ValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ArrayFloat32ValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body []float32, options *arraygroup.ArrayFloat32ValueClientPutOptions) (resp azfake.Responder[arraygroup.ArrayFloat32ValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewArrayFloat32ValueServerTransport creates a new instance of ArrayFloat32ValueServerTransport with the provided implementation. +// The returned ArrayFloat32ValueServerTransport instance is connected to an instance of arraygroup.ArrayFloat32ValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewArrayFloat32ValueServerTransport(srv *ArrayFloat32ValueServer) *ArrayFloat32ValueServerTransport { + return &ArrayFloat32ValueServerTransport{srv: srv} +} + +// ArrayFloat32ValueServerTransport connects instances of arraygroup.ArrayFloat32ValueClient to instances of ArrayFloat32ValueServer. +// Don't use this type directly, use NewArrayFloat32ValueServerTransport instead. +type ArrayFloat32ValueServerTransport struct { + srv *ArrayFloat32ValueServer +} + +// Do implements the policy.Transporter interface for ArrayFloat32ValueServerTransport. +func (a *ArrayFloat32ValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *ArrayFloat32ValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if arrayFloat32ValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = arrayFloat32ValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ArrayFloat32ValueClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "ArrayFloat32ValueClient.Put": + res.resp, res.err = a.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *ArrayFloat32ValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := a.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Float32Array, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *ArrayFloat32ValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if a.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[[]float32](req) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ArrayFloat32ValueServerTransport +var arrayFloat32ValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/arraygroup/fake/zz_arrayint32value_server.go b/test/http-specs/type/arraygroup/fake/zz_arrayint32value_server.go new file mode 100644 index 000000000000..37ecefc3572c --- /dev/null +++ b/test/http-specs/type/arraygroup/fake/zz_arrayint32value_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "arraygroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// ArrayInt32ValueServer is a fake server for instances of the arraygroup.ArrayInt32ValueClient type. +type ArrayInt32ValueServer struct { + // Get is the fake for method ArrayInt32ValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *arraygroup.ArrayInt32ValueClientGetOptions) (resp azfake.Responder[arraygroup.ArrayInt32ValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ArrayInt32ValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body []int32, options *arraygroup.ArrayInt32ValueClientPutOptions) (resp azfake.Responder[arraygroup.ArrayInt32ValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewArrayInt32ValueServerTransport creates a new instance of ArrayInt32ValueServerTransport with the provided implementation. +// The returned ArrayInt32ValueServerTransport instance is connected to an instance of arraygroup.ArrayInt32ValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewArrayInt32ValueServerTransport(srv *ArrayInt32ValueServer) *ArrayInt32ValueServerTransport { + return &ArrayInt32ValueServerTransport{srv: srv} +} + +// ArrayInt32ValueServerTransport connects instances of arraygroup.ArrayInt32ValueClient to instances of ArrayInt32ValueServer. +// Don't use this type directly, use NewArrayInt32ValueServerTransport instead. +type ArrayInt32ValueServerTransport struct { + srv *ArrayInt32ValueServer +} + +// Do implements the policy.Transporter interface for ArrayInt32ValueServerTransport. +func (a *ArrayInt32ValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *ArrayInt32ValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if arrayInt32ValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = arrayInt32ValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ArrayInt32ValueClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "ArrayInt32ValueClient.Put": + res.resp, res.err = a.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *ArrayInt32ValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := a.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Int32Array, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *ArrayInt32ValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if a.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[[]int32](req) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ArrayInt32ValueServerTransport +var arrayInt32ValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/arraygroup/fake/zz_arrayint64value_server.go b/test/http-specs/type/arraygroup/fake/zz_arrayint64value_server.go new file mode 100644 index 000000000000..0958cad8802d --- /dev/null +++ b/test/http-specs/type/arraygroup/fake/zz_arrayint64value_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "arraygroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// ArrayInt64ValueServer is a fake server for instances of the arraygroup.ArrayInt64ValueClient type. +type ArrayInt64ValueServer struct { + // Get is the fake for method ArrayInt64ValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *arraygroup.ArrayInt64ValueClientGetOptions) (resp azfake.Responder[arraygroup.ArrayInt64ValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ArrayInt64ValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body []int64, options *arraygroup.ArrayInt64ValueClientPutOptions) (resp azfake.Responder[arraygroup.ArrayInt64ValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewArrayInt64ValueServerTransport creates a new instance of ArrayInt64ValueServerTransport with the provided implementation. +// The returned ArrayInt64ValueServerTransport instance is connected to an instance of arraygroup.ArrayInt64ValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewArrayInt64ValueServerTransport(srv *ArrayInt64ValueServer) *ArrayInt64ValueServerTransport { + return &ArrayInt64ValueServerTransport{srv: srv} +} + +// ArrayInt64ValueServerTransport connects instances of arraygroup.ArrayInt64ValueClient to instances of ArrayInt64ValueServer. +// Don't use this type directly, use NewArrayInt64ValueServerTransport instead. +type ArrayInt64ValueServerTransport struct { + srv *ArrayInt64ValueServer +} + +// Do implements the policy.Transporter interface for ArrayInt64ValueServerTransport. +func (a *ArrayInt64ValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *ArrayInt64ValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if arrayInt64ValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = arrayInt64ValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ArrayInt64ValueClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "ArrayInt64ValueClient.Put": + res.resp, res.err = a.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *ArrayInt64ValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := a.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Int64Array, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *ArrayInt64ValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if a.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[[]int64](req) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ArrayInt64ValueServerTransport +var arrayInt64ValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/arraygroup/fake/zz_arraymodelvalue_server.go b/test/http-specs/type/arraygroup/fake/zz_arraymodelvalue_server.go new file mode 100644 index 000000000000..afb73c3bade9 --- /dev/null +++ b/test/http-specs/type/arraygroup/fake/zz_arraymodelvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "arraygroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// ArrayModelValueServer is a fake server for instances of the arraygroup.ArrayModelValueClient type. +type ArrayModelValueServer struct { + // Get is the fake for method ArrayModelValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *arraygroup.ArrayModelValueClientGetOptions) (resp azfake.Responder[arraygroup.ArrayModelValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ArrayModelValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body []arraygroup.InnerModel, options *arraygroup.ArrayModelValueClientPutOptions) (resp azfake.Responder[arraygroup.ArrayModelValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewArrayModelValueServerTransport creates a new instance of ArrayModelValueServerTransport with the provided implementation. +// The returned ArrayModelValueServerTransport instance is connected to an instance of arraygroup.ArrayModelValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewArrayModelValueServerTransport(srv *ArrayModelValueServer) *ArrayModelValueServerTransport { + return &ArrayModelValueServerTransport{srv: srv} +} + +// ArrayModelValueServerTransport connects instances of arraygroup.ArrayModelValueClient to instances of ArrayModelValueServer. +// Don't use this type directly, use NewArrayModelValueServerTransport instead. +type ArrayModelValueServerTransport struct { + srv *ArrayModelValueServer +} + +// Do implements the policy.Transporter interface for ArrayModelValueServerTransport. +func (a *ArrayModelValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *ArrayModelValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if arrayModelValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = arrayModelValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ArrayModelValueClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "ArrayModelValueClient.Put": + res.resp, res.err = a.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *ArrayModelValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := a.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).InnerModelArray, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *ArrayModelValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if a.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[[]arraygroup.InnerModel](req) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ArrayModelValueServerTransport +var arrayModelValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/arraygroup/fake/zz_arraynullablebooleanvalue_server.go b/test/http-specs/type/arraygroup/fake/zz_arraynullablebooleanvalue_server.go new file mode 100644 index 000000000000..ddddbff87781 --- /dev/null +++ b/test/http-specs/type/arraygroup/fake/zz_arraynullablebooleanvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "arraygroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// ArrayNullableBooleanValueServer is a fake server for instances of the arraygroup.ArrayNullableBooleanValueClient type. +type ArrayNullableBooleanValueServer struct { + // Get is the fake for method ArrayNullableBooleanValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *arraygroup.ArrayNullableBooleanValueClientGetOptions) (resp azfake.Responder[arraygroup.ArrayNullableBooleanValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ArrayNullableBooleanValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body []*bool, options *arraygroup.ArrayNullableBooleanValueClientPutOptions) (resp azfake.Responder[arraygroup.ArrayNullableBooleanValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewArrayNullableBooleanValueServerTransport creates a new instance of ArrayNullableBooleanValueServerTransport with the provided implementation. +// The returned ArrayNullableBooleanValueServerTransport instance is connected to an instance of arraygroup.ArrayNullableBooleanValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewArrayNullableBooleanValueServerTransport(srv *ArrayNullableBooleanValueServer) *ArrayNullableBooleanValueServerTransport { + return &ArrayNullableBooleanValueServerTransport{srv: srv} +} + +// ArrayNullableBooleanValueServerTransport connects instances of arraygroup.ArrayNullableBooleanValueClient to instances of ArrayNullableBooleanValueServer. +// Don't use this type directly, use NewArrayNullableBooleanValueServerTransport instead. +type ArrayNullableBooleanValueServerTransport struct { + srv *ArrayNullableBooleanValueServer +} + +// Do implements the policy.Transporter interface for ArrayNullableBooleanValueServerTransport. +func (a *ArrayNullableBooleanValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *ArrayNullableBooleanValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if arrayNullableBooleanValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = arrayNullableBooleanValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ArrayNullableBooleanValueClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "ArrayNullableBooleanValueClient.Put": + res.resp, res.err = a.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *ArrayNullableBooleanValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := a.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BoolArray, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *ArrayNullableBooleanValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if a.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[[]*bool](req) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ArrayNullableBooleanValueServerTransport +var arrayNullableBooleanValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/arraygroup/fake/zz_arraynullablefloatvalue_server.go b/test/http-specs/type/arraygroup/fake/zz_arraynullablefloatvalue_server.go new file mode 100644 index 000000000000..820d1ce6ddd1 --- /dev/null +++ b/test/http-specs/type/arraygroup/fake/zz_arraynullablefloatvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "arraygroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// ArrayNullableFloatValueServer is a fake server for instances of the arraygroup.ArrayNullableFloatValueClient type. +type ArrayNullableFloatValueServer struct { + // Get is the fake for method ArrayNullableFloatValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *arraygroup.ArrayNullableFloatValueClientGetOptions) (resp azfake.Responder[arraygroup.ArrayNullableFloatValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ArrayNullableFloatValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body []*float32, options *arraygroup.ArrayNullableFloatValueClientPutOptions) (resp azfake.Responder[arraygroup.ArrayNullableFloatValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewArrayNullableFloatValueServerTransport creates a new instance of ArrayNullableFloatValueServerTransport with the provided implementation. +// The returned ArrayNullableFloatValueServerTransport instance is connected to an instance of arraygroup.ArrayNullableFloatValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewArrayNullableFloatValueServerTransport(srv *ArrayNullableFloatValueServer) *ArrayNullableFloatValueServerTransport { + return &ArrayNullableFloatValueServerTransport{srv: srv} +} + +// ArrayNullableFloatValueServerTransport connects instances of arraygroup.ArrayNullableFloatValueClient to instances of ArrayNullableFloatValueServer. +// Don't use this type directly, use NewArrayNullableFloatValueServerTransport instead. +type ArrayNullableFloatValueServerTransport struct { + srv *ArrayNullableFloatValueServer +} + +// Do implements the policy.Transporter interface for ArrayNullableFloatValueServerTransport. +func (a *ArrayNullableFloatValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *ArrayNullableFloatValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if arrayNullableFloatValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = arrayNullableFloatValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ArrayNullableFloatValueClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "ArrayNullableFloatValueClient.Put": + res.resp, res.err = a.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *ArrayNullableFloatValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := a.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Float32Array, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *ArrayNullableFloatValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if a.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[[]*float32](req) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ArrayNullableFloatValueServerTransport +var arrayNullableFloatValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/arraygroup/fake/zz_arraynullableint32value_server.go b/test/http-specs/type/arraygroup/fake/zz_arraynullableint32value_server.go new file mode 100644 index 000000000000..bf360e40ca9a --- /dev/null +++ b/test/http-specs/type/arraygroup/fake/zz_arraynullableint32value_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "arraygroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// ArrayNullableInt32ValueServer is a fake server for instances of the arraygroup.ArrayNullableInt32ValueClient type. +type ArrayNullableInt32ValueServer struct { + // Get is the fake for method ArrayNullableInt32ValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *arraygroup.ArrayNullableInt32ValueClientGetOptions) (resp azfake.Responder[arraygroup.ArrayNullableInt32ValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ArrayNullableInt32ValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body []*int32, options *arraygroup.ArrayNullableInt32ValueClientPutOptions) (resp azfake.Responder[arraygroup.ArrayNullableInt32ValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewArrayNullableInt32ValueServerTransport creates a new instance of ArrayNullableInt32ValueServerTransport with the provided implementation. +// The returned ArrayNullableInt32ValueServerTransport instance is connected to an instance of arraygroup.ArrayNullableInt32ValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewArrayNullableInt32ValueServerTransport(srv *ArrayNullableInt32ValueServer) *ArrayNullableInt32ValueServerTransport { + return &ArrayNullableInt32ValueServerTransport{srv: srv} +} + +// ArrayNullableInt32ValueServerTransport connects instances of arraygroup.ArrayNullableInt32ValueClient to instances of ArrayNullableInt32ValueServer. +// Don't use this type directly, use NewArrayNullableInt32ValueServerTransport instead. +type ArrayNullableInt32ValueServerTransport struct { + srv *ArrayNullableInt32ValueServer +} + +// Do implements the policy.Transporter interface for ArrayNullableInt32ValueServerTransport. +func (a *ArrayNullableInt32ValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *ArrayNullableInt32ValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if arrayNullableInt32ValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = arrayNullableInt32ValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ArrayNullableInt32ValueClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "ArrayNullableInt32ValueClient.Put": + res.resp, res.err = a.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *ArrayNullableInt32ValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := a.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Int32Array, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *ArrayNullableInt32ValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if a.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[[]*int32](req) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ArrayNullableInt32ValueServerTransport +var arrayNullableInt32ValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/arraygroup/fake/zz_arraynullablemodelvalue_server.go b/test/http-specs/type/arraygroup/fake/zz_arraynullablemodelvalue_server.go new file mode 100644 index 000000000000..087c9aece46a --- /dev/null +++ b/test/http-specs/type/arraygroup/fake/zz_arraynullablemodelvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "arraygroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// ArrayNullableModelValueServer is a fake server for instances of the arraygroup.ArrayNullableModelValueClient type. +type ArrayNullableModelValueServer struct { + // Get is the fake for method ArrayNullableModelValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *arraygroup.ArrayNullableModelValueClientGetOptions) (resp azfake.Responder[arraygroup.ArrayNullableModelValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ArrayNullableModelValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body []*arraygroup.InnerModel, options *arraygroup.ArrayNullableModelValueClientPutOptions) (resp azfake.Responder[arraygroup.ArrayNullableModelValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewArrayNullableModelValueServerTransport creates a new instance of ArrayNullableModelValueServerTransport with the provided implementation. +// The returned ArrayNullableModelValueServerTransport instance is connected to an instance of arraygroup.ArrayNullableModelValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewArrayNullableModelValueServerTransport(srv *ArrayNullableModelValueServer) *ArrayNullableModelValueServerTransport { + return &ArrayNullableModelValueServerTransport{srv: srv} +} + +// ArrayNullableModelValueServerTransport connects instances of arraygroup.ArrayNullableModelValueClient to instances of ArrayNullableModelValueServer. +// Don't use this type directly, use NewArrayNullableModelValueServerTransport instead. +type ArrayNullableModelValueServerTransport struct { + srv *ArrayNullableModelValueServer +} + +// Do implements the policy.Transporter interface for ArrayNullableModelValueServerTransport. +func (a *ArrayNullableModelValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *ArrayNullableModelValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if arrayNullableModelValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = arrayNullableModelValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ArrayNullableModelValueClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "ArrayNullableModelValueClient.Put": + res.resp, res.err = a.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *ArrayNullableModelValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := a.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).InnerModelArray, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *ArrayNullableModelValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if a.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[[]*arraygroup.InnerModel](req) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ArrayNullableModelValueServerTransport +var arrayNullableModelValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/arraygroup/fake/zz_arraynullablestringvalue_server.go b/test/http-specs/type/arraygroup/fake/zz_arraynullablestringvalue_server.go new file mode 100644 index 000000000000..d9111e172da9 --- /dev/null +++ b/test/http-specs/type/arraygroup/fake/zz_arraynullablestringvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "arraygroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// ArrayNullableStringValueServer is a fake server for instances of the arraygroup.ArrayNullableStringValueClient type. +type ArrayNullableStringValueServer struct { + // Get is the fake for method ArrayNullableStringValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *arraygroup.ArrayNullableStringValueClientGetOptions) (resp azfake.Responder[arraygroup.ArrayNullableStringValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ArrayNullableStringValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body []*string, options *arraygroup.ArrayNullableStringValueClientPutOptions) (resp azfake.Responder[arraygroup.ArrayNullableStringValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewArrayNullableStringValueServerTransport creates a new instance of ArrayNullableStringValueServerTransport with the provided implementation. +// The returned ArrayNullableStringValueServerTransport instance is connected to an instance of arraygroup.ArrayNullableStringValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewArrayNullableStringValueServerTransport(srv *ArrayNullableStringValueServer) *ArrayNullableStringValueServerTransport { + return &ArrayNullableStringValueServerTransport{srv: srv} +} + +// ArrayNullableStringValueServerTransport connects instances of arraygroup.ArrayNullableStringValueClient to instances of ArrayNullableStringValueServer. +// Don't use this type directly, use NewArrayNullableStringValueServerTransport instead. +type ArrayNullableStringValueServerTransport struct { + srv *ArrayNullableStringValueServer +} + +// Do implements the policy.Transporter interface for ArrayNullableStringValueServerTransport. +func (a *ArrayNullableStringValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *ArrayNullableStringValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if arrayNullableStringValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = arrayNullableStringValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ArrayNullableStringValueClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "ArrayNullableStringValueClient.Put": + res.resp, res.err = a.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *ArrayNullableStringValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := a.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).StringArray, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *ArrayNullableStringValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if a.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[[]*string](req) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ArrayNullableStringValueServerTransport +var arrayNullableStringValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/arraygroup/fake/zz_arraystringvalue_server.go b/test/http-specs/type/arraygroup/fake/zz_arraystringvalue_server.go new file mode 100644 index 000000000000..2fd8d0ab444c --- /dev/null +++ b/test/http-specs/type/arraygroup/fake/zz_arraystringvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "arraygroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// ArrayStringValueServer is a fake server for instances of the arraygroup.ArrayStringValueClient type. +type ArrayStringValueServer struct { + // Get is the fake for method ArrayStringValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *arraygroup.ArrayStringValueClientGetOptions) (resp azfake.Responder[arraygroup.ArrayStringValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ArrayStringValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body []string, options *arraygroup.ArrayStringValueClientPutOptions) (resp azfake.Responder[arraygroup.ArrayStringValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewArrayStringValueServerTransport creates a new instance of ArrayStringValueServerTransport with the provided implementation. +// The returned ArrayStringValueServerTransport instance is connected to an instance of arraygroup.ArrayStringValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewArrayStringValueServerTransport(srv *ArrayStringValueServer) *ArrayStringValueServerTransport { + return &ArrayStringValueServerTransport{srv: srv} +} + +// ArrayStringValueServerTransport connects instances of arraygroup.ArrayStringValueClient to instances of ArrayStringValueServer. +// Don't use this type directly, use NewArrayStringValueServerTransport instead. +type ArrayStringValueServerTransport struct { + srv *ArrayStringValueServer +} + +// Do implements the policy.Transporter interface for ArrayStringValueServerTransport. +func (a *ArrayStringValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *ArrayStringValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if arrayStringValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = arrayStringValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ArrayStringValueClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "ArrayStringValueClient.Put": + res.resp, res.err = a.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *ArrayStringValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := a.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).StringArray, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *ArrayStringValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if a.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[[]string](req) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ArrayStringValueServerTransport +var arrayStringValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/arraygroup/fake/zz_arrayunknownvalue_server.go b/test/http-specs/type/arraygroup/fake/zz_arrayunknownvalue_server.go new file mode 100644 index 000000000000..902e99eb3f60 --- /dev/null +++ b/test/http-specs/type/arraygroup/fake/zz_arrayunknownvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "arraygroup" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// ArrayUnknownValueServer is a fake server for instances of the arraygroup.ArrayUnknownValueClient type. +type ArrayUnknownValueServer struct { + // Get is the fake for method ArrayUnknownValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *arraygroup.ArrayUnknownValueClientGetOptions) (resp azfake.Responder[arraygroup.ArrayUnknownValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ArrayUnknownValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body []any, options *arraygroup.ArrayUnknownValueClientPutOptions) (resp azfake.Responder[arraygroup.ArrayUnknownValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewArrayUnknownValueServerTransport creates a new instance of ArrayUnknownValueServerTransport with the provided implementation. +// The returned ArrayUnknownValueServerTransport instance is connected to an instance of arraygroup.ArrayUnknownValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewArrayUnknownValueServerTransport(srv *ArrayUnknownValueServer) *ArrayUnknownValueServerTransport { + return &ArrayUnknownValueServerTransport{srv: srv} +} + +// ArrayUnknownValueServerTransport connects instances of arraygroup.ArrayUnknownValueClient to instances of ArrayUnknownValueServer. +// Don't use this type directly, use NewArrayUnknownValueServerTransport instead. +type ArrayUnknownValueServerTransport struct { + srv *ArrayUnknownValueServer +} + +// Do implements the policy.Transporter interface for ArrayUnknownValueServerTransport. +func (a *ArrayUnknownValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *ArrayUnknownValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if arrayUnknownValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = arrayUnknownValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ArrayUnknownValueClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "ArrayUnknownValueClient.Put": + res.resp, res.err = a.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *ArrayUnknownValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := a.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).InterfaceArray, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *ArrayUnknownValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if a.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[[]any](req) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ArrayUnknownValueServerTransport +var arrayUnknownValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/arraygroup/fake/zz_internal.go b/test/http-specs/type/arraygroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/http-specs/type/arraygroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/http-specs/type/arraygroup/go.mod b/test/http-specs/type/arraygroup/go.mod new file mode 100644 index 000000000000..cee1de640490 --- /dev/null +++ b/test/http-specs/type/arraygroup/go.mod @@ -0,0 +1,17 @@ +module arraygroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/type/arraygroup/go.sum b/test/http-specs/type/arraygroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/type/arraygroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/type/arraygroup/testdata/_metadata.json b/test/http-specs/type/arraygroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/type/arraygroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/type/arraygroup/zz_array_client.go b/test/http-specs/type/arraygroup/zz_array_client.go new file mode 100644 index 000000000000..331fa8d24bbc --- /dev/null +++ b/test/http-specs/type/arraygroup/zz_array_client.go @@ -0,0 +1,152 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package arraygroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// ArrayClient - Illustrates various types of arrays. +// Don't use this type directly, use NewArrayClientWithNoCredential() instead. +type ArrayClient struct { + internal *azcore.Client + endpoint string +} + +// ArrayClientOptions contains the optional values for creating a [ArrayClient]. +type ArrayClientOptions struct { + azcore.ClientOptions +} + +// NewArrayClientWithNoCredential creates a new instance of ArrayClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewArrayClientWithNoCredential(endpoint string, options *ArrayClientOptions) (*ArrayClient, error) { + if options == nil { + options = &ArrayClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &ArrayClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewArrayBooleanValueClient creates a new instance of [ArrayBooleanValueClient]. +func (client *ArrayClient) NewArrayBooleanValueClient() *ArrayBooleanValueClient { + return &ArrayBooleanValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewArrayDatetimeValueClient creates a new instance of [ArrayDatetimeValueClient]. +func (client *ArrayClient) NewArrayDatetimeValueClient() *ArrayDatetimeValueClient { + return &ArrayDatetimeValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewArrayDurationValueClient creates a new instance of [ArrayDurationValueClient]. +func (client *ArrayClient) NewArrayDurationValueClient() *ArrayDurationValueClient { + return &ArrayDurationValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewArrayFloat32ValueClient creates a new instance of [ArrayFloat32ValueClient]. +func (client *ArrayClient) NewArrayFloat32ValueClient() *ArrayFloat32ValueClient { + return &ArrayFloat32ValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewArrayInt32ValueClient creates a new instance of [ArrayInt32ValueClient]. +func (client *ArrayClient) NewArrayInt32ValueClient() *ArrayInt32ValueClient { + return &ArrayInt32ValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewArrayInt64ValueClient creates a new instance of [ArrayInt64ValueClient]. +func (client *ArrayClient) NewArrayInt64ValueClient() *ArrayInt64ValueClient { + return &ArrayInt64ValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewArrayModelValueClient creates a new instance of [ArrayModelValueClient]. +func (client *ArrayClient) NewArrayModelValueClient() *ArrayModelValueClient { + return &ArrayModelValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewArrayNullableBooleanValueClient creates a new instance of [ArrayNullableBooleanValueClient]. +func (client *ArrayClient) NewArrayNullableBooleanValueClient() *ArrayNullableBooleanValueClient { + return &ArrayNullableBooleanValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewArrayNullableFloatValueClient creates a new instance of [ArrayNullableFloatValueClient]. +func (client *ArrayClient) NewArrayNullableFloatValueClient() *ArrayNullableFloatValueClient { + return &ArrayNullableFloatValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewArrayNullableInt32ValueClient creates a new instance of [ArrayNullableInt32ValueClient]. +func (client *ArrayClient) NewArrayNullableInt32ValueClient() *ArrayNullableInt32ValueClient { + return &ArrayNullableInt32ValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewArrayNullableModelValueClient creates a new instance of [ArrayNullableModelValueClient]. +func (client *ArrayClient) NewArrayNullableModelValueClient() *ArrayNullableModelValueClient { + return &ArrayNullableModelValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewArrayNullableStringValueClient creates a new instance of [ArrayNullableStringValueClient]. +func (client *ArrayClient) NewArrayNullableStringValueClient() *ArrayNullableStringValueClient { + return &ArrayNullableStringValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewArrayStringValueClient creates a new instance of [ArrayStringValueClient]. +func (client *ArrayClient) NewArrayStringValueClient() *ArrayStringValueClient { + return &ArrayStringValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewArrayUnknownValueClient creates a new instance of [ArrayUnknownValueClient]. +func (client *ArrayClient) NewArrayUnknownValueClient() *ArrayUnknownValueClient { + return &ArrayUnknownValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/http-specs/type/arraygroup/zz_arraybooleanvalue_client.go b/test/http-specs/type/arraygroup/zz_arraybooleanvalue_client.go new file mode 100644 index 000000000000..146d1bbba6ea --- /dev/null +++ b/test/http-specs/type/arraygroup/zz_arraybooleanvalue_client.go @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package arraygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ArrayBooleanValueClient - Array of boolean values +// Don't use this type directly, use [ArrayClient.NewArrayBooleanValueClient] instead. +type ArrayBooleanValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayBooleanValueClientGetOptions contains the optional parameters for the ArrayBooleanValueClient.Get method. +func (client *ArrayBooleanValueClient) Get(ctx context.Context, options *ArrayBooleanValueClientGetOptions) (ArrayBooleanValueClientGetResponse, error) { + var err error + const operationName = "ArrayBooleanValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ArrayBooleanValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayBooleanValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ArrayBooleanValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ArrayBooleanValueClient) getCreateRequest(ctx context.Context, _ *ArrayBooleanValueClientGetOptions) (*policy.Request, error) { + urlPath := "/type/array/boolean" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ArrayBooleanValueClient) getHandleResponse(resp *http.Response) (ArrayBooleanValueClientGetResponse, error) { + result := ArrayBooleanValueClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BoolArray); err != nil { + return ArrayBooleanValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayBooleanValueClientPutOptions contains the optional parameters for the ArrayBooleanValueClient.Put method. +func (client *ArrayBooleanValueClient) Put(ctx context.Context, body []bool, options *ArrayBooleanValueClientPutOptions) (ArrayBooleanValueClientPutResponse, error) { + var err error + const operationName = "ArrayBooleanValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ArrayBooleanValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayBooleanValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ArrayBooleanValueClientPutResponse{}, err + } + return ArrayBooleanValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ArrayBooleanValueClient) putCreateRequest(ctx context.Context, body []bool, _ *ArrayBooleanValueClientPutOptions) (*policy.Request, error) { + urlPath := "/type/array/boolean" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/arraygroup/zz_arraydatetimevalue_client.go b/test/http-specs/type/arraygroup/zz_arraydatetimevalue_client.go new file mode 100644 index 000000000000..db0eef9e5197 --- /dev/null +++ b/test/http-specs/type/arraygroup/zz_arraydatetimevalue_client.go @@ -0,0 +1,111 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package arraygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "net/http" + "time" +) + +// ArrayDatetimeValueClient - Array of datetime values +// Don't use this type directly, use [ArrayClient.NewArrayDatetimeValueClient] instead. +type ArrayDatetimeValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayDatetimeValueClientGetOptions contains the optional parameters for the ArrayDatetimeValueClient.Get method. +func (client *ArrayDatetimeValueClient) Get(ctx context.Context, options *ArrayDatetimeValueClientGetOptions) (ArrayDatetimeValueClientGetResponse, error) { + var err error + const operationName = "ArrayDatetimeValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ArrayDatetimeValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayDatetimeValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ArrayDatetimeValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ArrayDatetimeValueClient) getCreateRequest(ctx context.Context, _ *ArrayDatetimeValueClientGetOptions) (*policy.Request, error) { + urlPath := "/type/array/datetime" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ArrayDatetimeValueClient) getHandleResponse(resp *http.Response) (ArrayDatetimeValueClientGetResponse, error) { + result := ArrayDatetimeValueClientGetResponse{} + var aux []datetime.RFC3339 + if err := runtime.UnmarshalAsJSON(resp, &aux); err != nil { + return ArrayDatetimeValueClientGetResponse{}, err + } + cp := make([]time.Time, len(aux)) + for i := 0; i < len(aux); i++ { + cp[i] = (time.Time)(aux[i]) + } + result.TimeArray = cp + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayDatetimeValueClientPutOptions contains the optional parameters for the ArrayDatetimeValueClient.Put method. +func (client *ArrayDatetimeValueClient) Put(ctx context.Context, body []time.Time, options *ArrayDatetimeValueClientPutOptions) (ArrayDatetimeValueClientPutResponse, error) { + var err error + const operationName = "ArrayDatetimeValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ArrayDatetimeValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayDatetimeValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ArrayDatetimeValueClientPutResponse{}, err + } + return ArrayDatetimeValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ArrayDatetimeValueClient) putCreateRequest(ctx context.Context, body []time.Time, _ *ArrayDatetimeValueClientPutOptions) (*policy.Request, error) { + urlPath := "/type/array/datetime" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/arraygroup/zz_arraydurationvalue_client.go b/test/http-specs/type/arraygroup/zz_arraydurationvalue_client.go new file mode 100644 index 000000000000..6269a9b9326c --- /dev/null +++ b/test/http-specs/type/arraygroup/zz_arraydurationvalue_client.go @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package arraygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ArrayDurationValueClient - Array of duration values +// Don't use this type directly, use [ArrayClient.NewArrayDurationValueClient] instead. +type ArrayDurationValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayDurationValueClientGetOptions contains the optional parameters for the ArrayDurationValueClient.Get method. +func (client *ArrayDurationValueClient) Get(ctx context.Context, options *ArrayDurationValueClientGetOptions) (ArrayDurationValueClientGetResponse, error) { + var err error + const operationName = "ArrayDurationValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ArrayDurationValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayDurationValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ArrayDurationValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ArrayDurationValueClient) getCreateRequest(ctx context.Context, _ *ArrayDurationValueClientGetOptions) (*policy.Request, error) { + urlPath := "/type/array/duration" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ArrayDurationValueClient) getHandleResponse(resp *http.Response) (ArrayDurationValueClientGetResponse, error) { + result := ArrayDurationValueClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.StringArray); err != nil { + return ArrayDurationValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayDurationValueClientPutOptions contains the optional parameters for the ArrayDurationValueClient.Put method. +func (client *ArrayDurationValueClient) Put(ctx context.Context, body []string, options *ArrayDurationValueClientPutOptions) (ArrayDurationValueClientPutResponse, error) { + var err error + const operationName = "ArrayDurationValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ArrayDurationValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayDurationValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ArrayDurationValueClientPutResponse{}, err + } + return ArrayDurationValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ArrayDurationValueClient) putCreateRequest(ctx context.Context, body []string, _ *ArrayDurationValueClientPutOptions) (*policy.Request, error) { + urlPath := "/type/array/duration" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/arraygroup/zz_arrayfloat32value_client.go b/test/http-specs/type/arraygroup/zz_arrayfloat32value_client.go new file mode 100644 index 000000000000..179c52ae54a1 --- /dev/null +++ b/test/http-specs/type/arraygroup/zz_arrayfloat32value_client.go @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package arraygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ArrayFloat32ValueClient - Array of float values +// Don't use this type directly, use [ArrayClient.NewArrayFloat32ValueClient] instead. +type ArrayFloat32ValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayFloat32ValueClientGetOptions contains the optional parameters for the ArrayFloat32ValueClient.Get method. +func (client *ArrayFloat32ValueClient) Get(ctx context.Context, options *ArrayFloat32ValueClientGetOptions) (ArrayFloat32ValueClientGetResponse, error) { + var err error + const operationName = "ArrayFloat32ValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ArrayFloat32ValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayFloat32ValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ArrayFloat32ValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ArrayFloat32ValueClient) getCreateRequest(ctx context.Context, _ *ArrayFloat32ValueClientGetOptions) (*policy.Request, error) { + urlPath := "/type/array/float32" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ArrayFloat32ValueClient) getHandleResponse(resp *http.Response) (ArrayFloat32ValueClientGetResponse, error) { + result := ArrayFloat32ValueClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Float32Array); err != nil { + return ArrayFloat32ValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayFloat32ValueClientPutOptions contains the optional parameters for the ArrayFloat32ValueClient.Put method. +func (client *ArrayFloat32ValueClient) Put(ctx context.Context, body []float32, options *ArrayFloat32ValueClientPutOptions) (ArrayFloat32ValueClientPutResponse, error) { + var err error + const operationName = "ArrayFloat32ValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ArrayFloat32ValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayFloat32ValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ArrayFloat32ValueClientPutResponse{}, err + } + return ArrayFloat32ValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ArrayFloat32ValueClient) putCreateRequest(ctx context.Context, body []float32, _ *ArrayFloat32ValueClientPutOptions) (*policy.Request, error) { + urlPath := "/type/array/float32" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/arraygroup/zz_arrayint32value_client.go b/test/http-specs/type/arraygroup/zz_arrayint32value_client.go new file mode 100644 index 000000000000..b86aafe1f31c --- /dev/null +++ b/test/http-specs/type/arraygroup/zz_arrayint32value_client.go @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package arraygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ArrayInt32ValueClient - Array of int32 values +// Don't use this type directly, use [ArrayClient.NewArrayInt32ValueClient] instead. +type ArrayInt32ValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayInt32ValueClientGetOptions contains the optional parameters for the ArrayInt32ValueClient.Get method. +func (client *ArrayInt32ValueClient) Get(ctx context.Context, options *ArrayInt32ValueClientGetOptions) (ArrayInt32ValueClientGetResponse, error) { + var err error + const operationName = "ArrayInt32ValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ArrayInt32ValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayInt32ValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ArrayInt32ValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ArrayInt32ValueClient) getCreateRequest(ctx context.Context, _ *ArrayInt32ValueClientGetOptions) (*policy.Request, error) { + urlPath := "/type/array/int32" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ArrayInt32ValueClient) getHandleResponse(resp *http.Response) (ArrayInt32ValueClientGetResponse, error) { + result := ArrayInt32ValueClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Int32Array); err != nil { + return ArrayInt32ValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayInt32ValueClientPutOptions contains the optional parameters for the ArrayInt32ValueClient.Put method. +func (client *ArrayInt32ValueClient) Put(ctx context.Context, body []int32, options *ArrayInt32ValueClientPutOptions) (ArrayInt32ValueClientPutResponse, error) { + var err error + const operationName = "ArrayInt32ValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ArrayInt32ValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayInt32ValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ArrayInt32ValueClientPutResponse{}, err + } + return ArrayInt32ValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ArrayInt32ValueClient) putCreateRequest(ctx context.Context, body []int32, _ *ArrayInt32ValueClientPutOptions) (*policy.Request, error) { + urlPath := "/type/array/int32" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/arraygroup/zz_arrayint64value_client.go b/test/http-specs/type/arraygroup/zz_arrayint64value_client.go new file mode 100644 index 000000000000..b1f9680123d0 --- /dev/null +++ b/test/http-specs/type/arraygroup/zz_arrayint64value_client.go @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package arraygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ArrayInt64ValueClient - Array of int64 values +// Don't use this type directly, use [ArrayClient.NewArrayInt64ValueClient] instead. +type ArrayInt64ValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayInt64ValueClientGetOptions contains the optional parameters for the ArrayInt64ValueClient.Get method. +func (client *ArrayInt64ValueClient) Get(ctx context.Context, options *ArrayInt64ValueClientGetOptions) (ArrayInt64ValueClientGetResponse, error) { + var err error + const operationName = "ArrayInt64ValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ArrayInt64ValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayInt64ValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ArrayInt64ValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ArrayInt64ValueClient) getCreateRequest(ctx context.Context, _ *ArrayInt64ValueClientGetOptions) (*policy.Request, error) { + urlPath := "/type/array/int64" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ArrayInt64ValueClient) getHandleResponse(resp *http.Response) (ArrayInt64ValueClientGetResponse, error) { + result := ArrayInt64ValueClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Int64Array); err != nil { + return ArrayInt64ValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayInt64ValueClientPutOptions contains the optional parameters for the ArrayInt64ValueClient.Put method. +func (client *ArrayInt64ValueClient) Put(ctx context.Context, body []int64, options *ArrayInt64ValueClientPutOptions) (ArrayInt64ValueClientPutResponse, error) { + var err error + const operationName = "ArrayInt64ValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ArrayInt64ValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayInt64ValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ArrayInt64ValueClientPutResponse{}, err + } + return ArrayInt64ValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ArrayInt64ValueClient) putCreateRequest(ctx context.Context, body []int64, _ *ArrayInt64ValueClientPutOptions) (*policy.Request, error) { + urlPath := "/type/array/int64" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/arraygroup/zz_arraymodelvalue_client.go b/test/http-specs/type/arraygroup/zz_arraymodelvalue_client.go new file mode 100644 index 000000000000..97701ffb546b --- /dev/null +++ b/test/http-specs/type/arraygroup/zz_arraymodelvalue_client.go @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package arraygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ArrayModelValueClient - Array of model values +// Don't use this type directly, use [ArrayClient.NewArrayModelValueClient] instead. +type ArrayModelValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayModelValueClientGetOptions contains the optional parameters for the ArrayModelValueClient.Get method. +func (client *ArrayModelValueClient) Get(ctx context.Context, options *ArrayModelValueClientGetOptions) (ArrayModelValueClientGetResponse, error) { + var err error + const operationName = "ArrayModelValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ArrayModelValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayModelValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ArrayModelValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ArrayModelValueClient) getCreateRequest(ctx context.Context, _ *ArrayModelValueClientGetOptions) (*policy.Request, error) { + urlPath := "/type/array/model" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ArrayModelValueClient) getHandleResponse(resp *http.Response) (ArrayModelValueClientGetResponse, error) { + result := ArrayModelValueClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.InnerModelArray); err != nil { + return ArrayModelValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayModelValueClientPutOptions contains the optional parameters for the ArrayModelValueClient.Put method. +func (client *ArrayModelValueClient) Put(ctx context.Context, body []InnerModel, options *ArrayModelValueClientPutOptions) (ArrayModelValueClientPutResponse, error) { + var err error + const operationName = "ArrayModelValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ArrayModelValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayModelValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ArrayModelValueClientPutResponse{}, err + } + return ArrayModelValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ArrayModelValueClient) putCreateRequest(ctx context.Context, body []InnerModel, _ *ArrayModelValueClientPutOptions) (*policy.Request, error) { + urlPath := "/type/array/model" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/arraygroup/zz_arraynullablebooleanvalue_client.go b/test/http-specs/type/arraygroup/zz_arraynullablebooleanvalue_client.go new file mode 100644 index 000000000000..3acbfabb1f2f --- /dev/null +++ b/test/http-specs/type/arraygroup/zz_arraynullablebooleanvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package arraygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ArrayNullableBooleanValueClient - Array of nullable boolean values +// Don't use this type directly, use [ArrayClient.NewArrayNullableBooleanValueClient] instead. +type ArrayNullableBooleanValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayNullableBooleanValueClientGetOptions contains the optional parameters for the ArrayNullableBooleanValueClient.Get +// method. +func (client *ArrayNullableBooleanValueClient) Get(ctx context.Context, options *ArrayNullableBooleanValueClientGetOptions) (ArrayNullableBooleanValueClientGetResponse, error) { + var err error + const operationName = "ArrayNullableBooleanValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ArrayNullableBooleanValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayNullableBooleanValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ArrayNullableBooleanValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ArrayNullableBooleanValueClient) getCreateRequest(ctx context.Context, _ *ArrayNullableBooleanValueClientGetOptions) (*policy.Request, error) { + urlPath := "/type/array/nullable-boolean" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ArrayNullableBooleanValueClient) getHandleResponse(resp *http.Response) (ArrayNullableBooleanValueClientGetResponse, error) { + result := ArrayNullableBooleanValueClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BoolArray); err != nil { + return ArrayNullableBooleanValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayNullableBooleanValueClientPutOptions contains the optional parameters for the ArrayNullableBooleanValueClient.Put +// method. +func (client *ArrayNullableBooleanValueClient) Put(ctx context.Context, body []*bool, options *ArrayNullableBooleanValueClientPutOptions) (ArrayNullableBooleanValueClientPutResponse, error) { + var err error + const operationName = "ArrayNullableBooleanValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ArrayNullableBooleanValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayNullableBooleanValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ArrayNullableBooleanValueClientPutResponse{}, err + } + return ArrayNullableBooleanValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ArrayNullableBooleanValueClient) putCreateRequest(ctx context.Context, body []*bool, _ *ArrayNullableBooleanValueClientPutOptions) (*policy.Request, error) { + urlPath := "/type/array/nullable-boolean" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/arraygroup/zz_arraynullablefloatvalue_client.go b/test/http-specs/type/arraygroup/zz_arraynullablefloatvalue_client.go new file mode 100644 index 000000000000..4f68bba85ef0 --- /dev/null +++ b/test/http-specs/type/arraygroup/zz_arraynullablefloatvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package arraygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ArrayNullableFloatValueClient - Array of nullable float values +// Don't use this type directly, use [ArrayClient.NewArrayNullableFloatValueClient] instead. +type ArrayNullableFloatValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayNullableFloatValueClientGetOptions contains the optional parameters for the ArrayNullableFloatValueClient.Get +// method. +func (client *ArrayNullableFloatValueClient) Get(ctx context.Context, options *ArrayNullableFloatValueClientGetOptions) (ArrayNullableFloatValueClientGetResponse, error) { + var err error + const operationName = "ArrayNullableFloatValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ArrayNullableFloatValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayNullableFloatValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ArrayNullableFloatValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ArrayNullableFloatValueClient) getCreateRequest(ctx context.Context, _ *ArrayNullableFloatValueClientGetOptions) (*policy.Request, error) { + urlPath := "/type/array/nullable-float" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ArrayNullableFloatValueClient) getHandleResponse(resp *http.Response) (ArrayNullableFloatValueClientGetResponse, error) { + result := ArrayNullableFloatValueClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Float32Array); err != nil { + return ArrayNullableFloatValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayNullableFloatValueClientPutOptions contains the optional parameters for the ArrayNullableFloatValueClient.Put +// method. +func (client *ArrayNullableFloatValueClient) Put(ctx context.Context, body []*float32, options *ArrayNullableFloatValueClientPutOptions) (ArrayNullableFloatValueClientPutResponse, error) { + var err error + const operationName = "ArrayNullableFloatValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ArrayNullableFloatValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayNullableFloatValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ArrayNullableFloatValueClientPutResponse{}, err + } + return ArrayNullableFloatValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ArrayNullableFloatValueClient) putCreateRequest(ctx context.Context, body []*float32, _ *ArrayNullableFloatValueClientPutOptions) (*policy.Request, error) { + urlPath := "/type/array/nullable-float" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/arraygroup/zz_arraynullableint32value_client.go b/test/http-specs/type/arraygroup/zz_arraynullableint32value_client.go new file mode 100644 index 000000000000..52bdbd82f8c3 --- /dev/null +++ b/test/http-specs/type/arraygroup/zz_arraynullableint32value_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package arraygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ArrayNullableInt32ValueClient - Array of nullable int32 values +// Don't use this type directly, use [ArrayClient.NewArrayNullableInt32ValueClient] instead. +type ArrayNullableInt32ValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayNullableInt32ValueClientGetOptions contains the optional parameters for the ArrayNullableInt32ValueClient.Get +// method. +func (client *ArrayNullableInt32ValueClient) Get(ctx context.Context, options *ArrayNullableInt32ValueClientGetOptions) (ArrayNullableInt32ValueClientGetResponse, error) { + var err error + const operationName = "ArrayNullableInt32ValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ArrayNullableInt32ValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayNullableInt32ValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ArrayNullableInt32ValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ArrayNullableInt32ValueClient) getCreateRequest(ctx context.Context, _ *ArrayNullableInt32ValueClientGetOptions) (*policy.Request, error) { + urlPath := "/type/array/nullable-int32" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ArrayNullableInt32ValueClient) getHandleResponse(resp *http.Response) (ArrayNullableInt32ValueClientGetResponse, error) { + result := ArrayNullableInt32ValueClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Int32Array); err != nil { + return ArrayNullableInt32ValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayNullableInt32ValueClientPutOptions contains the optional parameters for the ArrayNullableInt32ValueClient.Put +// method. +func (client *ArrayNullableInt32ValueClient) Put(ctx context.Context, body []*int32, options *ArrayNullableInt32ValueClientPutOptions) (ArrayNullableInt32ValueClientPutResponse, error) { + var err error + const operationName = "ArrayNullableInt32ValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ArrayNullableInt32ValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayNullableInt32ValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ArrayNullableInt32ValueClientPutResponse{}, err + } + return ArrayNullableInt32ValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ArrayNullableInt32ValueClient) putCreateRequest(ctx context.Context, body []*int32, _ *ArrayNullableInt32ValueClientPutOptions) (*policy.Request, error) { + urlPath := "/type/array/nullable-int32" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/arraygroup/zz_arraynullablemodelvalue_client.go b/test/http-specs/type/arraygroup/zz_arraynullablemodelvalue_client.go new file mode 100644 index 000000000000..dd970b8fbcad --- /dev/null +++ b/test/http-specs/type/arraygroup/zz_arraynullablemodelvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package arraygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ArrayNullableModelValueClient - Array of nullable model values +// Don't use this type directly, use [ArrayClient.NewArrayNullableModelValueClient] instead. +type ArrayNullableModelValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayNullableModelValueClientGetOptions contains the optional parameters for the ArrayNullableModelValueClient.Get +// method. +func (client *ArrayNullableModelValueClient) Get(ctx context.Context, options *ArrayNullableModelValueClientGetOptions) (ArrayNullableModelValueClientGetResponse, error) { + var err error + const operationName = "ArrayNullableModelValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ArrayNullableModelValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayNullableModelValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ArrayNullableModelValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ArrayNullableModelValueClient) getCreateRequest(ctx context.Context, _ *ArrayNullableModelValueClientGetOptions) (*policy.Request, error) { + urlPath := "/type/array/nullable-model" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ArrayNullableModelValueClient) getHandleResponse(resp *http.Response) (ArrayNullableModelValueClientGetResponse, error) { + result := ArrayNullableModelValueClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.InnerModelArray); err != nil { + return ArrayNullableModelValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayNullableModelValueClientPutOptions contains the optional parameters for the ArrayNullableModelValueClient.Put +// method. +func (client *ArrayNullableModelValueClient) Put(ctx context.Context, body []*InnerModel, options *ArrayNullableModelValueClientPutOptions) (ArrayNullableModelValueClientPutResponse, error) { + var err error + const operationName = "ArrayNullableModelValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ArrayNullableModelValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayNullableModelValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ArrayNullableModelValueClientPutResponse{}, err + } + return ArrayNullableModelValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ArrayNullableModelValueClient) putCreateRequest(ctx context.Context, body []*InnerModel, _ *ArrayNullableModelValueClientPutOptions) (*policy.Request, error) { + urlPath := "/type/array/nullable-model" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/arraygroup/zz_arraynullablestringvalue_client.go b/test/http-specs/type/arraygroup/zz_arraynullablestringvalue_client.go new file mode 100644 index 000000000000..e879d78b0648 --- /dev/null +++ b/test/http-specs/type/arraygroup/zz_arraynullablestringvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package arraygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ArrayNullableStringValueClient - Array of nullable string values +// Don't use this type directly, use [ArrayClient.NewArrayNullableStringValueClient] instead. +type ArrayNullableStringValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayNullableStringValueClientGetOptions contains the optional parameters for the ArrayNullableStringValueClient.Get +// method. +func (client *ArrayNullableStringValueClient) Get(ctx context.Context, options *ArrayNullableStringValueClientGetOptions) (ArrayNullableStringValueClientGetResponse, error) { + var err error + const operationName = "ArrayNullableStringValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ArrayNullableStringValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayNullableStringValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ArrayNullableStringValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ArrayNullableStringValueClient) getCreateRequest(ctx context.Context, _ *ArrayNullableStringValueClientGetOptions) (*policy.Request, error) { + urlPath := "/type/array/nullable-string" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ArrayNullableStringValueClient) getHandleResponse(resp *http.Response) (ArrayNullableStringValueClientGetResponse, error) { + result := ArrayNullableStringValueClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.StringArray); err != nil { + return ArrayNullableStringValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayNullableStringValueClientPutOptions contains the optional parameters for the ArrayNullableStringValueClient.Put +// method. +func (client *ArrayNullableStringValueClient) Put(ctx context.Context, body []*string, options *ArrayNullableStringValueClientPutOptions) (ArrayNullableStringValueClientPutResponse, error) { + var err error + const operationName = "ArrayNullableStringValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ArrayNullableStringValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayNullableStringValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ArrayNullableStringValueClientPutResponse{}, err + } + return ArrayNullableStringValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ArrayNullableStringValueClient) putCreateRequest(ctx context.Context, body []*string, _ *ArrayNullableStringValueClientPutOptions) (*policy.Request, error) { + urlPath := "/type/array/nullable-string" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/arraygroup/zz_arraystringvalue_client.go b/test/http-specs/type/arraygroup/zz_arraystringvalue_client.go new file mode 100644 index 000000000000..9d4e42f023af --- /dev/null +++ b/test/http-specs/type/arraygroup/zz_arraystringvalue_client.go @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package arraygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ArrayStringValueClient - Array of string values +// Don't use this type directly, use [ArrayClient.NewArrayStringValueClient] instead. +type ArrayStringValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayStringValueClientGetOptions contains the optional parameters for the ArrayStringValueClient.Get method. +func (client *ArrayStringValueClient) Get(ctx context.Context, options *ArrayStringValueClientGetOptions) (ArrayStringValueClientGetResponse, error) { + var err error + const operationName = "ArrayStringValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ArrayStringValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayStringValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ArrayStringValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ArrayStringValueClient) getCreateRequest(ctx context.Context, _ *ArrayStringValueClientGetOptions) (*policy.Request, error) { + urlPath := "/type/array/string" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ArrayStringValueClient) getHandleResponse(resp *http.Response) (ArrayStringValueClientGetResponse, error) { + result := ArrayStringValueClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.StringArray); err != nil { + return ArrayStringValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayStringValueClientPutOptions contains the optional parameters for the ArrayStringValueClient.Put method. +func (client *ArrayStringValueClient) Put(ctx context.Context, body []string, options *ArrayStringValueClientPutOptions) (ArrayStringValueClientPutResponse, error) { + var err error + const operationName = "ArrayStringValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ArrayStringValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayStringValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ArrayStringValueClientPutResponse{}, err + } + return ArrayStringValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ArrayStringValueClient) putCreateRequest(ctx context.Context, body []string, _ *ArrayStringValueClientPutOptions) (*policy.Request, error) { + urlPath := "/type/array/string" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/arraygroup/zz_arrayunknownvalue_client.go b/test/http-specs/type/arraygroup/zz_arrayunknownvalue_client.go new file mode 100644 index 000000000000..19b727fab0eb --- /dev/null +++ b/test/http-specs/type/arraygroup/zz_arrayunknownvalue_client.go @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package arraygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ArrayUnknownValueClient - Array of unknown values +// Don't use this type directly, use [ArrayClient.NewArrayUnknownValueClient] instead. +type ArrayUnknownValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayUnknownValueClientGetOptions contains the optional parameters for the ArrayUnknownValueClient.Get method. +func (client *ArrayUnknownValueClient) Get(ctx context.Context, options *ArrayUnknownValueClientGetOptions) (ArrayUnknownValueClientGetResponse, error) { + var err error + const operationName = "ArrayUnknownValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ArrayUnknownValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayUnknownValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ArrayUnknownValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ArrayUnknownValueClient) getCreateRequest(ctx context.Context, _ *ArrayUnknownValueClientGetOptions) (*policy.Request, error) { + urlPath := "/type/array/unknown" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ArrayUnknownValueClient) getHandleResponse(resp *http.Response) (ArrayUnknownValueClientGetResponse, error) { + result := ArrayUnknownValueClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.InterfaceArray); err != nil { + return ArrayUnknownValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ArrayUnknownValueClientPutOptions contains the optional parameters for the ArrayUnknownValueClient.Put method. +func (client *ArrayUnknownValueClient) Put(ctx context.Context, body []any, options *ArrayUnknownValueClientPutOptions) (ArrayUnknownValueClientPutResponse, error) { + var err error + const operationName = "ArrayUnknownValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ArrayUnknownValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ArrayUnknownValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ArrayUnknownValueClientPutResponse{}, err + } + return ArrayUnknownValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ArrayUnknownValueClient) putCreateRequest(ctx context.Context, body []any, _ *ArrayUnknownValueClientPutOptions) (*policy.Request, error) { + urlPath := "/type/array/unknown" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/arraygroup/zz_models.go b/test/http-specs/type/arraygroup/zz_models.go new file mode 100644 index 000000000000..a7252c92f7db --- /dev/null +++ b/test/http-specs/type/arraygroup/zz_models.go @@ -0,0 +1,12 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package arraygroup + +// InnerModel - Array inner model +type InnerModel struct { + // REQUIRED; Required string property + Property *string + Children []InnerModel +} diff --git a/test/http-specs/type/arraygroup/zz_models_serde.go b/test/http-specs/type/arraygroup/zz_models_serde.go new file mode 100644 index 000000000000..0431f712f095 --- /dev/null +++ b/test/http-specs/type/arraygroup/zz_models_serde.go @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package arraygroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type InnerModel. +func (i InnerModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "children", i.Children) + populate(objectMap, "property", i.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InnerModel. +func (i *InnerModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "children": + err = unpopulate(val, "Children", &i.Children) + delete(rawMsg, key) + case "property": + err = unpopulate(val, "Property", &i.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/http-specs/type/arraygroup/zz_options.go b/test/http-specs/type/arraygroup/zz_options.go new file mode 100644 index 000000000000..0341eceebc94 --- /dev/null +++ b/test/http-specs/type/arraygroup/zz_options.go @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package arraygroup + +// ArrayBooleanValueClientGetOptions contains the optional parameters for the ArrayBooleanValueClient.Get method. +type ArrayBooleanValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// ArrayBooleanValueClientPutOptions contains the optional parameters for the ArrayBooleanValueClient.Put method. +type ArrayBooleanValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// ArrayDatetimeValueClientGetOptions contains the optional parameters for the ArrayDatetimeValueClient.Get method. +type ArrayDatetimeValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// ArrayDatetimeValueClientPutOptions contains the optional parameters for the ArrayDatetimeValueClient.Put method. +type ArrayDatetimeValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// ArrayDurationValueClientGetOptions contains the optional parameters for the ArrayDurationValueClient.Get method. +type ArrayDurationValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// ArrayDurationValueClientPutOptions contains the optional parameters for the ArrayDurationValueClient.Put method. +type ArrayDurationValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// ArrayFloat32ValueClientGetOptions contains the optional parameters for the ArrayFloat32ValueClient.Get method. +type ArrayFloat32ValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// ArrayFloat32ValueClientPutOptions contains the optional parameters for the ArrayFloat32ValueClient.Put method. +type ArrayFloat32ValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// ArrayInt32ValueClientGetOptions contains the optional parameters for the ArrayInt32ValueClient.Get method. +type ArrayInt32ValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// ArrayInt32ValueClientPutOptions contains the optional parameters for the ArrayInt32ValueClient.Put method. +type ArrayInt32ValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// ArrayInt64ValueClientGetOptions contains the optional parameters for the ArrayInt64ValueClient.Get method. +type ArrayInt64ValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// ArrayInt64ValueClientPutOptions contains the optional parameters for the ArrayInt64ValueClient.Put method. +type ArrayInt64ValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// ArrayModelValueClientGetOptions contains the optional parameters for the ArrayModelValueClient.Get method. +type ArrayModelValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// ArrayModelValueClientPutOptions contains the optional parameters for the ArrayModelValueClient.Put method. +type ArrayModelValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// ArrayNullableBooleanValueClientGetOptions contains the optional parameters for the ArrayNullableBooleanValueClient.Get +// method. +type ArrayNullableBooleanValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// ArrayNullableBooleanValueClientPutOptions contains the optional parameters for the ArrayNullableBooleanValueClient.Put +// method. +type ArrayNullableBooleanValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// ArrayNullableFloatValueClientGetOptions contains the optional parameters for the ArrayNullableFloatValueClient.Get method. +type ArrayNullableFloatValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// ArrayNullableFloatValueClientPutOptions contains the optional parameters for the ArrayNullableFloatValueClient.Put method. +type ArrayNullableFloatValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// ArrayNullableInt32ValueClientGetOptions contains the optional parameters for the ArrayNullableInt32ValueClient.Get method. +type ArrayNullableInt32ValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// ArrayNullableInt32ValueClientPutOptions contains the optional parameters for the ArrayNullableInt32ValueClient.Put method. +type ArrayNullableInt32ValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// ArrayNullableModelValueClientGetOptions contains the optional parameters for the ArrayNullableModelValueClient.Get method. +type ArrayNullableModelValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// ArrayNullableModelValueClientPutOptions contains the optional parameters for the ArrayNullableModelValueClient.Put method. +type ArrayNullableModelValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// ArrayNullableStringValueClientGetOptions contains the optional parameters for the ArrayNullableStringValueClient.Get method. +type ArrayNullableStringValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// ArrayNullableStringValueClientPutOptions contains the optional parameters for the ArrayNullableStringValueClient.Put method. +type ArrayNullableStringValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// ArrayStringValueClientGetOptions contains the optional parameters for the ArrayStringValueClient.Get method. +type ArrayStringValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// ArrayStringValueClientPutOptions contains the optional parameters for the ArrayStringValueClient.Put method. +type ArrayStringValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// ArrayUnknownValueClientGetOptions contains the optional parameters for the ArrayUnknownValueClient.Get method. +type ArrayUnknownValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// ArrayUnknownValueClientPutOptions contains the optional parameters for the ArrayUnknownValueClient.Put method. +type ArrayUnknownValueClientPutOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/type/arraygroup/zz_responses.go b/test/http-specs/type/arraygroup/zz_responses.go new file mode 100644 index 000000000000..64d1043b5eda --- /dev/null +++ b/test/http-specs/type/arraygroup/zz_responses.go @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package arraygroup + +import "time" + +// ArrayBooleanValueClientGetResponse contains the response from method ArrayBooleanValueClient.Get. +type ArrayBooleanValueClientGetResponse struct { + BoolArray []bool +} + +// ArrayBooleanValueClientPutResponse contains the response from method ArrayBooleanValueClient.Put. +type ArrayBooleanValueClientPutResponse struct { + // placeholder for future response values +} + +// ArrayDatetimeValueClientGetResponse contains the response from method ArrayDatetimeValueClient.Get. +type ArrayDatetimeValueClientGetResponse struct { + TimeArray []time.Time +} + +// ArrayDatetimeValueClientPutResponse contains the response from method ArrayDatetimeValueClient.Put. +type ArrayDatetimeValueClientPutResponse struct { + // placeholder for future response values +} + +// ArrayDurationValueClientGetResponse contains the response from method ArrayDurationValueClient.Get. +type ArrayDurationValueClientGetResponse struct { + StringArray []string +} + +// ArrayDurationValueClientPutResponse contains the response from method ArrayDurationValueClient.Put. +type ArrayDurationValueClientPutResponse struct { + // placeholder for future response values +} + +// ArrayFloat32ValueClientGetResponse contains the response from method ArrayFloat32ValueClient.Get. +type ArrayFloat32ValueClientGetResponse struct { + Float32Array []float32 +} + +// ArrayFloat32ValueClientPutResponse contains the response from method ArrayFloat32ValueClient.Put. +type ArrayFloat32ValueClientPutResponse struct { + // placeholder for future response values +} + +// ArrayInt32ValueClientGetResponse contains the response from method ArrayInt32ValueClient.Get. +type ArrayInt32ValueClientGetResponse struct { + Int32Array []int32 +} + +// ArrayInt32ValueClientPutResponse contains the response from method ArrayInt32ValueClient.Put. +type ArrayInt32ValueClientPutResponse struct { + // placeholder for future response values +} + +// ArrayInt64ValueClientGetResponse contains the response from method ArrayInt64ValueClient.Get. +type ArrayInt64ValueClientGetResponse struct { + Int64Array []int64 +} + +// ArrayInt64ValueClientPutResponse contains the response from method ArrayInt64ValueClient.Put. +type ArrayInt64ValueClientPutResponse struct { + // placeholder for future response values +} + +// ArrayModelValueClientGetResponse contains the response from method ArrayModelValueClient.Get. +type ArrayModelValueClientGetResponse struct { + InnerModelArray []InnerModel +} + +// ArrayModelValueClientPutResponse contains the response from method ArrayModelValueClient.Put. +type ArrayModelValueClientPutResponse struct { + // placeholder for future response values +} + +// ArrayNullableBooleanValueClientGetResponse contains the response from method ArrayNullableBooleanValueClient.Get. +type ArrayNullableBooleanValueClientGetResponse struct { + BoolArray []*bool +} + +// ArrayNullableBooleanValueClientPutResponse contains the response from method ArrayNullableBooleanValueClient.Put. +type ArrayNullableBooleanValueClientPutResponse struct { + // placeholder for future response values +} + +// ArrayNullableFloatValueClientGetResponse contains the response from method ArrayNullableFloatValueClient.Get. +type ArrayNullableFloatValueClientGetResponse struct { + Float32Array []*float32 +} + +// ArrayNullableFloatValueClientPutResponse contains the response from method ArrayNullableFloatValueClient.Put. +type ArrayNullableFloatValueClientPutResponse struct { + // placeholder for future response values +} + +// ArrayNullableInt32ValueClientGetResponse contains the response from method ArrayNullableInt32ValueClient.Get. +type ArrayNullableInt32ValueClientGetResponse struct { + Int32Array []*int32 +} + +// ArrayNullableInt32ValueClientPutResponse contains the response from method ArrayNullableInt32ValueClient.Put. +type ArrayNullableInt32ValueClientPutResponse struct { + // placeholder for future response values +} + +// ArrayNullableModelValueClientGetResponse contains the response from method ArrayNullableModelValueClient.Get. +type ArrayNullableModelValueClientGetResponse struct { + InnerModelArray []*InnerModel +} + +// ArrayNullableModelValueClientPutResponse contains the response from method ArrayNullableModelValueClient.Put. +type ArrayNullableModelValueClientPutResponse struct { + // placeholder for future response values +} + +// ArrayNullableStringValueClientGetResponse contains the response from method ArrayNullableStringValueClient.Get. +type ArrayNullableStringValueClientGetResponse struct { + StringArray []*string +} + +// ArrayNullableStringValueClientPutResponse contains the response from method ArrayNullableStringValueClient.Put. +type ArrayNullableStringValueClientPutResponse struct { + // placeholder for future response values +} + +// ArrayStringValueClientGetResponse contains the response from method ArrayStringValueClient.Get. +type ArrayStringValueClientGetResponse struct { + StringArray []string +} + +// ArrayStringValueClientPutResponse contains the response from method ArrayStringValueClient.Put. +type ArrayStringValueClientPutResponse struct { + // placeholder for future response values +} + +// ArrayUnknownValueClientGetResponse contains the response from method ArrayUnknownValueClient.Get. +type ArrayUnknownValueClientGetResponse struct { + InterfaceArray []any +} + +// ArrayUnknownValueClientPutResponse contains the response from method ArrayUnknownValueClient.Put. +type ArrayUnknownValueClientPutResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/type/arraygroup/zz_version.go b/test/http-specs/type/arraygroup/zz_version.go new file mode 100644 index 000000000000..424f2da00812 --- /dev/null +++ b/test/http-specs/type/arraygroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package arraygroup + +const ( + moduleName = "arraygroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/type/dictionarygroup/LICENSE.txt b/test/http-specs/type/dictionarygroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/type/dictionarygroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/type/dictionarygroup/dictionarygroup_test.go b/test/http-specs/type/dictionarygroup/dictionarygroup_test.go new file mode 100644 index 000000000000..250a25a457ae --- /dev/null +++ b/test/http-specs/type/dictionarygroup/dictionarygroup_test.go @@ -0,0 +1,282 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package dictionarygroup_test + +import ( + "context" + "dictionarygroup" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestBooleanValueClientGet(t *testing.T) { + client, err := dictionarygroup.NewDictionaryClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDictionaryBooleanValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, map[string]*bool{ + "k1": to.Ptr(true), + "k2": to.Ptr(false), + }, resp.Value) +} + +func TestBooleanValueClientPut(t *testing.T) { + client, err := dictionarygroup.NewDictionaryClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDictionaryBooleanValueClient().Put(context.Background(), map[string]*bool{ + "k1": to.Ptr(true), + "k2": to.Ptr(false), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestDatetimeValueClientGet(t *testing.T) { + client, err := dictionarygroup.NewDictionaryClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDictionaryDatetimeValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, map[string]*time.Time{ + "k1": to.Ptr(time.Date(2022, time.August, 26, 18, 38, 0, 0, time.UTC)), + }, resp.Value) +} + +func TestDatetimeValueClientPut(t *testing.T) { + client, err := dictionarygroup.NewDictionaryClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDictionaryDatetimeValueClient().Put(context.Background(), map[string]*time.Time{ + "k1": to.Ptr(time.Date(2022, time.August, 26, 18, 38, 0, 0, time.UTC)), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestDurationValueClientGet(t *testing.T) { + client, err := dictionarygroup.NewDictionaryClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDictionaryDurationValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, map[string]*string{ + "k1": to.Ptr("P123DT22H14M12.011S"), + }, resp.Value) +} + +func TestDurationValueClientPut(t *testing.T) { + client, err := dictionarygroup.NewDictionaryClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDictionaryDurationValueClient().Put(context.Background(), map[string]*string{ + "k1": to.Ptr("P123DT22H14M12.011S"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestFloat32ValueClientGet(t *testing.T) { + client, err := dictionarygroup.NewDictionaryClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDictionaryFloat32ValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, map[string]*float32{ + "k1": to.Ptr[float32](43.125), + }, resp.Value) +} + +func TestFloat32ValueClientPut(t *testing.T) { + client, err := dictionarygroup.NewDictionaryClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDictionaryFloat32ValueClient().Put(context.Background(), map[string]*float32{ + "k1": to.Ptr[float32](43.125), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestInt32ValueClientGet(t *testing.T) { + client, err := dictionarygroup.NewDictionaryClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDictionaryInt32ValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, map[string]*int32{ + "k1": to.Ptr[int32](1), + "k2": to.Ptr[int32](2), + }, resp.Value) +} + +func TestInt32ValueClientPut(t *testing.T) { + client, err := dictionarygroup.NewDictionaryClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDictionaryInt32ValueClient().Put(context.Background(), map[string]*int32{ + "k1": to.Ptr[int32](1), + "k2": to.Ptr[int32](2), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestInt64ValueClientGet(t *testing.T) { + client, err := dictionarygroup.NewDictionaryClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDictionaryInt64ValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, map[string]*int64{ + "k1": to.Ptr[int64](9007199254740991), + "k2": to.Ptr[int64](-9007199254740991), + }, resp.Value) +} + +func TestInt64ValueClientPut(t *testing.T) { + client, err := dictionarygroup.NewDictionaryClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDictionaryInt64ValueClient().Put(context.Background(), map[string]*int64{ + "k1": to.Ptr[int64](9007199254740991), + "k2": to.Ptr[int64](-9007199254740991), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestModelValueClientGet(t *testing.T) { + client, err := dictionarygroup.NewDictionaryClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDictionaryModelValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, map[string]*dictionarygroup.InnerModel{ + "k1": { + Property: to.Ptr("hello"), + }, + "k2": { + Property: to.Ptr("world"), + }, + }, resp.Value) +} + +func TestModelValueClientPut(t *testing.T) { + client, err := dictionarygroup.NewDictionaryClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDictionaryModelValueClient().Put(context.Background(), map[string]*dictionarygroup.InnerModel{ + "k1": { + Property: to.Ptr("hello"), + }, + "k2": { + Property: to.Ptr("world"), + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestNullableFloatValueClientGet(t *testing.T) { + client, err := dictionarygroup.NewDictionaryClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDictionaryNullableFloatValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, map[string]*float32{ + "k1": to.Ptr[float32](1.25), + "k2": to.Ptr[float32](0.5), + "k3": nil, + }, resp.Value) +} + +func TestNullableFloatValueClientPut(t *testing.T) { + client, err := dictionarygroup.NewDictionaryClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDictionaryNullableFloatValueClient().Put(context.Background(), map[string]*float32{ + "k1": to.Ptr[float32](1.25), + "k2": to.Ptr[float32](0.5), + "k3": nil, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestRecursiveModelValueClientGet(t *testing.T) { + client, err := dictionarygroup.NewDictionaryClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDictionaryRecursiveModelValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, map[string]*dictionarygroup.InnerModel{ + "k1": { + Property: to.Ptr("hello"), + Children: map[string]*dictionarygroup.InnerModel{}, + }, + "k2": { + Property: to.Ptr("world"), + Children: map[string]*dictionarygroup.InnerModel{ + "k2.1": { + Property: to.Ptr("inner world"), + }, + }, + }, + }, resp.Value) +} + +func TestRecursiveModelValueClientPut(t *testing.T) { + client, err := dictionarygroup.NewDictionaryClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDictionaryRecursiveModelValueClient().Put(context.Background(), map[string]*dictionarygroup.InnerModel{ + "k1": { + Property: to.Ptr("hello"), + Children: map[string]*dictionarygroup.InnerModel{}, + }, + "k2": { + Property: to.Ptr("world"), + Children: map[string]*dictionarygroup.InnerModel{ + "k2.1": { + Property: to.Ptr("inner world"), + }, + }, + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestStringValueClientGet(t *testing.T) { + client, err := dictionarygroup.NewDictionaryClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDictionaryStringValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, map[string]*string{ + "k1": to.Ptr("hello"), + "k2": to.Ptr(""), + }, resp.Value) +} + +func TestStringValueClientPut(t *testing.T) { + client, err := dictionarygroup.NewDictionaryClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDictionaryStringValueClient().Put(context.Background(), map[string]*string{ + "k1": to.Ptr("hello"), + "k2": to.Ptr(""), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestUnknownValueClientGet(t *testing.T) { + client, err := dictionarygroup.NewDictionaryClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDictionaryUnknownValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, map[string]any{ + "k1": float64(1), + "k2": "hello", + "k3": nil, + }, resp.Value) +} + +func TestUnknownValueClientPut(t *testing.T) { + client, err := dictionarygroup.NewDictionaryClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewDictionaryUnknownValueClient().Put(context.Background(), map[string]any{ + "k1": float64(1), + "k2": "hello", + "k3": nil, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/dictionarygroup/fake/zz_dictionary_server.go b/test/http-specs/type/dictionarygroup/fake/zz_dictionary_server.go new file mode 100644 index 000000000000..2eb753d65d45 --- /dev/null +++ b/test/http-specs/type/dictionarygroup/fake/zz_dictionary_server.go @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// DictionaryServer is a fake server for instances of the dictionarygroup.DictionaryClient type. +type DictionaryServer struct { + // DictionaryBooleanValueServer contains the fakes for client DictionaryBooleanValueClient + DictionaryBooleanValueServer DictionaryBooleanValueServer + + // DictionaryDatetimeValueServer contains the fakes for client DictionaryDatetimeValueClient + DictionaryDatetimeValueServer DictionaryDatetimeValueServer + + // DictionaryDurationValueServer contains the fakes for client DictionaryDurationValueClient + DictionaryDurationValueServer DictionaryDurationValueServer + + // DictionaryFloat32ValueServer contains the fakes for client DictionaryFloat32ValueClient + DictionaryFloat32ValueServer DictionaryFloat32ValueServer + + // DictionaryInt32ValueServer contains the fakes for client DictionaryInt32ValueClient + DictionaryInt32ValueServer DictionaryInt32ValueServer + + // DictionaryInt64ValueServer contains the fakes for client DictionaryInt64ValueClient + DictionaryInt64ValueServer DictionaryInt64ValueServer + + // DictionaryModelValueServer contains the fakes for client DictionaryModelValueClient + DictionaryModelValueServer DictionaryModelValueServer + + // DictionaryNullableFloatValueServer contains the fakes for client DictionaryNullableFloatValueClient + DictionaryNullableFloatValueServer DictionaryNullableFloatValueServer + + // DictionaryRecursiveModelValueServer contains the fakes for client DictionaryRecursiveModelValueClient + DictionaryRecursiveModelValueServer DictionaryRecursiveModelValueServer + + // DictionaryStringValueServer contains the fakes for client DictionaryStringValueClient + DictionaryStringValueServer DictionaryStringValueServer + + // DictionaryUnknownValueServer contains the fakes for client DictionaryUnknownValueClient + DictionaryUnknownValueServer DictionaryUnknownValueServer +} + +// NewDictionaryServerTransport creates a new instance of DictionaryServerTransport with the provided implementation. +// The returned DictionaryServerTransport instance is connected to an instance of dictionarygroup.DictionaryClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDictionaryServerTransport(srv *DictionaryServer) *DictionaryServerTransport { + return &DictionaryServerTransport{srv: srv} +} + +// DictionaryServerTransport connects instances of dictionarygroup.DictionaryClient to instances of DictionaryServer. +// Don't use this type directly, use NewDictionaryServerTransport instead. +type DictionaryServerTransport struct { + srv *DictionaryServer + trMu sync.Mutex + trDictionaryBooleanValueServer *DictionaryBooleanValueServerTransport + trDictionaryDatetimeValueServer *DictionaryDatetimeValueServerTransport + trDictionaryDurationValueServer *DictionaryDurationValueServerTransport + trDictionaryFloat32ValueServer *DictionaryFloat32ValueServerTransport + trDictionaryInt32ValueServer *DictionaryInt32ValueServerTransport + trDictionaryInt64ValueServer *DictionaryInt64ValueServerTransport + trDictionaryModelValueServer *DictionaryModelValueServerTransport + trDictionaryNullableFloatValueServer *DictionaryNullableFloatValueServerTransport + trDictionaryRecursiveModelValueServer *DictionaryRecursiveModelValueServerTransport + trDictionaryStringValueServer *DictionaryStringValueServerTransport + trDictionaryUnknownValueServer *DictionaryUnknownValueServerTransport +} + +// Do implements the policy.Transporter interface for DictionaryServerTransport. +func (d *DictionaryServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (d *DictionaryServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "DictionaryBooleanValueClient": + initServer(&d.trMu, &d.trDictionaryBooleanValueServer, func() *DictionaryBooleanValueServerTransport { + return NewDictionaryBooleanValueServerTransport(&d.srv.DictionaryBooleanValueServer) + }) + resp, err = d.trDictionaryBooleanValueServer.Do(req) + case "DictionaryDatetimeValueClient": + initServer(&d.trMu, &d.trDictionaryDatetimeValueServer, func() *DictionaryDatetimeValueServerTransport { + return NewDictionaryDatetimeValueServerTransport(&d.srv.DictionaryDatetimeValueServer) + }) + resp, err = d.trDictionaryDatetimeValueServer.Do(req) + case "DictionaryDurationValueClient": + initServer(&d.trMu, &d.trDictionaryDurationValueServer, func() *DictionaryDurationValueServerTransport { + return NewDictionaryDurationValueServerTransport(&d.srv.DictionaryDurationValueServer) + }) + resp, err = d.trDictionaryDurationValueServer.Do(req) + case "DictionaryFloat32ValueClient": + initServer(&d.trMu, &d.trDictionaryFloat32ValueServer, func() *DictionaryFloat32ValueServerTransport { + return NewDictionaryFloat32ValueServerTransport(&d.srv.DictionaryFloat32ValueServer) + }) + resp, err = d.trDictionaryFloat32ValueServer.Do(req) + case "DictionaryInt32ValueClient": + initServer(&d.trMu, &d.trDictionaryInt32ValueServer, func() *DictionaryInt32ValueServerTransport { + return NewDictionaryInt32ValueServerTransport(&d.srv.DictionaryInt32ValueServer) + }) + resp, err = d.trDictionaryInt32ValueServer.Do(req) + case "DictionaryInt64ValueClient": + initServer(&d.trMu, &d.trDictionaryInt64ValueServer, func() *DictionaryInt64ValueServerTransport { + return NewDictionaryInt64ValueServerTransport(&d.srv.DictionaryInt64ValueServer) + }) + resp, err = d.trDictionaryInt64ValueServer.Do(req) + case "DictionaryModelValueClient": + initServer(&d.trMu, &d.trDictionaryModelValueServer, func() *DictionaryModelValueServerTransport { + return NewDictionaryModelValueServerTransport(&d.srv.DictionaryModelValueServer) + }) + resp, err = d.trDictionaryModelValueServer.Do(req) + case "DictionaryNullableFloatValueClient": + initServer(&d.trMu, &d.trDictionaryNullableFloatValueServer, func() *DictionaryNullableFloatValueServerTransport { + return NewDictionaryNullableFloatValueServerTransport(&d.srv.DictionaryNullableFloatValueServer) + }) + resp, err = d.trDictionaryNullableFloatValueServer.Do(req) + case "DictionaryRecursiveModelValueClient": + initServer(&d.trMu, &d.trDictionaryRecursiveModelValueServer, func() *DictionaryRecursiveModelValueServerTransport { + return NewDictionaryRecursiveModelValueServerTransport(&d.srv.DictionaryRecursiveModelValueServer) + }) + resp, err = d.trDictionaryRecursiveModelValueServer.Do(req) + case "DictionaryStringValueClient": + initServer(&d.trMu, &d.trDictionaryStringValueServer, func() *DictionaryStringValueServerTransport { + return NewDictionaryStringValueServerTransport(&d.srv.DictionaryStringValueServer) + }) + resp, err = d.trDictionaryStringValueServer.Do(req) + case "DictionaryUnknownValueClient": + initServer(&d.trMu, &d.trDictionaryUnknownValueServer, func() *DictionaryUnknownValueServerTransport { + return NewDictionaryUnknownValueServerTransport(&d.srv.DictionaryUnknownValueServer) + }) + resp, err = d.trDictionaryUnknownValueServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to DictionaryServerTransport +var dictionaryServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/dictionarygroup/fake/zz_dictionarybooleanvalue_server.go b/test/http-specs/type/dictionarygroup/fake/zz_dictionarybooleanvalue_server.go new file mode 100644 index 000000000000..d0865dfc59ad --- /dev/null +++ b/test/http-specs/type/dictionarygroup/fake/zz_dictionarybooleanvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "dictionarygroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// DictionaryBooleanValueServer is a fake server for instances of the dictionarygroup.DictionaryBooleanValueClient type. +type DictionaryBooleanValueServer struct { + // Get is the fake for method DictionaryBooleanValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *dictionarygroup.DictionaryBooleanValueClientGetOptions) (resp azfake.Responder[dictionarygroup.DictionaryBooleanValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method DictionaryBooleanValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body map[string]*bool, options *dictionarygroup.DictionaryBooleanValueClientPutOptions) (resp azfake.Responder[dictionarygroup.DictionaryBooleanValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewDictionaryBooleanValueServerTransport creates a new instance of DictionaryBooleanValueServerTransport with the provided implementation. +// The returned DictionaryBooleanValueServerTransport instance is connected to an instance of dictionarygroup.DictionaryBooleanValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDictionaryBooleanValueServerTransport(srv *DictionaryBooleanValueServer) *DictionaryBooleanValueServerTransport { + return &DictionaryBooleanValueServerTransport{srv: srv} +} + +// DictionaryBooleanValueServerTransport connects instances of dictionarygroup.DictionaryBooleanValueClient to instances of DictionaryBooleanValueServer. +// Don't use this type directly, use NewDictionaryBooleanValueServerTransport instead. +type DictionaryBooleanValueServerTransport struct { + srv *DictionaryBooleanValueServer +} + +// Do implements the policy.Transporter interface for DictionaryBooleanValueServerTransport. +func (d *DictionaryBooleanValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DictionaryBooleanValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if dictionaryBooleanValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = dictionaryBooleanValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DictionaryBooleanValueClient.Get": + res.resp, res.err = d.dispatchGet(req) + case "DictionaryBooleanValueClient.Put": + res.resp, res.err = d.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DictionaryBooleanValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := d.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Value, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DictionaryBooleanValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if d.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[map[string]*bool](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DictionaryBooleanValueServerTransport +var dictionaryBooleanValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/dictionarygroup/fake/zz_dictionarydatetimevalue_server.go b/test/http-specs/type/dictionarygroup/fake/zz_dictionarydatetimevalue_server.go new file mode 100644 index 000000000000..6198c6d1da5d --- /dev/null +++ b/test/http-specs/type/dictionarygroup/fake/zz_dictionarydatetimevalue_server.go @@ -0,0 +1,131 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "dictionarygroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "time" +) + +// DictionaryDatetimeValueServer is a fake server for instances of the dictionarygroup.DictionaryDatetimeValueClient type. +type DictionaryDatetimeValueServer struct { + // Get is the fake for method DictionaryDatetimeValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *dictionarygroup.DictionaryDatetimeValueClientGetOptions) (resp azfake.Responder[dictionarygroup.DictionaryDatetimeValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method DictionaryDatetimeValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body map[string]*time.Time, options *dictionarygroup.DictionaryDatetimeValueClientPutOptions) (resp azfake.Responder[dictionarygroup.DictionaryDatetimeValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewDictionaryDatetimeValueServerTransport creates a new instance of DictionaryDatetimeValueServerTransport with the provided implementation. +// The returned DictionaryDatetimeValueServerTransport instance is connected to an instance of dictionarygroup.DictionaryDatetimeValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDictionaryDatetimeValueServerTransport(srv *DictionaryDatetimeValueServer) *DictionaryDatetimeValueServerTransport { + return &DictionaryDatetimeValueServerTransport{srv: srv} +} + +// DictionaryDatetimeValueServerTransport connects instances of dictionarygroup.DictionaryDatetimeValueClient to instances of DictionaryDatetimeValueServer. +// Don't use this type directly, use NewDictionaryDatetimeValueServerTransport instead. +type DictionaryDatetimeValueServerTransport struct { + srv *DictionaryDatetimeValueServer +} + +// Do implements the policy.Transporter interface for DictionaryDatetimeValueServerTransport. +func (d *DictionaryDatetimeValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DictionaryDatetimeValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if dictionaryDatetimeValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = dictionaryDatetimeValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DictionaryDatetimeValueClient.Get": + res.resp, res.err = d.dispatchGet(req) + case "DictionaryDatetimeValueClient.Put": + res.resp, res.err = d.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DictionaryDatetimeValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := d.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Value, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DictionaryDatetimeValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if d.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[map[string]*time.Time](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DictionaryDatetimeValueServerTransport +var dictionaryDatetimeValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/dictionarygroup/fake/zz_dictionarydurationvalue_server.go b/test/http-specs/type/dictionarygroup/fake/zz_dictionarydurationvalue_server.go new file mode 100644 index 000000000000..31de7d81692b --- /dev/null +++ b/test/http-specs/type/dictionarygroup/fake/zz_dictionarydurationvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "dictionarygroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// DictionaryDurationValueServer is a fake server for instances of the dictionarygroup.DictionaryDurationValueClient type. +type DictionaryDurationValueServer struct { + // Get is the fake for method DictionaryDurationValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *dictionarygroup.DictionaryDurationValueClientGetOptions) (resp azfake.Responder[dictionarygroup.DictionaryDurationValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method DictionaryDurationValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body map[string]*string, options *dictionarygroup.DictionaryDurationValueClientPutOptions) (resp azfake.Responder[dictionarygroup.DictionaryDurationValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewDictionaryDurationValueServerTransport creates a new instance of DictionaryDurationValueServerTransport with the provided implementation. +// The returned DictionaryDurationValueServerTransport instance is connected to an instance of dictionarygroup.DictionaryDurationValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDictionaryDurationValueServerTransport(srv *DictionaryDurationValueServer) *DictionaryDurationValueServerTransport { + return &DictionaryDurationValueServerTransport{srv: srv} +} + +// DictionaryDurationValueServerTransport connects instances of dictionarygroup.DictionaryDurationValueClient to instances of DictionaryDurationValueServer. +// Don't use this type directly, use NewDictionaryDurationValueServerTransport instead. +type DictionaryDurationValueServerTransport struct { + srv *DictionaryDurationValueServer +} + +// Do implements the policy.Transporter interface for DictionaryDurationValueServerTransport. +func (d *DictionaryDurationValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DictionaryDurationValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if dictionaryDurationValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = dictionaryDurationValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DictionaryDurationValueClient.Get": + res.resp, res.err = d.dispatchGet(req) + case "DictionaryDurationValueClient.Put": + res.resp, res.err = d.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DictionaryDurationValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := d.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Value, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DictionaryDurationValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if d.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[map[string]*string](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DictionaryDurationValueServerTransport +var dictionaryDurationValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/dictionarygroup/fake/zz_dictionaryfloat32value_server.go b/test/http-specs/type/dictionarygroup/fake/zz_dictionaryfloat32value_server.go new file mode 100644 index 000000000000..913142be8e41 --- /dev/null +++ b/test/http-specs/type/dictionarygroup/fake/zz_dictionaryfloat32value_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "dictionarygroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// DictionaryFloat32ValueServer is a fake server for instances of the dictionarygroup.DictionaryFloat32ValueClient type. +type DictionaryFloat32ValueServer struct { + // Get is the fake for method DictionaryFloat32ValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *dictionarygroup.DictionaryFloat32ValueClientGetOptions) (resp azfake.Responder[dictionarygroup.DictionaryFloat32ValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method DictionaryFloat32ValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body map[string]*float32, options *dictionarygroup.DictionaryFloat32ValueClientPutOptions) (resp azfake.Responder[dictionarygroup.DictionaryFloat32ValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewDictionaryFloat32ValueServerTransport creates a new instance of DictionaryFloat32ValueServerTransport with the provided implementation. +// The returned DictionaryFloat32ValueServerTransport instance is connected to an instance of dictionarygroup.DictionaryFloat32ValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDictionaryFloat32ValueServerTransport(srv *DictionaryFloat32ValueServer) *DictionaryFloat32ValueServerTransport { + return &DictionaryFloat32ValueServerTransport{srv: srv} +} + +// DictionaryFloat32ValueServerTransport connects instances of dictionarygroup.DictionaryFloat32ValueClient to instances of DictionaryFloat32ValueServer. +// Don't use this type directly, use NewDictionaryFloat32ValueServerTransport instead. +type DictionaryFloat32ValueServerTransport struct { + srv *DictionaryFloat32ValueServer +} + +// Do implements the policy.Transporter interface for DictionaryFloat32ValueServerTransport. +func (d *DictionaryFloat32ValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DictionaryFloat32ValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if dictionaryFloat32ValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = dictionaryFloat32ValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DictionaryFloat32ValueClient.Get": + res.resp, res.err = d.dispatchGet(req) + case "DictionaryFloat32ValueClient.Put": + res.resp, res.err = d.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DictionaryFloat32ValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := d.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Value, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DictionaryFloat32ValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if d.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[map[string]*float32](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DictionaryFloat32ValueServerTransport +var dictionaryFloat32ValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/dictionarygroup/fake/zz_dictionaryint32value_server.go b/test/http-specs/type/dictionarygroup/fake/zz_dictionaryint32value_server.go new file mode 100644 index 000000000000..caf9ce2ea1d4 --- /dev/null +++ b/test/http-specs/type/dictionarygroup/fake/zz_dictionaryint32value_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "dictionarygroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// DictionaryInt32ValueServer is a fake server for instances of the dictionarygroup.DictionaryInt32ValueClient type. +type DictionaryInt32ValueServer struct { + // Get is the fake for method DictionaryInt32ValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *dictionarygroup.DictionaryInt32ValueClientGetOptions) (resp azfake.Responder[dictionarygroup.DictionaryInt32ValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method DictionaryInt32ValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body map[string]*int32, options *dictionarygroup.DictionaryInt32ValueClientPutOptions) (resp azfake.Responder[dictionarygroup.DictionaryInt32ValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewDictionaryInt32ValueServerTransport creates a new instance of DictionaryInt32ValueServerTransport with the provided implementation. +// The returned DictionaryInt32ValueServerTransport instance is connected to an instance of dictionarygroup.DictionaryInt32ValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDictionaryInt32ValueServerTransport(srv *DictionaryInt32ValueServer) *DictionaryInt32ValueServerTransport { + return &DictionaryInt32ValueServerTransport{srv: srv} +} + +// DictionaryInt32ValueServerTransport connects instances of dictionarygroup.DictionaryInt32ValueClient to instances of DictionaryInt32ValueServer. +// Don't use this type directly, use NewDictionaryInt32ValueServerTransport instead. +type DictionaryInt32ValueServerTransport struct { + srv *DictionaryInt32ValueServer +} + +// Do implements the policy.Transporter interface for DictionaryInt32ValueServerTransport. +func (d *DictionaryInt32ValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DictionaryInt32ValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if dictionaryInt32ValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = dictionaryInt32ValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DictionaryInt32ValueClient.Get": + res.resp, res.err = d.dispatchGet(req) + case "DictionaryInt32ValueClient.Put": + res.resp, res.err = d.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DictionaryInt32ValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := d.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Value, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DictionaryInt32ValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if d.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[map[string]*int32](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DictionaryInt32ValueServerTransport +var dictionaryInt32ValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/dictionarygroup/fake/zz_dictionaryint64value_server.go b/test/http-specs/type/dictionarygroup/fake/zz_dictionaryint64value_server.go new file mode 100644 index 000000000000..484daa2c1e3e --- /dev/null +++ b/test/http-specs/type/dictionarygroup/fake/zz_dictionaryint64value_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "dictionarygroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// DictionaryInt64ValueServer is a fake server for instances of the dictionarygroup.DictionaryInt64ValueClient type. +type DictionaryInt64ValueServer struct { + // Get is the fake for method DictionaryInt64ValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *dictionarygroup.DictionaryInt64ValueClientGetOptions) (resp azfake.Responder[dictionarygroup.DictionaryInt64ValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method DictionaryInt64ValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body map[string]*int64, options *dictionarygroup.DictionaryInt64ValueClientPutOptions) (resp azfake.Responder[dictionarygroup.DictionaryInt64ValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewDictionaryInt64ValueServerTransport creates a new instance of DictionaryInt64ValueServerTransport with the provided implementation. +// The returned DictionaryInt64ValueServerTransport instance is connected to an instance of dictionarygroup.DictionaryInt64ValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDictionaryInt64ValueServerTransport(srv *DictionaryInt64ValueServer) *DictionaryInt64ValueServerTransport { + return &DictionaryInt64ValueServerTransport{srv: srv} +} + +// DictionaryInt64ValueServerTransport connects instances of dictionarygroup.DictionaryInt64ValueClient to instances of DictionaryInt64ValueServer. +// Don't use this type directly, use NewDictionaryInt64ValueServerTransport instead. +type DictionaryInt64ValueServerTransport struct { + srv *DictionaryInt64ValueServer +} + +// Do implements the policy.Transporter interface for DictionaryInt64ValueServerTransport. +func (d *DictionaryInt64ValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DictionaryInt64ValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if dictionaryInt64ValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = dictionaryInt64ValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DictionaryInt64ValueClient.Get": + res.resp, res.err = d.dispatchGet(req) + case "DictionaryInt64ValueClient.Put": + res.resp, res.err = d.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DictionaryInt64ValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := d.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Value, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DictionaryInt64ValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if d.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[map[string]*int64](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DictionaryInt64ValueServerTransport +var dictionaryInt64ValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/dictionarygroup/fake/zz_dictionarymodelvalue_server.go b/test/http-specs/type/dictionarygroup/fake/zz_dictionarymodelvalue_server.go new file mode 100644 index 000000000000..5fa628059d23 --- /dev/null +++ b/test/http-specs/type/dictionarygroup/fake/zz_dictionarymodelvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "dictionarygroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// DictionaryModelValueServer is a fake server for instances of the dictionarygroup.DictionaryModelValueClient type. +type DictionaryModelValueServer struct { + // Get is the fake for method DictionaryModelValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *dictionarygroup.DictionaryModelValueClientGetOptions) (resp azfake.Responder[dictionarygroup.DictionaryModelValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method DictionaryModelValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body map[string]*dictionarygroup.InnerModel, options *dictionarygroup.DictionaryModelValueClientPutOptions) (resp azfake.Responder[dictionarygroup.DictionaryModelValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewDictionaryModelValueServerTransport creates a new instance of DictionaryModelValueServerTransport with the provided implementation. +// The returned DictionaryModelValueServerTransport instance is connected to an instance of dictionarygroup.DictionaryModelValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDictionaryModelValueServerTransport(srv *DictionaryModelValueServer) *DictionaryModelValueServerTransport { + return &DictionaryModelValueServerTransport{srv: srv} +} + +// DictionaryModelValueServerTransport connects instances of dictionarygroup.DictionaryModelValueClient to instances of DictionaryModelValueServer. +// Don't use this type directly, use NewDictionaryModelValueServerTransport instead. +type DictionaryModelValueServerTransport struct { + srv *DictionaryModelValueServer +} + +// Do implements the policy.Transporter interface for DictionaryModelValueServerTransport. +func (d *DictionaryModelValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DictionaryModelValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if dictionaryModelValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = dictionaryModelValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DictionaryModelValueClient.Get": + res.resp, res.err = d.dispatchGet(req) + case "DictionaryModelValueClient.Put": + res.resp, res.err = d.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DictionaryModelValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := d.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Value, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DictionaryModelValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if d.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[map[string]*dictionarygroup.InnerModel](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DictionaryModelValueServerTransport +var dictionaryModelValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/dictionarygroup/fake/zz_dictionarynullablefloatvalue_server.go b/test/http-specs/type/dictionarygroup/fake/zz_dictionarynullablefloatvalue_server.go new file mode 100644 index 000000000000..86c0eda64c37 --- /dev/null +++ b/test/http-specs/type/dictionarygroup/fake/zz_dictionarynullablefloatvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "dictionarygroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// DictionaryNullableFloatValueServer is a fake server for instances of the dictionarygroup.DictionaryNullableFloatValueClient type. +type DictionaryNullableFloatValueServer struct { + // Get is the fake for method DictionaryNullableFloatValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *dictionarygroup.DictionaryNullableFloatValueClientGetOptions) (resp azfake.Responder[dictionarygroup.DictionaryNullableFloatValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method DictionaryNullableFloatValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body map[string]*float32, options *dictionarygroup.DictionaryNullableFloatValueClientPutOptions) (resp azfake.Responder[dictionarygroup.DictionaryNullableFloatValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewDictionaryNullableFloatValueServerTransport creates a new instance of DictionaryNullableFloatValueServerTransport with the provided implementation. +// The returned DictionaryNullableFloatValueServerTransport instance is connected to an instance of dictionarygroup.DictionaryNullableFloatValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDictionaryNullableFloatValueServerTransport(srv *DictionaryNullableFloatValueServer) *DictionaryNullableFloatValueServerTransport { + return &DictionaryNullableFloatValueServerTransport{srv: srv} +} + +// DictionaryNullableFloatValueServerTransport connects instances of dictionarygroup.DictionaryNullableFloatValueClient to instances of DictionaryNullableFloatValueServer. +// Don't use this type directly, use NewDictionaryNullableFloatValueServerTransport instead. +type DictionaryNullableFloatValueServerTransport struct { + srv *DictionaryNullableFloatValueServer +} + +// Do implements the policy.Transporter interface for DictionaryNullableFloatValueServerTransport. +func (d *DictionaryNullableFloatValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DictionaryNullableFloatValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if dictionaryNullableFloatValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = dictionaryNullableFloatValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DictionaryNullableFloatValueClient.Get": + res.resp, res.err = d.dispatchGet(req) + case "DictionaryNullableFloatValueClient.Put": + res.resp, res.err = d.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DictionaryNullableFloatValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := d.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Value, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DictionaryNullableFloatValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if d.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[map[string]*float32](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DictionaryNullableFloatValueServerTransport +var dictionaryNullableFloatValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/dictionarygroup/fake/zz_dictionaryrecursivemodelvalue_server.go b/test/http-specs/type/dictionarygroup/fake/zz_dictionaryrecursivemodelvalue_server.go new file mode 100644 index 000000000000..920598e90536 --- /dev/null +++ b/test/http-specs/type/dictionarygroup/fake/zz_dictionaryrecursivemodelvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "dictionarygroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// DictionaryRecursiveModelValueServer is a fake server for instances of the dictionarygroup.DictionaryRecursiveModelValueClient type. +type DictionaryRecursiveModelValueServer struct { + // Get is the fake for method DictionaryRecursiveModelValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *dictionarygroup.DictionaryRecursiveModelValueClientGetOptions) (resp azfake.Responder[dictionarygroup.DictionaryRecursiveModelValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method DictionaryRecursiveModelValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body map[string]*dictionarygroup.InnerModel, options *dictionarygroup.DictionaryRecursiveModelValueClientPutOptions) (resp azfake.Responder[dictionarygroup.DictionaryRecursiveModelValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewDictionaryRecursiveModelValueServerTransport creates a new instance of DictionaryRecursiveModelValueServerTransport with the provided implementation. +// The returned DictionaryRecursiveModelValueServerTransport instance is connected to an instance of dictionarygroup.DictionaryRecursiveModelValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDictionaryRecursiveModelValueServerTransport(srv *DictionaryRecursiveModelValueServer) *DictionaryRecursiveModelValueServerTransport { + return &DictionaryRecursiveModelValueServerTransport{srv: srv} +} + +// DictionaryRecursiveModelValueServerTransport connects instances of dictionarygroup.DictionaryRecursiveModelValueClient to instances of DictionaryRecursiveModelValueServer. +// Don't use this type directly, use NewDictionaryRecursiveModelValueServerTransport instead. +type DictionaryRecursiveModelValueServerTransport struct { + srv *DictionaryRecursiveModelValueServer +} + +// Do implements the policy.Transporter interface for DictionaryRecursiveModelValueServerTransport. +func (d *DictionaryRecursiveModelValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DictionaryRecursiveModelValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if dictionaryRecursiveModelValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = dictionaryRecursiveModelValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DictionaryRecursiveModelValueClient.Get": + res.resp, res.err = d.dispatchGet(req) + case "DictionaryRecursiveModelValueClient.Put": + res.resp, res.err = d.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DictionaryRecursiveModelValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := d.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Value, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DictionaryRecursiveModelValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if d.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[map[string]*dictionarygroup.InnerModel](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DictionaryRecursiveModelValueServerTransport +var dictionaryRecursiveModelValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/dictionarygroup/fake/zz_dictionarystringvalue_server.go b/test/http-specs/type/dictionarygroup/fake/zz_dictionarystringvalue_server.go new file mode 100644 index 000000000000..09905c6c7bfb --- /dev/null +++ b/test/http-specs/type/dictionarygroup/fake/zz_dictionarystringvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "dictionarygroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// DictionaryStringValueServer is a fake server for instances of the dictionarygroup.DictionaryStringValueClient type. +type DictionaryStringValueServer struct { + // Get is the fake for method DictionaryStringValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *dictionarygroup.DictionaryStringValueClientGetOptions) (resp azfake.Responder[dictionarygroup.DictionaryStringValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method DictionaryStringValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body map[string]*string, options *dictionarygroup.DictionaryStringValueClientPutOptions) (resp azfake.Responder[dictionarygroup.DictionaryStringValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewDictionaryStringValueServerTransport creates a new instance of DictionaryStringValueServerTransport with the provided implementation. +// The returned DictionaryStringValueServerTransport instance is connected to an instance of dictionarygroup.DictionaryStringValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDictionaryStringValueServerTransport(srv *DictionaryStringValueServer) *DictionaryStringValueServerTransport { + return &DictionaryStringValueServerTransport{srv: srv} +} + +// DictionaryStringValueServerTransport connects instances of dictionarygroup.DictionaryStringValueClient to instances of DictionaryStringValueServer. +// Don't use this type directly, use NewDictionaryStringValueServerTransport instead. +type DictionaryStringValueServerTransport struct { + srv *DictionaryStringValueServer +} + +// Do implements the policy.Transporter interface for DictionaryStringValueServerTransport. +func (d *DictionaryStringValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DictionaryStringValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if dictionaryStringValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = dictionaryStringValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DictionaryStringValueClient.Get": + res.resp, res.err = d.dispatchGet(req) + case "DictionaryStringValueClient.Put": + res.resp, res.err = d.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DictionaryStringValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := d.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Value, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DictionaryStringValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if d.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[map[string]*string](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DictionaryStringValueServerTransport +var dictionaryStringValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/dictionarygroup/fake/zz_dictionaryunknownvalue_server.go b/test/http-specs/type/dictionarygroup/fake/zz_dictionaryunknownvalue_server.go new file mode 100644 index 000000000000..4229bf8ef379 --- /dev/null +++ b/test/http-specs/type/dictionarygroup/fake/zz_dictionaryunknownvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "dictionarygroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// DictionaryUnknownValueServer is a fake server for instances of the dictionarygroup.DictionaryUnknownValueClient type. +type DictionaryUnknownValueServer struct { + // Get is the fake for method DictionaryUnknownValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *dictionarygroup.DictionaryUnknownValueClientGetOptions) (resp azfake.Responder[dictionarygroup.DictionaryUnknownValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method DictionaryUnknownValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body map[string]any, options *dictionarygroup.DictionaryUnknownValueClientPutOptions) (resp azfake.Responder[dictionarygroup.DictionaryUnknownValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewDictionaryUnknownValueServerTransport creates a new instance of DictionaryUnknownValueServerTransport with the provided implementation. +// The returned DictionaryUnknownValueServerTransport instance is connected to an instance of dictionarygroup.DictionaryUnknownValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDictionaryUnknownValueServerTransport(srv *DictionaryUnknownValueServer) *DictionaryUnknownValueServerTransport { + return &DictionaryUnknownValueServerTransport{srv: srv} +} + +// DictionaryUnknownValueServerTransport connects instances of dictionarygroup.DictionaryUnknownValueClient to instances of DictionaryUnknownValueServer. +// Don't use this type directly, use NewDictionaryUnknownValueServerTransport instead. +type DictionaryUnknownValueServerTransport struct { + srv *DictionaryUnknownValueServer +} + +// Do implements the policy.Transporter interface for DictionaryUnknownValueServerTransport. +func (d *DictionaryUnknownValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DictionaryUnknownValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if dictionaryUnknownValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = dictionaryUnknownValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DictionaryUnknownValueClient.Get": + res.resp, res.err = d.dispatchGet(req) + case "DictionaryUnknownValueClient.Put": + res.resp, res.err = d.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DictionaryUnknownValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := d.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Value, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DictionaryUnknownValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if d.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[map[string]any](req) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DictionaryUnknownValueServerTransport +var dictionaryUnknownValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/dictionarygroup/fake/zz_internal.go b/test/http-specs/type/dictionarygroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/http-specs/type/dictionarygroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/http-specs/type/dictionarygroup/go.mod b/test/http-specs/type/dictionarygroup/go.mod new file mode 100644 index 000000000000..e92939af3fd3 --- /dev/null +++ b/test/http-specs/type/dictionarygroup/go.mod @@ -0,0 +1,17 @@ +module dictionarygroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/type/dictionarygroup/go.sum b/test/http-specs/type/dictionarygroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/type/dictionarygroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/type/dictionarygroup/testdata/_metadata.json b/test/http-specs/type/dictionarygroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/type/dictionarygroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/type/dictionarygroup/zz_dictionary_client.go b/test/http-specs/type/dictionarygroup/zz_dictionary_client.go new file mode 100644 index 000000000000..3e681a0c65ca --- /dev/null +++ b/test/http-specs/type/dictionarygroup/zz_dictionary_client.go @@ -0,0 +1,128 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package dictionarygroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// DictionaryClient - Illustrates various of dictionaries. +// Don't use this type directly, use NewDictionaryClientWithNoCredential() instead. +type DictionaryClient struct { + internal *azcore.Client + endpoint string +} + +// DictionaryClientOptions contains the optional values for creating a [DictionaryClient]. +type DictionaryClientOptions struct { + azcore.ClientOptions +} + +// NewDictionaryClientWithNoCredential creates a new instance of DictionaryClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewDictionaryClientWithNoCredential(endpoint string, options *DictionaryClientOptions) (*DictionaryClient, error) { + if options == nil { + options = &DictionaryClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &DictionaryClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewDictionaryBooleanValueClient creates a new instance of [DictionaryBooleanValueClient]. +func (client *DictionaryClient) NewDictionaryBooleanValueClient() *DictionaryBooleanValueClient { + return &DictionaryBooleanValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewDictionaryDatetimeValueClient creates a new instance of [DictionaryDatetimeValueClient]. +func (client *DictionaryClient) NewDictionaryDatetimeValueClient() *DictionaryDatetimeValueClient { + return &DictionaryDatetimeValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewDictionaryDurationValueClient creates a new instance of [DictionaryDurationValueClient]. +func (client *DictionaryClient) NewDictionaryDurationValueClient() *DictionaryDurationValueClient { + return &DictionaryDurationValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewDictionaryFloat32ValueClient creates a new instance of [DictionaryFloat32ValueClient]. +func (client *DictionaryClient) NewDictionaryFloat32ValueClient() *DictionaryFloat32ValueClient { + return &DictionaryFloat32ValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewDictionaryInt32ValueClient creates a new instance of [DictionaryInt32ValueClient]. +func (client *DictionaryClient) NewDictionaryInt32ValueClient() *DictionaryInt32ValueClient { + return &DictionaryInt32ValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewDictionaryInt64ValueClient creates a new instance of [DictionaryInt64ValueClient]. +func (client *DictionaryClient) NewDictionaryInt64ValueClient() *DictionaryInt64ValueClient { + return &DictionaryInt64ValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewDictionaryModelValueClient creates a new instance of [DictionaryModelValueClient]. +func (client *DictionaryClient) NewDictionaryModelValueClient() *DictionaryModelValueClient { + return &DictionaryModelValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewDictionaryNullableFloatValueClient creates a new instance of [DictionaryNullableFloatValueClient]. +func (client *DictionaryClient) NewDictionaryNullableFloatValueClient() *DictionaryNullableFloatValueClient { + return &DictionaryNullableFloatValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewDictionaryRecursiveModelValueClient creates a new instance of [DictionaryRecursiveModelValueClient]. +func (client *DictionaryClient) NewDictionaryRecursiveModelValueClient() *DictionaryRecursiveModelValueClient { + return &DictionaryRecursiveModelValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewDictionaryStringValueClient creates a new instance of [DictionaryStringValueClient]. +func (client *DictionaryClient) NewDictionaryStringValueClient() *DictionaryStringValueClient { + return &DictionaryStringValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewDictionaryUnknownValueClient creates a new instance of [DictionaryUnknownValueClient]. +func (client *DictionaryClient) NewDictionaryUnknownValueClient() *DictionaryUnknownValueClient { + return &DictionaryUnknownValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/http-specs/type/dictionarygroup/zz_dictionarybooleanvalue_client.go b/test/http-specs/type/dictionarygroup/zz_dictionarybooleanvalue_client.go new file mode 100644 index 000000000000..4785e938c3ae --- /dev/null +++ b/test/http-specs/type/dictionarygroup/zz_dictionarybooleanvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package dictionarygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// DictionaryBooleanValueClient - Dictionary of boolean values +// Don't use this type directly, use [DictionaryClient.NewDictionaryBooleanValueClient] instead. +type DictionaryBooleanValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DictionaryBooleanValueClientGetOptions contains the optional parameters for the DictionaryBooleanValueClient.Get +// method. +func (client *DictionaryBooleanValueClient) Get(ctx context.Context, options *DictionaryBooleanValueClientGetOptions) (DictionaryBooleanValueClientGetResponse, error) { + var err error + const operationName = "DictionaryBooleanValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return DictionaryBooleanValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DictionaryBooleanValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DictionaryBooleanValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DictionaryBooleanValueClient) getCreateRequest(ctx context.Context, _ *DictionaryBooleanValueClientGetOptions) (*policy.Request, error) { + urlPath := "/type/dictionary/boolean" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DictionaryBooleanValueClient) getHandleResponse(resp *http.Response) (DictionaryBooleanValueClientGetResponse, error) { + result := DictionaryBooleanValueClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Value); err != nil { + return DictionaryBooleanValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DictionaryBooleanValueClientPutOptions contains the optional parameters for the DictionaryBooleanValueClient.Put +// method. +func (client *DictionaryBooleanValueClient) Put(ctx context.Context, body map[string]*bool, options *DictionaryBooleanValueClientPutOptions) (DictionaryBooleanValueClientPutResponse, error) { + var err error + const operationName = "DictionaryBooleanValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return DictionaryBooleanValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DictionaryBooleanValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DictionaryBooleanValueClientPutResponse{}, err + } + return DictionaryBooleanValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *DictionaryBooleanValueClient) putCreateRequest(ctx context.Context, body map[string]*bool, _ *DictionaryBooleanValueClientPutOptions) (*policy.Request, error) { + urlPath := "/type/dictionary/boolean" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/dictionarygroup/zz_dictionarydatetimevalue_client.go b/test/http-specs/type/dictionarygroup/zz_dictionarydatetimevalue_client.go new file mode 100644 index 000000000000..b1402ffa11fe --- /dev/null +++ b/test/http-specs/type/dictionarygroup/zz_dictionarydatetimevalue_client.go @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package dictionarygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "net/http" + "time" +) + +// DictionaryDatetimeValueClient - Dictionary of datetime values +// Don't use this type directly, use [DictionaryClient.NewDictionaryDatetimeValueClient] instead. +type DictionaryDatetimeValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DictionaryDatetimeValueClientGetOptions contains the optional parameters for the DictionaryDatetimeValueClient.Get +// method. +func (client *DictionaryDatetimeValueClient) Get(ctx context.Context, options *DictionaryDatetimeValueClientGetOptions) (DictionaryDatetimeValueClientGetResponse, error) { + var err error + const operationName = "DictionaryDatetimeValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return DictionaryDatetimeValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DictionaryDatetimeValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DictionaryDatetimeValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DictionaryDatetimeValueClient) getCreateRequest(ctx context.Context, _ *DictionaryDatetimeValueClientGetOptions) (*policy.Request, error) { + urlPath := "/type/dictionary/datetime" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DictionaryDatetimeValueClient) getHandleResponse(resp *http.Response) (DictionaryDatetimeValueClientGetResponse, error) { + result := DictionaryDatetimeValueClientGetResponse{} + aux := map[string]*datetime.RFC3339{} + if err := runtime.UnmarshalAsJSON(resp, &aux); err != nil { + return DictionaryDatetimeValueClientGetResponse{}, err + } + cp := map[string]*time.Time{} + for k, v := range aux { + cp[k] = (*time.Time)(v) + } + result.Value = cp + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DictionaryDatetimeValueClientPutOptions contains the optional parameters for the DictionaryDatetimeValueClient.Put +// method. +func (client *DictionaryDatetimeValueClient) Put(ctx context.Context, body map[string]*time.Time, options *DictionaryDatetimeValueClientPutOptions) (DictionaryDatetimeValueClientPutResponse, error) { + var err error + const operationName = "DictionaryDatetimeValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return DictionaryDatetimeValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DictionaryDatetimeValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DictionaryDatetimeValueClientPutResponse{}, err + } + return DictionaryDatetimeValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *DictionaryDatetimeValueClient) putCreateRequest(ctx context.Context, body map[string]*time.Time, _ *DictionaryDatetimeValueClientPutOptions) (*policy.Request, error) { + urlPath := "/type/dictionary/datetime" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + aux := map[string]*datetime.RFC3339{} + for k, v := range body { + aux[k] = (*datetime.RFC3339)(v) + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, aux); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/dictionarygroup/zz_dictionarydurationvalue_client.go b/test/http-specs/type/dictionarygroup/zz_dictionarydurationvalue_client.go new file mode 100644 index 000000000000..e2e91d1aa476 --- /dev/null +++ b/test/http-specs/type/dictionarygroup/zz_dictionarydurationvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package dictionarygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// DictionaryDurationValueClient - Dictionary of duration values +// Don't use this type directly, use [DictionaryClient.NewDictionaryDurationValueClient] instead. +type DictionaryDurationValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DictionaryDurationValueClientGetOptions contains the optional parameters for the DictionaryDurationValueClient.Get +// method. +func (client *DictionaryDurationValueClient) Get(ctx context.Context, options *DictionaryDurationValueClientGetOptions) (DictionaryDurationValueClientGetResponse, error) { + var err error + const operationName = "DictionaryDurationValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return DictionaryDurationValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DictionaryDurationValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DictionaryDurationValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DictionaryDurationValueClient) getCreateRequest(ctx context.Context, _ *DictionaryDurationValueClientGetOptions) (*policy.Request, error) { + urlPath := "/type/dictionary/duration" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DictionaryDurationValueClient) getHandleResponse(resp *http.Response) (DictionaryDurationValueClientGetResponse, error) { + result := DictionaryDurationValueClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Value); err != nil { + return DictionaryDurationValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DictionaryDurationValueClientPutOptions contains the optional parameters for the DictionaryDurationValueClient.Put +// method. +func (client *DictionaryDurationValueClient) Put(ctx context.Context, body map[string]*string, options *DictionaryDurationValueClientPutOptions) (DictionaryDurationValueClientPutResponse, error) { + var err error + const operationName = "DictionaryDurationValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return DictionaryDurationValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DictionaryDurationValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DictionaryDurationValueClientPutResponse{}, err + } + return DictionaryDurationValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *DictionaryDurationValueClient) putCreateRequest(ctx context.Context, body map[string]*string, _ *DictionaryDurationValueClientPutOptions) (*policy.Request, error) { + urlPath := "/type/dictionary/duration" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/dictionarygroup/zz_dictionaryfloat32value_client.go b/test/http-specs/type/dictionarygroup/zz_dictionaryfloat32value_client.go new file mode 100644 index 000000000000..19bc3470b3e1 --- /dev/null +++ b/test/http-specs/type/dictionarygroup/zz_dictionaryfloat32value_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package dictionarygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// DictionaryFloat32ValueClient - Dictionary of float values +// Don't use this type directly, use [DictionaryClient.NewDictionaryFloat32ValueClient] instead. +type DictionaryFloat32ValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DictionaryFloat32ValueClientGetOptions contains the optional parameters for the DictionaryFloat32ValueClient.Get +// method. +func (client *DictionaryFloat32ValueClient) Get(ctx context.Context, options *DictionaryFloat32ValueClientGetOptions) (DictionaryFloat32ValueClientGetResponse, error) { + var err error + const operationName = "DictionaryFloat32ValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return DictionaryFloat32ValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DictionaryFloat32ValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DictionaryFloat32ValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DictionaryFloat32ValueClient) getCreateRequest(ctx context.Context, _ *DictionaryFloat32ValueClientGetOptions) (*policy.Request, error) { + urlPath := "/type/dictionary/float32" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DictionaryFloat32ValueClient) getHandleResponse(resp *http.Response) (DictionaryFloat32ValueClientGetResponse, error) { + result := DictionaryFloat32ValueClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Value); err != nil { + return DictionaryFloat32ValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DictionaryFloat32ValueClientPutOptions contains the optional parameters for the DictionaryFloat32ValueClient.Put +// method. +func (client *DictionaryFloat32ValueClient) Put(ctx context.Context, body map[string]*float32, options *DictionaryFloat32ValueClientPutOptions) (DictionaryFloat32ValueClientPutResponse, error) { + var err error + const operationName = "DictionaryFloat32ValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return DictionaryFloat32ValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DictionaryFloat32ValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DictionaryFloat32ValueClientPutResponse{}, err + } + return DictionaryFloat32ValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *DictionaryFloat32ValueClient) putCreateRequest(ctx context.Context, body map[string]*float32, _ *DictionaryFloat32ValueClientPutOptions) (*policy.Request, error) { + urlPath := "/type/dictionary/float32" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/dictionarygroup/zz_dictionaryint32value_client.go b/test/http-specs/type/dictionarygroup/zz_dictionaryint32value_client.go new file mode 100644 index 000000000000..bbef45540e75 --- /dev/null +++ b/test/http-specs/type/dictionarygroup/zz_dictionaryint32value_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package dictionarygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// DictionaryInt32ValueClient - Dictionary of int32 values +// Don't use this type directly, use [DictionaryClient.NewDictionaryInt32ValueClient] instead. +type DictionaryInt32ValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DictionaryInt32ValueClientGetOptions contains the optional parameters for the DictionaryInt32ValueClient.Get +// method. +func (client *DictionaryInt32ValueClient) Get(ctx context.Context, options *DictionaryInt32ValueClientGetOptions) (DictionaryInt32ValueClientGetResponse, error) { + var err error + const operationName = "DictionaryInt32ValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return DictionaryInt32ValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DictionaryInt32ValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DictionaryInt32ValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DictionaryInt32ValueClient) getCreateRequest(ctx context.Context, _ *DictionaryInt32ValueClientGetOptions) (*policy.Request, error) { + urlPath := "/type/dictionary/int32" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DictionaryInt32ValueClient) getHandleResponse(resp *http.Response) (DictionaryInt32ValueClientGetResponse, error) { + result := DictionaryInt32ValueClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Value); err != nil { + return DictionaryInt32ValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DictionaryInt32ValueClientPutOptions contains the optional parameters for the DictionaryInt32ValueClient.Put +// method. +func (client *DictionaryInt32ValueClient) Put(ctx context.Context, body map[string]*int32, options *DictionaryInt32ValueClientPutOptions) (DictionaryInt32ValueClientPutResponse, error) { + var err error + const operationName = "DictionaryInt32ValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return DictionaryInt32ValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DictionaryInt32ValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DictionaryInt32ValueClientPutResponse{}, err + } + return DictionaryInt32ValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *DictionaryInt32ValueClient) putCreateRequest(ctx context.Context, body map[string]*int32, _ *DictionaryInt32ValueClientPutOptions) (*policy.Request, error) { + urlPath := "/type/dictionary/int32" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/dictionarygroup/zz_dictionaryint64value_client.go b/test/http-specs/type/dictionarygroup/zz_dictionaryint64value_client.go new file mode 100644 index 000000000000..c8aecceb99e1 --- /dev/null +++ b/test/http-specs/type/dictionarygroup/zz_dictionaryint64value_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package dictionarygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// DictionaryInt64ValueClient - Dictionary of int64 values +// Don't use this type directly, use [DictionaryClient.NewDictionaryInt64ValueClient] instead. +type DictionaryInt64ValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DictionaryInt64ValueClientGetOptions contains the optional parameters for the DictionaryInt64ValueClient.Get +// method. +func (client *DictionaryInt64ValueClient) Get(ctx context.Context, options *DictionaryInt64ValueClientGetOptions) (DictionaryInt64ValueClientGetResponse, error) { + var err error + const operationName = "DictionaryInt64ValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return DictionaryInt64ValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DictionaryInt64ValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DictionaryInt64ValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DictionaryInt64ValueClient) getCreateRequest(ctx context.Context, _ *DictionaryInt64ValueClientGetOptions) (*policy.Request, error) { + urlPath := "/type/dictionary/int64" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DictionaryInt64ValueClient) getHandleResponse(resp *http.Response) (DictionaryInt64ValueClientGetResponse, error) { + result := DictionaryInt64ValueClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Value); err != nil { + return DictionaryInt64ValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DictionaryInt64ValueClientPutOptions contains the optional parameters for the DictionaryInt64ValueClient.Put +// method. +func (client *DictionaryInt64ValueClient) Put(ctx context.Context, body map[string]*int64, options *DictionaryInt64ValueClientPutOptions) (DictionaryInt64ValueClientPutResponse, error) { + var err error + const operationName = "DictionaryInt64ValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return DictionaryInt64ValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DictionaryInt64ValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DictionaryInt64ValueClientPutResponse{}, err + } + return DictionaryInt64ValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *DictionaryInt64ValueClient) putCreateRequest(ctx context.Context, body map[string]*int64, _ *DictionaryInt64ValueClientPutOptions) (*policy.Request, error) { + urlPath := "/type/dictionary/int64" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/dictionarygroup/zz_dictionarymodelvalue_client.go b/test/http-specs/type/dictionarygroup/zz_dictionarymodelvalue_client.go new file mode 100644 index 000000000000..a7729907f5d8 --- /dev/null +++ b/test/http-specs/type/dictionarygroup/zz_dictionarymodelvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package dictionarygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// DictionaryModelValueClient - Dictionary of model values +// Don't use this type directly, use [DictionaryClient.NewDictionaryModelValueClient] instead. +type DictionaryModelValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DictionaryModelValueClientGetOptions contains the optional parameters for the DictionaryModelValueClient.Get +// method. +func (client *DictionaryModelValueClient) Get(ctx context.Context, options *DictionaryModelValueClientGetOptions) (DictionaryModelValueClientGetResponse, error) { + var err error + const operationName = "DictionaryModelValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return DictionaryModelValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DictionaryModelValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DictionaryModelValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DictionaryModelValueClient) getCreateRequest(ctx context.Context, _ *DictionaryModelValueClientGetOptions) (*policy.Request, error) { + urlPath := "/type/dictionary/model" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DictionaryModelValueClient) getHandleResponse(resp *http.Response) (DictionaryModelValueClientGetResponse, error) { + result := DictionaryModelValueClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Value); err != nil { + return DictionaryModelValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DictionaryModelValueClientPutOptions contains the optional parameters for the DictionaryModelValueClient.Put +// method. +func (client *DictionaryModelValueClient) Put(ctx context.Context, body map[string]*InnerModel, options *DictionaryModelValueClientPutOptions) (DictionaryModelValueClientPutResponse, error) { + var err error + const operationName = "DictionaryModelValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return DictionaryModelValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DictionaryModelValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DictionaryModelValueClientPutResponse{}, err + } + return DictionaryModelValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *DictionaryModelValueClient) putCreateRequest(ctx context.Context, body map[string]*InnerModel, _ *DictionaryModelValueClientPutOptions) (*policy.Request, error) { + urlPath := "/type/dictionary/model" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/dictionarygroup/zz_dictionarynullablefloatvalue_client.go b/test/http-specs/type/dictionarygroup/zz_dictionarynullablefloatvalue_client.go new file mode 100644 index 000000000000..2d9d99f12aed --- /dev/null +++ b/test/http-specs/type/dictionarygroup/zz_dictionarynullablefloatvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package dictionarygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// DictionaryNullableFloatValueClient - Dictionary of nullable float values +// Don't use this type directly, use [DictionaryClient.NewDictionaryNullableFloatValueClient] instead. +type DictionaryNullableFloatValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DictionaryNullableFloatValueClientGetOptions contains the optional parameters for the DictionaryNullableFloatValueClient.Get +// method. +func (client *DictionaryNullableFloatValueClient) Get(ctx context.Context, options *DictionaryNullableFloatValueClientGetOptions) (DictionaryNullableFloatValueClientGetResponse, error) { + var err error + const operationName = "DictionaryNullableFloatValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return DictionaryNullableFloatValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DictionaryNullableFloatValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DictionaryNullableFloatValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DictionaryNullableFloatValueClient) getCreateRequest(ctx context.Context, _ *DictionaryNullableFloatValueClientGetOptions) (*policy.Request, error) { + urlPath := "/type/dictionary/nullable-float" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DictionaryNullableFloatValueClient) getHandleResponse(resp *http.Response) (DictionaryNullableFloatValueClientGetResponse, error) { + result := DictionaryNullableFloatValueClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Value); err != nil { + return DictionaryNullableFloatValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DictionaryNullableFloatValueClientPutOptions contains the optional parameters for the DictionaryNullableFloatValueClient.Put +// method. +func (client *DictionaryNullableFloatValueClient) Put(ctx context.Context, body map[string]*float32, options *DictionaryNullableFloatValueClientPutOptions) (DictionaryNullableFloatValueClientPutResponse, error) { + var err error + const operationName = "DictionaryNullableFloatValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return DictionaryNullableFloatValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DictionaryNullableFloatValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DictionaryNullableFloatValueClientPutResponse{}, err + } + return DictionaryNullableFloatValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *DictionaryNullableFloatValueClient) putCreateRequest(ctx context.Context, body map[string]*float32, _ *DictionaryNullableFloatValueClientPutOptions) (*policy.Request, error) { + urlPath := "/type/dictionary/nullable-float" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/dictionarygroup/zz_dictionaryrecursivemodelvalue_client.go b/test/http-specs/type/dictionarygroup/zz_dictionaryrecursivemodelvalue_client.go new file mode 100644 index 000000000000..9197cdb44044 --- /dev/null +++ b/test/http-specs/type/dictionarygroup/zz_dictionaryrecursivemodelvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package dictionarygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// DictionaryRecursiveModelValueClient - Dictionary of model values +// Don't use this type directly, use [DictionaryClient.NewDictionaryRecursiveModelValueClient] instead. +type DictionaryRecursiveModelValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DictionaryRecursiveModelValueClientGetOptions contains the optional parameters for the DictionaryRecursiveModelValueClient.Get +// method. +func (client *DictionaryRecursiveModelValueClient) Get(ctx context.Context, options *DictionaryRecursiveModelValueClientGetOptions) (DictionaryRecursiveModelValueClientGetResponse, error) { + var err error + const operationName = "DictionaryRecursiveModelValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return DictionaryRecursiveModelValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DictionaryRecursiveModelValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DictionaryRecursiveModelValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DictionaryRecursiveModelValueClient) getCreateRequest(ctx context.Context, _ *DictionaryRecursiveModelValueClientGetOptions) (*policy.Request, error) { + urlPath := "/type/dictionary/model/recursive" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DictionaryRecursiveModelValueClient) getHandleResponse(resp *http.Response) (DictionaryRecursiveModelValueClientGetResponse, error) { + result := DictionaryRecursiveModelValueClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Value); err != nil { + return DictionaryRecursiveModelValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DictionaryRecursiveModelValueClientPutOptions contains the optional parameters for the DictionaryRecursiveModelValueClient.Put +// method. +func (client *DictionaryRecursiveModelValueClient) Put(ctx context.Context, body map[string]*InnerModel, options *DictionaryRecursiveModelValueClientPutOptions) (DictionaryRecursiveModelValueClientPutResponse, error) { + var err error + const operationName = "DictionaryRecursiveModelValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return DictionaryRecursiveModelValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DictionaryRecursiveModelValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DictionaryRecursiveModelValueClientPutResponse{}, err + } + return DictionaryRecursiveModelValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *DictionaryRecursiveModelValueClient) putCreateRequest(ctx context.Context, body map[string]*InnerModel, _ *DictionaryRecursiveModelValueClientPutOptions) (*policy.Request, error) { + urlPath := "/type/dictionary/model/recursive" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/dictionarygroup/zz_dictionarystringvalue_client.go b/test/http-specs/type/dictionarygroup/zz_dictionarystringvalue_client.go new file mode 100644 index 000000000000..43f835e25972 --- /dev/null +++ b/test/http-specs/type/dictionarygroup/zz_dictionarystringvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package dictionarygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// DictionaryStringValueClient - Dictionary of string values +// Don't use this type directly, use [DictionaryClient.NewDictionaryStringValueClient] instead. +type DictionaryStringValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DictionaryStringValueClientGetOptions contains the optional parameters for the DictionaryStringValueClient.Get +// method. +func (client *DictionaryStringValueClient) Get(ctx context.Context, options *DictionaryStringValueClientGetOptions) (DictionaryStringValueClientGetResponse, error) { + var err error + const operationName = "DictionaryStringValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return DictionaryStringValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DictionaryStringValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DictionaryStringValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DictionaryStringValueClient) getCreateRequest(ctx context.Context, _ *DictionaryStringValueClientGetOptions) (*policy.Request, error) { + urlPath := "/type/dictionary/string" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DictionaryStringValueClient) getHandleResponse(resp *http.Response) (DictionaryStringValueClientGetResponse, error) { + result := DictionaryStringValueClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Value); err != nil { + return DictionaryStringValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DictionaryStringValueClientPutOptions contains the optional parameters for the DictionaryStringValueClient.Put +// method. +func (client *DictionaryStringValueClient) Put(ctx context.Context, body map[string]*string, options *DictionaryStringValueClientPutOptions) (DictionaryStringValueClientPutResponse, error) { + var err error + const operationName = "DictionaryStringValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return DictionaryStringValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DictionaryStringValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DictionaryStringValueClientPutResponse{}, err + } + return DictionaryStringValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *DictionaryStringValueClient) putCreateRequest(ctx context.Context, body map[string]*string, _ *DictionaryStringValueClientPutOptions) (*policy.Request, error) { + urlPath := "/type/dictionary/string" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/dictionarygroup/zz_dictionaryunknownvalue_client.go b/test/http-specs/type/dictionarygroup/zz_dictionaryunknownvalue_client.go new file mode 100644 index 000000000000..c0131f4a376c --- /dev/null +++ b/test/http-specs/type/dictionarygroup/zz_dictionaryunknownvalue_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package dictionarygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// DictionaryUnknownValueClient - Dictionary of unknown values +// Don't use this type directly, use [DictionaryClient.NewDictionaryUnknownValueClient] instead. +type DictionaryUnknownValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DictionaryUnknownValueClientGetOptions contains the optional parameters for the DictionaryUnknownValueClient.Get +// method. +func (client *DictionaryUnknownValueClient) Get(ctx context.Context, options *DictionaryUnknownValueClientGetOptions) (DictionaryUnknownValueClientGetResponse, error) { + var err error + const operationName = "DictionaryUnknownValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return DictionaryUnknownValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DictionaryUnknownValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DictionaryUnknownValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DictionaryUnknownValueClient) getCreateRequest(ctx context.Context, _ *DictionaryUnknownValueClientGetOptions) (*policy.Request, error) { + urlPath := "/type/dictionary/unknown" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DictionaryUnknownValueClient) getHandleResponse(resp *http.Response) (DictionaryUnknownValueClientGetResponse, error) { + result := DictionaryUnknownValueClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Value); err != nil { + return DictionaryUnknownValueClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - DictionaryUnknownValueClientPutOptions contains the optional parameters for the DictionaryUnknownValueClient.Put +// method. +func (client *DictionaryUnknownValueClient) Put(ctx context.Context, body map[string]any, options *DictionaryUnknownValueClientPutOptions) (DictionaryUnknownValueClientPutResponse, error) { + var err error + const operationName = "DictionaryUnknownValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return DictionaryUnknownValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DictionaryUnknownValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DictionaryUnknownValueClientPutResponse{}, err + } + return DictionaryUnknownValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *DictionaryUnknownValueClient) putCreateRequest(ctx context.Context, body map[string]any, _ *DictionaryUnknownValueClientPutOptions) (*policy.Request, error) { + urlPath := "/type/dictionary/unknown" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/dictionarygroup/zz_models.go b/test/http-specs/type/dictionarygroup/zz_models.go new file mode 100644 index 000000000000..0463eb15dbd8 --- /dev/null +++ b/test/http-specs/type/dictionarygroup/zz_models.go @@ -0,0 +1,12 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package dictionarygroup + +// InnerModel - Dictionary inner model +type InnerModel struct { + // REQUIRED; Required string property + Property *string + Children map[string]*InnerModel +} diff --git a/test/http-specs/type/dictionarygroup/zz_models_serde.go b/test/http-specs/type/dictionarygroup/zz_models_serde.go new file mode 100644 index 000000000000..e8f903ce47f5 --- /dev/null +++ b/test/http-specs/type/dictionarygroup/zz_models_serde.go @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package dictionarygroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type InnerModel. +func (i InnerModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "children", i.Children) + populate(objectMap, "property", i.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InnerModel. +func (i *InnerModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "children": + err = unpopulate(val, "Children", &i.Children) + delete(rawMsg, key) + case "property": + err = unpopulate(val, "Property", &i.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/http-specs/type/dictionarygroup/zz_options.go b/test/http-specs/type/dictionarygroup/zz_options.go new file mode 100644 index 000000000000..cacf3556958b --- /dev/null +++ b/test/http-specs/type/dictionarygroup/zz_options.go @@ -0,0 +1,119 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package dictionarygroup + +// DictionaryBooleanValueClientGetOptions contains the optional parameters for the DictionaryBooleanValueClient.Get method. +type DictionaryBooleanValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// DictionaryBooleanValueClientPutOptions contains the optional parameters for the DictionaryBooleanValueClient.Put method. +type DictionaryBooleanValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// DictionaryDatetimeValueClientGetOptions contains the optional parameters for the DictionaryDatetimeValueClient.Get method. +type DictionaryDatetimeValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// DictionaryDatetimeValueClientPutOptions contains the optional parameters for the DictionaryDatetimeValueClient.Put method. +type DictionaryDatetimeValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// DictionaryDurationValueClientGetOptions contains the optional parameters for the DictionaryDurationValueClient.Get method. +type DictionaryDurationValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// DictionaryDurationValueClientPutOptions contains the optional parameters for the DictionaryDurationValueClient.Put method. +type DictionaryDurationValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// DictionaryFloat32ValueClientGetOptions contains the optional parameters for the DictionaryFloat32ValueClient.Get method. +type DictionaryFloat32ValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// DictionaryFloat32ValueClientPutOptions contains the optional parameters for the DictionaryFloat32ValueClient.Put method. +type DictionaryFloat32ValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// DictionaryInt32ValueClientGetOptions contains the optional parameters for the DictionaryInt32ValueClient.Get method. +type DictionaryInt32ValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// DictionaryInt32ValueClientPutOptions contains the optional parameters for the DictionaryInt32ValueClient.Put method. +type DictionaryInt32ValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// DictionaryInt64ValueClientGetOptions contains the optional parameters for the DictionaryInt64ValueClient.Get method. +type DictionaryInt64ValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// DictionaryInt64ValueClientPutOptions contains the optional parameters for the DictionaryInt64ValueClient.Put method. +type DictionaryInt64ValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// DictionaryModelValueClientGetOptions contains the optional parameters for the DictionaryModelValueClient.Get method. +type DictionaryModelValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// DictionaryModelValueClientPutOptions contains the optional parameters for the DictionaryModelValueClient.Put method. +type DictionaryModelValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// DictionaryNullableFloatValueClientGetOptions contains the optional parameters for the DictionaryNullableFloatValueClient.Get +// method. +type DictionaryNullableFloatValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// DictionaryNullableFloatValueClientPutOptions contains the optional parameters for the DictionaryNullableFloatValueClient.Put +// method. +type DictionaryNullableFloatValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// DictionaryRecursiveModelValueClientGetOptions contains the optional parameters for the DictionaryRecursiveModelValueClient.Get +// method. +type DictionaryRecursiveModelValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// DictionaryRecursiveModelValueClientPutOptions contains the optional parameters for the DictionaryRecursiveModelValueClient.Put +// method. +type DictionaryRecursiveModelValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// DictionaryStringValueClientGetOptions contains the optional parameters for the DictionaryStringValueClient.Get method. +type DictionaryStringValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// DictionaryStringValueClientPutOptions contains the optional parameters for the DictionaryStringValueClient.Put method. +type DictionaryStringValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// DictionaryUnknownValueClientGetOptions contains the optional parameters for the DictionaryUnknownValueClient.Get method. +type DictionaryUnknownValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// DictionaryUnknownValueClientPutOptions contains the optional parameters for the DictionaryUnknownValueClient.Put method. +type DictionaryUnknownValueClientPutOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/type/dictionarygroup/zz_responses.go b/test/http-specs/type/dictionarygroup/zz_responses.go new file mode 100644 index 000000000000..13f7293cb9f1 --- /dev/null +++ b/test/http-specs/type/dictionarygroup/zz_responses.go @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package dictionarygroup + +import "time" + +// DictionaryBooleanValueClientGetResponse contains the response from method DictionaryBooleanValueClient.Get. +type DictionaryBooleanValueClientGetResponse struct { + Value map[string]*bool +} + +// DictionaryBooleanValueClientPutResponse contains the response from method DictionaryBooleanValueClient.Put. +type DictionaryBooleanValueClientPutResponse struct { + // placeholder for future response values +} + +// DictionaryDatetimeValueClientGetResponse contains the response from method DictionaryDatetimeValueClient.Get. +type DictionaryDatetimeValueClientGetResponse struct { + Value map[string]*time.Time +} + +// DictionaryDatetimeValueClientPutResponse contains the response from method DictionaryDatetimeValueClient.Put. +type DictionaryDatetimeValueClientPutResponse struct { + // placeholder for future response values +} + +// DictionaryDurationValueClientGetResponse contains the response from method DictionaryDurationValueClient.Get. +type DictionaryDurationValueClientGetResponse struct { + Value map[string]*string +} + +// DictionaryDurationValueClientPutResponse contains the response from method DictionaryDurationValueClient.Put. +type DictionaryDurationValueClientPutResponse struct { + // placeholder for future response values +} + +// DictionaryFloat32ValueClientGetResponse contains the response from method DictionaryFloat32ValueClient.Get. +type DictionaryFloat32ValueClientGetResponse struct { + Value map[string]*float32 +} + +// DictionaryFloat32ValueClientPutResponse contains the response from method DictionaryFloat32ValueClient.Put. +type DictionaryFloat32ValueClientPutResponse struct { + // placeholder for future response values +} + +// DictionaryInt32ValueClientGetResponse contains the response from method DictionaryInt32ValueClient.Get. +type DictionaryInt32ValueClientGetResponse struct { + Value map[string]*int32 +} + +// DictionaryInt32ValueClientPutResponse contains the response from method DictionaryInt32ValueClient.Put. +type DictionaryInt32ValueClientPutResponse struct { + // placeholder for future response values +} + +// DictionaryInt64ValueClientGetResponse contains the response from method DictionaryInt64ValueClient.Get. +type DictionaryInt64ValueClientGetResponse struct { + Value map[string]*int64 +} + +// DictionaryInt64ValueClientPutResponse contains the response from method DictionaryInt64ValueClient.Put. +type DictionaryInt64ValueClientPutResponse struct { + // placeholder for future response values +} + +// DictionaryModelValueClientGetResponse contains the response from method DictionaryModelValueClient.Get. +type DictionaryModelValueClientGetResponse struct { + Value map[string]*InnerModel +} + +// DictionaryModelValueClientPutResponse contains the response from method DictionaryModelValueClient.Put. +type DictionaryModelValueClientPutResponse struct { + // placeholder for future response values +} + +// DictionaryNullableFloatValueClientGetResponse contains the response from method DictionaryNullableFloatValueClient.Get. +type DictionaryNullableFloatValueClientGetResponse struct { + Value map[string]*float32 +} + +// DictionaryNullableFloatValueClientPutResponse contains the response from method DictionaryNullableFloatValueClient.Put. +type DictionaryNullableFloatValueClientPutResponse struct { + // placeholder for future response values +} + +// DictionaryRecursiveModelValueClientGetResponse contains the response from method DictionaryRecursiveModelValueClient.Get. +type DictionaryRecursiveModelValueClientGetResponse struct { + Value map[string]*InnerModel +} + +// DictionaryRecursiveModelValueClientPutResponse contains the response from method DictionaryRecursiveModelValueClient.Put. +type DictionaryRecursiveModelValueClientPutResponse struct { + // placeholder for future response values +} + +// DictionaryStringValueClientGetResponse contains the response from method DictionaryStringValueClient.Get. +type DictionaryStringValueClientGetResponse struct { + Value map[string]*string +} + +// DictionaryStringValueClientPutResponse contains the response from method DictionaryStringValueClient.Put. +type DictionaryStringValueClientPutResponse struct { + // placeholder for future response values +} + +// DictionaryUnknownValueClientGetResponse contains the response from method DictionaryUnknownValueClient.Get. +type DictionaryUnknownValueClientGetResponse struct { + Value map[string]any +} + +// DictionaryUnknownValueClientPutResponse contains the response from method DictionaryUnknownValueClient.Put. +type DictionaryUnknownValueClientPutResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/type/dictionarygroup/zz_version.go b/test/http-specs/type/dictionarygroup/zz_version.go new file mode 100644 index 000000000000..7a800be818ab --- /dev/null +++ b/test/http-specs/type/dictionarygroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package dictionarygroup + +const ( + moduleName = "dictionarygroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/type/enum/extensiblegroup/LICENSE.txt b/test/http-specs/type/enum/extensiblegroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/type/enum/extensiblegroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/type/enum/extensiblegroup/fake/zz_extensible_server.go b/test/http-specs/type/enum/extensiblegroup/fake/zz_extensible_server.go new file mode 100644 index 000000000000..66cb6d2bf105 --- /dev/null +++ b/test/http-specs/type/enum/extensiblegroup/fake/zz_extensible_server.go @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ExtensibleServer is a fake server for instances of the extensiblegroup.ExtensibleClient type. +type ExtensibleServer struct { + // ExtensibleStringServer contains the fakes for client ExtensibleStringClient + ExtensibleStringServer ExtensibleStringServer +} + +// NewExtensibleServerTransport creates a new instance of ExtensibleServerTransport with the provided implementation. +// The returned ExtensibleServerTransport instance is connected to an instance of extensiblegroup.ExtensibleClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewExtensibleServerTransport(srv *ExtensibleServer) *ExtensibleServerTransport { + return &ExtensibleServerTransport{srv: srv} +} + +// ExtensibleServerTransport connects instances of extensiblegroup.ExtensibleClient to instances of ExtensibleServer. +// Don't use this type directly, use NewExtensibleServerTransport instead. +type ExtensibleServerTransport struct { + srv *ExtensibleServer + trMu sync.Mutex + trExtensibleStringServer *ExtensibleStringServerTransport +} + +// Do implements the policy.Transporter interface for ExtensibleServerTransport. +func (e *ExtensibleServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return e.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (e *ExtensibleServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "ExtensibleStringClient": + initServer(&e.trMu, &e.trExtensibleStringServer, func() *ExtensibleStringServerTransport { + return NewExtensibleStringServerTransport(&e.srv.ExtensibleStringServer) + }) + resp, err = e.trExtensibleStringServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to ExtensibleServerTransport +var extensibleServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/enum/extensiblegroup/fake/zz_extensiblestring_server.go b/test/http-specs/type/enum/extensiblegroup/fake/zz_extensiblestring_server.go new file mode 100644 index 000000000000..55b8d3554637 --- /dev/null +++ b/test/http-specs/type/enum/extensiblegroup/fake/zz_extensiblestring_server.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "extensiblegroup" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// ExtensibleStringServer is a fake server for instances of the extensiblegroup.ExtensibleStringClient type. +type ExtensibleStringServer struct { + // GetKnownValue is the fake for method ExtensibleStringClient.GetKnownValue + // HTTP status codes to indicate success: http.StatusOK + GetKnownValue func(ctx context.Context, options *extensiblegroup.ExtensibleStringClientGetKnownValueOptions) (resp azfake.Responder[extensiblegroup.ExtensibleStringClientGetKnownValueResponse], errResp azfake.ErrorResponder) + + // GetUnknownValue is the fake for method ExtensibleStringClient.GetUnknownValue + // HTTP status codes to indicate success: http.StatusOK + GetUnknownValue func(ctx context.Context, options *extensiblegroup.ExtensibleStringClientGetUnknownValueOptions) (resp azfake.Responder[extensiblegroup.ExtensibleStringClientGetUnknownValueResponse], errResp azfake.ErrorResponder) + + // PutKnownValue is the fake for method ExtensibleStringClient.PutKnownValue + // HTTP status codes to indicate success: http.StatusNoContent + PutKnownValue func(ctx context.Context, body extensiblegroup.DaysOfWeekExtensibleEnum, options *extensiblegroup.ExtensibleStringClientPutKnownValueOptions) (resp azfake.Responder[extensiblegroup.ExtensibleStringClientPutKnownValueResponse], errResp azfake.ErrorResponder) + + // PutUnknownValue is the fake for method ExtensibleStringClient.PutUnknownValue + // HTTP status codes to indicate success: http.StatusNoContent + PutUnknownValue func(ctx context.Context, body extensiblegroup.DaysOfWeekExtensibleEnum, options *extensiblegroup.ExtensibleStringClientPutUnknownValueOptions) (resp azfake.Responder[extensiblegroup.ExtensibleStringClientPutUnknownValueResponse], errResp azfake.ErrorResponder) +} + +// NewExtensibleStringServerTransport creates a new instance of ExtensibleStringServerTransport with the provided implementation. +// The returned ExtensibleStringServerTransport instance is connected to an instance of extensiblegroup.ExtensibleStringClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewExtensibleStringServerTransport(srv *ExtensibleStringServer) *ExtensibleStringServerTransport { + return &ExtensibleStringServerTransport{srv: srv} +} + +// ExtensibleStringServerTransport connects instances of extensiblegroup.ExtensibleStringClient to instances of ExtensibleStringServer. +// Don't use this type directly, use NewExtensibleStringServerTransport instead. +type ExtensibleStringServerTransport struct { + srv *ExtensibleStringServer +} + +// Do implements the policy.Transporter interface for ExtensibleStringServerTransport. +func (e *ExtensibleStringServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return e.dispatchToMethodFake(req, method) +} + +func (e *ExtensibleStringServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if extensibleStringServerTransportInterceptor != nil { + res.resp, res.err, intercepted = extensibleStringServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ExtensibleStringClient.GetKnownValue": + res.resp, res.err = e.dispatchGetKnownValue(req) + case "ExtensibleStringClient.GetUnknownValue": + res.resp, res.err = e.dispatchGetUnknownValue(req) + case "ExtensibleStringClient.PutKnownValue": + res.resp, res.err = e.dispatchPutKnownValue(req) + case "ExtensibleStringClient.PutUnknownValue": + res.resp, res.err = e.dispatchPutUnknownValue(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (e *ExtensibleStringServerTransport) dispatchGetKnownValue(req *http.Request) (*http.Response, error) { + if e.srv.GetKnownValue == nil { + return nil, &nonRetriableError{errors.New("fake for method GetKnownValue not implemented")} + } + respr, errRespr := e.srv.GetKnownValue(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Value, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *ExtensibleStringServerTransport) dispatchGetUnknownValue(req *http.Request) (*http.Response, error) { + if e.srv.GetUnknownValue == nil { + return nil, &nonRetriableError{errors.New("fake for method GetUnknownValue not implemented")} + } + respr, errRespr := e.srv.GetUnknownValue(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Value, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *ExtensibleStringServerTransport) dispatchPutKnownValue(req *http.Request) (*http.Response, error) { + if e.srv.PutKnownValue == nil { + return nil, &nonRetriableError{errors.New("fake for method PutKnownValue not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[extensiblegroup.DaysOfWeekExtensibleEnum](req) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.PutKnownValue(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *ExtensibleStringServerTransport) dispatchPutUnknownValue(req *http.Request) (*http.Response, error) { + if e.srv.PutUnknownValue == nil { + return nil, &nonRetriableError{errors.New("fake for method PutUnknownValue not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[extensiblegroup.DaysOfWeekExtensibleEnum](req) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.PutUnknownValue(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ExtensibleStringServerTransport +var extensibleStringServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/enum/extensiblegroup/fake/zz_internal.go b/test/http-specs/type/enum/extensiblegroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/http-specs/type/enum/extensiblegroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/http-specs/type/enum/extensiblegroup/go.mod b/test/http-specs/type/enum/extensiblegroup/go.mod new file mode 100644 index 000000000000..be028ded81b7 --- /dev/null +++ b/test/http-specs/type/enum/extensiblegroup/go.mod @@ -0,0 +1,17 @@ +module extensiblegroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/type/enum/extensiblegroup/go.sum b/test/http-specs/type/enum/extensiblegroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/type/enum/extensiblegroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/type/enum/extensiblegroup/string_client_test.go b/test/http-specs/type/enum/extensiblegroup/string_client_test.go new file mode 100644 index 000000000000..9b90638f41da --- /dev/null +++ b/test/http-specs/type/enum/extensiblegroup/string_client_test.go @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package extensiblegroup_test + +import ( + "context" + "extensiblegroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestExtensibleClientGetKnownValue(t *testing.T) { + client, err := extensiblegroup.NewExtensibleClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewExtensibleStringClient().GetKnownValue(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.Equal(t, extensiblegroup.DaysOfWeekExtensibleEnumMonday, *resp.Value) +} + +func TestExtensibleClientGetUnknownValue(t *testing.T) { + client, err := extensiblegroup.NewExtensibleClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewExtensibleStringClient().GetUnknownValue(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.Equal(t, extensiblegroup.DaysOfWeekExtensibleEnum("Weekend"), *resp.Value) +} + +func TestExtensibleClientPutKnownValue(t *testing.T) { + client, err := extensiblegroup.NewExtensibleClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewExtensibleStringClient().PutKnownValue(context.Background(), extensiblegroup.DaysOfWeekExtensibleEnumMonday, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestExtensibleClientPutUnknownValue(t *testing.T) { + client, err := extensiblegroup.NewExtensibleClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewExtensibleStringClient().PutUnknownValue(context.Background(), extensiblegroup.DaysOfWeekExtensibleEnum("Weekend"), nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/enum/extensiblegroup/testdata/_metadata.json b/test/http-specs/type/enum/extensiblegroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/type/enum/extensiblegroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/type/enum/extensiblegroup/zz_constants.go b/test/http-specs/type/enum/extensiblegroup/zz_constants.go new file mode 100644 index 000000000000..7ee42287cc04 --- /dev/null +++ b/test/http-specs/type/enum/extensiblegroup/zz_constants.go @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package extensiblegroup + +// DaysOfWeekExtensibleEnum - Days of the week +type DaysOfWeekExtensibleEnum string + +const ( + // DaysOfWeekExtensibleEnumFriday - Friday. + DaysOfWeekExtensibleEnumFriday DaysOfWeekExtensibleEnum = "Friday" + // DaysOfWeekExtensibleEnumMonday - Monday. + DaysOfWeekExtensibleEnumMonday DaysOfWeekExtensibleEnum = "Monday" + // DaysOfWeekExtensibleEnumSaturday - Saturday. + DaysOfWeekExtensibleEnumSaturday DaysOfWeekExtensibleEnum = "Saturday" + // DaysOfWeekExtensibleEnumSunday - Sunday. + DaysOfWeekExtensibleEnumSunday DaysOfWeekExtensibleEnum = "Sunday" + // DaysOfWeekExtensibleEnumThursday - Thursday. + DaysOfWeekExtensibleEnumThursday DaysOfWeekExtensibleEnum = "Thursday" + // DaysOfWeekExtensibleEnumTuesday - Tuesday. + DaysOfWeekExtensibleEnumTuesday DaysOfWeekExtensibleEnum = "Tuesday" + // DaysOfWeekExtensibleEnumWednesday - Wednesday. + DaysOfWeekExtensibleEnumWednesday DaysOfWeekExtensibleEnum = "Wednesday" +) + +// PossibleDaysOfWeekExtensibleEnumValues returns the possible values for the DaysOfWeekExtensibleEnum const type. +func PossibleDaysOfWeekExtensibleEnumValues() []DaysOfWeekExtensibleEnum { + return []DaysOfWeekExtensibleEnum{ + DaysOfWeekExtensibleEnumFriday, + DaysOfWeekExtensibleEnumMonday, + DaysOfWeekExtensibleEnumSaturday, + DaysOfWeekExtensibleEnumSunday, + DaysOfWeekExtensibleEnumThursday, + DaysOfWeekExtensibleEnumTuesday, + DaysOfWeekExtensibleEnumWednesday, + } +} diff --git a/test/http-specs/type/enum/extensiblegroup/zz_extensible_client.go b/test/http-specs/type/enum/extensiblegroup/zz_extensible_client.go new file mode 100644 index 000000000000..c73a207ddfc5 --- /dev/null +++ b/test/http-specs/type/enum/extensiblegroup/zz_extensible_client.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package extensiblegroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// ExtensibleClient contains the methods for the Extensible group. +// Don't use this type directly, use NewExtensibleClientWithNoCredential() instead. +type ExtensibleClient struct { + internal *azcore.Client + endpoint string +} + +// ExtensibleClientOptions contains the optional values for creating a [ExtensibleClient]. +type ExtensibleClientOptions struct { + azcore.ClientOptions +} + +// NewExtensibleClientWithNoCredential creates a new instance of ExtensibleClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewExtensibleClientWithNoCredential(endpoint string, options *ExtensibleClientOptions) (*ExtensibleClient, error) { + if options == nil { + options = &ExtensibleClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &ExtensibleClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewExtensibleStringClient creates a new instance of [ExtensibleStringClient]. +func (client *ExtensibleClient) NewExtensibleStringClient() *ExtensibleStringClient { + return &ExtensibleStringClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/http-specs/type/enum/extensiblegroup/zz_extensiblestring_client.go b/test/http-specs/type/enum/extensiblegroup/zz_extensiblestring_client.go new file mode 100644 index 000000000000..8c2d64f4d588 --- /dev/null +++ b/test/http-specs/type/enum/extensiblegroup/zz_extensiblestring_client.go @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package extensiblegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ExtensibleStringClient contains the methods for the ExtensibleString group. +// Don't use this type directly, use [ExtensibleClient.NewExtensibleStringClient] instead. +type ExtensibleStringClient struct { + internal *azcore.Client + endpoint string +} + +// GetKnownValue - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ExtensibleStringClientGetKnownValueOptions contains the optional parameters for the ExtensibleStringClient.GetKnownValue +// method. +func (client *ExtensibleStringClient) GetKnownValue(ctx context.Context, options *ExtensibleStringClientGetKnownValueOptions) (ExtensibleStringClientGetKnownValueResponse, error) { + var err error + const operationName = "ExtensibleStringClient.GetKnownValue" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getKnownValueCreateRequest(ctx, options) + if err != nil { + return ExtensibleStringClientGetKnownValueResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExtensibleStringClientGetKnownValueResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExtensibleStringClientGetKnownValueResponse{}, err + } + resp, err := client.getKnownValueHandleResponse(httpResp) + return resp, err +} + +// getKnownValueCreateRequest creates the GetKnownValue request. +func (client *ExtensibleStringClient) getKnownValueCreateRequest(ctx context.Context, _ *ExtensibleStringClientGetKnownValueOptions) (*policy.Request, error) { + urlPath := "/type/enum/extensible/string/known-value" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getKnownValueHandleResponse handles the GetKnownValue response. +func (client *ExtensibleStringClient) getKnownValueHandleResponse(resp *http.Response) (ExtensibleStringClientGetKnownValueResponse, error) { + result := ExtensibleStringClientGetKnownValueResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Value); err != nil { + return ExtensibleStringClientGetKnownValueResponse{}, err + } + return result, nil +} + +// GetUnknownValue - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ExtensibleStringClientGetUnknownValueOptions contains the optional parameters for the ExtensibleStringClient.GetUnknownValue +// method. +func (client *ExtensibleStringClient) GetUnknownValue(ctx context.Context, options *ExtensibleStringClientGetUnknownValueOptions) (ExtensibleStringClientGetUnknownValueResponse, error) { + var err error + const operationName = "ExtensibleStringClient.GetUnknownValue" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getUnknownValueCreateRequest(ctx, options) + if err != nil { + return ExtensibleStringClientGetUnknownValueResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExtensibleStringClientGetUnknownValueResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExtensibleStringClientGetUnknownValueResponse{}, err + } + resp, err := client.getUnknownValueHandleResponse(httpResp) + return resp, err +} + +// getUnknownValueCreateRequest creates the GetUnknownValue request. +func (client *ExtensibleStringClient) getUnknownValueCreateRequest(ctx context.Context, _ *ExtensibleStringClientGetUnknownValueOptions) (*policy.Request, error) { + urlPath := "/type/enum/extensible/string/unknown-value" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getUnknownValueHandleResponse handles the GetUnknownValue response. +func (client *ExtensibleStringClient) getUnknownValueHandleResponse(resp *http.Response) (ExtensibleStringClientGetUnknownValueResponse, error) { + result := ExtensibleStringClientGetUnknownValueResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Value); err != nil { + return ExtensibleStringClientGetUnknownValueResponse{}, err + } + return result, nil +} + +// PutKnownValue - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ExtensibleStringClientPutKnownValueOptions contains the optional parameters for the ExtensibleStringClient.PutKnownValue +// method. +func (client *ExtensibleStringClient) PutKnownValue(ctx context.Context, body DaysOfWeekExtensibleEnum, options *ExtensibleStringClientPutKnownValueOptions) (ExtensibleStringClientPutKnownValueResponse, error) { + var err error + const operationName = "ExtensibleStringClient.PutKnownValue" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putKnownValueCreateRequest(ctx, body, options) + if err != nil { + return ExtensibleStringClientPutKnownValueResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExtensibleStringClientPutKnownValueResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ExtensibleStringClientPutKnownValueResponse{}, err + } + return ExtensibleStringClientPutKnownValueResponse{}, nil +} + +// putKnownValueCreateRequest creates the PutKnownValue request. +func (client *ExtensibleStringClient) putKnownValueCreateRequest(ctx context.Context, body DaysOfWeekExtensibleEnum, _ *ExtensibleStringClientPutKnownValueOptions) (*policy.Request, error) { + urlPath := "/type/enum/extensible/string/known-value" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// PutUnknownValue - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ExtensibleStringClientPutUnknownValueOptions contains the optional parameters for the ExtensibleStringClient.PutUnknownValue +// method. +func (client *ExtensibleStringClient) PutUnknownValue(ctx context.Context, body DaysOfWeekExtensibleEnum, options *ExtensibleStringClientPutUnknownValueOptions) (ExtensibleStringClientPutUnknownValueResponse, error) { + var err error + const operationName = "ExtensibleStringClient.PutUnknownValue" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putUnknownValueCreateRequest(ctx, body, options) + if err != nil { + return ExtensibleStringClientPutUnknownValueResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExtensibleStringClientPutUnknownValueResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ExtensibleStringClientPutUnknownValueResponse{}, err + } + return ExtensibleStringClientPutUnknownValueResponse{}, nil +} + +// putUnknownValueCreateRequest creates the PutUnknownValue request. +func (client *ExtensibleStringClient) putUnknownValueCreateRequest(ctx context.Context, body DaysOfWeekExtensibleEnum, _ *ExtensibleStringClientPutUnknownValueOptions) (*policy.Request, error) { + urlPath := "/type/enum/extensible/string/unknown-value" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/enum/extensiblegroup/zz_options.go b/test/http-specs/type/enum/extensiblegroup/zz_options.go new file mode 100644 index 000000000000..24bdc72ca328 --- /dev/null +++ b/test/http-specs/type/enum/extensiblegroup/zz_options.go @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package extensiblegroup + +// ExtensibleStringClientGetKnownValueOptions contains the optional parameters for the ExtensibleStringClient.GetKnownValue +// method. +type ExtensibleStringClientGetKnownValueOptions struct { + // placeholder for future optional parameters +} + +// ExtensibleStringClientGetUnknownValueOptions contains the optional parameters for the ExtensibleStringClient.GetUnknownValue +// method. +type ExtensibleStringClientGetUnknownValueOptions struct { + // placeholder for future optional parameters +} + +// ExtensibleStringClientPutKnownValueOptions contains the optional parameters for the ExtensibleStringClient.PutKnownValue +// method. +type ExtensibleStringClientPutKnownValueOptions struct { + // placeholder for future optional parameters +} + +// ExtensibleStringClientPutUnknownValueOptions contains the optional parameters for the ExtensibleStringClient.PutUnknownValue +// method. +type ExtensibleStringClientPutUnknownValueOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/type/enum/extensiblegroup/zz_responses.go b/test/http-specs/type/enum/extensiblegroup/zz_responses.go new file mode 100644 index 000000000000..7c9a0cc1ac25 --- /dev/null +++ b/test/http-specs/type/enum/extensiblegroup/zz_responses.go @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package extensiblegroup + +// ExtensibleStringClientGetKnownValueResponse contains the response from method ExtensibleStringClient.GetKnownValue. +type ExtensibleStringClientGetKnownValueResponse struct { + Value *DaysOfWeekExtensibleEnum +} + +// ExtensibleStringClientGetUnknownValueResponse contains the response from method ExtensibleStringClient.GetUnknownValue. +type ExtensibleStringClientGetUnknownValueResponse struct { + Value *DaysOfWeekExtensibleEnum +} + +// ExtensibleStringClientPutKnownValueResponse contains the response from method ExtensibleStringClient.PutKnownValue. +type ExtensibleStringClientPutKnownValueResponse struct { + // placeholder for future response values +} + +// ExtensibleStringClientPutUnknownValueResponse contains the response from method ExtensibleStringClient.PutUnknownValue. +type ExtensibleStringClientPutUnknownValueResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/type/enum/extensiblegroup/zz_version.go b/test/http-specs/type/enum/extensiblegroup/zz_version.go new file mode 100644 index 000000000000..e0f1acfdddcc --- /dev/null +++ b/test/http-specs/type/enum/extensiblegroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package extensiblegroup + +const ( + moduleName = "extensiblegroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/type/enum/fixedgroup/LICENSE.txt b/test/http-specs/type/enum/fixedgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/type/enum/fixedgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/type/enum/fixedgroup/fake/zz_fixed_server.go b/test/http-specs/type/enum/fixedgroup/fake/zz_fixed_server.go new file mode 100644 index 000000000000..9aad102ba470 --- /dev/null +++ b/test/http-specs/type/enum/fixedgroup/fake/zz_fixed_server.go @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// FixedServer is a fake server for instances of the fixedgroup.FixedClient type. +type FixedServer struct { + // FixedStringServer contains the fakes for client FixedStringClient + FixedStringServer FixedStringServer +} + +// NewFixedServerTransport creates a new instance of FixedServerTransport with the provided implementation. +// The returned FixedServerTransport instance is connected to an instance of fixedgroup.FixedClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewFixedServerTransport(srv *FixedServer) *FixedServerTransport { + return &FixedServerTransport{srv: srv} +} + +// FixedServerTransport connects instances of fixedgroup.FixedClient to instances of FixedServer. +// Don't use this type directly, use NewFixedServerTransport instead. +type FixedServerTransport struct { + srv *FixedServer + trMu sync.Mutex + trFixedStringServer *FixedStringServerTransport +} + +// Do implements the policy.Transporter interface for FixedServerTransport. +func (f *FixedServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return f.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (f *FixedServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "FixedStringClient": + initServer(&f.trMu, &f.trFixedStringServer, func() *FixedStringServerTransport { + return NewFixedStringServerTransport(&f.srv.FixedStringServer) + }) + resp, err = f.trFixedStringServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to FixedServerTransport +var fixedServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/enum/fixedgroup/fake/zz_fixedstring_server.go b/test/http-specs/type/enum/fixedgroup/fake/zz_fixedstring_server.go new file mode 100644 index 000000000000..356daee63a96 --- /dev/null +++ b/test/http-specs/type/enum/fixedgroup/fake/zz_fixedstring_server.go @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fixedgroup" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// FixedStringServer is a fake server for instances of the fixedgroup.FixedStringClient type. +type FixedStringServer struct { + // GetKnownValue is the fake for method FixedStringClient.GetKnownValue + // HTTP status codes to indicate success: http.StatusOK + GetKnownValue func(ctx context.Context, options *fixedgroup.FixedStringClientGetKnownValueOptions) (resp azfake.Responder[fixedgroup.FixedStringClientGetKnownValueResponse], errResp azfake.ErrorResponder) + + // PutKnownValue is the fake for method FixedStringClient.PutKnownValue + // HTTP status codes to indicate success: http.StatusNoContent + PutKnownValue func(ctx context.Context, body fixedgroup.DaysOfWeekEnum, options *fixedgroup.FixedStringClientPutKnownValueOptions) (resp azfake.Responder[fixedgroup.FixedStringClientPutKnownValueResponse], errResp azfake.ErrorResponder) + + // PutUnknownValue is the fake for method FixedStringClient.PutUnknownValue + // HTTP status codes to indicate success: http.StatusNoContent + PutUnknownValue func(ctx context.Context, body fixedgroup.DaysOfWeekEnum, options *fixedgroup.FixedStringClientPutUnknownValueOptions) (resp azfake.Responder[fixedgroup.FixedStringClientPutUnknownValueResponse], errResp azfake.ErrorResponder) +} + +// NewFixedStringServerTransport creates a new instance of FixedStringServerTransport with the provided implementation. +// The returned FixedStringServerTransport instance is connected to an instance of fixedgroup.FixedStringClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewFixedStringServerTransport(srv *FixedStringServer) *FixedStringServerTransport { + return &FixedStringServerTransport{srv: srv} +} + +// FixedStringServerTransport connects instances of fixedgroup.FixedStringClient to instances of FixedStringServer. +// Don't use this type directly, use NewFixedStringServerTransport instead. +type FixedStringServerTransport struct { + srv *FixedStringServer +} + +// Do implements the policy.Transporter interface for FixedStringServerTransport. +func (f *FixedStringServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return f.dispatchToMethodFake(req, method) +} + +func (f *FixedStringServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if fixedStringServerTransportInterceptor != nil { + res.resp, res.err, intercepted = fixedStringServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "FixedStringClient.GetKnownValue": + res.resp, res.err = f.dispatchGetKnownValue(req) + case "FixedStringClient.PutKnownValue": + res.resp, res.err = f.dispatchPutKnownValue(req) + case "FixedStringClient.PutUnknownValue": + res.resp, res.err = f.dispatchPutUnknownValue(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (f *FixedStringServerTransport) dispatchGetKnownValue(req *http.Request) (*http.Response, error) { + if f.srv.GetKnownValue == nil { + return nil, &nonRetriableError{errors.New("fake for method GetKnownValue not implemented")} + } + respr, errRespr := f.srv.GetKnownValue(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Value, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (f *FixedStringServerTransport) dispatchPutKnownValue(req *http.Request) (*http.Response, error) { + if f.srv.PutKnownValue == nil { + return nil, &nonRetriableError{errors.New("fake for method PutKnownValue not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[fixedgroup.DaysOfWeekEnum](req) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.PutKnownValue(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (f *FixedStringServerTransport) dispatchPutUnknownValue(req *http.Request) (*http.Response, error) { + if f.srv.PutUnknownValue == nil { + return nil, &nonRetriableError{errors.New("fake for method PutUnknownValue not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[fixedgroup.DaysOfWeekEnum](req) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.PutUnknownValue(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to FixedStringServerTransport +var fixedStringServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/enum/fixedgroup/fake/zz_internal.go b/test/http-specs/type/enum/fixedgroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/http-specs/type/enum/fixedgroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/http-specs/type/enum/fixedgroup/go.mod b/test/http-specs/type/enum/fixedgroup/go.mod new file mode 100644 index 000000000000..bf007fb5f8e4 --- /dev/null +++ b/test/http-specs/type/enum/fixedgroup/go.mod @@ -0,0 +1,17 @@ +module fixedgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/type/enum/fixedgroup/go.sum b/test/http-specs/type/enum/fixedgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/type/enum/fixedgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/type/enum/fixedgroup/string_client_test.go b/test/http-specs/type/enum/fixedgroup/string_client_test.go new file mode 100644 index 000000000000..1a47a0c4be7e --- /dev/null +++ b/test/http-specs/type/enum/fixedgroup/string_client_test.go @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package fixedgroup_test + +import ( + "context" + "fixedgroup" + "net/http" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/stretchr/testify/require" +) + +func TestFixedClientGetKnownValue(t *testing.T) { + client, err := fixedgroup.NewFixedClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewFixedStringClient().GetKnownValue(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, fixedgroup.DaysOfWeekEnumMonday, *resp.Value) +} + +func TestFixedClientPutKnownValue(t *testing.T) { + client, err := fixedgroup.NewFixedClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewFixedStringClient().PutKnownValue(context.Background(), fixedgroup.DaysOfWeekEnumMonday, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestFixedClientPutUnknownValue(t *testing.T) { + client, err := fixedgroup.NewFixedClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewFixedStringClient().PutUnknownValue(context.Background(), fixedgroup.DaysOfWeekEnum("Weekend"), nil) + var respErr *azcore.ResponseError + require.ErrorAs(t, err, &respErr) + require.EqualValues(t, http.StatusInternalServerError, respErr.StatusCode) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/enum/fixedgroup/testdata/_metadata.json b/test/http-specs/type/enum/fixedgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/type/enum/fixedgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/type/enum/fixedgroup/zz_constants.go b/test/http-specs/type/enum/fixedgroup/zz_constants.go new file mode 100644 index 000000000000..a8337ee3e8f1 --- /dev/null +++ b/test/http-specs/type/enum/fixedgroup/zz_constants.go @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fixedgroup + +// DaysOfWeekEnum - Days of the week +type DaysOfWeekEnum string + +const ( + // DaysOfWeekEnumFriday - Friday. + DaysOfWeekEnumFriday DaysOfWeekEnum = "Friday" + // DaysOfWeekEnumMonday - Monday. + DaysOfWeekEnumMonday DaysOfWeekEnum = "Monday" + // DaysOfWeekEnumSaturday - Saturday. + DaysOfWeekEnumSaturday DaysOfWeekEnum = "Saturday" + // DaysOfWeekEnumSunday - Sunday. + DaysOfWeekEnumSunday DaysOfWeekEnum = "Sunday" + // DaysOfWeekEnumThursday - Thursday. + DaysOfWeekEnumThursday DaysOfWeekEnum = "Thursday" + // DaysOfWeekEnumTuesday - Tuesday. + DaysOfWeekEnumTuesday DaysOfWeekEnum = "Tuesday" + // DaysOfWeekEnumWednesday - Wednesday. + DaysOfWeekEnumWednesday DaysOfWeekEnum = "Wednesday" +) + +// PossibleDaysOfWeekEnumValues returns the possible values for the DaysOfWeekEnum const type. +func PossibleDaysOfWeekEnumValues() []DaysOfWeekEnum { + return []DaysOfWeekEnum{ + DaysOfWeekEnumFriday, + DaysOfWeekEnumMonday, + DaysOfWeekEnumSaturday, + DaysOfWeekEnumSunday, + DaysOfWeekEnumThursday, + DaysOfWeekEnumTuesday, + DaysOfWeekEnumWednesday, + } +} diff --git a/test/http-specs/type/enum/fixedgroup/zz_fixed_client.go b/test/http-specs/type/enum/fixedgroup/zz_fixed_client.go new file mode 100644 index 000000000000..48f6e16d6804 --- /dev/null +++ b/test/http-specs/type/enum/fixedgroup/zz_fixed_client.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fixedgroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// FixedClient contains the methods for the Fixed group. +// Don't use this type directly, use NewFixedClientWithNoCredential() instead. +type FixedClient struct { + internal *azcore.Client + endpoint string +} + +// FixedClientOptions contains the optional values for creating a [FixedClient]. +type FixedClientOptions struct { + azcore.ClientOptions +} + +// NewFixedClientWithNoCredential creates a new instance of FixedClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewFixedClientWithNoCredential(endpoint string, options *FixedClientOptions) (*FixedClient, error) { + if options == nil { + options = &FixedClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &FixedClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewFixedStringClient creates a new instance of [FixedStringClient]. +func (client *FixedClient) NewFixedStringClient() *FixedStringClient { + return &FixedStringClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/http-specs/type/enum/fixedgroup/zz_fixedstring_client.go b/test/http-specs/type/enum/fixedgroup/zz_fixedstring_client.go new file mode 100644 index 000000000000..f5d6c69c1b98 --- /dev/null +++ b/test/http-specs/type/enum/fixedgroup/zz_fixedstring_client.go @@ -0,0 +1,146 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fixedgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// FixedStringClient contains the methods for the FixedString group. +// Don't use this type directly, use [FixedClient.NewFixedStringClient] instead. +type FixedStringClient struct { + internal *azcore.Client + endpoint string +} + +// GetKnownValue - getKnownValue +// If the operation fails it returns an *azcore.ResponseError type. +// - options - FixedStringClientGetKnownValueOptions contains the optional parameters for the FixedStringClient.GetKnownValue +// method. +func (client *FixedStringClient) GetKnownValue(ctx context.Context, options *FixedStringClientGetKnownValueOptions) (FixedStringClientGetKnownValueResponse, error) { + var err error + const operationName = "FixedStringClient.GetKnownValue" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getKnownValueCreateRequest(ctx, options) + if err != nil { + return FixedStringClientGetKnownValueResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FixedStringClientGetKnownValueResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FixedStringClientGetKnownValueResponse{}, err + } + resp, err := client.getKnownValueHandleResponse(httpResp) + return resp, err +} + +// getKnownValueCreateRequest creates the GetKnownValue request. +func (client *FixedStringClient) getKnownValueCreateRequest(ctx context.Context, _ *FixedStringClientGetKnownValueOptions) (*policy.Request, error) { + urlPath := "/type/enum/fixed/string/known-value" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getKnownValueHandleResponse handles the GetKnownValue response. +func (client *FixedStringClient) getKnownValueHandleResponse(resp *http.Response) (FixedStringClientGetKnownValueResponse, error) { + result := FixedStringClientGetKnownValueResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Value); err != nil { + return FixedStringClientGetKnownValueResponse{}, err + } + return result, nil +} + +// PutKnownValue - putKnownValue +// If the operation fails it returns an *azcore.ResponseError type. +// - body - _ +// - options - FixedStringClientPutKnownValueOptions contains the optional parameters for the FixedStringClient.PutKnownValue +// method. +func (client *FixedStringClient) PutKnownValue(ctx context.Context, body DaysOfWeekEnum, options *FixedStringClientPutKnownValueOptions) (FixedStringClientPutKnownValueResponse, error) { + var err error + const operationName = "FixedStringClient.PutKnownValue" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putKnownValueCreateRequest(ctx, body, options) + if err != nil { + return FixedStringClientPutKnownValueResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FixedStringClientPutKnownValueResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return FixedStringClientPutKnownValueResponse{}, err + } + return FixedStringClientPutKnownValueResponse{}, nil +} + +// putKnownValueCreateRequest creates the PutKnownValue request. +func (client *FixedStringClient) putKnownValueCreateRequest(ctx context.Context, body DaysOfWeekEnum, _ *FixedStringClientPutKnownValueOptions) (*policy.Request, error) { + urlPath := "/type/enum/fixed/string/known-value" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// PutUnknownValue - putUnknownValue +// If the operation fails it returns an *azcore.ResponseError type. +// - body - _ +// - options - FixedStringClientPutUnknownValueOptions contains the optional parameters for the FixedStringClient.PutUnknownValue +// method. +func (client *FixedStringClient) PutUnknownValue(ctx context.Context, body DaysOfWeekEnum, options *FixedStringClientPutUnknownValueOptions) (FixedStringClientPutUnknownValueResponse, error) { + var err error + const operationName = "FixedStringClient.PutUnknownValue" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putUnknownValueCreateRequest(ctx, body, options) + if err != nil { + return FixedStringClientPutUnknownValueResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FixedStringClientPutUnknownValueResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return FixedStringClientPutUnknownValueResponse{}, err + } + return FixedStringClientPutUnknownValueResponse{}, nil +} + +// putUnknownValueCreateRequest creates the PutUnknownValue request. +func (client *FixedStringClient) putUnknownValueCreateRequest(ctx context.Context, body DaysOfWeekEnum, _ *FixedStringClientPutUnknownValueOptions) (*policy.Request, error) { + urlPath := "/type/enum/fixed/string/unknown-value" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/enum/fixedgroup/zz_options.go b/test/http-specs/type/enum/fixedgroup/zz_options.go new file mode 100644 index 000000000000..ca8dc2c36f37 --- /dev/null +++ b/test/http-specs/type/enum/fixedgroup/zz_options.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fixedgroup + +// FixedStringClientGetKnownValueOptions contains the optional parameters for the FixedStringClient.GetKnownValue method. +type FixedStringClientGetKnownValueOptions struct { + // placeholder for future optional parameters +} + +// FixedStringClientPutKnownValueOptions contains the optional parameters for the FixedStringClient.PutKnownValue method. +type FixedStringClientPutKnownValueOptions struct { + // placeholder for future optional parameters +} + +// FixedStringClientPutUnknownValueOptions contains the optional parameters for the FixedStringClient.PutUnknownValue method. +type FixedStringClientPutUnknownValueOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/type/enum/fixedgroup/zz_responses.go b/test/http-specs/type/enum/fixedgroup/zz_responses.go new file mode 100644 index 000000000000..d7912220a20b --- /dev/null +++ b/test/http-specs/type/enum/fixedgroup/zz_responses.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fixedgroup + +// FixedStringClientGetKnownValueResponse contains the response from method FixedStringClient.GetKnownValue. +type FixedStringClientGetKnownValueResponse struct { + Value *DaysOfWeekEnum +} + +// FixedStringClientPutKnownValueResponse contains the response from method FixedStringClient.PutKnownValue. +type FixedStringClientPutKnownValueResponse struct { + // placeholder for future response values +} + +// FixedStringClientPutUnknownValueResponse contains the response from method FixedStringClient.PutUnknownValue. +type FixedStringClientPutUnknownValueResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/type/enum/fixedgroup/zz_version.go b/test/http-specs/type/enum/fixedgroup/zz_version.go new file mode 100644 index 000000000000..65ce87a2c623 --- /dev/null +++ b/test/http-specs/type/enum/fixedgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package fixedgroup + +const ( + moduleName = "fixedgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/type/model/emptygroup/LICENSE.txt b/test/http-specs/type/model/emptygroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/type/model/emptygroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/type/model/emptygroup/empty_client_test.go b/test/http-specs/type/model/emptygroup/empty_client_test.go new file mode 100644 index 000000000000..c4f90ba3147f --- /dev/null +++ b/test/http-specs/type/model/emptygroup/empty_client_test.go @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package emptygroup_test + +import ( + "context" + "emptygroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestEmptyClientGetEmpty(t *testing.T) { + client, err := emptygroup.NewEmptyClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.GetEmpty(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestEmptyClientPostRoundTripEmpty(t *testing.T) { + client, err := emptygroup.NewEmptyClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.PostRoundTripEmpty(context.Background(), emptygroup.EmptyInputOutput{}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestEmptyClientPutEmpty(t *testing.T) { + client, err := emptygroup.NewEmptyClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.PutEmpty(context.Background(), emptygroup.EmptyInput{}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/model/emptygroup/fake/zz_empty_server.go b/test/http-specs/type/model/emptygroup/fake/zz_empty_server.go new file mode 100644 index 000000000000..7d8cbf9677c7 --- /dev/null +++ b/test/http-specs/type/model/emptygroup/fake/zz_empty_server.go @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "emptygroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// EmptyServer is a fake server for instances of the emptygroup.EmptyClient type. +type EmptyServer struct { + // GetEmpty is the fake for method EmptyClient.GetEmpty + // HTTP status codes to indicate success: http.StatusOK + GetEmpty func(ctx context.Context, options *emptygroup.GetEmptyOptions) (resp azfake.Responder[emptygroup.GetEmptyResponse], errResp azfake.ErrorResponder) + + // PostRoundTripEmpty is the fake for method EmptyClient.PostRoundTripEmpty + // HTTP status codes to indicate success: http.StatusOK + PostRoundTripEmpty func(ctx context.Context, body emptygroup.EmptyInputOutput, options *emptygroup.PostRoundTripEmptyOptions) (resp azfake.Responder[emptygroup.PostRoundTripEmptyResponse], errResp azfake.ErrorResponder) + + // PutEmpty is the fake for method EmptyClient.PutEmpty + // HTTP status codes to indicate success: http.StatusNoContent + PutEmpty func(ctx context.Context, input emptygroup.EmptyInput, options *emptygroup.PutEmptyOptions) (resp azfake.Responder[emptygroup.PutEmptyResponse], errResp azfake.ErrorResponder) +} + +// NewEmptyServerTransport creates a new instance of EmptyServerTransport with the provided implementation. +// The returned EmptyServerTransport instance is connected to an instance of emptygroup.EmptyClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewEmptyServerTransport(srv *EmptyServer) *EmptyServerTransport { + return &EmptyServerTransport{srv: srv} +} + +// EmptyServerTransport connects instances of emptygroup.EmptyClient to instances of EmptyServer. +// Don't use this type directly, use NewEmptyServerTransport instead. +type EmptyServerTransport struct { + srv *EmptyServer +} + +// Do implements the policy.Transporter interface for EmptyServerTransport. +func (e *EmptyServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return e.dispatchToMethodFake(req, method) +} + +func (e *EmptyServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if emptyServerTransportInterceptor != nil { + res.resp, res.err, intercepted = emptyServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "EmptyClient.GetEmpty": + res.resp, res.err = e.dispatchGetEmpty(req) + case "EmptyClient.PostRoundTripEmpty": + res.resp, res.err = e.dispatchPostRoundTripEmpty(req) + case "EmptyClient.PutEmpty": + res.resp, res.err = e.dispatchPutEmpty(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (e *EmptyServerTransport) dispatchGetEmpty(req *http.Request) (*http.Response, error) { + if e.srv.GetEmpty == nil { + return nil, &nonRetriableError{errors.New("fake for method GetEmpty not implemented")} + } + respr, errRespr := e.srv.GetEmpty(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).EmptyOutput, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *EmptyServerTransport) dispatchPostRoundTripEmpty(req *http.Request) (*http.Response, error) { + if e.srv.PostRoundTripEmpty == nil { + return nil, &nonRetriableError{errors.New("fake for method PostRoundTripEmpty not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[emptygroup.EmptyInputOutput](req) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.PostRoundTripEmpty(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).EmptyInputOutput, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *EmptyServerTransport) dispatchPutEmpty(req *http.Request) (*http.Response, error) { + if e.srv.PutEmpty == nil { + return nil, &nonRetriableError{errors.New("fake for method PutEmpty not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[emptygroup.EmptyInput](req) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.PutEmpty(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to EmptyServerTransport +var emptyServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/model/emptygroup/fake/zz_internal.go b/test/http-specs/type/model/emptygroup/fake/zz_internal.go new file mode 100644 index 000000000000..705f81eacafe --- /dev/null +++ b/test/http-specs/type/model/emptygroup/fake/zz_internal.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import "net/http" + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} diff --git a/test/http-specs/type/model/emptygroup/go.mod b/test/http-specs/type/model/emptygroup/go.mod new file mode 100644 index 000000000000..4154992c30e8 --- /dev/null +++ b/test/http-specs/type/model/emptygroup/go.mod @@ -0,0 +1,17 @@ +module emptygroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/type/model/emptygroup/go.sum b/test/http-specs/type/model/emptygroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/type/model/emptygroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/type/model/emptygroup/testdata/_metadata.json b/test/http-specs/type/model/emptygroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/type/model/emptygroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/type/model/emptygroup/zz_empty_client.go b/test/http-specs/type/model/emptygroup/zz_empty_client.go new file mode 100644 index 000000000000..1678e7f968bb --- /dev/null +++ b/test/http-specs/type/model/emptygroup/zz_empty_client.go @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package emptygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// EmptyClient - Illustrates usage of empty model used in operation's parameters and responses. +// Don't use this type directly, use NewEmptyClientWithNoCredential() instead. +type EmptyClient struct { + internal *azcore.Client + endpoint string +} + +// EmptyClientOptions contains the optional values for creating a [EmptyClient]. +type EmptyClientOptions struct { + azcore.ClientOptions +} + +// NewEmptyClientWithNoCredential creates a new instance of EmptyClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewEmptyClientWithNoCredential(endpoint string, options *EmptyClientOptions) (*EmptyClient, error) { + if options == nil { + options = &EmptyClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &EmptyClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// GetEmpty - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - GetEmptyOptions contains the optional parameters for the EmptyClient.GetEmpty method. +func (client *EmptyClient) GetEmpty(ctx context.Context, options *GetEmptyOptions) (GetEmptyResponse, error) { + var err error + const operationName = "EmptyClient.GetEmpty" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getEmptyCreateRequest(ctx, options) + if err != nil { + return GetEmptyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GetEmptyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GetEmptyResponse{}, err + } + resp, err := client.getEmptyHandleResponse(httpResp) + return resp, err +} + +// getEmptyCreateRequest creates the GetEmpty request. +func (client *EmptyClient) getEmptyCreateRequest(ctx context.Context, _ *GetEmptyOptions) (*policy.Request, error) { + urlPath := "/type/model/empty/alone" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getEmptyHandleResponse handles the GetEmpty response. +func (client *EmptyClient) getEmptyHandleResponse(resp *http.Response) (GetEmptyResponse, error) { + result := GetEmptyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.EmptyOutput); err != nil { + return GetEmptyResponse{}, err + } + return result, nil +} + +// PostRoundTripEmpty - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - PostRoundTripEmptyOptions contains the optional parameters for the EmptyClient.PostRoundTripEmpty method. +func (client *EmptyClient) PostRoundTripEmpty(ctx context.Context, body EmptyInputOutput, options *PostRoundTripEmptyOptions) (PostRoundTripEmptyResponse, error) { + var err error + const operationName = "EmptyClient.PostRoundTripEmpty" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.postRoundTripEmptyCreateRequest(ctx, body, options) + if err != nil { + return PostRoundTripEmptyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PostRoundTripEmptyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PostRoundTripEmptyResponse{}, err + } + resp, err := client.postRoundTripEmptyHandleResponse(httpResp) + return resp, err +} + +// postRoundTripEmptyCreateRequest creates the PostRoundTripEmpty request. +func (client *EmptyClient) postRoundTripEmptyCreateRequest(ctx context.Context, body EmptyInputOutput, _ *PostRoundTripEmptyOptions) (*policy.Request, error) { + urlPath := "/type/model/empty/round-trip" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// postRoundTripEmptyHandleResponse handles the PostRoundTripEmpty response. +func (client *EmptyClient) postRoundTripEmptyHandleResponse(resp *http.Response) (PostRoundTripEmptyResponse, error) { + result := PostRoundTripEmptyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.EmptyInputOutput); err != nil { + return PostRoundTripEmptyResponse{}, err + } + return result, nil +} + +// PutEmpty - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - PutEmptyOptions contains the optional parameters for the EmptyClient.PutEmpty method. +func (client *EmptyClient) PutEmpty(ctx context.Context, input EmptyInput, options *PutEmptyOptions) (PutEmptyResponse, error) { + var err error + const operationName = "EmptyClient.PutEmpty" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putEmptyCreateRequest(ctx, input, options) + if err != nil { + return PutEmptyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PutEmptyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return PutEmptyResponse{}, err + } + return PutEmptyResponse{}, nil +} + +// putEmptyCreateRequest creates the PutEmpty request. +func (client *EmptyClient) putEmptyCreateRequest(ctx context.Context, input EmptyInput, _ *PutEmptyOptions) (*policy.Request, error) { + urlPath := "/type/model/empty/alone" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/model/emptygroup/zz_models.go b/test/http-specs/type/model/emptygroup/zz_models.go new file mode 100644 index 000000000000..e84deda09d6d --- /dev/null +++ b/test/http-specs/type/model/emptygroup/zz_models.go @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package emptygroup + +// EmptyInput - Empty model used in operation parameters +type EmptyInput struct { +} + +// EmptyInputOutput - Empty model used in both parameter and return type +type EmptyInputOutput struct { +} + +// EmptyOutput - Empty model used in operation return type +type EmptyOutput struct { +} diff --git a/test/http-specs/type/model/emptygroup/zz_options.go b/test/http-specs/type/model/emptygroup/zz_options.go new file mode 100644 index 000000000000..7920890d78aa --- /dev/null +++ b/test/http-specs/type/model/emptygroup/zz_options.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package emptygroup + +// GetEmptyOptions contains the optional parameters for the EmptyClient.GetEmpty method. +type GetEmptyOptions struct { + // placeholder for future optional parameters +} + +// PostRoundTripEmptyOptions contains the optional parameters for the EmptyClient.PostRoundTripEmpty method. +type PostRoundTripEmptyOptions struct { + // placeholder for future optional parameters +} + +// PutEmptyOptions contains the optional parameters for the EmptyClient.PutEmpty method. +type PutEmptyOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/type/model/emptygroup/zz_responses.go b/test/http-specs/type/model/emptygroup/zz_responses.go new file mode 100644 index 000000000000..1aa60986a90a --- /dev/null +++ b/test/http-specs/type/model/emptygroup/zz_responses.go @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package emptygroup + +// GetEmptyResponse contains the response from method EmptyClient.GetEmpty. +type GetEmptyResponse struct { + // Empty model used in operation return type + EmptyOutput +} + +// PostRoundTripEmptyResponse contains the response from method EmptyClient.PostRoundTripEmpty. +type PostRoundTripEmptyResponse struct { + // Empty model used in both parameter and return type + EmptyInputOutput +} + +// PutEmptyResponse contains the response from method EmptyClient.PutEmpty. +type PutEmptyResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/type/model/emptygroup/zz_version.go b/test/http-specs/type/model/emptygroup/zz_version.go new file mode 100644 index 000000000000..1a0fb37226da --- /dev/null +++ b/test/http-specs/type/model/emptygroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package emptygroup + +const ( + moduleName = "emptygroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/type/model/inheritance/enumdiscgroup/LICENSE.txt b/test/http-specs/type/model/inheritance/enumdiscgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/type/model/inheritance/enumdiscgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/type/model/inheritance/enumdiscgroup/enumdiscriminator_client_test.go b/test/http-specs/type/model/inheritance/enumdiscgroup/enumdiscriminator_client_test.go new file mode 100644 index 000000000000..15935f81dfad --- /dev/null +++ b/test/http-specs/type/model/inheritance/enumdiscgroup/enumdiscriminator_client_test.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package enumdiscgroup_test + +import ( + "context" + "enumdiscgroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestEnumDiscriminatorClientGetExtensibleModel(t *testing.T) { + client, err := enumdiscgroup.NewEnumDiscriminatorClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.GetExtensibleModel(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.DogClassification) + require.Equal(t, &enumdiscgroup.Golden{ + Kind: to.Ptr(enumdiscgroup.DogKindGolden), + Weight: to.Ptr[int32](10), + }, resp.DogClassification) +} + +func TestEnumDiscriminatorClientGetExtensibleModelMissingDiscriminator(t *testing.T) { + client, err := enumdiscgroup.NewEnumDiscriminatorClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.GetExtensibleModelMissingDiscriminator(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.DogClassification) + require.Equal(t, &enumdiscgroup.Dog{ + Weight: to.Ptr[int32](10), + }, resp.DogClassification) +} + +func TestEnumDiscriminatorClientGetExtensibleModelWrongDiscriminator(t *testing.T) { + client, err := enumdiscgroup.NewEnumDiscriminatorClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.GetExtensibleModelWrongDiscriminator(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.DogClassification) + require.Equal(t, &enumdiscgroup.Dog{ + Kind: to.Ptr(enumdiscgroup.DogKind("wrongKind")), + Weight: to.Ptr[int32](8), + }, resp.DogClassification) +} + +func TestEnumDiscriminatorClientGetFixedModel(t *testing.T) { + client, err := enumdiscgroup.NewEnumDiscriminatorClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.GetFixedModel(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.SnakeClassification) + require.Equal(t, &enumdiscgroup.Cobra{ + Kind: to.Ptr(enumdiscgroup.SnakeKindCobra), + Length: to.Ptr[int32](10), + }, resp.SnakeClassification) +} + +func TestEnumDiscriminatorClientGetFixedModelMissingDiscriminator(t *testing.T) { + client, err := enumdiscgroup.NewEnumDiscriminatorClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.GetFixedModelMissingDiscriminator(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.SnakeClassification) + require.Equal(t, &enumdiscgroup.Snake{ + Length: to.Ptr[int32](10), + }, resp.SnakeClassification) +} + +func TestEnumDiscriminatorClientGetFixedModelWrongDiscriminator(t *testing.T) { + client, err := enumdiscgroup.NewEnumDiscriminatorClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.GetFixedModelWrongDiscriminator(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.SnakeClassification) + require.Equal(t, &enumdiscgroup.Snake{ + Kind: to.Ptr(enumdiscgroup.SnakeKind("wrongKind")), + Length: to.Ptr[int32](8), + }, resp.SnakeClassification) +} + +func TestEnumDiscriminatorClientPutExtensibleModel(t *testing.T) { + client, err := enumdiscgroup.NewEnumDiscriminatorClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.PutExtensibleModel(context.Background(), &enumdiscgroup.Golden{ + Kind: to.Ptr(enumdiscgroup.DogKindGolden), + Weight: to.Ptr[int32](10), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestEnumDiscriminatorClientPutFixedModel(t *testing.T) { + client, err := enumdiscgroup.NewEnumDiscriminatorClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.PutFixedModel(context.Background(), &enumdiscgroup.Cobra{ + Kind: to.Ptr(enumdiscgroup.SnakeKindCobra), + Length: to.Ptr[int32](10), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/model/inheritance/enumdiscgroup/fake/zz_enumdiscriminator_server.go b/test/http-specs/type/model/inheritance/enumdiscgroup/fake/zz_enumdiscriminator_server.go new file mode 100644 index 000000000000..bac791055f70 --- /dev/null +++ b/test/http-specs/type/model/inheritance/enumdiscgroup/fake/zz_enumdiscriminator_server.go @@ -0,0 +1,292 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "enumdiscgroup" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// EnumDiscriminatorServer is a fake server for instances of the enumdiscgroup.EnumDiscriminatorClient type. +type EnumDiscriminatorServer struct { + // GetExtensibleModel is the fake for method EnumDiscriminatorClient.GetExtensibleModel + // HTTP status codes to indicate success: http.StatusOK + GetExtensibleModel func(ctx context.Context, options *enumdiscgroup.EnumDiscriminatorClientGetExtensibleModelOptions) (resp azfake.Responder[enumdiscgroup.EnumDiscriminatorClientGetExtensibleModelResponse], errResp azfake.ErrorResponder) + + // GetExtensibleModelMissingDiscriminator is the fake for method EnumDiscriminatorClient.GetExtensibleModelMissingDiscriminator + // HTTP status codes to indicate success: http.StatusOK + GetExtensibleModelMissingDiscriminator func(ctx context.Context, options *enumdiscgroup.EnumDiscriminatorClientGetExtensibleModelMissingDiscriminatorOptions) (resp azfake.Responder[enumdiscgroup.EnumDiscriminatorClientGetExtensibleModelMissingDiscriminatorResponse], errResp azfake.ErrorResponder) + + // GetExtensibleModelWrongDiscriminator is the fake for method EnumDiscriminatorClient.GetExtensibleModelWrongDiscriminator + // HTTP status codes to indicate success: http.StatusOK + GetExtensibleModelWrongDiscriminator func(ctx context.Context, options *enumdiscgroup.EnumDiscriminatorClientGetExtensibleModelWrongDiscriminatorOptions) (resp azfake.Responder[enumdiscgroup.EnumDiscriminatorClientGetExtensibleModelWrongDiscriminatorResponse], errResp azfake.ErrorResponder) + + // GetFixedModel is the fake for method EnumDiscriminatorClient.GetFixedModel + // HTTP status codes to indicate success: http.StatusOK + GetFixedModel func(ctx context.Context, options *enumdiscgroup.EnumDiscriminatorClientGetFixedModelOptions) (resp azfake.Responder[enumdiscgroup.EnumDiscriminatorClientGetFixedModelResponse], errResp azfake.ErrorResponder) + + // GetFixedModelMissingDiscriminator is the fake for method EnumDiscriminatorClient.GetFixedModelMissingDiscriminator + // HTTP status codes to indicate success: http.StatusOK + GetFixedModelMissingDiscriminator func(ctx context.Context, options *enumdiscgroup.EnumDiscriminatorClientGetFixedModelMissingDiscriminatorOptions) (resp azfake.Responder[enumdiscgroup.EnumDiscriminatorClientGetFixedModelMissingDiscriminatorResponse], errResp azfake.ErrorResponder) + + // GetFixedModelWrongDiscriminator is the fake for method EnumDiscriminatorClient.GetFixedModelWrongDiscriminator + // HTTP status codes to indicate success: http.StatusOK + GetFixedModelWrongDiscriminator func(ctx context.Context, options *enumdiscgroup.EnumDiscriminatorClientGetFixedModelWrongDiscriminatorOptions) (resp azfake.Responder[enumdiscgroup.EnumDiscriminatorClientGetFixedModelWrongDiscriminatorResponse], errResp azfake.ErrorResponder) + + // PutExtensibleModel is the fake for method EnumDiscriminatorClient.PutExtensibleModel + // HTTP status codes to indicate success: http.StatusNoContent + PutExtensibleModel func(ctx context.Context, input enumdiscgroup.DogClassification, options *enumdiscgroup.EnumDiscriminatorClientPutExtensibleModelOptions) (resp azfake.Responder[enumdiscgroup.EnumDiscriminatorClientPutExtensibleModelResponse], errResp azfake.ErrorResponder) + + // PutFixedModel is the fake for method EnumDiscriminatorClient.PutFixedModel + // HTTP status codes to indicate success: http.StatusNoContent + PutFixedModel func(ctx context.Context, input enumdiscgroup.SnakeClassification, options *enumdiscgroup.EnumDiscriminatorClientPutFixedModelOptions) (resp azfake.Responder[enumdiscgroup.EnumDiscriminatorClientPutFixedModelResponse], errResp azfake.ErrorResponder) +} + +// NewEnumDiscriminatorServerTransport creates a new instance of EnumDiscriminatorServerTransport with the provided implementation. +// The returned EnumDiscriminatorServerTransport instance is connected to an instance of enumdiscgroup.EnumDiscriminatorClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewEnumDiscriminatorServerTransport(srv *EnumDiscriminatorServer) *EnumDiscriminatorServerTransport { + return &EnumDiscriminatorServerTransport{srv: srv} +} + +// EnumDiscriminatorServerTransport connects instances of enumdiscgroup.EnumDiscriminatorClient to instances of EnumDiscriminatorServer. +// Don't use this type directly, use NewEnumDiscriminatorServerTransport instead. +type EnumDiscriminatorServerTransport struct { + srv *EnumDiscriminatorServer +} + +// Do implements the policy.Transporter interface for EnumDiscriminatorServerTransport. +func (e *EnumDiscriminatorServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return e.dispatchToMethodFake(req, method) +} + +func (e *EnumDiscriminatorServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if enumDiscriminatorServerTransportInterceptor != nil { + res.resp, res.err, intercepted = enumDiscriminatorServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "EnumDiscriminatorClient.GetExtensibleModel": + res.resp, res.err = e.dispatchGetExtensibleModel(req) + case "EnumDiscriminatorClient.GetExtensibleModelMissingDiscriminator": + res.resp, res.err = e.dispatchGetExtensibleModelMissingDiscriminator(req) + case "EnumDiscriminatorClient.GetExtensibleModelWrongDiscriminator": + res.resp, res.err = e.dispatchGetExtensibleModelWrongDiscriminator(req) + case "EnumDiscriminatorClient.GetFixedModel": + res.resp, res.err = e.dispatchGetFixedModel(req) + case "EnumDiscriminatorClient.GetFixedModelMissingDiscriminator": + res.resp, res.err = e.dispatchGetFixedModelMissingDiscriminator(req) + case "EnumDiscriminatorClient.GetFixedModelWrongDiscriminator": + res.resp, res.err = e.dispatchGetFixedModelWrongDiscriminator(req) + case "EnumDiscriminatorClient.PutExtensibleModel": + res.resp, res.err = e.dispatchPutExtensibleModel(req) + case "EnumDiscriminatorClient.PutFixedModel": + res.resp, res.err = e.dispatchPutFixedModel(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (e *EnumDiscriminatorServerTransport) dispatchGetExtensibleModel(req *http.Request) (*http.Response, error) { + if e.srv.GetExtensibleModel == nil { + return nil, &nonRetriableError{errors.New("fake for method GetExtensibleModel not implemented")} + } + respr, errRespr := e.srv.GetExtensibleModel(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DogClassification, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *EnumDiscriminatorServerTransport) dispatchGetExtensibleModelMissingDiscriminator(req *http.Request) (*http.Response, error) { + if e.srv.GetExtensibleModelMissingDiscriminator == nil { + return nil, &nonRetriableError{errors.New("fake for method GetExtensibleModelMissingDiscriminator not implemented")} + } + respr, errRespr := e.srv.GetExtensibleModelMissingDiscriminator(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DogClassification, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *EnumDiscriminatorServerTransport) dispatchGetExtensibleModelWrongDiscriminator(req *http.Request) (*http.Response, error) { + if e.srv.GetExtensibleModelWrongDiscriminator == nil { + return nil, &nonRetriableError{errors.New("fake for method GetExtensibleModelWrongDiscriminator not implemented")} + } + respr, errRespr := e.srv.GetExtensibleModelWrongDiscriminator(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DogClassification, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *EnumDiscriminatorServerTransport) dispatchGetFixedModel(req *http.Request) (*http.Response, error) { + if e.srv.GetFixedModel == nil { + return nil, &nonRetriableError{errors.New("fake for method GetFixedModel not implemented")} + } + respr, errRespr := e.srv.GetFixedModel(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).SnakeClassification, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *EnumDiscriminatorServerTransport) dispatchGetFixedModelMissingDiscriminator(req *http.Request) (*http.Response, error) { + if e.srv.GetFixedModelMissingDiscriminator == nil { + return nil, &nonRetriableError{errors.New("fake for method GetFixedModelMissingDiscriminator not implemented")} + } + respr, errRespr := e.srv.GetFixedModelMissingDiscriminator(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).SnakeClassification, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *EnumDiscriminatorServerTransport) dispatchGetFixedModelWrongDiscriminator(req *http.Request) (*http.Response, error) { + if e.srv.GetFixedModelWrongDiscriminator == nil { + return nil, &nonRetriableError{errors.New("fake for method GetFixedModelWrongDiscriminator not implemented")} + } + respr, errRespr := e.srv.GetFixedModelWrongDiscriminator(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).SnakeClassification, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *EnumDiscriminatorServerTransport) dispatchPutExtensibleModel(req *http.Request) (*http.Response, error) { + if e.srv.PutExtensibleModel == nil { + return nil, &nonRetriableError{errors.New("fake for method PutExtensibleModel not implemented")} + } + raw, err := readRequestBody(req) + if err != nil { + return nil, err + } + body, err := unmarshalDogClassification(raw) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.PutExtensibleModel(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *EnumDiscriminatorServerTransport) dispatchPutFixedModel(req *http.Request) (*http.Response, error) { + if e.srv.PutFixedModel == nil { + return nil, &nonRetriableError{errors.New("fake for method PutFixedModel not implemented")} + } + raw, err := readRequestBody(req) + if err != nil { + return nil, err + } + body, err := unmarshalSnakeClassification(raw) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.PutFixedModel(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to EnumDiscriminatorServerTransport +var enumDiscriminatorServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/model/inheritance/enumdiscgroup/fake/zz_internal.go b/test/http-specs/type/model/inheritance/enumdiscgroup/fake/zz_internal.go new file mode 100644 index 000000000000..ee1bb08ff0bf --- /dev/null +++ b/test/http-specs/type/model/inheritance/enumdiscgroup/fake/zz_internal.go @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "io" + "net/http" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func readRequestBody(req *http.Request) ([]byte, error) { + if req.Body == nil { + return nil, nil + } + body, err := io.ReadAll(req.Body) + if err != nil { + return nil, err + } + req.Body.Close() + return body, nil +} diff --git a/test/http-specs/type/model/inheritance/enumdiscgroup/fake/zz_polymorphic_helpers.go b/test/http-specs/type/model/inheritance/enumdiscgroup/fake/zz_polymorphic_helpers.go new file mode 100644 index 000000000000..b923e8468af6 --- /dev/null +++ b/test/http-specs/type/model/inheritance/enumdiscgroup/fake/zz_polymorphic_helpers.go @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "encoding/json" + "enumdiscgroup" +) + +func unmarshalDogClassification(rawMsg json.RawMessage) (enumdiscgroup.DogClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b enumdiscgroup.DogClassification + switch m["kind"] { + case string(enumdiscgroup.DogKindGolden): + b = &enumdiscgroup.Golden{} + default: + b = &enumdiscgroup.Dog{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} + +func unmarshalSnakeClassification(rawMsg json.RawMessage) (enumdiscgroup.SnakeClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b enumdiscgroup.SnakeClassification + switch m["kind"] { + case string(enumdiscgroup.SnakeKindCobra): + b = &enumdiscgroup.Cobra{} + default: + b = &enumdiscgroup.Snake{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} diff --git a/test/http-specs/type/model/inheritance/enumdiscgroup/go.mod b/test/http-specs/type/model/inheritance/enumdiscgroup/go.mod new file mode 100644 index 000000000000..34fc740c3ebb --- /dev/null +++ b/test/http-specs/type/model/inheritance/enumdiscgroup/go.mod @@ -0,0 +1,17 @@ +module enumdiscgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/type/model/inheritance/enumdiscgroup/go.sum b/test/http-specs/type/model/inheritance/enumdiscgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/type/model/inheritance/enumdiscgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/type/model/inheritance/enumdiscgroup/testdata/_metadata.json b/test/http-specs/type/model/inheritance/enumdiscgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/type/model/inheritance/enumdiscgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/type/model/inheritance/enumdiscgroup/zz_constants.go b/test/http-specs/type/model/inheritance/enumdiscgroup/zz_constants.go new file mode 100644 index 000000000000..6702c3865b1b --- /dev/null +++ b/test/http-specs/type/model/inheritance/enumdiscgroup/zz_constants.go @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package enumdiscgroup + +// DogKind - extensible enum type for discriminator +type DogKind string + +const ( + // DogKindGolden - Species golden + DogKindGolden DogKind = "golden" +) + +// PossibleDogKindValues returns the possible values for the DogKind const type. +func PossibleDogKindValues() []DogKind { + return []DogKind{ + DogKindGolden, + } +} + +// SnakeKind - fixed enum type for discriminator +type SnakeKind string + +const ( + // SnakeKindCobra - Species cobra + SnakeKindCobra SnakeKind = "cobra" +) + +// PossibleSnakeKindValues returns the possible values for the SnakeKind const type. +func PossibleSnakeKindValues() []SnakeKind { + return []SnakeKind{ + SnakeKindCobra, + } +} diff --git a/test/http-specs/type/model/inheritance/enumdiscgroup/zz_enumdiscriminator_client.go b/test/http-specs/type/model/inheritance/enumdiscgroup/zz_enumdiscriminator_client.go new file mode 100644 index 000000000000..d6962a698485 --- /dev/null +++ b/test/http-specs/type/model/inheritance/enumdiscgroup/zz_enumdiscriminator_client.go @@ -0,0 +1,399 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package enumdiscgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// EnumDiscriminatorClient - Illustrates inheritance with enum discriminator. +// Don't use this type directly, use NewEnumDiscriminatorClientWithNoCredential() instead. +type EnumDiscriminatorClient struct { + internal *azcore.Client + endpoint string +} + +// EnumDiscriminatorClientOptions contains the optional values for creating a [EnumDiscriminatorClient]. +type EnumDiscriminatorClientOptions struct { + azcore.ClientOptions +} + +// NewEnumDiscriminatorClientWithNoCredential creates a new instance of EnumDiscriminatorClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewEnumDiscriminatorClientWithNoCredential(endpoint string, options *EnumDiscriminatorClientOptions) (*EnumDiscriminatorClient, error) { + if options == nil { + options = &EnumDiscriminatorClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &EnumDiscriminatorClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// GetExtensibleModel - Receive model with extensible enum discriminator type. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - EnumDiscriminatorClientGetExtensibleModelOptions contains the optional parameters for the EnumDiscriminatorClient.GetExtensibleModel +// method. +func (client *EnumDiscriminatorClient) GetExtensibleModel(ctx context.Context, options *EnumDiscriminatorClientGetExtensibleModelOptions) (EnumDiscriminatorClientGetExtensibleModelResponse, error) { + var err error + const operationName = "EnumDiscriminatorClient.GetExtensibleModel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getExtensibleModelCreateRequest(ctx, options) + if err != nil { + return EnumDiscriminatorClientGetExtensibleModelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EnumDiscriminatorClientGetExtensibleModelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return EnumDiscriminatorClientGetExtensibleModelResponse{}, err + } + resp, err := client.getExtensibleModelHandleResponse(httpResp) + return resp, err +} + +// getExtensibleModelCreateRequest creates the GetExtensibleModel request. +func (client *EnumDiscriminatorClient) getExtensibleModelCreateRequest(ctx context.Context, _ *EnumDiscriminatorClientGetExtensibleModelOptions) (*policy.Request, error) { + urlPath := "/type/model/inheritance/enum-discriminator/extensible-enum" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getExtensibleModelHandleResponse handles the GetExtensibleModel response. +func (client *EnumDiscriminatorClient) getExtensibleModelHandleResponse(resp *http.Response) (EnumDiscriminatorClientGetExtensibleModelResponse, error) { + result := EnumDiscriminatorClientGetExtensibleModelResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result); err != nil { + return EnumDiscriminatorClientGetExtensibleModelResponse{}, err + } + return result, nil +} + +// GetExtensibleModelMissingDiscriminator - Get a model omitting the discriminator. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - EnumDiscriminatorClientGetExtensibleModelMissingDiscriminatorOptions contains the optional parameters for the +// EnumDiscriminatorClient.GetExtensibleModelMissingDiscriminator method. +func (client *EnumDiscriminatorClient) GetExtensibleModelMissingDiscriminator(ctx context.Context, options *EnumDiscriminatorClientGetExtensibleModelMissingDiscriminatorOptions) (EnumDiscriminatorClientGetExtensibleModelMissingDiscriminatorResponse, error) { + var err error + const operationName = "EnumDiscriminatorClient.GetExtensibleModelMissingDiscriminator" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getExtensibleModelMissingDiscriminatorCreateRequest(ctx, options) + if err != nil { + return EnumDiscriminatorClientGetExtensibleModelMissingDiscriminatorResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EnumDiscriminatorClientGetExtensibleModelMissingDiscriminatorResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return EnumDiscriminatorClientGetExtensibleModelMissingDiscriminatorResponse{}, err + } + resp, err := client.getExtensibleModelMissingDiscriminatorHandleResponse(httpResp) + return resp, err +} + +// getExtensibleModelMissingDiscriminatorCreateRequest creates the GetExtensibleModelMissingDiscriminator request. +func (client *EnumDiscriminatorClient) getExtensibleModelMissingDiscriminatorCreateRequest(ctx context.Context, _ *EnumDiscriminatorClientGetExtensibleModelMissingDiscriminatorOptions) (*policy.Request, error) { + urlPath := "/type/model/inheritance/enum-discriminator/extensible-enum/missingdiscriminator" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getExtensibleModelMissingDiscriminatorHandleResponse handles the GetExtensibleModelMissingDiscriminator response. +func (client *EnumDiscriminatorClient) getExtensibleModelMissingDiscriminatorHandleResponse(resp *http.Response) (EnumDiscriminatorClientGetExtensibleModelMissingDiscriminatorResponse, error) { + result := EnumDiscriminatorClientGetExtensibleModelMissingDiscriminatorResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result); err != nil { + return EnumDiscriminatorClientGetExtensibleModelMissingDiscriminatorResponse{}, err + } + return result, nil +} + +// GetExtensibleModelWrongDiscriminator - Get a model containing discriminator value never defined. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - EnumDiscriminatorClientGetExtensibleModelWrongDiscriminatorOptions contains the optional parameters for the EnumDiscriminatorClient.GetExtensibleModelWrongDiscriminator +// method. +func (client *EnumDiscriminatorClient) GetExtensibleModelWrongDiscriminator(ctx context.Context, options *EnumDiscriminatorClientGetExtensibleModelWrongDiscriminatorOptions) (EnumDiscriminatorClientGetExtensibleModelWrongDiscriminatorResponse, error) { + var err error + const operationName = "EnumDiscriminatorClient.GetExtensibleModelWrongDiscriminator" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getExtensibleModelWrongDiscriminatorCreateRequest(ctx, options) + if err != nil { + return EnumDiscriminatorClientGetExtensibleModelWrongDiscriminatorResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EnumDiscriminatorClientGetExtensibleModelWrongDiscriminatorResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return EnumDiscriminatorClientGetExtensibleModelWrongDiscriminatorResponse{}, err + } + resp, err := client.getExtensibleModelWrongDiscriminatorHandleResponse(httpResp) + return resp, err +} + +// getExtensibleModelWrongDiscriminatorCreateRequest creates the GetExtensibleModelWrongDiscriminator request. +func (client *EnumDiscriminatorClient) getExtensibleModelWrongDiscriminatorCreateRequest(ctx context.Context, _ *EnumDiscriminatorClientGetExtensibleModelWrongDiscriminatorOptions) (*policy.Request, error) { + urlPath := "/type/model/inheritance/enum-discriminator/extensible-enum/wrongdiscriminator" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getExtensibleModelWrongDiscriminatorHandleResponse handles the GetExtensibleModelWrongDiscriminator response. +func (client *EnumDiscriminatorClient) getExtensibleModelWrongDiscriminatorHandleResponse(resp *http.Response) (EnumDiscriminatorClientGetExtensibleModelWrongDiscriminatorResponse, error) { + result := EnumDiscriminatorClientGetExtensibleModelWrongDiscriminatorResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result); err != nil { + return EnumDiscriminatorClientGetExtensibleModelWrongDiscriminatorResponse{}, err + } + return result, nil +} + +// GetFixedModel - Receive model with fixed enum discriminator type. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - EnumDiscriminatorClientGetFixedModelOptions contains the optional parameters for the EnumDiscriminatorClient.GetFixedModel +// method. +func (client *EnumDiscriminatorClient) GetFixedModel(ctx context.Context, options *EnumDiscriminatorClientGetFixedModelOptions) (EnumDiscriminatorClientGetFixedModelResponse, error) { + var err error + const operationName = "EnumDiscriminatorClient.GetFixedModel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getFixedModelCreateRequest(ctx, options) + if err != nil { + return EnumDiscriminatorClientGetFixedModelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EnumDiscriminatorClientGetFixedModelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return EnumDiscriminatorClientGetFixedModelResponse{}, err + } + resp, err := client.getFixedModelHandleResponse(httpResp) + return resp, err +} + +// getFixedModelCreateRequest creates the GetFixedModel request. +func (client *EnumDiscriminatorClient) getFixedModelCreateRequest(ctx context.Context, _ *EnumDiscriminatorClientGetFixedModelOptions) (*policy.Request, error) { + urlPath := "/type/model/inheritance/enum-discriminator/fixed-enum" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getFixedModelHandleResponse handles the GetFixedModel response. +func (client *EnumDiscriminatorClient) getFixedModelHandleResponse(resp *http.Response) (EnumDiscriminatorClientGetFixedModelResponse, error) { + result := EnumDiscriminatorClientGetFixedModelResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result); err != nil { + return EnumDiscriminatorClientGetFixedModelResponse{}, err + } + return result, nil +} + +// GetFixedModelMissingDiscriminator - Get a model omitting the discriminator. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - EnumDiscriminatorClientGetFixedModelMissingDiscriminatorOptions contains the optional parameters for the EnumDiscriminatorClient.GetFixedModelMissingDiscriminator +// method. +func (client *EnumDiscriminatorClient) GetFixedModelMissingDiscriminator(ctx context.Context, options *EnumDiscriminatorClientGetFixedModelMissingDiscriminatorOptions) (EnumDiscriminatorClientGetFixedModelMissingDiscriminatorResponse, error) { + var err error + const operationName = "EnumDiscriminatorClient.GetFixedModelMissingDiscriminator" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getFixedModelMissingDiscriminatorCreateRequest(ctx, options) + if err != nil { + return EnumDiscriminatorClientGetFixedModelMissingDiscriminatorResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EnumDiscriminatorClientGetFixedModelMissingDiscriminatorResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return EnumDiscriminatorClientGetFixedModelMissingDiscriminatorResponse{}, err + } + resp, err := client.getFixedModelMissingDiscriminatorHandleResponse(httpResp) + return resp, err +} + +// getFixedModelMissingDiscriminatorCreateRequest creates the GetFixedModelMissingDiscriminator request. +func (client *EnumDiscriminatorClient) getFixedModelMissingDiscriminatorCreateRequest(ctx context.Context, _ *EnumDiscriminatorClientGetFixedModelMissingDiscriminatorOptions) (*policy.Request, error) { + urlPath := "/type/model/inheritance/enum-discriminator/fixed-enum/missingdiscriminator" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getFixedModelMissingDiscriminatorHandleResponse handles the GetFixedModelMissingDiscriminator response. +func (client *EnumDiscriminatorClient) getFixedModelMissingDiscriminatorHandleResponse(resp *http.Response) (EnumDiscriminatorClientGetFixedModelMissingDiscriminatorResponse, error) { + result := EnumDiscriminatorClientGetFixedModelMissingDiscriminatorResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result); err != nil { + return EnumDiscriminatorClientGetFixedModelMissingDiscriminatorResponse{}, err + } + return result, nil +} + +// GetFixedModelWrongDiscriminator - Get a model containing discriminator value never defined. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - EnumDiscriminatorClientGetFixedModelWrongDiscriminatorOptions contains the optional parameters for the EnumDiscriminatorClient.GetFixedModelWrongDiscriminator +// method. +func (client *EnumDiscriminatorClient) GetFixedModelWrongDiscriminator(ctx context.Context, options *EnumDiscriminatorClientGetFixedModelWrongDiscriminatorOptions) (EnumDiscriminatorClientGetFixedModelWrongDiscriminatorResponse, error) { + var err error + const operationName = "EnumDiscriminatorClient.GetFixedModelWrongDiscriminator" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getFixedModelWrongDiscriminatorCreateRequest(ctx, options) + if err != nil { + return EnumDiscriminatorClientGetFixedModelWrongDiscriminatorResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EnumDiscriminatorClientGetFixedModelWrongDiscriminatorResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return EnumDiscriminatorClientGetFixedModelWrongDiscriminatorResponse{}, err + } + resp, err := client.getFixedModelWrongDiscriminatorHandleResponse(httpResp) + return resp, err +} + +// getFixedModelWrongDiscriminatorCreateRequest creates the GetFixedModelWrongDiscriminator request. +func (client *EnumDiscriminatorClient) getFixedModelWrongDiscriminatorCreateRequest(ctx context.Context, _ *EnumDiscriminatorClientGetFixedModelWrongDiscriminatorOptions) (*policy.Request, error) { + urlPath := "/type/model/inheritance/enum-discriminator/fixed-enum/wrongdiscriminator" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getFixedModelWrongDiscriminatorHandleResponse handles the GetFixedModelWrongDiscriminator response. +func (client *EnumDiscriminatorClient) getFixedModelWrongDiscriminatorHandleResponse(resp *http.Response) (EnumDiscriminatorClientGetFixedModelWrongDiscriminatorResponse, error) { + result := EnumDiscriminatorClientGetFixedModelWrongDiscriminatorResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result); err != nil { + return EnumDiscriminatorClientGetFixedModelWrongDiscriminatorResponse{}, err + } + return result, nil +} + +// PutExtensibleModel - Send model with extensible enum discriminator type. +// If the operation fails it returns an *azcore.ResponseError type. +// - input - Dog to create +// - options - EnumDiscriminatorClientPutExtensibleModelOptions contains the optional parameters for the EnumDiscriminatorClient.PutExtensibleModel +// method. +func (client *EnumDiscriminatorClient) PutExtensibleModel(ctx context.Context, input DogClassification, options *EnumDiscriminatorClientPutExtensibleModelOptions) (EnumDiscriminatorClientPutExtensibleModelResponse, error) { + var err error + const operationName = "EnumDiscriminatorClient.PutExtensibleModel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putExtensibleModelCreateRequest(ctx, input, options) + if err != nil { + return EnumDiscriminatorClientPutExtensibleModelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EnumDiscriminatorClientPutExtensibleModelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return EnumDiscriminatorClientPutExtensibleModelResponse{}, err + } + return EnumDiscriminatorClientPutExtensibleModelResponse{}, nil +} + +// putExtensibleModelCreateRequest creates the PutExtensibleModel request. +func (client *EnumDiscriminatorClient) putExtensibleModelCreateRequest(ctx context.Context, input DogClassification, _ *EnumDiscriminatorClientPutExtensibleModelOptions) (*policy.Request, error) { + urlPath := "/type/model/inheritance/enum-discriminator/extensible-enum" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, input); err != nil { + return nil, err + } + return req, nil +} + +// PutFixedModel - Send model with fixed enum discriminator type. +// If the operation fails it returns an *azcore.ResponseError type. +// - input - Snake to create +// - options - EnumDiscriminatorClientPutFixedModelOptions contains the optional parameters for the EnumDiscriminatorClient.PutFixedModel +// method. +func (client *EnumDiscriminatorClient) PutFixedModel(ctx context.Context, input SnakeClassification, options *EnumDiscriminatorClientPutFixedModelOptions) (EnumDiscriminatorClientPutFixedModelResponse, error) { + var err error + const operationName = "EnumDiscriminatorClient.PutFixedModel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putFixedModelCreateRequest(ctx, input, options) + if err != nil { + return EnumDiscriminatorClientPutFixedModelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EnumDiscriminatorClientPutFixedModelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return EnumDiscriminatorClientPutFixedModelResponse{}, err + } + return EnumDiscriminatorClientPutFixedModelResponse{}, nil +} + +// putFixedModelCreateRequest creates the PutFixedModel request. +func (client *EnumDiscriminatorClient) putFixedModelCreateRequest(ctx context.Context, input SnakeClassification, _ *EnumDiscriminatorClientPutFixedModelOptions) (*policy.Request, error) { + urlPath := "/type/model/inheritance/enum-discriminator/fixed-enum" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/model/inheritance/enumdiscgroup/zz_interfaces.go b/test/http-specs/type/model/inheritance/enumdiscgroup/zz_interfaces.go new file mode 100644 index 000000000000..2ec06521f99e --- /dev/null +++ b/test/http-specs/type/model/inheritance/enumdiscgroup/zz_interfaces.go @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package enumdiscgroup + +// DogClassification provides polymorphic access to related types. +// Call the interface's GetDog() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *Dog, *Golden +type DogClassification interface { + // GetDog returns the Dog content of the underlying type. + GetDog() *Dog +} + +// SnakeClassification provides polymorphic access to related types. +// Call the interface's GetSnake() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *Cobra, *Snake +type SnakeClassification interface { + // GetSnake returns the Snake content of the underlying type. + GetSnake() *Snake +} diff --git a/test/http-specs/type/model/inheritance/enumdiscgroup/zz_models.go b/test/http-specs/type/model/inheritance/enumdiscgroup/zz_models.go new file mode 100644 index 000000000000..8b2dba84eaf6 --- /dev/null +++ b/test/http-specs/type/model/inheritance/enumdiscgroup/zz_models.go @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package enumdiscgroup + +// Cobra model +type Cobra struct { + // CONSTANT; discriminator property + // Field has constant value SnakeKindCobra, any specified value is ignored. + Kind *SnakeKind + + // REQUIRED; Length of the snake + Length *int32 +} + +// GetSnake implements the SnakeClassification interface for type Cobra. +func (c *Cobra) GetSnake() *Snake { + return &Snake{ + Kind: c.Kind, + Length: c.Length, + } +} + +// Dog - Test extensible enum type for discriminator +type Dog struct { + // REQUIRED; discriminator property + Kind *DogKind + + // REQUIRED; Weight of the dog + Weight *int32 +} + +// GetDog implements the DogClassification interface for type Dog. +func (d *Dog) GetDog() *Dog { return d } + +// Golden dog model +type Golden struct { + // CONSTANT; discriminator property + // Field has constant value DogKindGolden, any specified value is ignored. + Kind *DogKind + + // REQUIRED; Weight of the dog + Weight *int32 +} + +// GetDog implements the DogClassification interface for type Golden. +func (g *Golden) GetDog() *Dog { + return &Dog{ + Kind: g.Kind, + Weight: g.Weight, + } +} + +// Snake - Test fixed enum type for discriminator +type Snake struct { + // REQUIRED; discriminator property + Kind *SnakeKind + + // REQUIRED; Length of the snake + Length *int32 +} + +// GetSnake implements the SnakeClassification interface for type Snake. +func (s *Snake) GetSnake() *Snake { return s } diff --git a/test/http-specs/type/model/inheritance/enumdiscgroup/zz_models_serde.go b/test/http-specs/type/model/inheritance/enumdiscgroup/zz_models_serde.go new file mode 100644 index 000000000000..ffecb629148f --- /dev/null +++ b/test/http-specs/type/model/inheritance/enumdiscgroup/zz_models_serde.go @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package enumdiscgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type Cobra. +func (c Cobra) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["kind"] = SnakeKindCobra + populate(objectMap, "length", c.Length) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Cobra. +func (c *Cobra) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &c.Kind) + delete(rawMsg, key) + case "length": + err = unpopulate(val, "Length", &c.Length) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Dog. +func (d Dog) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "kind", d.Kind) + populate(objectMap, "weight", d.Weight) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Dog. +func (d *Dog) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &d.Kind) + delete(rawMsg, key) + case "weight": + err = unpopulate(val, "Weight", &d.Weight) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Golden. +func (g Golden) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["kind"] = DogKindGolden + populate(objectMap, "weight", g.Weight) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Golden. +func (g *Golden) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &g.Kind) + delete(rawMsg, key) + case "weight": + err = unpopulate(val, "Weight", &g.Weight) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Snake. +func (s Snake) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "kind", s.Kind) + populate(objectMap, "length", s.Length) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Snake. +func (s *Snake) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &s.Kind) + delete(rawMsg, key) + case "length": + err = unpopulate(val, "Length", &s.Length) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/http-specs/type/model/inheritance/enumdiscgroup/zz_options.go b/test/http-specs/type/model/inheritance/enumdiscgroup/zz_options.go new file mode 100644 index 000000000000..e7573eb6aed7 --- /dev/null +++ b/test/http-specs/type/model/inheritance/enumdiscgroup/zz_options.go @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package enumdiscgroup + +// EnumDiscriminatorClientGetExtensibleModelMissingDiscriminatorOptions contains the optional parameters for the EnumDiscriminatorClient.GetExtensibleModelMissingDiscriminator +// method. +type EnumDiscriminatorClientGetExtensibleModelMissingDiscriminatorOptions struct { + // placeholder for future optional parameters +} + +// EnumDiscriminatorClientGetExtensibleModelOptions contains the optional parameters for the EnumDiscriminatorClient.GetExtensibleModel +// method. +type EnumDiscriminatorClientGetExtensibleModelOptions struct { + // placeholder for future optional parameters +} + +// EnumDiscriminatorClientGetExtensibleModelWrongDiscriminatorOptions contains the optional parameters for the EnumDiscriminatorClient.GetExtensibleModelWrongDiscriminator +// method. +type EnumDiscriminatorClientGetExtensibleModelWrongDiscriminatorOptions struct { + // placeholder for future optional parameters +} + +// EnumDiscriminatorClientGetFixedModelMissingDiscriminatorOptions contains the optional parameters for the EnumDiscriminatorClient.GetFixedModelMissingDiscriminator +// method. +type EnumDiscriminatorClientGetFixedModelMissingDiscriminatorOptions struct { + // placeholder for future optional parameters +} + +// EnumDiscriminatorClientGetFixedModelOptions contains the optional parameters for the EnumDiscriminatorClient.GetFixedModel +// method. +type EnumDiscriminatorClientGetFixedModelOptions struct { + // placeholder for future optional parameters +} + +// EnumDiscriminatorClientGetFixedModelWrongDiscriminatorOptions contains the optional parameters for the EnumDiscriminatorClient.GetFixedModelWrongDiscriminator +// method. +type EnumDiscriminatorClientGetFixedModelWrongDiscriminatorOptions struct { + // placeholder for future optional parameters +} + +// EnumDiscriminatorClientPutExtensibleModelOptions contains the optional parameters for the EnumDiscriminatorClient.PutExtensibleModel +// method. +type EnumDiscriminatorClientPutExtensibleModelOptions struct { + // placeholder for future optional parameters +} + +// EnumDiscriminatorClientPutFixedModelOptions contains the optional parameters for the EnumDiscriminatorClient.PutFixedModel +// method. +type EnumDiscriminatorClientPutFixedModelOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/type/model/inheritance/enumdiscgroup/zz_polymorphic_helpers.go b/test/http-specs/type/model/inheritance/enumdiscgroup/zz_polymorphic_helpers.go new file mode 100644 index 000000000000..8737644e35b5 --- /dev/null +++ b/test/http-specs/type/model/inheritance/enumdiscgroup/zz_polymorphic_helpers.go @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package enumdiscgroup + +import "encoding/json" + +func unmarshalDogClassification(rawMsg json.RawMessage) (DogClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b DogClassification + switch m["kind"] { + case string(DogKindGolden): + b = &Golden{} + default: + b = &Dog{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} + +func unmarshalSnakeClassification(rawMsg json.RawMessage) (SnakeClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b SnakeClassification + switch m["kind"] { + case string(SnakeKindCobra): + b = &Cobra{} + default: + b = &Snake{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} diff --git a/test/http-specs/type/model/inheritance/enumdiscgroup/zz_responses.go b/test/http-specs/type/model/inheritance/enumdiscgroup/zz_responses.go new file mode 100644 index 000000000000..048352b3695b --- /dev/null +++ b/test/http-specs/type/model/inheritance/enumdiscgroup/zz_responses.go @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package enumdiscgroup + +// EnumDiscriminatorClientGetExtensibleModelMissingDiscriminatorResponse contains the response from method EnumDiscriminatorClient.GetExtensibleModelMissingDiscriminator. +type EnumDiscriminatorClientGetExtensibleModelMissingDiscriminatorResponse struct { + // Test extensible enum type for discriminator + DogClassification +} + +// EnumDiscriminatorClientGetExtensibleModelResponse contains the response from method EnumDiscriminatorClient.GetExtensibleModel. +type EnumDiscriminatorClientGetExtensibleModelResponse struct { + // Test extensible enum type for discriminator + DogClassification +} + +// EnumDiscriminatorClientGetExtensibleModelWrongDiscriminatorResponse contains the response from method EnumDiscriminatorClient.GetExtensibleModelWrongDiscriminator. +type EnumDiscriminatorClientGetExtensibleModelWrongDiscriminatorResponse struct { + // Test extensible enum type for discriminator + DogClassification +} + +// EnumDiscriminatorClientGetFixedModelMissingDiscriminatorResponse contains the response from method EnumDiscriminatorClient.GetFixedModelMissingDiscriminator. +type EnumDiscriminatorClientGetFixedModelMissingDiscriminatorResponse struct { + // Test fixed enum type for discriminator + SnakeClassification +} + +// EnumDiscriminatorClientGetFixedModelResponse contains the response from method EnumDiscriminatorClient.GetFixedModel. +type EnumDiscriminatorClientGetFixedModelResponse struct { + // Test fixed enum type for discriminator + SnakeClassification +} + +// EnumDiscriminatorClientGetFixedModelWrongDiscriminatorResponse contains the response from method EnumDiscriminatorClient.GetFixedModelWrongDiscriminator. +type EnumDiscriminatorClientGetFixedModelWrongDiscriminatorResponse struct { + // Test fixed enum type for discriminator + SnakeClassification +} + +// EnumDiscriminatorClientPutExtensibleModelResponse contains the response from method EnumDiscriminatorClient.PutExtensibleModel. +type EnumDiscriminatorClientPutExtensibleModelResponse struct { + // placeholder for future response values +} + +// EnumDiscriminatorClientPutFixedModelResponse contains the response from method EnumDiscriminatorClient.PutFixedModel. +type EnumDiscriminatorClientPutFixedModelResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/type/model/inheritance/enumdiscgroup/zz_responses_serde.go b/test/http-specs/type/model/inheritance/enumdiscgroup/zz_responses_serde.go new file mode 100644 index 000000000000..f4ace6d3ff29 --- /dev/null +++ b/test/http-specs/type/model/inheritance/enumdiscgroup/zz_responses_serde.go @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package enumdiscgroup + +// UnmarshalJSON implements the json.Unmarshaller interface for type EnumDiscriminatorClientGetExtensibleModelMissingDiscriminatorResponse. +func (e *EnumDiscriminatorClientGetExtensibleModelMissingDiscriminatorResponse) UnmarshalJSON(data []byte) error { + res, err := unmarshalDogClassification(data) + if err != nil { + return err + } + e.DogClassification = res + return nil +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EnumDiscriminatorClientGetExtensibleModelResponse. +func (e *EnumDiscriminatorClientGetExtensibleModelResponse) UnmarshalJSON(data []byte) error { + res, err := unmarshalDogClassification(data) + if err != nil { + return err + } + e.DogClassification = res + return nil +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EnumDiscriminatorClientGetExtensibleModelWrongDiscriminatorResponse. +func (e *EnumDiscriminatorClientGetExtensibleModelWrongDiscriminatorResponse) UnmarshalJSON(data []byte) error { + res, err := unmarshalDogClassification(data) + if err != nil { + return err + } + e.DogClassification = res + return nil +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EnumDiscriminatorClientGetFixedModelMissingDiscriminatorResponse. +func (e *EnumDiscriminatorClientGetFixedModelMissingDiscriminatorResponse) UnmarshalJSON(data []byte) error { + res, err := unmarshalSnakeClassification(data) + if err != nil { + return err + } + e.SnakeClassification = res + return nil +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EnumDiscriminatorClientGetFixedModelResponse. +func (e *EnumDiscriminatorClientGetFixedModelResponse) UnmarshalJSON(data []byte) error { + res, err := unmarshalSnakeClassification(data) + if err != nil { + return err + } + e.SnakeClassification = res + return nil +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EnumDiscriminatorClientGetFixedModelWrongDiscriminatorResponse. +func (e *EnumDiscriminatorClientGetFixedModelWrongDiscriminatorResponse) UnmarshalJSON(data []byte) error { + res, err := unmarshalSnakeClassification(data) + if err != nil { + return err + } + e.SnakeClassification = res + return nil +} diff --git a/test/http-specs/type/model/inheritance/enumdiscgroup/zz_version.go b/test/http-specs/type/model/inheritance/enumdiscgroup/zz_version.go new file mode 100644 index 000000000000..c41361e4e1bf --- /dev/null +++ b/test/http-specs/type/model/inheritance/enumdiscgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package enumdiscgroup + +const ( + moduleName = "enumdiscgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/type/model/inheritance/nodiscgroup/LICENSE.txt b/test/http-specs/type/model/inheritance/nodiscgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/type/model/inheritance/nodiscgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/type/model/inheritance/nodiscgroup/fake/zz_internal.go b/test/http-specs/type/model/inheritance/nodiscgroup/fake/zz_internal.go new file mode 100644 index 000000000000..705f81eacafe --- /dev/null +++ b/test/http-specs/type/model/inheritance/nodiscgroup/fake/zz_internal.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import "net/http" + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} diff --git a/test/http-specs/type/model/inheritance/nodiscgroup/fake/zz_notdiscriminated_server.go b/test/http-specs/type/model/inheritance/nodiscgroup/fake/zz_notdiscriminated_server.go new file mode 100644 index 000000000000..4e48d00317ed --- /dev/null +++ b/test/http-specs/type/model/inheritance/nodiscgroup/fake/zz_notdiscriminated_server.go @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "nodiscgroup" + "slices" +) + +// NotDiscriminatedServer is a fake server for instances of the nodiscgroup.NotDiscriminatedClient type. +type NotDiscriminatedServer struct { + // GetValid is the fake for method NotDiscriminatedClient.GetValid + // HTTP status codes to indicate success: http.StatusOK + GetValid func(ctx context.Context, options *nodiscgroup.NotDiscriminatedClientGetValidOptions) (resp azfake.Responder[nodiscgroup.NotDiscriminatedClientGetValidResponse], errResp azfake.ErrorResponder) + + // PostValid is the fake for method NotDiscriminatedClient.PostValid + // HTTP status codes to indicate success: http.StatusNoContent + PostValid func(ctx context.Context, input nodiscgroup.Siamese, options *nodiscgroup.NotDiscriminatedClientPostValidOptions) (resp azfake.Responder[nodiscgroup.NotDiscriminatedClientPostValidResponse], errResp azfake.ErrorResponder) + + // PutValid is the fake for method NotDiscriminatedClient.PutValid + // HTTP status codes to indicate success: http.StatusOK + PutValid func(ctx context.Context, input nodiscgroup.Siamese, options *nodiscgroup.NotDiscriminatedClientPutValidOptions) (resp azfake.Responder[nodiscgroup.NotDiscriminatedClientPutValidResponse], errResp azfake.ErrorResponder) +} + +// NewNotDiscriminatedServerTransport creates a new instance of NotDiscriminatedServerTransport with the provided implementation. +// The returned NotDiscriminatedServerTransport instance is connected to an instance of nodiscgroup.NotDiscriminatedClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewNotDiscriminatedServerTransport(srv *NotDiscriminatedServer) *NotDiscriminatedServerTransport { + return &NotDiscriminatedServerTransport{srv: srv} +} + +// NotDiscriminatedServerTransport connects instances of nodiscgroup.NotDiscriminatedClient to instances of NotDiscriminatedServer. +// Don't use this type directly, use NewNotDiscriminatedServerTransport instead. +type NotDiscriminatedServerTransport struct { + srv *NotDiscriminatedServer +} + +// Do implements the policy.Transporter interface for NotDiscriminatedServerTransport. +func (n *NotDiscriminatedServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return n.dispatchToMethodFake(req, method) +} + +func (n *NotDiscriminatedServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if notDiscriminatedServerTransportInterceptor != nil { + res.resp, res.err, intercepted = notDiscriminatedServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "NotDiscriminatedClient.GetValid": + res.resp, res.err = n.dispatchGetValid(req) + case "NotDiscriminatedClient.PostValid": + res.resp, res.err = n.dispatchPostValid(req) + case "NotDiscriminatedClient.PutValid": + res.resp, res.err = n.dispatchPutValid(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (n *NotDiscriminatedServerTransport) dispatchGetValid(req *http.Request) (*http.Response, error) { + if n.srv.GetValid == nil { + return nil, &nonRetriableError{errors.New("fake for method GetValid not implemented")} + } + respr, errRespr := n.srv.GetValid(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Siamese, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NotDiscriminatedServerTransport) dispatchPostValid(req *http.Request) (*http.Response, error) { + if n.srv.PostValid == nil { + return nil, &nonRetriableError{errors.New("fake for method PostValid not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[nodiscgroup.Siamese](req) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.PostValid(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NotDiscriminatedServerTransport) dispatchPutValid(req *http.Request) (*http.Response, error) { + if n.srv.PutValid == nil { + return nil, &nonRetriableError{errors.New("fake for method PutValid not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[nodiscgroup.Siamese](req) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.PutValid(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Siamese, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to NotDiscriminatedServerTransport +var notDiscriminatedServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/model/inheritance/nodiscgroup/go.mod b/test/http-specs/type/model/inheritance/nodiscgroup/go.mod new file mode 100644 index 000000000000..824053390c03 --- /dev/null +++ b/test/http-specs/type/model/inheritance/nodiscgroup/go.mod @@ -0,0 +1,17 @@ +module nodiscgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/type/model/inheritance/nodiscgroup/go.sum b/test/http-specs/type/model/inheritance/nodiscgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/type/model/inheritance/nodiscgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/type/model/inheritance/nodiscgroup/notdiscriminated_client_test.go b/test/http-specs/type/model/inheritance/nodiscgroup/notdiscriminated_client_test.go new file mode 100644 index 000000000000..7427af1c0174 --- /dev/null +++ b/test/http-specs/type/model/inheritance/nodiscgroup/notdiscriminated_client_test.go @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package nodiscgroup_test + +import ( + "context" + "nodiscgroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestNotDiscriminatedClientGetValid(t *testing.T) { + client, err := nodiscgroup.NewNotDiscriminatedClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.GetValid(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, nodiscgroup.Siamese{ + Age: to.Ptr[int32](32), + Name: to.Ptr("abc"), + Smart: to.Ptr(true), + }, resp.Siamese) +} + +func TestNotDiscriminatedClientPostValid(t *testing.T) { + client, err := nodiscgroup.NewNotDiscriminatedClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.PostValid(context.Background(), nodiscgroup.Siamese{ + Age: to.Ptr[int32](32), + Name: to.Ptr("abc"), + Smart: to.Ptr(true), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestNotDiscriminatedClientPutValid(t *testing.T) { + client, err := nodiscgroup.NewNotDiscriminatedClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + myCat := nodiscgroup.Siamese{ + Age: to.Ptr[int32](32), + Name: to.Ptr("abc"), + Smart: to.Ptr(true), + } + resp, err := client.PutValid(context.Background(), myCat, nil) + require.NoError(t, err) + require.EqualValues(t, resp.Siamese, myCat) +} diff --git a/test/http-specs/type/model/inheritance/nodiscgroup/testdata/_metadata.json b/test/http-specs/type/model/inheritance/nodiscgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/type/model/inheritance/nodiscgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/type/model/inheritance/nodiscgroup/zz_models.go b/test/http-specs/type/model/inheritance/nodiscgroup/zz_models.go new file mode 100644 index 000000000000..237ee3e3effd --- /dev/null +++ b/test/http-specs/type/model/inheritance/nodiscgroup/zz_models.go @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nodiscgroup + +// Siamese - The third level model in the normal multiple levels inheritance. +type Siamese struct { + // REQUIRED + Age *int32 + + // REQUIRED + Name *string + + // REQUIRED + Smart *bool +} diff --git a/test/http-specs/type/model/inheritance/nodiscgroup/zz_models_serde.go b/test/http-specs/type/model/inheritance/nodiscgroup/zz_models_serde.go new file mode 100644 index 000000000000..579002fd7f07 --- /dev/null +++ b/test/http-specs/type/model/inheritance/nodiscgroup/zz_models_serde.go @@ -0,0 +1,67 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nodiscgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type Siamese. +func (s Siamese) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "age", s.Age) + populate(objectMap, "name", s.Name) + populate(objectMap, "smart", s.Smart) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Siamese. +func (s *Siamese) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "age": + err = unpopulate(val, "Age", &s.Age) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "smart": + err = unpopulate(val, "Smart", &s.Smart) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/http-specs/type/model/inheritance/nodiscgroup/zz_notdiscriminated_client.go b/test/http-specs/type/model/inheritance/nodiscgroup/zz_notdiscriminated_client.go new file mode 100644 index 000000000000..de9ead260713 --- /dev/null +++ b/test/http-specs/type/model/inheritance/nodiscgroup/zz_notdiscriminated_client.go @@ -0,0 +1,178 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nodiscgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// NotDiscriminatedClient - Illustrates not-discriminated inheritance model. +// Don't use this type directly, use NewNotDiscriminatedClientWithNoCredential() instead. +type NotDiscriminatedClient struct { + internal *azcore.Client + endpoint string +} + +// NotDiscriminatedClientOptions contains the optional values for creating a [NotDiscriminatedClient]. +type NotDiscriminatedClientOptions struct { + azcore.ClientOptions +} + +// NewNotDiscriminatedClientWithNoCredential creates a new instance of NotDiscriminatedClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewNotDiscriminatedClientWithNoCredential(endpoint string, options *NotDiscriminatedClientOptions) (*NotDiscriminatedClient, error) { + if options == nil { + options = &NotDiscriminatedClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &NotDiscriminatedClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// GetValid - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NotDiscriminatedClientGetValidOptions contains the optional parameters for the NotDiscriminatedClient.GetValid +// method. +func (client *NotDiscriminatedClient) GetValid(ctx context.Context, options *NotDiscriminatedClientGetValidOptions) (NotDiscriminatedClientGetValidResponse, error) { + var err error + const operationName = "NotDiscriminatedClient.GetValid" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getValidCreateRequest(ctx, options) + if err != nil { + return NotDiscriminatedClientGetValidResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NotDiscriminatedClientGetValidResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NotDiscriminatedClientGetValidResponse{}, err + } + resp, err := client.getValidHandleResponse(httpResp) + return resp, err +} + +// getValidCreateRequest creates the GetValid request. +func (client *NotDiscriminatedClient) getValidCreateRequest(ctx context.Context, _ *NotDiscriminatedClientGetValidOptions) (*policy.Request, error) { + urlPath := "/type/model/inheritance/not-discriminated/valid" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getValidHandleResponse handles the GetValid response. +func (client *NotDiscriminatedClient) getValidHandleResponse(resp *http.Response) (NotDiscriminatedClientGetValidResponse, error) { + result := NotDiscriminatedClientGetValidResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Siamese); err != nil { + return NotDiscriminatedClientGetValidResponse{}, err + } + return result, nil +} + +// PostValid - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NotDiscriminatedClientPostValidOptions contains the optional parameters for the NotDiscriminatedClient.PostValid +// method. +func (client *NotDiscriminatedClient) PostValid(ctx context.Context, input Siamese, options *NotDiscriminatedClientPostValidOptions) (NotDiscriminatedClientPostValidResponse, error) { + var err error + const operationName = "NotDiscriminatedClient.PostValid" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.postValidCreateRequest(ctx, input, options) + if err != nil { + return NotDiscriminatedClientPostValidResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NotDiscriminatedClientPostValidResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return NotDiscriminatedClientPostValidResponse{}, err + } + return NotDiscriminatedClientPostValidResponse{}, nil +} + +// postValidCreateRequest creates the PostValid request. +func (client *NotDiscriminatedClient) postValidCreateRequest(ctx context.Context, input Siamese, _ *NotDiscriminatedClientPostValidOptions) (*policy.Request, error) { + urlPath := "/type/model/inheritance/not-discriminated/valid" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, input); err != nil { + return nil, err + } + return req, nil +} + +// PutValid - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NotDiscriminatedClientPutValidOptions contains the optional parameters for the NotDiscriminatedClient.PutValid +// method. +func (client *NotDiscriminatedClient) PutValid(ctx context.Context, input Siamese, options *NotDiscriminatedClientPutValidOptions) (NotDiscriminatedClientPutValidResponse, error) { + var err error + const operationName = "NotDiscriminatedClient.PutValid" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putValidCreateRequest(ctx, input, options) + if err != nil { + return NotDiscriminatedClientPutValidResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NotDiscriminatedClientPutValidResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NotDiscriminatedClientPutValidResponse{}, err + } + resp, err := client.putValidHandleResponse(httpResp) + return resp, err +} + +// putValidCreateRequest creates the PutValid request. +func (client *NotDiscriminatedClient) putValidCreateRequest(ctx context.Context, input Siamese, _ *NotDiscriminatedClientPutValidOptions) (*policy.Request, error) { + urlPath := "/type/model/inheritance/not-discriminated/valid" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, input); err != nil { + return nil, err + } + return req, nil +} + +// putValidHandleResponse handles the PutValid response. +func (client *NotDiscriminatedClient) putValidHandleResponse(resp *http.Response) (NotDiscriminatedClientPutValidResponse, error) { + result := NotDiscriminatedClientPutValidResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Siamese); err != nil { + return NotDiscriminatedClientPutValidResponse{}, err + } + return result, nil +} diff --git a/test/http-specs/type/model/inheritance/nodiscgroup/zz_options.go b/test/http-specs/type/model/inheritance/nodiscgroup/zz_options.go new file mode 100644 index 000000000000..52a9bf1ce226 --- /dev/null +++ b/test/http-specs/type/model/inheritance/nodiscgroup/zz_options.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nodiscgroup + +// NotDiscriminatedClientGetValidOptions contains the optional parameters for the NotDiscriminatedClient.GetValid method. +type NotDiscriminatedClientGetValidOptions struct { + // placeholder for future optional parameters +} + +// NotDiscriminatedClientPostValidOptions contains the optional parameters for the NotDiscriminatedClient.PostValid method. +type NotDiscriminatedClientPostValidOptions struct { + // placeholder for future optional parameters +} + +// NotDiscriminatedClientPutValidOptions contains the optional parameters for the NotDiscriminatedClient.PutValid method. +type NotDiscriminatedClientPutValidOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/type/model/inheritance/nodiscgroup/zz_responses.go b/test/http-specs/type/model/inheritance/nodiscgroup/zz_responses.go new file mode 100644 index 000000000000..c9b52597c9ee --- /dev/null +++ b/test/http-specs/type/model/inheritance/nodiscgroup/zz_responses.go @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nodiscgroup + +// NotDiscriminatedClientGetValidResponse contains the response from method NotDiscriminatedClient.GetValid. +type NotDiscriminatedClientGetValidResponse struct { + // The third level model in the normal multiple levels inheritance. + Siamese +} + +// NotDiscriminatedClientPostValidResponse contains the response from method NotDiscriminatedClient.PostValid. +type NotDiscriminatedClientPostValidResponse struct { + // placeholder for future response values +} + +// NotDiscriminatedClientPutValidResponse contains the response from method NotDiscriminatedClient.PutValid. +type NotDiscriminatedClientPutValidResponse struct { + // The third level model in the normal multiple levels inheritance. + Siamese +} diff --git a/test/http-specs/type/model/inheritance/nodiscgroup/zz_version.go b/test/http-specs/type/model/inheritance/nodiscgroup/zz_version.go new file mode 100644 index 000000000000..db3b0436eeb9 --- /dev/null +++ b/test/http-specs/type/model/inheritance/nodiscgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package nodiscgroup + +const ( + moduleName = "nodiscgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/type/model/inheritance/recursivegroup/LICENSE.txt b/test/http-specs/type/model/inheritance/recursivegroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/type/model/inheritance/recursivegroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/type/model/inheritance/recursivegroup/fake/zz_internal.go b/test/http-specs/type/model/inheritance/recursivegroup/fake/zz_internal.go new file mode 100644 index 000000000000..705f81eacafe --- /dev/null +++ b/test/http-specs/type/model/inheritance/recursivegroup/fake/zz_internal.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import "net/http" + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} diff --git a/test/http-specs/type/model/inheritance/recursivegroup/fake/zz_recursive_server.go b/test/http-specs/type/model/inheritance/recursivegroup/fake/zz_recursive_server.go new file mode 100644 index 000000000000..60fde23aaa01 --- /dev/null +++ b/test/http-specs/type/model/inheritance/recursivegroup/fake/zz_recursive_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "recursivegroup" + "slices" +) + +// RecursiveServer is a fake server for instances of the recursivegroup.RecursiveClient type. +type RecursiveServer struct { + // Get is the fake for method RecursiveClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *recursivegroup.RecursiveClientGetOptions) (resp azfake.Responder[recursivegroup.RecursiveClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method RecursiveClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, input recursivegroup.Extension, options *recursivegroup.RecursiveClientPutOptions) (resp azfake.Responder[recursivegroup.RecursiveClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewRecursiveServerTransport creates a new instance of RecursiveServerTransport with the provided implementation. +// The returned RecursiveServerTransport instance is connected to an instance of recursivegroup.RecursiveClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewRecursiveServerTransport(srv *RecursiveServer) *RecursiveServerTransport { + return &RecursiveServerTransport{srv: srv} +} + +// RecursiveServerTransport connects instances of recursivegroup.RecursiveClient to instances of RecursiveServer. +// Don't use this type directly, use NewRecursiveServerTransport instead. +type RecursiveServerTransport struct { + srv *RecursiveServer +} + +// Do implements the policy.Transporter interface for RecursiveServerTransport. +func (r *RecursiveServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return r.dispatchToMethodFake(req, method) +} + +func (r *RecursiveServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if recursiveServerTransportInterceptor != nil { + res.resp, res.err, intercepted = recursiveServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "RecursiveClient.Get": + res.resp, res.err = r.dispatchGet(req) + case "RecursiveClient.Put": + res.resp, res.err = r.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (r *RecursiveServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if r.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := r.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Extension, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (r *RecursiveServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if r.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[recursivegroup.Extension](req) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to RecursiveServerTransport +var recursiveServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/model/inheritance/recursivegroup/go.mod b/test/http-specs/type/model/inheritance/recursivegroup/go.mod new file mode 100644 index 000000000000..954a40093ea2 --- /dev/null +++ b/test/http-specs/type/model/inheritance/recursivegroup/go.mod @@ -0,0 +1,17 @@ +module recursivegroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/type/model/inheritance/recursivegroup/go.sum b/test/http-specs/type/model/inheritance/recursivegroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/type/model/inheritance/recursivegroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/type/model/inheritance/recursivegroup/recursive_client_test.go b/test/http-specs/type/model/inheritance/recursivegroup/recursive_client_test.go new file mode 100644 index 000000000000..616e5cad7cfe --- /dev/null +++ b/test/http-specs/type/model/inheritance/recursivegroup/recursive_client_test.go @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package recursivegroup_test + +import ( + "context" + "recursivegroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestRecursiveClientGet(t *testing.T) { + client, err := recursivegroup.NewRecursiveClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, recursivegroup.Extension{ + Extension: []recursivegroup.Extension{ + { + Extension: []recursivegroup.Extension{ + { + Level: to.Ptr[int8](2), + }, + }, + Level: to.Ptr[int8](1), + }, + { + Level: to.Ptr[int8](1), + }, + }, + Level: to.Ptr[int8](0), + }, resp.Extension) +} + +func TestRecursiveClientPut(t *testing.T) { + client, err := recursivegroup.NewRecursiveClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.Put(context.Background(), recursivegroup.Extension{ + Extension: []recursivegroup.Extension{ + { + Extension: []recursivegroup.Extension{ + { + Level: to.Ptr[int8](2), + }, + }, + Level: to.Ptr[int8](1), + }, + { + Level: to.Ptr[int8](1), + }, + }, + Level: to.Ptr[int8](0), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/model/inheritance/recursivegroup/testdata/_metadata.json b/test/http-specs/type/model/inheritance/recursivegroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/type/model/inheritance/recursivegroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/type/model/inheritance/recursivegroup/zz_models.go b/test/http-specs/type/model/inheritance/recursivegroup/zz_models.go new file mode 100644 index 000000000000..cdd40f333366 --- /dev/null +++ b/test/http-specs/type/model/inheritance/recursivegroup/zz_models.go @@ -0,0 +1,12 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package recursivegroup + +// Extension - extension +type Extension struct { + // REQUIRED + Level *int8 + Extension []Extension +} diff --git a/test/http-specs/type/model/inheritance/recursivegroup/zz_models_serde.go b/test/http-specs/type/model/inheritance/recursivegroup/zz_models_serde.go new file mode 100644 index 000000000000..8cd00f0c93e7 --- /dev/null +++ b/test/http-specs/type/model/inheritance/recursivegroup/zz_models_serde.go @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package recursivegroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type Extension. +func (e Extension) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "extension", e.Extension) + populate(objectMap, "level", e.Level) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Extension. +func (e *Extension) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "extension": + err = unpopulate(val, "Extension", &e.Extension) + delete(rawMsg, key) + case "level": + err = unpopulate(val, "Level", &e.Level) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/http-specs/type/model/inheritance/recursivegroup/zz_options.go b/test/http-specs/type/model/inheritance/recursivegroup/zz_options.go new file mode 100644 index 000000000000..823cc2b945ad --- /dev/null +++ b/test/http-specs/type/model/inheritance/recursivegroup/zz_options.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package recursivegroup + +// RecursiveClientGetOptions contains the optional parameters for the RecursiveClient.Get method. +type RecursiveClientGetOptions struct { + // placeholder for future optional parameters +} + +// RecursiveClientPutOptions contains the optional parameters for the RecursiveClient.Put method. +type RecursiveClientPutOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/type/model/inheritance/recursivegroup/zz_recursive_client.go b/test/http-specs/type/model/inheritance/recursivegroup/zz_recursive_client.go new file mode 100644 index 000000000000..b522265ed434 --- /dev/null +++ b/test/http-specs/type/model/inheritance/recursivegroup/zz_recursive_client.go @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package recursivegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// RecursiveClient - Illustrates inheritance recursion +// Don't use this type directly, use NewRecursiveClientWithNoCredential() instead. +type RecursiveClient struct { + internal *azcore.Client + endpoint string +} + +// RecursiveClientOptions contains the optional values for creating a [RecursiveClient]. +type RecursiveClientOptions struct { + azcore.ClientOptions +} + +// NewRecursiveClientWithNoCredential creates a new instance of RecursiveClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewRecursiveClientWithNoCredential(endpoint string, options *RecursiveClientOptions) (*RecursiveClient, error) { + if options == nil { + options = &RecursiveClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &RecursiveClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - RecursiveClientGetOptions contains the optional parameters for the RecursiveClient.Get method. +func (client *RecursiveClient) Get(ctx context.Context, options *RecursiveClientGetOptions) (RecursiveClientGetResponse, error) { + var err error + const operationName = "RecursiveClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return RecursiveClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RecursiveClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RecursiveClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *RecursiveClient) getCreateRequest(ctx context.Context, _ *RecursiveClientGetOptions) (*policy.Request, error) { + urlPath := "/type/model/inheritance/recursive" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *RecursiveClient) getHandleResponse(resp *http.Response) (RecursiveClientGetResponse, error) { + result := RecursiveClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Extension); err != nil { + return RecursiveClientGetResponse{}, err + } + return result, nil +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - RecursiveClientPutOptions contains the optional parameters for the RecursiveClient.Put method. +func (client *RecursiveClient) Put(ctx context.Context, input Extension, options *RecursiveClientPutOptions) (RecursiveClientPutResponse, error) { + var err error + const operationName = "RecursiveClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, input, options) + if err != nil { + return RecursiveClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RecursiveClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return RecursiveClientPutResponse{}, err + } + return RecursiveClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *RecursiveClient) putCreateRequest(ctx context.Context, input Extension, _ *RecursiveClientPutOptions) (*policy.Request, error) { + urlPath := "/type/model/inheritance/recursive" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/model/inheritance/recursivegroup/zz_responses.go b/test/http-specs/type/model/inheritance/recursivegroup/zz_responses.go new file mode 100644 index 000000000000..a7ae4d5c31c9 --- /dev/null +++ b/test/http-specs/type/model/inheritance/recursivegroup/zz_responses.go @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package recursivegroup + +// RecursiveClientGetResponse contains the response from method RecursiveClient.Get. +type RecursiveClientGetResponse struct { + // extension + Extension +} + +// RecursiveClientPutResponse contains the response from method RecursiveClient.Put. +type RecursiveClientPutResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/type/model/inheritance/recursivegroup/zz_version.go b/test/http-specs/type/model/inheritance/recursivegroup/zz_version.go new file mode 100644 index 000000000000..1de058462f8b --- /dev/null +++ b/test/http-specs/type/model/inheritance/recursivegroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package recursivegroup + +const ( + moduleName = "recursivegroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/type/model/inheritance/singlediscgroup/LICENSE.txt b/test/http-specs/type/model/inheritance/singlediscgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/type/model/inheritance/singlediscgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/type/model/inheritance/singlediscgroup/fake/zz_internal.go b/test/http-specs/type/model/inheritance/singlediscgroup/fake/zz_internal.go new file mode 100644 index 000000000000..ee1bb08ff0bf --- /dev/null +++ b/test/http-specs/type/model/inheritance/singlediscgroup/fake/zz_internal.go @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "io" + "net/http" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func readRequestBody(req *http.Request) ([]byte, error) { + if req.Body == nil { + return nil, nil + } + body, err := io.ReadAll(req.Body) + if err != nil { + return nil, err + } + req.Body.Close() + return body, nil +} diff --git a/test/http-specs/type/model/inheritance/singlediscgroup/fake/zz_polymorphic_helpers.go b/test/http-specs/type/model/inheritance/singlediscgroup/fake/zz_polymorphic_helpers.go new file mode 100644 index 000000000000..c8546e208e14 --- /dev/null +++ b/test/http-specs/type/model/inheritance/singlediscgroup/fake/zz_polymorphic_helpers.go @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "encoding/json" + "singlediscgroup" +) + +func unmarshalBirdClassification(rawMsg json.RawMessage) (singlediscgroup.BirdClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b singlediscgroup.BirdClassification + switch m["kind"] { + case "eagle": + b = &singlediscgroup.Eagle{} + case "goose": + b = &singlediscgroup.Goose{} + case "seagull": + b = &singlediscgroup.SeaGull{} + case "sparrow": + b = &singlediscgroup.Sparrow{} + default: + b = &singlediscgroup.Bird{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} + +func unmarshalFishClassification(rawMsg json.RawMessage) (singlediscgroup.FishClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b singlediscgroup.FishClassification + switch m["kind"] { + default: + b = &singlediscgroup.Fish{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} diff --git a/test/http-specs/type/model/inheritance/singlediscgroup/fake/zz_singlediscriminator_server.go b/test/http-specs/type/model/inheritance/singlediscgroup/fake/zz_singlediscriminator_server.go new file mode 100644 index 000000000000..e9efc9f67ca0 --- /dev/null +++ b/test/http-specs/type/model/inheritance/singlediscgroup/fake/zz_singlediscriminator_server.go @@ -0,0 +1,325 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "singlediscgroup" + "slices" +) + +// SingleDiscriminatorServer is a fake server for instances of the singlediscgroup.SingleDiscriminatorClient type. +type SingleDiscriminatorServer struct { + // GetLegacyModel is the fake for method SingleDiscriminatorClient.GetLegacyModel + // HTTP status codes to indicate success: http.StatusOK + GetLegacyModel func(ctx context.Context, options *singlediscgroup.SingleDiscriminatorClientGetLegacyModelOptions) (resp azfake.Responder[singlediscgroup.SingleDiscriminatorClientGetLegacyModelResponse], errResp azfake.ErrorResponder) + + // GetMissingDiscriminator is the fake for method SingleDiscriminatorClient.GetMissingDiscriminator + // HTTP status codes to indicate success: http.StatusOK + GetMissingDiscriminator func(ctx context.Context, options *singlediscgroup.SingleDiscriminatorClientGetMissingDiscriminatorOptions) (resp azfake.Responder[singlediscgroup.SingleDiscriminatorClientGetMissingDiscriminatorResponse], errResp azfake.ErrorResponder) + + // GetModel is the fake for method SingleDiscriminatorClient.GetModel + // HTTP status codes to indicate success: http.StatusOK + GetModel func(ctx context.Context, options *singlediscgroup.SingleDiscriminatorClientGetModelOptions) (resp azfake.Responder[singlediscgroup.SingleDiscriminatorClientGetModelResponse], errResp azfake.ErrorResponder) + + // GetNoSubtypesModel is the fake for method SingleDiscriminatorClient.GetNoSubtypesModel + // HTTP status codes to indicate success: http.StatusOK + GetNoSubtypesModel func(ctx context.Context, options *singlediscgroup.SingleDiscriminatorClientGetNoSubtypesModelOptions) (resp azfake.Responder[singlediscgroup.SingleDiscriminatorClientGetNoSubtypesModelResponse], errResp azfake.ErrorResponder) + + // GetRecursiveModel is the fake for method SingleDiscriminatorClient.GetRecursiveModel + // HTTP status codes to indicate success: http.StatusOK + GetRecursiveModel func(ctx context.Context, options *singlediscgroup.SingleDiscriminatorClientGetRecursiveModelOptions) (resp azfake.Responder[singlediscgroup.SingleDiscriminatorClientGetRecursiveModelResponse], errResp azfake.ErrorResponder) + + // GetWrongDiscriminator is the fake for method SingleDiscriminatorClient.GetWrongDiscriminator + // HTTP status codes to indicate success: http.StatusOK + GetWrongDiscriminator func(ctx context.Context, options *singlediscgroup.SingleDiscriminatorClientGetWrongDiscriminatorOptions) (resp azfake.Responder[singlediscgroup.SingleDiscriminatorClientGetWrongDiscriminatorResponse], errResp azfake.ErrorResponder) + + // PutModel is the fake for method SingleDiscriminatorClient.PutModel + // HTTP status codes to indicate success: http.StatusNoContent + PutModel func(ctx context.Context, input singlediscgroup.BirdClassification, options *singlediscgroup.SingleDiscriminatorClientPutModelOptions) (resp azfake.Responder[singlediscgroup.SingleDiscriminatorClientPutModelResponse], errResp azfake.ErrorResponder) + + // PutNoSubtypesModel is the fake for method SingleDiscriminatorClient.PutNoSubtypesModel + // HTTP status codes to indicate success: http.StatusNoContent + PutNoSubtypesModel func(ctx context.Context, input singlediscgroup.FishClassification, options *singlediscgroup.SingleDiscriminatorClientPutNoSubtypesModelOptions) (resp azfake.Responder[singlediscgroup.SingleDiscriminatorClientPutNoSubtypesModelResponse], errResp azfake.ErrorResponder) + + // PutRecursiveModel is the fake for method SingleDiscriminatorClient.PutRecursiveModel + // HTTP status codes to indicate success: http.StatusNoContent + PutRecursiveModel func(ctx context.Context, input singlediscgroup.BirdClassification, options *singlediscgroup.SingleDiscriminatorClientPutRecursiveModelOptions) (resp azfake.Responder[singlediscgroup.SingleDiscriminatorClientPutRecursiveModelResponse], errResp azfake.ErrorResponder) +} + +// NewSingleDiscriminatorServerTransport creates a new instance of SingleDiscriminatorServerTransport with the provided implementation. +// The returned SingleDiscriminatorServerTransport instance is connected to an instance of singlediscgroup.SingleDiscriminatorClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSingleDiscriminatorServerTransport(srv *SingleDiscriminatorServer) *SingleDiscriminatorServerTransport { + return &SingleDiscriminatorServerTransport{srv: srv} +} + +// SingleDiscriminatorServerTransport connects instances of singlediscgroup.SingleDiscriminatorClient to instances of SingleDiscriminatorServer. +// Don't use this type directly, use NewSingleDiscriminatorServerTransport instead. +type SingleDiscriminatorServerTransport struct { + srv *SingleDiscriminatorServer +} + +// Do implements the policy.Transporter interface for SingleDiscriminatorServerTransport. +func (s *SingleDiscriminatorServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *SingleDiscriminatorServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if singleDiscriminatorServerTransportInterceptor != nil { + res.resp, res.err, intercepted = singleDiscriminatorServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SingleDiscriminatorClient.GetLegacyModel": + res.resp, res.err = s.dispatchGetLegacyModel(req) + case "SingleDiscriminatorClient.GetMissingDiscriminator": + res.resp, res.err = s.dispatchGetMissingDiscriminator(req) + case "SingleDiscriminatorClient.GetModel": + res.resp, res.err = s.dispatchGetModel(req) + case "SingleDiscriminatorClient.GetNoSubtypesModel": + res.resp, res.err = s.dispatchGetNoSubtypesModel(req) + case "SingleDiscriminatorClient.GetRecursiveModel": + res.resp, res.err = s.dispatchGetRecursiveModel(req) + case "SingleDiscriminatorClient.GetWrongDiscriminator": + res.resp, res.err = s.dispatchGetWrongDiscriminator(req) + case "SingleDiscriminatorClient.PutModel": + res.resp, res.err = s.dispatchPutModel(req) + case "SingleDiscriminatorClient.PutNoSubtypesModel": + res.resp, res.err = s.dispatchPutNoSubtypesModel(req) + case "SingleDiscriminatorClient.PutRecursiveModel": + res.resp, res.err = s.dispatchPutRecursiveModel(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *SingleDiscriminatorServerTransport) dispatchGetLegacyModel(req *http.Request) (*http.Response, error) { + if s.srv.GetLegacyModel == nil { + return nil, &nonRetriableError{errors.New("fake for method GetLegacyModel not implemented")} + } + respr, errRespr := s.srv.GetLegacyModel(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DinosaurClassification, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SingleDiscriminatorServerTransport) dispatchGetMissingDiscriminator(req *http.Request) (*http.Response, error) { + if s.srv.GetMissingDiscriminator == nil { + return nil, &nonRetriableError{errors.New("fake for method GetMissingDiscriminator not implemented")} + } + respr, errRespr := s.srv.GetMissingDiscriminator(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BirdClassification, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SingleDiscriminatorServerTransport) dispatchGetModel(req *http.Request) (*http.Response, error) { + if s.srv.GetModel == nil { + return nil, &nonRetriableError{errors.New("fake for method GetModel not implemented")} + } + respr, errRespr := s.srv.GetModel(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BirdClassification, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SingleDiscriminatorServerTransport) dispatchGetNoSubtypesModel(req *http.Request) (*http.Response, error) { + if s.srv.GetNoSubtypesModel == nil { + return nil, &nonRetriableError{errors.New("fake for method GetNoSubtypesModel not implemented")} + } + respr, errRespr := s.srv.GetNoSubtypesModel(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).FishClassification, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SingleDiscriminatorServerTransport) dispatchGetRecursiveModel(req *http.Request) (*http.Response, error) { + if s.srv.GetRecursiveModel == nil { + return nil, &nonRetriableError{errors.New("fake for method GetRecursiveModel not implemented")} + } + respr, errRespr := s.srv.GetRecursiveModel(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BirdClassification, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SingleDiscriminatorServerTransport) dispatchGetWrongDiscriminator(req *http.Request) (*http.Response, error) { + if s.srv.GetWrongDiscriminator == nil { + return nil, &nonRetriableError{errors.New("fake for method GetWrongDiscriminator not implemented")} + } + respr, errRespr := s.srv.GetWrongDiscriminator(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BirdClassification, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SingleDiscriminatorServerTransport) dispatchPutModel(req *http.Request) (*http.Response, error) { + if s.srv.PutModel == nil { + return nil, &nonRetriableError{errors.New("fake for method PutModel not implemented")} + } + raw, err := readRequestBody(req) + if err != nil { + return nil, err + } + body, err := unmarshalBirdClassification(raw) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.PutModel(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SingleDiscriminatorServerTransport) dispatchPutNoSubtypesModel(req *http.Request) (*http.Response, error) { + if s.srv.PutNoSubtypesModel == nil { + return nil, &nonRetriableError{errors.New("fake for method PutNoSubtypesModel not implemented")} + } + raw, err := readRequestBody(req) + if err != nil { + return nil, err + } + body, err := unmarshalFishClassification(raw) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.PutNoSubtypesModel(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SingleDiscriminatorServerTransport) dispatchPutRecursiveModel(req *http.Request) (*http.Response, error) { + if s.srv.PutRecursiveModel == nil { + return nil, &nonRetriableError{errors.New("fake for method PutRecursiveModel not implemented")} + } + raw, err := readRequestBody(req) + if err != nil { + return nil, err + } + body, err := unmarshalBirdClassification(raw) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.PutRecursiveModel(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SingleDiscriminatorServerTransport +var singleDiscriminatorServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/model/inheritance/singlediscgroup/go.mod b/test/http-specs/type/model/inheritance/singlediscgroup/go.mod new file mode 100644 index 000000000000..03ac284a4944 --- /dev/null +++ b/test/http-specs/type/model/inheritance/singlediscgroup/go.mod @@ -0,0 +1,17 @@ +module singlediscgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/type/model/inheritance/singlediscgroup/go.sum b/test/http-specs/type/model/inheritance/singlediscgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/type/model/inheritance/singlediscgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/type/model/inheritance/singlediscgroup/singlediscriminator_client_test.go b/test/http-specs/type/model/inheritance/singlediscgroup/singlediscriminator_client_test.go new file mode 100644 index 000000000000..f358c20d84c0 --- /dev/null +++ b/test/http-specs/type/model/inheritance/singlediscgroup/singlediscriminator_client_test.go @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package singlediscgroup_test + +import ( + "context" + "singlediscgroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestSingleDiscriminatorClientGetLegacyModel(t *testing.T) { + client, err := singlediscgroup.NewSingleDiscriminatorClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.GetLegacyModel(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.DinosaurClassification) + require.Equal(t, &singlediscgroup.TRex{ + Kind: to.Ptr("t-rex"), + Size: to.Ptr[int32](20), + }, resp.DinosaurClassification) +} + +func TestSingleDiscriminatorClientGetMissingDiscriminator(t *testing.T) { + client, err := singlediscgroup.NewSingleDiscriminatorClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.GetMissingDiscriminator(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.BirdClassification) + require.Equal(t, &singlediscgroup.Bird{ + Wingspan: to.Ptr[int32](1), + }, resp.BirdClassification) +} + +func TestSingleDiscriminatorClientGetModel(t *testing.T) { + client, err := singlediscgroup.NewSingleDiscriminatorClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.GetModel(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.BirdClassification) + require.Equal(t, &singlediscgroup.Sparrow{ + Kind: to.Ptr("sparrow"), + Wingspan: to.Ptr[int32](1), + }, resp.BirdClassification) +} + +func TestSingleDiscriminatorClientGetRecursiveModel(t *testing.T) { + client, err := singlediscgroup.NewSingleDiscriminatorClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.GetRecursiveModel(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.BirdClassification) + require.Equal(t, &singlediscgroup.Eagle{ + Kind: to.Ptr("eagle"), + Wingspan: to.Ptr[int32](5), + Partner: &singlediscgroup.Goose{ + Kind: to.Ptr("goose"), + Wingspan: to.Ptr[int32](2), + }, + Friends: []singlediscgroup.BirdClassification{ + &singlediscgroup.SeaGull{ + Kind: to.Ptr("seagull"), + Wingspan: to.Ptr[int32](2), + }, + }, + Hate: map[string]singlediscgroup.BirdClassification{ + "key3": &singlediscgroup.Sparrow{ + Kind: to.Ptr("sparrow"), + Wingspan: to.Ptr[int32](1), + }, + }, + }, resp.BirdClassification) +} + +func TestSingleDiscriminatorClientGetWrongDiscriminator(t *testing.T) { + client, err := singlediscgroup.NewSingleDiscriminatorClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.GetWrongDiscriminator(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.BirdClassification) + require.Equal(t, &singlediscgroup.Bird{ + Kind: to.Ptr("wrongKind"), + Wingspan: to.Ptr[int32](1), + }, resp.BirdClassification) +} + +func TestSingleDiscriminatorClientPutModel(t *testing.T) { + client, err := singlediscgroup.NewSingleDiscriminatorClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.PutModel(context.Background(), &singlediscgroup.Sparrow{ + Kind: to.Ptr("sparrow"), + Wingspan: to.Ptr[int32](1), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestSingleDiscriminatorClientPutRecursiveModel(t *testing.T) { + client, err := singlediscgroup.NewSingleDiscriminatorClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.PutRecursiveModel(context.Background(), &singlediscgroup.Eagle{ + Kind: to.Ptr("eagle"), + Wingspan: to.Ptr[int32](5), + Partner: &singlediscgroup.Goose{ + Kind: to.Ptr("goose"), + Wingspan: to.Ptr[int32](2), + }, + Friends: []singlediscgroup.BirdClassification{ + &singlediscgroup.SeaGull{ + Kind: to.Ptr("seagull"), + Wingspan: to.Ptr[int32](2), + }, + }, + Hate: map[string]singlediscgroup.BirdClassification{ + "key3": &singlediscgroup.Sparrow{ + Kind: to.Ptr("sparrow"), + Wingspan: to.Ptr[int32](1), + }, + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/model/inheritance/singlediscgroup/testdata/_metadata.json b/test/http-specs/type/model/inheritance/singlediscgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/type/model/inheritance/singlediscgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/type/model/inheritance/singlediscgroup/zz_interfaces.go b/test/http-specs/type/model/inheritance/singlediscgroup/zz_interfaces.go new file mode 100644 index 000000000000..35d6bc884e3b --- /dev/null +++ b/test/http-specs/type/model/inheritance/singlediscgroup/zz_interfaces.go @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package singlediscgroup + +// BirdClassification provides polymorphic access to related types. +// Call the interface's GetBird() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *Bird, *Eagle, *Goose, *SeaGull, *Sparrow +type BirdClassification interface { + // GetBird returns the Bird content of the underlying type. + GetBird() *Bird +} + +// DinosaurClassification provides polymorphic access to related types. +// Call the interface's GetDinosaur() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *Dinosaur, *TRex +type DinosaurClassification interface { + // GetDinosaur returns the Dinosaur content of the underlying type. + GetDinosaur() *Dinosaur +} + +// FishClassification provides polymorphic access to related types. +// Call the interface's GetFish() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *Fish +type FishClassification interface { + // GetFish returns the Fish content of the underlying type. + GetFish() *Fish +} diff --git a/test/http-specs/type/model/inheritance/singlediscgroup/zz_models.go b/test/http-specs/type/model/inheritance/singlediscgroup/zz_models.go new file mode 100644 index 000000000000..7609ba18cfec --- /dev/null +++ b/test/http-specs/type/model/inheritance/singlediscgroup/zz_models.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package singlediscgroup + +// Bird - This is base model for polymorphic single level inheritance with a discriminator. +type Bird struct { + // REQUIRED + Kind *string + + // REQUIRED + Wingspan *int32 +} + +// GetBird implements the BirdClassification interface for type Bird. +func (b *Bird) GetBird() *Bird { return b } + +// Dinosaur - Define a base class in the legacy way. Discriminator property is not explicitly defined in the model. +type Dinosaur struct { + // REQUIRED; Discriminator property for Dinosaur. + Kind *string + + // REQUIRED + Size *int32 +} + +// GetDinosaur implements the DinosaurClassification interface for type Dinosaur. +func (d *Dinosaur) GetDinosaur() *Dinosaur { return d } + +// Eagle - The second level model in polymorphic single levels inheritance which contains references to other polymorphic +// instances. +type Eagle struct { + // CONSTANT; Field has constant value "eagle", any specified value is ignored. + Kind *string + + // REQUIRED + Wingspan *int32 + Friends []BirdClassification + Hate map[string]BirdClassification + Partner BirdClassification +} + +// GetBird implements the BirdClassification interface for type Eagle. +func (e *Eagle) GetBird() *Bird { + return &Bird{ + Kind: e.Kind, + Wingspan: e.Wingspan, + } +} + +// Fish - A discriminated model with no defined subtypes. The discriminator is declared but no models extend it. +type Fish struct { + // REQUIRED + Kind *string + + // REQUIRED + Size *int32 +} + +// GetFish implements the FishClassification interface for type Fish. +func (f *Fish) GetFish() *Fish { return f } + +// Goose - The second level model in polymorphic single level inheritance. +type Goose struct { + // CONSTANT; Field has constant value "goose", any specified value is ignored. + Kind *string + + // REQUIRED + Wingspan *int32 +} + +// GetBird implements the BirdClassification interface for type Goose. +func (g *Goose) GetBird() *Bird { + return &Bird{ + Kind: g.Kind, + Wingspan: g.Wingspan, + } +} + +// SeaGull - The second level model in polymorphic single level inheritance. +type SeaGull struct { + // CONSTANT; Field has constant value "seagull", any specified value is ignored. + Kind *string + + // REQUIRED + Wingspan *int32 +} + +// GetBird implements the BirdClassification interface for type SeaGull. +func (s *SeaGull) GetBird() *Bird { + return &Bird{ + Kind: s.Kind, + Wingspan: s.Wingspan, + } +} + +// Sparrow - The second level model in polymorphic single level inheritance. +type Sparrow struct { + // CONSTANT; Field has constant value "sparrow", any specified value is ignored. + Kind *string + + // REQUIRED + Wingspan *int32 +} + +// GetBird implements the BirdClassification interface for type Sparrow. +func (s *Sparrow) GetBird() *Bird { + return &Bird{ + Kind: s.Kind, + Wingspan: s.Wingspan, + } +} + +// TRex - The second level legacy model in polymorphic single level inheritance. +type TRex struct { + // REQUIRED + Kind *string + + // REQUIRED + Size *int32 +} + +// GetDinosaur implements the DinosaurClassification interface for type TRex. +func (t *TRex) GetDinosaur() *Dinosaur { + return &Dinosaur{ + Kind: t.Kind, + Size: t.Size, + } +} diff --git a/test/http-specs/type/model/inheritance/singlediscgroup/zz_models_serde.go b/test/http-specs/type/model/inheritance/singlediscgroup/zz_models_serde.go new file mode 100644 index 000000000000..e91f04a29815 --- /dev/null +++ b/test/http-specs/type/model/inheritance/singlediscgroup/zz_models_serde.go @@ -0,0 +1,292 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package singlediscgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type Bird. +func (b Bird) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "kind", b.Kind) + populate(objectMap, "wingspan", b.Wingspan) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Bird. +func (b *Bird) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &b.Kind) + delete(rawMsg, key) + case "wingspan": + err = unpopulate(val, "Wingspan", &b.Wingspan) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Dinosaur. +func (d Dinosaur) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "kind", d.Kind) + populate(objectMap, "size", d.Size) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Dinosaur. +func (d *Dinosaur) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &d.Kind) + delete(rawMsg, key) + case "size": + err = unpopulate(val, "Size", &d.Size) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Eagle. +func (e Eagle) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "friends", e.Friends) + populate(objectMap, "hate", e.Hate) + objectMap["kind"] = "eagle" + populate(objectMap, "partner", e.Partner) + populate(objectMap, "wingspan", e.Wingspan) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Eagle. +func (e *Eagle) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "friends": + e.Friends, err = unmarshalBirdClassificationArray(val) + delete(rawMsg, key) + case "hate": + e.Hate, err = unmarshalBirdClassificationMap(val) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &e.Kind) + delete(rawMsg, key) + case "partner": + e.Partner, err = unmarshalBirdClassification(val) + delete(rawMsg, key) + case "wingspan": + err = unpopulate(val, "Wingspan", &e.Wingspan) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Fish. +func (f Fish) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "kind", f.Kind) + populate(objectMap, "size", f.Size) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Fish. +func (f *Fish) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &f.Kind) + delete(rawMsg, key) + case "size": + err = unpopulate(val, "Size", &f.Size) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Goose. +func (g Goose) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["kind"] = "goose" + populate(objectMap, "wingspan", g.Wingspan) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Goose. +func (g *Goose) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &g.Kind) + delete(rawMsg, key) + case "wingspan": + err = unpopulate(val, "Wingspan", &g.Wingspan) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SeaGull. +func (s SeaGull) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["kind"] = "seagull" + populate(objectMap, "wingspan", s.Wingspan) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SeaGull. +func (s *SeaGull) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &s.Kind) + delete(rawMsg, key) + case "wingspan": + err = unpopulate(val, "Wingspan", &s.Wingspan) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Sparrow. +func (s Sparrow) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["kind"] = "sparrow" + populate(objectMap, "wingspan", s.Wingspan) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Sparrow. +func (s *Sparrow) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &s.Kind) + delete(rawMsg, key) + case "wingspan": + err = unpopulate(val, "Wingspan", &s.Wingspan) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TRex. +func (t TRex) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["kind"] = "t-rex" + populate(objectMap, "size", t.Size) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TRex. +func (t *TRex) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &t.Kind) + delete(rawMsg, key) + case "size": + err = unpopulate(val, "Size", &t.Size) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/http-specs/type/model/inheritance/singlediscgroup/zz_options.go b/test/http-specs/type/model/inheritance/singlediscgroup/zz_options.go new file mode 100644 index 000000000000..0c27906d33cb --- /dev/null +++ b/test/http-specs/type/model/inheritance/singlediscgroup/zz_options.go @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package singlediscgroup + +// SingleDiscriminatorClientGetLegacyModelOptions contains the optional parameters for the SingleDiscriminatorClient.GetLegacyModel +// method. +type SingleDiscriminatorClientGetLegacyModelOptions struct { + // placeholder for future optional parameters +} + +// SingleDiscriminatorClientGetMissingDiscriminatorOptions contains the optional parameters for the SingleDiscriminatorClient.GetMissingDiscriminator +// method. +type SingleDiscriminatorClientGetMissingDiscriminatorOptions struct { + // placeholder for future optional parameters +} + +// SingleDiscriminatorClientGetModelOptions contains the optional parameters for the SingleDiscriminatorClient.GetModel method. +type SingleDiscriminatorClientGetModelOptions struct { + // placeholder for future optional parameters +} + +// SingleDiscriminatorClientGetNoSubtypesModelOptions contains the optional parameters for the SingleDiscriminatorClient.GetNoSubtypesModel +// method. +type SingleDiscriminatorClientGetNoSubtypesModelOptions struct { + // placeholder for future optional parameters +} + +// SingleDiscriminatorClientGetRecursiveModelOptions contains the optional parameters for the SingleDiscriminatorClient.GetRecursiveModel +// method. +type SingleDiscriminatorClientGetRecursiveModelOptions struct { + // placeholder for future optional parameters +} + +// SingleDiscriminatorClientGetWrongDiscriminatorOptions contains the optional parameters for the SingleDiscriminatorClient.GetWrongDiscriminator +// method. +type SingleDiscriminatorClientGetWrongDiscriminatorOptions struct { + // placeholder for future optional parameters +} + +// SingleDiscriminatorClientPutModelOptions contains the optional parameters for the SingleDiscriminatorClient.PutModel method. +type SingleDiscriminatorClientPutModelOptions struct { + // placeholder for future optional parameters +} + +// SingleDiscriminatorClientPutNoSubtypesModelOptions contains the optional parameters for the SingleDiscriminatorClient.PutNoSubtypesModel +// method. +type SingleDiscriminatorClientPutNoSubtypesModelOptions struct { + // placeholder for future optional parameters +} + +// SingleDiscriminatorClientPutRecursiveModelOptions contains the optional parameters for the SingleDiscriminatorClient.PutRecursiveModel +// method. +type SingleDiscriminatorClientPutRecursiveModelOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/type/model/inheritance/singlediscgroup/zz_polymorphic_helpers.go b/test/http-specs/type/model/inheritance/singlediscgroup/zz_polymorphic_helpers.go new file mode 100644 index 000000000000..2783749e9916 --- /dev/null +++ b/test/http-specs/type/model/inheritance/singlediscgroup/zz_polymorphic_helpers.go @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package singlediscgroup + +import "encoding/json" + +func unmarshalBirdClassification(rawMsg json.RawMessage) (BirdClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b BirdClassification + switch m["kind"] { + case "eagle": + b = &Eagle{} + case "goose": + b = &Goose{} + case "seagull": + b = &SeaGull{} + case "sparrow": + b = &Sparrow{} + default: + b = &Bird{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} + +func unmarshalBirdClassificationArray(rawMsg json.RawMessage) ([]BirdClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]BirdClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalBirdClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalBirdClassificationMap(rawMsg json.RawMessage) (map[string]BirdClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var rawMessages map[string]json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fMap := make(map[string]BirdClassification, len(rawMessages)) + for key, rawMessage := range rawMessages { + f, err := unmarshalBirdClassification(rawMessage) + if err != nil { + return nil, err + } + fMap[key] = f + } + return fMap, nil +} + +func unmarshalDinosaurClassification(rawMsg json.RawMessage) (DinosaurClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b DinosaurClassification + switch m["kind"] { + case "t-rex": + b = &TRex{} + default: + b = &Dinosaur{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} + +func unmarshalFishClassification(rawMsg json.RawMessage) (FishClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b FishClassification + switch m["kind"] { + default: + b = &Fish{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} diff --git a/test/http-specs/type/model/inheritance/singlediscgroup/zz_responses.go b/test/http-specs/type/model/inheritance/singlediscgroup/zz_responses.go new file mode 100644 index 000000000000..1359129c2a9f --- /dev/null +++ b/test/http-specs/type/model/inheritance/singlediscgroup/zz_responses.go @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package singlediscgroup + +// SingleDiscriminatorClientGetLegacyModelResponse contains the response from method SingleDiscriminatorClient.GetLegacyModel. +type SingleDiscriminatorClientGetLegacyModelResponse struct { + // Define a base class in the legacy way. Discriminator property is not explicitly defined in the model. + DinosaurClassification +} + +// SingleDiscriminatorClientGetMissingDiscriminatorResponse contains the response from method SingleDiscriminatorClient.GetMissingDiscriminator. +type SingleDiscriminatorClientGetMissingDiscriminatorResponse struct { + // This is base model for polymorphic single level inheritance with a discriminator. + BirdClassification +} + +// SingleDiscriminatorClientGetModelResponse contains the response from method SingleDiscriminatorClient.GetModel. +type SingleDiscriminatorClientGetModelResponse struct { + // This is base model for polymorphic single level inheritance with a discriminator. + BirdClassification +} + +// SingleDiscriminatorClientGetNoSubtypesModelResponse contains the response from method SingleDiscriminatorClient.GetNoSubtypesModel. +type SingleDiscriminatorClientGetNoSubtypesModelResponse struct { + // A discriminated model with no defined subtypes. The discriminator is declared but no models extend it. + FishClassification +} + +// SingleDiscriminatorClientGetRecursiveModelResponse contains the response from method SingleDiscriminatorClient.GetRecursiveModel. +type SingleDiscriminatorClientGetRecursiveModelResponse struct { + // This is base model for polymorphic single level inheritance with a discriminator. + BirdClassification +} + +// SingleDiscriminatorClientGetWrongDiscriminatorResponse contains the response from method SingleDiscriminatorClient.GetWrongDiscriminator. +type SingleDiscriminatorClientGetWrongDiscriminatorResponse struct { + // This is base model for polymorphic single level inheritance with a discriminator. + BirdClassification +} + +// SingleDiscriminatorClientPutModelResponse contains the response from method SingleDiscriminatorClient.PutModel. +type SingleDiscriminatorClientPutModelResponse struct { + // placeholder for future response values +} + +// SingleDiscriminatorClientPutNoSubtypesModelResponse contains the response from method SingleDiscriminatorClient.PutNoSubtypesModel. +type SingleDiscriminatorClientPutNoSubtypesModelResponse struct { + // placeholder for future response values +} + +// SingleDiscriminatorClientPutRecursiveModelResponse contains the response from method SingleDiscriminatorClient.PutRecursiveModel. +type SingleDiscriminatorClientPutRecursiveModelResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/type/model/inheritance/singlediscgroup/zz_responses_serde.go b/test/http-specs/type/model/inheritance/singlediscgroup/zz_responses_serde.go new file mode 100644 index 000000000000..271b40b65f33 --- /dev/null +++ b/test/http-specs/type/model/inheritance/singlediscgroup/zz_responses_serde.go @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package singlediscgroup + +// UnmarshalJSON implements the json.Unmarshaller interface for type SingleDiscriminatorClientGetLegacyModelResponse. +func (s *SingleDiscriminatorClientGetLegacyModelResponse) UnmarshalJSON(data []byte) error { + res, err := unmarshalDinosaurClassification(data) + if err != nil { + return err + } + s.DinosaurClassification = res + return nil +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SingleDiscriminatorClientGetMissingDiscriminatorResponse. +func (s *SingleDiscriminatorClientGetMissingDiscriminatorResponse) UnmarshalJSON(data []byte) error { + res, err := unmarshalBirdClassification(data) + if err != nil { + return err + } + s.BirdClassification = res + return nil +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SingleDiscriminatorClientGetModelResponse. +func (s *SingleDiscriminatorClientGetModelResponse) UnmarshalJSON(data []byte) error { + res, err := unmarshalBirdClassification(data) + if err != nil { + return err + } + s.BirdClassification = res + return nil +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SingleDiscriminatorClientGetNoSubtypesModelResponse. +func (s *SingleDiscriminatorClientGetNoSubtypesModelResponse) UnmarshalJSON(data []byte) error { + res, err := unmarshalFishClassification(data) + if err != nil { + return err + } + s.FishClassification = res + return nil +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SingleDiscriminatorClientGetRecursiveModelResponse. +func (s *SingleDiscriminatorClientGetRecursiveModelResponse) UnmarshalJSON(data []byte) error { + res, err := unmarshalBirdClassification(data) + if err != nil { + return err + } + s.BirdClassification = res + return nil +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SingleDiscriminatorClientGetWrongDiscriminatorResponse. +func (s *SingleDiscriminatorClientGetWrongDiscriminatorResponse) UnmarshalJSON(data []byte) error { + res, err := unmarshalBirdClassification(data) + if err != nil { + return err + } + s.BirdClassification = res + return nil +} diff --git a/test/http-specs/type/model/inheritance/singlediscgroup/zz_singlediscriminator_client.go b/test/http-specs/type/model/inheritance/singlediscgroup/zz_singlediscriminator_client.go new file mode 100644 index 000000000000..13b972d02675 --- /dev/null +++ b/test/http-specs/type/model/inheritance/singlediscgroup/zz_singlediscriminator_client.go @@ -0,0 +1,436 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package singlediscgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// SingleDiscriminatorClient - Illustrates inheritance with single discriminator. +// Don't use this type directly, use NewSingleDiscriminatorClientWithNoCredential() instead. +type SingleDiscriminatorClient struct { + internal *azcore.Client + endpoint string +} + +// SingleDiscriminatorClientOptions contains the optional values for creating a [SingleDiscriminatorClient]. +type SingleDiscriminatorClientOptions struct { + azcore.ClientOptions +} + +// NewSingleDiscriminatorClientWithNoCredential creates a new instance of SingleDiscriminatorClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewSingleDiscriminatorClientWithNoCredential(endpoint string, options *SingleDiscriminatorClientOptions) (*SingleDiscriminatorClient, error) { + if options == nil { + options = &SingleDiscriminatorClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &SingleDiscriminatorClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// GetLegacyModel - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SingleDiscriminatorClientGetLegacyModelOptions contains the optional parameters for the SingleDiscriminatorClient.GetLegacyModel +// method. +func (client *SingleDiscriminatorClient) GetLegacyModel(ctx context.Context, options *SingleDiscriminatorClientGetLegacyModelOptions) (SingleDiscriminatorClientGetLegacyModelResponse, error) { + var err error + const operationName = "SingleDiscriminatorClient.GetLegacyModel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getLegacyModelCreateRequest(ctx, options) + if err != nil { + return SingleDiscriminatorClientGetLegacyModelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SingleDiscriminatorClientGetLegacyModelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SingleDiscriminatorClientGetLegacyModelResponse{}, err + } + resp, err := client.getLegacyModelHandleResponse(httpResp) + return resp, err +} + +// getLegacyModelCreateRequest creates the GetLegacyModel request. +func (client *SingleDiscriminatorClient) getLegacyModelCreateRequest(ctx context.Context, _ *SingleDiscriminatorClientGetLegacyModelOptions) (*policy.Request, error) { + urlPath := "/type/model/inheritance/single-discriminator/legacy-model" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getLegacyModelHandleResponse handles the GetLegacyModel response. +func (client *SingleDiscriminatorClient) getLegacyModelHandleResponse(resp *http.Response) (SingleDiscriminatorClientGetLegacyModelResponse, error) { + result := SingleDiscriminatorClientGetLegacyModelResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result); err != nil { + return SingleDiscriminatorClientGetLegacyModelResponse{}, err + } + return result, nil +} + +// GetMissingDiscriminator - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SingleDiscriminatorClientGetMissingDiscriminatorOptions contains the optional parameters for the SingleDiscriminatorClient.GetMissingDiscriminator +// method. +func (client *SingleDiscriminatorClient) GetMissingDiscriminator(ctx context.Context, options *SingleDiscriminatorClientGetMissingDiscriminatorOptions) (SingleDiscriminatorClientGetMissingDiscriminatorResponse, error) { + var err error + const operationName = "SingleDiscriminatorClient.GetMissingDiscriminator" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getMissingDiscriminatorCreateRequest(ctx, options) + if err != nil { + return SingleDiscriminatorClientGetMissingDiscriminatorResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SingleDiscriminatorClientGetMissingDiscriminatorResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SingleDiscriminatorClientGetMissingDiscriminatorResponse{}, err + } + resp, err := client.getMissingDiscriminatorHandleResponse(httpResp) + return resp, err +} + +// getMissingDiscriminatorCreateRequest creates the GetMissingDiscriminator request. +func (client *SingleDiscriminatorClient) getMissingDiscriminatorCreateRequest(ctx context.Context, _ *SingleDiscriminatorClientGetMissingDiscriminatorOptions) (*policy.Request, error) { + urlPath := "/type/model/inheritance/single-discriminator/missingdiscriminator" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getMissingDiscriminatorHandleResponse handles the GetMissingDiscriminator response. +func (client *SingleDiscriminatorClient) getMissingDiscriminatorHandleResponse(resp *http.Response) (SingleDiscriminatorClientGetMissingDiscriminatorResponse, error) { + result := SingleDiscriminatorClientGetMissingDiscriminatorResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result); err != nil { + return SingleDiscriminatorClientGetMissingDiscriminatorResponse{}, err + } + return result, nil +} + +// GetModel - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SingleDiscriminatorClientGetModelOptions contains the optional parameters for the SingleDiscriminatorClient.GetModel +// method. +func (client *SingleDiscriminatorClient) GetModel(ctx context.Context, options *SingleDiscriminatorClientGetModelOptions) (SingleDiscriminatorClientGetModelResponse, error) { + var err error + const operationName = "SingleDiscriminatorClient.GetModel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getModelCreateRequest(ctx, options) + if err != nil { + return SingleDiscriminatorClientGetModelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SingleDiscriminatorClientGetModelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SingleDiscriminatorClientGetModelResponse{}, err + } + resp, err := client.getModelHandleResponse(httpResp) + return resp, err +} + +// getModelCreateRequest creates the GetModel request. +func (client *SingleDiscriminatorClient) getModelCreateRequest(ctx context.Context, _ *SingleDiscriminatorClientGetModelOptions) (*policy.Request, error) { + urlPath := "/type/model/inheritance/single-discriminator/model" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getModelHandleResponse handles the GetModel response. +func (client *SingleDiscriminatorClient) getModelHandleResponse(resp *http.Response) (SingleDiscriminatorClientGetModelResponse, error) { + result := SingleDiscriminatorClientGetModelResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result); err != nil { + return SingleDiscriminatorClientGetModelResponse{}, err + } + return result, nil +} + +// GetNoSubtypesModel - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SingleDiscriminatorClientGetNoSubtypesModelOptions contains the optional parameters for the SingleDiscriminatorClient.GetNoSubtypesModel +// method. +func (client *SingleDiscriminatorClient) GetNoSubtypesModel(ctx context.Context, options *SingleDiscriminatorClientGetNoSubtypesModelOptions) (SingleDiscriminatorClientGetNoSubtypesModelResponse, error) { + var err error + const operationName = "SingleDiscriminatorClient.GetNoSubtypesModel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getNoSubtypesModelCreateRequest(ctx, options) + if err != nil { + return SingleDiscriminatorClientGetNoSubtypesModelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SingleDiscriminatorClientGetNoSubtypesModelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SingleDiscriminatorClientGetNoSubtypesModelResponse{}, err + } + resp, err := client.getNoSubtypesModelHandleResponse(httpResp) + return resp, err +} + +// getNoSubtypesModelCreateRequest creates the GetNoSubtypesModel request. +func (client *SingleDiscriminatorClient) getNoSubtypesModelCreateRequest(ctx context.Context, _ *SingleDiscriminatorClientGetNoSubtypesModelOptions) (*policy.Request, error) { + urlPath := "/type/model/inheritance/single-discriminator/no-subtypes/model" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getNoSubtypesModelHandleResponse handles the GetNoSubtypesModel response. +func (client *SingleDiscriminatorClient) getNoSubtypesModelHandleResponse(resp *http.Response) (SingleDiscriminatorClientGetNoSubtypesModelResponse, error) { + result := SingleDiscriminatorClientGetNoSubtypesModelResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result); err != nil { + return SingleDiscriminatorClientGetNoSubtypesModelResponse{}, err + } + return result, nil +} + +// GetRecursiveModel - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SingleDiscriminatorClientGetRecursiveModelOptions contains the optional parameters for the SingleDiscriminatorClient.GetRecursiveModel +// method. +func (client *SingleDiscriminatorClient) GetRecursiveModel(ctx context.Context, options *SingleDiscriminatorClientGetRecursiveModelOptions) (SingleDiscriminatorClientGetRecursiveModelResponse, error) { + var err error + const operationName = "SingleDiscriminatorClient.GetRecursiveModel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getRecursiveModelCreateRequest(ctx, options) + if err != nil { + return SingleDiscriminatorClientGetRecursiveModelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SingleDiscriminatorClientGetRecursiveModelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SingleDiscriminatorClientGetRecursiveModelResponse{}, err + } + resp, err := client.getRecursiveModelHandleResponse(httpResp) + return resp, err +} + +// getRecursiveModelCreateRequest creates the GetRecursiveModel request. +func (client *SingleDiscriminatorClient) getRecursiveModelCreateRequest(ctx context.Context, _ *SingleDiscriminatorClientGetRecursiveModelOptions) (*policy.Request, error) { + urlPath := "/type/model/inheritance/single-discriminator/recursivemodel" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getRecursiveModelHandleResponse handles the GetRecursiveModel response. +func (client *SingleDiscriminatorClient) getRecursiveModelHandleResponse(resp *http.Response) (SingleDiscriminatorClientGetRecursiveModelResponse, error) { + result := SingleDiscriminatorClientGetRecursiveModelResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result); err != nil { + return SingleDiscriminatorClientGetRecursiveModelResponse{}, err + } + return result, nil +} + +// GetWrongDiscriminator - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SingleDiscriminatorClientGetWrongDiscriminatorOptions contains the optional parameters for the SingleDiscriminatorClient.GetWrongDiscriminator +// method. +func (client *SingleDiscriminatorClient) GetWrongDiscriminator(ctx context.Context, options *SingleDiscriminatorClientGetWrongDiscriminatorOptions) (SingleDiscriminatorClientGetWrongDiscriminatorResponse, error) { + var err error + const operationName = "SingleDiscriminatorClient.GetWrongDiscriminator" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getWrongDiscriminatorCreateRequest(ctx, options) + if err != nil { + return SingleDiscriminatorClientGetWrongDiscriminatorResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SingleDiscriminatorClientGetWrongDiscriminatorResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SingleDiscriminatorClientGetWrongDiscriminatorResponse{}, err + } + resp, err := client.getWrongDiscriminatorHandleResponse(httpResp) + return resp, err +} + +// getWrongDiscriminatorCreateRequest creates the GetWrongDiscriminator request. +func (client *SingleDiscriminatorClient) getWrongDiscriminatorCreateRequest(ctx context.Context, _ *SingleDiscriminatorClientGetWrongDiscriminatorOptions) (*policy.Request, error) { + urlPath := "/type/model/inheritance/single-discriminator/wrongdiscriminator" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getWrongDiscriminatorHandleResponse handles the GetWrongDiscriminator response. +func (client *SingleDiscriminatorClient) getWrongDiscriminatorHandleResponse(resp *http.Response) (SingleDiscriminatorClientGetWrongDiscriminatorResponse, error) { + result := SingleDiscriminatorClientGetWrongDiscriminatorResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result); err != nil { + return SingleDiscriminatorClientGetWrongDiscriminatorResponse{}, err + } + return result, nil +} + +// PutModel - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SingleDiscriminatorClientPutModelOptions contains the optional parameters for the SingleDiscriminatorClient.PutModel +// method. +func (client *SingleDiscriminatorClient) PutModel(ctx context.Context, input BirdClassification, options *SingleDiscriminatorClientPutModelOptions) (SingleDiscriminatorClientPutModelResponse, error) { + var err error + const operationName = "SingleDiscriminatorClient.PutModel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putModelCreateRequest(ctx, input, options) + if err != nil { + return SingleDiscriminatorClientPutModelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SingleDiscriminatorClientPutModelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SingleDiscriminatorClientPutModelResponse{}, err + } + return SingleDiscriminatorClientPutModelResponse{}, nil +} + +// putModelCreateRequest creates the PutModel request. +func (client *SingleDiscriminatorClient) putModelCreateRequest(ctx context.Context, input BirdClassification, _ *SingleDiscriminatorClientPutModelOptions) (*policy.Request, error) { + urlPath := "/type/model/inheritance/single-discriminator/model" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, input); err != nil { + return nil, err + } + return req, nil +} + +// PutNoSubtypesModel - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SingleDiscriminatorClientPutNoSubtypesModelOptions contains the optional parameters for the SingleDiscriminatorClient.PutNoSubtypesModel +// method. +func (client *SingleDiscriminatorClient) PutNoSubtypesModel(ctx context.Context, input FishClassification, options *SingleDiscriminatorClientPutNoSubtypesModelOptions) (SingleDiscriminatorClientPutNoSubtypesModelResponse, error) { + var err error + const operationName = "SingleDiscriminatorClient.PutNoSubtypesModel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putNoSubtypesModelCreateRequest(ctx, input, options) + if err != nil { + return SingleDiscriminatorClientPutNoSubtypesModelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SingleDiscriminatorClientPutNoSubtypesModelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SingleDiscriminatorClientPutNoSubtypesModelResponse{}, err + } + return SingleDiscriminatorClientPutNoSubtypesModelResponse{}, nil +} + +// putNoSubtypesModelCreateRequest creates the PutNoSubtypesModel request. +func (client *SingleDiscriminatorClient) putNoSubtypesModelCreateRequest(ctx context.Context, input FishClassification, _ *SingleDiscriminatorClientPutNoSubtypesModelOptions) (*policy.Request, error) { + urlPath := "/type/model/inheritance/single-discriminator/no-subtypes/model" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, input); err != nil { + return nil, err + } + return req, nil +} + +// PutRecursiveModel - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SingleDiscriminatorClientPutRecursiveModelOptions contains the optional parameters for the SingleDiscriminatorClient.PutRecursiveModel +// method. +func (client *SingleDiscriminatorClient) PutRecursiveModel(ctx context.Context, input BirdClassification, options *SingleDiscriminatorClientPutRecursiveModelOptions) (SingleDiscriminatorClientPutRecursiveModelResponse, error) { + var err error + const operationName = "SingleDiscriminatorClient.PutRecursiveModel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putRecursiveModelCreateRequest(ctx, input, options) + if err != nil { + return SingleDiscriminatorClientPutRecursiveModelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SingleDiscriminatorClientPutRecursiveModelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SingleDiscriminatorClientPutRecursiveModelResponse{}, err + } + return SingleDiscriminatorClientPutRecursiveModelResponse{}, nil +} + +// putRecursiveModelCreateRequest creates the PutRecursiveModel request. +func (client *SingleDiscriminatorClient) putRecursiveModelCreateRequest(ctx context.Context, input BirdClassification, _ *SingleDiscriminatorClientPutRecursiveModelOptions) (*policy.Request, error) { + urlPath := "/type/model/inheritance/single-discriminator/recursivemodel" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, input); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/model/inheritance/singlediscgroup/zz_version.go b/test/http-specs/type/model/inheritance/singlediscgroup/zz_version.go new file mode 100644 index 000000000000..ba32b27c685e --- /dev/null +++ b/test/http-specs/type/model/inheritance/singlediscgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package singlediscgroup + +const ( + moduleName = "singlediscgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/type/model/usagegroup/LICENSE.txt b/test/http-specs/type/model/usagegroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/type/model/usagegroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/type/model/usagegroup/fake/zz_internal.go b/test/http-specs/type/model/usagegroup/fake/zz_internal.go new file mode 100644 index 000000000000..705f81eacafe --- /dev/null +++ b/test/http-specs/type/model/usagegroup/fake/zz_internal.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import "net/http" + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} diff --git a/test/http-specs/type/model/usagegroup/fake/zz_usage_server.go b/test/http-specs/type/model/usagegroup/fake/zz_usage_server.go new file mode 100644 index 000000000000..8fb4ba80ee5b --- /dev/null +++ b/test/http-specs/type/model/usagegroup/fake/zz_usage_server.go @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "usagegroup" +) + +// UsageServer is a fake server for instances of the usagegroup.UsageClient type. +type UsageServer struct { + // Input is the fake for method UsageClient.Input + // HTTP status codes to indicate success: http.StatusNoContent + Input func(ctx context.Context, input usagegroup.InputRecord, options *usagegroup.UsageClientInputOptions) (resp azfake.Responder[usagegroup.UsageClientInputResponse], errResp azfake.ErrorResponder) + + // InputAndOutput is the fake for method UsageClient.InputAndOutput + // HTTP status codes to indicate success: http.StatusOK + InputAndOutput func(ctx context.Context, body usagegroup.InputOutputRecord, options *usagegroup.UsageClientInputAndOutputOptions) (resp azfake.Responder[usagegroup.UsageClientInputAndOutputResponse], errResp azfake.ErrorResponder) + + // Output is the fake for method UsageClient.Output + // HTTP status codes to indicate success: http.StatusOK + Output func(ctx context.Context, options *usagegroup.UsageClientOutputOptions) (resp azfake.Responder[usagegroup.UsageClientOutputResponse], errResp azfake.ErrorResponder) +} + +// NewUsageServerTransport creates a new instance of UsageServerTransport with the provided implementation. +// The returned UsageServerTransport instance is connected to an instance of usagegroup.UsageClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewUsageServerTransport(srv *UsageServer) *UsageServerTransport { + return &UsageServerTransport{srv: srv} +} + +// UsageServerTransport connects instances of usagegroup.UsageClient to instances of UsageServer. +// Don't use this type directly, use NewUsageServerTransport instead. +type UsageServerTransport struct { + srv *UsageServer +} + +// Do implements the policy.Transporter interface for UsageServerTransport. +func (u *UsageServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return u.dispatchToMethodFake(req, method) +} + +func (u *UsageServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if usageServerTransportInterceptor != nil { + res.resp, res.err, intercepted = usageServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "UsageClient.Input": + res.resp, res.err = u.dispatchInput(req) + case "UsageClient.InputAndOutput": + res.resp, res.err = u.dispatchInputAndOutput(req) + case "UsageClient.Output": + res.resp, res.err = u.dispatchOutput(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (u *UsageServerTransport) dispatchInput(req *http.Request) (*http.Response, error) { + if u.srv.Input == nil { + return nil, &nonRetriableError{errors.New("fake for method Input not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[usagegroup.InputRecord](req) + if err != nil { + return nil, err + } + respr, errRespr := u.srv.Input(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (u *UsageServerTransport) dispatchInputAndOutput(req *http.Request) (*http.Response, error) { + if u.srv.InputAndOutput == nil { + return nil, &nonRetriableError{errors.New("fake for method InputAndOutput not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[usagegroup.InputOutputRecord](req) + if err != nil { + return nil, err + } + respr, errRespr := u.srv.InputAndOutput(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).InputOutputRecord, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (u *UsageServerTransport) dispatchOutput(req *http.Request) (*http.Response, error) { + if u.srv.Output == nil { + return nil, &nonRetriableError{errors.New("fake for method Output not implemented")} + } + respr, errRespr := u.srv.Output(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).OutputRecord, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to UsageServerTransport +var usageServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/model/usagegroup/go.mod b/test/http-specs/type/model/usagegroup/go.mod new file mode 100644 index 000000000000..831c13074942 --- /dev/null +++ b/test/http-specs/type/model/usagegroup/go.mod @@ -0,0 +1,17 @@ +module usagegroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/type/model/usagegroup/go.sum b/test/http-specs/type/model/usagegroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/type/model/usagegroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/type/model/usagegroup/testdata/_metadata.json b/test/http-specs/type/model/usagegroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/type/model/usagegroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/type/model/usagegroup/usage_client_test.go b/test/http-specs/type/model/usagegroup/usage_client_test.go new file mode 100644 index 000000000000..957bf5dba3da --- /dev/null +++ b/test/http-specs/type/model/usagegroup/usage_client_test.go @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package usagegroup_test + +import ( + "context" + "testing" + "usagegroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestUsageClientInput(t *testing.T) { + client, err := usagegroup.NewUsageClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.Input(context.Background(), usagegroup.InputRecord{ + RequiredProp: to.Ptr("example-value"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestUsageClientInputAndOutput(t *testing.T) { + client, err := usagegroup.NewUsageClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.InputAndOutput(context.Background(), usagegroup.InputOutputRecord{ + RequiredProp: to.Ptr("example-value"), + }, nil) + require.NoError(t, err) + require.NotNil(t, resp.RequiredProp) + require.EqualValues(t, "example-value", *resp.RequiredProp) +} + +func TestUsageClientOutput(t *testing.T) { + client, err := usagegroup.NewUsageClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.Output(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.RequiredProp) + require.EqualValues(t, "example-value", *resp.RequiredProp) +} diff --git a/test/http-specs/type/model/usagegroup/zz_models.go b/test/http-specs/type/model/usagegroup/zz_models.go new file mode 100644 index 000000000000..ad74da652c5f --- /dev/null +++ b/test/http-specs/type/model/usagegroup/zz_models.go @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package usagegroup + +// InputOutputRecord - Record used both as operation parameter and return type +type InputOutputRecord struct { + // REQUIRED + RequiredProp *string +} + +// InputRecord - Record used in operation parameters +type InputRecord struct { + // REQUIRED + RequiredProp *string +} + +// OutputRecord - Record used in operation return type +type OutputRecord struct { + // REQUIRED + RequiredProp *string +} diff --git a/test/http-specs/type/model/usagegroup/zz_models_serde.go b/test/http-specs/type/model/usagegroup/zz_models_serde.go new file mode 100644 index 000000000000..5be4b2995f68 --- /dev/null +++ b/test/http-specs/type/model/usagegroup/zz_models_serde.go @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package usagegroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type InputOutputRecord. +func (i InputOutputRecord) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "requiredProp", i.RequiredProp) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InputOutputRecord. +func (i *InputOutputRecord) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "requiredProp": + err = unpopulate(val, "RequiredProp", &i.RequiredProp) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type InputRecord. +func (i InputRecord) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "requiredProp", i.RequiredProp) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InputRecord. +func (i *InputRecord) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "requiredProp": + err = unpopulate(val, "RequiredProp", &i.RequiredProp) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OutputRecord. +func (o OutputRecord) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "requiredProp", o.RequiredProp) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OutputRecord. +func (o *OutputRecord) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "requiredProp": + err = unpopulate(val, "RequiredProp", &o.RequiredProp) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/http-specs/type/model/usagegroup/zz_options.go b/test/http-specs/type/model/usagegroup/zz_options.go new file mode 100644 index 000000000000..aad621b30072 --- /dev/null +++ b/test/http-specs/type/model/usagegroup/zz_options.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package usagegroup + +// UsageClientInputAndOutputOptions contains the optional parameters for the UsageClient.InputAndOutput method. +type UsageClientInputAndOutputOptions struct { + // placeholder for future optional parameters +} + +// UsageClientInputOptions contains the optional parameters for the UsageClient.Input method. +type UsageClientInputOptions struct { + // placeholder for future optional parameters +} + +// UsageClientOutputOptions contains the optional parameters for the UsageClient.Output method. +type UsageClientOutputOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/type/model/usagegroup/zz_responses.go b/test/http-specs/type/model/usagegroup/zz_responses.go new file mode 100644 index 000000000000..03cbf3fb5ac9 --- /dev/null +++ b/test/http-specs/type/model/usagegroup/zz_responses.go @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package usagegroup + +// UsageClientInputAndOutputResponse contains the response from method UsageClient.InputAndOutput. +type UsageClientInputAndOutputResponse struct { + // Record used both as operation parameter and return type + InputOutputRecord +} + +// UsageClientInputResponse contains the response from method UsageClient.Input. +type UsageClientInputResponse struct { + // placeholder for future response values +} + +// UsageClientOutputResponse contains the response from method UsageClient.Output. +type UsageClientOutputResponse struct { + // Record used in operation return type + OutputRecord +} diff --git a/test/http-specs/type/model/usagegroup/zz_usage_client.go b/test/http-specs/type/model/usagegroup/zz_usage_client.go new file mode 100644 index 000000000000..5c37b5e3690d --- /dev/null +++ b/test/http-specs/type/model/usagegroup/zz_usage_client.go @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package usagegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// UsageClient - Illustrates usage of Record in different places(Operation parameters, return type or both). +// Don't use this type directly, use NewUsageClientWithNoCredential() instead. +type UsageClient struct { + internal *azcore.Client + endpoint string +} + +// UsageClientOptions contains the optional values for creating a [UsageClient]. +type UsageClientOptions struct { + azcore.ClientOptions +} + +// NewUsageClientWithNoCredential creates a new instance of UsageClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewUsageClientWithNoCredential(endpoint string, options *UsageClientOptions) (*UsageClient, error) { + if options == nil { + options = &UsageClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &UsageClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// Input - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - UsageClientInputOptions contains the optional parameters for the UsageClient.Input method. +func (client *UsageClient) Input(ctx context.Context, input InputRecord, options *UsageClientInputOptions) (UsageClientInputResponse, error) { + var err error + const operationName = "UsageClient.Input" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.inputCreateRequest(ctx, input, options) + if err != nil { + return UsageClientInputResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return UsageClientInputResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return UsageClientInputResponse{}, err + } + return UsageClientInputResponse{}, nil +} + +// inputCreateRequest creates the Input request. +func (client *UsageClient) inputCreateRequest(ctx context.Context, input InputRecord, _ *UsageClientInputOptions) (*policy.Request, error) { + urlPath := "/type/model/usage/input" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, input); err != nil { + return nil, err + } + return req, nil +} + +// InputAndOutput - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - UsageClientInputAndOutputOptions contains the optional parameters for the UsageClient.InputAndOutput method. +func (client *UsageClient) InputAndOutput(ctx context.Context, body InputOutputRecord, options *UsageClientInputAndOutputOptions) (UsageClientInputAndOutputResponse, error) { + var err error + const operationName = "UsageClient.InputAndOutput" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.inputAndOutputCreateRequest(ctx, body, options) + if err != nil { + return UsageClientInputAndOutputResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return UsageClientInputAndOutputResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return UsageClientInputAndOutputResponse{}, err + } + resp, err := client.inputAndOutputHandleResponse(httpResp) + return resp, err +} + +// inputAndOutputCreateRequest creates the InputAndOutput request. +func (client *UsageClient) inputAndOutputCreateRequest(ctx context.Context, body InputOutputRecord, _ *UsageClientInputAndOutputOptions) (*policy.Request, error) { + urlPath := "/type/model/usage/input-output" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// inputAndOutputHandleResponse handles the InputAndOutput response. +func (client *UsageClient) inputAndOutputHandleResponse(resp *http.Response) (UsageClientInputAndOutputResponse, error) { + result := UsageClientInputAndOutputResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.InputOutputRecord); err != nil { + return UsageClientInputAndOutputResponse{}, err + } + return result, nil +} + +// Output - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - UsageClientOutputOptions contains the optional parameters for the UsageClient.Output method. +func (client *UsageClient) Output(ctx context.Context, options *UsageClientOutputOptions) (UsageClientOutputResponse, error) { + var err error + const operationName = "UsageClient.Output" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.outputCreateRequest(ctx, options) + if err != nil { + return UsageClientOutputResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return UsageClientOutputResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return UsageClientOutputResponse{}, err + } + resp, err := client.outputHandleResponse(httpResp) + return resp, err +} + +// outputCreateRequest creates the Output request. +func (client *UsageClient) outputCreateRequest(ctx context.Context, _ *UsageClientOutputOptions) (*policy.Request, error) { + urlPath := "/type/model/usage/output" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// outputHandleResponse handles the Output response. +func (client *UsageClient) outputHandleResponse(resp *http.Response) (UsageClientOutputResponse, error) { + result := UsageClientOutputResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OutputRecord); err != nil { + return UsageClientOutputResponse{}, err + } + return result, nil +} diff --git a/test/http-specs/type/model/usagegroup/zz_version.go b/test/http-specs/type/model/usagegroup/zz_version.go new file mode 100644 index 000000000000..29ca12c8e288 --- /dev/null +++ b/test/http-specs/type/model/usagegroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package usagegroup + +const ( + moduleName = "usagegroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/type/model/visibilitygroup/LICENSE.txt b/test/http-specs/type/model/visibilitygroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/type/model/visibilitygroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/type/model/visibilitygroup/fake/zz_internal.go b/test/http-specs/type/model/visibilitygroup/fake/zz_internal.go new file mode 100644 index 000000000000..30e0a51be6ee --- /dev/null +++ b/test/http-specs/type/model/visibilitygroup/fake/zz_internal.go @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import "net/http" + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func parseWithCast[T any](v string, parse func(v string) (T, error)) (T, error) { + t, err := parse(v) + if err != nil { + return *new(T), err + } + return t, err +} diff --git a/test/http-specs/type/model/visibilitygroup/fake/zz_visibility_server.go b/test/http-specs/type/model/visibilitygroup/fake/zz_visibility_server.go new file mode 100644 index 000000000000..339de8edde8a --- /dev/null +++ b/test/http-specs/type/model/visibilitygroup/fake/zz_visibility_server.go @@ -0,0 +1,294 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "strconv" + "visibilitygroup" +) + +// VisibilityServer is a fake server for instances of the visibilitygroup.VisibilityClient type. +type VisibilityServer struct { + // DeleteModel is the fake for method VisibilityClient.DeleteModel + // HTTP status codes to indicate success: http.StatusNoContent + DeleteModel func(ctx context.Context, input visibilitygroup.VisibilityModel, options *visibilitygroup.VisibilityClientDeleteModelOptions) (resp azfake.Responder[visibilitygroup.VisibilityClientDeleteModelResponse], errResp azfake.ErrorResponder) + + // GetModel is the fake for method VisibilityClient.GetModel + // HTTP status codes to indicate success: http.StatusOK + GetModel func(ctx context.Context, queryProp int32, options *visibilitygroup.VisibilityClientGetModelOptions) (resp azfake.Responder[visibilitygroup.VisibilityClientGetModelResponse], errResp azfake.ErrorResponder) + + // HeadModel is the fake for method VisibilityClient.HeadModel + // HTTP status codes to indicate success: http.StatusOK + HeadModel func(ctx context.Context, queryProp int32, options *visibilitygroup.VisibilityClientHeadModelOptions) (resp azfake.Responder[visibilitygroup.VisibilityClientHeadModelResponse], errResp azfake.ErrorResponder) + + // PatchModel is the fake for method VisibilityClient.PatchModel + // HTTP status codes to indicate success: http.StatusNoContent + PatchModel func(ctx context.Context, input visibilitygroup.VisibilityModel, options *visibilitygroup.VisibilityClientPatchModelOptions) (resp azfake.Responder[visibilitygroup.VisibilityClientPatchModelResponse], errResp azfake.ErrorResponder) + + // PostModel is the fake for method VisibilityClient.PostModel + // HTTP status codes to indicate success: http.StatusNoContent + PostModel func(ctx context.Context, input visibilitygroup.VisibilityModel, options *visibilitygroup.VisibilityClientPostModelOptions) (resp azfake.Responder[visibilitygroup.VisibilityClientPostModelResponse], errResp azfake.ErrorResponder) + + // PutModel is the fake for method VisibilityClient.PutModel + // HTTP status codes to indicate success: http.StatusNoContent + PutModel func(ctx context.Context, input visibilitygroup.VisibilityModel, options *visibilitygroup.VisibilityClientPutModelOptions) (resp azfake.Responder[visibilitygroup.VisibilityClientPutModelResponse], errResp azfake.ErrorResponder) + + // PutReadOnlyModel is the fake for method VisibilityClient.PutReadOnlyModel + // HTTP status codes to indicate success: http.StatusOK + PutReadOnlyModel func(ctx context.Context, input visibilitygroup.ReadOnlyModel, options *visibilitygroup.VisibilityClientPutReadOnlyModelOptions) (resp azfake.Responder[visibilitygroup.VisibilityClientPutReadOnlyModelResponse], errResp azfake.ErrorResponder) +} + +// NewVisibilityServerTransport creates a new instance of VisibilityServerTransport with the provided implementation. +// The returned VisibilityServerTransport instance is connected to an instance of visibilitygroup.VisibilityClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewVisibilityServerTransport(srv *VisibilityServer) *VisibilityServerTransport { + return &VisibilityServerTransport{srv: srv} +} + +// VisibilityServerTransport connects instances of visibilitygroup.VisibilityClient to instances of VisibilityServer. +// Don't use this type directly, use NewVisibilityServerTransport instead. +type VisibilityServerTransport struct { + srv *VisibilityServer +} + +// Do implements the policy.Transporter interface for VisibilityServerTransport. +func (v *VisibilityServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *VisibilityServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if visibilityServerTransportInterceptor != nil { + res.resp, res.err, intercepted = visibilityServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "VisibilityClient.DeleteModel": + res.resp, res.err = v.dispatchDeleteModel(req) + case "VisibilityClient.GetModel": + res.resp, res.err = v.dispatchGetModel(req) + case "VisibilityClient.HeadModel": + res.resp, res.err = v.dispatchHeadModel(req) + case "VisibilityClient.PatchModel": + res.resp, res.err = v.dispatchPatchModel(req) + case "VisibilityClient.PostModel": + res.resp, res.err = v.dispatchPostModel(req) + case "VisibilityClient.PutModel": + res.resp, res.err = v.dispatchPutModel(req) + case "VisibilityClient.PutReadOnlyModel": + res.resp, res.err = v.dispatchPutReadOnlyModel(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *VisibilityServerTransport) dispatchDeleteModel(req *http.Request) (*http.Response, error) { + if v.srv.DeleteModel == nil { + return nil, &nonRetriableError{errors.New("fake for method DeleteModel not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[visibilitygroup.VisibilityModel](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.DeleteModel(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *VisibilityServerTransport) dispatchGetModel(req *http.Request) (*http.Response, error) { + if v.srv.GetModel == nil { + return nil, &nonRetriableError{errors.New("fake for method GetModel not implemented")} + } + qp := req.URL.Query() + queryPropParam, err := parseWithCast(qp.Get("queryProp"), func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.GetModel(req.Context(), queryPropParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).VisibilityModel, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *VisibilityServerTransport) dispatchHeadModel(req *http.Request) (*http.Response, error) { + if v.srv.HeadModel == nil { + return nil, &nonRetriableError{errors.New("fake for method HeadModel not implemented")} + } + qp := req.URL.Query() + queryPropParam, err := parseWithCast(qp.Get("queryProp"), func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.HeadModel(req.Context(), queryPropParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *VisibilityServerTransport) dispatchPatchModel(req *http.Request) (*http.Response, error) { + if v.srv.PatchModel == nil { + return nil, &nonRetriableError{errors.New("fake for method PatchModel not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[visibilitygroup.VisibilityModel](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.PatchModel(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *VisibilityServerTransport) dispatchPostModel(req *http.Request) (*http.Response, error) { + if v.srv.PostModel == nil { + return nil, &nonRetriableError{errors.New("fake for method PostModel not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[visibilitygroup.VisibilityModel](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.PostModel(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *VisibilityServerTransport) dispatchPutModel(req *http.Request) (*http.Response, error) { + if v.srv.PutModel == nil { + return nil, &nonRetriableError{errors.New("fake for method PutModel not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[visibilitygroup.VisibilityModel](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.PutModel(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *VisibilityServerTransport) dispatchPutReadOnlyModel(req *http.Request) (*http.Response, error) { + if v.srv.PutReadOnlyModel == nil { + return nil, &nonRetriableError{errors.New("fake for method PutReadOnlyModel not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[visibilitygroup.ReadOnlyModel](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.PutReadOnlyModel(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ReadOnlyModel, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to VisibilityServerTransport +var visibilityServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/model/visibilitygroup/go.mod b/test/http-specs/type/model/visibilitygroup/go.mod new file mode 100644 index 000000000000..3f749b167aa8 --- /dev/null +++ b/test/http-specs/type/model/visibilitygroup/go.mod @@ -0,0 +1,17 @@ +module visibilitygroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/type/model/visibilitygroup/go.sum b/test/http-specs/type/model/visibilitygroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/type/model/visibilitygroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/type/model/visibilitygroup/testdata/_metadata.json b/test/http-specs/type/model/visibilitygroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/type/model/visibilitygroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/type/model/visibilitygroup/visibility_client_test.go b/test/http-specs/type/model/visibilitygroup/visibility_client_test.go new file mode 100644 index 000000000000..382052d31e0b --- /dev/null +++ b/test/http-specs/type/model/visibilitygroup/visibility_client_test.go @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package visibilitygroup_test + +import ( + "context" + "testing" + "visibilitygroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestVisibilityClientDeleteModel(t *testing.T) { + client, err := visibilitygroup.NewVisibilityClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.DeleteModel(context.Background(), visibilitygroup.VisibilityModel{ + DeleteProp: to.Ptr(true), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestVisibilityClientGetModel(t *testing.T) { + client, err := visibilitygroup.NewVisibilityClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.GetModel(context.Background(), 123, nil) + require.NoError(t, err) + require.EqualValues(t, visibilitygroup.VisibilityModel{ + ReadProp: to.Ptr("abc"), + }, resp.VisibilityModel) +} + +func TestVisibilityClientHeadModel(t *testing.T) { + client, err := visibilitygroup.NewVisibilityClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.HeadModel(context.Background(), 123, nil) + require.NoError(t, err) + require.True(t, resp.Success) +} + +func TestVisibilityClientPatchModel(t *testing.T) { + client, err := visibilitygroup.NewVisibilityClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.PatchModel(context.Background(), visibilitygroup.VisibilityModel{ + UpdateProp: []*int32{ + to.Ptr[int32](1), + to.Ptr[int32](2), + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestVisibilityClientPostModel(t *testing.T) { + client, err := visibilitygroup.NewVisibilityClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.PostModel(context.Background(), visibilitygroup.VisibilityModel{ + CreateProp: []*string{ + to.Ptr("foo"), + to.Ptr("bar"), + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestVisibilityClientPutModel(t *testing.T) { + client, err := visibilitygroup.NewVisibilityClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.PutModel(context.Background(), visibilitygroup.VisibilityModel{ + CreateProp: []*string{ + to.Ptr("foo"), + to.Ptr("bar"), + }, + UpdateProp: []*int32{ + to.Ptr[int32](1), + to.Ptr[int32](2), + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestVisibilityClientPutReadOnlyModel(t *testing.T) { + client, err := visibilitygroup.NewVisibilityClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.PutReadOnlyModel(context.Background(), visibilitygroup.ReadOnlyModel{}, nil) + require.NoError(t, err) + expect := visibilitygroup.ReadOnlyModel{ + OptionalNullableIntList: []*int32{ + to.Ptr[int32](1), + to.Ptr[int32](2), + to.Ptr[int32](3), + }, + OptionalStringRecord: map[string]*string{ + "k1": to.Ptr("value1"), + "k2": to.Ptr("value2"), + }, + } + require.EqualValues(t, expect, resp.ReadOnlyModel) +} diff --git a/test/http-specs/type/model/visibilitygroup/zz_models.go b/test/http-specs/type/model/visibilitygroup/zz_models.go new file mode 100644 index 000000000000..f01938998736 --- /dev/null +++ b/test/http-specs/type/model/visibilitygroup/zz_models.go @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package visibilitygroup + +// ReadOnlyModel - RoundTrip model with readonly optional properties. +type ReadOnlyModel struct { + // READ-ONLY; Optional readonly nullable int list. + OptionalNullableIntList []*int32 + + // READ-ONLY; Optional readonly string dictionary. + OptionalStringRecord map[string]*string +} + +// VisibilityModel - Output model with visibility properties. +type VisibilityModel struct { + // REQUIRED; Required string[], illustrating a create property. + CreateProp []*string + + // REQUIRED; Required bool, illustrating a delete property. + DeleteProp *bool + + // REQUIRED; Required int32[], illustrating a update property. + UpdateProp []*int32 + + // READ-ONLY; Required string, illustrating a readonly property. + ReadProp *string +} diff --git a/test/http-specs/type/model/visibilitygroup/zz_models_serde.go b/test/http-specs/type/model/visibilitygroup/zz_models_serde.go new file mode 100644 index 000000000000..3610cb980950 --- /dev/null +++ b/test/http-specs/type/model/visibilitygroup/zz_models_serde.go @@ -0,0 +1,102 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package visibilitygroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type ReadOnlyModel. +func (r ReadOnlyModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "optionalNullableIntList", r.OptionalNullableIntList) + populate(objectMap, "optionalStringRecord", r.OptionalStringRecord) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ReadOnlyModel. +func (r *ReadOnlyModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "optionalNullableIntList": + err = unpopulate(val, "OptionalNullableIntList", &r.OptionalNullableIntList) + delete(rawMsg, key) + case "optionalStringRecord": + err = unpopulate(val, "OptionalStringRecord", &r.OptionalStringRecord) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VisibilityModel. +func (v VisibilityModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "createProp", v.CreateProp) + populate(objectMap, "deleteProp", v.DeleteProp) + populate(objectMap, "readProp", v.ReadProp) + populate(objectMap, "updateProp", v.UpdateProp) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VisibilityModel. +func (v *VisibilityModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createProp": + err = unpopulate(val, "CreateProp", &v.CreateProp) + delete(rawMsg, key) + case "deleteProp": + err = unpopulate(val, "DeleteProp", &v.DeleteProp) + delete(rawMsg, key) + case "readProp": + err = unpopulate(val, "ReadProp", &v.ReadProp) + delete(rawMsg, key) + case "updateProp": + err = unpopulate(val, "UpdateProp", &v.UpdateProp) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/http-specs/type/model/visibilitygroup/zz_options.go b/test/http-specs/type/model/visibilitygroup/zz_options.go new file mode 100644 index 000000000000..a0f28263ee03 --- /dev/null +++ b/test/http-specs/type/model/visibilitygroup/zz_options.go @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package visibilitygroup + +// VisibilityClientDeleteModelOptions contains the optional parameters for the VisibilityClient.DeleteModel method. +type VisibilityClientDeleteModelOptions struct { + // placeholder for future optional parameters +} + +// VisibilityClientGetModelOptions contains the optional parameters for the VisibilityClient.GetModel method. +type VisibilityClientGetModelOptions struct { + // placeholder for future optional parameters +} + +// VisibilityClientHeadModelOptions contains the optional parameters for the VisibilityClient.HeadModel method. +type VisibilityClientHeadModelOptions struct { + // placeholder for future optional parameters +} + +// VisibilityClientPatchModelOptions contains the optional parameters for the VisibilityClient.PatchModel method. +type VisibilityClientPatchModelOptions struct { + // placeholder for future optional parameters +} + +// VisibilityClientPostModelOptions contains the optional parameters for the VisibilityClient.PostModel method. +type VisibilityClientPostModelOptions struct { + // placeholder for future optional parameters +} + +// VisibilityClientPutModelOptions contains the optional parameters for the VisibilityClient.PutModel method. +type VisibilityClientPutModelOptions struct { + // placeholder for future optional parameters +} + +// VisibilityClientPutReadOnlyModelOptions contains the optional parameters for the VisibilityClient.PutReadOnlyModel method. +type VisibilityClientPutReadOnlyModelOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/type/model/visibilitygroup/zz_responses.go b/test/http-specs/type/model/visibilitygroup/zz_responses.go new file mode 100644 index 000000000000..c971c88d9511 --- /dev/null +++ b/test/http-specs/type/model/visibilitygroup/zz_responses.go @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package visibilitygroup + +// VisibilityClientDeleteModelResponse contains the response from method VisibilityClient.DeleteModel. +type VisibilityClientDeleteModelResponse struct { + // placeholder for future response values +} + +// VisibilityClientGetModelResponse contains the response from method VisibilityClient.GetModel. +type VisibilityClientGetModelResponse struct { + // Output model with visibility properties. + VisibilityModel +} + +// VisibilityClientHeadModelResponse contains the response from method VisibilityClient.HeadModel. +type VisibilityClientHeadModelResponse struct { + // Success indicates if the operation succeeded or failed. + Success bool +} + +// VisibilityClientPatchModelResponse contains the response from method VisibilityClient.PatchModel. +type VisibilityClientPatchModelResponse struct { + // placeholder for future response values +} + +// VisibilityClientPostModelResponse contains the response from method VisibilityClient.PostModel. +type VisibilityClientPostModelResponse struct { + // placeholder for future response values +} + +// VisibilityClientPutModelResponse contains the response from method VisibilityClient.PutModel. +type VisibilityClientPutModelResponse struct { + // placeholder for future response values +} + +// VisibilityClientPutReadOnlyModelResponse contains the response from method VisibilityClient.PutReadOnlyModel. +type VisibilityClientPutReadOnlyModelResponse struct { + // RoundTrip model with readonly optional properties. + ReadOnlyModel +} diff --git a/test/http-specs/type/model/visibilitygroup/zz_version.go b/test/http-specs/type/model/visibilitygroup/zz_version.go new file mode 100644 index 000000000000..954d037d9944 --- /dev/null +++ b/test/http-specs/type/model/visibilitygroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package visibilitygroup + +const ( + moduleName = "visibilitygroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/type/model/visibilitygroup/zz_visibility_client.go b/test/http-specs/type/model/visibilitygroup/zz_visibility_client.go new file mode 100644 index 000000000000..52004bffb3ad --- /dev/null +++ b/test/http-specs/type/model/visibilitygroup/zz_visibility_client.go @@ -0,0 +1,330 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package visibilitygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strconv" + "strings" +) + +// VisibilityClient - Illustrates models with visibility properties. +// Don't use this type directly, use NewVisibilityClientWithNoCredential() instead. +type VisibilityClient struct { + internal *azcore.Client + endpoint string +} + +// VisibilityClientOptions contains the optional values for creating a [VisibilityClient]. +type VisibilityClientOptions struct { + azcore.ClientOptions +} + +// NewVisibilityClientWithNoCredential creates a new instance of VisibilityClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewVisibilityClientWithNoCredential(endpoint string, options *VisibilityClientOptions) (*VisibilityClient, error) { + if options == nil { + options = &VisibilityClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &VisibilityClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// DeleteModel - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - VisibilityClientDeleteModelOptions contains the optional parameters for the VisibilityClient.DeleteModel method. +func (client *VisibilityClient) DeleteModel(ctx context.Context, input VisibilityModel, options *VisibilityClientDeleteModelOptions) (VisibilityClientDeleteModelResponse, error) { + var err error + const operationName = "VisibilityClient.DeleteModel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteModelCreateRequest(ctx, input, options) + if err != nil { + return VisibilityClientDeleteModelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VisibilityClientDeleteModelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return VisibilityClientDeleteModelResponse{}, err + } + return VisibilityClientDeleteModelResponse{}, nil +} + +// deleteModelCreateRequest creates the DeleteModel request. +func (client *VisibilityClient) deleteModelCreateRequest(ctx context.Context, input VisibilityModel, _ *VisibilityClientDeleteModelOptions) (*policy.Request, error) { + urlPath := "/type/model/visibility" + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, input); err != nil { + return nil, err + } + return req, nil +} + +// GetModel - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - VisibilityClientGetModelOptions contains the optional parameters for the VisibilityClient.GetModel method. +func (client *VisibilityClient) GetModel(ctx context.Context, queryProp int32, options *VisibilityClientGetModelOptions) (VisibilityClientGetModelResponse, error) { + var err error + const operationName = "VisibilityClient.GetModel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getModelCreateRequest(ctx, queryProp, options) + if err != nil { + return VisibilityClientGetModelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VisibilityClientGetModelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VisibilityClientGetModelResponse{}, err + } + resp, err := client.getModelHandleResponse(httpResp) + return resp, err +} + +// getModelCreateRequest creates the GetModel request. +func (client *VisibilityClient) getModelCreateRequest(ctx context.Context, queryProp int32, _ *VisibilityClientGetModelOptions) (*policy.Request, error) { + urlPath := "/type/model/visibility" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("queryProp", strconv.FormatInt(int64(queryProp), 10)) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getModelHandleResponse handles the GetModel response. +func (client *VisibilityClient) getModelHandleResponse(resp *http.Response) (VisibilityClientGetModelResponse, error) { + result := VisibilityClientGetModelResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VisibilityModel); err != nil { + return VisibilityClientGetModelResponse{}, err + } + return result, nil +} + +// - options - VisibilityClientHeadModelOptions contains the optional parameters for the VisibilityClient.HeadModel method. +func (client *VisibilityClient) HeadModel(ctx context.Context, queryProp int32, options *VisibilityClientHeadModelOptions) (VisibilityClientHeadModelResponse, error) { + var err error + const operationName = "VisibilityClient.HeadModel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.headModelCreateRequest(ctx, queryProp, options) + if err != nil { + return VisibilityClientHeadModelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VisibilityClientHeadModelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VisibilityClientHeadModelResponse{}, err + } + return VisibilityClientHeadModelResponse{Success: httpResp.StatusCode >= 200 && httpResp.StatusCode < 300}, nil +} + +// headModelCreateRequest creates the HeadModel request. +func (client *VisibilityClient) headModelCreateRequest(ctx context.Context, queryProp int32, _ *VisibilityClientHeadModelOptions) (*policy.Request, error) { + urlPath := "/type/model/visibility" + req, err := runtime.NewRequest(ctx, http.MethodHead, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("queryProp", strconv.FormatInt(int64(queryProp), 10)) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// PatchModel - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - VisibilityClientPatchModelOptions contains the optional parameters for the VisibilityClient.PatchModel method. +func (client *VisibilityClient) PatchModel(ctx context.Context, input VisibilityModel, options *VisibilityClientPatchModelOptions) (VisibilityClientPatchModelResponse, error) { + var err error + const operationName = "VisibilityClient.PatchModel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.patchModelCreateRequest(ctx, input, options) + if err != nil { + return VisibilityClientPatchModelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VisibilityClientPatchModelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return VisibilityClientPatchModelResponse{}, err + } + return VisibilityClientPatchModelResponse{}, nil +} + +// patchModelCreateRequest creates the PatchModel request. +func (client *VisibilityClient) patchModelCreateRequest(ctx context.Context, input VisibilityModel, _ *VisibilityClientPatchModelOptions) (*policy.Request, error) { + urlPath := "/type/model/visibility" + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, input); err != nil { + return nil, err + } + return req, nil +} + +// PostModel - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - VisibilityClientPostModelOptions contains the optional parameters for the VisibilityClient.PostModel method. +func (client *VisibilityClient) PostModel(ctx context.Context, input VisibilityModel, options *VisibilityClientPostModelOptions) (VisibilityClientPostModelResponse, error) { + var err error + const operationName = "VisibilityClient.PostModel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.postModelCreateRequest(ctx, input, options) + if err != nil { + return VisibilityClientPostModelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VisibilityClientPostModelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return VisibilityClientPostModelResponse{}, err + } + return VisibilityClientPostModelResponse{}, nil +} + +// postModelCreateRequest creates the PostModel request. +func (client *VisibilityClient) postModelCreateRequest(ctx context.Context, input VisibilityModel, _ *VisibilityClientPostModelOptions) (*policy.Request, error) { + urlPath := "/type/model/visibility" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, input); err != nil { + return nil, err + } + return req, nil +} + +// PutModel - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - VisibilityClientPutModelOptions contains the optional parameters for the VisibilityClient.PutModel method. +func (client *VisibilityClient) PutModel(ctx context.Context, input VisibilityModel, options *VisibilityClientPutModelOptions) (VisibilityClientPutModelResponse, error) { + var err error + const operationName = "VisibilityClient.PutModel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putModelCreateRequest(ctx, input, options) + if err != nil { + return VisibilityClientPutModelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VisibilityClientPutModelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return VisibilityClientPutModelResponse{}, err + } + return VisibilityClientPutModelResponse{}, nil +} + +// putModelCreateRequest creates the PutModel request. +func (client *VisibilityClient) putModelCreateRequest(ctx context.Context, input VisibilityModel, _ *VisibilityClientPutModelOptions) (*policy.Request, error) { + urlPath := "/type/model/visibility" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, input); err != nil { + return nil, err + } + return req, nil +} + +// PutReadOnlyModel - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - VisibilityClientPutReadOnlyModelOptions contains the optional parameters for the VisibilityClient.PutReadOnlyModel +// method. +func (client *VisibilityClient) PutReadOnlyModel(ctx context.Context, input ReadOnlyModel, options *VisibilityClientPutReadOnlyModelOptions) (VisibilityClientPutReadOnlyModelResponse, error) { + var err error + const operationName = "VisibilityClient.PutReadOnlyModel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putReadOnlyModelCreateRequest(ctx, input, options) + if err != nil { + return VisibilityClientPutReadOnlyModelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VisibilityClientPutReadOnlyModelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VisibilityClientPutReadOnlyModelResponse{}, err + } + resp, err := client.putReadOnlyModelHandleResponse(httpResp) + return resp, err +} + +// putReadOnlyModelCreateRequest creates the PutReadOnlyModel request. +func (client *VisibilityClient) putReadOnlyModelCreateRequest(ctx context.Context, input ReadOnlyModel, _ *VisibilityClientPutReadOnlyModelOptions) (*policy.Request, error) { + urlPath := "/type/model/visibility/readonlyroundtrip" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, input); err != nil { + return nil, err + } + return req, nil +} + +// putReadOnlyModelHandleResponse handles the PutReadOnlyModel response. +func (client *VisibilityClient) putReadOnlyModelHandleResponse(resp *http.Response) (VisibilityClientPutReadOnlyModelResponse, error) { + result := VisibilityClientPutReadOnlyModelResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ReadOnlyModel); err != nil { + return VisibilityClientPutReadOnlyModelResponse{}, err + } + return result, nil +} diff --git a/test/http-specs/type/property/addlpropsgroup/custom_client.go b/test/http-specs/type/property/addlpropsgroup/custom_client.go new file mode 100644 index 000000000000..e8de5b2a2515 --- /dev/null +++ b/test/http-specs/type/property/addlpropsgroup/custom_client.go @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package addlpropsgroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +func NewAdditionalPropertiesClient(options *azcore.ClientOptions) (*AdditionalPropertiesClient, error) { + internal, err := azcore.NewClient("addlpropsgroup", "v0.1.0", runtime.PipelineOptions{}, options) + if err != nil { + return nil, err + } + return &AdditionalPropertiesClient{ + internal: internal, + }, nil +} diff --git a/test/http-specs/type/property/addlpropsgroup/extendsfloat_client_test.go b/test/http-specs/type/property/addlpropsgroup/extendsfloat_client_test.go new file mode 100644 index 000000000000..3f472629e3f0 --- /dev/null +++ b/test/http-specs/type/property/addlpropsgroup/extendsfloat_client_test.go @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package addlpropsgroup_test + +import ( + "addlpropsgroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestExtendsFloatClient_Get(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesExtendsFloatClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, addlpropsgroup.ExtendsFloatAdditionalProperties{ + ID: to.Ptr[float32](43.125), + AdditionalProperties: map[string]*float32{ + "prop": to.Ptr[float32](43.125), + }, + }, resp.ExtendsFloatAdditionalProperties) +} + +func TestExtendsFloatClient_Put(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesExtendsFloatClient().Put(context.Background(), addlpropsgroup.ExtendsFloatAdditionalProperties{ + ID: to.Ptr[float32](43.125), + AdditionalProperties: map[string]*float32{ + "prop": to.Ptr[float32](43.125), + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/addlpropsgroup/extendsmodel_client_test.go b/test/http-specs/type/property/addlpropsgroup/extendsmodel_client_test.go new file mode 100644 index 000000000000..47562c54a252 --- /dev/null +++ b/test/http-specs/type/property/addlpropsgroup/extendsmodel_client_test.go @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package addlpropsgroup_test + +import ( + "addlpropsgroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestExtendsModelClient_Get(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesExtendsModelClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, addlpropsgroup.ExtendsModelAdditionalProperties{ + AdditionalProperties: map[string]*addlpropsgroup.ModelForRecord{ + "knownProp": { + State: to.Ptr("ok"), + }, + "prop": { + State: to.Ptr("ok"), + }, + }, + }, resp.ExtendsModelAdditionalProperties) +} + +func TestExtendsModelClient_Put(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesExtendsModelClient().Put(context.Background(), addlpropsgroup.ExtendsModelAdditionalProperties{ + AdditionalProperties: map[string]*addlpropsgroup.ModelForRecord{ + "knownProp": { + State: to.Ptr("ok"), + }, + "prop": { + State: to.Ptr("ok"), + }, + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/addlpropsgroup/extendsmodelarray_client_test.go b/test/http-specs/type/property/addlpropsgroup/extendsmodelarray_client_test.go new file mode 100644 index 000000000000..415a52fc0286 --- /dev/null +++ b/test/http-specs/type/property/addlpropsgroup/extendsmodelarray_client_test.go @@ -0,0 +1,67 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package addlpropsgroup_test + +import ( + "addlpropsgroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestExtendsModelArrayClient_Get(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesExtendsModelArrayClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, addlpropsgroup.ExtendsModelArrayAdditionalProperties{ + AdditionalProperties: map[string][]*addlpropsgroup.ModelForRecord{ + "knownProp": { + { + State: to.Ptr("ok"), + }, + { + State: to.Ptr("ok"), + }, + }, + "prop": { + { + State: to.Ptr("ok"), + }, + { + State: to.Ptr("ok"), + }, + }, + }, + }, resp.ExtendsModelArrayAdditionalProperties) +} + +func TestExtendsModelArrayClient_Put(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesExtendsModelArrayClient().Put(context.Background(), addlpropsgroup.ExtendsModelArrayAdditionalProperties{ + AdditionalProperties: map[string][]*addlpropsgroup.ModelForRecord{ + "knownProp": { + { + State: to.Ptr("ok"), + }, + { + State: to.Ptr("ok"), + }, + }, + "prop": { + { + State: to.Ptr("ok"), + }, + { + State: to.Ptr("ok"), + }, + }, + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/addlpropsgroup/extendsstring_client_test.go b/test/http-specs/type/property/addlpropsgroup/extendsstring_client_test.go new file mode 100644 index 000000000000..f9e04d4d3ec6 --- /dev/null +++ b/test/http-specs/type/property/addlpropsgroup/extendsstring_client_test.go @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package addlpropsgroup_test + +import ( + "addlpropsgroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestExtendsStringClient_Get(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesExtendsStringClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, addlpropsgroup.ExtendsStringAdditionalProperties{ + Name: to.Ptr("ExtendsStringAdditionalProperties"), + AdditionalProperties: map[string]*string{ + "prop": to.Ptr("abc"), + }, + }, resp.ExtendsStringAdditionalProperties) +} + +func TestExtendsStringClient_Put(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesExtendsStringClient().Put(context.Background(), addlpropsgroup.ExtendsStringAdditionalProperties{ + Name: to.Ptr("ExtendsStringAdditionalProperties"), + AdditionalProperties: map[string]*string{ + "prop": to.Ptr("abc"), + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/addlpropsgroup/extendsunknown_client_test.go b/test/http-specs/type/property/addlpropsgroup/extendsunknown_client_test.go new file mode 100644 index 000000000000..ca82ef6a659e --- /dev/null +++ b/test/http-specs/type/property/addlpropsgroup/extendsunknown_client_test.go @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package addlpropsgroup_test + +import ( + "addlpropsgroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestExtendsUnknownClient_Get(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesExtendsUnknownClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, addlpropsgroup.ExtendsUnknownAdditionalProperties{ + Name: to.Ptr("ExtendsUnknownAdditionalProperties"), + AdditionalProperties: map[string]any{ + "prop1": float64(32), + "prop2": true, + "prop3": "abc", + }, + }, resp.ExtendsUnknownAdditionalProperties) +} + +func TestExtendsUnknownClient_Put(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesExtendsUnknownClient().Put(context.Background(), addlpropsgroup.ExtendsUnknownAdditionalProperties{ + Name: to.Ptr("ExtendsUnknownAdditionalProperties"), + AdditionalProperties: map[string]any{ + "prop1": float64(32), + "prop2": true, + "prop3": "abc", + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/addlpropsgroup/extendsunknownderived_client_test.go b/test/http-specs/type/property/addlpropsgroup/extendsunknownderived_client_test.go new file mode 100644 index 000000000000..639ad5a21a42 --- /dev/null +++ b/test/http-specs/type/property/addlpropsgroup/extendsunknownderived_client_test.go @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package addlpropsgroup_test + +import ( + "addlpropsgroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestExtendsUnknownDerivedClient_Get(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesExtendsUnknownDerivedClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, addlpropsgroup.ExtendsUnknownAdditionalPropertiesDerived{ + Index: to.Ptr[int32](314), + Name: to.Ptr("ExtendsUnknownAdditionalProperties"), + AdditionalProperties: map[string]any{ + "prop1": float64(32), + "prop2": true, + "prop3": "abc", + }, + Age: to.Ptr[float32](2.71875), + }, resp.ExtendsUnknownAdditionalPropertiesDerived) +} + +func TestExtendsUnknownDerivedClient_Put(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesExtendsUnknownDerivedClient().Put(context.Background(), addlpropsgroup.ExtendsUnknownAdditionalPropertiesDerived{ + Index: to.Ptr[int32](314), + Name: to.Ptr("ExtendsUnknownAdditionalProperties"), + AdditionalProperties: map[string]any{ + "prop1": float64(32), + "prop2": true, + "prop3": "abc", + }, + Age: to.Ptr[float32](2.71875), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/addlpropsgroup/extendsunknowndiscriminated_client_test.go b/test/http-specs/type/property/addlpropsgroup/extendsunknowndiscriminated_client_test.go new file mode 100644 index 000000000000..f5b1f0265bc1 --- /dev/null +++ b/test/http-specs/type/property/addlpropsgroup/extendsunknowndiscriminated_client_test.go @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package addlpropsgroup_test + +import ( + "addlpropsgroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestExtendsUnknownDiscriminatedClient_Get(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesExtendsUnknownDiscriminatedClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, &addlpropsgroup.ExtendsUnknownAdditionalPropertiesDiscriminatedDerived{ + Index: to.Ptr[int32](314), + Kind: to.Ptr("derived"), + Name: to.Ptr("Derived"), + AdditionalProperties: map[string]any{ + "prop1": float64(32), + "prop2": true, + "prop3": "abc", + }, + Age: to.Ptr[float32](2.71875), + }, resp.ExtendsUnknownAdditionalPropertiesDiscriminatedClassification) +} + +func TestExtendsUnknownDiscriminatedClient_Put(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesExtendsUnknownDiscriminatedClient().Put(context.Background(), &addlpropsgroup.ExtendsUnknownAdditionalPropertiesDiscriminatedDerived{ + Index: to.Ptr[int32](314), + Kind: to.Ptr("derived"), + Name: to.Ptr("Derived"), + AdditionalProperties: map[string]any{ + "prop1": float64(32), + "prop2": true, + "prop3": "abc", + }, + Age: to.Ptr[float32](2.71875), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/addlpropsgroup/isfloat_client_test.go b/test/http-specs/type/property/addlpropsgroup/isfloat_client_test.go new file mode 100644 index 000000000000..8cbf6162523c --- /dev/null +++ b/test/http-specs/type/property/addlpropsgroup/isfloat_client_test.go @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package addlpropsgroup_test + +import ( + "addlpropsgroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestIsFloatClient_Get(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesIsFloatClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, addlpropsgroup.IsFloatAdditionalProperties{ + ID: to.Ptr[float32](43.125), + AdditionalProperties: map[string]*float32{ + "prop": to.Ptr[float32](43.125), + }, + }, resp.IsFloatAdditionalProperties) +} + +func TestIsFloatClient_Put(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesIsFloatClient().Put(context.Background(), addlpropsgroup.IsFloatAdditionalProperties{ + ID: to.Ptr[float32](43.125), + AdditionalProperties: map[string]*float32{ + "prop": to.Ptr[float32](43.125), + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/addlpropsgroup/ismodel_client_test.go b/test/http-specs/type/property/addlpropsgroup/ismodel_client_test.go new file mode 100644 index 000000000000..8aa4a28f7dce --- /dev/null +++ b/test/http-specs/type/property/addlpropsgroup/ismodel_client_test.go @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package addlpropsgroup_test + +import ( + "addlpropsgroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestIsModelClient_Get(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesIsModelClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, addlpropsgroup.IsModelAdditionalProperties{ + AdditionalProperties: map[string]*addlpropsgroup.ModelForRecord{ + "knownProp": { + State: to.Ptr("ok"), + }, + "prop": { + State: to.Ptr("ok"), + }, + }, + }, resp.IsModelAdditionalProperties) +} + +func TestIsModelClient_Put(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesIsModelClient().Put(context.Background(), addlpropsgroup.IsModelAdditionalProperties{ + AdditionalProperties: map[string]*addlpropsgroup.ModelForRecord{ + "knownProp": { + State: to.Ptr("ok"), + }, + "prop": { + State: to.Ptr("ok"), + }, + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/addlpropsgroup/ismodelarray_client_test.go b/test/http-specs/type/property/addlpropsgroup/ismodelarray_client_test.go new file mode 100644 index 000000000000..952586ee745b --- /dev/null +++ b/test/http-specs/type/property/addlpropsgroup/ismodelarray_client_test.go @@ -0,0 +1,67 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package addlpropsgroup_test + +import ( + "addlpropsgroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestIsModelArrayClient_Get(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesIsModelArrayClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, addlpropsgroup.IsModelArrayAdditionalProperties{ + AdditionalProperties: map[string][]*addlpropsgroup.ModelForRecord{ + "knownProp": { + { + State: to.Ptr("ok"), + }, + { + State: to.Ptr("ok"), + }, + }, + "prop": { + { + State: to.Ptr("ok"), + }, + { + State: to.Ptr("ok"), + }, + }, + }, + }, resp.IsModelArrayAdditionalProperties) +} + +func TestIsModelArrayClient_Put(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesIsModelArrayClient().Put(context.Background(), addlpropsgroup.IsModelArrayAdditionalProperties{ + AdditionalProperties: map[string][]*addlpropsgroup.ModelForRecord{ + "knownProp": { + { + State: to.Ptr("ok"), + }, + { + State: to.Ptr("ok"), + }, + }, + "prop": { + { + State: to.Ptr("ok"), + }, + { + State: to.Ptr("ok"), + }, + }, + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/addlpropsgroup/isstring_client_test.go b/test/http-specs/type/property/addlpropsgroup/isstring_client_test.go new file mode 100644 index 000000000000..010d51a9e964 --- /dev/null +++ b/test/http-specs/type/property/addlpropsgroup/isstring_client_test.go @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package addlpropsgroup_test + +import ( + "addlpropsgroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestIsStringClient_Get(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesIsStringClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, addlpropsgroup.IsStringAdditionalProperties{ + Name: to.Ptr("IsStringAdditionalProperties"), + AdditionalProperties: map[string]*string{ + "prop": to.Ptr("abc"), + }, + }, resp.IsStringAdditionalProperties) +} + +func TestIsStringClient_Put(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesIsStringClient().Put(context.Background(), addlpropsgroup.IsStringAdditionalProperties{ + Name: to.Ptr("IsStringAdditionalProperties"), + AdditionalProperties: map[string]*string{ + "prop": to.Ptr("abc"), + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/addlpropsgroup/isunknown_client_test.go b/test/http-specs/type/property/addlpropsgroup/isunknown_client_test.go new file mode 100644 index 000000000000..857bf0f58613 --- /dev/null +++ b/test/http-specs/type/property/addlpropsgroup/isunknown_client_test.go @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package addlpropsgroup_test + +import ( + "addlpropsgroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestIsUnknownClient_Get(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesIsUnknownClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, addlpropsgroup.IsUnknownAdditionalProperties{ + Name: to.Ptr("IsUnknownAdditionalProperties"), + AdditionalProperties: map[string]any{ + "prop1": float64(32), + "prop2": true, + "prop3": "abc", + }, + }, resp.IsUnknownAdditionalProperties) +} + +func TestIsUnknownClient_Put(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesIsUnknownClient().Put(context.Background(), addlpropsgroup.IsUnknownAdditionalProperties{ + Name: to.Ptr("IsUnknownAdditionalProperties"), + AdditionalProperties: map[string]any{ + "prop1": float64(32), + "prop2": true, + "prop3": "abc", + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/addlpropsgroup/isunknownderived_client_test.go b/test/http-specs/type/property/addlpropsgroup/isunknownderived_client_test.go new file mode 100644 index 000000000000..c33dfa1a1425 --- /dev/null +++ b/test/http-specs/type/property/addlpropsgroup/isunknownderived_client_test.go @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package addlpropsgroup_test + +import ( + "addlpropsgroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestIsUnknownDerivedClient_Get(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesIsUnknownDerivedClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, addlpropsgroup.IsUnknownAdditionalPropertiesDerived{ + Index: to.Ptr[int32](314), + Name: to.Ptr("IsUnknownAdditionalProperties"), + AdditionalProperties: map[string]any{ + "prop1": float64(32), + "prop2": true, + "prop3": "abc", + }, + Age: to.Ptr[float32](2.71875), + }, resp.IsUnknownAdditionalPropertiesDerived) +} + +func TestIsUnknownDerivedClient_Put(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesIsUnknownDerivedClient().Put(context.Background(), addlpropsgroup.IsUnknownAdditionalPropertiesDerived{ + Index: to.Ptr[int32](314), + Name: to.Ptr("IsUnknownAdditionalProperties"), + AdditionalProperties: map[string]any{ + "prop1": float64(32), + "prop2": true, + "prop3": "abc", + }, + Age: to.Ptr[float32](2.71875), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/addlpropsgroup/isunknowndiscriminated_client_test.go b/test/http-specs/type/property/addlpropsgroup/isunknowndiscriminated_client_test.go new file mode 100644 index 000000000000..bf840c2d904a --- /dev/null +++ b/test/http-specs/type/property/addlpropsgroup/isunknowndiscriminated_client_test.go @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package addlpropsgroup_test + +import ( + "addlpropsgroup" + "context" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestIsUnknownDiscriminatedClient_Get(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesIsUnknownDiscriminatedClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, &addlpropsgroup.IsUnknownAdditionalPropertiesDiscriminatedDerived{ + Index: to.Ptr[int32](314), + Kind: to.Ptr("derived"), + Name: to.Ptr("Derived"), + AdditionalProperties: map[string]any{ + "prop1": float64(32), + "prop2": true, + "prop3": "abc", + }, + Age: to.Ptr[float32](2.71875), + }, resp.IsUnknownAdditionalPropertiesDiscriminatedClassification) +} + +func TestIsUnknownDiscriminatedClient_Put(t *testing.T) { + client, err := addlpropsgroup.NewAdditionalPropertiesClient(nil) + require.NoError(t, err) + resp, err := client.NewAdditionalPropertiesIsUnknownDiscriminatedClient().Put(context.Background(), &addlpropsgroup.IsUnknownAdditionalPropertiesDiscriminatedDerived{ + Index: to.Ptr[int32](314), + Kind: to.Ptr("derived"), + Name: to.Ptr("Derived"), + AdditionalProperties: map[string]any{ + "prop1": float64(32), + "prop2": true, + "prop3": "abc", + }, + Age: to.Ptr[float32](2.71875), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/nullablegroup/LICENSE.txt b/test/http-specs/type/property/nullablegroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/type/property/nullablegroup/bytes_client_test.go b/test/http-specs/type/property/nullablegroup/bytes_client_test.go new file mode 100644 index 000000000000..b2235a98fb5e --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/bytes_client_test.go @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package nullablegroup_test + +import ( + "context" + "nullablegroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestBytesClientGetNonNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNullableBytesClient().GetNonNull(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, nullablegroup.BytesProperty{ + NullableProperty: []byte("hello, world!"), + RequiredProperty: to.Ptr("foo"), + }, resp.BytesProperty) +} + +func TestBytesClientGetNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNullableBytesClient().GetNull(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, nullablegroup.BytesProperty{ + RequiredProperty: to.Ptr("foo"), + }, resp.BytesProperty) +} + +func TestBytesClientPatchNonNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNullableBytesClient().PatchNonNull(context.Background(), nullablegroup.BytesProperty{ + NullableProperty: []byte("hello, world!"), + RequiredProperty: to.Ptr("foo"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestBytesClientPatchNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNullableBytesClient().PatchNull(context.Background(), nullablegroup.BytesProperty{ + NullableProperty: azcore.NullValue[[]byte](), + RequiredProperty: to.Ptr("foo"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/nullablegroup/collectionsbyte_client_test.go b/test/http-specs/type/property/nullablegroup/collectionsbyte_client_test.go new file mode 100644 index 000000000000..fe222e5e3a98 --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/collectionsbyte_client_test.go @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package nullablegroup_test + +import ( + "context" + "nullablegroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestCollectionsByteClientGetNonNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNullableCollectionsByteClient().GetNonNull(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, nullablegroup.CollectionsByteProperty{ + NullableProperty: [][]byte{ + []byte("hello, world!"), + []byte("hello, world!"), + }, + RequiredProperty: to.Ptr("foo"), + }, resp.CollectionsByteProperty) +} + +func TestCollectionsByteClientGetNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNullableCollectionsByteClient().GetNull(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, nullablegroup.CollectionsByteProperty{ + RequiredProperty: to.Ptr("foo"), + }, resp.CollectionsByteProperty) +} + +func TestCollectionsByteClientPatchNonNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNullableCollectionsByteClient().PatchNonNull(context.Background(), nullablegroup.CollectionsByteProperty{ + NullableProperty: [][]byte{ + []byte("hello, world!"), + []byte("hello, world!"), + }, + RequiredProperty: to.Ptr("foo"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestCollectionsByteClientPatchNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNullableCollectionsByteClient().PatchNull(context.Background(), nullablegroup.CollectionsByteProperty{ + NullableProperty: azcore.NullValue[[][]byte](), + RequiredProperty: to.Ptr("foo"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/nullablegroup/collectionsmodel_client_test.go b/test/http-specs/type/property/nullablegroup/collectionsmodel_client_test.go new file mode 100644 index 000000000000..379b8baa1377 --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/collectionsmodel_client_test.go @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package nullablegroup_test + +import ( + "context" + "nullablegroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestCollectionsModelClientGetNonNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNullableCollectionsModelClient().GetNonNull(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, nullablegroup.CollectionsModelProperty{ + NullableProperty: []*nullablegroup.InnerModel{ + { + Property: to.Ptr("hello"), + }, + { + Property: to.Ptr("world"), + }, + }, + RequiredProperty: to.Ptr("foo"), + }, resp.CollectionsModelProperty) +} + +func TestCollectionsModelClientGetNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNullableCollectionsModelClient().GetNull(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, nullablegroup.CollectionsModelProperty{ + RequiredProperty: to.Ptr("foo"), + }, resp.CollectionsModelProperty) +} + +func TestCollectionsModelClientPatchNonNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNullableCollectionsModelClient().PatchNonNull(context.Background(), nullablegroup.CollectionsModelProperty{ + NullableProperty: []*nullablegroup.InnerModel{ + { + Property: to.Ptr("hello"), + }, + { + Property: to.Ptr("world"), + }, + }, + RequiredProperty: to.Ptr("foo"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestCollectionsModelClientPatchNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNullableCollectionsModelClient().PatchNull(context.Background(), nullablegroup.CollectionsModelProperty{ + NullableProperty: azcore.NullValue[[]*nullablegroup.InnerModel](), + RequiredProperty: to.Ptr("foo"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/nullablegroup/collectionsstring_client_test.go b/test/http-specs/type/property/nullablegroup/collectionsstring_client_test.go new file mode 100644 index 000000000000..19fd68cdfbd2 --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/collectionsstring_client_test.go @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package nullablegroup_test + +import ( + "context" + "nullablegroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestCollectionsStringClientGetNonNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNullableCollectionsStringClient().GetNonNull(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, nullablegroup.CollectionsStringProperty{ + NullableProperty: []*string{to.Ptr("hello"), to.Ptr("world")}, + RequiredProperty: to.Ptr("foo"), + }, resp.CollectionsStringProperty) +} + +func TestCollectionsStringClientGetNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNullableCollectionsStringClient().GetNull(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, nullablegroup.CollectionsStringProperty{ + RequiredProperty: to.Ptr("foo"), + }, resp.CollectionsStringProperty) +} + +func TestCollectionsStringClientPatchNonNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + _, err = client.NewNullableCollectionsStringClient().PatchNonNull(context.Background(), nullablegroup.CollectionsStringProperty{ + NullableProperty: []*string{to.Ptr("hello"), to.Ptr("world")}, + RequiredProperty: to.Ptr("foo"), + }, nil) + require.NoError(t, err) +} + +func TestCollectionsStringClientPatchNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + _, err = client.NewNullableCollectionsStringClient().PatchNull(context.Background(), nullablegroup.CollectionsStringProperty{ + NullableProperty: azcore.NullValue[[]*string](), + RequiredProperty: to.Ptr("foo"), + }, nil) + require.NoError(t, err) +} diff --git a/test/http-specs/type/property/nullablegroup/datetime_client_test.go b/test/http-specs/type/property/nullablegroup/datetime_client_test.go new file mode 100644 index 000000000000..b070e45b51bc --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/datetime_client_test.go @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package nullablegroup_test + +import ( + "context" + "nullablegroup" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestDatetimeClientGetNonNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNullableDatetimeClient().GetNonNull(context.Background(), nil) + require.NoError(t, err) + timeProp, err := time.Parse(time.RFC3339, "2022-08-26T18:38:00Z") + require.NoError(t, err) + require.EqualValues(t, nullablegroup.DatetimeProperty{ + NullableProperty: &timeProp, + RequiredProperty: to.Ptr("foo"), + }, resp.DatetimeProperty) +} + +func TestDatetimeClientGetNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNullableDatetimeClient().GetNull(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, nullablegroup.DatetimeProperty{ + RequiredProperty: to.Ptr("foo"), + }, resp.DatetimeProperty) +} + +func TestDatetimeClientPatchNonNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + timeProp, err := time.Parse(time.RFC3339, "2022-08-26T18:38:00Z") + require.NoError(t, err) + resp, err := client.NewNullableDatetimeClient().PatchNonNull(context.Background(), nullablegroup.DatetimeProperty{ + NullableProperty: &timeProp, + RequiredProperty: to.Ptr("foo"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestDatetimeClientPatchNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNullableDatetimeClient().PatchNull(context.Background(), nullablegroup.DatetimeProperty{ + NullableProperty: azcore.NullValue[*time.Time](), + RequiredProperty: to.Ptr("foo"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/nullablegroup/duration_client_test.go b/test/http-specs/type/property/nullablegroup/duration_client_test.go new file mode 100644 index 000000000000..432696b1b765 --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/duration_client_test.go @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package nullablegroup_test + +import ( + "context" + "nullablegroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestDurationClientGetNonNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNullableDurationClient().GetNonNull(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, nullablegroup.DurationProperty{ + NullableProperty: to.Ptr("P123DT22H14M12.011S"), + RequiredProperty: to.Ptr("foo"), + }, resp.DurationProperty) +} + +func TestDurationClientGetNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNullableDurationClient().GetNull(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, nullablegroup.DurationProperty{ + RequiredProperty: to.Ptr("foo"), + }, resp.DurationProperty) +} + +func TestDurationClientPatchNonNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNullableDurationClient().PatchNonNull(context.Background(), nullablegroup.DurationProperty{ + NullableProperty: to.Ptr("P123DT22H14M12.011S"), + RequiredProperty: to.Ptr("foo"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestDurationClientPatchNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNullableDurationClient().PatchNull(context.Background(), nullablegroup.DurationProperty{ + NullableProperty: azcore.NullValue[*string](), + RequiredProperty: to.Ptr("foo"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/nullablegroup/fake/zz_internal.go b/test/http-specs/type/property/nullablegroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/http-specs/type/property/nullablegroup/fake/zz_nullable_server.go b/test/http-specs/type/property/nullablegroup/fake/zz_nullable_server.go new file mode 100644 index 000000000000..c1e2a74de3e9 --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/fake/zz_nullable_server.go @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// NullableServer is a fake server for instances of the nullablegroup.NullableClient type. +type NullableServer struct { + // NullableBytesServer contains the fakes for client NullableBytesClient + NullableBytesServer NullableBytesServer + + // NullableCollectionsByteServer contains the fakes for client NullableCollectionsByteClient + NullableCollectionsByteServer NullableCollectionsByteServer + + // NullableCollectionsModelServer contains the fakes for client NullableCollectionsModelClient + NullableCollectionsModelServer NullableCollectionsModelServer + + // NullableCollectionsStringServer contains the fakes for client NullableCollectionsStringClient + NullableCollectionsStringServer NullableCollectionsStringServer + + // NullableDatetimeServer contains the fakes for client NullableDatetimeClient + NullableDatetimeServer NullableDatetimeServer + + // NullableDurationServer contains the fakes for client NullableDurationClient + NullableDurationServer NullableDurationServer + + // NullableStringServer contains the fakes for client NullableStringClient + NullableStringServer NullableStringServer +} + +// NewNullableServerTransport creates a new instance of NullableServerTransport with the provided implementation. +// The returned NullableServerTransport instance is connected to an instance of nullablegroup.NullableClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewNullableServerTransport(srv *NullableServer) *NullableServerTransport { + return &NullableServerTransport{srv: srv} +} + +// NullableServerTransport connects instances of nullablegroup.NullableClient to instances of NullableServer. +// Don't use this type directly, use NewNullableServerTransport instead. +type NullableServerTransport struct { + srv *NullableServer + trMu sync.Mutex + trNullableBytesServer *NullableBytesServerTransport + trNullableCollectionsByteServer *NullableCollectionsByteServerTransport + trNullableCollectionsModelServer *NullableCollectionsModelServerTransport + trNullableCollectionsStringServer *NullableCollectionsStringServerTransport + trNullableDatetimeServer *NullableDatetimeServerTransport + trNullableDurationServer *NullableDurationServerTransport + trNullableStringServer *NullableStringServerTransport +} + +// Do implements the policy.Transporter interface for NullableServerTransport. +func (n *NullableServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return n.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (n *NullableServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "NullableBytesClient": + initServer(&n.trMu, &n.trNullableBytesServer, func() *NullableBytesServerTransport { + return NewNullableBytesServerTransport(&n.srv.NullableBytesServer) + }) + resp, err = n.trNullableBytesServer.Do(req) + case "NullableCollectionsByteClient": + initServer(&n.trMu, &n.trNullableCollectionsByteServer, func() *NullableCollectionsByteServerTransport { + return NewNullableCollectionsByteServerTransport(&n.srv.NullableCollectionsByteServer) + }) + resp, err = n.trNullableCollectionsByteServer.Do(req) + case "NullableCollectionsModelClient": + initServer(&n.trMu, &n.trNullableCollectionsModelServer, func() *NullableCollectionsModelServerTransport { + return NewNullableCollectionsModelServerTransport(&n.srv.NullableCollectionsModelServer) + }) + resp, err = n.trNullableCollectionsModelServer.Do(req) + case "NullableCollectionsStringClient": + initServer(&n.trMu, &n.trNullableCollectionsStringServer, func() *NullableCollectionsStringServerTransport { + return NewNullableCollectionsStringServerTransport(&n.srv.NullableCollectionsStringServer) + }) + resp, err = n.trNullableCollectionsStringServer.Do(req) + case "NullableDatetimeClient": + initServer(&n.trMu, &n.trNullableDatetimeServer, func() *NullableDatetimeServerTransport { + return NewNullableDatetimeServerTransport(&n.srv.NullableDatetimeServer) + }) + resp, err = n.trNullableDatetimeServer.Do(req) + case "NullableDurationClient": + initServer(&n.trMu, &n.trNullableDurationServer, func() *NullableDurationServerTransport { + return NewNullableDurationServerTransport(&n.srv.NullableDurationServer) + }) + resp, err = n.trNullableDurationServer.Do(req) + case "NullableStringClient": + initServer(&n.trMu, &n.trNullableStringServer, func() *NullableStringServerTransport { + return NewNullableStringServerTransport(&n.srv.NullableStringServer) + }) + resp, err = n.trNullableStringServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to NullableServerTransport +var nullableServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/nullablegroup/fake/zz_nullablebytes_server.go b/test/http-specs/type/property/nullablegroup/fake/zz_nullablebytes_server.go new file mode 100644 index 000000000000..5c5b1a8a5e4a --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/fake/zz_nullablebytes_server.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "nullablegroup" + "slices" +) + +// NullableBytesServer is a fake server for instances of the nullablegroup.NullableBytesClient type. +type NullableBytesServer struct { + // GetNonNull is the fake for method NullableBytesClient.GetNonNull + // HTTP status codes to indicate success: http.StatusOK + GetNonNull func(ctx context.Context, options *nullablegroup.NullableBytesClientGetNonNullOptions) (resp azfake.Responder[nullablegroup.NullableBytesClientGetNonNullResponse], errResp azfake.ErrorResponder) + + // GetNull is the fake for method NullableBytesClient.GetNull + // HTTP status codes to indicate success: http.StatusOK + GetNull func(ctx context.Context, options *nullablegroup.NullableBytesClientGetNullOptions) (resp azfake.Responder[nullablegroup.NullableBytesClientGetNullResponse], errResp azfake.ErrorResponder) + + // PatchNonNull is the fake for method NullableBytesClient.PatchNonNull + // HTTP status codes to indicate success: http.StatusNoContent + PatchNonNull func(ctx context.Context, body nullablegroup.BytesProperty, options *nullablegroup.NullableBytesClientPatchNonNullOptions) (resp azfake.Responder[nullablegroup.NullableBytesClientPatchNonNullResponse], errResp azfake.ErrorResponder) + + // PatchNull is the fake for method NullableBytesClient.PatchNull + // HTTP status codes to indicate success: http.StatusNoContent + PatchNull func(ctx context.Context, body nullablegroup.BytesProperty, options *nullablegroup.NullableBytesClientPatchNullOptions) (resp azfake.Responder[nullablegroup.NullableBytesClientPatchNullResponse], errResp azfake.ErrorResponder) +} + +// NewNullableBytesServerTransport creates a new instance of NullableBytesServerTransport with the provided implementation. +// The returned NullableBytesServerTransport instance is connected to an instance of nullablegroup.NullableBytesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewNullableBytesServerTransport(srv *NullableBytesServer) *NullableBytesServerTransport { + return &NullableBytesServerTransport{srv: srv} +} + +// NullableBytesServerTransport connects instances of nullablegroup.NullableBytesClient to instances of NullableBytesServer. +// Don't use this type directly, use NewNullableBytesServerTransport instead. +type NullableBytesServerTransport struct { + srv *NullableBytesServer +} + +// Do implements the policy.Transporter interface for NullableBytesServerTransport. +func (n *NullableBytesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return n.dispatchToMethodFake(req, method) +} + +func (n *NullableBytesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if nullableBytesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = nullableBytesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "NullableBytesClient.GetNonNull": + res.resp, res.err = n.dispatchGetNonNull(req) + case "NullableBytesClient.GetNull": + res.resp, res.err = n.dispatchGetNull(req) + case "NullableBytesClient.PatchNonNull": + res.resp, res.err = n.dispatchPatchNonNull(req) + case "NullableBytesClient.PatchNull": + res.resp, res.err = n.dispatchPatchNull(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (n *NullableBytesServerTransport) dispatchGetNonNull(req *http.Request) (*http.Response, error) { + if n.srv.GetNonNull == nil { + return nil, &nonRetriableError{errors.New("fake for method GetNonNull not implemented")} + } + respr, errRespr := n.srv.GetNonNull(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BytesProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NullableBytesServerTransport) dispatchGetNull(req *http.Request) (*http.Response, error) { + if n.srv.GetNull == nil { + return nil, &nonRetriableError{errors.New("fake for method GetNull not implemented")} + } + respr, errRespr := n.srv.GetNull(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BytesProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NullableBytesServerTransport) dispatchPatchNonNull(req *http.Request) (*http.Response, error) { + if n.srv.PatchNonNull == nil { + return nil, &nonRetriableError{errors.New("fake for method PatchNonNull not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[nullablegroup.BytesProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.PatchNonNull(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NullableBytesServerTransport) dispatchPatchNull(req *http.Request) (*http.Response, error) { + if n.srv.PatchNull == nil { + return nil, &nonRetriableError{errors.New("fake for method PatchNull not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[nullablegroup.BytesProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.PatchNull(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to NullableBytesServerTransport +var nullableBytesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/nullablegroup/fake/zz_nullablecollectionsbyte_server.go b/test/http-specs/type/property/nullablegroup/fake/zz_nullablecollectionsbyte_server.go new file mode 100644 index 000000000000..e709a707af22 --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/fake/zz_nullablecollectionsbyte_server.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "nullablegroup" + "slices" +) + +// NullableCollectionsByteServer is a fake server for instances of the nullablegroup.NullableCollectionsByteClient type. +type NullableCollectionsByteServer struct { + // GetNonNull is the fake for method NullableCollectionsByteClient.GetNonNull + // HTTP status codes to indicate success: http.StatusOK + GetNonNull func(ctx context.Context, options *nullablegroup.NullableCollectionsByteClientGetNonNullOptions) (resp azfake.Responder[nullablegroup.NullableCollectionsByteClientGetNonNullResponse], errResp azfake.ErrorResponder) + + // GetNull is the fake for method NullableCollectionsByteClient.GetNull + // HTTP status codes to indicate success: http.StatusOK + GetNull func(ctx context.Context, options *nullablegroup.NullableCollectionsByteClientGetNullOptions) (resp azfake.Responder[nullablegroup.NullableCollectionsByteClientGetNullResponse], errResp azfake.ErrorResponder) + + // PatchNonNull is the fake for method NullableCollectionsByteClient.PatchNonNull + // HTTP status codes to indicate success: http.StatusNoContent + PatchNonNull func(ctx context.Context, body nullablegroup.CollectionsByteProperty, options *nullablegroup.NullableCollectionsByteClientPatchNonNullOptions) (resp azfake.Responder[nullablegroup.NullableCollectionsByteClientPatchNonNullResponse], errResp azfake.ErrorResponder) + + // PatchNull is the fake for method NullableCollectionsByteClient.PatchNull + // HTTP status codes to indicate success: http.StatusNoContent + PatchNull func(ctx context.Context, body nullablegroup.CollectionsByteProperty, options *nullablegroup.NullableCollectionsByteClientPatchNullOptions) (resp azfake.Responder[nullablegroup.NullableCollectionsByteClientPatchNullResponse], errResp azfake.ErrorResponder) +} + +// NewNullableCollectionsByteServerTransport creates a new instance of NullableCollectionsByteServerTransport with the provided implementation. +// The returned NullableCollectionsByteServerTransport instance is connected to an instance of nullablegroup.NullableCollectionsByteClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewNullableCollectionsByteServerTransport(srv *NullableCollectionsByteServer) *NullableCollectionsByteServerTransport { + return &NullableCollectionsByteServerTransport{srv: srv} +} + +// NullableCollectionsByteServerTransport connects instances of nullablegroup.NullableCollectionsByteClient to instances of NullableCollectionsByteServer. +// Don't use this type directly, use NewNullableCollectionsByteServerTransport instead. +type NullableCollectionsByteServerTransport struct { + srv *NullableCollectionsByteServer +} + +// Do implements the policy.Transporter interface for NullableCollectionsByteServerTransport. +func (n *NullableCollectionsByteServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return n.dispatchToMethodFake(req, method) +} + +func (n *NullableCollectionsByteServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if nullableCollectionsByteServerTransportInterceptor != nil { + res.resp, res.err, intercepted = nullableCollectionsByteServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "NullableCollectionsByteClient.GetNonNull": + res.resp, res.err = n.dispatchGetNonNull(req) + case "NullableCollectionsByteClient.GetNull": + res.resp, res.err = n.dispatchGetNull(req) + case "NullableCollectionsByteClient.PatchNonNull": + res.resp, res.err = n.dispatchPatchNonNull(req) + case "NullableCollectionsByteClient.PatchNull": + res.resp, res.err = n.dispatchPatchNull(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (n *NullableCollectionsByteServerTransport) dispatchGetNonNull(req *http.Request) (*http.Response, error) { + if n.srv.GetNonNull == nil { + return nil, &nonRetriableError{errors.New("fake for method GetNonNull not implemented")} + } + respr, errRespr := n.srv.GetNonNull(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CollectionsByteProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NullableCollectionsByteServerTransport) dispatchGetNull(req *http.Request) (*http.Response, error) { + if n.srv.GetNull == nil { + return nil, &nonRetriableError{errors.New("fake for method GetNull not implemented")} + } + respr, errRespr := n.srv.GetNull(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CollectionsByteProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NullableCollectionsByteServerTransport) dispatchPatchNonNull(req *http.Request) (*http.Response, error) { + if n.srv.PatchNonNull == nil { + return nil, &nonRetriableError{errors.New("fake for method PatchNonNull not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[nullablegroup.CollectionsByteProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.PatchNonNull(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NullableCollectionsByteServerTransport) dispatchPatchNull(req *http.Request) (*http.Response, error) { + if n.srv.PatchNull == nil { + return nil, &nonRetriableError{errors.New("fake for method PatchNull not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[nullablegroup.CollectionsByteProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.PatchNull(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to NullableCollectionsByteServerTransport +var nullableCollectionsByteServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/nullablegroup/fake/zz_nullablecollectionsmodel_server.go b/test/http-specs/type/property/nullablegroup/fake/zz_nullablecollectionsmodel_server.go new file mode 100644 index 000000000000..14c0d70af89d --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/fake/zz_nullablecollectionsmodel_server.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "nullablegroup" + "slices" +) + +// NullableCollectionsModelServer is a fake server for instances of the nullablegroup.NullableCollectionsModelClient type. +type NullableCollectionsModelServer struct { + // GetNonNull is the fake for method NullableCollectionsModelClient.GetNonNull + // HTTP status codes to indicate success: http.StatusOK + GetNonNull func(ctx context.Context, options *nullablegroup.NullableCollectionsModelClientGetNonNullOptions) (resp azfake.Responder[nullablegroup.NullableCollectionsModelClientGetNonNullResponse], errResp azfake.ErrorResponder) + + // GetNull is the fake for method NullableCollectionsModelClient.GetNull + // HTTP status codes to indicate success: http.StatusOK + GetNull func(ctx context.Context, options *nullablegroup.NullableCollectionsModelClientGetNullOptions) (resp azfake.Responder[nullablegroup.NullableCollectionsModelClientGetNullResponse], errResp azfake.ErrorResponder) + + // PatchNonNull is the fake for method NullableCollectionsModelClient.PatchNonNull + // HTTP status codes to indicate success: http.StatusNoContent + PatchNonNull func(ctx context.Context, body nullablegroup.CollectionsModelProperty, options *nullablegroup.NullableCollectionsModelClientPatchNonNullOptions) (resp azfake.Responder[nullablegroup.NullableCollectionsModelClientPatchNonNullResponse], errResp azfake.ErrorResponder) + + // PatchNull is the fake for method NullableCollectionsModelClient.PatchNull + // HTTP status codes to indicate success: http.StatusNoContent + PatchNull func(ctx context.Context, body nullablegroup.CollectionsModelProperty, options *nullablegroup.NullableCollectionsModelClientPatchNullOptions) (resp azfake.Responder[nullablegroup.NullableCollectionsModelClientPatchNullResponse], errResp azfake.ErrorResponder) +} + +// NewNullableCollectionsModelServerTransport creates a new instance of NullableCollectionsModelServerTransport with the provided implementation. +// The returned NullableCollectionsModelServerTransport instance is connected to an instance of nullablegroup.NullableCollectionsModelClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewNullableCollectionsModelServerTransport(srv *NullableCollectionsModelServer) *NullableCollectionsModelServerTransport { + return &NullableCollectionsModelServerTransport{srv: srv} +} + +// NullableCollectionsModelServerTransport connects instances of nullablegroup.NullableCollectionsModelClient to instances of NullableCollectionsModelServer. +// Don't use this type directly, use NewNullableCollectionsModelServerTransport instead. +type NullableCollectionsModelServerTransport struct { + srv *NullableCollectionsModelServer +} + +// Do implements the policy.Transporter interface for NullableCollectionsModelServerTransport. +func (n *NullableCollectionsModelServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return n.dispatchToMethodFake(req, method) +} + +func (n *NullableCollectionsModelServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if nullableCollectionsModelServerTransportInterceptor != nil { + res.resp, res.err, intercepted = nullableCollectionsModelServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "NullableCollectionsModelClient.GetNonNull": + res.resp, res.err = n.dispatchGetNonNull(req) + case "NullableCollectionsModelClient.GetNull": + res.resp, res.err = n.dispatchGetNull(req) + case "NullableCollectionsModelClient.PatchNonNull": + res.resp, res.err = n.dispatchPatchNonNull(req) + case "NullableCollectionsModelClient.PatchNull": + res.resp, res.err = n.dispatchPatchNull(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (n *NullableCollectionsModelServerTransport) dispatchGetNonNull(req *http.Request) (*http.Response, error) { + if n.srv.GetNonNull == nil { + return nil, &nonRetriableError{errors.New("fake for method GetNonNull not implemented")} + } + respr, errRespr := n.srv.GetNonNull(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CollectionsModelProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NullableCollectionsModelServerTransport) dispatchGetNull(req *http.Request) (*http.Response, error) { + if n.srv.GetNull == nil { + return nil, &nonRetriableError{errors.New("fake for method GetNull not implemented")} + } + respr, errRespr := n.srv.GetNull(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CollectionsModelProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NullableCollectionsModelServerTransport) dispatchPatchNonNull(req *http.Request) (*http.Response, error) { + if n.srv.PatchNonNull == nil { + return nil, &nonRetriableError{errors.New("fake for method PatchNonNull not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[nullablegroup.CollectionsModelProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.PatchNonNull(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NullableCollectionsModelServerTransport) dispatchPatchNull(req *http.Request) (*http.Response, error) { + if n.srv.PatchNull == nil { + return nil, &nonRetriableError{errors.New("fake for method PatchNull not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[nullablegroup.CollectionsModelProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.PatchNull(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to NullableCollectionsModelServerTransport +var nullableCollectionsModelServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/nullablegroup/fake/zz_nullablecollectionsstring_server.go b/test/http-specs/type/property/nullablegroup/fake/zz_nullablecollectionsstring_server.go new file mode 100644 index 000000000000..7c5ce43ae440 --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/fake/zz_nullablecollectionsstring_server.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "nullablegroup" + "slices" +) + +// NullableCollectionsStringServer is a fake server for instances of the nullablegroup.NullableCollectionsStringClient type. +type NullableCollectionsStringServer struct { + // GetNonNull is the fake for method NullableCollectionsStringClient.GetNonNull + // HTTP status codes to indicate success: http.StatusOK + GetNonNull func(ctx context.Context, options *nullablegroup.NullableCollectionsStringClientGetNonNullOptions) (resp azfake.Responder[nullablegroup.NullableCollectionsStringClientGetNonNullResponse], errResp azfake.ErrorResponder) + + // GetNull is the fake for method NullableCollectionsStringClient.GetNull + // HTTP status codes to indicate success: http.StatusOK + GetNull func(ctx context.Context, options *nullablegroup.NullableCollectionsStringClientGetNullOptions) (resp azfake.Responder[nullablegroup.NullableCollectionsStringClientGetNullResponse], errResp azfake.ErrorResponder) + + // PatchNonNull is the fake for method NullableCollectionsStringClient.PatchNonNull + // HTTP status codes to indicate success: http.StatusNoContent + PatchNonNull func(ctx context.Context, body nullablegroup.CollectionsStringProperty, options *nullablegroup.NullableCollectionsStringClientPatchNonNullOptions) (resp azfake.Responder[nullablegroup.NullableCollectionsStringClientPatchNonNullResponse], errResp azfake.ErrorResponder) + + // PatchNull is the fake for method NullableCollectionsStringClient.PatchNull + // HTTP status codes to indicate success: http.StatusNoContent + PatchNull func(ctx context.Context, body nullablegroup.CollectionsStringProperty, options *nullablegroup.NullableCollectionsStringClientPatchNullOptions) (resp azfake.Responder[nullablegroup.NullableCollectionsStringClientPatchNullResponse], errResp azfake.ErrorResponder) +} + +// NewNullableCollectionsStringServerTransport creates a new instance of NullableCollectionsStringServerTransport with the provided implementation. +// The returned NullableCollectionsStringServerTransport instance is connected to an instance of nullablegroup.NullableCollectionsStringClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewNullableCollectionsStringServerTransport(srv *NullableCollectionsStringServer) *NullableCollectionsStringServerTransport { + return &NullableCollectionsStringServerTransport{srv: srv} +} + +// NullableCollectionsStringServerTransport connects instances of nullablegroup.NullableCollectionsStringClient to instances of NullableCollectionsStringServer. +// Don't use this type directly, use NewNullableCollectionsStringServerTransport instead. +type NullableCollectionsStringServerTransport struct { + srv *NullableCollectionsStringServer +} + +// Do implements the policy.Transporter interface for NullableCollectionsStringServerTransport. +func (n *NullableCollectionsStringServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return n.dispatchToMethodFake(req, method) +} + +func (n *NullableCollectionsStringServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if nullableCollectionsStringServerTransportInterceptor != nil { + res.resp, res.err, intercepted = nullableCollectionsStringServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "NullableCollectionsStringClient.GetNonNull": + res.resp, res.err = n.dispatchGetNonNull(req) + case "NullableCollectionsStringClient.GetNull": + res.resp, res.err = n.dispatchGetNull(req) + case "NullableCollectionsStringClient.PatchNonNull": + res.resp, res.err = n.dispatchPatchNonNull(req) + case "NullableCollectionsStringClient.PatchNull": + res.resp, res.err = n.dispatchPatchNull(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (n *NullableCollectionsStringServerTransport) dispatchGetNonNull(req *http.Request) (*http.Response, error) { + if n.srv.GetNonNull == nil { + return nil, &nonRetriableError{errors.New("fake for method GetNonNull not implemented")} + } + respr, errRespr := n.srv.GetNonNull(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CollectionsStringProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NullableCollectionsStringServerTransport) dispatchGetNull(req *http.Request) (*http.Response, error) { + if n.srv.GetNull == nil { + return nil, &nonRetriableError{errors.New("fake for method GetNull not implemented")} + } + respr, errRespr := n.srv.GetNull(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CollectionsStringProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NullableCollectionsStringServerTransport) dispatchPatchNonNull(req *http.Request) (*http.Response, error) { + if n.srv.PatchNonNull == nil { + return nil, &nonRetriableError{errors.New("fake for method PatchNonNull not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[nullablegroup.CollectionsStringProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.PatchNonNull(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NullableCollectionsStringServerTransport) dispatchPatchNull(req *http.Request) (*http.Response, error) { + if n.srv.PatchNull == nil { + return nil, &nonRetriableError{errors.New("fake for method PatchNull not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[nullablegroup.CollectionsStringProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.PatchNull(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to NullableCollectionsStringServerTransport +var nullableCollectionsStringServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/nullablegroup/fake/zz_nullabledatetime_server.go b/test/http-specs/type/property/nullablegroup/fake/zz_nullabledatetime_server.go new file mode 100644 index 000000000000..24310f9df7d4 --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/fake/zz_nullabledatetime_server.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "nullablegroup" + "slices" +) + +// NullableDatetimeServer is a fake server for instances of the nullablegroup.NullableDatetimeClient type. +type NullableDatetimeServer struct { + // GetNonNull is the fake for method NullableDatetimeClient.GetNonNull + // HTTP status codes to indicate success: http.StatusOK + GetNonNull func(ctx context.Context, options *nullablegroup.NullableDatetimeClientGetNonNullOptions) (resp azfake.Responder[nullablegroup.NullableDatetimeClientGetNonNullResponse], errResp azfake.ErrorResponder) + + // GetNull is the fake for method NullableDatetimeClient.GetNull + // HTTP status codes to indicate success: http.StatusOK + GetNull func(ctx context.Context, options *nullablegroup.NullableDatetimeClientGetNullOptions) (resp azfake.Responder[nullablegroup.NullableDatetimeClientGetNullResponse], errResp azfake.ErrorResponder) + + // PatchNonNull is the fake for method NullableDatetimeClient.PatchNonNull + // HTTP status codes to indicate success: http.StatusNoContent + PatchNonNull func(ctx context.Context, body nullablegroup.DatetimeProperty, options *nullablegroup.NullableDatetimeClientPatchNonNullOptions) (resp azfake.Responder[nullablegroup.NullableDatetimeClientPatchNonNullResponse], errResp azfake.ErrorResponder) + + // PatchNull is the fake for method NullableDatetimeClient.PatchNull + // HTTP status codes to indicate success: http.StatusNoContent + PatchNull func(ctx context.Context, body nullablegroup.DatetimeProperty, options *nullablegroup.NullableDatetimeClientPatchNullOptions) (resp azfake.Responder[nullablegroup.NullableDatetimeClientPatchNullResponse], errResp azfake.ErrorResponder) +} + +// NewNullableDatetimeServerTransport creates a new instance of NullableDatetimeServerTransport with the provided implementation. +// The returned NullableDatetimeServerTransport instance is connected to an instance of nullablegroup.NullableDatetimeClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewNullableDatetimeServerTransport(srv *NullableDatetimeServer) *NullableDatetimeServerTransport { + return &NullableDatetimeServerTransport{srv: srv} +} + +// NullableDatetimeServerTransport connects instances of nullablegroup.NullableDatetimeClient to instances of NullableDatetimeServer. +// Don't use this type directly, use NewNullableDatetimeServerTransport instead. +type NullableDatetimeServerTransport struct { + srv *NullableDatetimeServer +} + +// Do implements the policy.Transporter interface for NullableDatetimeServerTransport. +func (n *NullableDatetimeServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return n.dispatchToMethodFake(req, method) +} + +func (n *NullableDatetimeServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if nullableDatetimeServerTransportInterceptor != nil { + res.resp, res.err, intercepted = nullableDatetimeServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "NullableDatetimeClient.GetNonNull": + res.resp, res.err = n.dispatchGetNonNull(req) + case "NullableDatetimeClient.GetNull": + res.resp, res.err = n.dispatchGetNull(req) + case "NullableDatetimeClient.PatchNonNull": + res.resp, res.err = n.dispatchPatchNonNull(req) + case "NullableDatetimeClient.PatchNull": + res.resp, res.err = n.dispatchPatchNull(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (n *NullableDatetimeServerTransport) dispatchGetNonNull(req *http.Request) (*http.Response, error) { + if n.srv.GetNonNull == nil { + return nil, &nonRetriableError{errors.New("fake for method GetNonNull not implemented")} + } + respr, errRespr := n.srv.GetNonNull(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DatetimeProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NullableDatetimeServerTransport) dispatchGetNull(req *http.Request) (*http.Response, error) { + if n.srv.GetNull == nil { + return nil, &nonRetriableError{errors.New("fake for method GetNull not implemented")} + } + respr, errRespr := n.srv.GetNull(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DatetimeProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NullableDatetimeServerTransport) dispatchPatchNonNull(req *http.Request) (*http.Response, error) { + if n.srv.PatchNonNull == nil { + return nil, &nonRetriableError{errors.New("fake for method PatchNonNull not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[nullablegroup.DatetimeProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.PatchNonNull(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NullableDatetimeServerTransport) dispatchPatchNull(req *http.Request) (*http.Response, error) { + if n.srv.PatchNull == nil { + return nil, &nonRetriableError{errors.New("fake for method PatchNull not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[nullablegroup.DatetimeProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.PatchNull(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to NullableDatetimeServerTransport +var nullableDatetimeServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/nullablegroup/fake/zz_nullableduration_server.go b/test/http-specs/type/property/nullablegroup/fake/zz_nullableduration_server.go new file mode 100644 index 000000000000..ab2835b0466e --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/fake/zz_nullableduration_server.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "nullablegroup" + "slices" +) + +// NullableDurationServer is a fake server for instances of the nullablegroup.NullableDurationClient type. +type NullableDurationServer struct { + // GetNonNull is the fake for method NullableDurationClient.GetNonNull + // HTTP status codes to indicate success: http.StatusOK + GetNonNull func(ctx context.Context, options *nullablegroup.NullableDurationClientGetNonNullOptions) (resp azfake.Responder[nullablegroup.NullableDurationClientGetNonNullResponse], errResp azfake.ErrorResponder) + + // GetNull is the fake for method NullableDurationClient.GetNull + // HTTP status codes to indicate success: http.StatusOK + GetNull func(ctx context.Context, options *nullablegroup.NullableDurationClientGetNullOptions) (resp azfake.Responder[nullablegroup.NullableDurationClientGetNullResponse], errResp azfake.ErrorResponder) + + // PatchNonNull is the fake for method NullableDurationClient.PatchNonNull + // HTTP status codes to indicate success: http.StatusNoContent + PatchNonNull func(ctx context.Context, body nullablegroup.DurationProperty, options *nullablegroup.NullableDurationClientPatchNonNullOptions) (resp azfake.Responder[nullablegroup.NullableDurationClientPatchNonNullResponse], errResp azfake.ErrorResponder) + + // PatchNull is the fake for method NullableDurationClient.PatchNull + // HTTP status codes to indicate success: http.StatusNoContent + PatchNull func(ctx context.Context, body nullablegroup.DurationProperty, options *nullablegroup.NullableDurationClientPatchNullOptions) (resp azfake.Responder[nullablegroup.NullableDurationClientPatchNullResponse], errResp azfake.ErrorResponder) +} + +// NewNullableDurationServerTransport creates a new instance of NullableDurationServerTransport with the provided implementation. +// The returned NullableDurationServerTransport instance is connected to an instance of nullablegroup.NullableDurationClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewNullableDurationServerTransport(srv *NullableDurationServer) *NullableDurationServerTransport { + return &NullableDurationServerTransport{srv: srv} +} + +// NullableDurationServerTransport connects instances of nullablegroup.NullableDurationClient to instances of NullableDurationServer. +// Don't use this type directly, use NewNullableDurationServerTransport instead. +type NullableDurationServerTransport struct { + srv *NullableDurationServer +} + +// Do implements the policy.Transporter interface for NullableDurationServerTransport. +func (n *NullableDurationServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return n.dispatchToMethodFake(req, method) +} + +func (n *NullableDurationServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if nullableDurationServerTransportInterceptor != nil { + res.resp, res.err, intercepted = nullableDurationServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "NullableDurationClient.GetNonNull": + res.resp, res.err = n.dispatchGetNonNull(req) + case "NullableDurationClient.GetNull": + res.resp, res.err = n.dispatchGetNull(req) + case "NullableDurationClient.PatchNonNull": + res.resp, res.err = n.dispatchPatchNonNull(req) + case "NullableDurationClient.PatchNull": + res.resp, res.err = n.dispatchPatchNull(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (n *NullableDurationServerTransport) dispatchGetNonNull(req *http.Request) (*http.Response, error) { + if n.srv.GetNonNull == nil { + return nil, &nonRetriableError{errors.New("fake for method GetNonNull not implemented")} + } + respr, errRespr := n.srv.GetNonNull(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DurationProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NullableDurationServerTransport) dispatchGetNull(req *http.Request) (*http.Response, error) { + if n.srv.GetNull == nil { + return nil, &nonRetriableError{errors.New("fake for method GetNull not implemented")} + } + respr, errRespr := n.srv.GetNull(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DurationProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NullableDurationServerTransport) dispatchPatchNonNull(req *http.Request) (*http.Response, error) { + if n.srv.PatchNonNull == nil { + return nil, &nonRetriableError{errors.New("fake for method PatchNonNull not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[nullablegroup.DurationProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.PatchNonNull(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NullableDurationServerTransport) dispatchPatchNull(req *http.Request) (*http.Response, error) { + if n.srv.PatchNull == nil { + return nil, &nonRetriableError{errors.New("fake for method PatchNull not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[nullablegroup.DurationProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.PatchNull(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to NullableDurationServerTransport +var nullableDurationServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/nullablegroup/fake/zz_nullablestring_server.go b/test/http-specs/type/property/nullablegroup/fake/zz_nullablestring_server.go new file mode 100644 index 000000000000..05b3cd7db016 --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/fake/zz_nullablestring_server.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "nullablegroup" + "slices" +) + +// NullableStringServer is a fake server for instances of the nullablegroup.NullableStringClient type. +type NullableStringServer struct { + // GetNonNull is the fake for method NullableStringClient.GetNonNull + // HTTP status codes to indicate success: http.StatusOK + GetNonNull func(ctx context.Context, options *nullablegroup.NullableStringClientGetNonNullOptions) (resp azfake.Responder[nullablegroup.NullableStringClientGetNonNullResponse], errResp azfake.ErrorResponder) + + // GetNull is the fake for method NullableStringClient.GetNull + // HTTP status codes to indicate success: http.StatusOK + GetNull func(ctx context.Context, options *nullablegroup.NullableStringClientGetNullOptions) (resp azfake.Responder[nullablegroup.NullableStringClientGetNullResponse], errResp azfake.ErrorResponder) + + // PatchNonNull is the fake for method NullableStringClient.PatchNonNull + // HTTP status codes to indicate success: http.StatusNoContent + PatchNonNull func(ctx context.Context, body nullablegroup.StringProperty, options *nullablegroup.NullableStringClientPatchNonNullOptions) (resp azfake.Responder[nullablegroup.NullableStringClientPatchNonNullResponse], errResp azfake.ErrorResponder) + + // PatchNull is the fake for method NullableStringClient.PatchNull + // HTTP status codes to indicate success: http.StatusNoContent + PatchNull func(ctx context.Context, body nullablegroup.StringProperty, options *nullablegroup.NullableStringClientPatchNullOptions) (resp azfake.Responder[nullablegroup.NullableStringClientPatchNullResponse], errResp azfake.ErrorResponder) +} + +// NewNullableStringServerTransport creates a new instance of NullableStringServerTransport with the provided implementation. +// The returned NullableStringServerTransport instance is connected to an instance of nullablegroup.NullableStringClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewNullableStringServerTransport(srv *NullableStringServer) *NullableStringServerTransport { + return &NullableStringServerTransport{srv: srv} +} + +// NullableStringServerTransport connects instances of nullablegroup.NullableStringClient to instances of NullableStringServer. +// Don't use this type directly, use NewNullableStringServerTransport instead. +type NullableStringServerTransport struct { + srv *NullableStringServer +} + +// Do implements the policy.Transporter interface for NullableStringServerTransport. +func (n *NullableStringServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return n.dispatchToMethodFake(req, method) +} + +func (n *NullableStringServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if nullableStringServerTransportInterceptor != nil { + res.resp, res.err, intercepted = nullableStringServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "NullableStringClient.GetNonNull": + res.resp, res.err = n.dispatchGetNonNull(req) + case "NullableStringClient.GetNull": + res.resp, res.err = n.dispatchGetNull(req) + case "NullableStringClient.PatchNonNull": + res.resp, res.err = n.dispatchPatchNonNull(req) + case "NullableStringClient.PatchNull": + res.resp, res.err = n.dispatchPatchNull(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (n *NullableStringServerTransport) dispatchGetNonNull(req *http.Request) (*http.Response, error) { + if n.srv.GetNonNull == nil { + return nil, &nonRetriableError{errors.New("fake for method GetNonNull not implemented")} + } + respr, errRespr := n.srv.GetNonNull(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).StringProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NullableStringServerTransport) dispatchGetNull(req *http.Request) (*http.Response, error) { + if n.srv.GetNull == nil { + return nil, &nonRetriableError{errors.New("fake for method GetNull not implemented")} + } + respr, errRespr := n.srv.GetNull(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).StringProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NullableStringServerTransport) dispatchPatchNonNull(req *http.Request) (*http.Response, error) { + if n.srv.PatchNonNull == nil { + return nil, &nonRetriableError{errors.New("fake for method PatchNonNull not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[nullablegroup.StringProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.PatchNonNull(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NullableStringServerTransport) dispatchPatchNull(req *http.Request) (*http.Response, error) { + if n.srv.PatchNull == nil { + return nil, &nonRetriableError{errors.New("fake for method PatchNull not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[nullablegroup.StringProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.PatchNull(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to NullableStringServerTransport +var nullableStringServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/nullablegroup/go.mod b/test/http-specs/type/property/nullablegroup/go.mod new file mode 100644 index 000000000000..f889ad018d6d --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/go.mod @@ -0,0 +1,17 @@ +module nullablegroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/type/property/nullablegroup/go.sum b/test/http-specs/type/property/nullablegroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/type/property/nullablegroup/string_client_test.go b/test/http-specs/type/property/nullablegroup/string_client_test.go new file mode 100644 index 000000000000..04a906acd84f --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/string_client_test.go @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package nullablegroup_test + +import ( + "context" + "nullablegroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestStringClientGetNonNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNullableStringClient().GetNonNull(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, nullablegroup.StringProperty{ + NullableProperty: to.Ptr("hello"), + RequiredProperty: to.Ptr("foo"), + }, resp.StringProperty) +} + +func TestStringClientGetNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNullableStringClient().GetNull(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, nullablegroup.StringProperty{ + RequiredProperty: to.Ptr("foo"), + }, resp.StringProperty) +} + +func TestStringClientPatchNonNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNullableStringClient().PatchNonNull(context.Background(), nullablegroup.StringProperty{ + NullableProperty: to.Ptr("hello"), + RequiredProperty: to.Ptr("foo"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestStringClientPatchNull(t *testing.T) { + client, err := nullablegroup.NewNullableClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewNullableStringClient().PatchNull(context.Background(), nullablegroup.StringProperty{ + NullableProperty: azcore.NullValue[*string](), + RequiredProperty: to.Ptr("foo"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/nullablegroup/testdata/_metadata.json b/test/http-specs/type/property/nullablegroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/type/property/nullablegroup/zz_models.go b/test/http-specs/type/property/nullablegroup/zz_models.go new file mode 100644 index 000000000000..448bc81988f4 --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/zz_models.go @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nullablegroup + +import "time" + +// BytesProperty - Template type for testing models with nullable property. Pass in the type of the property you are looking +// for +type BytesProperty struct { + // REQUIRED; Property + NullableProperty []byte + + // REQUIRED; Required property + RequiredProperty *string +} + +// CollectionsByteProperty - Model with collection bytes properties +type CollectionsByteProperty struct { + // REQUIRED; Property + NullableProperty [][]byte + + // REQUIRED; Required property + RequiredProperty *string +} + +// CollectionsModelProperty - Model with collection models properties +type CollectionsModelProperty struct { + // REQUIRED; Property + NullableProperty []*InnerModel + + // REQUIRED; Required property + RequiredProperty *string +} + +// CollectionsStringProperty - Model with collection string properties +type CollectionsStringProperty struct { + // REQUIRED; Property + NullableProperty []*string + + // REQUIRED; Required property + RequiredProperty *string +} + +// DatetimeProperty - Model with a datetime property +type DatetimeProperty struct { + // REQUIRED; Property + NullableProperty *time.Time + + // REQUIRED; Required property + RequiredProperty *string +} + +// DurationProperty - Model with a duration property +type DurationProperty struct { + // REQUIRED; Property + NullableProperty *string + + // REQUIRED; Required property + RequiredProperty *string +} + +// InnerModel - Inner model used in collections model property +type InnerModel struct { + // REQUIRED; Inner model property + Property *string +} + +// StringProperty - Template type for testing models with nullable property. Pass in the type of the property you are looking +// for +type StringProperty struct { + // REQUIRED; Property + NullableProperty *string + + // REQUIRED; Required property + RequiredProperty *string +} diff --git a/test/http-specs/type/property/nullablegroup/zz_models_serde.go b/test/http-specs/type/property/nullablegroup/zz_models_serde.go new file mode 100644 index 000000000000..db4e780a78a7 --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/zz_models_serde.go @@ -0,0 +1,334 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nullablegroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type BytesProperty. +func (b BytesProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateByteArray(objectMap, "nullableProperty", b.NullableProperty, func() any { + return runtime.EncodeByteArray(b.NullableProperty, runtime.Base64StdFormat) + }) + populate(objectMap, "requiredProperty", b.RequiredProperty) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BytesProperty. +func (b *BytesProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nullableProperty": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &b.NullableProperty, runtime.Base64StdFormat) + } + delete(rawMsg, key) + case "requiredProperty": + err = unpopulate(val, "RequiredProperty", &b.RequiredProperty) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CollectionsByteProperty. +func (c CollectionsByteProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateByteArray(objectMap, "nullableProperty", c.NullableProperty, func() any { + encodedValue := make([]string, len(c.NullableProperty)) + for i := 0; i < len(c.NullableProperty); i++ { + encodedValue[i] = runtime.EncodeByteArray(c.NullableProperty[i], runtime.Base64StdFormat) + } + return encodedValue + }) + populate(objectMap, "requiredProperty", c.RequiredProperty) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CollectionsByteProperty. +func (c *CollectionsByteProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nullableProperty": + var encodedValue []string + err = unpopulate(val, "NullableProperty", &encodedValue) + if err == nil && len(encodedValue) > 0 { + c.NullableProperty = make([][]byte, len(encodedValue)) + for i := 0; i < len(encodedValue) && err == nil; i++ { + err = runtime.DecodeByteArray(encodedValue[i], &c.NullableProperty[i], runtime.Base64StdFormat) + } + } + delete(rawMsg, key) + case "requiredProperty": + err = unpopulate(val, "RequiredProperty", &c.RequiredProperty) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CollectionsModelProperty. +func (c CollectionsModelProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nullableProperty", c.NullableProperty) + populate(objectMap, "requiredProperty", c.RequiredProperty) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CollectionsModelProperty. +func (c *CollectionsModelProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nullableProperty": + err = unpopulate(val, "NullableProperty", &c.NullableProperty) + delete(rawMsg, key) + case "requiredProperty": + err = unpopulate(val, "RequiredProperty", &c.RequiredProperty) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CollectionsStringProperty. +func (c CollectionsStringProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nullableProperty", c.NullableProperty) + populate(objectMap, "requiredProperty", c.RequiredProperty) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CollectionsStringProperty. +func (c *CollectionsStringProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nullableProperty": + err = unpopulate(val, "NullableProperty", &c.NullableProperty) + delete(rawMsg, key) + case "requiredProperty": + err = unpopulate(val, "RequiredProperty", &c.RequiredProperty) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DatetimeProperty. +func (d DatetimeProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "nullableProperty", d.NullableProperty) + populate(objectMap, "requiredProperty", d.RequiredProperty) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DatetimeProperty. +func (d *DatetimeProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nullableProperty": + err = unpopulateTime[datetime.RFC3339](val, "NullableProperty", &d.NullableProperty) + delete(rawMsg, key) + case "requiredProperty": + err = unpopulate(val, "RequiredProperty", &d.RequiredProperty) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DurationProperty. +func (d DurationProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nullableProperty", d.NullableProperty) + populate(objectMap, "requiredProperty", d.RequiredProperty) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DurationProperty. +func (d *DurationProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nullableProperty": + err = unpopulate(val, "NullableProperty", &d.NullableProperty) + delete(rawMsg, key) + case "requiredProperty": + err = unpopulate(val, "RequiredProperty", &d.RequiredProperty) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type InnerModel. +func (i InnerModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "property", i.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InnerModel. +func (i *InnerModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &i.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type StringProperty. +func (s StringProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nullableProperty", s.NullableProperty) + populate(objectMap, "requiredProperty", s.RequiredProperty) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StringProperty. +func (s *StringProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nullableProperty": + err = unpopulate(val, "NullableProperty", &s.NullableProperty) + delete(rawMsg, key) + case "requiredProperty": + err = unpopulate(val, "RequiredProperty", &s.RequiredProperty) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func populateByteArray[T any](m map[string]any, k string, b []T, convert func() any) { + if azcore.IsNullValue(b) { + m[k] = nil + } else if len(b) == 0 { + return + } else { + m[k] = convert() + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/http-specs/type/property/nullablegroup/zz_nullable_client.go b/test/http-specs/type/property/nullablegroup/zz_nullable_client.go new file mode 100644 index 000000000000..d02b2e2abc33 --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/zz_nullable_client.go @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nullablegroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// NullableClient - Illustrates models with nullable properties. +// Don't use this type directly, use NewNullableClientWithNoCredential() instead. +type NullableClient struct { + internal *azcore.Client + endpoint string +} + +// NullableClientOptions contains the optional values for creating a [NullableClient]. +type NullableClientOptions struct { + azcore.ClientOptions +} + +// NewNullableClientWithNoCredential creates a new instance of NullableClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewNullableClientWithNoCredential(endpoint string, options *NullableClientOptions) (*NullableClient, error) { + if options == nil { + options = &NullableClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &NullableClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewNullableBytesClient creates a new instance of [NullableBytesClient]. +func (client *NullableClient) NewNullableBytesClient() *NullableBytesClient { + return &NullableBytesClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewNullableCollectionsByteClient creates a new instance of [NullableCollectionsByteClient]. +func (client *NullableClient) NewNullableCollectionsByteClient() *NullableCollectionsByteClient { + return &NullableCollectionsByteClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewNullableCollectionsModelClient creates a new instance of [NullableCollectionsModelClient]. +func (client *NullableClient) NewNullableCollectionsModelClient() *NullableCollectionsModelClient { + return &NullableCollectionsModelClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewNullableCollectionsStringClient creates a new instance of [NullableCollectionsStringClient]. +func (client *NullableClient) NewNullableCollectionsStringClient() *NullableCollectionsStringClient { + return &NullableCollectionsStringClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewNullableDatetimeClient creates a new instance of [NullableDatetimeClient]. +func (client *NullableClient) NewNullableDatetimeClient() *NullableDatetimeClient { + return &NullableDatetimeClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewNullableDurationClient creates a new instance of [NullableDurationClient]. +func (client *NullableClient) NewNullableDurationClient() *NullableDurationClient { + return &NullableDurationClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewNullableStringClient creates a new instance of [NullableStringClient]. +func (client *NullableClient) NewNullableStringClient() *NullableStringClient { + return &NullableStringClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/http-specs/type/property/nullablegroup/zz_nullablebytes_client.go b/test/http-specs/type/property/nullablegroup/zz_nullablebytes_client.go new file mode 100644 index 000000000000..025b92e2e8ba --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/zz_nullablebytes_client.go @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nullablegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// NullableBytesClient contains the methods for the NullableBytes group. +// Don't use this type directly, use [NullableClient.NewNullableBytesClient] instead. +type NullableBytesClient struct { + internal *azcore.Client + endpoint string +} + +// GetNonNull - Get models that will return all properties in the model +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableBytesClientGetNonNullOptions contains the optional parameters for the NullableBytesClient.GetNonNull +// method. +func (client *NullableBytesClient) GetNonNull(ctx context.Context, options *NullableBytesClientGetNonNullOptions) (NullableBytesClientGetNonNullResponse, error) { + var err error + const operationName = "NullableBytesClient.GetNonNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getNonNullCreateRequest(ctx, options) + if err != nil { + return NullableBytesClientGetNonNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableBytesClientGetNonNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NullableBytesClientGetNonNullResponse{}, err + } + resp, err := client.getNonNullHandleResponse(httpResp) + return resp, err +} + +// getNonNullCreateRequest creates the GetNonNull request. +func (client *NullableBytesClient) getNonNullCreateRequest(ctx context.Context, _ *NullableBytesClientGetNonNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/bytes/non-null" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getNonNullHandleResponse handles the GetNonNull response. +func (client *NullableBytesClient) getNonNullHandleResponse(resp *http.Response) (NullableBytesClientGetNonNullResponse, error) { + result := NullableBytesClientGetNonNullResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BytesProperty); err != nil { + return NullableBytesClientGetNonNullResponse{}, err + } + return result, nil +} + +// GetNull - Get models that will return the default object +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableBytesClientGetNullOptions contains the optional parameters for the NullableBytesClient.GetNull method. +func (client *NullableBytesClient) GetNull(ctx context.Context, options *NullableBytesClientGetNullOptions) (NullableBytesClientGetNullResponse, error) { + var err error + const operationName = "NullableBytesClient.GetNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getNullCreateRequest(ctx, options) + if err != nil { + return NullableBytesClientGetNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableBytesClientGetNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NullableBytesClientGetNullResponse{}, err + } + resp, err := client.getNullHandleResponse(httpResp) + return resp, err +} + +// getNullCreateRequest creates the GetNull request. +func (client *NullableBytesClient) getNullCreateRequest(ctx context.Context, _ *NullableBytesClientGetNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/bytes/null" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getNullHandleResponse handles the GetNull response. +func (client *NullableBytesClient) getNullHandleResponse(resp *http.Response) (NullableBytesClientGetNullResponse, error) { + result := NullableBytesClientGetNullResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BytesProperty); err != nil { + return NullableBytesClientGetNullResponse{}, err + } + return result, nil +} + +// PatchNonNull - Put a body with all properties present. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableBytesClientPatchNonNullOptions contains the optional parameters for the NullableBytesClient.PatchNonNull +// method. +func (client *NullableBytesClient) PatchNonNull(ctx context.Context, body BytesProperty, options *NullableBytesClientPatchNonNullOptions) (NullableBytesClientPatchNonNullResponse, error) { + var err error + const operationName = "NullableBytesClient.PatchNonNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.patchNonNullCreateRequest(ctx, body, options) + if err != nil { + return NullableBytesClientPatchNonNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableBytesClientPatchNonNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return NullableBytesClientPatchNonNullResponse{}, err + } + return NullableBytesClientPatchNonNullResponse{}, nil +} + +// patchNonNullCreateRequest creates the PatchNonNull request. +func (client *NullableBytesClient) patchNonNullCreateRequest(ctx context.Context, body BytesProperty, _ *NullableBytesClientPatchNonNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/bytes/non-null" + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/merge-patch+json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// PatchNull - Put a body with default properties. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableBytesClientPatchNullOptions contains the optional parameters for the NullableBytesClient.PatchNull method. +func (client *NullableBytesClient) PatchNull(ctx context.Context, body BytesProperty, options *NullableBytesClientPatchNullOptions) (NullableBytesClientPatchNullResponse, error) { + var err error + const operationName = "NullableBytesClient.PatchNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.patchNullCreateRequest(ctx, body, options) + if err != nil { + return NullableBytesClientPatchNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableBytesClientPatchNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return NullableBytesClientPatchNullResponse{}, err + } + return NullableBytesClientPatchNullResponse{}, nil +} + +// patchNullCreateRequest creates the PatchNull request. +func (client *NullableBytesClient) patchNullCreateRequest(ctx context.Context, body BytesProperty, _ *NullableBytesClientPatchNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/bytes/null" + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/merge-patch+json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/nullablegroup/zz_nullablecollectionsbyte_client.go b/test/http-specs/type/property/nullablegroup/zz_nullablecollectionsbyte_client.go new file mode 100644 index 000000000000..d70a8ec14997 --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/zz_nullablecollectionsbyte_client.go @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nullablegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// NullableCollectionsByteClient contains the methods for the NullableCollectionsByte group. +// Don't use this type directly, use [NullableClient.NewNullableCollectionsByteClient] instead. +type NullableCollectionsByteClient struct { + internal *azcore.Client + endpoint string +} + +// GetNonNull - Get models that will return all properties in the model +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableCollectionsByteClientGetNonNullOptions contains the optional parameters for the NullableCollectionsByteClient.GetNonNull +// method. +func (client *NullableCollectionsByteClient) GetNonNull(ctx context.Context, options *NullableCollectionsByteClientGetNonNullOptions) (NullableCollectionsByteClientGetNonNullResponse, error) { + var err error + const operationName = "NullableCollectionsByteClient.GetNonNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getNonNullCreateRequest(ctx, options) + if err != nil { + return NullableCollectionsByteClientGetNonNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableCollectionsByteClientGetNonNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NullableCollectionsByteClientGetNonNullResponse{}, err + } + resp, err := client.getNonNullHandleResponse(httpResp) + return resp, err +} + +// getNonNullCreateRequest creates the GetNonNull request. +func (client *NullableCollectionsByteClient) getNonNullCreateRequest(ctx context.Context, _ *NullableCollectionsByteClientGetNonNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/collections/bytes/non-null" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getNonNullHandleResponse handles the GetNonNull response. +func (client *NullableCollectionsByteClient) getNonNullHandleResponse(resp *http.Response) (NullableCollectionsByteClientGetNonNullResponse, error) { + result := NullableCollectionsByteClientGetNonNullResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CollectionsByteProperty); err != nil { + return NullableCollectionsByteClientGetNonNullResponse{}, err + } + return result, nil +} + +// GetNull - Get models that will return the default object +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableCollectionsByteClientGetNullOptions contains the optional parameters for the NullableCollectionsByteClient.GetNull +// method. +func (client *NullableCollectionsByteClient) GetNull(ctx context.Context, options *NullableCollectionsByteClientGetNullOptions) (NullableCollectionsByteClientGetNullResponse, error) { + var err error + const operationName = "NullableCollectionsByteClient.GetNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getNullCreateRequest(ctx, options) + if err != nil { + return NullableCollectionsByteClientGetNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableCollectionsByteClientGetNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NullableCollectionsByteClientGetNullResponse{}, err + } + resp, err := client.getNullHandleResponse(httpResp) + return resp, err +} + +// getNullCreateRequest creates the GetNull request. +func (client *NullableCollectionsByteClient) getNullCreateRequest(ctx context.Context, _ *NullableCollectionsByteClientGetNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/collections/bytes/null" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getNullHandleResponse handles the GetNull response. +func (client *NullableCollectionsByteClient) getNullHandleResponse(resp *http.Response) (NullableCollectionsByteClientGetNullResponse, error) { + result := NullableCollectionsByteClientGetNullResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CollectionsByteProperty); err != nil { + return NullableCollectionsByteClientGetNullResponse{}, err + } + return result, nil +} + +// PatchNonNull - Put a body with all properties present. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableCollectionsByteClientPatchNonNullOptions contains the optional parameters for the NullableCollectionsByteClient.PatchNonNull +// method. +func (client *NullableCollectionsByteClient) PatchNonNull(ctx context.Context, body CollectionsByteProperty, options *NullableCollectionsByteClientPatchNonNullOptions) (NullableCollectionsByteClientPatchNonNullResponse, error) { + var err error + const operationName = "NullableCollectionsByteClient.PatchNonNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.patchNonNullCreateRequest(ctx, body, options) + if err != nil { + return NullableCollectionsByteClientPatchNonNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableCollectionsByteClientPatchNonNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return NullableCollectionsByteClientPatchNonNullResponse{}, err + } + return NullableCollectionsByteClientPatchNonNullResponse{}, nil +} + +// patchNonNullCreateRequest creates the PatchNonNull request. +func (client *NullableCollectionsByteClient) patchNonNullCreateRequest(ctx context.Context, body CollectionsByteProperty, _ *NullableCollectionsByteClientPatchNonNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/collections/bytes/non-null" + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/merge-patch+json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// PatchNull - Put a body with default properties. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableCollectionsByteClientPatchNullOptions contains the optional parameters for the NullableCollectionsByteClient.PatchNull +// method. +func (client *NullableCollectionsByteClient) PatchNull(ctx context.Context, body CollectionsByteProperty, options *NullableCollectionsByteClientPatchNullOptions) (NullableCollectionsByteClientPatchNullResponse, error) { + var err error + const operationName = "NullableCollectionsByteClient.PatchNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.patchNullCreateRequest(ctx, body, options) + if err != nil { + return NullableCollectionsByteClientPatchNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableCollectionsByteClientPatchNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return NullableCollectionsByteClientPatchNullResponse{}, err + } + return NullableCollectionsByteClientPatchNullResponse{}, nil +} + +// patchNullCreateRequest creates the PatchNull request. +func (client *NullableCollectionsByteClient) patchNullCreateRequest(ctx context.Context, body CollectionsByteProperty, _ *NullableCollectionsByteClientPatchNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/collections/bytes/null" + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/merge-patch+json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/nullablegroup/zz_nullablecollectionsmodel_client.go b/test/http-specs/type/property/nullablegroup/zz_nullablecollectionsmodel_client.go new file mode 100644 index 000000000000..20ecc605df25 --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/zz_nullablecollectionsmodel_client.go @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nullablegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// NullableCollectionsModelClient contains the methods for the NullableCollectionsModel group. +// Don't use this type directly, use [NullableClient.NewNullableCollectionsModelClient] instead. +type NullableCollectionsModelClient struct { + internal *azcore.Client + endpoint string +} + +// GetNonNull - Get models that will return all properties in the model +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableCollectionsModelClientGetNonNullOptions contains the optional parameters for the NullableCollectionsModelClient.GetNonNull +// method. +func (client *NullableCollectionsModelClient) GetNonNull(ctx context.Context, options *NullableCollectionsModelClientGetNonNullOptions) (NullableCollectionsModelClientGetNonNullResponse, error) { + var err error + const operationName = "NullableCollectionsModelClient.GetNonNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getNonNullCreateRequest(ctx, options) + if err != nil { + return NullableCollectionsModelClientGetNonNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableCollectionsModelClientGetNonNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NullableCollectionsModelClientGetNonNullResponse{}, err + } + resp, err := client.getNonNullHandleResponse(httpResp) + return resp, err +} + +// getNonNullCreateRequest creates the GetNonNull request. +func (client *NullableCollectionsModelClient) getNonNullCreateRequest(ctx context.Context, _ *NullableCollectionsModelClientGetNonNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/collections/model/non-null" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getNonNullHandleResponse handles the GetNonNull response. +func (client *NullableCollectionsModelClient) getNonNullHandleResponse(resp *http.Response) (NullableCollectionsModelClientGetNonNullResponse, error) { + result := NullableCollectionsModelClientGetNonNullResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CollectionsModelProperty); err != nil { + return NullableCollectionsModelClientGetNonNullResponse{}, err + } + return result, nil +} + +// GetNull - Get models that will return the default object +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableCollectionsModelClientGetNullOptions contains the optional parameters for the NullableCollectionsModelClient.GetNull +// method. +func (client *NullableCollectionsModelClient) GetNull(ctx context.Context, options *NullableCollectionsModelClientGetNullOptions) (NullableCollectionsModelClientGetNullResponse, error) { + var err error + const operationName = "NullableCollectionsModelClient.GetNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getNullCreateRequest(ctx, options) + if err != nil { + return NullableCollectionsModelClientGetNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableCollectionsModelClientGetNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NullableCollectionsModelClientGetNullResponse{}, err + } + resp, err := client.getNullHandleResponse(httpResp) + return resp, err +} + +// getNullCreateRequest creates the GetNull request. +func (client *NullableCollectionsModelClient) getNullCreateRequest(ctx context.Context, _ *NullableCollectionsModelClientGetNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/collections/model/null" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getNullHandleResponse handles the GetNull response. +func (client *NullableCollectionsModelClient) getNullHandleResponse(resp *http.Response) (NullableCollectionsModelClientGetNullResponse, error) { + result := NullableCollectionsModelClientGetNullResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CollectionsModelProperty); err != nil { + return NullableCollectionsModelClientGetNullResponse{}, err + } + return result, nil +} + +// PatchNonNull - Put a body with all properties present. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableCollectionsModelClientPatchNonNullOptions contains the optional parameters for the NullableCollectionsModelClient.PatchNonNull +// method. +func (client *NullableCollectionsModelClient) PatchNonNull(ctx context.Context, body CollectionsModelProperty, options *NullableCollectionsModelClientPatchNonNullOptions) (NullableCollectionsModelClientPatchNonNullResponse, error) { + var err error + const operationName = "NullableCollectionsModelClient.PatchNonNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.patchNonNullCreateRequest(ctx, body, options) + if err != nil { + return NullableCollectionsModelClientPatchNonNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableCollectionsModelClientPatchNonNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return NullableCollectionsModelClientPatchNonNullResponse{}, err + } + return NullableCollectionsModelClientPatchNonNullResponse{}, nil +} + +// patchNonNullCreateRequest creates the PatchNonNull request. +func (client *NullableCollectionsModelClient) patchNonNullCreateRequest(ctx context.Context, body CollectionsModelProperty, _ *NullableCollectionsModelClientPatchNonNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/collections/model/non-null" + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/merge-patch+json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// PatchNull - Put a body with default properties. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableCollectionsModelClientPatchNullOptions contains the optional parameters for the NullableCollectionsModelClient.PatchNull +// method. +func (client *NullableCollectionsModelClient) PatchNull(ctx context.Context, body CollectionsModelProperty, options *NullableCollectionsModelClientPatchNullOptions) (NullableCollectionsModelClientPatchNullResponse, error) { + var err error + const operationName = "NullableCollectionsModelClient.PatchNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.patchNullCreateRequest(ctx, body, options) + if err != nil { + return NullableCollectionsModelClientPatchNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableCollectionsModelClientPatchNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return NullableCollectionsModelClientPatchNullResponse{}, err + } + return NullableCollectionsModelClientPatchNullResponse{}, nil +} + +// patchNullCreateRequest creates the PatchNull request. +func (client *NullableCollectionsModelClient) patchNullCreateRequest(ctx context.Context, body CollectionsModelProperty, _ *NullableCollectionsModelClientPatchNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/collections/model/null" + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/merge-patch+json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/nullablegroup/zz_nullablecollectionsstring_client.go b/test/http-specs/type/property/nullablegroup/zz_nullablecollectionsstring_client.go new file mode 100644 index 000000000000..9e4060f5647b --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/zz_nullablecollectionsstring_client.go @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nullablegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// NullableCollectionsStringClient contains the methods for the NullableCollectionsString group. +// Don't use this type directly, use [NullableClient.NewNullableCollectionsStringClient] instead. +type NullableCollectionsStringClient struct { + internal *azcore.Client + endpoint string +} + +// GetNonNull - Get models that will return all properties in the model +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableCollectionsStringClientGetNonNullOptions contains the optional parameters for the NullableCollectionsStringClient.GetNonNull +// method. +func (client *NullableCollectionsStringClient) GetNonNull(ctx context.Context, options *NullableCollectionsStringClientGetNonNullOptions) (NullableCollectionsStringClientGetNonNullResponse, error) { + var err error + const operationName = "NullableCollectionsStringClient.GetNonNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getNonNullCreateRequest(ctx, options) + if err != nil { + return NullableCollectionsStringClientGetNonNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableCollectionsStringClientGetNonNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NullableCollectionsStringClientGetNonNullResponse{}, err + } + resp, err := client.getNonNullHandleResponse(httpResp) + return resp, err +} + +// getNonNullCreateRequest creates the GetNonNull request. +func (client *NullableCollectionsStringClient) getNonNullCreateRequest(ctx context.Context, _ *NullableCollectionsStringClientGetNonNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/collections/string/non-null" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getNonNullHandleResponse handles the GetNonNull response. +func (client *NullableCollectionsStringClient) getNonNullHandleResponse(resp *http.Response) (NullableCollectionsStringClientGetNonNullResponse, error) { + result := NullableCollectionsStringClientGetNonNullResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CollectionsStringProperty); err != nil { + return NullableCollectionsStringClientGetNonNullResponse{}, err + } + return result, nil +} + +// GetNull - Get models that will return the default object +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableCollectionsStringClientGetNullOptions contains the optional parameters for the NullableCollectionsStringClient.GetNull +// method. +func (client *NullableCollectionsStringClient) GetNull(ctx context.Context, options *NullableCollectionsStringClientGetNullOptions) (NullableCollectionsStringClientGetNullResponse, error) { + var err error + const operationName = "NullableCollectionsStringClient.GetNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getNullCreateRequest(ctx, options) + if err != nil { + return NullableCollectionsStringClientGetNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableCollectionsStringClientGetNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NullableCollectionsStringClientGetNullResponse{}, err + } + resp, err := client.getNullHandleResponse(httpResp) + return resp, err +} + +// getNullCreateRequest creates the GetNull request. +func (client *NullableCollectionsStringClient) getNullCreateRequest(ctx context.Context, _ *NullableCollectionsStringClientGetNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/collections/string/null" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getNullHandleResponse handles the GetNull response. +func (client *NullableCollectionsStringClient) getNullHandleResponse(resp *http.Response) (NullableCollectionsStringClientGetNullResponse, error) { + result := NullableCollectionsStringClientGetNullResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CollectionsStringProperty); err != nil { + return NullableCollectionsStringClientGetNullResponse{}, err + } + return result, nil +} + +// PatchNonNull - Put a body with all properties present. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableCollectionsStringClientPatchNonNullOptions contains the optional parameters for the NullableCollectionsStringClient.PatchNonNull +// method. +func (client *NullableCollectionsStringClient) PatchNonNull(ctx context.Context, body CollectionsStringProperty, options *NullableCollectionsStringClientPatchNonNullOptions) (NullableCollectionsStringClientPatchNonNullResponse, error) { + var err error + const operationName = "NullableCollectionsStringClient.PatchNonNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.patchNonNullCreateRequest(ctx, body, options) + if err != nil { + return NullableCollectionsStringClientPatchNonNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableCollectionsStringClientPatchNonNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return NullableCollectionsStringClientPatchNonNullResponse{}, err + } + return NullableCollectionsStringClientPatchNonNullResponse{}, nil +} + +// patchNonNullCreateRequest creates the PatchNonNull request. +func (client *NullableCollectionsStringClient) patchNonNullCreateRequest(ctx context.Context, body CollectionsStringProperty, _ *NullableCollectionsStringClientPatchNonNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/collections/string/non-null" + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/merge-patch+json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// PatchNull - Put a body with default properties. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableCollectionsStringClientPatchNullOptions contains the optional parameters for the NullableCollectionsStringClient.PatchNull +// method. +func (client *NullableCollectionsStringClient) PatchNull(ctx context.Context, body CollectionsStringProperty, options *NullableCollectionsStringClientPatchNullOptions) (NullableCollectionsStringClientPatchNullResponse, error) { + var err error + const operationName = "NullableCollectionsStringClient.PatchNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.patchNullCreateRequest(ctx, body, options) + if err != nil { + return NullableCollectionsStringClientPatchNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableCollectionsStringClientPatchNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return NullableCollectionsStringClientPatchNullResponse{}, err + } + return NullableCollectionsStringClientPatchNullResponse{}, nil +} + +// patchNullCreateRequest creates the PatchNull request. +func (client *NullableCollectionsStringClient) patchNullCreateRequest(ctx context.Context, body CollectionsStringProperty, _ *NullableCollectionsStringClientPatchNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/collections/string/null" + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/merge-patch+json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/nullablegroup/zz_nullabledatetime_client.go b/test/http-specs/type/property/nullablegroup/zz_nullabledatetime_client.go new file mode 100644 index 000000000000..31f57bd42a19 --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/zz_nullabledatetime_client.go @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nullablegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// NullableDatetimeClient contains the methods for the NullableDatetime group. +// Don't use this type directly, use [NullableClient.NewNullableDatetimeClient] instead. +type NullableDatetimeClient struct { + internal *azcore.Client + endpoint string +} + +// GetNonNull - Get models that will return all properties in the model +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableDatetimeClientGetNonNullOptions contains the optional parameters for the NullableDatetimeClient.GetNonNull +// method. +func (client *NullableDatetimeClient) GetNonNull(ctx context.Context, options *NullableDatetimeClientGetNonNullOptions) (NullableDatetimeClientGetNonNullResponse, error) { + var err error + const operationName = "NullableDatetimeClient.GetNonNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getNonNullCreateRequest(ctx, options) + if err != nil { + return NullableDatetimeClientGetNonNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableDatetimeClientGetNonNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NullableDatetimeClientGetNonNullResponse{}, err + } + resp, err := client.getNonNullHandleResponse(httpResp) + return resp, err +} + +// getNonNullCreateRequest creates the GetNonNull request. +func (client *NullableDatetimeClient) getNonNullCreateRequest(ctx context.Context, _ *NullableDatetimeClientGetNonNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/datetime/non-null" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getNonNullHandleResponse handles the GetNonNull response. +func (client *NullableDatetimeClient) getNonNullHandleResponse(resp *http.Response) (NullableDatetimeClientGetNonNullResponse, error) { + result := NullableDatetimeClientGetNonNullResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DatetimeProperty); err != nil { + return NullableDatetimeClientGetNonNullResponse{}, err + } + return result, nil +} + +// GetNull - Get models that will return the default object +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableDatetimeClientGetNullOptions contains the optional parameters for the NullableDatetimeClient.GetNull +// method. +func (client *NullableDatetimeClient) GetNull(ctx context.Context, options *NullableDatetimeClientGetNullOptions) (NullableDatetimeClientGetNullResponse, error) { + var err error + const operationName = "NullableDatetimeClient.GetNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getNullCreateRequest(ctx, options) + if err != nil { + return NullableDatetimeClientGetNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableDatetimeClientGetNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NullableDatetimeClientGetNullResponse{}, err + } + resp, err := client.getNullHandleResponse(httpResp) + return resp, err +} + +// getNullCreateRequest creates the GetNull request. +func (client *NullableDatetimeClient) getNullCreateRequest(ctx context.Context, _ *NullableDatetimeClientGetNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/datetime/null" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getNullHandleResponse handles the GetNull response. +func (client *NullableDatetimeClient) getNullHandleResponse(resp *http.Response) (NullableDatetimeClientGetNullResponse, error) { + result := NullableDatetimeClientGetNullResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DatetimeProperty); err != nil { + return NullableDatetimeClientGetNullResponse{}, err + } + return result, nil +} + +// PatchNonNull - Put a body with all properties present. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableDatetimeClientPatchNonNullOptions contains the optional parameters for the NullableDatetimeClient.PatchNonNull +// method. +func (client *NullableDatetimeClient) PatchNonNull(ctx context.Context, body DatetimeProperty, options *NullableDatetimeClientPatchNonNullOptions) (NullableDatetimeClientPatchNonNullResponse, error) { + var err error + const operationName = "NullableDatetimeClient.PatchNonNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.patchNonNullCreateRequest(ctx, body, options) + if err != nil { + return NullableDatetimeClientPatchNonNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableDatetimeClientPatchNonNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return NullableDatetimeClientPatchNonNullResponse{}, err + } + return NullableDatetimeClientPatchNonNullResponse{}, nil +} + +// patchNonNullCreateRequest creates the PatchNonNull request. +func (client *NullableDatetimeClient) patchNonNullCreateRequest(ctx context.Context, body DatetimeProperty, _ *NullableDatetimeClientPatchNonNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/datetime/non-null" + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/merge-patch+json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// PatchNull - Put a body with default properties. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableDatetimeClientPatchNullOptions contains the optional parameters for the NullableDatetimeClient.PatchNull +// method. +func (client *NullableDatetimeClient) PatchNull(ctx context.Context, body DatetimeProperty, options *NullableDatetimeClientPatchNullOptions) (NullableDatetimeClientPatchNullResponse, error) { + var err error + const operationName = "NullableDatetimeClient.PatchNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.patchNullCreateRequest(ctx, body, options) + if err != nil { + return NullableDatetimeClientPatchNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableDatetimeClientPatchNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return NullableDatetimeClientPatchNullResponse{}, err + } + return NullableDatetimeClientPatchNullResponse{}, nil +} + +// patchNullCreateRequest creates the PatchNull request. +func (client *NullableDatetimeClient) patchNullCreateRequest(ctx context.Context, body DatetimeProperty, _ *NullableDatetimeClientPatchNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/datetime/null" + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/merge-patch+json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/nullablegroup/zz_nullableduration_client.go b/test/http-specs/type/property/nullablegroup/zz_nullableduration_client.go new file mode 100644 index 000000000000..2131bc2c96f2 --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/zz_nullableduration_client.go @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nullablegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// NullableDurationClient contains the methods for the NullableDuration group. +// Don't use this type directly, use [NullableClient.NewNullableDurationClient] instead. +type NullableDurationClient struct { + internal *azcore.Client + endpoint string +} + +// GetNonNull - Get models that will return all properties in the model +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableDurationClientGetNonNullOptions contains the optional parameters for the NullableDurationClient.GetNonNull +// method. +func (client *NullableDurationClient) GetNonNull(ctx context.Context, options *NullableDurationClientGetNonNullOptions) (NullableDurationClientGetNonNullResponse, error) { + var err error + const operationName = "NullableDurationClient.GetNonNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getNonNullCreateRequest(ctx, options) + if err != nil { + return NullableDurationClientGetNonNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableDurationClientGetNonNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NullableDurationClientGetNonNullResponse{}, err + } + resp, err := client.getNonNullHandleResponse(httpResp) + return resp, err +} + +// getNonNullCreateRequest creates the GetNonNull request. +func (client *NullableDurationClient) getNonNullCreateRequest(ctx context.Context, _ *NullableDurationClientGetNonNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/duration/non-null" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getNonNullHandleResponse handles the GetNonNull response. +func (client *NullableDurationClient) getNonNullHandleResponse(resp *http.Response) (NullableDurationClientGetNonNullResponse, error) { + result := NullableDurationClientGetNonNullResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DurationProperty); err != nil { + return NullableDurationClientGetNonNullResponse{}, err + } + return result, nil +} + +// GetNull - Get models that will return the default object +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableDurationClientGetNullOptions contains the optional parameters for the NullableDurationClient.GetNull +// method. +func (client *NullableDurationClient) GetNull(ctx context.Context, options *NullableDurationClientGetNullOptions) (NullableDurationClientGetNullResponse, error) { + var err error + const operationName = "NullableDurationClient.GetNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getNullCreateRequest(ctx, options) + if err != nil { + return NullableDurationClientGetNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableDurationClientGetNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NullableDurationClientGetNullResponse{}, err + } + resp, err := client.getNullHandleResponse(httpResp) + return resp, err +} + +// getNullCreateRequest creates the GetNull request. +func (client *NullableDurationClient) getNullCreateRequest(ctx context.Context, _ *NullableDurationClientGetNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/duration/null" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getNullHandleResponse handles the GetNull response. +func (client *NullableDurationClient) getNullHandleResponse(resp *http.Response) (NullableDurationClientGetNullResponse, error) { + result := NullableDurationClientGetNullResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DurationProperty); err != nil { + return NullableDurationClientGetNullResponse{}, err + } + return result, nil +} + +// PatchNonNull - Put a body with all properties present. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableDurationClientPatchNonNullOptions contains the optional parameters for the NullableDurationClient.PatchNonNull +// method. +func (client *NullableDurationClient) PatchNonNull(ctx context.Context, body DurationProperty, options *NullableDurationClientPatchNonNullOptions) (NullableDurationClientPatchNonNullResponse, error) { + var err error + const operationName = "NullableDurationClient.PatchNonNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.patchNonNullCreateRequest(ctx, body, options) + if err != nil { + return NullableDurationClientPatchNonNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableDurationClientPatchNonNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return NullableDurationClientPatchNonNullResponse{}, err + } + return NullableDurationClientPatchNonNullResponse{}, nil +} + +// patchNonNullCreateRequest creates the PatchNonNull request. +func (client *NullableDurationClient) patchNonNullCreateRequest(ctx context.Context, body DurationProperty, _ *NullableDurationClientPatchNonNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/duration/non-null" + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/merge-patch+json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// PatchNull - Put a body with default properties. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableDurationClientPatchNullOptions contains the optional parameters for the NullableDurationClient.PatchNull +// method. +func (client *NullableDurationClient) PatchNull(ctx context.Context, body DurationProperty, options *NullableDurationClientPatchNullOptions) (NullableDurationClientPatchNullResponse, error) { + var err error + const operationName = "NullableDurationClient.PatchNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.patchNullCreateRequest(ctx, body, options) + if err != nil { + return NullableDurationClientPatchNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableDurationClientPatchNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return NullableDurationClientPatchNullResponse{}, err + } + return NullableDurationClientPatchNullResponse{}, nil +} + +// patchNullCreateRequest creates the PatchNull request. +func (client *NullableDurationClient) patchNullCreateRequest(ctx context.Context, body DurationProperty, _ *NullableDurationClientPatchNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/duration/null" + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/merge-patch+json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/nullablegroup/zz_nullablestring_client.go b/test/http-specs/type/property/nullablegroup/zz_nullablestring_client.go new file mode 100644 index 000000000000..6040b0a1eacf --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/zz_nullablestring_client.go @@ -0,0 +1,189 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nullablegroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// NullableStringClient contains the methods for the NullableString group. +// Don't use this type directly, use [NullableClient.NewNullableStringClient] instead. +type NullableStringClient struct { + internal *azcore.Client + endpoint string +} + +// GetNonNull - Get models that will return all properties in the model +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableStringClientGetNonNullOptions contains the optional parameters for the NullableStringClient.GetNonNull +// method. +func (client *NullableStringClient) GetNonNull(ctx context.Context, options *NullableStringClientGetNonNullOptions) (NullableStringClientGetNonNullResponse, error) { + var err error + const operationName = "NullableStringClient.GetNonNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getNonNullCreateRequest(ctx, options) + if err != nil { + return NullableStringClientGetNonNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableStringClientGetNonNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NullableStringClientGetNonNullResponse{}, err + } + resp, err := client.getNonNullHandleResponse(httpResp) + return resp, err +} + +// getNonNullCreateRequest creates the GetNonNull request. +func (client *NullableStringClient) getNonNullCreateRequest(ctx context.Context, _ *NullableStringClientGetNonNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/string/non-null" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getNonNullHandleResponse handles the GetNonNull response. +func (client *NullableStringClient) getNonNullHandleResponse(resp *http.Response) (NullableStringClientGetNonNullResponse, error) { + result := NullableStringClientGetNonNullResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.StringProperty); err != nil { + return NullableStringClientGetNonNullResponse{}, err + } + return result, nil +} + +// GetNull - Get models that will return the default object +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableStringClientGetNullOptions contains the optional parameters for the NullableStringClient.GetNull method. +func (client *NullableStringClient) GetNull(ctx context.Context, options *NullableStringClientGetNullOptions) (NullableStringClientGetNullResponse, error) { + var err error + const operationName = "NullableStringClient.GetNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getNullCreateRequest(ctx, options) + if err != nil { + return NullableStringClientGetNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableStringClientGetNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NullableStringClientGetNullResponse{}, err + } + resp, err := client.getNullHandleResponse(httpResp) + return resp, err +} + +// getNullCreateRequest creates the GetNull request. +func (client *NullableStringClient) getNullCreateRequest(ctx context.Context, _ *NullableStringClientGetNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/string/null" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getNullHandleResponse handles the GetNull response. +func (client *NullableStringClient) getNullHandleResponse(resp *http.Response) (NullableStringClientGetNullResponse, error) { + result := NullableStringClientGetNullResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.StringProperty); err != nil { + return NullableStringClientGetNullResponse{}, err + } + return result, nil +} + +// PatchNonNull - Put a body with all properties present. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableStringClientPatchNonNullOptions contains the optional parameters for the NullableStringClient.PatchNonNull +// method. +func (client *NullableStringClient) PatchNonNull(ctx context.Context, body StringProperty, options *NullableStringClientPatchNonNullOptions) (NullableStringClientPatchNonNullResponse, error) { + var err error + const operationName = "NullableStringClient.PatchNonNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.patchNonNullCreateRequest(ctx, body, options) + if err != nil { + return NullableStringClientPatchNonNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableStringClientPatchNonNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return NullableStringClientPatchNonNullResponse{}, err + } + return NullableStringClientPatchNonNullResponse{}, nil +} + +// patchNonNullCreateRequest creates the PatchNonNull request. +func (client *NullableStringClient) patchNonNullCreateRequest(ctx context.Context, body StringProperty, _ *NullableStringClientPatchNonNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/string/non-null" + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/merge-patch+json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// PatchNull - Put a body with default properties. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - NullableStringClientPatchNullOptions contains the optional parameters for the NullableStringClient.PatchNull +// method. +func (client *NullableStringClient) PatchNull(ctx context.Context, body StringProperty, options *NullableStringClientPatchNullOptions) (NullableStringClientPatchNullResponse, error) { + var err error + const operationName = "NullableStringClient.PatchNull" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.patchNullCreateRequest(ctx, body, options) + if err != nil { + return NullableStringClientPatchNullResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NullableStringClientPatchNullResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return NullableStringClientPatchNullResponse{}, err + } + return NullableStringClientPatchNullResponse{}, nil +} + +// patchNullCreateRequest creates the PatchNull request. +func (client *NullableStringClient) patchNullCreateRequest(ctx context.Context, body StringProperty, _ *NullableStringClientPatchNullOptions) (*policy.Request, error) { + urlPath := "/type/property/nullable/string/null" + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/merge-patch+json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/nullablegroup/zz_options.go b/test/http-specs/type/property/nullablegroup/zz_options.go new file mode 100644 index 000000000000..9ca35d6b2079 --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/zz_options.go @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nullablegroup + +// NullableBytesClientGetNonNullOptions contains the optional parameters for the NullableBytesClient.GetNonNull method. +type NullableBytesClientGetNonNullOptions struct { + // placeholder for future optional parameters +} + +// NullableBytesClientGetNullOptions contains the optional parameters for the NullableBytesClient.GetNull method. +type NullableBytesClientGetNullOptions struct { + // placeholder for future optional parameters +} + +// NullableBytesClientPatchNonNullOptions contains the optional parameters for the NullableBytesClient.PatchNonNull method. +type NullableBytesClientPatchNonNullOptions struct { + // placeholder for future optional parameters +} + +// NullableBytesClientPatchNullOptions contains the optional parameters for the NullableBytesClient.PatchNull method. +type NullableBytesClientPatchNullOptions struct { + // placeholder for future optional parameters +} + +// NullableCollectionsByteClientGetNonNullOptions contains the optional parameters for the NullableCollectionsByteClient.GetNonNull +// method. +type NullableCollectionsByteClientGetNonNullOptions struct { + // placeholder for future optional parameters +} + +// NullableCollectionsByteClientGetNullOptions contains the optional parameters for the NullableCollectionsByteClient.GetNull +// method. +type NullableCollectionsByteClientGetNullOptions struct { + // placeholder for future optional parameters +} + +// NullableCollectionsByteClientPatchNonNullOptions contains the optional parameters for the NullableCollectionsByteClient.PatchNonNull +// method. +type NullableCollectionsByteClientPatchNonNullOptions struct { + // placeholder for future optional parameters +} + +// NullableCollectionsByteClientPatchNullOptions contains the optional parameters for the NullableCollectionsByteClient.PatchNull +// method. +type NullableCollectionsByteClientPatchNullOptions struct { + // placeholder for future optional parameters +} + +// NullableCollectionsModelClientGetNonNullOptions contains the optional parameters for the NullableCollectionsModelClient.GetNonNull +// method. +type NullableCollectionsModelClientGetNonNullOptions struct { + // placeholder for future optional parameters +} + +// NullableCollectionsModelClientGetNullOptions contains the optional parameters for the NullableCollectionsModelClient.GetNull +// method. +type NullableCollectionsModelClientGetNullOptions struct { + // placeholder for future optional parameters +} + +// NullableCollectionsModelClientPatchNonNullOptions contains the optional parameters for the NullableCollectionsModelClient.PatchNonNull +// method. +type NullableCollectionsModelClientPatchNonNullOptions struct { + // placeholder for future optional parameters +} + +// NullableCollectionsModelClientPatchNullOptions contains the optional parameters for the NullableCollectionsModelClient.PatchNull +// method. +type NullableCollectionsModelClientPatchNullOptions struct { + // placeholder for future optional parameters +} + +// NullableCollectionsStringClientGetNonNullOptions contains the optional parameters for the NullableCollectionsStringClient.GetNonNull +// method. +type NullableCollectionsStringClientGetNonNullOptions struct { + // placeholder for future optional parameters +} + +// NullableCollectionsStringClientGetNullOptions contains the optional parameters for the NullableCollectionsStringClient.GetNull +// method. +type NullableCollectionsStringClientGetNullOptions struct { + // placeholder for future optional parameters +} + +// NullableCollectionsStringClientPatchNonNullOptions contains the optional parameters for the NullableCollectionsStringClient.PatchNonNull +// method. +type NullableCollectionsStringClientPatchNonNullOptions struct { + // placeholder for future optional parameters +} + +// NullableCollectionsStringClientPatchNullOptions contains the optional parameters for the NullableCollectionsStringClient.PatchNull +// method. +type NullableCollectionsStringClientPatchNullOptions struct { + // placeholder for future optional parameters +} + +// NullableDatetimeClientGetNonNullOptions contains the optional parameters for the NullableDatetimeClient.GetNonNull method. +type NullableDatetimeClientGetNonNullOptions struct { + // placeholder for future optional parameters +} + +// NullableDatetimeClientGetNullOptions contains the optional parameters for the NullableDatetimeClient.GetNull method. +type NullableDatetimeClientGetNullOptions struct { + // placeholder for future optional parameters +} + +// NullableDatetimeClientPatchNonNullOptions contains the optional parameters for the NullableDatetimeClient.PatchNonNull +// method. +type NullableDatetimeClientPatchNonNullOptions struct { + // placeholder for future optional parameters +} + +// NullableDatetimeClientPatchNullOptions contains the optional parameters for the NullableDatetimeClient.PatchNull method. +type NullableDatetimeClientPatchNullOptions struct { + // placeholder for future optional parameters +} + +// NullableDurationClientGetNonNullOptions contains the optional parameters for the NullableDurationClient.GetNonNull method. +type NullableDurationClientGetNonNullOptions struct { + // placeholder for future optional parameters +} + +// NullableDurationClientGetNullOptions contains the optional parameters for the NullableDurationClient.GetNull method. +type NullableDurationClientGetNullOptions struct { + // placeholder for future optional parameters +} + +// NullableDurationClientPatchNonNullOptions contains the optional parameters for the NullableDurationClient.PatchNonNull +// method. +type NullableDurationClientPatchNonNullOptions struct { + // placeholder for future optional parameters +} + +// NullableDurationClientPatchNullOptions contains the optional parameters for the NullableDurationClient.PatchNull method. +type NullableDurationClientPatchNullOptions struct { + // placeholder for future optional parameters +} + +// NullableStringClientGetNonNullOptions contains the optional parameters for the NullableStringClient.GetNonNull method. +type NullableStringClientGetNonNullOptions struct { + // placeholder for future optional parameters +} + +// NullableStringClientGetNullOptions contains the optional parameters for the NullableStringClient.GetNull method. +type NullableStringClientGetNullOptions struct { + // placeholder for future optional parameters +} + +// NullableStringClientPatchNonNullOptions contains the optional parameters for the NullableStringClient.PatchNonNull method. +type NullableStringClientPatchNonNullOptions struct { + // placeholder for future optional parameters +} + +// NullableStringClientPatchNullOptions contains the optional parameters for the NullableStringClient.PatchNull method. +type NullableStringClientPatchNullOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/type/property/nullablegroup/zz_responses.go b/test/http-specs/type/property/nullablegroup/zz_responses.go new file mode 100644 index 000000000000..4b6d6c62bf38 --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/zz_responses.go @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nullablegroup + +// NullableBytesClientGetNonNullResponse contains the response from method NullableBytesClient.GetNonNull. +type NullableBytesClientGetNonNullResponse struct { + // Template type for testing models with nullable property. Pass in the type of the property you are looking for + BytesProperty +} + +// NullableBytesClientGetNullResponse contains the response from method NullableBytesClient.GetNull. +type NullableBytesClientGetNullResponse struct { + // Template type for testing models with nullable property. Pass in the type of the property you are looking for + BytesProperty +} + +// NullableBytesClientPatchNonNullResponse contains the response from method NullableBytesClient.PatchNonNull. +type NullableBytesClientPatchNonNullResponse struct { + // placeholder for future response values +} + +// NullableBytesClientPatchNullResponse contains the response from method NullableBytesClient.PatchNull. +type NullableBytesClientPatchNullResponse struct { + // placeholder for future response values +} + +// NullableCollectionsByteClientGetNonNullResponse contains the response from method NullableCollectionsByteClient.GetNonNull. +type NullableCollectionsByteClientGetNonNullResponse struct { + // Model with collection bytes properties + CollectionsByteProperty +} + +// NullableCollectionsByteClientGetNullResponse contains the response from method NullableCollectionsByteClient.GetNull. +type NullableCollectionsByteClientGetNullResponse struct { + // Model with collection bytes properties + CollectionsByteProperty +} + +// NullableCollectionsByteClientPatchNonNullResponse contains the response from method NullableCollectionsByteClient.PatchNonNull. +type NullableCollectionsByteClientPatchNonNullResponse struct { + // placeholder for future response values +} + +// NullableCollectionsByteClientPatchNullResponse contains the response from method NullableCollectionsByteClient.PatchNull. +type NullableCollectionsByteClientPatchNullResponse struct { + // placeholder for future response values +} + +// NullableCollectionsModelClientGetNonNullResponse contains the response from method NullableCollectionsModelClient.GetNonNull. +type NullableCollectionsModelClientGetNonNullResponse struct { + // Model with collection models properties + CollectionsModelProperty +} + +// NullableCollectionsModelClientGetNullResponse contains the response from method NullableCollectionsModelClient.GetNull. +type NullableCollectionsModelClientGetNullResponse struct { + // Model with collection models properties + CollectionsModelProperty +} + +// NullableCollectionsModelClientPatchNonNullResponse contains the response from method NullableCollectionsModelClient.PatchNonNull. +type NullableCollectionsModelClientPatchNonNullResponse struct { + // placeholder for future response values +} + +// NullableCollectionsModelClientPatchNullResponse contains the response from method NullableCollectionsModelClient.PatchNull. +type NullableCollectionsModelClientPatchNullResponse struct { + // placeholder for future response values +} + +// NullableCollectionsStringClientGetNonNullResponse contains the response from method NullableCollectionsStringClient.GetNonNull. +type NullableCollectionsStringClientGetNonNullResponse struct { + // Model with collection string properties + CollectionsStringProperty +} + +// NullableCollectionsStringClientGetNullResponse contains the response from method NullableCollectionsStringClient.GetNull. +type NullableCollectionsStringClientGetNullResponse struct { + // Model with collection string properties + CollectionsStringProperty +} + +// NullableCollectionsStringClientPatchNonNullResponse contains the response from method NullableCollectionsStringClient.PatchNonNull. +type NullableCollectionsStringClientPatchNonNullResponse struct { + // placeholder for future response values +} + +// NullableCollectionsStringClientPatchNullResponse contains the response from method NullableCollectionsStringClient.PatchNull. +type NullableCollectionsStringClientPatchNullResponse struct { + // placeholder for future response values +} + +// NullableDatetimeClientGetNonNullResponse contains the response from method NullableDatetimeClient.GetNonNull. +type NullableDatetimeClientGetNonNullResponse struct { + // Model with a datetime property + DatetimeProperty +} + +// NullableDatetimeClientGetNullResponse contains the response from method NullableDatetimeClient.GetNull. +type NullableDatetimeClientGetNullResponse struct { + // Model with a datetime property + DatetimeProperty +} + +// NullableDatetimeClientPatchNonNullResponse contains the response from method NullableDatetimeClient.PatchNonNull. +type NullableDatetimeClientPatchNonNullResponse struct { + // placeholder for future response values +} + +// NullableDatetimeClientPatchNullResponse contains the response from method NullableDatetimeClient.PatchNull. +type NullableDatetimeClientPatchNullResponse struct { + // placeholder for future response values +} + +// NullableDurationClientGetNonNullResponse contains the response from method NullableDurationClient.GetNonNull. +type NullableDurationClientGetNonNullResponse struct { + // Model with a duration property + DurationProperty +} + +// NullableDurationClientGetNullResponse contains the response from method NullableDurationClient.GetNull. +type NullableDurationClientGetNullResponse struct { + // Model with a duration property + DurationProperty +} + +// NullableDurationClientPatchNonNullResponse contains the response from method NullableDurationClient.PatchNonNull. +type NullableDurationClientPatchNonNullResponse struct { + // placeholder for future response values +} + +// NullableDurationClientPatchNullResponse contains the response from method NullableDurationClient.PatchNull. +type NullableDurationClientPatchNullResponse struct { + // placeholder for future response values +} + +// NullableStringClientGetNonNullResponse contains the response from method NullableStringClient.GetNonNull. +type NullableStringClientGetNonNullResponse struct { + // Template type for testing models with nullable property. Pass in the type of the property you are looking for + StringProperty +} + +// NullableStringClientGetNullResponse contains the response from method NullableStringClient.GetNull. +type NullableStringClientGetNullResponse struct { + // Template type for testing models with nullable property. Pass in the type of the property you are looking for + StringProperty +} + +// NullableStringClientPatchNonNullResponse contains the response from method NullableStringClient.PatchNonNull. +type NullableStringClientPatchNonNullResponse struct { + // placeholder for future response values +} + +// NullableStringClientPatchNullResponse contains the response from method NullableStringClient.PatchNull. +type NullableStringClientPatchNullResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/type/property/nullablegroup/zz_version.go b/test/http-specs/type/property/nullablegroup/zz_version.go new file mode 100644 index 000000000000..0a9e17985e80 --- /dev/null +++ b/test/http-specs/type/property/nullablegroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package nullablegroup + +const ( + moduleName = "nullablegroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/type/property/optionalitygroup/LICENSE.txt b/test/http-specs/type/property/optionalitygroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/type/property/optionalitygroup/fake/zz_internal.go b/test/http-specs/type/property/optionalitygroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/http-specs/type/property/optionalitygroup/fake/zz_optional_server.go b/test/http-specs/type/property/optionalitygroup/fake/zz_optional_server.go new file mode 100644 index 000000000000..6e3baab44e0c --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/fake/zz_optional_server.go @@ -0,0 +1,204 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// OptionalServer is a fake server for instances of the optionalitygroup.OptionalClient type. +type OptionalServer struct { + // OptionalBooleanLiteralServer contains the fakes for client OptionalBooleanLiteralClient + OptionalBooleanLiteralServer OptionalBooleanLiteralServer + + // OptionalBytesServer contains the fakes for client OptionalBytesClient + OptionalBytesServer OptionalBytesServer + + // OptionalCollectionsByteServer contains the fakes for client OptionalCollectionsByteClient + OptionalCollectionsByteServer OptionalCollectionsByteServer + + // OptionalCollectionsModelServer contains the fakes for client OptionalCollectionsModelClient + OptionalCollectionsModelServer OptionalCollectionsModelServer + + // OptionalDatetimeServer contains the fakes for client OptionalDatetimeClient + OptionalDatetimeServer OptionalDatetimeServer + + // OptionalDurationServer contains the fakes for client OptionalDurationClient + OptionalDurationServer OptionalDurationServer + + // OptionalFloatLiteralServer contains the fakes for client OptionalFloatLiteralClient + OptionalFloatLiteralServer OptionalFloatLiteralServer + + // OptionalIntLiteralServer contains the fakes for client OptionalIntLiteralClient + OptionalIntLiteralServer OptionalIntLiteralServer + + // OptionalPlainDateServer contains the fakes for client OptionalPlainDateClient + OptionalPlainDateServer OptionalPlainDateServer + + // OptionalPlainTimeServer contains the fakes for client OptionalPlainTimeClient + OptionalPlainTimeServer OptionalPlainTimeServer + + // OptionalRequiredAndOptionalServer contains the fakes for client OptionalRequiredAndOptionalClient + OptionalRequiredAndOptionalServer OptionalRequiredAndOptionalServer + + // OptionalStringServer contains the fakes for client OptionalStringClient + OptionalStringServer OptionalStringServer + + // OptionalStringLiteralServer contains the fakes for client OptionalStringLiteralClient + OptionalStringLiteralServer OptionalStringLiteralServer + + // OptionalUnionFloatLiteralServer contains the fakes for client OptionalUnionFloatLiteralClient + OptionalUnionFloatLiteralServer OptionalUnionFloatLiteralServer + + // OptionalUnionIntLiteralServer contains the fakes for client OptionalUnionIntLiteralClient + OptionalUnionIntLiteralServer OptionalUnionIntLiteralServer + + // OptionalUnionStringLiteralServer contains the fakes for client OptionalUnionStringLiteralClient + OptionalUnionStringLiteralServer OptionalUnionStringLiteralServer +} + +// NewOptionalServerTransport creates a new instance of OptionalServerTransport with the provided implementation. +// The returned OptionalServerTransport instance is connected to an instance of optionalitygroup.OptionalClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOptionalServerTransport(srv *OptionalServer) *OptionalServerTransport { + return &OptionalServerTransport{srv: srv} +} + +// OptionalServerTransport connects instances of optionalitygroup.OptionalClient to instances of OptionalServer. +// Don't use this type directly, use NewOptionalServerTransport instead. +type OptionalServerTransport struct { + srv *OptionalServer + trMu sync.Mutex + trOptionalBooleanLiteralServer *OptionalBooleanLiteralServerTransport + trOptionalBytesServer *OptionalBytesServerTransport + trOptionalCollectionsByteServer *OptionalCollectionsByteServerTransport + trOptionalCollectionsModelServer *OptionalCollectionsModelServerTransport + trOptionalDatetimeServer *OptionalDatetimeServerTransport + trOptionalDurationServer *OptionalDurationServerTransport + trOptionalFloatLiteralServer *OptionalFloatLiteralServerTransport + trOptionalIntLiteralServer *OptionalIntLiteralServerTransport + trOptionalPlainDateServer *OptionalPlainDateServerTransport + trOptionalPlainTimeServer *OptionalPlainTimeServerTransport + trOptionalRequiredAndOptionalServer *OptionalRequiredAndOptionalServerTransport + trOptionalStringServer *OptionalStringServerTransport + trOptionalStringLiteralServer *OptionalStringLiteralServerTransport + trOptionalUnionFloatLiteralServer *OptionalUnionFloatLiteralServerTransport + trOptionalUnionIntLiteralServer *OptionalUnionIntLiteralServerTransport + trOptionalUnionStringLiteralServer *OptionalUnionStringLiteralServerTransport +} + +// Do implements the policy.Transporter interface for OptionalServerTransport. +func (o *OptionalServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (o *OptionalServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "OptionalBooleanLiteralClient": + initServer(&o.trMu, &o.trOptionalBooleanLiteralServer, func() *OptionalBooleanLiteralServerTransport { + return NewOptionalBooleanLiteralServerTransport(&o.srv.OptionalBooleanLiteralServer) + }) + resp, err = o.trOptionalBooleanLiteralServer.Do(req) + case "OptionalBytesClient": + initServer(&o.trMu, &o.trOptionalBytesServer, func() *OptionalBytesServerTransport { + return NewOptionalBytesServerTransport(&o.srv.OptionalBytesServer) + }) + resp, err = o.trOptionalBytesServer.Do(req) + case "OptionalCollectionsByteClient": + initServer(&o.trMu, &o.trOptionalCollectionsByteServer, func() *OptionalCollectionsByteServerTransport { + return NewOptionalCollectionsByteServerTransport(&o.srv.OptionalCollectionsByteServer) + }) + resp, err = o.trOptionalCollectionsByteServer.Do(req) + case "OptionalCollectionsModelClient": + initServer(&o.trMu, &o.trOptionalCollectionsModelServer, func() *OptionalCollectionsModelServerTransport { + return NewOptionalCollectionsModelServerTransport(&o.srv.OptionalCollectionsModelServer) + }) + resp, err = o.trOptionalCollectionsModelServer.Do(req) + case "OptionalDatetimeClient": + initServer(&o.trMu, &o.trOptionalDatetimeServer, func() *OptionalDatetimeServerTransport { + return NewOptionalDatetimeServerTransport(&o.srv.OptionalDatetimeServer) + }) + resp, err = o.trOptionalDatetimeServer.Do(req) + case "OptionalDurationClient": + initServer(&o.trMu, &o.trOptionalDurationServer, func() *OptionalDurationServerTransport { + return NewOptionalDurationServerTransport(&o.srv.OptionalDurationServer) + }) + resp, err = o.trOptionalDurationServer.Do(req) + case "OptionalFloatLiteralClient": + initServer(&o.trMu, &o.trOptionalFloatLiteralServer, func() *OptionalFloatLiteralServerTransport { + return NewOptionalFloatLiteralServerTransport(&o.srv.OptionalFloatLiteralServer) + }) + resp, err = o.trOptionalFloatLiteralServer.Do(req) + case "OptionalIntLiteralClient": + initServer(&o.trMu, &o.trOptionalIntLiteralServer, func() *OptionalIntLiteralServerTransport { + return NewOptionalIntLiteralServerTransport(&o.srv.OptionalIntLiteralServer) + }) + resp, err = o.trOptionalIntLiteralServer.Do(req) + case "OptionalPlainDateClient": + initServer(&o.trMu, &o.trOptionalPlainDateServer, func() *OptionalPlainDateServerTransport { + return NewOptionalPlainDateServerTransport(&o.srv.OptionalPlainDateServer) + }) + resp, err = o.trOptionalPlainDateServer.Do(req) + case "OptionalPlainTimeClient": + initServer(&o.trMu, &o.trOptionalPlainTimeServer, func() *OptionalPlainTimeServerTransport { + return NewOptionalPlainTimeServerTransport(&o.srv.OptionalPlainTimeServer) + }) + resp, err = o.trOptionalPlainTimeServer.Do(req) + case "OptionalRequiredAndOptionalClient": + initServer(&o.trMu, &o.trOptionalRequiredAndOptionalServer, func() *OptionalRequiredAndOptionalServerTransport { + return NewOptionalRequiredAndOptionalServerTransport(&o.srv.OptionalRequiredAndOptionalServer) + }) + resp, err = o.trOptionalRequiredAndOptionalServer.Do(req) + case "OptionalStringClient": + initServer(&o.trMu, &o.trOptionalStringServer, func() *OptionalStringServerTransport { + return NewOptionalStringServerTransport(&o.srv.OptionalStringServer) + }) + resp, err = o.trOptionalStringServer.Do(req) + case "OptionalStringLiteralClient": + initServer(&o.trMu, &o.trOptionalStringLiteralServer, func() *OptionalStringLiteralServerTransport { + return NewOptionalStringLiteralServerTransport(&o.srv.OptionalStringLiteralServer) + }) + resp, err = o.trOptionalStringLiteralServer.Do(req) + case "OptionalUnionFloatLiteralClient": + initServer(&o.trMu, &o.trOptionalUnionFloatLiteralServer, func() *OptionalUnionFloatLiteralServerTransport { + return NewOptionalUnionFloatLiteralServerTransport(&o.srv.OptionalUnionFloatLiteralServer) + }) + resp, err = o.trOptionalUnionFloatLiteralServer.Do(req) + case "OptionalUnionIntLiteralClient": + initServer(&o.trMu, &o.trOptionalUnionIntLiteralServer, func() *OptionalUnionIntLiteralServerTransport { + return NewOptionalUnionIntLiteralServerTransport(&o.srv.OptionalUnionIntLiteralServer) + }) + resp, err = o.trOptionalUnionIntLiteralServer.Do(req) + case "OptionalUnionStringLiteralClient": + initServer(&o.trMu, &o.trOptionalUnionStringLiteralServer, func() *OptionalUnionStringLiteralServerTransport { + return NewOptionalUnionStringLiteralServerTransport(&o.srv.OptionalUnionStringLiteralServer) + }) + resp, err = o.trOptionalUnionStringLiteralServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to OptionalServerTransport +var optionalServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/optionalitygroup/fake/zz_optionalbooleanliteral_server.go b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalbooleanliteral_server.go new file mode 100644 index 000000000000..0340d7801561 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalbooleanliteral_server.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "optionalitygroup" + "slices" +) + +// OptionalBooleanLiteralServer is a fake server for instances of the optionalitygroup.OptionalBooleanLiteralClient type. +type OptionalBooleanLiteralServer struct { + // GetAll is the fake for method OptionalBooleanLiteralClient.GetAll + // HTTP status codes to indicate success: http.StatusOK + GetAll func(ctx context.Context, options *optionalitygroup.OptionalBooleanLiteralClientGetAllOptions) (resp azfake.Responder[optionalitygroup.OptionalBooleanLiteralClientGetAllResponse], errResp azfake.ErrorResponder) + + // GetDefault is the fake for method OptionalBooleanLiteralClient.GetDefault + // HTTP status codes to indicate success: http.StatusOK + GetDefault func(ctx context.Context, options *optionalitygroup.OptionalBooleanLiteralClientGetDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalBooleanLiteralClientGetDefaultResponse], errResp azfake.ErrorResponder) + + // PutAll is the fake for method OptionalBooleanLiteralClient.PutAll + // HTTP status codes to indicate success: http.StatusNoContent + PutAll func(ctx context.Context, body optionalitygroup.BooleanLiteralProperty, options *optionalitygroup.OptionalBooleanLiteralClientPutAllOptions) (resp azfake.Responder[optionalitygroup.OptionalBooleanLiteralClientPutAllResponse], errResp azfake.ErrorResponder) + + // PutDefault is the fake for method OptionalBooleanLiteralClient.PutDefault + // HTTP status codes to indicate success: http.StatusNoContent + PutDefault func(ctx context.Context, body optionalitygroup.BooleanLiteralProperty, options *optionalitygroup.OptionalBooleanLiteralClientPutDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalBooleanLiteralClientPutDefaultResponse], errResp azfake.ErrorResponder) +} + +// NewOptionalBooleanLiteralServerTransport creates a new instance of OptionalBooleanLiteralServerTransport with the provided implementation. +// The returned OptionalBooleanLiteralServerTransport instance is connected to an instance of optionalitygroup.OptionalBooleanLiteralClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOptionalBooleanLiteralServerTransport(srv *OptionalBooleanLiteralServer) *OptionalBooleanLiteralServerTransport { + return &OptionalBooleanLiteralServerTransport{srv: srv} +} + +// OptionalBooleanLiteralServerTransport connects instances of optionalitygroup.OptionalBooleanLiteralClient to instances of OptionalBooleanLiteralServer. +// Don't use this type directly, use NewOptionalBooleanLiteralServerTransport instead. +type OptionalBooleanLiteralServerTransport struct { + srv *OptionalBooleanLiteralServer +} + +// Do implements the policy.Transporter interface for OptionalBooleanLiteralServerTransport. +func (o *OptionalBooleanLiteralServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OptionalBooleanLiteralServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if optionalBooleanLiteralServerTransportInterceptor != nil { + res.resp, res.err, intercepted = optionalBooleanLiteralServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OptionalBooleanLiteralClient.GetAll": + res.resp, res.err = o.dispatchGetAll(req) + case "OptionalBooleanLiteralClient.GetDefault": + res.resp, res.err = o.dispatchGetDefault(req) + case "OptionalBooleanLiteralClient.PutAll": + res.resp, res.err = o.dispatchPutAll(req) + case "OptionalBooleanLiteralClient.PutDefault": + res.resp, res.err = o.dispatchPutDefault(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OptionalBooleanLiteralServerTransport) dispatchGetAll(req *http.Request) (*http.Response, error) { + if o.srv.GetAll == nil { + return nil, &nonRetriableError{errors.New("fake for method GetAll not implemented")} + } + respr, errRespr := o.srv.GetAll(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BooleanLiteralProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalBooleanLiteralServerTransport) dispatchGetDefault(req *http.Request) (*http.Response, error) { + if o.srv.GetDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method GetDefault not implemented")} + } + respr, errRespr := o.srv.GetDefault(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BooleanLiteralProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalBooleanLiteralServerTransport) dispatchPutAll(req *http.Request) (*http.Response, error) { + if o.srv.PutAll == nil { + return nil, &nonRetriableError{errors.New("fake for method PutAll not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.BooleanLiteralProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutAll(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalBooleanLiteralServerTransport) dispatchPutDefault(req *http.Request) (*http.Response, error) { + if o.srv.PutDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method PutDefault not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.BooleanLiteralProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutDefault(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OptionalBooleanLiteralServerTransport +var optionalBooleanLiteralServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/optionalitygroup/fake/zz_optionalbytes_server.go b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalbytes_server.go new file mode 100644 index 000000000000..3e7600ae18ae --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalbytes_server.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "optionalitygroup" + "slices" +) + +// OptionalBytesServer is a fake server for instances of the optionalitygroup.OptionalBytesClient type. +type OptionalBytesServer struct { + // GetAll is the fake for method OptionalBytesClient.GetAll + // HTTP status codes to indicate success: http.StatusOK + GetAll func(ctx context.Context, options *optionalitygroup.OptionalBytesClientGetAllOptions) (resp azfake.Responder[optionalitygroup.OptionalBytesClientGetAllResponse], errResp azfake.ErrorResponder) + + // GetDefault is the fake for method OptionalBytesClient.GetDefault + // HTTP status codes to indicate success: http.StatusOK + GetDefault func(ctx context.Context, options *optionalitygroup.OptionalBytesClientGetDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalBytesClientGetDefaultResponse], errResp azfake.ErrorResponder) + + // PutAll is the fake for method OptionalBytesClient.PutAll + // HTTP status codes to indicate success: http.StatusNoContent + PutAll func(ctx context.Context, body optionalitygroup.BytesProperty, options *optionalitygroup.OptionalBytesClientPutAllOptions) (resp azfake.Responder[optionalitygroup.OptionalBytesClientPutAllResponse], errResp azfake.ErrorResponder) + + // PutDefault is the fake for method OptionalBytesClient.PutDefault + // HTTP status codes to indicate success: http.StatusNoContent + PutDefault func(ctx context.Context, body optionalitygroup.BytesProperty, options *optionalitygroup.OptionalBytesClientPutDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalBytesClientPutDefaultResponse], errResp azfake.ErrorResponder) +} + +// NewOptionalBytesServerTransport creates a new instance of OptionalBytesServerTransport with the provided implementation. +// The returned OptionalBytesServerTransport instance is connected to an instance of optionalitygroup.OptionalBytesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOptionalBytesServerTransport(srv *OptionalBytesServer) *OptionalBytesServerTransport { + return &OptionalBytesServerTransport{srv: srv} +} + +// OptionalBytesServerTransport connects instances of optionalitygroup.OptionalBytesClient to instances of OptionalBytesServer. +// Don't use this type directly, use NewOptionalBytesServerTransport instead. +type OptionalBytesServerTransport struct { + srv *OptionalBytesServer +} + +// Do implements the policy.Transporter interface for OptionalBytesServerTransport. +func (o *OptionalBytesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OptionalBytesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if optionalBytesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = optionalBytesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OptionalBytesClient.GetAll": + res.resp, res.err = o.dispatchGetAll(req) + case "OptionalBytesClient.GetDefault": + res.resp, res.err = o.dispatchGetDefault(req) + case "OptionalBytesClient.PutAll": + res.resp, res.err = o.dispatchPutAll(req) + case "OptionalBytesClient.PutDefault": + res.resp, res.err = o.dispatchPutDefault(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OptionalBytesServerTransport) dispatchGetAll(req *http.Request) (*http.Response, error) { + if o.srv.GetAll == nil { + return nil, &nonRetriableError{errors.New("fake for method GetAll not implemented")} + } + respr, errRespr := o.srv.GetAll(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BytesProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalBytesServerTransport) dispatchGetDefault(req *http.Request) (*http.Response, error) { + if o.srv.GetDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method GetDefault not implemented")} + } + respr, errRespr := o.srv.GetDefault(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BytesProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalBytesServerTransport) dispatchPutAll(req *http.Request) (*http.Response, error) { + if o.srv.PutAll == nil { + return nil, &nonRetriableError{errors.New("fake for method PutAll not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.BytesProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutAll(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalBytesServerTransport) dispatchPutDefault(req *http.Request) (*http.Response, error) { + if o.srv.PutDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method PutDefault not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.BytesProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutDefault(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OptionalBytesServerTransport +var optionalBytesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/optionalitygroup/fake/zz_optionalcollectionsbyte_server.go b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalcollectionsbyte_server.go new file mode 100644 index 000000000000..72949b928a76 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalcollectionsbyte_server.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "optionalitygroup" + "slices" +) + +// OptionalCollectionsByteServer is a fake server for instances of the optionalitygroup.OptionalCollectionsByteClient type. +type OptionalCollectionsByteServer struct { + // GetAll is the fake for method OptionalCollectionsByteClient.GetAll + // HTTP status codes to indicate success: http.StatusOK + GetAll func(ctx context.Context, options *optionalitygroup.OptionalCollectionsByteClientGetAllOptions) (resp azfake.Responder[optionalitygroup.OptionalCollectionsByteClientGetAllResponse], errResp azfake.ErrorResponder) + + // GetDefault is the fake for method OptionalCollectionsByteClient.GetDefault + // HTTP status codes to indicate success: http.StatusOK + GetDefault func(ctx context.Context, options *optionalitygroup.OptionalCollectionsByteClientGetDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalCollectionsByteClientGetDefaultResponse], errResp azfake.ErrorResponder) + + // PutAll is the fake for method OptionalCollectionsByteClient.PutAll + // HTTP status codes to indicate success: http.StatusNoContent + PutAll func(ctx context.Context, body optionalitygroup.CollectionsByteProperty, options *optionalitygroup.OptionalCollectionsByteClientPutAllOptions) (resp azfake.Responder[optionalitygroup.OptionalCollectionsByteClientPutAllResponse], errResp azfake.ErrorResponder) + + // PutDefault is the fake for method OptionalCollectionsByteClient.PutDefault + // HTTP status codes to indicate success: http.StatusNoContent + PutDefault func(ctx context.Context, body optionalitygroup.CollectionsByteProperty, options *optionalitygroup.OptionalCollectionsByteClientPutDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalCollectionsByteClientPutDefaultResponse], errResp azfake.ErrorResponder) +} + +// NewOptionalCollectionsByteServerTransport creates a new instance of OptionalCollectionsByteServerTransport with the provided implementation. +// The returned OptionalCollectionsByteServerTransport instance is connected to an instance of optionalitygroup.OptionalCollectionsByteClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOptionalCollectionsByteServerTransport(srv *OptionalCollectionsByteServer) *OptionalCollectionsByteServerTransport { + return &OptionalCollectionsByteServerTransport{srv: srv} +} + +// OptionalCollectionsByteServerTransport connects instances of optionalitygroup.OptionalCollectionsByteClient to instances of OptionalCollectionsByteServer. +// Don't use this type directly, use NewOptionalCollectionsByteServerTransport instead. +type OptionalCollectionsByteServerTransport struct { + srv *OptionalCollectionsByteServer +} + +// Do implements the policy.Transporter interface for OptionalCollectionsByteServerTransport. +func (o *OptionalCollectionsByteServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OptionalCollectionsByteServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if optionalCollectionsByteServerTransportInterceptor != nil { + res.resp, res.err, intercepted = optionalCollectionsByteServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OptionalCollectionsByteClient.GetAll": + res.resp, res.err = o.dispatchGetAll(req) + case "OptionalCollectionsByteClient.GetDefault": + res.resp, res.err = o.dispatchGetDefault(req) + case "OptionalCollectionsByteClient.PutAll": + res.resp, res.err = o.dispatchPutAll(req) + case "OptionalCollectionsByteClient.PutDefault": + res.resp, res.err = o.dispatchPutDefault(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OptionalCollectionsByteServerTransport) dispatchGetAll(req *http.Request) (*http.Response, error) { + if o.srv.GetAll == nil { + return nil, &nonRetriableError{errors.New("fake for method GetAll not implemented")} + } + respr, errRespr := o.srv.GetAll(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CollectionsByteProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalCollectionsByteServerTransport) dispatchGetDefault(req *http.Request) (*http.Response, error) { + if o.srv.GetDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method GetDefault not implemented")} + } + respr, errRespr := o.srv.GetDefault(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CollectionsByteProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalCollectionsByteServerTransport) dispatchPutAll(req *http.Request) (*http.Response, error) { + if o.srv.PutAll == nil { + return nil, &nonRetriableError{errors.New("fake for method PutAll not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.CollectionsByteProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutAll(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalCollectionsByteServerTransport) dispatchPutDefault(req *http.Request) (*http.Response, error) { + if o.srv.PutDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method PutDefault not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.CollectionsByteProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutDefault(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OptionalCollectionsByteServerTransport +var optionalCollectionsByteServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/optionalitygroup/fake/zz_optionalcollectionsmodel_server.go b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalcollectionsmodel_server.go new file mode 100644 index 000000000000..5ccfa23334e6 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalcollectionsmodel_server.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "optionalitygroup" + "slices" +) + +// OptionalCollectionsModelServer is a fake server for instances of the optionalitygroup.OptionalCollectionsModelClient type. +type OptionalCollectionsModelServer struct { + // GetAll is the fake for method OptionalCollectionsModelClient.GetAll + // HTTP status codes to indicate success: http.StatusOK + GetAll func(ctx context.Context, options *optionalitygroup.OptionalCollectionsModelClientGetAllOptions) (resp azfake.Responder[optionalitygroup.OptionalCollectionsModelClientGetAllResponse], errResp azfake.ErrorResponder) + + // GetDefault is the fake for method OptionalCollectionsModelClient.GetDefault + // HTTP status codes to indicate success: http.StatusOK + GetDefault func(ctx context.Context, options *optionalitygroup.OptionalCollectionsModelClientGetDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalCollectionsModelClientGetDefaultResponse], errResp azfake.ErrorResponder) + + // PutAll is the fake for method OptionalCollectionsModelClient.PutAll + // HTTP status codes to indicate success: http.StatusNoContent + PutAll func(ctx context.Context, body optionalitygroup.CollectionsModelProperty, options *optionalitygroup.OptionalCollectionsModelClientPutAllOptions) (resp azfake.Responder[optionalitygroup.OptionalCollectionsModelClientPutAllResponse], errResp azfake.ErrorResponder) + + // PutDefault is the fake for method OptionalCollectionsModelClient.PutDefault + // HTTP status codes to indicate success: http.StatusNoContent + PutDefault func(ctx context.Context, body optionalitygroup.CollectionsModelProperty, options *optionalitygroup.OptionalCollectionsModelClientPutDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalCollectionsModelClientPutDefaultResponse], errResp azfake.ErrorResponder) +} + +// NewOptionalCollectionsModelServerTransport creates a new instance of OptionalCollectionsModelServerTransport with the provided implementation. +// The returned OptionalCollectionsModelServerTransport instance is connected to an instance of optionalitygroup.OptionalCollectionsModelClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOptionalCollectionsModelServerTransport(srv *OptionalCollectionsModelServer) *OptionalCollectionsModelServerTransport { + return &OptionalCollectionsModelServerTransport{srv: srv} +} + +// OptionalCollectionsModelServerTransport connects instances of optionalitygroup.OptionalCollectionsModelClient to instances of OptionalCollectionsModelServer. +// Don't use this type directly, use NewOptionalCollectionsModelServerTransport instead. +type OptionalCollectionsModelServerTransport struct { + srv *OptionalCollectionsModelServer +} + +// Do implements the policy.Transporter interface for OptionalCollectionsModelServerTransport. +func (o *OptionalCollectionsModelServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OptionalCollectionsModelServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if optionalCollectionsModelServerTransportInterceptor != nil { + res.resp, res.err, intercepted = optionalCollectionsModelServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OptionalCollectionsModelClient.GetAll": + res.resp, res.err = o.dispatchGetAll(req) + case "OptionalCollectionsModelClient.GetDefault": + res.resp, res.err = o.dispatchGetDefault(req) + case "OptionalCollectionsModelClient.PutAll": + res.resp, res.err = o.dispatchPutAll(req) + case "OptionalCollectionsModelClient.PutDefault": + res.resp, res.err = o.dispatchPutDefault(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OptionalCollectionsModelServerTransport) dispatchGetAll(req *http.Request) (*http.Response, error) { + if o.srv.GetAll == nil { + return nil, &nonRetriableError{errors.New("fake for method GetAll not implemented")} + } + respr, errRespr := o.srv.GetAll(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CollectionsModelProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalCollectionsModelServerTransport) dispatchGetDefault(req *http.Request) (*http.Response, error) { + if o.srv.GetDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method GetDefault not implemented")} + } + respr, errRespr := o.srv.GetDefault(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CollectionsModelProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalCollectionsModelServerTransport) dispatchPutAll(req *http.Request) (*http.Response, error) { + if o.srv.PutAll == nil { + return nil, &nonRetriableError{errors.New("fake for method PutAll not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.CollectionsModelProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutAll(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalCollectionsModelServerTransport) dispatchPutDefault(req *http.Request) (*http.Response, error) { + if o.srv.PutDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method PutDefault not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.CollectionsModelProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutDefault(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OptionalCollectionsModelServerTransport +var optionalCollectionsModelServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/optionalitygroup/fake/zz_optionaldatetime_server.go b/test/http-specs/type/property/optionalitygroup/fake/zz_optionaldatetime_server.go new file mode 100644 index 000000000000..51834f218683 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/fake/zz_optionaldatetime_server.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "optionalitygroup" + "slices" +) + +// OptionalDatetimeServer is a fake server for instances of the optionalitygroup.OptionalDatetimeClient type. +type OptionalDatetimeServer struct { + // GetAll is the fake for method OptionalDatetimeClient.GetAll + // HTTP status codes to indicate success: http.StatusOK + GetAll func(ctx context.Context, options *optionalitygroup.OptionalDatetimeClientGetAllOptions) (resp azfake.Responder[optionalitygroup.OptionalDatetimeClientGetAllResponse], errResp azfake.ErrorResponder) + + // GetDefault is the fake for method OptionalDatetimeClient.GetDefault + // HTTP status codes to indicate success: http.StatusOK + GetDefault func(ctx context.Context, options *optionalitygroup.OptionalDatetimeClientGetDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalDatetimeClientGetDefaultResponse], errResp azfake.ErrorResponder) + + // PutAll is the fake for method OptionalDatetimeClient.PutAll + // HTTP status codes to indicate success: http.StatusNoContent + PutAll func(ctx context.Context, body optionalitygroup.DatetimeProperty, options *optionalitygroup.OptionalDatetimeClientPutAllOptions) (resp azfake.Responder[optionalitygroup.OptionalDatetimeClientPutAllResponse], errResp azfake.ErrorResponder) + + // PutDefault is the fake for method OptionalDatetimeClient.PutDefault + // HTTP status codes to indicate success: http.StatusNoContent + PutDefault func(ctx context.Context, body optionalitygroup.DatetimeProperty, options *optionalitygroup.OptionalDatetimeClientPutDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalDatetimeClientPutDefaultResponse], errResp azfake.ErrorResponder) +} + +// NewOptionalDatetimeServerTransport creates a new instance of OptionalDatetimeServerTransport with the provided implementation. +// The returned OptionalDatetimeServerTransport instance is connected to an instance of optionalitygroup.OptionalDatetimeClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOptionalDatetimeServerTransport(srv *OptionalDatetimeServer) *OptionalDatetimeServerTransport { + return &OptionalDatetimeServerTransport{srv: srv} +} + +// OptionalDatetimeServerTransport connects instances of optionalitygroup.OptionalDatetimeClient to instances of OptionalDatetimeServer. +// Don't use this type directly, use NewOptionalDatetimeServerTransport instead. +type OptionalDatetimeServerTransport struct { + srv *OptionalDatetimeServer +} + +// Do implements the policy.Transporter interface for OptionalDatetimeServerTransport. +func (o *OptionalDatetimeServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OptionalDatetimeServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if optionalDatetimeServerTransportInterceptor != nil { + res.resp, res.err, intercepted = optionalDatetimeServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OptionalDatetimeClient.GetAll": + res.resp, res.err = o.dispatchGetAll(req) + case "OptionalDatetimeClient.GetDefault": + res.resp, res.err = o.dispatchGetDefault(req) + case "OptionalDatetimeClient.PutAll": + res.resp, res.err = o.dispatchPutAll(req) + case "OptionalDatetimeClient.PutDefault": + res.resp, res.err = o.dispatchPutDefault(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OptionalDatetimeServerTransport) dispatchGetAll(req *http.Request) (*http.Response, error) { + if o.srv.GetAll == nil { + return nil, &nonRetriableError{errors.New("fake for method GetAll not implemented")} + } + respr, errRespr := o.srv.GetAll(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DatetimeProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalDatetimeServerTransport) dispatchGetDefault(req *http.Request) (*http.Response, error) { + if o.srv.GetDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method GetDefault not implemented")} + } + respr, errRespr := o.srv.GetDefault(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DatetimeProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalDatetimeServerTransport) dispatchPutAll(req *http.Request) (*http.Response, error) { + if o.srv.PutAll == nil { + return nil, &nonRetriableError{errors.New("fake for method PutAll not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.DatetimeProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutAll(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalDatetimeServerTransport) dispatchPutDefault(req *http.Request) (*http.Response, error) { + if o.srv.PutDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method PutDefault not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.DatetimeProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutDefault(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OptionalDatetimeServerTransport +var optionalDatetimeServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/optionalitygroup/fake/zz_optionalduration_server.go b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalduration_server.go new file mode 100644 index 000000000000..27ac1c40a03e --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalduration_server.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "optionalitygroup" + "slices" +) + +// OptionalDurationServer is a fake server for instances of the optionalitygroup.OptionalDurationClient type. +type OptionalDurationServer struct { + // GetAll is the fake for method OptionalDurationClient.GetAll + // HTTP status codes to indicate success: http.StatusOK + GetAll func(ctx context.Context, options *optionalitygroup.OptionalDurationClientGetAllOptions) (resp azfake.Responder[optionalitygroup.OptionalDurationClientGetAllResponse], errResp azfake.ErrorResponder) + + // GetDefault is the fake for method OptionalDurationClient.GetDefault + // HTTP status codes to indicate success: http.StatusOK + GetDefault func(ctx context.Context, options *optionalitygroup.OptionalDurationClientGetDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalDurationClientGetDefaultResponse], errResp azfake.ErrorResponder) + + // PutAll is the fake for method OptionalDurationClient.PutAll + // HTTP status codes to indicate success: http.StatusNoContent + PutAll func(ctx context.Context, body optionalitygroup.DurationProperty, options *optionalitygroup.OptionalDurationClientPutAllOptions) (resp azfake.Responder[optionalitygroup.OptionalDurationClientPutAllResponse], errResp azfake.ErrorResponder) + + // PutDefault is the fake for method OptionalDurationClient.PutDefault + // HTTP status codes to indicate success: http.StatusNoContent + PutDefault func(ctx context.Context, body optionalitygroup.DurationProperty, options *optionalitygroup.OptionalDurationClientPutDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalDurationClientPutDefaultResponse], errResp azfake.ErrorResponder) +} + +// NewOptionalDurationServerTransport creates a new instance of OptionalDurationServerTransport with the provided implementation. +// The returned OptionalDurationServerTransport instance is connected to an instance of optionalitygroup.OptionalDurationClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOptionalDurationServerTransport(srv *OptionalDurationServer) *OptionalDurationServerTransport { + return &OptionalDurationServerTransport{srv: srv} +} + +// OptionalDurationServerTransport connects instances of optionalitygroup.OptionalDurationClient to instances of OptionalDurationServer. +// Don't use this type directly, use NewOptionalDurationServerTransport instead. +type OptionalDurationServerTransport struct { + srv *OptionalDurationServer +} + +// Do implements the policy.Transporter interface for OptionalDurationServerTransport. +func (o *OptionalDurationServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OptionalDurationServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if optionalDurationServerTransportInterceptor != nil { + res.resp, res.err, intercepted = optionalDurationServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OptionalDurationClient.GetAll": + res.resp, res.err = o.dispatchGetAll(req) + case "OptionalDurationClient.GetDefault": + res.resp, res.err = o.dispatchGetDefault(req) + case "OptionalDurationClient.PutAll": + res.resp, res.err = o.dispatchPutAll(req) + case "OptionalDurationClient.PutDefault": + res.resp, res.err = o.dispatchPutDefault(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OptionalDurationServerTransport) dispatchGetAll(req *http.Request) (*http.Response, error) { + if o.srv.GetAll == nil { + return nil, &nonRetriableError{errors.New("fake for method GetAll not implemented")} + } + respr, errRespr := o.srv.GetAll(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DurationProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalDurationServerTransport) dispatchGetDefault(req *http.Request) (*http.Response, error) { + if o.srv.GetDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method GetDefault not implemented")} + } + respr, errRespr := o.srv.GetDefault(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DurationProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalDurationServerTransport) dispatchPutAll(req *http.Request) (*http.Response, error) { + if o.srv.PutAll == nil { + return nil, &nonRetriableError{errors.New("fake for method PutAll not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.DurationProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutAll(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalDurationServerTransport) dispatchPutDefault(req *http.Request) (*http.Response, error) { + if o.srv.PutDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method PutDefault not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.DurationProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutDefault(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OptionalDurationServerTransport +var optionalDurationServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/optionalitygroup/fake/zz_optionalfloatliteral_server.go b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalfloatliteral_server.go new file mode 100644 index 000000000000..59a23c64d10e --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalfloatliteral_server.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "optionalitygroup" + "slices" +) + +// OptionalFloatLiteralServer is a fake server for instances of the optionalitygroup.OptionalFloatLiteralClient type. +type OptionalFloatLiteralServer struct { + // GetAll is the fake for method OptionalFloatLiteralClient.GetAll + // HTTP status codes to indicate success: http.StatusOK + GetAll func(ctx context.Context, options *optionalitygroup.OptionalFloatLiteralClientGetAllOptions) (resp azfake.Responder[optionalitygroup.OptionalFloatLiteralClientGetAllResponse], errResp azfake.ErrorResponder) + + // GetDefault is the fake for method OptionalFloatLiteralClient.GetDefault + // HTTP status codes to indicate success: http.StatusOK + GetDefault func(ctx context.Context, options *optionalitygroup.OptionalFloatLiteralClientGetDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalFloatLiteralClientGetDefaultResponse], errResp azfake.ErrorResponder) + + // PutAll is the fake for method OptionalFloatLiteralClient.PutAll + // HTTP status codes to indicate success: http.StatusNoContent + PutAll func(ctx context.Context, body optionalitygroup.FloatLiteralProperty, options *optionalitygroup.OptionalFloatLiteralClientPutAllOptions) (resp azfake.Responder[optionalitygroup.OptionalFloatLiteralClientPutAllResponse], errResp azfake.ErrorResponder) + + // PutDefault is the fake for method OptionalFloatLiteralClient.PutDefault + // HTTP status codes to indicate success: http.StatusNoContent + PutDefault func(ctx context.Context, body optionalitygroup.FloatLiteralProperty, options *optionalitygroup.OptionalFloatLiteralClientPutDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalFloatLiteralClientPutDefaultResponse], errResp azfake.ErrorResponder) +} + +// NewOptionalFloatLiteralServerTransport creates a new instance of OptionalFloatLiteralServerTransport with the provided implementation. +// The returned OptionalFloatLiteralServerTransport instance is connected to an instance of optionalitygroup.OptionalFloatLiteralClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOptionalFloatLiteralServerTransport(srv *OptionalFloatLiteralServer) *OptionalFloatLiteralServerTransport { + return &OptionalFloatLiteralServerTransport{srv: srv} +} + +// OptionalFloatLiteralServerTransport connects instances of optionalitygroup.OptionalFloatLiteralClient to instances of OptionalFloatLiteralServer. +// Don't use this type directly, use NewOptionalFloatLiteralServerTransport instead. +type OptionalFloatLiteralServerTransport struct { + srv *OptionalFloatLiteralServer +} + +// Do implements the policy.Transporter interface for OptionalFloatLiteralServerTransport. +func (o *OptionalFloatLiteralServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OptionalFloatLiteralServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if optionalFloatLiteralServerTransportInterceptor != nil { + res.resp, res.err, intercepted = optionalFloatLiteralServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OptionalFloatLiteralClient.GetAll": + res.resp, res.err = o.dispatchGetAll(req) + case "OptionalFloatLiteralClient.GetDefault": + res.resp, res.err = o.dispatchGetDefault(req) + case "OptionalFloatLiteralClient.PutAll": + res.resp, res.err = o.dispatchPutAll(req) + case "OptionalFloatLiteralClient.PutDefault": + res.resp, res.err = o.dispatchPutDefault(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OptionalFloatLiteralServerTransport) dispatchGetAll(req *http.Request) (*http.Response, error) { + if o.srv.GetAll == nil { + return nil, &nonRetriableError{errors.New("fake for method GetAll not implemented")} + } + respr, errRespr := o.srv.GetAll(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).FloatLiteralProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalFloatLiteralServerTransport) dispatchGetDefault(req *http.Request) (*http.Response, error) { + if o.srv.GetDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method GetDefault not implemented")} + } + respr, errRespr := o.srv.GetDefault(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).FloatLiteralProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalFloatLiteralServerTransport) dispatchPutAll(req *http.Request) (*http.Response, error) { + if o.srv.PutAll == nil { + return nil, &nonRetriableError{errors.New("fake for method PutAll not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.FloatLiteralProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutAll(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalFloatLiteralServerTransport) dispatchPutDefault(req *http.Request) (*http.Response, error) { + if o.srv.PutDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method PutDefault not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.FloatLiteralProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutDefault(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OptionalFloatLiteralServerTransport +var optionalFloatLiteralServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/optionalitygroup/fake/zz_optionalintliteral_server.go b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalintliteral_server.go new file mode 100644 index 000000000000..98bf34d79137 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalintliteral_server.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "optionalitygroup" + "slices" +) + +// OptionalIntLiteralServer is a fake server for instances of the optionalitygroup.OptionalIntLiteralClient type. +type OptionalIntLiteralServer struct { + // GetAll is the fake for method OptionalIntLiteralClient.GetAll + // HTTP status codes to indicate success: http.StatusOK + GetAll func(ctx context.Context, options *optionalitygroup.OptionalIntLiteralClientGetAllOptions) (resp azfake.Responder[optionalitygroup.OptionalIntLiteralClientGetAllResponse], errResp azfake.ErrorResponder) + + // GetDefault is the fake for method OptionalIntLiteralClient.GetDefault + // HTTP status codes to indicate success: http.StatusOK + GetDefault func(ctx context.Context, options *optionalitygroup.OptionalIntLiteralClientGetDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalIntLiteralClientGetDefaultResponse], errResp azfake.ErrorResponder) + + // PutAll is the fake for method OptionalIntLiteralClient.PutAll + // HTTP status codes to indicate success: http.StatusNoContent + PutAll func(ctx context.Context, body optionalitygroup.IntLiteralProperty, options *optionalitygroup.OptionalIntLiteralClientPutAllOptions) (resp azfake.Responder[optionalitygroup.OptionalIntLiteralClientPutAllResponse], errResp azfake.ErrorResponder) + + // PutDefault is the fake for method OptionalIntLiteralClient.PutDefault + // HTTP status codes to indicate success: http.StatusNoContent + PutDefault func(ctx context.Context, body optionalitygroup.IntLiteralProperty, options *optionalitygroup.OptionalIntLiteralClientPutDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalIntLiteralClientPutDefaultResponse], errResp azfake.ErrorResponder) +} + +// NewOptionalIntLiteralServerTransport creates a new instance of OptionalIntLiteralServerTransport with the provided implementation. +// The returned OptionalIntLiteralServerTransport instance is connected to an instance of optionalitygroup.OptionalIntLiteralClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOptionalIntLiteralServerTransport(srv *OptionalIntLiteralServer) *OptionalIntLiteralServerTransport { + return &OptionalIntLiteralServerTransport{srv: srv} +} + +// OptionalIntLiteralServerTransport connects instances of optionalitygroup.OptionalIntLiteralClient to instances of OptionalIntLiteralServer. +// Don't use this type directly, use NewOptionalIntLiteralServerTransport instead. +type OptionalIntLiteralServerTransport struct { + srv *OptionalIntLiteralServer +} + +// Do implements the policy.Transporter interface for OptionalIntLiteralServerTransport. +func (o *OptionalIntLiteralServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OptionalIntLiteralServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if optionalIntLiteralServerTransportInterceptor != nil { + res.resp, res.err, intercepted = optionalIntLiteralServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OptionalIntLiteralClient.GetAll": + res.resp, res.err = o.dispatchGetAll(req) + case "OptionalIntLiteralClient.GetDefault": + res.resp, res.err = o.dispatchGetDefault(req) + case "OptionalIntLiteralClient.PutAll": + res.resp, res.err = o.dispatchPutAll(req) + case "OptionalIntLiteralClient.PutDefault": + res.resp, res.err = o.dispatchPutDefault(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OptionalIntLiteralServerTransport) dispatchGetAll(req *http.Request) (*http.Response, error) { + if o.srv.GetAll == nil { + return nil, &nonRetriableError{errors.New("fake for method GetAll not implemented")} + } + respr, errRespr := o.srv.GetAll(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).IntLiteralProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalIntLiteralServerTransport) dispatchGetDefault(req *http.Request) (*http.Response, error) { + if o.srv.GetDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method GetDefault not implemented")} + } + respr, errRespr := o.srv.GetDefault(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).IntLiteralProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalIntLiteralServerTransport) dispatchPutAll(req *http.Request) (*http.Response, error) { + if o.srv.PutAll == nil { + return nil, &nonRetriableError{errors.New("fake for method PutAll not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.IntLiteralProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutAll(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalIntLiteralServerTransport) dispatchPutDefault(req *http.Request) (*http.Response, error) { + if o.srv.PutDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method PutDefault not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.IntLiteralProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutDefault(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OptionalIntLiteralServerTransport +var optionalIntLiteralServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/optionalitygroup/fake/zz_optionalplaindate_server.go b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalplaindate_server.go new file mode 100644 index 000000000000..578b2479324c --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalplaindate_server.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "optionalitygroup" + "slices" +) + +// OptionalPlainDateServer is a fake server for instances of the optionalitygroup.OptionalPlainDateClient type. +type OptionalPlainDateServer struct { + // GetAll is the fake for method OptionalPlainDateClient.GetAll + // HTTP status codes to indicate success: http.StatusOK + GetAll func(ctx context.Context, options *optionalitygroup.OptionalPlainDateClientGetAllOptions) (resp azfake.Responder[optionalitygroup.OptionalPlainDateClientGetAllResponse], errResp azfake.ErrorResponder) + + // GetDefault is the fake for method OptionalPlainDateClient.GetDefault + // HTTP status codes to indicate success: http.StatusOK + GetDefault func(ctx context.Context, options *optionalitygroup.OptionalPlainDateClientGetDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalPlainDateClientGetDefaultResponse], errResp azfake.ErrorResponder) + + // PutAll is the fake for method OptionalPlainDateClient.PutAll + // HTTP status codes to indicate success: http.StatusNoContent + PutAll func(ctx context.Context, body optionalitygroup.PlainDateProperty, options *optionalitygroup.OptionalPlainDateClientPutAllOptions) (resp azfake.Responder[optionalitygroup.OptionalPlainDateClientPutAllResponse], errResp azfake.ErrorResponder) + + // PutDefault is the fake for method OptionalPlainDateClient.PutDefault + // HTTP status codes to indicate success: http.StatusNoContent + PutDefault func(ctx context.Context, body optionalitygroup.PlainDateProperty, options *optionalitygroup.OptionalPlainDateClientPutDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalPlainDateClientPutDefaultResponse], errResp azfake.ErrorResponder) +} + +// NewOptionalPlainDateServerTransport creates a new instance of OptionalPlainDateServerTransport with the provided implementation. +// The returned OptionalPlainDateServerTransport instance is connected to an instance of optionalitygroup.OptionalPlainDateClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOptionalPlainDateServerTransport(srv *OptionalPlainDateServer) *OptionalPlainDateServerTransport { + return &OptionalPlainDateServerTransport{srv: srv} +} + +// OptionalPlainDateServerTransport connects instances of optionalitygroup.OptionalPlainDateClient to instances of OptionalPlainDateServer. +// Don't use this type directly, use NewOptionalPlainDateServerTransport instead. +type OptionalPlainDateServerTransport struct { + srv *OptionalPlainDateServer +} + +// Do implements the policy.Transporter interface for OptionalPlainDateServerTransport. +func (o *OptionalPlainDateServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OptionalPlainDateServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if optionalPlainDateServerTransportInterceptor != nil { + res.resp, res.err, intercepted = optionalPlainDateServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OptionalPlainDateClient.GetAll": + res.resp, res.err = o.dispatchGetAll(req) + case "OptionalPlainDateClient.GetDefault": + res.resp, res.err = o.dispatchGetDefault(req) + case "OptionalPlainDateClient.PutAll": + res.resp, res.err = o.dispatchPutAll(req) + case "OptionalPlainDateClient.PutDefault": + res.resp, res.err = o.dispatchPutDefault(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OptionalPlainDateServerTransport) dispatchGetAll(req *http.Request) (*http.Response, error) { + if o.srv.GetAll == nil { + return nil, &nonRetriableError{errors.New("fake for method GetAll not implemented")} + } + respr, errRespr := o.srv.GetAll(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).PlainDateProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalPlainDateServerTransport) dispatchGetDefault(req *http.Request) (*http.Response, error) { + if o.srv.GetDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method GetDefault not implemented")} + } + respr, errRespr := o.srv.GetDefault(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).PlainDateProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalPlainDateServerTransport) dispatchPutAll(req *http.Request) (*http.Response, error) { + if o.srv.PutAll == nil { + return nil, &nonRetriableError{errors.New("fake for method PutAll not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.PlainDateProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutAll(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalPlainDateServerTransport) dispatchPutDefault(req *http.Request) (*http.Response, error) { + if o.srv.PutDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method PutDefault not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.PlainDateProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutDefault(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OptionalPlainDateServerTransport +var optionalPlainDateServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/optionalitygroup/fake/zz_optionalplaintime_server.go b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalplaintime_server.go new file mode 100644 index 000000000000..0ffeee1816bb --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalplaintime_server.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "optionalitygroup" + "slices" +) + +// OptionalPlainTimeServer is a fake server for instances of the optionalitygroup.OptionalPlainTimeClient type. +type OptionalPlainTimeServer struct { + // GetAll is the fake for method OptionalPlainTimeClient.GetAll + // HTTP status codes to indicate success: http.StatusOK + GetAll func(ctx context.Context, options *optionalitygroup.OptionalPlainTimeClientGetAllOptions) (resp azfake.Responder[optionalitygroup.OptionalPlainTimeClientGetAllResponse], errResp azfake.ErrorResponder) + + // GetDefault is the fake for method OptionalPlainTimeClient.GetDefault + // HTTP status codes to indicate success: http.StatusOK + GetDefault func(ctx context.Context, options *optionalitygroup.OptionalPlainTimeClientGetDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalPlainTimeClientGetDefaultResponse], errResp azfake.ErrorResponder) + + // PutAll is the fake for method OptionalPlainTimeClient.PutAll + // HTTP status codes to indicate success: http.StatusNoContent + PutAll func(ctx context.Context, body optionalitygroup.PlainTimeProperty, options *optionalitygroup.OptionalPlainTimeClientPutAllOptions) (resp azfake.Responder[optionalitygroup.OptionalPlainTimeClientPutAllResponse], errResp azfake.ErrorResponder) + + // PutDefault is the fake for method OptionalPlainTimeClient.PutDefault + // HTTP status codes to indicate success: http.StatusNoContent + PutDefault func(ctx context.Context, body optionalitygroup.PlainTimeProperty, options *optionalitygroup.OptionalPlainTimeClientPutDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalPlainTimeClientPutDefaultResponse], errResp azfake.ErrorResponder) +} + +// NewOptionalPlainTimeServerTransport creates a new instance of OptionalPlainTimeServerTransport with the provided implementation. +// The returned OptionalPlainTimeServerTransport instance is connected to an instance of optionalitygroup.OptionalPlainTimeClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOptionalPlainTimeServerTransport(srv *OptionalPlainTimeServer) *OptionalPlainTimeServerTransport { + return &OptionalPlainTimeServerTransport{srv: srv} +} + +// OptionalPlainTimeServerTransport connects instances of optionalitygroup.OptionalPlainTimeClient to instances of OptionalPlainTimeServer. +// Don't use this type directly, use NewOptionalPlainTimeServerTransport instead. +type OptionalPlainTimeServerTransport struct { + srv *OptionalPlainTimeServer +} + +// Do implements the policy.Transporter interface for OptionalPlainTimeServerTransport. +func (o *OptionalPlainTimeServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OptionalPlainTimeServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if optionalPlainTimeServerTransportInterceptor != nil { + res.resp, res.err, intercepted = optionalPlainTimeServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OptionalPlainTimeClient.GetAll": + res.resp, res.err = o.dispatchGetAll(req) + case "OptionalPlainTimeClient.GetDefault": + res.resp, res.err = o.dispatchGetDefault(req) + case "OptionalPlainTimeClient.PutAll": + res.resp, res.err = o.dispatchPutAll(req) + case "OptionalPlainTimeClient.PutDefault": + res.resp, res.err = o.dispatchPutDefault(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OptionalPlainTimeServerTransport) dispatchGetAll(req *http.Request) (*http.Response, error) { + if o.srv.GetAll == nil { + return nil, &nonRetriableError{errors.New("fake for method GetAll not implemented")} + } + respr, errRespr := o.srv.GetAll(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).PlainTimeProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalPlainTimeServerTransport) dispatchGetDefault(req *http.Request) (*http.Response, error) { + if o.srv.GetDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method GetDefault not implemented")} + } + respr, errRespr := o.srv.GetDefault(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).PlainTimeProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalPlainTimeServerTransport) dispatchPutAll(req *http.Request) (*http.Response, error) { + if o.srv.PutAll == nil { + return nil, &nonRetriableError{errors.New("fake for method PutAll not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.PlainTimeProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutAll(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalPlainTimeServerTransport) dispatchPutDefault(req *http.Request) (*http.Response, error) { + if o.srv.PutDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method PutDefault not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.PlainTimeProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutDefault(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OptionalPlainTimeServerTransport +var optionalPlainTimeServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/optionalitygroup/fake/zz_optionalrequiredandoptional_server.go b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalrequiredandoptional_server.go new file mode 100644 index 000000000000..ff55fbd0f26f --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalrequiredandoptional_server.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "optionalitygroup" + "slices" +) + +// OptionalRequiredAndOptionalServer is a fake server for instances of the optionalitygroup.OptionalRequiredAndOptionalClient type. +type OptionalRequiredAndOptionalServer struct { + // GetAll is the fake for method OptionalRequiredAndOptionalClient.GetAll + // HTTP status codes to indicate success: http.StatusOK + GetAll func(ctx context.Context, options *optionalitygroup.OptionalRequiredAndOptionalClientGetAllOptions) (resp azfake.Responder[optionalitygroup.OptionalRequiredAndOptionalClientGetAllResponse], errResp azfake.ErrorResponder) + + // GetRequiredOnly is the fake for method OptionalRequiredAndOptionalClient.GetRequiredOnly + // HTTP status codes to indicate success: http.StatusOK + GetRequiredOnly func(ctx context.Context, options *optionalitygroup.OptionalRequiredAndOptionalClientGetRequiredOnlyOptions) (resp azfake.Responder[optionalitygroup.OptionalRequiredAndOptionalClientGetRequiredOnlyResponse], errResp azfake.ErrorResponder) + + // PutAll is the fake for method OptionalRequiredAndOptionalClient.PutAll + // HTTP status codes to indicate success: http.StatusNoContent + PutAll func(ctx context.Context, body optionalitygroup.RequiredAndOptionalProperty, options *optionalitygroup.OptionalRequiredAndOptionalClientPutAllOptions) (resp azfake.Responder[optionalitygroup.OptionalRequiredAndOptionalClientPutAllResponse], errResp azfake.ErrorResponder) + + // PutRequiredOnly is the fake for method OptionalRequiredAndOptionalClient.PutRequiredOnly + // HTTP status codes to indicate success: http.StatusNoContent + PutRequiredOnly func(ctx context.Context, body optionalitygroup.RequiredAndOptionalProperty, options *optionalitygroup.OptionalRequiredAndOptionalClientPutRequiredOnlyOptions) (resp azfake.Responder[optionalitygroup.OptionalRequiredAndOptionalClientPutRequiredOnlyResponse], errResp azfake.ErrorResponder) +} + +// NewOptionalRequiredAndOptionalServerTransport creates a new instance of OptionalRequiredAndOptionalServerTransport with the provided implementation. +// The returned OptionalRequiredAndOptionalServerTransport instance is connected to an instance of optionalitygroup.OptionalRequiredAndOptionalClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOptionalRequiredAndOptionalServerTransport(srv *OptionalRequiredAndOptionalServer) *OptionalRequiredAndOptionalServerTransport { + return &OptionalRequiredAndOptionalServerTransport{srv: srv} +} + +// OptionalRequiredAndOptionalServerTransport connects instances of optionalitygroup.OptionalRequiredAndOptionalClient to instances of OptionalRequiredAndOptionalServer. +// Don't use this type directly, use NewOptionalRequiredAndOptionalServerTransport instead. +type OptionalRequiredAndOptionalServerTransport struct { + srv *OptionalRequiredAndOptionalServer +} + +// Do implements the policy.Transporter interface for OptionalRequiredAndOptionalServerTransport. +func (o *OptionalRequiredAndOptionalServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OptionalRequiredAndOptionalServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if optionalRequiredAndOptionalServerTransportInterceptor != nil { + res.resp, res.err, intercepted = optionalRequiredAndOptionalServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OptionalRequiredAndOptionalClient.GetAll": + res.resp, res.err = o.dispatchGetAll(req) + case "OptionalRequiredAndOptionalClient.GetRequiredOnly": + res.resp, res.err = o.dispatchGetRequiredOnly(req) + case "OptionalRequiredAndOptionalClient.PutAll": + res.resp, res.err = o.dispatchPutAll(req) + case "OptionalRequiredAndOptionalClient.PutRequiredOnly": + res.resp, res.err = o.dispatchPutRequiredOnly(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OptionalRequiredAndOptionalServerTransport) dispatchGetAll(req *http.Request) (*http.Response, error) { + if o.srv.GetAll == nil { + return nil, &nonRetriableError{errors.New("fake for method GetAll not implemented")} + } + respr, errRespr := o.srv.GetAll(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RequiredAndOptionalProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalRequiredAndOptionalServerTransport) dispatchGetRequiredOnly(req *http.Request) (*http.Response, error) { + if o.srv.GetRequiredOnly == nil { + return nil, &nonRetriableError{errors.New("fake for method GetRequiredOnly not implemented")} + } + respr, errRespr := o.srv.GetRequiredOnly(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RequiredAndOptionalProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalRequiredAndOptionalServerTransport) dispatchPutAll(req *http.Request) (*http.Response, error) { + if o.srv.PutAll == nil { + return nil, &nonRetriableError{errors.New("fake for method PutAll not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.RequiredAndOptionalProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutAll(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalRequiredAndOptionalServerTransport) dispatchPutRequiredOnly(req *http.Request) (*http.Response, error) { + if o.srv.PutRequiredOnly == nil { + return nil, &nonRetriableError{errors.New("fake for method PutRequiredOnly not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.RequiredAndOptionalProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutRequiredOnly(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OptionalRequiredAndOptionalServerTransport +var optionalRequiredAndOptionalServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/optionalitygroup/fake/zz_optionalstring_server.go b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalstring_server.go new file mode 100644 index 000000000000..bf829bf0b47e --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalstring_server.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "optionalitygroup" + "slices" +) + +// OptionalStringServer is a fake server for instances of the optionalitygroup.OptionalStringClient type. +type OptionalStringServer struct { + // GetAll is the fake for method OptionalStringClient.GetAll + // HTTP status codes to indicate success: http.StatusOK + GetAll func(ctx context.Context, options *optionalitygroup.OptionalStringClientGetAllOptions) (resp azfake.Responder[optionalitygroup.OptionalStringClientGetAllResponse], errResp azfake.ErrorResponder) + + // GetDefault is the fake for method OptionalStringClient.GetDefault + // HTTP status codes to indicate success: http.StatusOK + GetDefault func(ctx context.Context, options *optionalitygroup.OptionalStringClientGetDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalStringClientGetDefaultResponse], errResp azfake.ErrorResponder) + + // PutAll is the fake for method OptionalStringClient.PutAll + // HTTP status codes to indicate success: http.StatusNoContent + PutAll func(ctx context.Context, body optionalitygroup.StringProperty, options *optionalitygroup.OptionalStringClientPutAllOptions) (resp azfake.Responder[optionalitygroup.OptionalStringClientPutAllResponse], errResp azfake.ErrorResponder) + + // PutDefault is the fake for method OptionalStringClient.PutDefault + // HTTP status codes to indicate success: http.StatusNoContent + PutDefault func(ctx context.Context, body optionalitygroup.StringProperty, options *optionalitygroup.OptionalStringClientPutDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalStringClientPutDefaultResponse], errResp azfake.ErrorResponder) +} + +// NewOptionalStringServerTransport creates a new instance of OptionalStringServerTransport with the provided implementation. +// The returned OptionalStringServerTransport instance is connected to an instance of optionalitygroup.OptionalStringClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOptionalStringServerTransport(srv *OptionalStringServer) *OptionalStringServerTransport { + return &OptionalStringServerTransport{srv: srv} +} + +// OptionalStringServerTransport connects instances of optionalitygroup.OptionalStringClient to instances of OptionalStringServer. +// Don't use this type directly, use NewOptionalStringServerTransport instead. +type OptionalStringServerTransport struct { + srv *OptionalStringServer +} + +// Do implements the policy.Transporter interface for OptionalStringServerTransport. +func (o *OptionalStringServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OptionalStringServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if optionalStringServerTransportInterceptor != nil { + res.resp, res.err, intercepted = optionalStringServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OptionalStringClient.GetAll": + res.resp, res.err = o.dispatchGetAll(req) + case "OptionalStringClient.GetDefault": + res.resp, res.err = o.dispatchGetDefault(req) + case "OptionalStringClient.PutAll": + res.resp, res.err = o.dispatchPutAll(req) + case "OptionalStringClient.PutDefault": + res.resp, res.err = o.dispatchPutDefault(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OptionalStringServerTransport) dispatchGetAll(req *http.Request) (*http.Response, error) { + if o.srv.GetAll == nil { + return nil, &nonRetriableError{errors.New("fake for method GetAll not implemented")} + } + respr, errRespr := o.srv.GetAll(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).StringProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalStringServerTransport) dispatchGetDefault(req *http.Request) (*http.Response, error) { + if o.srv.GetDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method GetDefault not implemented")} + } + respr, errRespr := o.srv.GetDefault(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).StringProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalStringServerTransport) dispatchPutAll(req *http.Request) (*http.Response, error) { + if o.srv.PutAll == nil { + return nil, &nonRetriableError{errors.New("fake for method PutAll not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.StringProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutAll(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalStringServerTransport) dispatchPutDefault(req *http.Request) (*http.Response, error) { + if o.srv.PutDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method PutDefault not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.StringProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutDefault(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OptionalStringServerTransport +var optionalStringServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/optionalitygroup/fake/zz_optionalstringliteral_server.go b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalstringliteral_server.go new file mode 100644 index 000000000000..fcf960b48f8d --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalstringliteral_server.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "optionalitygroup" + "slices" +) + +// OptionalStringLiteralServer is a fake server for instances of the optionalitygroup.OptionalStringLiteralClient type. +type OptionalStringLiteralServer struct { + // GetAll is the fake for method OptionalStringLiteralClient.GetAll + // HTTP status codes to indicate success: http.StatusOK + GetAll func(ctx context.Context, options *optionalitygroup.OptionalStringLiteralClientGetAllOptions) (resp azfake.Responder[optionalitygroup.OptionalStringLiteralClientGetAllResponse], errResp azfake.ErrorResponder) + + // GetDefault is the fake for method OptionalStringLiteralClient.GetDefault + // HTTP status codes to indicate success: http.StatusOK + GetDefault func(ctx context.Context, options *optionalitygroup.OptionalStringLiteralClientGetDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalStringLiteralClientGetDefaultResponse], errResp azfake.ErrorResponder) + + // PutAll is the fake for method OptionalStringLiteralClient.PutAll + // HTTP status codes to indicate success: http.StatusNoContent + PutAll func(ctx context.Context, body optionalitygroup.StringLiteralProperty, options *optionalitygroup.OptionalStringLiteralClientPutAllOptions) (resp azfake.Responder[optionalitygroup.OptionalStringLiteralClientPutAllResponse], errResp azfake.ErrorResponder) + + // PutDefault is the fake for method OptionalStringLiteralClient.PutDefault + // HTTP status codes to indicate success: http.StatusNoContent + PutDefault func(ctx context.Context, body optionalitygroup.StringLiteralProperty, options *optionalitygroup.OptionalStringLiteralClientPutDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalStringLiteralClientPutDefaultResponse], errResp azfake.ErrorResponder) +} + +// NewOptionalStringLiteralServerTransport creates a new instance of OptionalStringLiteralServerTransport with the provided implementation. +// The returned OptionalStringLiteralServerTransport instance is connected to an instance of optionalitygroup.OptionalStringLiteralClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOptionalStringLiteralServerTransport(srv *OptionalStringLiteralServer) *OptionalStringLiteralServerTransport { + return &OptionalStringLiteralServerTransport{srv: srv} +} + +// OptionalStringLiteralServerTransport connects instances of optionalitygroup.OptionalStringLiteralClient to instances of OptionalStringLiteralServer. +// Don't use this type directly, use NewOptionalStringLiteralServerTransport instead. +type OptionalStringLiteralServerTransport struct { + srv *OptionalStringLiteralServer +} + +// Do implements the policy.Transporter interface for OptionalStringLiteralServerTransport. +func (o *OptionalStringLiteralServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OptionalStringLiteralServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if optionalStringLiteralServerTransportInterceptor != nil { + res.resp, res.err, intercepted = optionalStringLiteralServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OptionalStringLiteralClient.GetAll": + res.resp, res.err = o.dispatchGetAll(req) + case "OptionalStringLiteralClient.GetDefault": + res.resp, res.err = o.dispatchGetDefault(req) + case "OptionalStringLiteralClient.PutAll": + res.resp, res.err = o.dispatchPutAll(req) + case "OptionalStringLiteralClient.PutDefault": + res.resp, res.err = o.dispatchPutDefault(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OptionalStringLiteralServerTransport) dispatchGetAll(req *http.Request) (*http.Response, error) { + if o.srv.GetAll == nil { + return nil, &nonRetriableError{errors.New("fake for method GetAll not implemented")} + } + respr, errRespr := o.srv.GetAll(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).StringLiteralProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalStringLiteralServerTransport) dispatchGetDefault(req *http.Request) (*http.Response, error) { + if o.srv.GetDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method GetDefault not implemented")} + } + respr, errRespr := o.srv.GetDefault(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).StringLiteralProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalStringLiteralServerTransport) dispatchPutAll(req *http.Request) (*http.Response, error) { + if o.srv.PutAll == nil { + return nil, &nonRetriableError{errors.New("fake for method PutAll not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.StringLiteralProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutAll(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalStringLiteralServerTransport) dispatchPutDefault(req *http.Request) (*http.Response, error) { + if o.srv.PutDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method PutDefault not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.StringLiteralProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutDefault(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OptionalStringLiteralServerTransport +var optionalStringLiteralServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/optionalitygroup/fake/zz_optionalunionfloatliteral_server.go b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalunionfloatliteral_server.go new file mode 100644 index 000000000000..24c0a11b5378 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalunionfloatliteral_server.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "optionalitygroup" + "slices" +) + +// OptionalUnionFloatLiteralServer is a fake server for instances of the optionalitygroup.OptionalUnionFloatLiteralClient type. +type OptionalUnionFloatLiteralServer struct { + // GetAll is the fake for method OptionalUnionFloatLiteralClient.GetAll + // HTTP status codes to indicate success: http.StatusOK + GetAll func(ctx context.Context, options *optionalitygroup.OptionalUnionFloatLiteralClientGetAllOptions) (resp azfake.Responder[optionalitygroup.OptionalUnionFloatLiteralClientGetAllResponse], errResp azfake.ErrorResponder) + + // GetDefault is the fake for method OptionalUnionFloatLiteralClient.GetDefault + // HTTP status codes to indicate success: http.StatusOK + GetDefault func(ctx context.Context, options *optionalitygroup.OptionalUnionFloatLiteralClientGetDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalUnionFloatLiteralClientGetDefaultResponse], errResp azfake.ErrorResponder) + + // PutAll is the fake for method OptionalUnionFloatLiteralClient.PutAll + // HTTP status codes to indicate success: http.StatusNoContent + PutAll func(ctx context.Context, body optionalitygroup.UnionFloatLiteralProperty, options *optionalitygroup.OptionalUnionFloatLiteralClientPutAllOptions) (resp azfake.Responder[optionalitygroup.OptionalUnionFloatLiteralClientPutAllResponse], errResp azfake.ErrorResponder) + + // PutDefault is the fake for method OptionalUnionFloatLiteralClient.PutDefault + // HTTP status codes to indicate success: http.StatusNoContent + PutDefault func(ctx context.Context, body optionalitygroup.UnionFloatLiteralProperty, options *optionalitygroup.OptionalUnionFloatLiteralClientPutDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalUnionFloatLiteralClientPutDefaultResponse], errResp azfake.ErrorResponder) +} + +// NewOptionalUnionFloatLiteralServerTransport creates a new instance of OptionalUnionFloatLiteralServerTransport with the provided implementation. +// The returned OptionalUnionFloatLiteralServerTransport instance is connected to an instance of optionalitygroup.OptionalUnionFloatLiteralClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOptionalUnionFloatLiteralServerTransport(srv *OptionalUnionFloatLiteralServer) *OptionalUnionFloatLiteralServerTransport { + return &OptionalUnionFloatLiteralServerTransport{srv: srv} +} + +// OptionalUnionFloatLiteralServerTransport connects instances of optionalitygroup.OptionalUnionFloatLiteralClient to instances of OptionalUnionFloatLiteralServer. +// Don't use this type directly, use NewOptionalUnionFloatLiteralServerTransport instead. +type OptionalUnionFloatLiteralServerTransport struct { + srv *OptionalUnionFloatLiteralServer +} + +// Do implements the policy.Transporter interface for OptionalUnionFloatLiteralServerTransport. +func (o *OptionalUnionFloatLiteralServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OptionalUnionFloatLiteralServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if optionalUnionFloatLiteralServerTransportInterceptor != nil { + res.resp, res.err, intercepted = optionalUnionFloatLiteralServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OptionalUnionFloatLiteralClient.GetAll": + res.resp, res.err = o.dispatchGetAll(req) + case "OptionalUnionFloatLiteralClient.GetDefault": + res.resp, res.err = o.dispatchGetDefault(req) + case "OptionalUnionFloatLiteralClient.PutAll": + res.resp, res.err = o.dispatchPutAll(req) + case "OptionalUnionFloatLiteralClient.PutDefault": + res.resp, res.err = o.dispatchPutDefault(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OptionalUnionFloatLiteralServerTransport) dispatchGetAll(req *http.Request) (*http.Response, error) { + if o.srv.GetAll == nil { + return nil, &nonRetriableError{errors.New("fake for method GetAll not implemented")} + } + respr, errRespr := o.srv.GetAll(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).UnionFloatLiteralProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalUnionFloatLiteralServerTransport) dispatchGetDefault(req *http.Request) (*http.Response, error) { + if o.srv.GetDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method GetDefault not implemented")} + } + respr, errRespr := o.srv.GetDefault(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).UnionFloatLiteralProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalUnionFloatLiteralServerTransport) dispatchPutAll(req *http.Request) (*http.Response, error) { + if o.srv.PutAll == nil { + return nil, &nonRetriableError{errors.New("fake for method PutAll not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.UnionFloatLiteralProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutAll(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalUnionFloatLiteralServerTransport) dispatchPutDefault(req *http.Request) (*http.Response, error) { + if o.srv.PutDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method PutDefault not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.UnionFloatLiteralProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutDefault(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OptionalUnionFloatLiteralServerTransport +var optionalUnionFloatLiteralServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/optionalitygroup/fake/zz_optionalunionintliteral_server.go b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalunionintliteral_server.go new file mode 100644 index 000000000000..5fd761275276 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalunionintliteral_server.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "optionalitygroup" + "slices" +) + +// OptionalUnionIntLiteralServer is a fake server for instances of the optionalitygroup.OptionalUnionIntLiteralClient type. +type OptionalUnionIntLiteralServer struct { + // GetAll is the fake for method OptionalUnionIntLiteralClient.GetAll + // HTTP status codes to indicate success: http.StatusOK + GetAll func(ctx context.Context, options *optionalitygroup.OptionalUnionIntLiteralClientGetAllOptions) (resp azfake.Responder[optionalitygroup.OptionalUnionIntLiteralClientGetAllResponse], errResp azfake.ErrorResponder) + + // GetDefault is the fake for method OptionalUnionIntLiteralClient.GetDefault + // HTTP status codes to indicate success: http.StatusOK + GetDefault func(ctx context.Context, options *optionalitygroup.OptionalUnionIntLiteralClientGetDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalUnionIntLiteralClientGetDefaultResponse], errResp azfake.ErrorResponder) + + // PutAll is the fake for method OptionalUnionIntLiteralClient.PutAll + // HTTP status codes to indicate success: http.StatusNoContent + PutAll func(ctx context.Context, body optionalitygroup.UnionIntLiteralProperty, options *optionalitygroup.OptionalUnionIntLiteralClientPutAllOptions) (resp azfake.Responder[optionalitygroup.OptionalUnionIntLiteralClientPutAllResponse], errResp azfake.ErrorResponder) + + // PutDefault is the fake for method OptionalUnionIntLiteralClient.PutDefault + // HTTP status codes to indicate success: http.StatusNoContent + PutDefault func(ctx context.Context, body optionalitygroup.UnionIntLiteralProperty, options *optionalitygroup.OptionalUnionIntLiteralClientPutDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalUnionIntLiteralClientPutDefaultResponse], errResp azfake.ErrorResponder) +} + +// NewOptionalUnionIntLiteralServerTransport creates a new instance of OptionalUnionIntLiteralServerTransport with the provided implementation. +// The returned OptionalUnionIntLiteralServerTransport instance is connected to an instance of optionalitygroup.OptionalUnionIntLiteralClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOptionalUnionIntLiteralServerTransport(srv *OptionalUnionIntLiteralServer) *OptionalUnionIntLiteralServerTransport { + return &OptionalUnionIntLiteralServerTransport{srv: srv} +} + +// OptionalUnionIntLiteralServerTransport connects instances of optionalitygroup.OptionalUnionIntLiteralClient to instances of OptionalUnionIntLiteralServer. +// Don't use this type directly, use NewOptionalUnionIntLiteralServerTransport instead. +type OptionalUnionIntLiteralServerTransport struct { + srv *OptionalUnionIntLiteralServer +} + +// Do implements the policy.Transporter interface for OptionalUnionIntLiteralServerTransport. +func (o *OptionalUnionIntLiteralServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OptionalUnionIntLiteralServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if optionalUnionIntLiteralServerTransportInterceptor != nil { + res.resp, res.err, intercepted = optionalUnionIntLiteralServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OptionalUnionIntLiteralClient.GetAll": + res.resp, res.err = o.dispatchGetAll(req) + case "OptionalUnionIntLiteralClient.GetDefault": + res.resp, res.err = o.dispatchGetDefault(req) + case "OptionalUnionIntLiteralClient.PutAll": + res.resp, res.err = o.dispatchPutAll(req) + case "OptionalUnionIntLiteralClient.PutDefault": + res.resp, res.err = o.dispatchPutDefault(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OptionalUnionIntLiteralServerTransport) dispatchGetAll(req *http.Request) (*http.Response, error) { + if o.srv.GetAll == nil { + return nil, &nonRetriableError{errors.New("fake for method GetAll not implemented")} + } + respr, errRespr := o.srv.GetAll(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).UnionIntLiteralProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalUnionIntLiteralServerTransport) dispatchGetDefault(req *http.Request) (*http.Response, error) { + if o.srv.GetDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method GetDefault not implemented")} + } + respr, errRespr := o.srv.GetDefault(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).UnionIntLiteralProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalUnionIntLiteralServerTransport) dispatchPutAll(req *http.Request) (*http.Response, error) { + if o.srv.PutAll == nil { + return nil, &nonRetriableError{errors.New("fake for method PutAll not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.UnionIntLiteralProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutAll(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalUnionIntLiteralServerTransport) dispatchPutDefault(req *http.Request) (*http.Response, error) { + if o.srv.PutDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method PutDefault not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.UnionIntLiteralProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutDefault(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OptionalUnionIntLiteralServerTransport +var optionalUnionIntLiteralServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/optionalitygroup/fake/zz_optionalunionstringliteral_server.go b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalunionstringliteral_server.go new file mode 100644 index 000000000000..8cf55ff5d139 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/fake/zz_optionalunionstringliteral_server.go @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "optionalitygroup" + "slices" +) + +// OptionalUnionStringLiteralServer is a fake server for instances of the optionalitygroup.OptionalUnionStringLiteralClient type. +type OptionalUnionStringLiteralServer struct { + // GetAll is the fake for method OptionalUnionStringLiteralClient.GetAll + // HTTP status codes to indicate success: http.StatusOK + GetAll func(ctx context.Context, options *optionalitygroup.OptionalUnionStringLiteralClientGetAllOptions) (resp azfake.Responder[optionalitygroup.OptionalUnionStringLiteralClientGetAllResponse], errResp azfake.ErrorResponder) + + // GetDefault is the fake for method OptionalUnionStringLiteralClient.GetDefault + // HTTP status codes to indicate success: http.StatusOK + GetDefault func(ctx context.Context, options *optionalitygroup.OptionalUnionStringLiteralClientGetDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalUnionStringLiteralClientGetDefaultResponse], errResp azfake.ErrorResponder) + + // PutAll is the fake for method OptionalUnionStringLiteralClient.PutAll + // HTTP status codes to indicate success: http.StatusNoContent + PutAll func(ctx context.Context, body optionalitygroup.UnionStringLiteralProperty, options *optionalitygroup.OptionalUnionStringLiteralClientPutAllOptions) (resp azfake.Responder[optionalitygroup.OptionalUnionStringLiteralClientPutAllResponse], errResp azfake.ErrorResponder) + + // PutDefault is the fake for method OptionalUnionStringLiteralClient.PutDefault + // HTTP status codes to indicate success: http.StatusNoContent + PutDefault func(ctx context.Context, body optionalitygroup.UnionStringLiteralProperty, options *optionalitygroup.OptionalUnionStringLiteralClientPutDefaultOptions) (resp azfake.Responder[optionalitygroup.OptionalUnionStringLiteralClientPutDefaultResponse], errResp azfake.ErrorResponder) +} + +// NewOptionalUnionStringLiteralServerTransport creates a new instance of OptionalUnionStringLiteralServerTransport with the provided implementation. +// The returned OptionalUnionStringLiteralServerTransport instance is connected to an instance of optionalitygroup.OptionalUnionStringLiteralClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOptionalUnionStringLiteralServerTransport(srv *OptionalUnionStringLiteralServer) *OptionalUnionStringLiteralServerTransport { + return &OptionalUnionStringLiteralServerTransport{srv: srv} +} + +// OptionalUnionStringLiteralServerTransport connects instances of optionalitygroup.OptionalUnionStringLiteralClient to instances of OptionalUnionStringLiteralServer. +// Don't use this type directly, use NewOptionalUnionStringLiteralServerTransport instead. +type OptionalUnionStringLiteralServerTransport struct { + srv *OptionalUnionStringLiteralServer +} + +// Do implements the policy.Transporter interface for OptionalUnionStringLiteralServerTransport. +func (o *OptionalUnionStringLiteralServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OptionalUnionStringLiteralServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if optionalUnionStringLiteralServerTransportInterceptor != nil { + res.resp, res.err, intercepted = optionalUnionStringLiteralServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OptionalUnionStringLiteralClient.GetAll": + res.resp, res.err = o.dispatchGetAll(req) + case "OptionalUnionStringLiteralClient.GetDefault": + res.resp, res.err = o.dispatchGetDefault(req) + case "OptionalUnionStringLiteralClient.PutAll": + res.resp, res.err = o.dispatchPutAll(req) + case "OptionalUnionStringLiteralClient.PutDefault": + res.resp, res.err = o.dispatchPutDefault(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OptionalUnionStringLiteralServerTransport) dispatchGetAll(req *http.Request) (*http.Response, error) { + if o.srv.GetAll == nil { + return nil, &nonRetriableError{errors.New("fake for method GetAll not implemented")} + } + respr, errRespr := o.srv.GetAll(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).UnionStringLiteralProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalUnionStringLiteralServerTransport) dispatchGetDefault(req *http.Request) (*http.Response, error) { + if o.srv.GetDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method GetDefault not implemented")} + } + respr, errRespr := o.srv.GetDefault(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).UnionStringLiteralProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalUnionStringLiteralServerTransport) dispatchPutAll(req *http.Request) (*http.Response, error) { + if o.srv.PutAll == nil { + return nil, &nonRetriableError{errors.New("fake for method PutAll not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.UnionStringLiteralProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutAll(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OptionalUnionStringLiteralServerTransport) dispatchPutDefault(req *http.Request) (*http.Response, error) { + if o.srv.PutDefault == nil { + return nil, &nonRetriableError{errors.New("fake for method PutDefault not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[optionalitygroup.UnionStringLiteralProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.PutDefault(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OptionalUnionStringLiteralServerTransport +var optionalUnionStringLiteralServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/optionalitygroup/go.mod b/test/http-specs/type/property/optionalitygroup/go.mod new file mode 100644 index 000000000000..9973c8f0741f --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/go.mod @@ -0,0 +1,17 @@ +module optionalitygroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/type/property/optionalitygroup/go.sum b/test/http-specs/type/property/optionalitygroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/type/property/optionalitygroup/optionalbooleanliteral_client_test.go b/test/http-specs/type/property/optionalitygroup/optionalbooleanliteral_client_test.go new file mode 100644 index 000000000000..e19d7e3501ef --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/optionalbooleanliteral_client_test.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package optionalitygroup_test + +import ( + "context" + "optionalitygroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestOptionalBooleanLiteralClient_GetAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalBooleanLiteralClient().GetAll(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.True(t, *resp.Property) +} + +func TestOptionalBooleanLiteralClient_GetDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalBooleanLiteralClient().GetDefault(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalBooleanLiteralClient_PutAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalBooleanLiteralClient().PutAll(context.Background(), optionalitygroup.BooleanLiteralProperty{ + Property: to.Ptr(true), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalBooleanLiteralClient_PutDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalBooleanLiteralClient().PutDefault(context.Background(), optionalitygroup.BooleanLiteralProperty{}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/optionalitygroup/optionalbytes_client_test.go b/test/http-specs/type/property/optionalitygroup/optionalbytes_client_test.go new file mode 100644 index 000000000000..ea4145a909c2 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/optionalbytes_client_test.go @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package optionalitygroup_test + +import ( + "context" + "optionalitygroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestOptionalBytesClient_GetAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalBytesClient().GetAll(context.Background(), nil) + require.NoError(t, err) + require.Equal(t, []byte("hello, world!"), resp.Property) +} + +func TestOptionalBytesClient_GetDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalBytesClient().GetDefault(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalBytesClient_PutAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalBytesClient().PutAll(context.Background(), optionalitygroup.BytesProperty{ + Property: []byte("hello, world!"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalBytesClient_PutDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalBytesClient().PutDefault(context.Background(), optionalitygroup.BytesProperty{}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/optionalitygroup/optionalcollectionsbyte_client_test.go b/test/http-specs/type/property/optionalitygroup/optionalcollectionsbyte_client_test.go new file mode 100644 index 000000000000..86a59cebc2e4 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/optionalcollectionsbyte_client_test.go @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package optionalitygroup_test + +import ( + "context" + "optionalitygroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestOptionalCollectionsByteClient_GetAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalCollectionsByteClient().GetAll(context.Background(), nil) + require.NoError(t, err) + require.Equal(t, [][]byte{ + []byte("hello, world!"), + []byte("hello, world!"), + }, resp.Property) +} + +func TestOptionalCollectionsByteClient_GetDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalCollectionsByteClient().GetDefault(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalCollectionsByteClient_PutAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalCollectionsByteClient().PutAll(context.Background(), optionalitygroup.CollectionsByteProperty{ + Property: [][]byte{ + []byte("hello, world!"), + []byte("hello, world!"), + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalCollectionsByteClient_PutDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalCollectionsByteClient().PutDefault(context.Background(), optionalitygroup.CollectionsByteProperty{}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/optionalitygroup/optionalcollectionsmodel_client_test.go b/test/http-specs/type/property/optionalitygroup/optionalcollectionsmodel_client_test.go new file mode 100644 index 000000000000..66235bf344de --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/optionalcollectionsmodel_client_test.go @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package optionalitygroup_test + +import ( + "context" + "optionalitygroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestOptionalCollectionsModelClient_GetAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalCollectionsModelClient().GetAll(context.Background(), nil) + require.NoError(t, err) + require.Equal(t, []optionalitygroup.StringProperty{ + { + Property: to.Ptr("hello"), + }, + { + Property: to.Ptr("world"), + }, + }, resp.Property) +} + +func TestOptionalCollectionsModelClient_GetDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalCollectionsModelClient().GetDefault(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalCollectionsModelClient_PutAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalCollectionsModelClient().PutAll(context.Background(), optionalitygroup.CollectionsModelProperty{ + Property: []optionalitygroup.StringProperty{ + { + Property: to.Ptr("hello"), + }, + { + Property: to.Ptr("world"), + }, + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalCollectionsModelClient_PutDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalCollectionsModelClient().PutDefault(context.Background(), optionalitygroup.CollectionsModelProperty{}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/optionalitygroup/optionaldatetime_client_test.go b/test/http-specs/type/property/optionalitygroup/optionaldatetime_client_test.go new file mode 100644 index 000000000000..b26e419040b7 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/optionaldatetime_client_test.go @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package optionalitygroup_test + +import ( + "context" + "optionalitygroup" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestOptionalDatetimeClient_GetAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalDatetimeClient().GetAll(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.WithinDuration(t, time.Date(2022, 8, 26, 18, 38, 0, 0, time.UTC), *resp.Property, 0) +} + +func TestOptionalDatetimeClient_GetDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalDatetimeClient().GetDefault(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalDatetimeClient_PutAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalDatetimeClient().PutAll(context.Background(), optionalitygroup.DatetimeProperty{ + Property: to.Ptr(time.Date(2022, 8, 26, 18, 38, 0, 0, time.UTC)), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalDatetimeClient_PutDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalDatetimeClient().PutDefault(context.Background(), optionalitygroup.DatetimeProperty{}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/optionalitygroup/optionalduration_client_test.go b/test/http-specs/type/property/optionalitygroup/optionalduration_client_test.go new file mode 100644 index 000000000000..6b376bfc5ec9 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/optionalduration_client_test.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package optionalitygroup_test + +import ( + "context" + "optionalitygroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestOptionalDurationClient_GetAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalDurationClient().GetAll(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.Equal(t, "P123DT22H14M12.011S", *resp.Property) +} + +func TestOptionalDurationClient_GetDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalDurationClient().GetDefault(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalDurationClient_PutAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalDurationClient().PutAll(context.Background(), optionalitygroup.DurationProperty{ + Property: to.Ptr("P123DT22H14M12.011S"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalDurationClient_PutDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalDurationClient().PutDefault(context.Background(), optionalitygroup.DurationProperty{}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/optionalitygroup/optionalfloatliteral_client_test.go b/test/http-specs/type/property/optionalitygroup/optionalfloatliteral_client_test.go new file mode 100644 index 000000000000..04bbba1c1bd1 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/optionalfloatliteral_client_test.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package optionalitygroup_test + +import ( + "context" + "optionalitygroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestOptionalFloatLiteralClient_GetAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalFloatLiteralClient().GetAll(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.Equal(t, float32(1.25), *resp.Property) +} + +func TestOptionalFloatLiteralClient_GetDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalFloatLiteralClient().GetDefault(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalFloatLiteralClient_PutAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalFloatLiteralClient().PutAll(context.Background(), optionalitygroup.FloatLiteralProperty{ + Property: to.Ptr[float32](1.25), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalFloatLiteralClient_PutDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalFloatLiteralClient().PutDefault(context.Background(), optionalitygroup.FloatLiteralProperty{}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/optionalitygroup/optionalintliteral_client_test.go b/test/http-specs/type/property/optionalitygroup/optionalintliteral_client_test.go new file mode 100644 index 000000000000..38160c87062f --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/optionalintliteral_client_test.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package optionalitygroup_test + +import ( + "context" + "optionalitygroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestOptionalIntLiteralClient_GetAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalIntLiteralClient().GetAll(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.Equal(t, int32(1), *resp.Property) +} + +func TestOptionalIntLiteralClient_GetDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalIntLiteralClient().GetDefault(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalIntLiteralClient_PutAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalIntLiteralClient().PutAll(context.Background(), optionalitygroup.IntLiteralProperty{ + Property: to.Ptr[int32](1), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalIntLiteralClient_PutDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalIntLiteralClient().PutDefault(context.Background(), optionalitygroup.IntLiteralProperty{}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/optionalitygroup/optionalplaindate_client_test.go b/test/http-specs/type/property/optionalitygroup/optionalplaindate_client_test.go new file mode 100644 index 000000000000..c64edf2f3d49 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/optionalplaindate_client_test.go @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package optionalitygroup_test + +import ( + "context" + "optionalitygroup" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestOptionalPlainDateClient_GetAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalPlainDateClient().GetAll(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.WithinDuration(t, time.Date(2022, 12, 12, 0, 0, 0, 0, time.UTC), *resp.Property, 0) +} + +func TestOptionalPlainDateClient_GetDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalPlainDateClient().GetDefault(context.Background(), nil) + require.NoError(t, err) + require.Nil(t, resp.Property) +} + +func TestOptionalPlainDateClient_PutAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + _, err = client.NewOptionalPlainDateClient().PutAll(context.Background(), optionalitygroup.PlainDateProperty{Property: to.Ptr(time.Date(2022, 12, 12, 0, 0, 0, 0, time.UTC))}, nil) + require.NoError(t, err) +} + +func TestOptionalPlainDateClient_PutDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + _, err = client.NewOptionalPlainDateClient().PutDefault(context.Background(), optionalitygroup.PlainDateProperty{}, nil) + require.NoError(t, err) +} diff --git a/test/http-specs/type/property/optionalitygroup/optionalplaintime_client_test.go b/test/http-specs/type/property/optionalitygroup/optionalplaintime_client_test.go new file mode 100644 index 000000000000..4811372426f2 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/optionalplaintime_client_test.go @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package optionalitygroup_test + +import ( + "context" + "optionalitygroup" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestOptionalPlainTimeClient_GetAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalPlainTimeClient().GetAll(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.WithinDuration(t, time.Date(0, 1, 1, 13, 6, 12, 0, time.UTC), *resp.Property, 0) +} + +func TestOptionalPlainTimeClient_GetDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalPlainTimeClient().GetDefault(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalPlainTimeClient_PutAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalPlainTimeClient().PutAll(context.Background(), optionalitygroup.PlainTimeProperty{Property: to.Ptr(time.Date(0, 1, 1, 13, 6, 12, 0, time.UTC))}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalPlainTimeClient_PutDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalPlainTimeClient().PutDefault(context.Background(), optionalitygroup.PlainTimeProperty{}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/optionalitygroup/optionalrequiredandoptional_client_test.go b/test/http-specs/type/property/optionalitygroup/optionalrequiredandoptional_client_test.go new file mode 100644 index 000000000000..3d55fd377918 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/optionalrequiredandoptional_client_test.go @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package optionalitygroup_test + +import ( + "context" + "optionalitygroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestOptionalRequiredAndOptionalClient_GetAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalRequiredAndOptionalClient().GetAll(context.Background(), nil) + require.NoError(t, err) + require.Equal(t, optionalitygroup.RequiredAndOptionalProperty{ + RequiredProperty: to.Ptr[int32](42), + OptionalProperty: to.Ptr("hello"), + }, resp.RequiredAndOptionalProperty) +} + +func TestOptionalRequiredAndOptionalClient_GetRequiredOnly(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalRequiredAndOptionalClient().GetRequiredOnly(context.Background(), nil) + require.NoError(t, err) + require.Equal(t, optionalitygroup.RequiredAndOptionalProperty{ + RequiredProperty: to.Ptr[int32](42), + }, resp.RequiredAndOptionalProperty) +} + +func TestOptionalRequiredAndOptionalClient_PutAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalRequiredAndOptionalClient().PutAll(context.Background(), optionalitygroup.RequiredAndOptionalProperty{ + RequiredProperty: to.Ptr[int32](42), + OptionalProperty: to.Ptr("hello"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalRequiredAndOptionalClient_PutRequiredOnly(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalRequiredAndOptionalClient().PutRequiredOnly(context.Background(), optionalitygroup.RequiredAndOptionalProperty{ + RequiredProperty: to.Ptr[int32](42), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/optionalitygroup/optionalstring_client_test.go b/test/http-specs/type/property/optionalitygroup/optionalstring_client_test.go new file mode 100644 index 000000000000..bb3858eacd80 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/optionalstring_client_test.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package optionalitygroup_test + +import ( + "context" + "optionalitygroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestOptionalStringClient_GetAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalStringClient().GetAll(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.Equal(t, "hello", *resp.Property) +} + +func TestOptionalStringClient_GetDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalStringClient().GetDefault(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalStringClient_PutAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalStringClient().PutAll(context.Background(), optionalitygroup.StringProperty{ + Property: to.Ptr("hello"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalStringClient_PutDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalStringClient().PutDefault(context.Background(), optionalitygroup.StringProperty{}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/optionalitygroup/optionalstringliteral_client_test.go b/test/http-specs/type/property/optionalitygroup/optionalstringliteral_client_test.go new file mode 100644 index 000000000000..d0823be00e07 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/optionalstringliteral_client_test.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package optionalitygroup_test + +import ( + "context" + "optionalitygroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestOptionalStringLiteralClient_GetAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalStringLiteralClient().GetAll(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.Equal(t, "hello", *resp.Property) +} + +func TestOptionalStringLiteralClient_GetDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalStringLiteralClient().GetDefault(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalStringLiteralClient_PutAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalStringLiteralClient().PutAll(context.Background(), optionalitygroup.StringLiteralProperty{ + Property: to.Ptr("hello"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalStringLiteralClient_PutDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalStringLiteralClient().PutDefault(context.Background(), optionalitygroup.StringLiteralProperty{}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/optionalitygroup/optionalunionfloatliteral_client_test.go b/test/http-specs/type/property/optionalitygroup/optionalunionfloatliteral_client_test.go new file mode 100644 index 000000000000..140f00a7963e --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/optionalunionfloatliteral_client_test.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package optionalitygroup_test + +import ( + "context" + "optionalitygroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestOptionalUnionFloatLiteralClient_GetAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalUnionFloatLiteralClient().GetAll(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.Equal(t, optionalitygroup.UnionFloatLiteralPropertyProperty2375, *resp.Property) +} + +func TestOptionalUnionFloatLiteralClient_GetDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalUnionFloatLiteralClient().GetDefault(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalUnionFloatLiteralClient_PutAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalUnionFloatLiteralClient().PutAll(context.Background(), optionalitygroup.UnionFloatLiteralProperty{ + Property: to.Ptr(optionalitygroup.UnionFloatLiteralPropertyProperty2375), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalUnionFloatLiteralClient_PutDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalUnionFloatLiteralClient().PutDefault(context.Background(), optionalitygroup.UnionFloatLiteralProperty{}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/optionalitygroup/optionalunionintliteral_client_test.go b/test/http-specs/type/property/optionalitygroup/optionalunionintliteral_client_test.go new file mode 100644 index 000000000000..4e0f35a1981c --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/optionalunionintliteral_client_test.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package optionalitygroup_test + +import ( + "context" + "optionalitygroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestOptionalUnionIntLiteralClient_GetAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalUnionIntLiteralClient().GetAll(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.Equal(t, optionalitygroup.UnionIntLiteralPropertyProperty2, *resp.Property) +} + +func TestOptionalUnionIntLiteralClient_GetDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalUnionIntLiteralClient().GetDefault(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalUnionIntLiteralClient_PutAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalUnionIntLiteralClient().PutAll(context.Background(), optionalitygroup.UnionIntLiteralProperty{ + Property: to.Ptr(optionalitygroup.UnionIntLiteralPropertyProperty2), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalUnionIntLiteralClient_PutDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalUnionIntLiteralClient().PutDefault(context.Background(), optionalitygroup.UnionIntLiteralProperty{}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/optionalitygroup/optionalunionstringliteral_client_test.go b/test/http-specs/type/property/optionalitygroup/optionalunionstringliteral_client_test.go new file mode 100644 index 000000000000..fec609af75b2 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/optionalunionstringliteral_client_test.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package optionalitygroup_test + +import ( + "context" + "optionalitygroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestOptionalUnionStringLiteralClient_GetAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalUnionStringLiteralClient().GetAll(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.Equal(t, optionalitygroup.UnionStringLiteralPropertyPropertyWorld, *resp.Property) +} + +func TestOptionalUnionStringLiteralClient_GetDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalUnionStringLiteralClient().GetDefault(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalUnionStringLiteralClient_PutAll(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalUnionStringLiteralClient().PutAll(context.Background(), optionalitygroup.UnionStringLiteralProperty{ + Property: to.Ptr(optionalitygroup.UnionStringLiteralPropertyPropertyWorld), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestOptionalUnionStringLiteralClient_PutDefault(t *testing.T) { + client, err := optionalitygroup.NewOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewOptionalUnionStringLiteralClient().PutDefault(context.Background(), optionalitygroup.UnionStringLiteralProperty{}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/optionalitygroup/testdata/_metadata.json b/test/http-specs/type/property/optionalitygroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/type/property/optionalitygroup/zz_constants.go b/test/http-specs/type/property/optionalitygroup/zz_constants.go new file mode 100644 index 000000000000..ae2393dbd6b6 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/zz_constants.go @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package optionalitygroup + +type UnionFloatLiteralPropertyProperty float32 + +const ( + UnionFloatLiteralPropertyProperty125 UnionFloatLiteralPropertyProperty = 1.25 + UnionFloatLiteralPropertyProperty2375 UnionFloatLiteralPropertyProperty = 2.375 +) + +// PossibleUnionFloatLiteralPropertyPropertyValues returns the possible values for the UnionFloatLiteralPropertyProperty const type. +func PossibleUnionFloatLiteralPropertyPropertyValues() []UnionFloatLiteralPropertyProperty { + return []UnionFloatLiteralPropertyProperty{ + UnionFloatLiteralPropertyProperty125, + UnionFloatLiteralPropertyProperty2375, + } +} + +type UnionIntLiteralPropertyProperty int32 + +const ( + UnionIntLiteralPropertyProperty1 UnionIntLiteralPropertyProperty = 1 + UnionIntLiteralPropertyProperty2 UnionIntLiteralPropertyProperty = 2 +) + +// PossibleUnionIntLiteralPropertyPropertyValues returns the possible values for the UnionIntLiteralPropertyProperty const type. +func PossibleUnionIntLiteralPropertyPropertyValues() []UnionIntLiteralPropertyProperty { + return []UnionIntLiteralPropertyProperty{ + UnionIntLiteralPropertyProperty1, + UnionIntLiteralPropertyProperty2, + } +} + +type UnionStringLiteralPropertyProperty string + +const ( + UnionStringLiteralPropertyPropertyHello UnionStringLiteralPropertyProperty = "hello" + UnionStringLiteralPropertyPropertyWorld UnionStringLiteralPropertyProperty = "world" +) + +// PossibleUnionStringLiteralPropertyPropertyValues returns the possible values for the UnionStringLiteralPropertyProperty const type. +func PossibleUnionStringLiteralPropertyPropertyValues() []UnionStringLiteralPropertyProperty { + return []UnionStringLiteralPropertyProperty{ + UnionStringLiteralPropertyPropertyHello, + UnionStringLiteralPropertyPropertyWorld, + } +} diff --git a/test/http-specs/type/property/optionalitygroup/zz_models.go b/test/http-specs/type/property/optionalitygroup/zz_models.go new file mode 100644 index 000000000000..a9adf0676f9b --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/zz_models.go @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package optionalitygroup + +import "time" + +// BooleanLiteralProperty - Model with boolean literal property +type BooleanLiteralProperty struct { + // FLAG; CONSTANT; Property + // Field has constant value true, any specified value is ignored. + Property *bool +} + +// BytesProperty - Template type for testing models with optional property. Pass in the type of the property you are looking +// for +type BytesProperty struct { + // Property + Property []byte +} + +// CollectionsByteProperty - Model with collection bytes properties +type CollectionsByteProperty struct { + // Property + Property [][]byte +} + +// CollectionsModelProperty - Model with collection models properties +type CollectionsModelProperty struct { + // Property + Property []StringProperty +} + +// DatetimeProperty - Model with a datetime property +type DatetimeProperty struct { + // Property + Property *time.Time +} + +// DurationProperty - Model with a duration property +type DurationProperty struct { + // Property + Property *string +} + +// FloatLiteralProperty - Model with float literal property +type FloatLiteralProperty struct { + // FLAG; CONSTANT; Property + // Field has constant value 1.25, any specified value is ignored. + Property *float32 +} + +// IntLiteralProperty - Model with int literal property +type IntLiteralProperty struct { + // FLAG; CONSTANT; Property + // Field has constant value 1, any specified value is ignored. + Property *int32 +} + +// PlainDateProperty - Model with a plainDate property +type PlainDateProperty struct { + // Property + Property *time.Time +} + +// PlainTimeProperty - Model with a plainTime property +type PlainTimeProperty struct { + // Property + Property *time.Time +} + +// RequiredAndOptionalProperty - Model with required and optional properties +type RequiredAndOptionalProperty struct { + // REQUIRED; required int property + RequiredProperty *int32 + + // optional string property + OptionalProperty *string +} + +// StringLiteralProperty - Model with string literal property +type StringLiteralProperty struct { + // FLAG; CONSTANT; Property + // Field has constant value "hello", any specified value is ignored. + Property *string +} + +// StringProperty - Template type for testing models with optional property. Pass in the type of the property you are looking +// for +type StringProperty struct { + // Property + Property *string +} + +// UnionFloatLiteralProperty - Model with union of float literal property +type UnionFloatLiteralProperty struct { + // Property + Property *UnionFloatLiteralPropertyProperty +} + +// UnionIntLiteralProperty - Model with union of int literal property +type UnionIntLiteralProperty struct { + // Property + Property *UnionIntLiteralPropertyProperty +} + +// UnionStringLiteralProperty - Model with union of string literal property +type UnionStringLiteralProperty struct { + // Property + Property *UnionStringLiteralPropertyProperty +} diff --git a/test/http-specs/type/property/optionalitygroup/zz_models_serde.go b/test/http-specs/type/property/optionalitygroup/zz_models_serde.go new file mode 100644 index 000000000000..2377c4ca0c90 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/zz_models_serde.go @@ -0,0 +1,534 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package optionalitygroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type BooleanLiteralProperty. +func (b BooleanLiteralProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + if b.Property != nil { + objectMap["property"] = true + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BooleanLiteralProperty. +func (b *BooleanLiteralProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &b.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BytesProperty. +func (b BytesProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateByteArray(objectMap, "property", b.Property, func() any { + return runtime.EncodeByteArray(b.Property, runtime.Base64StdFormat) + }) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BytesProperty. +func (b *BytesProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &b.Property, runtime.Base64StdFormat) + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CollectionsByteProperty. +func (c CollectionsByteProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateByteArray(objectMap, "property", c.Property, func() any { + encodedValue := make([]string, len(c.Property)) + for i := 0; i < len(c.Property); i++ { + encodedValue[i] = runtime.EncodeByteArray(c.Property[i], runtime.Base64StdFormat) + } + return encodedValue + }) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CollectionsByteProperty. +func (c *CollectionsByteProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + var encodedValue []string + err = unpopulate(val, "Property", &encodedValue) + if err == nil && len(encodedValue) > 0 { + c.Property = make([][]byte, len(encodedValue)) + for i := 0; i < len(encodedValue) && err == nil; i++ { + err = runtime.DecodeByteArray(encodedValue[i], &c.Property[i], runtime.Base64StdFormat) + } + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CollectionsModelProperty. +func (c CollectionsModelProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "property", c.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CollectionsModelProperty. +func (c *CollectionsModelProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &c.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DatetimeProperty. +func (d DatetimeProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "property", d.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DatetimeProperty. +func (d *DatetimeProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulateTime[datetime.RFC3339](val, "Property", &d.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DurationProperty. +func (d DurationProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "property", d.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DurationProperty. +func (d *DurationProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &d.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FloatLiteralProperty. +func (f FloatLiteralProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + if f.Property != nil { + objectMap["property"] = float32(1.25) + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FloatLiteralProperty. +func (f *FloatLiteralProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &f.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type IntLiteralProperty. +func (i IntLiteralProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + if i.Property != nil { + objectMap["property"] = int32(1) + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IntLiteralProperty. +func (i *IntLiteralProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &i.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PlainDateProperty. +func (p PlainDateProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.PlainDate](objectMap, "property", p.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PlainDateProperty. +func (p *PlainDateProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulateTime[datetime.PlainDate](val, "Property", &p.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PlainTimeProperty. +func (p PlainTimeProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.PlainTime](objectMap, "property", p.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PlainTimeProperty. +func (p *PlainTimeProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulateTime[datetime.PlainTime](val, "Property", &p.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RequiredAndOptionalProperty. +func (r RequiredAndOptionalProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "optionalProperty", r.OptionalProperty) + populate(objectMap, "requiredProperty", r.RequiredProperty) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RequiredAndOptionalProperty. +func (r *RequiredAndOptionalProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "optionalProperty": + err = unpopulate(val, "OptionalProperty", &r.OptionalProperty) + delete(rawMsg, key) + case "requiredProperty": + err = unpopulate(val, "RequiredProperty", &r.RequiredProperty) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type StringLiteralProperty. +func (s StringLiteralProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + if s.Property != nil { + objectMap["property"] = "hello" + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StringLiteralProperty. +func (s *StringLiteralProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &s.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type StringProperty. +func (s StringProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "property", s.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StringProperty. +func (s *StringProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &s.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UnionFloatLiteralProperty. +func (u UnionFloatLiteralProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "property", u.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UnionFloatLiteralProperty. +func (u *UnionFloatLiteralProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &u.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UnionIntLiteralProperty. +func (u UnionIntLiteralProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "property", u.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UnionIntLiteralProperty. +func (u *UnionIntLiteralProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &u.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UnionStringLiteralProperty. +func (u UnionStringLiteralProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "property", u.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UnionStringLiteralProperty. +func (u *UnionStringLiteralProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &u.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func populateByteArray[T any](m map[string]any, k string, b []T, convert func() any) { + if azcore.IsNullValue(b) { + m[k] = nil + } else if len(b) == 0 { + return + } else { + m[k] = convert() + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/http-specs/type/property/optionalitygroup/zz_optional_client.go b/test/http-specs/type/property/optionalitygroup/zz_optional_client.go new file mode 100644 index 000000000000..dc2b7b0f326d --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/zz_optional_client.go @@ -0,0 +1,168 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package optionalitygroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// OptionalClient - Illustrates models with optional properties. +// Don't use this type directly, use NewOptionalClientWithNoCredential() instead. +type OptionalClient struct { + internal *azcore.Client + endpoint string +} + +// OptionalClientOptions contains the optional values for creating a [OptionalClient]. +type OptionalClientOptions struct { + azcore.ClientOptions +} + +// NewOptionalClientWithNoCredential creates a new instance of OptionalClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewOptionalClientWithNoCredential(endpoint string, options *OptionalClientOptions) (*OptionalClient, error) { + if options == nil { + options = &OptionalClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &OptionalClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewOptionalBooleanLiteralClient creates a new instance of [OptionalBooleanLiteralClient]. +func (client *OptionalClient) NewOptionalBooleanLiteralClient() *OptionalBooleanLiteralClient { + return &OptionalBooleanLiteralClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewOptionalBytesClient creates a new instance of [OptionalBytesClient]. +func (client *OptionalClient) NewOptionalBytesClient() *OptionalBytesClient { + return &OptionalBytesClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewOptionalCollectionsByteClient creates a new instance of [OptionalCollectionsByteClient]. +func (client *OptionalClient) NewOptionalCollectionsByteClient() *OptionalCollectionsByteClient { + return &OptionalCollectionsByteClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewOptionalCollectionsModelClient creates a new instance of [OptionalCollectionsModelClient]. +func (client *OptionalClient) NewOptionalCollectionsModelClient() *OptionalCollectionsModelClient { + return &OptionalCollectionsModelClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewOptionalDatetimeClient creates a new instance of [OptionalDatetimeClient]. +func (client *OptionalClient) NewOptionalDatetimeClient() *OptionalDatetimeClient { + return &OptionalDatetimeClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewOptionalDurationClient creates a new instance of [OptionalDurationClient]. +func (client *OptionalClient) NewOptionalDurationClient() *OptionalDurationClient { + return &OptionalDurationClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewOptionalFloatLiteralClient creates a new instance of [OptionalFloatLiteralClient]. +func (client *OptionalClient) NewOptionalFloatLiteralClient() *OptionalFloatLiteralClient { + return &OptionalFloatLiteralClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewOptionalIntLiteralClient creates a new instance of [OptionalIntLiteralClient]. +func (client *OptionalClient) NewOptionalIntLiteralClient() *OptionalIntLiteralClient { + return &OptionalIntLiteralClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewOptionalPlainDateClient creates a new instance of [OptionalPlainDateClient]. +func (client *OptionalClient) NewOptionalPlainDateClient() *OptionalPlainDateClient { + return &OptionalPlainDateClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewOptionalPlainTimeClient creates a new instance of [OptionalPlainTimeClient]. +func (client *OptionalClient) NewOptionalPlainTimeClient() *OptionalPlainTimeClient { + return &OptionalPlainTimeClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewOptionalRequiredAndOptionalClient creates a new instance of [OptionalRequiredAndOptionalClient]. +func (client *OptionalClient) NewOptionalRequiredAndOptionalClient() *OptionalRequiredAndOptionalClient { + return &OptionalRequiredAndOptionalClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewOptionalStringClient creates a new instance of [OptionalStringClient]. +func (client *OptionalClient) NewOptionalStringClient() *OptionalStringClient { + return &OptionalStringClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewOptionalStringLiteralClient creates a new instance of [OptionalStringLiteralClient]. +func (client *OptionalClient) NewOptionalStringLiteralClient() *OptionalStringLiteralClient { + return &OptionalStringLiteralClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewOptionalUnionFloatLiteralClient creates a new instance of [OptionalUnionFloatLiteralClient]. +func (client *OptionalClient) NewOptionalUnionFloatLiteralClient() *OptionalUnionFloatLiteralClient { + return &OptionalUnionFloatLiteralClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewOptionalUnionIntLiteralClient creates a new instance of [OptionalUnionIntLiteralClient]. +func (client *OptionalClient) NewOptionalUnionIntLiteralClient() *OptionalUnionIntLiteralClient { + return &OptionalUnionIntLiteralClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewOptionalUnionStringLiteralClient creates a new instance of [OptionalUnionStringLiteralClient]. +func (client *OptionalClient) NewOptionalUnionStringLiteralClient() *OptionalUnionStringLiteralClient { + return &OptionalUnionStringLiteralClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/http-specs/type/property/optionalitygroup/zz_optionalbooleanliteral_client.go b/test/http-specs/type/property/optionalitygroup/zz_optionalbooleanliteral_client.go new file mode 100644 index 000000000000..1ef65394a751 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/zz_optionalbooleanliteral_client.go @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package optionalitygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// OptionalBooleanLiteralClient contains the methods for the OptionalBooleanLiteral group. +// Don't use this type directly, use [OptionalClient.NewOptionalBooleanLiteralClient] instead. +type OptionalBooleanLiteralClient struct { + internal *azcore.Client + endpoint string +} + +// GetAll - Get models that will return all properties in the model +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalBooleanLiteralClientGetAllOptions contains the optional parameters for the OptionalBooleanLiteralClient.GetAll +// method. +func (client *OptionalBooleanLiteralClient) GetAll(ctx context.Context, options *OptionalBooleanLiteralClientGetAllOptions) (OptionalBooleanLiteralClientGetAllResponse, error) { + var err error + const operationName = "OptionalBooleanLiteralClient.GetAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getAllCreateRequest(ctx, options) + if err != nil { + return OptionalBooleanLiteralClientGetAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalBooleanLiteralClientGetAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalBooleanLiteralClientGetAllResponse{}, err + } + resp, err := client.getAllHandleResponse(httpResp) + return resp, err +} + +// getAllCreateRequest creates the GetAll request. +func (client *OptionalBooleanLiteralClient) getAllCreateRequest(ctx context.Context, _ *OptionalBooleanLiteralClientGetAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/boolean/literal/all" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getAllHandleResponse handles the GetAll response. +func (client *OptionalBooleanLiteralClient) getAllHandleResponse(resp *http.Response) (OptionalBooleanLiteralClientGetAllResponse, error) { + result := OptionalBooleanLiteralClientGetAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BooleanLiteralProperty); err != nil { + return OptionalBooleanLiteralClientGetAllResponse{}, err + } + return result, nil +} + +// GetDefault - Get models that will return the default object +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalBooleanLiteralClientGetDefaultOptions contains the optional parameters for the OptionalBooleanLiteralClient.GetDefault +// method. +func (client *OptionalBooleanLiteralClient) GetDefault(ctx context.Context, options *OptionalBooleanLiteralClientGetDefaultOptions) (OptionalBooleanLiteralClientGetDefaultResponse, error) { + var err error + const operationName = "OptionalBooleanLiteralClient.GetDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getDefaultCreateRequest(ctx, options) + if err != nil { + return OptionalBooleanLiteralClientGetDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalBooleanLiteralClientGetDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalBooleanLiteralClientGetDefaultResponse{}, err + } + resp, err := client.getDefaultHandleResponse(httpResp) + return resp, err +} + +// getDefaultCreateRequest creates the GetDefault request. +func (client *OptionalBooleanLiteralClient) getDefaultCreateRequest(ctx context.Context, _ *OptionalBooleanLiteralClientGetDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/boolean/literal/default" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getDefaultHandleResponse handles the GetDefault response. +func (client *OptionalBooleanLiteralClient) getDefaultHandleResponse(resp *http.Response) (OptionalBooleanLiteralClientGetDefaultResponse, error) { + result := OptionalBooleanLiteralClientGetDefaultResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BooleanLiteralProperty); err != nil { + return OptionalBooleanLiteralClientGetDefaultResponse{}, err + } + return result, nil +} + +// PutAll - Put a body with all properties present. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalBooleanLiteralClientPutAllOptions contains the optional parameters for the OptionalBooleanLiteralClient.PutAll +// method. +func (client *OptionalBooleanLiteralClient) PutAll(ctx context.Context, body BooleanLiteralProperty, options *OptionalBooleanLiteralClientPutAllOptions) (OptionalBooleanLiteralClientPutAllResponse, error) { + var err error + const operationName = "OptionalBooleanLiteralClient.PutAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putAllCreateRequest(ctx, body, options) + if err != nil { + return OptionalBooleanLiteralClientPutAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalBooleanLiteralClientPutAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalBooleanLiteralClientPutAllResponse{}, err + } + return OptionalBooleanLiteralClientPutAllResponse{}, nil +} + +// putAllCreateRequest creates the PutAll request. +func (client *OptionalBooleanLiteralClient) putAllCreateRequest(ctx context.Context, body BooleanLiteralProperty, _ *OptionalBooleanLiteralClientPutAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/boolean/literal/all" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// PutDefault - Put a body with default properties. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalBooleanLiteralClientPutDefaultOptions contains the optional parameters for the OptionalBooleanLiteralClient.PutDefault +// method. +func (client *OptionalBooleanLiteralClient) PutDefault(ctx context.Context, body BooleanLiteralProperty, options *OptionalBooleanLiteralClientPutDefaultOptions) (OptionalBooleanLiteralClientPutDefaultResponse, error) { + var err error + const operationName = "OptionalBooleanLiteralClient.PutDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putDefaultCreateRequest(ctx, body, options) + if err != nil { + return OptionalBooleanLiteralClientPutDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalBooleanLiteralClientPutDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalBooleanLiteralClientPutDefaultResponse{}, err + } + return OptionalBooleanLiteralClientPutDefaultResponse{}, nil +} + +// putDefaultCreateRequest creates the PutDefault request. +func (client *OptionalBooleanLiteralClient) putDefaultCreateRequest(ctx context.Context, body BooleanLiteralProperty, _ *OptionalBooleanLiteralClientPutDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/boolean/literal/default" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/optionalitygroup/zz_optionalbytes_client.go b/test/http-specs/type/property/optionalitygroup/zz_optionalbytes_client.go new file mode 100644 index 000000000000..1fbb11280b39 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/zz_optionalbytes_client.go @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package optionalitygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// OptionalBytesClient contains the methods for the OptionalBytes group. +// Don't use this type directly, use [OptionalClient.NewOptionalBytesClient] instead. +type OptionalBytesClient struct { + internal *azcore.Client + endpoint string +} + +// GetAll - Get models that will return all properties in the model +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalBytesClientGetAllOptions contains the optional parameters for the OptionalBytesClient.GetAll method. +func (client *OptionalBytesClient) GetAll(ctx context.Context, options *OptionalBytesClientGetAllOptions) (OptionalBytesClientGetAllResponse, error) { + var err error + const operationName = "OptionalBytesClient.GetAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getAllCreateRequest(ctx, options) + if err != nil { + return OptionalBytesClientGetAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalBytesClientGetAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalBytesClientGetAllResponse{}, err + } + resp, err := client.getAllHandleResponse(httpResp) + return resp, err +} + +// getAllCreateRequest creates the GetAll request. +func (client *OptionalBytesClient) getAllCreateRequest(ctx context.Context, _ *OptionalBytesClientGetAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/bytes/all" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getAllHandleResponse handles the GetAll response. +func (client *OptionalBytesClient) getAllHandleResponse(resp *http.Response) (OptionalBytesClientGetAllResponse, error) { + result := OptionalBytesClientGetAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BytesProperty); err != nil { + return OptionalBytesClientGetAllResponse{}, err + } + return result, nil +} + +// GetDefault - Get models that will return the default object +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalBytesClientGetDefaultOptions contains the optional parameters for the OptionalBytesClient.GetDefault +// method. +func (client *OptionalBytesClient) GetDefault(ctx context.Context, options *OptionalBytesClientGetDefaultOptions) (OptionalBytesClientGetDefaultResponse, error) { + var err error + const operationName = "OptionalBytesClient.GetDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getDefaultCreateRequest(ctx, options) + if err != nil { + return OptionalBytesClientGetDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalBytesClientGetDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalBytesClientGetDefaultResponse{}, err + } + resp, err := client.getDefaultHandleResponse(httpResp) + return resp, err +} + +// getDefaultCreateRequest creates the GetDefault request. +func (client *OptionalBytesClient) getDefaultCreateRequest(ctx context.Context, _ *OptionalBytesClientGetDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/bytes/default" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getDefaultHandleResponse handles the GetDefault response. +func (client *OptionalBytesClient) getDefaultHandleResponse(resp *http.Response) (OptionalBytesClientGetDefaultResponse, error) { + result := OptionalBytesClientGetDefaultResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BytesProperty); err != nil { + return OptionalBytesClientGetDefaultResponse{}, err + } + return result, nil +} + +// PutAll - Put a body with all properties present. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalBytesClientPutAllOptions contains the optional parameters for the OptionalBytesClient.PutAll method. +func (client *OptionalBytesClient) PutAll(ctx context.Context, body BytesProperty, options *OptionalBytesClientPutAllOptions) (OptionalBytesClientPutAllResponse, error) { + var err error + const operationName = "OptionalBytesClient.PutAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putAllCreateRequest(ctx, body, options) + if err != nil { + return OptionalBytesClientPutAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalBytesClientPutAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalBytesClientPutAllResponse{}, err + } + return OptionalBytesClientPutAllResponse{}, nil +} + +// putAllCreateRequest creates the PutAll request. +func (client *OptionalBytesClient) putAllCreateRequest(ctx context.Context, body BytesProperty, _ *OptionalBytesClientPutAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/bytes/all" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// PutDefault - Put a body with default properties. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalBytesClientPutDefaultOptions contains the optional parameters for the OptionalBytesClient.PutDefault +// method. +func (client *OptionalBytesClient) PutDefault(ctx context.Context, body BytesProperty, options *OptionalBytesClientPutDefaultOptions) (OptionalBytesClientPutDefaultResponse, error) { + var err error + const operationName = "OptionalBytesClient.PutDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putDefaultCreateRequest(ctx, body, options) + if err != nil { + return OptionalBytesClientPutDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalBytesClientPutDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalBytesClientPutDefaultResponse{}, err + } + return OptionalBytesClientPutDefaultResponse{}, nil +} + +// putDefaultCreateRequest creates the PutDefault request. +func (client *OptionalBytesClient) putDefaultCreateRequest(ctx context.Context, body BytesProperty, _ *OptionalBytesClientPutDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/bytes/default" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/optionalitygroup/zz_optionalcollectionsbyte_client.go b/test/http-specs/type/property/optionalitygroup/zz_optionalcollectionsbyte_client.go new file mode 100644 index 000000000000..cbf0eaedff2c --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/zz_optionalcollectionsbyte_client.go @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package optionalitygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// OptionalCollectionsByteClient contains the methods for the OptionalCollectionsByte group. +// Don't use this type directly, use [OptionalClient.NewOptionalCollectionsByteClient] instead. +type OptionalCollectionsByteClient struct { + internal *azcore.Client + endpoint string +} + +// GetAll - Get models that will return all properties in the model +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalCollectionsByteClientGetAllOptions contains the optional parameters for the OptionalCollectionsByteClient.GetAll +// method. +func (client *OptionalCollectionsByteClient) GetAll(ctx context.Context, options *OptionalCollectionsByteClientGetAllOptions) (OptionalCollectionsByteClientGetAllResponse, error) { + var err error + const operationName = "OptionalCollectionsByteClient.GetAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getAllCreateRequest(ctx, options) + if err != nil { + return OptionalCollectionsByteClientGetAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalCollectionsByteClientGetAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalCollectionsByteClientGetAllResponse{}, err + } + resp, err := client.getAllHandleResponse(httpResp) + return resp, err +} + +// getAllCreateRequest creates the GetAll request. +func (client *OptionalCollectionsByteClient) getAllCreateRequest(ctx context.Context, _ *OptionalCollectionsByteClientGetAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/collections/bytes/all" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getAllHandleResponse handles the GetAll response. +func (client *OptionalCollectionsByteClient) getAllHandleResponse(resp *http.Response) (OptionalCollectionsByteClientGetAllResponse, error) { + result := OptionalCollectionsByteClientGetAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CollectionsByteProperty); err != nil { + return OptionalCollectionsByteClientGetAllResponse{}, err + } + return result, nil +} + +// GetDefault - Get models that will return the default object +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalCollectionsByteClientGetDefaultOptions contains the optional parameters for the OptionalCollectionsByteClient.GetDefault +// method. +func (client *OptionalCollectionsByteClient) GetDefault(ctx context.Context, options *OptionalCollectionsByteClientGetDefaultOptions) (OptionalCollectionsByteClientGetDefaultResponse, error) { + var err error + const operationName = "OptionalCollectionsByteClient.GetDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getDefaultCreateRequest(ctx, options) + if err != nil { + return OptionalCollectionsByteClientGetDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalCollectionsByteClientGetDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalCollectionsByteClientGetDefaultResponse{}, err + } + resp, err := client.getDefaultHandleResponse(httpResp) + return resp, err +} + +// getDefaultCreateRequest creates the GetDefault request. +func (client *OptionalCollectionsByteClient) getDefaultCreateRequest(ctx context.Context, _ *OptionalCollectionsByteClientGetDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/collections/bytes/default" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getDefaultHandleResponse handles the GetDefault response. +func (client *OptionalCollectionsByteClient) getDefaultHandleResponse(resp *http.Response) (OptionalCollectionsByteClientGetDefaultResponse, error) { + result := OptionalCollectionsByteClientGetDefaultResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CollectionsByteProperty); err != nil { + return OptionalCollectionsByteClientGetDefaultResponse{}, err + } + return result, nil +} + +// PutAll - Put a body with all properties present. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalCollectionsByteClientPutAllOptions contains the optional parameters for the OptionalCollectionsByteClient.PutAll +// method. +func (client *OptionalCollectionsByteClient) PutAll(ctx context.Context, body CollectionsByteProperty, options *OptionalCollectionsByteClientPutAllOptions) (OptionalCollectionsByteClientPutAllResponse, error) { + var err error + const operationName = "OptionalCollectionsByteClient.PutAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putAllCreateRequest(ctx, body, options) + if err != nil { + return OptionalCollectionsByteClientPutAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalCollectionsByteClientPutAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalCollectionsByteClientPutAllResponse{}, err + } + return OptionalCollectionsByteClientPutAllResponse{}, nil +} + +// putAllCreateRequest creates the PutAll request. +func (client *OptionalCollectionsByteClient) putAllCreateRequest(ctx context.Context, body CollectionsByteProperty, _ *OptionalCollectionsByteClientPutAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/collections/bytes/all" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// PutDefault - Put a body with default properties. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalCollectionsByteClientPutDefaultOptions contains the optional parameters for the OptionalCollectionsByteClient.PutDefault +// method. +func (client *OptionalCollectionsByteClient) PutDefault(ctx context.Context, body CollectionsByteProperty, options *OptionalCollectionsByteClientPutDefaultOptions) (OptionalCollectionsByteClientPutDefaultResponse, error) { + var err error + const operationName = "OptionalCollectionsByteClient.PutDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putDefaultCreateRequest(ctx, body, options) + if err != nil { + return OptionalCollectionsByteClientPutDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalCollectionsByteClientPutDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalCollectionsByteClientPutDefaultResponse{}, err + } + return OptionalCollectionsByteClientPutDefaultResponse{}, nil +} + +// putDefaultCreateRequest creates the PutDefault request. +func (client *OptionalCollectionsByteClient) putDefaultCreateRequest(ctx context.Context, body CollectionsByteProperty, _ *OptionalCollectionsByteClientPutDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/collections/bytes/default" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/optionalitygroup/zz_optionalcollectionsmodel_client.go b/test/http-specs/type/property/optionalitygroup/zz_optionalcollectionsmodel_client.go new file mode 100644 index 000000000000..396c63d2648f --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/zz_optionalcollectionsmodel_client.go @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package optionalitygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// OptionalCollectionsModelClient contains the methods for the OptionalCollectionsModel group. +// Don't use this type directly, use [OptionalClient.NewOptionalCollectionsModelClient] instead. +type OptionalCollectionsModelClient struct { + internal *azcore.Client + endpoint string +} + +// GetAll - Get models that will return all properties in the model +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalCollectionsModelClientGetAllOptions contains the optional parameters for the OptionalCollectionsModelClient.GetAll +// method. +func (client *OptionalCollectionsModelClient) GetAll(ctx context.Context, options *OptionalCollectionsModelClientGetAllOptions) (OptionalCollectionsModelClientGetAllResponse, error) { + var err error + const operationName = "OptionalCollectionsModelClient.GetAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getAllCreateRequest(ctx, options) + if err != nil { + return OptionalCollectionsModelClientGetAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalCollectionsModelClientGetAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalCollectionsModelClientGetAllResponse{}, err + } + resp, err := client.getAllHandleResponse(httpResp) + return resp, err +} + +// getAllCreateRequest creates the GetAll request. +func (client *OptionalCollectionsModelClient) getAllCreateRequest(ctx context.Context, _ *OptionalCollectionsModelClientGetAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/collections/model/all" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getAllHandleResponse handles the GetAll response. +func (client *OptionalCollectionsModelClient) getAllHandleResponse(resp *http.Response) (OptionalCollectionsModelClientGetAllResponse, error) { + result := OptionalCollectionsModelClientGetAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CollectionsModelProperty); err != nil { + return OptionalCollectionsModelClientGetAllResponse{}, err + } + return result, nil +} + +// GetDefault - Get models that will return the default object +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalCollectionsModelClientGetDefaultOptions contains the optional parameters for the OptionalCollectionsModelClient.GetDefault +// method. +func (client *OptionalCollectionsModelClient) GetDefault(ctx context.Context, options *OptionalCollectionsModelClientGetDefaultOptions) (OptionalCollectionsModelClientGetDefaultResponse, error) { + var err error + const operationName = "OptionalCollectionsModelClient.GetDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getDefaultCreateRequest(ctx, options) + if err != nil { + return OptionalCollectionsModelClientGetDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalCollectionsModelClientGetDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalCollectionsModelClientGetDefaultResponse{}, err + } + resp, err := client.getDefaultHandleResponse(httpResp) + return resp, err +} + +// getDefaultCreateRequest creates the GetDefault request. +func (client *OptionalCollectionsModelClient) getDefaultCreateRequest(ctx context.Context, _ *OptionalCollectionsModelClientGetDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/collections/model/default" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getDefaultHandleResponse handles the GetDefault response. +func (client *OptionalCollectionsModelClient) getDefaultHandleResponse(resp *http.Response) (OptionalCollectionsModelClientGetDefaultResponse, error) { + result := OptionalCollectionsModelClientGetDefaultResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CollectionsModelProperty); err != nil { + return OptionalCollectionsModelClientGetDefaultResponse{}, err + } + return result, nil +} + +// PutAll - Put a body with all properties present. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalCollectionsModelClientPutAllOptions contains the optional parameters for the OptionalCollectionsModelClient.PutAll +// method. +func (client *OptionalCollectionsModelClient) PutAll(ctx context.Context, body CollectionsModelProperty, options *OptionalCollectionsModelClientPutAllOptions) (OptionalCollectionsModelClientPutAllResponse, error) { + var err error + const operationName = "OptionalCollectionsModelClient.PutAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putAllCreateRequest(ctx, body, options) + if err != nil { + return OptionalCollectionsModelClientPutAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalCollectionsModelClientPutAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalCollectionsModelClientPutAllResponse{}, err + } + return OptionalCollectionsModelClientPutAllResponse{}, nil +} + +// putAllCreateRequest creates the PutAll request. +func (client *OptionalCollectionsModelClient) putAllCreateRequest(ctx context.Context, body CollectionsModelProperty, _ *OptionalCollectionsModelClientPutAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/collections/model/all" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// PutDefault - Put a body with default properties. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalCollectionsModelClientPutDefaultOptions contains the optional parameters for the OptionalCollectionsModelClient.PutDefault +// method. +func (client *OptionalCollectionsModelClient) PutDefault(ctx context.Context, body CollectionsModelProperty, options *OptionalCollectionsModelClientPutDefaultOptions) (OptionalCollectionsModelClientPutDefaultResponse, error) { + var err error + const operationName = "OptionalCollectionsModelClient.PutDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putDefaultCreateRequest(ctx, body, options) + if err != nil { + return OptionalCollectionsModelClientPutDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalCollectionsModelClientPutDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalCollectionsModelClientPutDefaultResponse{}, err + } + return OptionalCollectionsModelClientPutDefaultResponse{}, nil +} + +// putDefaultCreateRequest creates the PutDefault request. +func (client *OptionalCollectionsModelClient) putDefaultCreateRequest(ctx context.Context, body CollectionsModelProperty, _ *OptionalCollectionsModelClientPutDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/collections/model/default" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/optionalitygroup/zz_optionaldatetime_client.go b/test/http-specs/type/property/optionalitygroup/zz_optionaldatetime_client.go new file mode 100644 index 000000000000..895a0b73bdcf --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/zz_optionaldatetime_client.go @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package optionalitygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// OptionalDatetimeClient contains the methods for the OptionalDatetime group. +// Don't use this type directly, use [OptionalClient.NewOptionalDatetimeClient] instead. +type OptionalDatetimeClient struct { + internal *azcore.Client + endpoint string +} + +// GetAll - Get models that will return all properties in the model +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalDatetimeClientGetAllOptions contains the optional parameters for the OptionalDatetimeClient.GetAll method. +func (client *OptionalDatetimeClient) GetAll(ctx context.Context, options *OptionalDatetimeClientGetAllOptions) (OptionalDatetimeClientGetAllResponse, error) { + var err error + const operationName = "OptionalDatetimeClient.GetAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getAllCreateRequest(ctx, options) + if err != nil { + return OptionalDatetimeClientGetAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalDatetimeClientGetAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalDatetimeClientGetAllResponse{}, err + } + resp, err := client.getAllHandleResponse(httpResp) + return resp, err +} + +// getAllCreateRequest creates the GetAll request. +func (client *OptionalDatetimeClient) getAllCreateRequest(ctx context.Context, _ *OptionalDatetimeClientGetAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/datetime/all" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getAllHandleResponse handles the GetAll response. +func (client *OptionalDatetimeClient) getAllHandleResponse(resp *http.Response) (OptionalDatetimeClientGetAllResponse, error) { + result := OptionalDatetimeClientGetAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DatetimeProperty); err != nil { + return OptionalDatetimeClientGetAllResponse{}, err + } + return result, nil +} + +// GetDefault - Get models that will return the default object +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalDatetimeClientGetDefaultOptions contains the optional parameters for the OptionalDatetimeClient.GetDefault +// method. +func (client *OptionalDatetimeClient) GetDefault(ctx context.Context, options *OptionalDatetimeClientGetDefaultOptions) (OptionalDatetimeClientGetDefaultResponse, error) { + var err error + const operationName = "OptionalDatetimeClient.GetDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getDefaultCreateRequest(ctx, options) + if err != nil { + return OptionalDatetimeClientGetDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalDatetimeClientGetDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalDatetimeClientGetDefaultResponse{}, err + } + resp, err := client.getDefaultHandleResponse(httpResp) + return resp, err +} + +// getDefaultCreateRequest creates the GetDefault request. +func (client *OptionalDatetimeClient) getDefaultCreateRequest(ctx context.Context, _ *OptionalDatetimeClientGetDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/datetime/default" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getDefaultHandleResponse handles the GetDefault response. +func (client *OptionalDatetimeClient) getDefaultHandleResponse(resp *http.Response) (OptionalDatetimeClientGetDefaultResponse, error) { + result := OptionalDatetimeClientGetDefaultResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DatetimeProperty); err != nil { + return OptionalDatetimeClientGetDefaultResponse{}, err + } + return result, nil +} + +// PutAll - Put a body with all properties present. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalDatetimeClientPutAllOptions contains the optional parameters for the OptionalDatetimeClient.PutAll method. +func (client *OptionalDatetimeClient) PutAll(ctx context.Context, body DatetimeProperty, options *OptionalDatetimeClientPutAllOptions) (OptionalDatetimeClientPutAllResponse, error) { + var err error + const operationName = "OptionalDatetimeClient.PutAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putAllCreateRequest(ctx, body, options) + if err != nil { + return OptionalDatetimeClientPutAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalDatetimeClientPutAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalDatetimeClientPutAllResponse{}, err + } + return OptionalDatetimeClientPutAllResponse{}, nil +} + +// putAllCreateRequest creates the PutAll request. +func (client *OptionalDatetimeClient) putAllCreateRequest(ctx context.Context, body DatetimeProperty, _ *OptionalDatetimeClientPutAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/datetime/all" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// PutDefault - Put a body with default properties. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalDatetimeClientPutDefaultOptions contains the optional parameters for the OptionalDatetimeClient.PutDefault +// method. +func (client *OptionalDatetimeClient) PutDefault(ctx context.Context, body DatetimeProperty, options *OptionalDatetimeClientPutDefaultOptions) (OptionalDatetimeClientPutDefaultResponse, error) { + var err error + const operationName = "OptionalDatetimeClient.PutDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putDefaultCreateRequest(ctx, body, options) + if err != nil { + return OptionalDatetimeClientPutDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalDatetimeClientPutDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalDatetimeClientPutDefaultResponse{}, err + } + return OptionalDatetimeClientPutDefaultResponse{}, nil +} + +// putDefaultCreateRequest creates the PutDefault request. +func (client *OptionalDatetimeClient) putDefaultCreateRequest(ctx context.Context, body DatetimeProperty, _ *OptionalDatetimeClientPutDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/datetime/default" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/optionalitygroup/zz_optionalduration_client.go b/test/http-specs/type/property/optionalitygroup/zz_optionalduration_client.go new file mode 100644 index 000000000000..56e7ac4eb208 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/zz_optionalduration_client.go @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package optionalitygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// OptionalDurationClient contains the methods for the OptionalDuration group. +// Don't use this type directly, use [OptionalClient.NewOptionalDurationClient] instead. +type OptionalDurationClient struct { + internal *azcore.Client + endpoint string +} + +// GetAll - Get models that will return all properties in the model +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalDurationClientGetAllOptions contains the optional parameters for the OptionalDurationClient.GetAll method. +func (client *OptionalDurationClient) GetAll(ctx context.Context, options *OptionalDurationClientGetAllOptions) (OptionalDurationClientGetAllResponse, error) { + var err error + const operationName = "OptionalDurationClient.GetAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getAllCreateRequest(ctx, options) + if err != nil { + return OptionalDurationClientGetAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalDurationClientGetAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalDurationClientGetAllResponse{}, err + } + resp, err := client.getAllHandleResponse(httpResp) + return resp, err +} + +// getAllCreateRequest creates the GetAll request. +func (client *OptionalDurationClient) getAllCreateRequest(ctx context.Context, _ *OptionalDurationClientGetAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/duration/all" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getAllHandleResponse handles the GetAll response. +func (client *OptionalDurationClient) getAllHandleResponse(resp *http.Response) (OptionalDurationClientGetAllResponse, error) { + result := OptionalDurationClientGetAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DurationProperty); err != nil { + return OptionalDurationClientGetAllResponse{}, err + } + return result, nil +} + +// GetDefault - Get models that will return the default object +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalDurationClientGetDefaultOptions contains the optional parameters for the OptionalDurationClient.GetDefault +// method. +func (client *OptionalDurationClient) GetDefault(ctx context.Context, options *OptionalDurationClientGetDefaultOptions) (OptionalDurationClientGetDefaultResponse, error) { + var err error + const operationName = "OptionalDurationClient.GetDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getDefaultCreateRequest(ctx, options) + if err != nil { + return OptionalDurationClientGetDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalDurationClientGetDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalDurationClientGetDefaultResponse{}, err + } + resp, err := client.getDefaultHandleResponse(httpResp) + return resp, err +} + +// getDefaultCreateRequest creates the GetDefault request. +func (client *OptionalDurationClient) getDefaultCreateRequest(ctx context.Context, _ *OptionalDurationClientGetDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/duration/default" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getDefaultHandleResponse handles the GetDefault response. +func (client *OptionalDurationClient) getDefaultHandleResponse(resp *http.Response) (OptionalDurationClientGetDefaultResponse, error) { + result := OptionalDurationClientGetDefaultResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DurationProperty); err != nil { + return OptionalDurationClientGetDefaultResponse{}, err + } + return result, nil +} + +// PutAll - Put a body with all properties present. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalDurationClientPutAllOptions contains the optional parameters for the OptionalDurationClient.PutAll method. +func (client *OptionalDurationClient) PutAll(ctx context.Context, body DurationProperty, options *OptionalDurationClientPutAllOptions) (OptionalDurationClientPutAllResponse, error) { + var err error + const operationName = "OptionalDurationClient.PutAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putAllCreateRequest(ctx, body, options) + if err != nil { + return OptionalDurationClientPutAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalDurationClientPutAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalDurationClientPutAllResponse{}, err + } + return OptionalDurationClientPutAllResponse{}, nil +} + +// putAllCreateRequest creates the PutAll request. +func (client *OptionalDurationClient) putAllCreateRequest(ctx context.Context, body DurationProperty, _ *OptionalDurationClientPutAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/duration/all" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// PutDefault - Put a body with default properties. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalDurationClientPutDefaultOptions contains the optional parameters for the OptionalDurationClient.PutDefault +// method. +func (client *OptionalDurationClient) PutDefault(ctx context.Context, body DurationProperty, options *OptionalDurationClientPutDefaultOptions) (OptionalDurationClientPutDefaultResponse, error) { + var err error + const operationName = "OptionalDurationClient.PutDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putDefaultCreateRequest(ctx, body, options) + if err != nil { + return OptionalDurationClientPutDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalDurationClientPutDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalDurationClientPutDefaultResponse{}, err + } + return OptionalDurationClientPutDefaultResponse{}, nil +} + +// putDefaultCreateRequest creates the PutDefault request. +func (client *OptionalDurationClient) putDefaultCreateRequest(ctx context.Context, body DurationProperty, _ *OptionalDurationClientPutDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/duration/default" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/optionalitygroup/zz_optionalfloatliteral_client.go b/test/http-specs/type/property/optionalitygroup/zz_optionalfloatliteral_client.go new file mode 100644 index 000000000000..536bf6ee9c1e --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/zz_optionalfloatliteral_client.go @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package optionalitygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// OptionalFloatLiteralClient contains the methods for the OptionalFloatLiteral group. +// Don't use this type directly, use [OptionalClient.NewOptionalFloatLiteralClient] instead. +type OptionalFloatLiteralClient struct { + internal *azcore.Client + endpoint string +} + +// GetAll - Get models that will return all properties in the model +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalFloatLiteralClientGetAllOptions contains the optional parameters for the OptionalFloatLiteralClient.GetAll +// method. +func (client *OptionalFloatLiteralClient) GetAll(ctx context.Context, options *OptionalFloatLiteralClientGetAllOptions) (OptionalFloatLiteralClientGetAllResponse, error) { + var err error + const operationName = "OptionalFloatLiteralClient.GetAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getAllCreateRequest(ctx, options) + if err != nil { + return OptionalFloatLiteralClientGetAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalFloatLiteralClientGetAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalFloatLiteralClientGetAllResponse{}, err + } + resp, err := client.getAllHandleResponse(httpResp) + return resp, err +} + +// getAllCreateRequest creates the GetAll request. +func (client *OptionalFloatLiteralClient) getAllCreateRequest(ctx context.Context, _ *OptionalFloatLiteralClientGetAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/float/literal/all" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getAllHandleResponse handles the GetAll response. +func (client *OptionalFloatLiteralClient) getAllHandleResponse(resp *http.Response) (OptionalFloatLiteralClientGetAllResponse, error) { + result := OptionalFloatLiteralClientGetAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FloatLiteralProperty); err != nil { + return OptionalFloatLiteralClientGetAllResponse{}, err + } + return result, nil +} + +// GetDefault - Get models that will return the default object +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalFloatLiteralClientGetDefaultOptions contains the optional parameters for the OptionalFloatLiteralClient.GetDefault +// method. +func (client *OptionalFloatLiteralClient) GetDefault(ctx context.Context, options *OptionalFloatLiteralClientGetDefaultOptions) (OptionalFloatLiteralClientGetDefaultResponse, error) { + var err error + const operationName = "OptionalFloatLiteralClient.GetDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getDefaultCreateRequest(ctx, options) + if err != nil { + return OptionalFloatLiteralClientGetDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalFloatLiteralClientGetDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalFloatLiteralClientGetDefaultResponse{}, err + } + resp, err := client.getDefaultHandleResponse(httpResp) + return resp, err +} + +// getDefaultCreateRequest creates the GetDefault request. +func (client *OptionalFloatLiteralClient) getDefaultCreateRequest(ctx context.Context, _ *OptionalFloatLiteralClientGetDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/float/literal/default" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getDefaultHandleResponse handles the GetDefault response. +func (client *OptionalFloatLiteralClient) getDefaultHandleResponse(resp *http.Response) (OptionalFloatLiteralClientGetDefaultResponse, error) { + result := OptionalFloatLiteralClientGetDefaultResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FloatLiteralProperty); err != nil { + return OptionalFloatLiteralClientGetDefaultResponse{}, err + } + return result, nil +} + +// PutAll - Put a body with all properties present. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalFloatLiteralClientPutAllOptions contains the optional parameters for the OptionalFloatLiteralClient.PutAll +// method. +func (client *OptionalFloatLiteralClient) PutAll(ctx context.Context, body FloatLiteralProperty, options *OptionalFloatLiteralClientPutAllOptions) (OptionalFloatLiteralClientPutAllResponse, error) { + var err error + const operationName = "OptionalFloatLiteralClient.PutAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putAllCreateRequest(ctx, body, options) + if err != nil { + return OptionalFloatLiteralClientPutAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalFloatLiteralClientPutAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalFloatLiteralClientPutAllResponse{}, err + } + return OptionalFloatLiteralClientPutAllResponse{}, nil +} + +// putAllCreateRequest creates the PutAll request. +func (client *OptionalFloatLiteralClient) putAllCreateRequest(ctx context.Context, body FloatLiteralProperty, _ *OptionalFloatLiteralClientPutAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/float/literal/all" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// PutDefault - Put a body with default properties. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalFloatLiteralClientPutDefaultOptions contains the optional parameters for the OptionalFloatLiteralClient.PutDefault +// method. +func (client *OptionalFloatLiteralClient) PutDefault(ctx context.Context, body FloatLiteralProperty, options *OptionalFloatLiteralClientPutDefaultOptions) (OptionalFloatLiteralClientPutDefaultResponse, error) { + var err error + const operationName = "OptionalFloatLiteralClient.PutDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putDefaultCreateRequest(ctx, body, options) + if err != nil { + return OptionalFloatLiteralClientPutDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalFloatLiteralClientPutDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalFloatLiteralClientPutDefaultResponse{}, err + } + return OptionalFloatLiteralClientPutDefaultResponse{}, nil +} + +// putDefaultCreateRequest creates the PutDefault request. +func (client *OptionalFloatLiteralClient) putDefaultCreateRequest(ctx context.Context, body FloatLiteralProperty, _ *OptionalFloatLiteralClientPutDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/float/literal/default" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/optionalitygroup/zz_optionalintliteral_client.go b/test/http-specs/type/property/optionalitygroup/zz_optionalintliteral_client.go new file mode 100644 index 000000000000..490916c6f7e7 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/zz_optionalintliteral_client.go @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package optionalitygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// OptionalIntLiteralClient contains the methods for the OptionalIntLiteral group. +// Don't use this type directly, use [OptionalClient.NewOptionalIntLiteralClient] instead. +type OptionalIntLiteralClient struct { + internal *azcore.Client + endpoint string +} + +// GetAll - Get models that will return all properties in the model +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalIntLiteralClientGetAllOptions contains the optional parameters for the OptionalIntLiteralClient.GetAll +// method. +func (client *OptionalIntLiteralClient) GetAll(ctx context.Context, options *OptionalIntLiteralClientGetAllOptions) (OptionalIntLiteralClientGetAllResponse, error) { + var err error + const operationName = "OptionalIntLiteralClient.GetAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getAllCreateRequest(ctx, options) + if err != nil { + return OptionalIntLiteralClientGetAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalIntLiteralClientGetAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalIntLiteralClientGetAllResponse{}, err + } + resp, err := client.getAllHandleResponse(httpResp) + return resp, err +} + +// getAllCreateRequest creates the GetAll request. +func (client *OptionalIntLiteralClient) getAllCreateRequest(ctx context.Context, _ *OptionalIntLiteralClientGetAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/int/literal/all" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getAllHandleResponse handles the GetAll response. +func (client *OptionalIntLiteralClient) getAllHandleResponse(resp *http.Response) (OptionalIntLiteralClientGetAllResponse, error) { + result := OptionalIntLiteralClientGetAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.IntLiteralProperty); err != nil { + return OptionalIntLiteralClientGetAllResponse{}, err + } + return result, nil +} + +// GetDefault - Get models that will return the default object +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalIntLiteralClientGetDefaultOptions contains the optional parameters for the OptionalIntLiteralClient.GetDefault +// method. +func (client *OptionalIntLiteralClient) GetDefault(ctx context.Context, options *OptionalIntLiteralClientGetDefaultOptions) (OptionalIntLiteralClientGetDefaultResponse, error) { + var err error + const operationName = "OptionalIntLiteralClient.GetDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getDefaultCreateRequest(ctx, options) + if err != nil { + return OptionalIntLiteralClientGetDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalIntLiteralClientGetDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalIntLiteralClientGetDefaultResponse{}, err + } + resp, err := client.getDefaultHandleResponse(httpResp) + return resp, err +} + +// getDefaultCreateRequest creates the GetDefault request. +func (client *OptionalIntLiteralClient) getDefaultCreateRequest(ctx context.Context, _ *OptionalIntLiteralClientGetDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/int/literal/default" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getDefaultHandleResponse handles the GetDefault response. +func (client *OptionalIntLiteralClient) getDefaultHandleResponse(resp *http.Response) (OptionalIntLiteralClientGetDefaultResponse, error) { + result := OptionalIntLiteralClientGetDefaultResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.IntLiteralProperty); err != nil { + return OptionalIntLiteralClientGetDefaultResponse{}, err + } + return result, nil +} + +// PutAll - Put a body with all properties present. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalIntLiteralClientPutAllOptions contains the optional parameters for the OptionalIntLiteralClient.PutAll +// method. +func (client *OptionalIntLiteralClient) PutAll(ctx context.Context, body IntLiteralProperty, options *OptionalIntLiteralClientPutAllOptions) (OptionalIntLiteralClientPutAllResponse, error) { + var err error + const operationName = "OptionalIntLiteralClient.PutAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putAllCreateRequest(ctx, body, options) + if err != nil { + return OptionalIntLiteralClientPutAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalIntLiteralClientPutAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalIntLiteralClientPutAllResponse{}, err + } + return OptionalIntLiteralClientPutAllResponse{}, nil +} + +// putAllCreateRequest creates the PutAll request. +func (client *OptionalIntLiteralClient) putAllCreateRequest(ctx context.Context, body IntLiteralProperty, _ *OptionalIntLiteralClientPutAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/int/literal/all" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// PutDefault - Put a body with default properties. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalIntLiteralClientPutDefaultOptions contains the optional parameters for the OptionalIntLiteralClient.PutDefault +// method. +func (client *OptionalIntLiteralClient) PutDefault(ctx context.Context, body IntLiteralProperty, options *OptionalIntLiteralClientPutDefaultOptions) (OptionalIntLiteralClientPutDefaultResponse, error) { + var err error + const operationName = "OptionalIntLiteralClient.PutDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putDefaultCreateRequest(ctx, body, options) + if err != nil { + return OptionalIntLiteralClientPutDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalIntLiteralClientPutDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalIntLiteralClientPutDefaultResponse{}, err + } + return OptionalIntLiteralClientPutDefaultResponse{}, nil +} + +// putDefaultCreateRequest creates the PutDefault request. +func (client *OptionalIntLiteralClient) putDefaultCreateRequest(ctx context.Context, body IntLiteralProperty, _ *OptionalIntLiteralClientPutDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/int/literal/default" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/optionalitygroup/zz_optionalplaindate_client.go b/test/http-specs/type/property/optionalitygroup/zz_optionalplaindate_client.go new file mode 100644 index 000000000000..8317a0486df3 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/zz_optionalplaindate_client.go @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package optionalitygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// OptionalPlainDateClient contains the methods for the OptionalPlainDate group. +// Don't use this type directly, use [OptionalClient.NewOptionalPlainDateClient] instead. +type OptionalPlainDateClient struct { + internal *azcore.Client + endpoint string +} + +// GetAll - Get models that will return all properties in the model +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalPlainDateClientGetAllOptions contains the optional parameters for the OptionalPlainDateClient.GetAll +// method. +func (client *OptionalPlainDateClient) GetAll(ctx context.Context, options *OptionalPlainDateClientGetAllOptions) (OptionalPlainDateClientGetAllResponse, error) { + var err error + const operationName = "OptionalPlainDateClient.GetAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getAllCreateRequest(ctx, options) + if err != nil { + return OptionalPlainDateClientGetAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalPlainDateClientGetAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalPlainDateClientGetAllResponse{}, err + } + resp, err := client.getAllHandleResponse(httpResp) + return resp, err +} + +// getAllCreateRequest creates the GetAll request. +func (client *OptionalPlainDateClient) getAllCreateRequest(ctx context.Context, _ *OptionalPlainDateClientGetAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/plainDate/all" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getAllHandleResponse handles the GetAll response. +func (client *OptionalPlainDateClient) getAllHandleResponse(resp *http.Response) (OptionalPlainDateClientGetAllResponse, error) { + result := OptionalPlainDateClientGetAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PlainDateProperty); err != nil { + return OptionalPlainDateClientGetAllResponse{}, err + } + return result, nil +} + +// GetDefault - Get models that will return the default object +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalPlainDateClientGetDefaultOptions contains the optional parameters for the OptionalPlainDateClient.GetDefault +// method. +func (client *OptionalPlainDateClient) GetDefault(ctx context.Context, options *OptionalPlainDateClientGetDefaultOptions) (OptionalPlainDateClientGetDefaultResponse, error) { + var err error + const operationName = "OptionalPlainDateClient.GetDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getDefaultCreateRequest(ctx, options) + if err != nil { + return OptionalPlainDateClientGetDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalPlainDateClientGetDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalPlainDateClientGetDefaultResponse{}, err + } + resp, err := client.getDefaultHandleResponse(httpResp) + return resp, err +} + +// getDefaultCreateRequest creates the GetDefault request. +func (client *OptionalPlainDateClient) getDefaultCreateRequest(ctx context.Context, _ *OptionalPlainDateClientGetDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/plainDate/default" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getDefaultHandleResponse handles the GetDefault response. +func (client *OptionalPlainDateClient) getDefaultHandleResponse(resp *http.Response) (OptionalPlainDateClientGetDefaultResponse, error) { + result := OptionalPlainDateClientGetDefaultResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PlainDateProperty); err != nil { + return OptionalPlainDateClientGetDefaultResponse{}, err + } + return result, nil +} + +// PutAll - Put a body with all properties present. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalPlainDateClientPutAllOptions contains the optional parameters for the OptionalPlainDateClient.PutAll +// method. +func (client *OptionalPlainDateClient) PutAll(ctx context.Context, body PlainDateProperty, options *OptionalPlainDateClientPutAllOptions) (OptionalPlainDateClientPutAllResponse, error) { + var err error + const operationName = "OptionalPlainDateClient.PutAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putAllCreateRequest(ctx, body, options) + if err != nil { + return OptionalPlainDateClientPutAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalPlainDateClientPutAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalPlainDateClientPutAllResponse{}, err + } + return OptionalPlainDateClientPutAllResponse{}, nil +} + +// putAllCreateRequest creates the PutAll request. +func (client *OptionalPlainDateClient) putAllCreateRequest(ctx context.Context, body PlainDateProperty, _ *OptionalPlainDateClientPutAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/plainDate/all" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// PutDefault - Put a body with default properties. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalPlainDateClientPutDefaultOptions contains the optional parameters for the OptionalPlainDateClient.PutDefault +// method. +func (client *OptionalPlainDateClient) PutDefault(ctx context.Context, body PlainDateProperty, options *OptionalPlainDateClientPutDefaultOptions) (OptionalPlainDateClientPutDefaultResponse, error) { + var err error + const operationName = "OptionalPlainDateClient.PutDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putDefaultCreateRequest(ctx, body, options) + if err != nil { + return OptionalPlainDateClientPutDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalPlainDateClientPutDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalPlainDateClientPutDefaultResponse{}, err + } + return OptionalPlainDateClientPutDefaultResponse{}, nil +} + +// putDefaultCreateRequest creates the PutDefault request. +func (client *OptionalPlainDateClient) putDefaultCreateRequest(ctx context.Context, body PlainDateProperty, _ *OptionalPlainDateClientPutDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/plainDate/default" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/optionalitygroup/zz_optionalplaintime_client.go b/test/http-specs/type/property/optionalitygroup/zz_optionalplaintime_client.go new file mode 100644 index 000000000000..acbae2c1906a --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/zz_optionalplaintime_client.go @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package optionalitygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// OptionalPlainTimeClient contains the methods for the OptionalPlainTime group. +// Don't use this type directly, use [OptionalClient.NewOptionalPlainTimeClient] instead. +type OptionalPlainTimeClient struct { + internal *azcore.Client + endpoint string +} + +// GetAll - Get models that will return all properties in the model +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalPlainTimeClientGetAllOptions contains the optional parameters for the OptionalPlainTimeClient.GetAll +// method. +func (client *OptionalPlainTimeClient) GetAll(ctx context.Context, options *OptionalPlainTimeClientGetAllOptions) (OptionalPlainTimeClientGetAllResponse, error) { + var err error + const operationName = "OptionalPlainTimeClient.GetAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getAllCreateRequest(ctx, options) + if err != nil { + return OptionalPlainTimeClientGetAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalPlainTimeClientGetAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalPlainTimeClientGetAllResponse{}, err + } + resp, err := client.getAllHandleResponse(httpResp) + return resp, err +} + +// getAllCreateRequest creates the GetAll request. +func (client *OptionalPlainTimeClient) getAllCreateRequest(ctx context.Context, _ *OptionalPlainTimeClientGetAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/plainTime/all" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getAllHandleResponse handles the GetAll response. +func (client *OptionalPlainTimeClient) getAllHandleResponse(resp *http.Response) (OptionalPlainTimeClientGetAllResponse, error) { + result := OptionalPlainTimeClientGetAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PlainTimeProperty); err != nil { + return OptionalPlainTimeClientGetAllResponse{}, err + } + return result, nil +} + +// GetDefault - Get models that will return the default object +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalPlainTimeClientGetDefaultOptions contains the optional parameters for the OptionalPlainTimeClient.GetDefault +// method. +func (client *OptionalPlainTimeClient) GetDefault(ctx context.Context, options *OptionalPlainTimeClientGetDefaultOptions) (OptionalPlainTimeClientGetDefaultResponse, error) { + var err error + const operationName = "OptionalPlainTimeClient.GetDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getDefaultCreateRequest(ctx, options) + if err != nil { + return OptionalPlainTimeClientGetDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalPlainTimeClientGetDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalPlainTimeClientGetDefaultResponse{}, err + } + resp, err := client.getDefaultHandleResponse(httpResp) + return resp, err +} + +// getDefaultCreateRequest creates the GetDefault request. +func (client *OptionalPlainTimeClient) getDefaultCreateRequest(ctx context.Context, _ *OptionalPlainTimeClientGetDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/plainTime/default" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getDefaultHandleResponse handles the GetDefault response. +func (client *OptionalPlainTimeClient) getDefaultHandleResponse(resp *http.Response) (OptionalPlainTimeClientGetDefaultResponse, error) { + result := OptionalPlainTimeClientGetDefaultResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PlainTimeProperty); err != nil { + return OptionalPlainTimeClientGetDefaultResponse{}, err + } + return result, nil +} + +// PutAll - Put a body with all properties present. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalPlainTimeClientPutAllOptions contains the optional parameters for the OptionalPlainTimeClient.PutAll +// method. +func (client *OptionalPlainTimeClient) PutAll(ctx context.Context, body PlainTimeProperty, options *OptionalPlainTimeClientPutAllOptions) (OptionalPlainTimeClientPutAllResponse, error) { + var err error + const operationName = "OptionalPlainTimeClient.PutAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putAllCreateRequest(ctx, body, options) + if err != nil { + return OptionalPlainTimeClientPutAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalPlainTimeClientPutAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalPlainTimeClientPutAllResponse{}, err + } + return OptionalPlainTimeClientPutAllResponse{}, nil +} + +// putAllCreateRequest creates the PutAll request. +func (client *OptionalPlainTimeClient) putAllCreateRequest(ctx context.Context, body PlainTimeProperty, _ *OptionalPlainTimeClientPutAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/plainTime/all" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// PutDefault - Put a body with default properties. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalPlainTimeClientPutDefaultOptions contains the optional parameters for the OptionalPlainTimeClient.PutDefault +// method. +func (client *OptionalPlainTimeClient) PutDefault(ctx context.Context, body PlainTimeProperty, options *OptionalPlainTimeClientPutDefaultOptions) (OptionalPlainTimeClientPutDefaultResponse, error) { + var err error + const operationName = "OptionalPlainTimeClient.PutDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putDefaultCreateRequest(ctx, body, options) + if err != nil { + return OptionalPlainTimeClientPutDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalPlainTimeClientPutDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalPlainTimeClientPutDefaultResponse{}, err + } + return OptionalPlainTimeClientPutDefaultResponse{}, nil +} + +// putDefaultCreateRequest creates the PutDefault request. +func (client *OptionalPlainTimeClient) putDefaultCreateRequest(ctx context.Context, body PlainTimeProperty, _ *OptionalPlainTimeClientPutDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/plainTime/default" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/optionalitygroup/zz_optionalrequiredandoptional_client.go b/test/http-specs/type/property/optionalitygroup/zz_optionalrequiredandoptional_client.go new file mode 100644 index 000000000000..a1cdfcfd29ce --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/zz_optionalrequiredandoptional_client.go @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package optionalitygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// OptionalRequiredAndOptionalClient - Test optional and required properties +// Don't use this type directly, use [OptionalClient.NewOptionalRequiredAndOptionalClient] instead. +type OptionalRequiredAndOptionalClient struct { + internal *azcore.Client + endpoint string +} + +// GetAll - Get models that will return all properties in the model +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalRequiredAndOptionalClientGetAllOptions contains the optional parameters for the OptionalRequiredAndOptionalClient.GetAll +// method. +func (client *OptionalRequiredAndOptionalClient) GetAll(ctx context.Context, options *OptionalRequiredAndOptionalClientGetAllOptions) (OptionalRequiredAndOptionalClientGetAllResponse, error) { + var err error + const operationName = "OptionalRequiredAndOptionalClient.GetAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getAllCreateRequest(ctx, options) + if err != nil { + return OptionalRequiredAndOptionalClientGetAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalRequiredAndOptionalClientGetAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalRequiredAndOptionalClientGetAllResponse{}, err + } + resp, err := client.getAllHandleResponse(httpResp) + return resp, err +} + +// getAllCreateRequest creates the GetAll request. +func (client *OptionalRequiredAndOptionalClient) getAllCreateRequest(ctx context.Context, _ *OptionalRequiredAndOptionalClientGetAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/requiredAndOptional/all" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getAllHandleResponse handles the GetAll response. +func (client *OptionalRequiredAndOptionalClient) getAllHandleResponse(resp *http.Response) (OptionalRequiredAndOptionalClientGetAllResponse, error) { + result := OptionalRequiredAndOptionalClientGetAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RequiredAndOptionalProperty); err != nil { + return OptionalRequiredAndOptionalClientGetAllResponse{}, err + } + return result, nil +} + +// GetRequiredOnly - Get models that will return only the required properties +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalRequiredAndOptionalClientGetRequiredOnlyOptions contains the optional parameters for the OptionalRequiredAndOptionalClient.GetRequiredOnly +// method. +func (client *OptionalRequiredAndOptionalClient) GetRequiredOnly(ctx context.Context, options *OptionalRequiredAndOptionalClientGetRequiredOnlyOptions) (OptionalRequiredAndOptionalClientGetRequiredOnlyResponse, error) { + var err error + const operationName = "OptionalRequiredAndOptionalClient.GetRequiredOnly" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getRequiredOnlyCreateRequest(ctx, options) + if err != nil { + return OptionalRequiredAndOptionalClientGetRequiredOnlyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalRequiredAndOptionalClientGetRequiredOnlyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalRequiredAndOptionalClientGetRequiredOnlyResponse{}, err + } + resp, err := client.getRequiredOnlyHandleResponse(httpResp) + return resp, err +} + +// getRequiredOnlyCreateRequest creates the GetRequiredOnly request. +func (client *OptionalRequiredAndOptionalClient) getRequiredOnlyCreateRequest(ctx context.Context, _ *OptionalRequiredAndOptionalClientGetRequiredOnlyOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/requiredAndOptional/requiredOnly" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getRequiredOnlyHandleResponse handles the GetRequiredOnly response. +func (client *OptionalRequiredAndOptionalClient) getRequiredOnlyHandleResponse(resp *http.Response) (OptionalRequiredAndOptionalClientGetRequiredOnlyResponse, error) { + result := OptionalRequiredAndOptionalClientGetRequiredOnlyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RequiredAndOptionalProperty); err != nil { + return OptionalRequiredAndOptionalClientGetRequiredOnlyResponse{}, err + } + return result, nil +} + +// PutAll - Put a body with all properties present. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalRequiredAndOptionalClientPutAllOptions contains the optional parameters for the OptionalRequiredAndOptionalClient.PutAll +// method. +func (client *OptionalRequiredAndOptionalClient) PutAll(ctx context.Context, body RequiredAndOptionalProperty, options *OptionalRequiredAndOptionalClientPutAllOptions) (OptionalRequiredAndOptionalClientPutAllResponse, error) { + var err error + const operationName = "OptionalRequiredAndOptionalClient.PutAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putAllCreateRequest(ctx, body, options) + if err != nil { + return OptionalRequiredAndOptionalClientPutAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalRequiredAndOptionalClientPutAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalRequiredAndOptionalClientPutAllResponse{}, err + } + return OptionalRequiredAndOptionalClientPutAllResponse{}, nil +} + +// putAllCreateRequest creates the PutAll request. +func (client *OptionalRequiredAndOptionalClient) putAllCreateRequest(ctx context.Context, body RequiredAndOptionalProperty, _ *OptionalRequiredAndOptionalClientPutAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/requiredAndOptional/all" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// PutRequiredOnly - Put a body with only required properties. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalRequiredAndOptionalClientPutRequiredOnlyOptions contains the optional parameters for the OptionalRequiredAndOptionalClient.PutRequiredOnly +// method. +func (client *OptionalRequiredAndOptionalClient) PutRequiredOnly(ctx context.Context, body RequiredAndOptionalProperty, options *OptionalRequiredAndOptionalClientPutRequiredOnlyOptions) (OptionalRequiredAndOptionalClientPutRequiredOnlyResponse, error) { + var err error + const operationName = "OptionalRequiredAndOptionalClient.PutRequiredOnly" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putRequiredOnlyCreateRequest(ctx, body, options) + if err != nil { + return OptionalRequiredAndOptionalClientPutRequiredOnlyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalRequiredAndOptionalClientPutRequiredOnlyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalRequiredAndOptionalClientPutRequiredOnlyResponse{}, err + } + return OptionalRequiredAndOptionalClientPutRequiredOnlyResponse{}, nil +} + +// putRequiredOnlyCreateRequest creates the PutRequiredOnly request. +func (client *OptionalRequiredAndOptionalClient) putRequiredOnlyCreateRequest(ctx context.Context, body RequiredAndOptionalProperty, _ *OptionalRequiredAndOptionalClientPutRequiredOnlyOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/requiredAndOptional/requiredOnly" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/optionalitygroup/zz_optionalstring_client.go b/test/http-specs/type/property/optionalitygroup/zz_optionalstring_client.go new file mode 100644 index 000000000000..d28383042792 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/zz_optionalstring_client.go @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package optionalitygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// OptionalStringClient contains the methods for the OptionalString group. +// Don't use this type directly, use [OptionalClient.NewOptionalStringClient] instead. +type OptionalStringClient struct { + internal *azcore.Client + endpoint string +} + +// GetAll - Get models that will return all properties in the model +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalStringClientGetAllOptions contains the optional parameters for the OptionalStringClient.GetAll method. +func (client *OptionalStringClient) GetAll(ctx context.Context, options *OptionalStringClientGetAllOptions) (OptionalStringClientGetAllResponse, error) { + var err error + const operationName = "OptionalStringClient.GetAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getAllCreateRequest(ctx, options) + if err != nil { + return OptionalStringClientGetAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalStringClientGetAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalStringClientGetAllResponse{}, err + } + resp, err := client.getAllHandleResponse(httpResp) + return resp, err +} + +// getAllCreateRequest creates the GetAll request. +func (client *OptionalStringClient) getAllCreateRequest(ctx context.Context, _ *OptionalStringClientGetAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/string/all" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getAllHandleResponse handles the GetAll response. +func (client *OptionalStringClient) getAllHandleResponse(resp *http.Response) (OptionalStringClientGetAllResponse, error) { + result := OptionalStringClientGetAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.StringProperty); err != nil { + return OptionalStringClientGetAllResponse{}, err + } + return result, nil +} + +// GetDefault - Get models that will return the default object +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalStringClientGetDefaultOptions contains the optional parameters for the OptionalStringClient.GetDefault +// method. +func (client *OptionalStringClient) GetDefault(ctx context.Context, options *OptionalStringClientGetDefaultOptions) (OptionalStringClientGetDefaultResponse, error) { + var err error + const operationName = "OptionalStringClient.GetDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getDefaultCreateRequest(ctx, options) + if err != nil { + return OptionalStringClientGetDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalStringClientGetDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalStringClientGetDefaultResponse{}, err + } + resp, err := client.getDefaultHandleResponse(httpResp) + return resp, err +} + +// getDefaultCreateRequest creates the GetDefault request. +func (client *OptionalStringClient) getDefaultCreateRequest(ctx context.Context, _ *OptionalStringClientGetDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/string/default" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getDefaultHandleResponse handles the GetDefault response. +func (client *OptionalStringClient) getDefaultHandleResponse(resp *http.Response) (OptionalStringClientGetDefaultResponse, error) { + result := OptionalStringClientGetDefaultResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.StringProperty); err != nil { + return OptionalStringClientGetDefaultResponse{}, err + } + return result, nil +} + +// PutAll - Put a body with all properties present. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalStringClientPutAllOptions contains the optional parameters for the OptionalStringClient.PutAll method. +func (client *OptionalStringClient) PutAll(ctx context.Context, body StringProperty, options *OptionalStringClientPutAllOptions) (OptionalStringClientPutAllResponse, error) { + var err error + const operationName = "OptionalStringClient.PutAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putAllCreateRequest(ctx, body, options) + if err != nil { + return OptionalStringClientPutAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalStringClientPutAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalStringClientPutAllResponse{}, err + } + return OptionalStringClientPutAllResponse{}, nil +} + +// putAllCreateRequest creates the PutAll request. +func (client *OptionalStringClient) putAllCreateRequest(ctx context.Context, body StringProperty, _ *OptionalStringClientPutAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/string/all" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// PutDefault - Put a body with default properties. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalStringClientPutDefaultOptions contains the optional parameters for the OptionalStringClient.PutDefault +// method. +func (client *OptionalStringClient) PutDefault(ctx context.Context, body StringProperty, options *OptionalStringClientPutDefaultOptions) (OptionalStringClientPutDefaultResponse, error) { + var err error + const operationName = "OptionalStringClient.PutDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putDefaultCreateRequest(ctx, body, options) + if err != nil { + return OptionalStringClientPutDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalStringClientPutDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalStringClientPutDefaultResponse{}, err + } + return OptionalStringClientPutDefaultResponse{}, nil +} + +// putDefaultCreateRequest creates the PutDefault request. +func (client *OptionalStringClient) putDefaultCreateRequest(ctx context.Context, body StringProperty, _ *OptionalStringClientPutDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/string/default" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/optionalitygroup/zz_optionalstringliteral_client.go b/test/http-specs/type/property/optionalitygroup/zz_optionalstringliteral_client.go new file mode 100644 index 000000000000..6d1dcd781933 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/zz_optionalstringliteral_client.go @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package optionalitygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// OptionalStringLiteralClient contains the methods for the OptionalStringLiteral group. +// Don't use this type directly, use [OptionalClient.NewOptionalStringLiteralClient] instead. +type OptionalStringLiteralClient struct { + internal *azcore.Client + endpoint string +} + +// GetAll - Get models that will return all properties in the model +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalStringLiteralClientGetAllOptions contains the optional parameters for the OptionalStringLiteralClient.GetAll +// method. +func (client *OptionalStringLiteralClient) GetAll(ctx context.Context, options *OptionalStringLiteralClientGetAllOptions) (OptionalStringLiteralClientGetAllResponse, error) { + var err error + const operationName = "OptionalStringLiteralClient.GetAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getAllCreateRequest(ctx, options) + if err != nil { + return OptionalStringLiteralClientGetAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalStringLiteralClientGetAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalStringLiteralClientGetAllResponse{}, err + } + resp, err := client.getAllHandleResponse(httpResp) + return resp, err +} + +// getAllCreateRequest creates the GetAll request. +func (client *OptionalStringLiteralClient) getAllCreateRequest(ctx context.Context, _ *OptionalStringLiteralClientGetAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/string/literal/all" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getAllHandleResponse handles the GetAll response. +func (client *OptionalStringLiteralClient) getAllHandleResponse(resp *http.Response) (OptionalStringLiteralClientGetAllResponse, error) { + result := OptionalStringLiteralClientGetAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.StringLiteralProperty); err != nil { + return OptionalStringLiteralClientGetAllResponse{}, err + } + return result, nil +} + +// GetDefault - Get models that will return the default object +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalStringLiteralClientGetDefaultOptions contains the optional parameters for the OptionalStringLiteralClient.GetDefault +// method. +func (client *OptionalStringLiteralClient) GetDefault(ctx context.Context, options *OptionalStringLiteralClientGetDefaultOptions) (OptionalStringLiteralClientGetDefaultResponse, error) { + var err error + const operationName = "OptionalStringLiteralClient.GetDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getDefaultCreateRequest(ctx, options) + if err != nil { + return OptionalStringLiteralClientGetDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalStringLiteralClientGetDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalStringLiteralClientGetDefaultResponse{}, err + } + resp, err := client.getDefaultHandleResponse(httpResp) + return resp, err +} + +// getDefaultCreateRequest creates the GetDefault request. +func (client *OptionalStringLiteralClient) getDefaultCreateRequest(ctx context.Context, _ *OptionalStringLiteralClientGetDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/string/literal/default" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getDefaultHandleResponse handles the GetDefault response. +func (client *OptionalStringLiteralClient) getDefaultHandleResponse(resp *http.Response) (OptionalStringLiteralClientGetDefaultResponse, error) { + result := OptionalStringLiteralClientGetDefaultResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.StringLiteralProperty); err != nil { + return OptionalStringLiteralClientGetDefaultResponse{}, err + } + return result, nil +} + +// PutAll - Put a body with all properties present. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalStringLiteralClientPutAllOptions contains the optional parameters for the OptionalStringLiteralClient.PutAll +// method. +func (client *OptionalStringLiteralClient) PutAll(ctx context.Context, body StringLiteralProperty, options *OptionalStringLiteralClientPutAllOptions) (OptionalStringLiteralClientPutAllResponse, error) { + var err error + const operationName = "OptionalStringLiteralClient.PutAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putAllCreateRequest(ctx, body, options) + if err != nil { + return OptionalStringLiteralClientPutAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalStringLiteralClientPutAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalStringLiteralClientPutAllResponse{}, err + } + return OptionalStringLiteralClientPutAllResponse{}, nil +} + +// putAllCreateRequest creates the PutAll request. +func (client *OptionalStringLiteralClient) putAllCreateRequest(ctx context.Context, body StringLiteralProperty, _ *OptionalStringLiteralClientPutAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/string/literal/all" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// PutDefault - Put a body with default properties. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalStringLiteralClientPutDefaultOptions contains the optional parameters for the OptionalStringLiteralClient.PutDefault +// method. +func (client *OptionalStringLiteralClient) PutDefault(ctx context.Context, body StringLiteralProperty, options *OptionalStringLiteralClientPutDefaultOptions) (OptionalStringLiteralClientPutDefaultResponse, error) { + var err error + const operationName = "OptionalStringLiteralClient.PutDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putDefaultCreateRequest(ctx, body, options) + if err != nil { + return OptionalStringLiteralClientPutDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalStringLiteralClientPutDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalStringLiteralClientPutDefaultResponse{}, err + } + return OptionalStringLiteralClientPutDefaultResponse{}, nil +} + +// putDefaultCreateRequest creates the PutDefault request. +func (client *OptionalStringLiteralClient) putDefaultCreateRequest(ctx context.Context, body StringLiteralProperty, _ *OptionalStringLiteralClientPutDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/string/literal/default" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/optionalitygroup/zz_optionalunionfloatliteral_client.go b/test/http-specs/type/property/optionalitygroup/zz_optionalunionfloatliteral_client.go new file mode 100644 index 000000000000..1a4262e34fa9 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/zz_optionalunionfloatliteral_client.go @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package optionalitygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// OptionalUnionFloatLiteralClient contains the methods for the OptionalUnionFloatLiteral group. +// Don't use this type directly, use [OptionalClient.NewOptionalUnionFloatLiteralClient] instead. +type OptionalUnionFloatLiteralClient struct { + internal *azcore.Client + endpoint string +} + +// GetAll - Get models that will return all properties in the model +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalUnionFloatLiteralClientGetAllOptions contains the optional parameters for the OptionalUnionFloatLiteralClient.GetAll +// method. +func (client *OptionalUnionFloatLiteralClient) GetAll(ctx context.Context, options *OptionalUnionFloatLiteralClientGetAllOptions) (OptionalUnionFloatLiteralClientGetAllResponse, error) { + var err error + const operationName = "OptionalUnionFloatLiteralClient.GetAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getAllCreateRequest(ctx, options) + if err != nil { + return OptionalUnionFloatLiteralClientGetAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalUnionFloatLiteralClientGetAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalUnionFloatLiteralClientGetAllResponse{}, err + } + resp, err := client.getAllHandleResponse(httpResp) + return resp, err +} + +// getAllCreateRequest creates the GetAll request. +func (client *OptionalUnionFloatLiteralClient) getAllCreateRequest(ctx context.Context, _ *OptionalUnionFloatLiteralClientGetAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/union/float/literal/all" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getAllHandleResponse handles the GetAll response. +func (client *OptionalUnionFloatLiteralClient) getAllHandleResponse(resp *http.Response) (OptionalUnionFloatLiteralClientGetAllResponse, error) { + result := OptionalUnionFloatLiteralClientGetAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.UnionFloatLiteralProperty); err != nil { + return OptionalUnionFloatLiteralClientGetAllResponse{}, err + } + return result, nil +} + +// GetDefault - Get models that will return the default object +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalUnionFloatLiteralClientGetDefaultOptions contains the optional parameters for the OptionalUnionFloatLiteralClient.GetDefault +// method. +func (client *OptionalUnionFloatLiteralClient) GetDefault(ctx context.Context, options *OptionalUnionFloatLiteralClientGetDefaultOptions) (OptionalUnionFloatLiteralClientGetDefaultResponse, error) { + var err error + const operationName = "OptionalUnionFloatLiteralClient.GetDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getDefaultCreateRequest(ctx, options) + if err != nil { + return OptionalUnionFloatLiteralClientGetDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalUnionFloatLiteralClientGetDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalUnionFloatLiteralClientGetDefaultResponse{}, err + } + resp, err := client.getDefaultHandleResponse(httpResp) + return resp, err +} + +// getDefaultCreateRequest creates the GetDefault request. +func (client *OptionalUnionFloatLiteralClient) getDefaultCreateRequest(ctx context.Context, _ *OptionalUnionFloatLiteralClientGetDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/union/float/literal/default" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getDefaultHandleResponse handles the GetDefault response. +func (client *OptionalUnionFloatLiteralClient) getDefaultHandleResponse(resp *http.Response) (OptionalUnionFloatLiteralClientGetDefaultResponse, error) { + result := OptionalUnionFloatLiteralClientGetDefaultResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.UnionFloatLiteralProperty); err != nil { + return OptionalUnionFloatLiteralClientGetDefaultResponse{}, err + } + return result, nil +} + +// PutAll - Put a body with all properties present. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalUnionFloatLiteralClientPutAllOptions contains the optional parameters for the OptionalUnionFloatLiteralClient.PutAll +// method. +func (client *OptionalUnionFloatLiteralClient) PutAll(ctx context.Context, body UnionFloatLiteralProperty, options *OptionalUnionFloatLiteralClientPutAllOptions) (OptionalUnionFloatLiteralClientPutAllResponse, error) { + var err error + const operationName = "OptionalUnionFloatLiteralClient.PutAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putAllCreateRequest(ctx, body, options) + if err != nil { + return OptionalUnionFloatLiteralClientPutAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalUnionFloatLiteralClientPutAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalUnionFloatLiteralClientPutAllResponse{}, err + } + return OptionalUnionFloatLiteralClientPutAllResponse{}, nil +} + +// putAllCreateRequest creates the PutAll request. +func (client *OptionalUnionFloatLiteralClient) putAllCreateRequest(ctx context.Context, body UnionFloatLiteralProperty, _ *OptionalUnionFloatLiteralClientPutAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/union/float/literal/all" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// PutDefault - Put a body with default properties. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalUnionFloatLiteralClientPutDefaultOptions contains the optional parameters for the OptionalUnionFloatLiteralClient.PutDefault +// method. +func (client *OptionalUnionFloatLiteralClient) PutDefault(ctx context.Context, body UnionFloatLiteralProperty, options *OptionalUnionFloatLiteralClientPutDefaultOptions) (OptionalUnionFloatLiteralClientPutDefaultResponse, error) { + var err error + const operationName = "OptionalUnionFloatLiteralClient.PutDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putDefaultCreateRequest(ctx, body, options) + if err != nil { + return OptionalUnionFloatLiteralClientPutDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalUnionFloatLiteralClientPutDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalUnionFloatLiteralClientPutDefaultResponse{}, err + } + return OptionalUnionFloatLiteralClientPutDefaultResponse{}, nil +} + +// putDefaultCreateRequest creates the PutDefault request. +func (client *OptionalUnionFloatLiteralClient) putDefaultCreateRequest(ctx context.Context, body UnionFloatLiteralProperty, _ *OptionalUnionFloatLiteralClientPutDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/union/float/literal/default" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/optionalitygroup/zz_optionalunionintliteral_client.go b/test/http-specs/type/property/optionalitygroup/zz_optionalunionintliteral_client.go new file mode 100644 index 000000000000..5c144be4bb80 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/zz_optionalunionintliteral_client.go @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package optionalitygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// OptionalUnionIntLiteralClient contains the methods for the OptionalUnionIntLiteral group. +// Don't use this type directly, use [OptionalClient.NewOptionalUnionIntLiteralClient] instead. +type OptionalUnionIntLiteralClient struct { + internal *azcore.Client + endpoint string +} + +// GetAll - Get models that will return all properties in the model +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalUnionIntLiteralClientGetAllOptions contains the optional parameters for the OptionalUnionIntLiteralClient.GetAll +// method. +func (client *OptionalUnionIntLiteralClient) GetAll(ctx context.Context, options *OptionalUnionIntLiteralClientGetAllOptions) (OptionalUnionIntLiteralClientGetAllResponse, error) { + var err error + const operationName = "OptionalUnionIntLiteralClient.GetAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getAllCreateRequest(ctx, options) + if err != nil { + return OptionalUnionIntLiteralClientGetAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalUnionIntLiteralClientGetAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalUnionIntLiteralClientGetAllResponse{}, err + } + resp, err := client.getAllHandleResponse(httpResp) + return resp, err +} + +// getAllCreateRequest creates the GetAll request. +func (client *OptionalUnionIntLiteralClient) getAllCreateRequest(ctx context.Context, _ *OptionalUnionIntLiteralClientGetAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/union/int/literal/all" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getAllHandleResponse handles the GetAll response. +func (client *OptionalUnionIntLiteralClient) getAllHandleResponse(resp *http.Response) (OptionalUnionIntLiteralClientGetAllResponse, error) { + result := OptionalUnionIntLiteralClientGetAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.UnionIntLiteralProperty); err != nil { + return OptionalUnionIntLiteralClientGetAllResponse{}, err + } + return result, nil +} + +// GetDefault - Get models that will return the default object +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalUnionIntLiteralClientGetDefaultOptions contains the optional parameters for the OptionalUnionIntLiteralClient.GetDefault +// method. +func (client *OptionalUnionIntLiteralClient) GetDefault(ctx context.Context, options *OptionalUnionIntLiteralClientGetDefaultOptions) (OptionalUnionIntLiteralClientGetDefaultResponse, error) { + var err error + const operationName = "OptionalUnionIntLiteralClient.GetDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getDefaultCreateRequest(ctx, options) + if err != nil { + return OptionalUnionIntLiteralClientGetDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalUnionIntLiteralClientGetDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalUnionIntLiteralClientGetDefaultResponse{}, err + } + resp, err := client.getDefaultHandleResponse(httpResp) + return resp, err +} + +// getDefaultCreateRequest creates the GetDefault request. +func (client *OptionalUnionIntLiteralClient) getDefaultCreateRequest(ctx context.Context, _ *OptionalUnionIntLiteralClientGetDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/union/int/literal/default" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getDefaultHandleResponse handles the GetDefault response. +func (client *OptionalUnionIntLiteralClient) getDefaultHandleResponse(resp *http.Response) (OptionalUnionIntLiteralClientGetDefaultResponse, error) { + result := OptionalUnionIntLiteralClientGetDefaultResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.UnionIntLiteralProperty); err != nil { + return OptionalUnionIntLiteralClientGetDefaultResponse{}, err + } + return result, nil +} + +// PutAll - Put a body with all properties present. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalUnionIntLiteralClientPutAllOptions contains the optional parameters for the OptionalUnionIntLiteralClient.PutAll +// method. +func (client *OptionalUnionIntLiteralClient) PutAll(ctx context.Context, body UnionIntLiteralProperty, options *OptionalUnionIntLiteralClientPutAllOptions) (OptionalUnionIntLiteralClientPutAllResponse, error) { + var err error + const operationName = "OptionalUnionIntLiteralClient.PutAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putAllCreateRequest(ctx, body, options) + if err != nil { + return OptionalUnionIntLiteralClientPutAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalUnionIntLiteralClientPutAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalUnionIntLiteralClientPutAllResponse{}, err + } + return OptionalUnionIntLiteralClientPutAllResponse{}, nil +} + +// putAllCreateRequest creates the PutAll request. +func (client *OptionalUnionIntLiteralClient) putAllCreateRequest(ctx context.Context, body UnionIntLiteralProperty, _ *OptionalUnionIntLiteralClientPutAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/union/int/literal/all" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// PutDefault - Put a body with default properties. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalUnionIntLiteralClientPutDefaultOptions contains the optional parameters for the OptionalUnionIntLiteralClient.PutDefault +// method. +func (client *OptionalUnionIntLiteralClient) PutDefault(ctx context.Context, body UnionIntLiteralProperty, options *OptionalUnionIntLiteralClientPutDefaultOptions) (OptionalUnionIntLiteralClientPutDefaultResponse, error) { + var err error + const operationName = "OptionalUnionIntLiteralClient.PutDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putDefaultCreateRequest(ctx, body, options) + if err != nil { + return OptionalUnionIntLiteralClientPutDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalUnionIntLiteralClientPutDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalUnionIntLiteralClientPutDefaultResponse{}, err + } + return OptionalUnionIntLiteralClientPutDefaultResponse{}, nil +} + +// putDefaultCreateRequest creates the PutDefault request. +func (client *OptionalUnionIntLiteralClient) putDefaultCreateRequest(ctx context.Context, body UnionIntLiteralProperty, _ *OptionalUnionIntLiteralClientPutDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/union/int/literal/default" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/optionalitygroup/zz_optionalunionstringliteral_client.go b/test/http-specs/type/property/optionalitygroup/zz_optionalunionstringliteral_client.go new file mode 100644 index 000000000000..eac9f12513df --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/zz_optionalunionstringliteral_client.go @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package optionalitygroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// OptionalUnionStringLiteralClient contains the methods for the OptionalUnionStringLiteral group. +// Don't use this type directly, use [OptionalClient.NewOptionalUnionStringLiteralClient] instead. +type OptionalUnionStringLiteralClient struct { + internal *azcore.Client + endpoint string +} + +// GetAll - Get models that will return all properties in the model +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalUnionStringLiteralClientGetAllOptions contains the optional parameters for the OptionalUnionStringLiteralClient.GetAll +// method. +func (client *OptionalUnionStringLiteralClient) GetAll(ctx context.Context, options *OptionalUnionStringLiteralClientGetAllOptions) (OptionalUnionStringLiteralClientGetAllResponse, error) { + var err error + const operationName = "OptionalUnionStringLiteralClient.GetAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getAllCreateRequest(ctx, options) + if err != nil { + return OptionalUnionStringLiteralClientGetAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalUnionStringLiteralClientGetAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalUnionStringLiteralClientGetAllResponse{}, err + } + resp, err := client.getAllHandleResponse(httpResp) + return resp, err +} + +// getAllCreateRequest creates the GetAll request. +func (client *OptionalUnionStringLiteralClient) getAllCreateRequest(ctx context.Context, _ *OptionalUnionStringLiteralClientGetAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/union/string/literal/all" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getAllHandleResponse handles the GetAll response. +func (client *OptionalUnionStringLiteralClient) getAllHandleResponse(resp *http.Response) (OptionalUnionStringLiteralClientGetAllResponse, error) { + result := OptionalUnionStringLiteralClientGetAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.UnionStringLiteralProperty); err != nil { + return OptionalUnionStringLiteralClientGetAllResponse{}, err + } + return result, nil +} + +// GetDefault - Get models that will return the default object +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalUnionStringLiteralClientGetDefaultOptions contains the optional parameters for the OptionalUnionStringLiteralClient.GetDefault +// method. +func (client *OptionalUnionStringLiteralClient) GetDefault(ctx context.Context, options *OptionalUnionStringLiteralClientGetDefaultOptions) (OptionalUnionStringLiteralClientGetDefaultResponse, error) { + var err error + const operationName = "OptionalUnionStringLiteralClient.GetDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getDefaultCreateRequest(ctx, options) + if err != nil { + return OptionalUnionStringLiteralClientGetDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalUnionStringLiteralClientGetDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OptionalUnionStringLiteralClientGetDefaultResponse{}, err + } + resp, err := client.getDefaultHandleResponse(httpResp) + return resp, err +} + +// getDefaultCreateRequest creates the GetDefault request. +func (client *OptionalUnionStringLiteralClient) getDefaultCreateRequest(ctx context.Context, _ *OptionalUnionStringLiteralClientGetDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/union/string/literal/default" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getDefaultHandleResponse handles the GetDefault response. +func (client *OptionalUnionStringLiteralClient) getDefaultHandleResponse(resp *http.Response) (OptionalUnionStringLiteralClientGetDefaultResponse, error) { + result := OptionalUnionStringLiteralClientGetDefaultResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.UnionStringLiteralProperty); err != nil { + return OptionalUnionStringLiteralClientGetDefaultResponse{}, err + } + return result, nil +} + +// PutAll - Put a body with all properties present. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalUnionStringLiteralClientPutAllOptions contains the optional parameters for the OptionalUnionStringLiteralClient.PutAll +// method. +func (client *OptionalUnionStringLiteralClient) PutAll(ctx context.Context, body UnionStringLiteralProperty, options *OptionalUnionStringLiteralClientPutAllOptions) (OptionalUnionStringLiteralClientPutAllResponse, error) { + var err error + const operationName = "OptionalUnionStringLiteralClient.PutAll" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putAllCreateRequest(ctx, body, options) + if err != nil { + return OptionalUnionStringLiteralClientPutAllResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalUnionStringLiteralClientPutAllResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalUnionStringLiteralClientPutAllResponse{}, err + } + return OptionalUnionStringLiteralClientPutAllResponse{}, nil +} + +// putAllCreateRequest creates the PutAll request. +func (client *OptionalUnionStringLiteralClient) putAllCreateRequest(ctx context.Context, body UnionStringLiteralProperty, _ *OptionalUnionStringLiteralClientPutAllOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/union/string/literal/all" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// PutDefault - Put a body with default properties. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OptionalUnionStringLiteralClientPutDefaultOptions contains the optional parameters for the OptionalUnionStringLiteralClient.PutDefault +// method. +func (client *OptionalUnionStringLiteralClient) PutDefault(ctx context.Context, body UnionStringLiteralProperty, options *OptionalUnionStringLiteralClientPutDefaultOptions) (OptionalUnionStringLiteralClientPutDefaultResponse, error) { + var err error + const operationName = "OptionalUnionStringLiteralClient.PutDefault" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putDefaultCreateRequest(ctx, body, options) + if err != nil { + return OptionalUnionStringLiteralClientPutDefaultResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OptionalUnionStringLiteralClientPutDefaultResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return OptionalUnionStringLiteralClientPutDefaultResponse{}, err + } + return OptionalUnionStringLiteralClientPutDefaultResponse{}, nil +} + +// putDefaultCreateRequest creates the PutDefault request. +func (client *OptionalUnionStringLiteralClient) putDefaultCreateRequest(ctx context.Context, body UnionStringLiteralProperty, _ *OptionalUnionStringLiteralClientPutDefaultOptions) (*policy.Request, error) { + urlPath := "/type/property/optional/union/string/literal/default" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/optionalitygroup/zz_options.go b/test/http-specs/type/property/optionalitygroup/zz_options.go new file mode 100644 index 000000000000..0585679f481f --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/zz_options.go @@ -0,0 +1,359 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package optionalitygroup + +// OptionalBooleanLiteralClientGetAllOptions contains the optional parameters for the OptionalBooleanLiteralClient.GetAll +// method. +type OptionalBooleanLiteralClientGetAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalBooleanLiteralClientGetDefaultOptions contains the optional parameters for the OptionalBooleanLiteralClient.GetDefault +// method. +type OptionalBooleanLiteralClientGetDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalBooleanLiteralClientPutAllOptions contains the optional parameters for the OptionalBooleanLiteralClient.PutAll +// method. +type OptionalBooleanLiteralClientPutAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalBooleanLiteralClientPutDefaultOptions contains the optional parameters for the OptionalBooleanLiteralClient.PutDefault +// method. +type OptionalBooleanLiteralClientPutDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalBytesClientGetAllOptions contains the optional parameters for the OptionalBytesClient.GetAll method. +type OptionalBytesClientGetAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalBytesClientGetDefaultOptions contains the optional parameters for the OptionalBytesClient.GetDefault method. +type OptionalBytesClientGetDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalBytesClientPutAllOptions contains the optional parameters for the OptionalBytesClient.PutAll method. +type OptionalBytesClientPutAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalBytesClientPutDefaultOptions contains the optional parameters for the OptionalBytesClient.PutDefault method. +type OptionalBytesClientPutDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalCollectionsByteClientGetAllOptions contains the optional parameters for the OptionalCollectionsByteClient.GetAll +// method. +type OptionalCollectionsByteClientGetAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalCollectionsByteClientGetDefaultOptions contains the optional parameters for the OptionalCollectionsByteClient.GetDefault +// method. +type OptionalCollectionsByteClientGetDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalCollectionsByteClientPutAllOptions contains the optional parameters for the OptionalCollectionsByteClient.PutAll +// method. +type OptionalCollectionsByteClientPutAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalCollectionsByteClientPutDefaultOptions contains the optional parameters for the OptionalCollectionsByteClient.PutDefault +// method. +type OptionalCollectionsByteClientPutDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalCollectionsModelClientGetAllOptions contains the optional parameters for the OptionalCollectionsModelClient.GetAll +// method. +type OptionalCollectionsModelClientGetAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalCollectionsModelClientGetDefaultOptions contains the optional parameters for the OptionalCollectionsModelClient.GetDefault +// method. +type OptionalCollectionsModelClientGetDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalCollectionsModelClientPutAllOptions contains the optional parameters for the OptionalCollectionsModelClient.PutAll +// method. +type OptionalCollectionsModelClientPutAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalCollectionsModelClientPutDefaultOptions contains the optional parameters for the OptionalCollectionsModelClient.PutDefault +// method. +type OptionalCollectionsModelClientPutDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalDatetimeClientGetAllOptions contains the optional parameters for the OptionalDatetimeClient.GetAll method. +type OptionalDatetimeClientGetAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalDatetimeClientGetDefaultOptions contains the optional parameters for the OptionalDatetimeClient.GetDefault method. +type OptionalDatetimeClientGetDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalDatetimeClientPutAllOptions contains the optional parameters for the OptionalDatetimeClient.PutAll method. +type OptionalDatetimeClientPutAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalDatetimeClientPutDefaultOptions contains the optional parameters for the OptionalDatetimeClient.PutDefault method. +type OptionalDatetimeClientPutDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalDurationClientGetAllOptions contains the optional parameters for the OptionalDurationClient.GetAll method. +type OptionalDurationClientGetAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalDurationClientGetDefaultOptions contains the optional parameters for the OptionalDurationClient.GetDefault method. +type OptionalDurationClientGetDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalDurationClientPutAllOptions contains the optional parameters for the OptionalDurationClient.PutAll method. +type OptionalDurationClientPutAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalDurationClientPutDefaultOptions contains the optional parameters for the OptionalDurationClient.PutDefault method. +type OptionalDurationClientPutDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalFloatLiteralClientGetAllOptions contains the optional parameters for the OptionalFloatLiteralClient.GetAll method. +type OptionalFloatLiteralClientGetAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalFloatLiteralClientGetDefaultOptions contains the optional parameters for the OptionalFloatLiteralClient.GetDefault +// method. +type OptionalFloatLiteralClientGetDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalFloatLiteralClientPutAllOptions contains the optional parameters for the OptionalFloatLiteralClient.PutAll method. +type OptionalFloatLiteralClientPutAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalFloatLiteralClientPutDefaultOptions contains the optional parameters for the OptionalFloatLiteralClient.PutDefault +// method. +type OptionalFloatLiteralClientPutDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalIntLiteralClientGetAllOptions contains the optional parameters for the OptionalIntLiteralClient.GetAll method. +type OptionalIntLiteralClientGetAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalIntLiteralClientGetDefaultOptions contains the optional parameters for the OptionalIntLiteralClient.GetDefault +// method. +type OptionalIntLiteralClientGetDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalIntLiteralClientPutAllOptions contains the optional parameters for the OptionalIntLiteralClient.PutAll method. +type OptionalIntLiteralClientPutAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalIntLiteralClientPutDefaultOptions contains the optional parameters for the OptionalIntLiteralClient.PutDefault +// method. +type OptionalIntLiteralClientPutDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalPlainDateClientGetAllOptions contains the optional parameters for the OptionalPlainDateClient.GetAll method. +type OptionalPlainDateClientGetAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalPlainDateClientGetDefaultOptions contains the optional parameters for the OptionalPlainDateClient.GetDefault method. +type OptionalPlainDateClientGetDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalPlainDateClientPutAllOptions contains the optional parameters for the OptionalPlainDateClient.PutAll method. +type OptionalPlainDateClientPutAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalPlainDateClientPutDefaultOptions contains the optional parameters for the OptionalPlainDateClient.PutDefault method. +type OptionalPlainDateClientPutDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalPlainTimeClientGetAllOptions contains the optional parameters for the OptionalPlainTimeClient.GetAll method. +type OptionalPlainTimeClientGetAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalPlainTimeClientGetDefaultOptions contains the optional parameters for the OptionalPlainTimeClient.GetDefault method. +type OptionalPlainTimeClientGetDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalPlainTimeClientPutAllOptions contains the optional parameters for the OptionalPlainTimeClient.PutAll method. +type OptionalPlainTimeClientPutAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalPlainTimeClientPutDefaultOptions contains the optional parameters for the OptionalPlainTimeClient.PutDefault method. +type OptionalPlainTimeClientPutDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalRequiredAndOptionalClientGetAllOptions contains the optional parameters for the OptionalRequiredAndOptionalClient.GetAll +// method. +type OptionalRequiredAndOptionalClientGetAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalRequiredAndOptionalClientGetRequiredOnlyOptions contains the optional parameters for the OptionalRequiredAndOptionalClient.GetRequiredOnly +// method. +type OptionalRequiredAndOptionalClientGetRequiredOnlyOptions struct { + // placeholder for future optional parameters +} + +// OptionalRequiredAndOptionalClientPutAllOptions contains the optional parameters for the OptionalRequiredAndOptionalClient.PutAll +// method. +type OptionalRequiredAndOptionalClientPutAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalRequiredAndOptionalClientPutRequiredOnlyOptions contains the optional parameters for the OptionalRequiredAndOptionalClient.PutRequiredOnly +// method. +type OptionalRequiredAndOptionalClientPutRequiredOnlyOptions struct { + // placeholder for future optional parameters +} + +// OptionalStringClientGetAllOptions contains the optional parameters for the OptionalStringClient.GetAll method. +type OptionalStringClientGetAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalStringClientGetDefaultOptions contains the optional parameters for the OptionalStringClient.GetDefault method. +type OptionalStringClientGetDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalStringClientPutAllOptions contains the optional parameters for the OptionalStringClient.PutAll method. +type OptionalStringClientPutAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalStringClientPutDefaultOptions contains the optional parameters for the OptionalStringClient.PutDefault method. +type OptionalStringClientPutDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalStringLiteralClientGetAllOptions contains the optional parameters for the OptionalStringLiteralClient.GetAll method. +type OptionalStringLiteralClientGetAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalStringLiteralClientGetDefaultOptions contains the optional parameters for the OptionalStringLiteralClient.GetDefault +// method. +type OptionalStringLiteralClientGetDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalStringLiteralClientPutAllOptions contains the optional parameters for the OptionalStringLiteralClient.PutAll method. +type OptionalStringLiteralClientPutAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalStringLiteralClientPutDefaultOptions contains the optional parameters for the OptionalStringLiteralClient.PutDefault +// method. +type OptionalStringLiteralClientPutDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalUnionFloatLiteralClientGetAllOptions contains the optional parameters for the OptionalUnionFloatLiteralClient.GetAll +// method. +type OptionalUnionFloatLiteralClientGetAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalUnionFloatLiteralClientGetDefaultOptions contains the optional parameters for the OptionalUnionFloatLiteralClient.GetDefault +// method. +type OptionalUnionFloatLiteralClientGetDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalUnionFloatLiteralClientPutAllOptions contains the optional parameters for the OptionalUnionFloatLiteralClient.PutAll +// method. +type OptionalUnionFloatLiteralClientPutAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalUnionFloatLiteralClientPutDefaultOptions contains the optional parameters for the OptionalUnionFloatLiteralClient.PutDefault +// method. +type OptionalUnionFloatLiteralClientPutDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalUnionIntLiteralClientGetAllOptions contains the optional parameters for the OptionalUnionIntLiteralClient.GetAll +// method. +type OptionalUnionIntLiteralClientGetAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalUnionIntLiteralClientGetDefaultOptions contains the optional parameters for the OptionalUnionIntLiteralClient.GetDefault +// method. +type OptionalUnionIntLiteralClientGetDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalUnionIntLiteralClientPutAllOptions contains the optional parameters for the OptionalUnionIntLiteralClient.PutAll +// method. +type OptionalUnionIntLiteralClientPutAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalUnionIntLiteralClientPutDefaultOptions contains the optional parameters for the OptionalUnionIntLiteralClient.PutDefault +// method. +type OptionalUnionIntLiteralClientPutDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalUnionStringLiteralClientGetAllOptions contains the optional parameters for the OptionalUnionStringLiteralClient.GetAll +// method. +type OptionalUnionStringLiteralClientGetAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalUnionStringLiteralClientGetDefaultOptions contains the optional parameters for the OptionalUnionStringLiteralClient.GetDefault +// method. +type OptionalUnionStringLiteralClientGetDefaultOptions struct { + // placeholder for future optional parameters +} + +// OptionalUnionStringLiteralClientPutAllOptions contains the optional parameters for the OptionalUnionStringLiteralClient.PutAll +// method. +type OptionalUnionStringLiteralClientPutAllOptions struct { + // placeholder for future optional parameters +} + +// OptionalUnionStringLiteralClientPutDefaultOptions contains the optional parameters for the OptionalUnionStringLiteralClient.PutDefault +// method. +type OptionalUnionStringLiteralClientPutDefaultOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/type/property/optionalitygroup/zz_responses.go b/test/http-specs/type/property/optionalitygroup/zz_responses.go new file mode 100644 index 000000000000..c3418e6d9f16 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/zz_responses.go @@ -0,0 +1,357 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package optionalitygroup + +// OptionalBooleanLiteralClientGetAllResponse contains the response from method OptionalBooleanLiteralClient.GetAll. +type OptionalBooleanLiteralClientGetAllResponse struct { + // Model with boolean literal property + BooleanLiteralProperty +} + +// OptionalBooleanLiteralClientGetDefaultResponse contains the response from method OptionalBooleanLiteralClient.GetDefault. +type OptionalBooleanLiteralClientGetDefaultResponse struct { + // Model with boolean literal property + BooleanLiteralProperty +} + +// OptionalBooleanLiteralClientPutAllResponse contains the response from method OptionalBooleanLiteralClient.PutAll. +type OptionalBooleanLiteralClientPutAllResponse struct { + // placeholder for future response values +} + +// OptionalBooleanLiteralClientPutDefaultResponse contains the response from method OptionalBooleanLiteralClient.PutDefault. +type OptionalBooleanLiteralClientPutDefaultResponse struct { + // placeholder for future response values +} + +// OptionalBytesClientGetAllResponse contains the response from method OptionalBytesClient.GetAll. +type OptionalBytesClientGetAllResponse struct { + // Template type for testing models with optional property. Pass in the type of the property you are looking for + BytesProperty +} + +// OptionalBytesClientGetDefaultResponse contains the response from method OptionalBytesClient.GetDefault. +type OptionalBytesClientGetDefaultResponse struct { + // Template type for testing models with optional property. Pass in the type of the property you are looking for + BytesProperty +} + +// OptionalBytesClientPutAllResponse contains the response from method OptionalBytesClient.PutAll. +type OptionalBytesClientPutAllResponse struct { + // placeholder for future response values +} + +// OptionalBytesClientPutDefaultResponse contains the response from method OptionalBytesClient.PutDefault. +type OptionalBytesClientPutDefaultResponse struct { + // placeholder for future response values +} + +// OptionalCollectionsByteClientGetAllResponse contains the response from method OptionalCollectionsByteClient.GetAll. +type OptionalCollectionsByteClientGetAllResponse struct { + // Model with collection bytes properties + CollectionsByteProperty +} + +// OptionalCollectionsByteClientGetDefaultResponse contains the response from method OptionalCollectionsByteClient.GetDefault. +type OptionalCollectionsByteClientGetDefaultResponse struct { + // Model with collection bytes properties + CollectionsByteProperty +} + +// OptionalCollectionsByteClientPutAllResponse contains the response from method OptionalCollectionsByteClient.PutAll. +type OptionalCollectionsByteClientPutAllResponse struct { + // placeholder for future response values +} + +// OptionalCollectionsByteClientPutDefaultResponse contains the response from method OptionalCollectionsByteClient.PutDefault. +type OptionalCollectionsByteClientPutDefaultResponse struct { + // placeholder for future response values +} + +// OptionalCollectionsModelClientGetAllResponse contains the response from method OptionalCollectionsModelClient.GetAll. +type OptionalCollectionsModelClientGetAllResponse struct { + // Model with collection models properties + CollectionsModelProperty +} + +// OptionalCollectionsModelClientGetDefaultResponse contains the response from method OptionalCollectionsModelClient.GetDefault. +type OptionalCollectionsModelClientGetDefaultResponse struct { + // Model with collection models properties + CollectionsModelProperty +} + +// OptionalCollectionsModelClientPutAllResponse contains the response from method OptionalCollectionsModelClient.PutAll. +type OptionalCollectionsModelClientPutAllResponse struct { + // placeholder for future response values +} + +// OptionalCollectionsModelClientPutDefaultResponse contains the response from method OptionalCollectionsModelClient.PutDefault. +type OptionalCollectionsModelClientPutDefaultResponse struct { + // placeholder for future response values +} + +// OptionalDatetimeClientGetAllResponse contains the response from method OptionalDatetimeClient.GetAll. +type OptionalDatetimeClientGetAllResponse struct { + // Model with a datetime property + DatetimeProperty +} + +// OptionalDatetimeClientGetDefaultResponse contains the response from method OptionalDatetimeClient.GetDefault. +type OptionalDatetimeClientGetDefaultResponse struct { + // Model with a datetime property + DatetimeProperty +} + +// OptionalDatetimeClientPutAllResponse contains the response from method OptionalDatetimeClient.PutAll. +type OptionalDatetimeClientPutAllResponse struct { + // placeholder for future response values +} + +// OptionalDatetimeClientPutDefaultResponse contains the response from method OptionalDatetimeClient.PutDefault. +type OptionalDatetimeClientPutDefaultResponse struct { + // placeholder for future response values +} + +// OptionalDurationClientGetAllResponse contains the response from method OptionalDurationClient.GetAll. +type OptionalDurationClientGetAllResponse struct { + // Model with a duration property + DurationProperty +} + +// OptionalDurationClientGetDefaultResponse contains the response from method OptionalDurationClient.GetDefault. +type OptionalDurationClientGetDefaultResponse struct { + // Model with a duration property + DurationProperty +} + +// OptionalDurationClientPutAllResponse contains the response from method OptionalDurationClient.PutAll. +type OptionalDurationClientPutAllResponse struct { + // placeholder for future response values +} + +// OptionalDurationClientPutDefaultResponse contains the response from method OptionalDurationClient.PutDefault. +type OptionalDurationClientPutDefaultResponse struct { + // placeholder for future response values +} + +// OptionalFloatLiteralClientGetAllResponse contains the response from method OptionalFloatLiteralClient.GetAll. +type OptionalFloatLiteralClientGetAllResponse struct { + // Model with float literal property + FloatLiteralProperty +} + +// OptionalFloatLiteralClientGetDefaultResponse contains the response from method OptionalFloatLiteralClient.GetDefault. +type OptionalFloatLiteralClientGetDefaultResponse struct { + // Model with float literal property + FloatLiteralProperty +} + +// OptionalFloatLiteralClientPutAllResponse contains the response from method OptionalFloatLiteralClient.PutAll. +type OptionalFloatLiteralClientPutAllResponse struct { + // placeholder for future response values +} + +// OptionalFloatLiteralClientPutDefaultResponse contains the response from method OptionalFloatLiteralClient.PutDefault. +type OptionalFloatLiteralClientPutDefaultResponse struct { + // placeholder for future response values +} + +// OptionalIntLiteralClientGetAllResponse contains the response from method OptionalIntLiteralClient.GetAll. +type OptionalIntLiteralClientGetAllResponse struct { + // Model with int literal property + IntLiteralProperty +} + +// OptionalIntLiteralClientGetDefaultResponse contains the response from method OptionalIntLiteralClient.GetDefault. +type OptionalIntLiteralClientGetDefaultResponse struct { + // Model with int literal property + IntLiteralProperty +} + +// OptionalIntLiteralClientPutAllResponse contains the response from method OptionalIntLiteralClient.PutAll. +type OptionalIntLiteralClientPutAllResponse struct { + // placeholder for future response values +} + +// OptionalIntLiteralClientPutDefaultResponse contains the response from method OptionalIntLiteralClient.PutDefault. +type OptionalIntLiteralClientPutDefaultResponse struct { + // placeholder for future response values +} + +// OptionalPlainDateClientGetAllResponse contains the response from method OptionalPlainDateClient.GetAll. +type OptionalPlainDateClientGetAllResponse struct { + // Model with a plainDate property + PlainDateProperty +} + +// OptionalPlainDateClientGetDefaultResponse contains the response from method OptionalPlainDateClient.GetDefault. +type OptionalPlainDateClientGetDefaultResponse struct { + // Model with a plainDate property + PlainDateProperty +} + +// OptionalPlainDateClientPutAllResponse contains the response from method OptionalPlainDateClient.PutAll. +type OptionalPlainDateClientPutAllResponse struct { + // placeholder for future response values +} + +// OptionalPlainDateClientPutDefaultResponse contains the response from method OptionalPlainDateClient.PutDefault. +type OptionalPlainDateClientPutDefaultResponse struct { + // placeholder for future response values +} + +// OptionalPlainTimeClientGetAllResponse contains the response from method OptionalPlainTimeClient.GetAll. +type OptionalPlainTimeClientGetAllResponse struct { + // Model with a plainTime property + PlainTimeProperty +} + +// OptionalPlainTimeClientGetDefaultResponse contains the response from method OptionalPlainTimeClient.GetDefault. +type OptionalPlainTimeClientGetDefaultResponse struct { + // Model with a plainTime property + PlainTimeProperty +} + +// OptionalPlainTimeClientPutAllResponse contains the response from method OptionalPlainTimeClient.PutAll. +type OptionalPlainTimeClientPutAllResponse struct { + // placeholder for future response values +} + +// OptionalPlainTimeClientPutDefaultResponse contains the response from method OptionalPlainTimeClient.PutDefault. +type OptionalPlainTimeClientPutDefaultResponse struct { + // placeholder for future response values +} + +// OptionalRequiredAndOptionalClientGetAllResponse contains the response from method OptionalRequiredAndOptionalClient.GetAll. +type OptionalRequiredAndOptionalClientGetAllResponse struct { + // Model with required and optional properties + RequiredAndOptionalProperty +} + +// OptionalRequiredAndOptionalClientGetRequiredOnlyResponse contains the response from method OptionalRequiredAndOptionalClient.GetRequiredOnly. +type OptionalRequiredAndOptionalClientGetRequiredOnlyResponse struct { + // Model with required and optional properties + RequiredAndOptionalProperty +} + +// OptionalRequiredAndOptionalClientPutAllResponse contains the response from method OptionalRequiredAndOptionalClient.PutAll. +type OptionalRequiredAndOptionalClientPutAllResponse struct { + // placeholder for future response values +} + +// OptionalRequiredAndOptionalClientPutRequiredOnlyResponse contains the response from method OptionalRequiredAndOptionalClient.PutRequiredOnly. +type OptionalRequiredAndOptionalClientPutRequiredOnlyResponse struct { + // placeholder for future response values +} + +// OptionalStringClientGetAllResponse contains the response from method OptionalStringClient.GetAll. +type OptionalStringClientGetAllResponse struct { + // Template type for testing models with optional property. Pass in the type of the property you are looking for + StringProperty +} + +// OptionalStringClientGetDefaultResponse contains the response from method OptionalStringClient.GetDefault. +type OptionalStringClientGetDefaultResponse struct { + // Template type for testing models with optional property. Pass in the type of the property you are looking for + StringProperty +} + +// OptionalStringClientPutAllResponse contains the response from method OptionalStringClient.PutAll. +type OptionalStringClientPutAllResponse struct { + // placeholder for future response values +} + +// OptionalStringClientPutDefaultResponse contains the response from method OptionalStringClient.PutDefault. +type OptionalStringClientPutDefaultResponse struct { + // placeholder for future response values +} + +// OptionalStringLiteralClientGetAllResponse contains the response from method OptionalStringLiteralClient.GetAll. +type OptionalStringLiteralClientGetAllResponse struct { + // Model with string literal property + StringLiteralProperty +} + +// OptionalStringLiteralClientGetDefaultResponse contains the response from method OptionalStringLiteralClient.GetDefault. +type OptionalStringLiteralClientGetDefaultResponse struct { + // Model with string literal property + StringLiteralProperty +} + +// OptionalStringLiteralClientPutAllResponse contains the response from method OptionalStringLiteralClient.PutAll. +type OptionalStringLiteralClientPutAllResponse struct { + // placeholder for future response values +} + +// OptionalStringLiteralClientPutDefaultResponse contains the response from method OptionalStringLiteralClient.PutDefault. +type OptionalStringLiteralClientPutDefaultResponse struct { + // placeholder for future response values +} + +// OptionalUnionFloatLiteralClientGetAllResponse contains the response from method OptionalUnionFloatLiteralClient.GetAll. +type OptionalUnionFloatLiteralClientGetAllResponse struct { + // Model with union of float literal property + UnionFloatLiteralProperty +} + +// OptionalUnionFloatLiteralClientGetDefaultResponse contains the response from method OptionalUnionFloatLiteralClient.GetDefault. +type OptionalUnionFloatLiteralClientGetDefaultResponse struct { + // Model with union of float literal property + UnionFloatLiteralProperty +} + +// OptionalUnionFloatLiteralClientPutAllResponse contains the response from method OptionalUnionFloatLiteralClient.PutAll. +type OptionalUnionFloatLiteralClientPutAllResponse struct { + // placeholder for future response values +} + +// OptionalUnionFloatLiteralClientPutDefaultResponse contains the response from method OptionalUnionFloatLiteralClient.PutDefault. +type OptionalUnionFloatLiteralClientPutDefaultResponse struct { + // placeholder for future response values +} + +// OptionalUnionIntLiteralClientGetAllResponse contains the response from method OptionalUnionIntLiteralClient.GetAll. +type OptionalUnionIntLiteralClientGetAllResponse struct { + // Model with union of int literal property + UnionIntLiteralProperty +} + +// OptionalUnionIntLiteralClientGetDefaultResponse contains the response from method OptionalUnionIntLiteralClient.GetDefault. +type OptionalUnionIntLiteralClientGetDefaultResponse struct { + // Model with union of int literal property + UnionIntLiteralProperty +} + +// OptionalUnionIntLiteralClientPutAllResponse contains the response from method OptionalUnionIntLiteralClient.PutAll. +type OptionalUnionIntLiteralClientPutAllResponse struct { + // placeholder for future response values +} + +// OptionalUnionIntLiteralClientPutDefaultResponse contains the response from method OptionalUnionIntLiteralClient.PutDefault. +type OptionalUnionIntLiteralClientPutDefaultResponse struct { + // placeholder for future response values +} + +// OptionalUnionStringLiteralClientGetAllResponse contains the response from method OptionalUnionStringLiteralClient.GetAll. +type OptionalUnionStringLiteralClientGetAllResponse struct { + // Model with union of string literal property + UnionStringLiteralProperty +} + +// OptionalUnionStringLiteralClientGetDefaultResponse contains the response from method OptionalUnionStringLiteralClient.GetDefault. +type OptionalUnionStringLiteralClientGetDefaultResponse struct { + // Model with union of string literal property + UnionStringLiteralProperty +} + +// OptionalUnionStringLiteralClientPutAllResponse contains the response from method OptionalUnionStringLiteralClient.PutAll. +type OptionalUnionStringLiteralClientPutAllResponse struct { + // placeholder for future response values +} + +// OptionalUnionStringLiteralClientPutDefaultResponse contains the response from method OptionalUnionStringLiteralClient.PutDefault. +type OptionalUnionStringLiteralClientPutDefaultResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/type/property/optionalitygroup/zz_version.go b/test/http-specs/type/property/optionalitygroup/zz_version.go new file mode 100644 index 000000000000..d5a8cc2a01b4 --- /dev/null +++ b/test/http-specs/type/property/optionalitygroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package optionalitygroup + +const ( + moduleName = "optionalitygroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/type/property/valuetypesgroup/LICENSE.txt b/test/http-specs/type/property/valuetypesgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_internal.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypes_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypes_server.go new file mode 100644 index 000000000000..309f1dd7789a --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypes_server.go @@ -0,0 +1,321 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ValueTypesServer is a fake server for instances of the valuetypesgroup.ValueTypesClient type. +type ValueTypesServer struct { + // ValueTypesBooleanServer contains the fakes for client ValueTypesBooleanClient + ValueTypesBooleanServer ValueTypesBooleanServer + + // ValueTypesBooleanLiteralServer contains the fakes for client ValueTypesBooleanLiteralClient + ValueTypesBooleanLiteralServer ValueTypesBooleanLiteralServer + + // ValueTypesBytesServer contains the fakes for client ValueTypesBytesClient + ValueTypesBytesServer ValueTypesBytesServer + + // ValueTypesCollectionsIntServer contains the fakes for client ValueTypesCollectionsIntClient + ValueTypesCollectionsIntServer ValueTypesCollectionsIntServer + + // ValueTypesCollectionsModelServer contains the fakes for client ValueTypesCollectionsModelClient + ValueTypesCollectionsModelServer ValueTypesCollectionsModelServer + + // ValueTypesCollectionsStringServer contains the fakes for client ValueTypesCollectionsStringClient + ValueTypesCollectionsStringServer ValueTypesCollectionsStringServer + + // ValueTypesDatetimeServer contains the fakes for client ValueTypesDatetimeClient + ValueTypesDatetimeServer ValueTypesDatetimeServer + + // ValueTypesDecimal128Server contains the fakes for client ValueTypesDecimal128Client + ValueTypesDecimal128Server ValueTypesDecimal128Server + + // ValueTypesDecimalServer contains the fakes for client ValueTypesDecimalClient + ValueTypesDecimalServer ValueTypesDecimalServer + + // ValueTypesDictionaryStringServer contains the fakes for client ValueTypesDictionaryStringClient + ValueTypesDictionaryStringServer ValueTypesDictionaryStringServer + + // ValueTypesDurationServer contains the fakes for client ValueTypesDurationClient + ValueTypesDurationServer ValueTypesDurationServer + + // ValueTypesEnumServer contains the fakes for client ValueTypesEnumClient + ValueTypesEnumServer ValueTypesEnumServer + + // ValueTypesExtensibleEnumServer contains the fakes for client ValueTypesExtensibleEnumClient + ValueTypesExtensibleEnumServer ValueTypesExtensibleEnumServer + + // ValueTypesFloatServer contains the fakes for client ValueTypesFloatClient + ValueTypesFloatServer ValueTypesFloatServer + + // ValueTypesFloatLiteralServer contains the fakes for client ValueTypesFloatLiteralClient + ValueTypesFloatLiteralServer ValueTypesFloatLiteralServer + + // ValueTypesIntServer contains the fakes for client ValueTypesIntClient + ValueTypesIntServer ValueTypesIntServer + + // ValueTypesIntLiteralServer contains the fakes for client ValueTypesIntLiteralClient + ValueTypesIntLiteralServer ValueTypesIntLiteralServer + + // ValueTypesModelServer contains the fakes for client ValueTypesModelClient + ValueTypesModelServer ValueTypesModelServer + + // ValueTypesNeverServer contains the fakes for client ValueTypesNeverClient + ValueTypesNeverServer ValueTypesNeverServer + + // ValueTypesStringServer contains the fakes for client ValueTypesStringClient + ValueTypesStringServer ValueTypesStringServer + + // ValueTypesStringLiteralServer contains the fakes for client ValueTypesStringLiteralClient + ValueTypesStringLiteralServer ValueTypesStringLiteralServer + + // ValueTypesUnionEnumValueServer contains the fakes for client ValueTypesUnionEnumValueClient + ValueTypesUnionEnumValueServer ValueTypesUnionEnumValueServer + + // ValueTypesUnionFloatLiteralServer contains the fakes for client ValueTypesUnionFloatLiteralClient + ValueTypesUnionFloatLiteralServer ValueTypesUnionFloatLiteralServer + + // ValueTypesUnionIntLiteralServer contains the fakes for client ValueTypesUnionIntLiteralClient + ValueTypesUnionIntLiteralServer ValueTypesUnionIntLiteralServer + + // ValueTypesUnionStringLiteralServer contains the fakes for client ValueTypesUnionStringLiteralClient + ValueTypesUnionStringLiteralServer ValueTypesUnionStringLiteralServer + + // ValueTypesUnknownArrayServer contains the fakes for client ValueTypesUnknownArrayClient + ValueTypesUnknownArrayServer ValueTypesUnknownArrayServer + + // ValueTypesUnknownDictServer contains the fakes for client ValueTypesUnknownDictClient + ValueTypesUnknownDictServer ValueTypesUnknownDictServer + + // ValueTypesUnknownIntServer contains the fakes for client ValueTypesUnknownIntClient + ValueTypesUnknownIntServer ValueTypesUnknownIntServer + + // ValueTypesUnknownStringServer contains the fakes for client ValueTypesUnknownStringClient + ValueTypesUnknownStringServer ValueTypesUnknownStringServer +} + +// NewValueTypesServerTransport creates a new instance of ValueTypesServerTransport with the provided implementation. +// The returned ValueTypesServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesServerTransport(srv *ValueTypesServer) *ValueTypesServerTransport { + return &ValueTypesServerTransport{srv: srv} +} + +// ValueTypesServerTransport connects instances of valuetypesgroup.ValueTypesClient to instances of ValueTypesServer. +// Don't use this type directly, use NewValueTypesServerTransport instead. +type ValueTypesServerTransport struct { + srv *ValueTypesServer + trMu sync.Mutex + trValueTypesBooleanServer *ValueTypesBooleanServerTransport + trValueTypesBooleanLiteralServer *ValueTypesBooleanLiteralServerTransport + trValueTypesBytesServer *ValueTypesBytesServerTransport + trValueTypesCollectionsIntServer *ValueTypesCollectionsIntServerTransport + trValueTypesCollectionsModelServer *ValueTypesCollectionsModelServerTransport + trValueTypesCollectionsStringServer *ValueTypesCollectionsStringServerTransport + trValueTypesDatetimeServer *ValueTypesDatetimeServerTransport + trValueTypesDecimal128Server *ValueTypesDecimal128ServerTransport + trValueTypesDecimalServer *ValueTypesDecimalServerTransport + trValueTypesDictionaryStringServer *ValueTypesDictionaryStringServerTransport + trValueTypesDurationServer *ValueTypesDurationServerTransport + trValueTypesEnumServer *ValueTypesEnumServerTransport + trValueTypesExtensibleEnumServer *ValueTypesExtensibleEnumServerTransport + trValueTypesFloatServer *ValueTypesFloatServerTransport + trValueTypesFloatLiteralServer *ValueTypesFloatLiteralServerTransport + trValueTypesIntServer *ValueTypesIntServerTransport + trValueTypesIntLiteralServer *ValueTypesIntLiteralServerTransport + trValueTypesModelServer *ValueTypesModelServerTransport + trValueTypesNeverServer *ValueTypesNeverServerTransport + trValueTypesStringServer *ValueTypesStringServerTransport + trValueTypesStringLiteralServer *ValueTypesStringLiteralServerTransport + trValueTypesUnionEnumValueServer *ValueTypesUnionEnumValueServerTransport + trValueTypesUnionFloatLiteralServer *ValueTypesUnionFloatLiteralServerTransport + trValueTypesUnionIntLiteralServer *ValueTypesUnionIntLiteralServerTransport + trValueTypesUnionStringLiteralServer *ValueTypesUnionStringLiteralServerTransport + trValueTypesUnknownArrayServer *ValueTypesUnknownArrayServerTransport + trValueTypesUnknownDictServer *ValueTypesUnknownDictServerTransport + trValueTypesUnknownIntServer *ValueTypesUnknownIntServerTransport + trValueTypesUnknownStringServer *ValueTypesUnknownStringServerTransport +} + +// Do implements the policy.Transporter interface for ValueTypesServerTransport. +func (v *ValueTypesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (v *ValueTypesServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "ValueTypesBooleanClient": + initServer(&v.trMu, &v.trValueTypesBooleanServer, func() *ValueTypesBooleanServerTransport { + return NewValueTypesBooleanServerTransport(&v.srv.ValueTypesBooleanServer) + }) + resp, err = v.trValueTypesBooleanServer.Do(req) + case "ValueTypesBooleanLiteralClient": + initServer(&v.trMu, &v.trValueTypesBooleanLiteralServer, func() *ValueTypesBooleanLiteralServerTransport { + return NewValueTypesBooleanLiteralServerTransport(&v.srv.ValueTypesBooleanLiteralServer) + }) + resp, err = v.trValueTypesBooleanLiteralServer.Do(req) + case "ValueTypesBytesClient": + initServer(&v.trMu, &v.trValueTypesBytesServer, func() *ValueTypesBytesServerTransport { + return NewValueTypesBytesServerTransport(&v.srv.ValueTypesBytesServer) + }) + resp, err = v.trValueTypesBytesServer.Do(req) + case "ValueTypesCollectionsIntClient": + initServer(&v.trMu, &v.trValueTypesCollectionsIntServer, func() *ValueTypesCollectionsIntServerTransport { + return NewValueTypesCollectionsIntServerTransport(&v.srv.ValueTypesCollectionsIntServer) + }) + resp, err = v.trValueTypesCollectionsIntServer.Do(req) + case "ValueTypesCollectionsModelClient": + initServer(&v.trMu, &v.trValueTypesCollectionsModelServer, func() *ValueTypesCollectionsModelServerTransport { + return NewValueTypesCollectionsModelServerTransport(&v.srv.ValueTypesCollectionsModelServer) + }) + resp, err = v.trValueTypesCollectionsModelServer.Do(req) + case "ValueTypesCollectionsStringClient": + initServer(&v.trMu, &v.trValueTypesCollectionsStringServer, func() *ValueTypesCollectionsStringServerTransport { + return NewValueTypesCollectionsStringServerTransport(&v.srv.ValueTypesCollectionsStringServer) + }) + resp, err = v.trValueTypesCollectionsStringServer.Do(req) + case "ValueTypesDatetimeClient": + initServer(&v.trMu, &v.trValueTypesDatetimeServer, func() *ValueTypesDatetimeServerTransport { + return NewValueTypesDatetimeServerTransport(&v.srv.ValueTypesDatetimeServer) + }) + resp, err = v.trValueTypesDatetimeServer.Do(req) + case "ValueTypesDecimal128Client": + initServer(&v.trMu, &v.trValueTypesDecimal128Server, func() *ValueTypesDecimal128ServerTransport { + return NewValueTypesDecimal128ServerTransport(&v.srv.ValueTypesDecimal128Server) + }) + resp, err = v.trValueTypesDecimal128Server.Do(req) + case "ValueTypesDecimalClient": + initServer(&v.trMu, &v.trValueTypesDecimalServer, func() *ValueTypesDecimalServerTransport { + return NewValueTypesDecimalServerTransport(&v.srv.ValueTypesDecimalServer) + }) + resp, err = v.trValueTypesDecimalServer.Do(req) + case "ValueTypesDictionaryStringClient": + initServer(&v.trMu, &v.trValueTypesDictionaryStringServer, func() *ValueTypesDictionaryStringServerTransport { + return NewValueTypesDictionaryStringServerTransport(&v.srv.ValueTypesDictionaryStringServer) + }) + resp, err = v.trValueTypesDictionaryStringServer.Do(req) + case "ValueTypesDurationClient": + initServer(&v.trMu, &v.trValueTypesDurationServer, func() *ValueTypesDurationServerTransport { + return NewValueTypesDurationServerTransport(&v.srv.ValueTypesDurationServer) + }) + resp, err = v.trValueTypesDurationServer.Do(req) + case "ValueTypesEnumClient": + initServer(&v.trMu, &v.trValueTypesEnumServer, func() *ValueTypesEnumServerTransport { + return NewValueTypesEnumServerTransport(&v.srv.ValueTypesEnumServer) + }) + resp, err = v.trValueTypesEnumServer.Do(req) + case "ValueTypesExtensibleEnumClient": + initServer(&v.trMu, &v.trValueTypesExtensibleEnumServer, func() *ValueTypesExtensibleEnumServerTransport { + return NewValueTypesExtensibleEnumServerTransport(&v.srv.ValueTypesExtensibleEnumServer) + }) + resp, err = v.trValueTypesExtensibleEnumServer.Do(req) + case "ValueTypesFloatClient": + initServer(&v.trMu, &v.trValueTypesFloatServer, func() *ValueTypesFloatServerTransport { + return NewValueTypesFloatServerTransport(&v.srv.ValueTypesFloatServer) + }) + resp, err = v.trValueTypesFloatServer.Do(req) + case "ValueTypesFloatLiteralClient": + initServer(&v.trMu, &v.trValueTypesFloatLiteralServer, func() *ValueTypesFloatLiteralServerTransport { + return NewValueTypesFloatLiteralServerTransport(&v.srv.ValueTypesFloatLiteralServer) + }) + resp, err = v.trValueTypesFloatLiteralServer.Do(req) + case "ValueTypesIntClient": + initServer(&v.trMu, &v.trValueTypesIntServer, func() *ValueTypesIntServerTransport { + return NewValueTypesIntServerTransport(&v.srv.ValueTypesIntServer) + }) + resp, err = v.trValueTypesIntServer.Do(req) + case "ValueTypesIntLiteralClient": + initServer(&v.trMu, &v.trValueTypesIntLiteralServer, func() *ValueTypesIntLiteralServerTransport { + return NewValueTypesIntLiteralServerTransport(&v.srv.ValueTypesIntLiteralServer) + }) + resp, err = v.trValueTypesIntLiteralServer.Do(req) + case "ValueTypesModelClient": + initServer(&v.trMu, &v.trValueTypesModelServer, func() *ValueTypesModelServerTransport { + return NewValueTypesModelServerTransport(&v.srv.ValueTypesModelServer) + }) + resp, err = v.trValueTypesModelServer.Do(req) + case "ValueTypesNeverClient": + initServer(&v.trMu, &v.trValueTypesNeverServer, func() *ValueTypesNeverServerTransport { + return NewValueTypesNeverServerTransport(&v.srv.ValueTypesNeverServer) + }) + resp, err = v.trValueTypesNeverServer.Do(req) + case "ValueTypesStringClient": + initServer(&v.trMu, &v.trValueTypesStringServer, func() *ValueTypesStringServerTransport { + return NewValueTypesStringServerTransport(&v.srv.ValueTypesStringServer) + }) + resp, err = v.trValueTypesStringServer.Do(req) + case "ValueTypesStringLiteralClient": + initServer(&v.trMu, &v.trValueTypesStringLiteralServer, func() *ValueTypesStringLiteralServerTransport { + return NewValueTypesStringLiteralServerTransport(&v.srv.ValueTypesStringLiteralServer) + }) + resp, err = v.trValueTypesStringLiteralServer.Do(req) + case "ValueTypesUnionEnumValueClient": + initServer(&v.trMu, &v.trValueTypesUnionEnumValueServer, func() *ValueTypesUnionEnumValueServerTransport { + return NewValueTypesUnionEnumValueServerTransport(&v.srv.ValueTypesUnionEnumValueServer) + }) + resp, err = v.trValueTypesUnionEnumValueServer.Do(req) + case "ValueTypesUnionFloatLiteralClient": + initServer(&v.trMu, &v.trValueTypesUnionFloatLiteralServer, func() *ValueTypesUnionFloatLiteralServerTransport { + return NewValueTypesUnionFloatLiteralServerTransport(&v.srv.ValueTypesUnionFloatLiteralServer) + }) + resp, err = v.trValueTypesUnionFloatLiteralServer.Do(req) + case "ValueTypesUnionIntLiteralClient": + initServer(&v.trMu, &v.trValueTypesUnionIntLiteralServer, func() *ValueTypesUnionIntLiteralServerTransport { + return NewValueTypesUnionIntLiteralServerTransport(&v.srv.ValueTypesUnionIntLiteralServer) + }) + resp, err = v.trValueTypesUnionIntLiteralServer.Do(req) + case "ValueTypesUnionStringLiteralClient": + initServer(&v.trMu, &v.trValueTypesUnionStringLiteralServer, func() *ValueTypesUnionStringLiteralServerTransport { + return NewValueTypesUnionStringLiteralServerTransport(&v.srv.ValueTypesUnionStringLiteralServer) + }) + resp, err = v.trValueTypesUnionStringLiteralServer.Do(req) + case "ValueTypesUnknownArrayClient": + initServer(&v.trMu, &v.trValueTypesUnknownArrayServer, func() *ValueTypesUnknownArrayServerTransport { + return NewValueTypesUnknownArrayServerTransport(&v.srv.ValueTypesUnknownArrayServer) + }) + resp, err = v.trValueTypesUnknownArrayServer.Do(req) + case "ValueTypesUnknownDictClient": + initServer(&v.trMu, &v.trValueTypesUnknownDictServer, func() *ValueTypesUnknownDictServerTransport { + return NewValueTypesUnknownDictServerTransport(&v.srv.ValueTypesUnknownDictServer) + }) + resp, err = v.trValueTypesUnknownDictServer.Do(req) + case "ValueTypesUnknownIntClient": + initServer(&v.trMu, &v.trValueTypesUnknownIntServer, func() *ValueTypesUnknownIntServerTransport { + return NewValueTypesUnknownIntServerTransport(&v.srv.ValueTypesUnknownIntServer) + }) + resp, err = v.trValueTypesUnknownIntServer.Do(req) + case "ValueTypesUnknownStringClient": + initServer(&v.trMu, &v.trValueTypesUnknownStringServer, func() *ValueTypesUnknownStringServerTransport { + return NewValueTypesUnknownStringServerTransport(&v.srv.ValueTypesUnknownStringServer) + }) + resp, err = v.trValueTypesUnknownStringServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to ValueTypesServerTransport +var valueTypesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesboolean_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesboolean_server.go new file mode 100644 index 000000000000..d42d1fc375a3 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesboolean_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesBooleanServer is a fake server for instances of the valuetypesgroup.ValueTypesBooleanClient type. +type ValueTypesBooleanServer struct { + // Get is the fake for method ValueTypesBooleanClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesBooleanClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesBooleanClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesBooleanClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.BooleanProperty, options *valuetypesgroup.ValueTypesBooleanClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesBooleanClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesBooleanServerTransport creates a new instance of ValueTypesBooleanServerTransport with the provided implementation. +// The returned ValueTypesBooleanServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesBooleanClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesBooleanServerTransport(srv *ValueTypesBooleanServer) *ValueTypesBooleanServerTransport { + return &ValueTypesBooleanServerTransport{srv: srv} +} + +// ValueTypesBooleanServerTransport connects instances of valuetypesgroup.ValueTypesBooleanClient to instances of ValueTypesBooleanServer. +// Don't use this type directly, use NewValueTypesBooleanServerTransport instead. +type ValueTypesBooleanServerTransport struct { + srv *ValueTypesBooleanServer +} + +// Do implements the policy.Transporter interface for ValueTypesBooleanServerTransport. +func (v *ValueTypesBooleanServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesBooleanServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesBooleanServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesBooleanServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesBooleanClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesBooleanClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesBooleanServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BooleanProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesBooleanServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.BooleanProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesBooleanServerTransport +var valueTypesBooleanServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesbooleanliteral_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesbooleanliteral_server.go new file mode 100644 index 000000000000..02e2b866f34a --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesbooleanliteral_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesBooleanLiteralServer is a fake server for instances of the valuetypesgroup.ValueTypesBooleanLiteralClient type. +type ValueTypesBooleanLiteralServer struct { + // Get is the fake for method ValueTypesBooleanLiteralClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesBooleanLiteralClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesBooleanLiteralClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesBooleanLiteralClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.BooleanLiteralProperty, options *valuetypesgroup.ValueTypesBooleanLiteralClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesBooleanLiteralClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesBooleanLiteralServerTransport creates a new instance of ValueTypesBooleanLiteralServerTransport with the provided implementation. +// The returned ValueTypesBooleanLiteralServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesBooleanLiteralClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesBooleanLiteralServerTransport(srv *ValueTypesBooleanLiteralServer) *ValueTypesBooleanLiteralServerTransport { + return &ValueTypesBooleanLiteralServerTransport{srv: srv} +} + +// ValueTypesBooleanLiteralServerTransport connects instances of valuetypesgroup.ValueTypesBooleanLiteralClient to instances of ValueTypesBooleanLiteralServer. +// Don't use this type directly, use NewValueTypesBooleanLiteralServerTransport instead. +type ValueTypesBooleanLiteralServerTransport struct { + srv *ValueTypesBooleanLiteralServer +} + +// Do implements the policy.Transporter interface for ValueTypesBooleanLiteralServerTransport. +func (v *ValueTypesBooleanLiteralServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesBooleanLiteralServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesBooleanLiteralServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesBooleanLiteralServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesBooleanLiteralClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesBooleanLiteralClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesBooleanLiteralServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BooleanLiteralProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesBooleanLiteralServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.BooleanLiteralProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesBooleanLiteralServerTransport +var valueTypesBooleanLiteralServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesbytes_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesbytes_server.go new file mode 100644 index 000000000000..a82c3981fd46 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesbytes_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesBytesServer is a fake server for instances of the valuetypesgroup.ValueTypesBytesClient type. +type ValueTypesBytesServer struct { + // Get is the fake for method ValueTypesBytesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesBytesClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesBytesClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesBytesClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.BytesProperty, options *valuetypesgroup.ValueTypesBytesClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesBytesClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesBytesServerTransport creates a new instance of ValueTypesBytesServerTransport with the provided implementation. +// The returned ValueTypesBytesServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesBytesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesBytesServerTransport(srv *ValueTypesBytesServer) *ValueTypesBytesServerTransport { + return &ValueTypesBytesServerTransport{srv: srv} +} + +// ValueTypesBytesServerTransport connects instances of valuetypesgroup.ValueTypesBytesClient to instances of ValueTypesBytesServer. +// Don't use this type directly, use NewValueTypesBytesServerTransport instead. +type ValueTypesBytesServerTransport struct { + srv *ValueTypesBytesServer +} + +// Do implements the policy.Transporter interface for ValueTypesBytesServerTransport. +func (v *ValueTypesBytesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesBytesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesBytesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesBytesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesBytesClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesBytesClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesBytesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BytesProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesBytesServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.BytesProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesBytesServerTransport +var valueTypesBytesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypescollectionsint_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypescollectionsint_server.go new file mode 100644 index 000000000000..4808b9221920 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypescollectionsint_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesCollectionsIntServer is a fake server for instances of the valuetypesgroup.ValueTypesCollectionsIntClient type. +type ValueTypesCollectionsIntServer struct { + // Get is the fake for method ValueTypesCollectionsIntClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesCollectionsIntClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesCollectionsIntClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesCollectionsIntClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.CollectionsIntProperty, options *valuetypesgroup.ValueTypesCollectionsIntClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesCollectionsIntClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesCollectionsIntServerTransport creates a new instance of ValueTypesCollectionsIntServerTransport with the provided implementation. +// The returned ValueTypesCollectionsIntServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesCollectionsIntClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesCollectionsIntServerTransport(srv *ValueTypesCollectionsIntServer) *ValueTypesCollectionsIntServerTransport { + return &ValueTypesCollectionsIntServerTransport{srv: srv} +} + +// ValueTypesCollectionsIntServerTransport connects instances of valuetypesgroup.ValueTypesCollectionsIntClient to instances of ValueTypesCollectionsIntServer. +// Don't use this type directly, use NewValueTypesCollectionsIntServerTransport instead. +type ValueTypesCollectionsIntServerTransport struct { + srv *ValueTypesCollectionsIntServer +} + +// Do implements the policy.Transporter interface for ValueTypesCollectionsIntServerTransport. +func (v *ValueTypesCollectionsIntServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesCollectionsIntServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesCollectionsIntServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesCollectionsIntServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesCollectionsIntClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesCollectionsIntClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesCollectionsIntServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CollectionsIntProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesCollectionsIntServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.CollectionsIntProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesCollectionsIntServerTransport +var valueTypesCollectionsIntServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypescollectionsmodel_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypescollectionsmodel_server.go new file mode 100644 index 000000000000..0cde57713908 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypescollectionsmodel_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesCollectionsModelServer is a fake server for instances of the valuetypesgroup.ValueTypesCollectionsModelClient type. +type ValueTypesCollectionsModelServer struct { + // Get is the fake for method ValueTypesCollectionsModelClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesCollectionsModelClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesCollectionsModelClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesCollectionsModelClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.CollectionsModelProperty, options *valuetypesgroup.ValueTypesCollectionsModelClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesCollectionsModelClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesCollectionsModelServerTransport creates a new instance of ValueTypesCollectionsModelServerTransport with the provided implementation. +// The returned ValueTypesCollectionsModelServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesCollectionsModelClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesCollectionsModelServerTransport(srv *ValueTypesCollectionsModelServer) *ValueTypesCollectionsModelServerTransport { + return &ValueTypesCollectionsModelServerTransport{srv: srv} +} + +// ValueTypesCollectionsModelServerTransport connects instances of valuetypesgroup.ValueTypesCollectionsModelClient to instances of ValueTypesCollectionsModelServer. +// Don't use this type directly, use NewValueTypesCollectionsModelServerTransport instead. +type ValueTypesCollectionsModelServerTransport struct { + srv *ValueTypesCollectionsModelServer +} + +// Do implements the policy.Transporter interface for ValueTypesCollectionsModelServerTransport. +func (v *ValueTypesCollectionsModelServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesCollectionsModelServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesCollectionsModelServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesCollectionsModelServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesCollectionsModelClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesCollectionsModelClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesCollectionsModelServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CollectionsModelProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesCollectionsModelServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.CollectionsModelProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesCollectionsModelServerTransport +var valueTypesCollectionsModelServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypescollectionsstring_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypescollectionsstring_server.go new file mode 100644 index 000000000000..5812a81b39c5 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypescollectionsstring_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesCollectionsStringServer is a fake server for instances of the valuetypesgroup.ValueTypesCollectionsStringClient type. +type ValueTypesCollectionsStringServer struct { + // Get is the fake for method ValueTypesCollectionsStringClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesCollectionsStringClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesCollectionsStringClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesCollectionsStringClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.CollectionsStringProperty, options *valuetypesgroup.ValueTypesCollectionsStringClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesCollectionsStringClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesCollectionsStringServerTransport creates a new instance of ValueTypesCollectionsStringServerTransport with the provided implementation. +// The returned ValueTypesCollectionsStringServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesCollectionsStringClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesCollectionsStringServerTransport(srv *ValueTypesCollectionsStringServer) *ValueTypesCollectionsStringServerTransport { + return &ValueTypesCollectionsStringServerTransport{srv: srv} +} + +// ValueTypesCollectionsStringServerTransport connects instances of valuetypesgroup.ValueTypesCollectionsStringClient to instances of ValueTypesCollectionsStringServer. +// Don't use this type directly, use NewValueTypesCollectionsStringServerTransport instead. +type ValueTypesCollectionsStringServerTransport struct { + srv *ValueTypesCollectionsStringServer +} + +// Do implements the policy.Transporter interface for ValueTypesCollectionsStringServerTransport. +func (v *ValueTypesCollectionsStringServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesCollectionsStringServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesCollectionsStringServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesCollectionsStringServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesCollectionsStringClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesCollectionsStringClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesCollectionsStringServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CollectionsStringProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesCollectionsStringServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.CollectionsStringProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesCollectionsStringServerTransport +var valueTypesCollectionsStringServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesdatetime_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesdatetime_server.go new file mode 100644 index 000000000000..4d069f56349e --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesdatetime_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesDatetimeServer is a fake server for instances of the valuetypesgroup.ValueTypesDatetimeClient type. +type ValueTypesDatetimeServer struct { + // Get is the fake for method ValueTypesDatetimeClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesDatetimeClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesDatetimeClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesDatetimeClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.DatetimeProperty, options *valuetypesgroup.ValueTypesDatetimeClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesDatetimeClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesDatetimeServerTransport creates a new instance of ValueTypesDatetimeServerTransport with the provided implementation. +// The returned ValueTypesDatetimeServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesDatetimeClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesDatetimeServerTransport(srv *ValueTypesDatetimeServer) *ValueTypesDatetimeServerTransport { + return &ValueTypesDatetimeServerTransport{srv: srv} +} + +// ValueTypesDatetimeServerTransport connects instances of valuetypesgroup.ValueTypesDatetimeClient to instances of ValueTypesDatetimeServer. +// Don't use this type directly, use NewValueTypesDatetimeServerTransport instead. +type ValueTypesDatetimeServerTransport struct { + srv *ValueTypesDatetimeServer +} + +// Do implements the policy.Transporter interface for ValueTypesDatetimeServerTransport. +func (v *ValueTypesDatetimeServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesDatetimeServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesDatetimeServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesDatetimeServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesDatetimeClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesDatetimeClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesDatetimeServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DatetimeProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesDatetimeServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.DatetimeProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesDatetimeServerTransport +var valueTypesDatetimeServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesdecimal128_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesdecimal128_server.go new file mode 100644 index 000000000000..48f6763ffab7 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesdecimal128_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesDecimal128Server is a fake server for instances of the valuetypesgroup.ValueTypesDecimal128Client type. +type ValueTypesDecimal128Server struct { + // Get is the fake for method ValueTypesDecimal128Client.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesDecimal128ClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesDecimal128ClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesDecimal128Client.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.Decimal128Property, options *valuetypesgroup.ValueTypesDecimal128ClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesDecimal128ClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesDecimal128ServerTransport creates a new instance of ValueTypesDecimal128ServerTransport with the provided implementation. +// The returned ValueTypesDecimal128ServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesDecimal128Client via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesDecimal128ServerTransport(srv *ValueTypesDecimal128Server) *ValueTypesDecimal128ServerTransport { + return &ValueTypesDecimal128ServerTransport{srv: srv} +} + +// ValueTypesDecimal128ServerTransport connects instances of valuetypesgroup.ValueTypesDecimal128Client to instances of ValueTypesDecimal128Server. +// Don't use this type directly, use NewValueTypesDecimal128ServerTransport instead. +type ValueTypesDecimal128ServerTransport struct { + srv *ValueTypesDecimal128Server +} + +// Do implements the policy.Transporter interface for ValueTypesDecimal128ServerTransport. +func (v *ValueTypesDecimal128ServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesDecimal128ServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesDecimal128ServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesDecimal128ServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesDecimal128Client.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesDecimal128Client.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesDecimal128ServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Decimal128Property, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesDecimal128ServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.Decimal128Property](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesDecimal128ServerTransport +var valueTypesDecimal128ServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesdecimal_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesdecimal_server.go new file mode 100644 index 000000000000..91c2ed2cd993 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesdecimal_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesDecimalServer is a fake server for instances of the valuetypesgroup.ValueTypesDecimalClient type. +type ValueTypesDecimalServer struct { + // Get is the fake for method ValueTypesDecimalClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesDecimalClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesDecimalClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesDecimalClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.DecimalProperty, options *valuetypesgroup.ValueTypesDecimalClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesDecimalClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesDecimalServerTransport creates a new instance of ValueTypesDecimalServerTransport with the provided implementation. +// The returned ValueTypesDecimalServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesDecimalClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesDecimalServerTransport(srv *ValueTypesDecimalServer) *ValueTypesDecimalServerTransport { + return &ValueTypesDecimalServerTransport{srv: srv} +} + +// ValueTypesDecimalServerTransport connects instances of valuetypesgroup.ValueTypesDecimalClient to instances of ValueTypesDecimalServer. +// Don't use this type directly, use NewValueTypesDecimalServerTransport instead. +type ValueTypesDecimalServerTransport struct { + srv *ValueTypesDecimalServer +} + +// Do implements the policy.Transporter interface for ValueTypesDecimalServerTransport. +func (v *ValueTypesDecimalServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesDecimalServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesDecimalServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesDecimalServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesDecimalClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesDecimalClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesDecimalServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DecimalProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesDecimalServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.DecimalProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesDecimalServerTransport +var valueTypesDecimalServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesdictionarystring_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesdictionarystring_server.go new file mode 100644 index 000000000000..44581b02f68c --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesdictionarystring_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesDictionaryStringServer is a fake server for instances of the valuetypesgroup.ValueTypesDictionaryStringClient type. +type ValueTypesDictionaryStringServer struct { + // Get is the fake for method ValueTypesDictionaryStringClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesDictionaryStringClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesDictionaryStringClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesDictionaryStringClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.DictionaryStringProperty, options *valuetypesgroup.ValueTypesDictionaryStringClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesDictionaryStringClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesDictionaryStringServerTransport creates a new instance of ValueTypesDictionaryStringServerTransport with the provided implementation. +// The returned ValueTypesDictionaryStringServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesDictionaryStringClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesDictionaryStringServerTransport(srv *ValueTypesDictionaryStringServer) *ValueTypesDictionaryStringServerTransport { + return &ValueTypesDictionaryStringServerTransport{srv: srv} +} + +// ValueTypesDictionaryStringServerTransport connects instances of valuetypesgroup.ValueTypesDictionaryStringClient to instances of ValueTypesDictionaryStringServer. +// Don't use this type directly, use NewValueTypesDictionaryStringServerTransport instead. +type ValueTypesDictionaryStringServerTransport struct { + srv *ValueTypesDictionaryStringServer +} + +// Do implements the policy.Transporter interface for ValueTypesDictionaryStringServerTransport. +func (v *ValueTypesDictionaryStringServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesDictionaryStringServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesDictionaryStringServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesDictionaryStringServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesDictionaryStringClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesDictionaryStringClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesDictionaryStringServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DictionaryStringProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesDictionaryStringServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.DictionaryStringProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesDictionaryStringServerTransport +var valueTypesDictionaryStringServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesduration_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesduration_server.go new file mode 100644 index 000000000000..5ae1dbea6161 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesduration_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesDurationServer is a fake server for instances of the valuetypesgroup.ValueTypesDurationClient type. +type ValueTypesDurationServer struct { + // Get is the fake for method ValueTypesDurationClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesDurationClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesDurationClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesDurationClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.DurationProperty, options *valuetypesgroup.ValueTypesDurationClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesDurationClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesDurationServerTransport creates a new instance of ValueTypesDurationServerTransport with the provided implementation. +// The returned ValueTypesDurationServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesDurationClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesDurationServerTransport(srv *ValueTypesDurationServer) *ValueTypesDurationServerTransport { + return &ValueTypesDurationServerTransport{srv: srv} +} + +// ValueTypesDurationServerTransport connects instances of valuetypesgroup.ValueTypesDurationClient to instances of ValueTypesDurationServer. +// Don't use this type directly, use NewValueTypesDurationServerTransport instead. +type ValueTypesDurationServerTransport struct { + srv *ValueTypesDurationServer +} + +// Do implements the policy.Transporter interface for ValueTypesDurationServerTransport. +func (v *ValueTypesDurationServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesDurationServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesDurationServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesDurationServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesDurationClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesDurationClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesDurationServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DurationProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesDurationServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.DurationProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesDurationServerTransport +var valueTypesDurationServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesenum_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesenum_server.go new file mode 100644 index 000000000000..a553c27b3824 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesenum_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesEnumServer is a fake server for instances of the valuetypesgroup.ValueTypesEnumClient type. +type ValueTypesEnumServer struct { + // Get is the fake for method ValueTypesEnumClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesEnumClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesEnumClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesEnumClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.EnumProperty, options *valuetypesgroup.ValueTypesEnumClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesEnumClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesEnumServerTransport creates a new instance of ValueTypesEnumServerTransport with the provided implementation. +// The returned ValueTypesEnumServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesEnumClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesEnumServerTransport(srv *ValueTypesEnumServer) *ValueTypesEnumServerTransport { + return &ValueTypesEnumServerTransport{srv: srv} +} + +// ValueTypesEnumServerTransport connects instances of valuetypesgroup.ValueTypesEnumClient to instances of ValueTypesEnumServer. +// Don't use this type directly, use NewValueTypesEnumServerTransport instead. +type ValueTypesEnumServerTransport struct { + srv *ValueTypesEnumServer +} + +// Do implements the policy.Transporter interface for ValueTypesEnumServerTransport. +func (v *ValueTypesEnumServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesEnumServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesEnumServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesEnumServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesEnumClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesEnumClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesEnumServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).EnumProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesEnumServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.EnumProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesEnumServerTransport +var valueTypesEnumServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesextensibleenum_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesextensibleenum_server.go new file mode 100644 index 000000000000..90933a7a879d --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesextensibleenum_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesExtensibleEnumServer is a fake server for instances of the valuetypesgroup.ValueTypesExtensibleEnumClient type. +type ValueTypesExtensibleEnumServer struct { + // Get is the fake for method ValueTypesExtensibleEnumClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesExtensibleEnumClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesExtensibleEnumClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesExtensibleEnumClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.ExtensibleEnumProperty, options *valuetypesgroup.ValueTypesExtensibleEnumClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesExtensibleEnumClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesExtensibleEnumServerTransport creates a new instance of ValueTypesExtensibleEnumServerTransport with the provided implementation. +// The returned ValueTypesExtensibleEnumServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesExtensibleEnumClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesExtensibleEnumServerTransport(srv *ValueTypesExtensibleEnumServer) *ValueTypesExtensibleEnumServerTransport { + return &ValueTypesExtensibleEnumServerTransport{srv: srv} +} + +// ValueTypesExtensibleEnumServerTransport connects instances of valuetypesgroup.ValueTypesExtensibleEnumClient to instances of ValueTypesExtensibleEnumServer. +// Don't use this type directly, use NewValueTypesExtensibleEnumServerTransport instead. +type ValueTypesExtensibleEnumServerTransport struct { + srv *ValueTypesExtensibleEnumServer +} + +// Do implements the policy.Transporter interface for ValueTypesExtensibleEnumServerTransport. +func (v *ValueTypesExtensibleEnumServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesExtensibleEnumServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesExtensibleEnumServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesExtensibleEnumServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesExtensibleEnumClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesExtensibleEnumClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesExtensibleEnumServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ExtensibleEnumProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesExtensibleEnumServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.ExtensibleEnumProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesExtensibleEnumServerTransport +var valueTypesExtensibleEnumServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesfloat_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesfloat_server.go new file mode 100644 index 000000000000..588e396cff7d --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesfloat_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesFloatServer is a fake server for instances of the valuetypesgroup.ValueTypesFloatClient type. +type ValueTypesFloatServer struct { + // Get is the fake for method ValueTypesFloatClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesFloatClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesFloatClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesFloatClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.FloatProperty, options *valuetypesgroup.ValueTypesFloatClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesFloatClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesFloatServerTransport creates a new instance of ValueTypesFloatServerTransport with the provided implementation. +// The returned ValueTypesFloatServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesFloatClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesFloatServerTransport(srv *ValueTypesFloatServer) *ValueTypesFloatServerTransport { + return &ValueTypesFloatServerTransport{srv: srv} +} + +// ValueTypesFloatServerTransport connects instances of valuetypesgroup.ValueTypesFloatClient to instances of ValueTypesFloatServer. +// Don't use this type directly, use NewValueTypesFloatServerTransport instead. +type ValueTypesFloatServerTransport struct { + srv *ValueTypesFloatServer +} + +// Do implements the policy.Transporter interface for ValueTypesFloatServerTransport. +func (v *ValueTypesFloatServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesFloatServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesFloatServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesFloatServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesFloatClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesFloatClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesFloatServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).FloatProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesFloatServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.FloatProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesFloatServerTransport +var valueTypesFloatServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesfloatliteral_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesfloatliteral_server.go new file mode 100644 index 000000000000..2271fcea8023 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesfloatliteral_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesFloatLiteralServer is a fake server for instances of the valuetypesgroup.ValueTypesFloatLiteralClient type. +type ValueTypesFloatLiteralServer struct { + // Get is the fake for method ValueTypesFloatLiteralClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesFloatLiteralClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesFloatLiteralClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesFloatLiteralClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.FloatLiteralProperty, options *valuetypesgroup.ValueTypesFloatLiteralClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesFloatLiteralClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesFloatLiteralServerTransport creates a new instance of ValueTypesFloatLiteralServerTransport with the provided implementation. +// The returned ValueTypesFloatLiteralServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesFloatLiteralClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesFloatLiteralServerTransport(srv *ValueTypesFloatLiteralServer) *ValueTypesFloatLiteralServerTransport { + return &ValueTypesFloatLiteralServerTransport{srv: srv} +} + +// ValueTypesFloatLiteralServerTransport connects instances of valuetypesgroup.ValueTypesFloatLiteralClient to instances of ValueTypesFloatLiteralServer. +// Don't use this type directly, use NewValueTypesFloatLiteralServerTransport instead. +type ValueTypesFloatLiteralServerTransport struct { + srv *ValueTypesFloatLiteralServer +} + +// Do implements the policy.Transporter interface for ValueTypesFloatLiteralServerTransport. +func (v *ValueTypesFloatLiteralServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesFloatLiteralServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesFloatLiteralServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesFloatLiteralServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesFloatLiteralClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesFloatLiteralClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesFloatLiteralServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).FloatLiteralProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesFloatLiteralServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.FloatLiteralProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesFloatLiteralServerTransport +var valueTypesFloatLiteralServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesint_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesint_server.go new file mode 100644 index 000000000000..dfc5139a29bc --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesint_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesIntServer is a fake server for instances of the valuetypesgroup.ValueTypesIntClient type. +type ValueTypesIntServer struct { + // Get is the fake for method ValueTypesIntClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesIntClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesIntClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesIntClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.IntProperty, options *valuetypesgroup.ValueTypesIntClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesIntClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesIntServerTransport creates a new instance of ValueTypesIntServerTransport with the provided implementation. +// The returned ValueTypesIntServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesIntClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesIntServerTransport(srv *ValueTypesIntServer) *ValueTypesIntServerTransport { + return &ValueTypesIntServerTransport{srv: srv} +} + +// ValueTypesIntServerTransport connects instances of valuetypesgroup.ValueTypesIntClient to instances of ValueTypesIntServer. +// Don't use this type directly, use NewValueTypesIntServerTransport instead. +type ValueTypesIntServerTransport struct { + srv *ValueTypesIntServer +} + +// Do implements the policy.Transporter interface for ValueTypesIntServerTransport. +func (v *ValueTypesIntServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesIntServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesIntServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesIntServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesIntClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesIntClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesIntServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).IntProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesIntServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.IntProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesIntServerTransport +var valueTypesIntServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesintliteral_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesintliteral_server.go new file mode 100644 index 000000000000..8cc4787ae69b --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesintliteral_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesIntLiteralServer is a fake server for instances of the valuetypesgroup.ValueTypesIntLiteralClient type. +type ValueTypesIntLiteralServer struct { + // Get is the fake for method ValueTypesIntLiteralClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesIntLiteralClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesIntLiteralClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesIntLiteralClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.IntLiteralProperty, options *valuetypesgroup.ValueTypesIntLiteralClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesIntLiteralClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesIntLiteralServerTransport creates a new instance of ValueTypesIntLiteralServerTransport with the provided implementation. +// The returned ValueTypesIntLiteralServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesIntLiteralClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesIntLiteralServerTransport(srv *ValueTypesIntLiteralServer) *ValueTypesIntLiteralServerTransport { + return &ValueTypesIntLiteralServerTransport{srv: srv} +} + +// ValueTypesIntLiteralServerTransport connects instances of valuetypesgroup.ValueTypesIntLiteralClient to instances of ValueTypesIntLiteralServer. +// Don't use this type directly, use NewValueTypesIntLiteralServerTransport instead. +type ValueTypesIntLiteralServerTransport struct { + srv *ValueTypesIntLiteralServer +} + +// Do implements the policy.Transporter interface for ValueTypesIntLiteralServerTransport. +func (v *ValueTypesIntLiteralServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesIntLiteralServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesIntLiteralServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesIntLiteralServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesIntLiteralClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesIntLiteralClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesIntLiteralServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).IntLiteralProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesIntLiteralServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.IntLiteralProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesIntLiteralServerTransport +var valueTypesIntLiteralServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesmodel_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesmodel_server.go new file mode 100644 index 000000000000..7b24e23a61ce --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesmodel_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesModelServer is a fake server for instances of the valuetypesgroup.ValueTypesModelClient type. +type ValueTypesModelServer struct { + // Get is the fake for method ValueTypesModelClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesModelClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesModelClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesModelClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.ModelProperty, options *valuetypesgroup.ValueTypesModelClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesModelClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesModelServerTransport creates a new instance of ValueTypesModelServerTransport with the provided implementation. +// The returned ValueTypesModelServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesModelClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesModelServerTransport(srv *ValueTypesModelServer) *ValueTypesModelServerTransport { + return &ValueTypesModelServerTransport{srv: srv} +} + +// ValueTypesModelServerTransport connects instances of valuetypesgroup.ValueTypesModelClient to instances of ValueTypesModelServer. +// Don't use this type directly, use NewValueTypesModelServerTransport instead. +type ValueTypesModelServerTransport struct { + srv *ValueTypesModelServer +} + +// Do implements the policy.Transporter interface for ValueTypesModelServerTransport. +func (v *ValueTypesModelServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesModelServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesModelServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesModelServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesModelClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesModelClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesModelServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ModelProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesModelServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.ModelProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesModelServerTransport +var valueTypesModelServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesnever_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesnever_server.go new file mode 100644 index 000000000000..e4a01dd722ae --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesnever_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesNeverServer is a fake server for instances of the valuetypesgroup.ValueTypesNeverClient type. +type ValueTypesNeverServer struct { + // Get is the fake for method ValueTypesNeverClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesNeverClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesNeverClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesNeverClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.NeverProperty, options *valuetypesgroup.ValueTypesNeverClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesNeverClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesNeverServerTransport creates a new instance of ValueTypesNeverServerTransport with the provided implementation. +// The returned ValueTypesNeverServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesNeverClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesNeverServerTransport(srv *ValueTypesNeverServer) *ValueTypesNeverServerTransport { + return &ValueTypesNeverServerTransport{srv: srv} +} + +// ValueTypesNeverServerTransport connects instances of valuetypesgroup.ValueTypesNeverClient to instances of ValueTypesNeverServer. +// Don't use this type directly, use NewValueTypesNeverServerTransport instead. +type ValueTypesNeverServerTransport struct { + srv *ValueTypesNeverServer +} + +// Do implements the policy.Transporter interface for ValueTypesNeverServerTransport. +func (v *ValueTypesNeverServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesNeverServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesNeverServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesNeverServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesNeverClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesNeverClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesNeverServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).NeverProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesNeverServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.NeverProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesNeverServerTransport +var valueTypesNeverServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesstring_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesstring_server.go new file mode 100644 index 000000000000..03b0dd97215f --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesstring_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesStringServer is a fake server for instances of the valuetypesgroup.ValueTypesStringClient type. +type ValueTypesStringServer struct { + // Get is the fake for method ValueTypesStringClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesStringClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesStringClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesStringClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.StringProperty, options *valuetypesgroup.ValueTypesStringClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesStringClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesStringServerTransport creates a new instance of ValueTypesStringServerTransport with the provided implementation. +// The returned ValueTypesStringServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesStringClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesStringServerTransport(srv *ValueTypesStringServer) *ValueTypesStringServerTransport { + return &ValueTypesStringServerTransport{srv: srv} +} + +// ValueTypesStringServerTransport connects instances of valuetypesgroup.ValueTypesStringClient to instances of ValueTypesStringServer. +// Don't use this type directly, use NewValueTypesStringServerTransport instead. +type ValueTypesStringServerTransport struct { + srv *ValueTypesStringServer +} + +// Do implements the policy.Transporter interface for ValueTypesStringServerTransport. +func (v *ValueTypesStringServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesStringServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesStringServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesStringServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesStringClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesStringClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesStringServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).StringProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesStringServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.StringProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesStringServerTransport +var valueTypesStringServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesstringliteral_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesstringliteral_server.go new file mode 100644 index 000000000000..f638b5add107 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesstringliteral_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesStringLiteralServer is a fake server for instances of the valuetypesgroup.ValueTypesStringLiteralClient type. +type ValueTypesStringLiteralServer struct { + // Get is the fake for method ValueTypesStringLiteralClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesStringLiteralClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesStringLiteralClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesStringLiteralClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.StringLiteralProperty, options *valuetypesgroup.ValueTypesStringLiteralClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesStringLiteralClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesStringLiteralServerTransport creates a new instance of ValueTypesStringLiteralServerTransport with the provided implementation. +// The returned ValueTypesStringLiteralServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesStringLiteralClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesStringLiteralServerTransport(srv *ValueTypesStringLiteralServer) *ValueTypesStringLiteralServerTransport { + return &ValueTypesStringLiteralServerTransport{srv: srv} +} + +// ValueTypesStringLiteralServerTransport connects instances of valuetypesgroup.ValueTypesStringLiteralClient to instances of ValueTypesStringLiteralServer. +// Don't use this type directly, use NewValueTypesStringLiteralServerTransport instead. +type ValueTypesStringLiteralServerTransport struct { + srv *ValueTypesStringLiteralServer +} + +// Do implements the policy.Transporter interface for ValueTypesStringLiteralServerTransport. +func (v *ValueTypesStringLiteralServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesStringLiteralServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesStringLiteralServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesStringLiteralServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesStringLiteralClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesStringLiteralClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesStringLiteralServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).StringLiteralProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesStringLiteralServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.StringLiteralProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesStringLiteralServerTransport +var valueTypesStringLiteralServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunionenumvalue_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunionenumvalue_server.go new file mode 100644 index 000000000000..b9dcd428ed47 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunionenumvalue_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesUnionEnumValueServer is a fake server for instances of the valuetypesgroup.ValueTypesUnionEnumValueClient type. +type ValueTypesUnionEnumValueServer struct { + // Get is the fake for method ValueTypesUnionEnumValueClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesUnionEnumValueClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesUnionEnumValueClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesUnionEnumValueClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.UnionEnumValueProperty, options *valuetypesgroup.ValueTypesUnionEnumValueClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesUnionEnumValueClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesUnionEnumValueServerTransport creates a new instance of ValueTypesUnionEnumValueServerTransport with the provided implementation. +// The returned ValueTypesUnionEnumValueServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesUnionEnumValueClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesUnionEnumValueServerTransport(srv *ValueTypesUnionEnumValueServer) *ValueTypesUnionEnumValueServerTransport { + return &ValueTypesUnionEnumValueServerTransport{srv: srv} +} + +// ValueTypesUnionEnumValueServerTransport connects instances of valuetypesgroup.ValueTypesUnionEnumValueClient to instances of ValueTypesUnionEnumValueServer. +// Don't use this type directly, use NewValueTypesUnionEnumValueServerTransport instead. +type ValueTypesUnionEnumValueServerTransport struct { + srv *ValueTypesUnionEnumValueServer +} + +// Do implements the policy.Transporter interface for ValueTypesUnionEnumValueServerTransport. +func (v *ValueTypesUnionEnumValueServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesUnionEnumValueServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesUnionEnumValueServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesUnionEnumValueServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesUnionEnumValueClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesUnionEnumValueClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesUnionEnumValueServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).UnionEnumValueProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesUnionEnumValueServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.UnionEnumValueProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesUnionEnumValueServerTransport +var valueTypesUnionEnumValueServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunionfloatliteral_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunionfloatliteral_server.go new file mode 100644 index 000000000000..281e4b9034de --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunionfloatliteral_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesUnionFloatLiteralServer is a fake server for instances of the valuetypesgroup.ValueTypesUnionFloatLiteralClient type. +type ValueTypesUnionFloatLiteralServer struct { + // Get is the fake for method ValueTypesUnionFloatLiteralClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesUnionFloatLiteralClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesUnionFloatLiteralClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesUnionFloatLiteralClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.UnionFloatLiteralProperty, options *valuetypesgroup.ValueTypesUnionFloatLiteralClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesUnionFloatLiteralClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesUnionFloatLiteralServerTransport creates a new instance of ValueTypesUnionFloatLiteralServerTransport with the provided implementation. +// The returned ValueTypesUnionFloatLiteralServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesUnionFloatLiteralClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesUnionFloatLiteralServerTransport(srv *ValueTypesUnionFloatLiteralServer) *ValueTypesUnionFloatLiteralServerTransport { + return &ValueTypesUnionFloatLiteralServerTransport{srv: srv} +} + +// ValueTypesUnionFloatLiteralServerTransport connects instances of valuetypesgroup.ValueTypesUnionFloatLiteralClient to instances of ValueTypesUnionFloatLiteralServer. +// Don't use this type directly, use NewValueTypesUnionFloatLiteralServerTransport instead. +type ValueTypesUnionFloatLiteralServerTransport struct { + srv *ValueTypesUnionFloatLiteralServer +} + +// Do implements the policy.Transporter interface for ValueTypesUnionFloatLiteralServerTransport. +func (v *ValueTypesUnionFloatLiteralServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesUnionFloatLiteralServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesUnionFloatLiteralServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesUnionFloatLiteralServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesUnionFloatLiteralClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesUnionFloatLiteralClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesUnionFloatLiteralServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).UnionFloatLiteralProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesUnionFloatLiteralServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.UnionFloatLiteralProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesUnionFloatLiteralServerTransport +var valueTypesUnionFloatLiteralServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunionintliteral_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunionintliteral_server.go new file mode 100644 index 000000000000..30a6dccc1c74 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunionintliteral_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesUnionIntLiteralServer is a fake server for instances of the valuetypesgroup.ValueTypesUnionIntLiteralClient type. +type ValueTypesUnionIntLiteralServer struct { + // Get is the fake for method ValueTypesUnionIntLiteralClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesUnionIntLiteralClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesUnionIntLiteralClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesUnionIntLiteralClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.UnionIntLiteralProperty, options *valuetypesgroup.ValueTypesUnionIntLiteralClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesUnionIntLiteralClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesUnionIntLiteralServerTransport creates a new instance of ValueTypesUnionIntLiteralServerTransport with the provided implementation. +// The returned ValueTypesUnionIntLiteralServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesUnionIntLiteralClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesUnionIntLiteralServerTransport(srv *ValueTypesUnionIntLiteralServer) *ValueTypesUnionIntLiteralServerTransport { + return &ValueTypesUnionIntLiteralServerTransport{srv: srv} +} + +// ValueTypesUnionIntLiteralServerTransport connects instances of valuetypesgroup.ValueTypesUnionIntLiteralClient to instances of ValueTypesUnionIntLiteralServer. +// Don't use this type directly, use NewValueTypesUnionIntLiteralServerTransport instead. +type ValueTypesUnionIntLiteralServerTransport struct { + srv *ValueTypesUnionIntLiteralServer +} + +// Do implements the policy.Transporter interface for ValueTypesUnionIntLiteralServerTransport. +func (v *ValueTypesUnionIntLiteralServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesUnionIntLiteralServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesUnionIntLiteralServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesUnionIntLiteralServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesUnionIntLiteralClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesUnionIntLiteralClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesUnionIntLiteralServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).UnionIntLiteralProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesUnionIntLiteralServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.UnionIntLiteralProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesUnionIntLiteralServerTransport +var valueTypesUnionIntLiteralServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunionstringliteral_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunionstringliteral_server.go new file mode 100644 index 000000000000..ee50aaba921e --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunionstringliteral_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesUnionStringLiteralServer is a fake server for instances of the valuetypesgroup.ValueTypesUnionStringLiteralClient type. +type ValueTypesUnionStringLiteralServer struct { + // Get is the fake for method ValueTypesUnionStringLiteralClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesUnionStringLiteralClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesUnionStringLiteralClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesUnionStringLiteralClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.UnionStringLiteralProperty, options *valuetypesgroup.ValueTypesUnionStringLiteralClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesUnionStringLiteralClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesUnionStringLiteralServerTransport creates a new instance of ValueTypesUnionStringLiteralServerTransport with the provided implementation. +// The returned ValueTypesUnionStringLiteralServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesUnionStringLiteralClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesUnionStringLiteralServerTransport(srv *ValueTypesUnionStringLiteralServer) *ValueTypesUnionStringLiteralServerTransport { + return &ValueTypesUnionStringLiteralServerTransport{srv: srv} +} + +// ValueTypesUnionStringLiteralServerTransport connects instances of valuetypesgroup.ValueTypesUnionStringLiteralClient to instances of ValueTypesUnionStringLiteralServer. +// Don't use this type directly, use NewValueTypesUnionStringLiteralServerTransport instead. +type ValueTypesUnionStringLiteralServerTransport struct { + srv *ValueTypesUnionStringLiteralServer +} + +// Do implements the policy.Transporter interface for ValueTypesUnionStringLiteralServerTransport. +func (v *ValueTypesUnionStringLiteralServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesUnionStringLiteralServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesUnionStringLiteralServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesUnionStringLiteralServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesUnionStringLiteralClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesUnionStringLiteralClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesUnionStringLiteralServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).UnionStringLiteralProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesUnionStringLiteralServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.UnionStringLiteralProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesUnionStringLiteralServerTransport +var valueTypesUnionStringLiteralServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunknownarray_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunknownarray_server.go new file mode 100644 index 000000000000..3bc2832bb321 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunknownarray_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesUnknownArrayServer is a fake server for instances of the valuetypesgroup.ValueTypesUnknownArrayClient type. +type ValueTypesUnknownArrayServer struct { + // Get is the fake for method ValueTypesUnknownArrayClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesUnknownArrayClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesUnknownArrayClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesUnknownArrayClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.UnknownArrayProperty, options *valuetypesgroup.ValueTypesUnknownArrayClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesUnknownArrayClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesUnknownArrayServerTransport creates a new instance of ValueTypesUnknownArrayServerTransport with the provided implementation. +// The returned ValueTypesUnknownArrayServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesUnknownArrayClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesUnknownArrayServerTransport(srv *ValueTypesUnknownArrayServer) *ValueTypesUnknownArrayServerTransport { + return &ValueTypesUnknownArrayServerTransport{srv: srv} +} + +// ValueTypesUnknownArrayServerTransport connects instances of valuetypesgroup.ValueTypesUnknownArrayClient to instances of ValueTypesUnknownArrayServer. +// Don't use this type directly, use NewValueTypesUnknownArrayServerTransport instead. +type ValueTypesUnknownArrayServerTransport struct { + srv *ValueTypesUnknownArrayServer +} + +// Do implements the policy.Transporter interface for ValueTypesUnknownArrayServerTransport. +func (v *ValueTypesUnknownArrayServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesUnknownArrayServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesUnknownArrayServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesUnknownArrayServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesUnknownArrayClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesUnknownArrayClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesUnknownArrayServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).UnknownArrayProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesUnknownArrayServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.UnknownArrayProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesUnknownArrayServerTransport +var valueTypesUnknownArrayServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunknowndict_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunknowndict_server.go new file mode 100644 index 000000000000..069ee0434700 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunknowndict_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesUnknownDictServer is a fake server for instances of the valuetypesgroup.ValueTypesUnknownDictClient type. +type ValueTypesUnknownDictServer struct { + // Get is the fake for method ValueTypesUnknownDictClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesUnknownDictClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesUnknownDictClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesUnknownDictClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.UnknownDictProperty, options *valuetypesgroup.ValueTypesUnknownDictClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesUnknownDictClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesUnknownDictServerTransport creates a new instance of ValueTypesUnknownDictServerTransport with the provided implementation. +// The returned ValueTypesUnknownDictServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesUnknownDictClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesUnknownDictServerTransport(srv *ValueTypesUnknownDictServer) *ValueTypesUnknownDictServerTransport { + return &ValueTypesUnknownDictServerTransport{srv: srv} +} + +// ValueTypesUnknownDictServerTransport connects instances of valuetypesgroup.ValueTypesUnknownDictClient to instances of ValueTypesUnknownDictServer. +// Don't use this type directly, use NewValueTypesUnknownDictServerTransport instead. +type ValueTypesUnknownDictServerTransport struct { + srv *ValueTypesUnknownDictServer +} + +// Do implements the policy.Transporter interface for ValueTypesUnknownDictServerTransport. +func (v *ValueTypesUnknownDictServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesUnknownDictServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesUnknownDictServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesUnknownDictServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesUnknownDictClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesUnknownDictClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesUnknownDictServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).UnknownDictProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesUnknownDictServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.UnknownDictProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesUnknownDictServerTransport +var valueTypesUnknownDictServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunknownint_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunknownint_server.go new file mode 100644 index 000000000000..9d394493919d --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunknownint_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesUnknownIntServer is a fake server for instances of the valuetypesgroup.ValueTypesUnknownIntClient type. +type ValueTypesUnknownIntServer struct { + // Get is the fake for method ValueTypesUnknownIntClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesUnknownIntClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesUnknownIntClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesUnknownIntClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.UnknownIntProperty, options *valuetypesgroup.ValueTypesUnknownIntClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesUnknownIntClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesUnknownIntServerTransport creates a new instance of ValueTypesUnknownIntServerTransport with the provided implementation. +// The returned ValueTypesUnknownIntServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesUnknownIntClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesUnknownIntServerTransport(srv *ValueTypesUnknownIntServer) *ValueTypesUnknownIntServerTransport { + return &ValueTypesUnknownIntServerTransport{srv: srv} +} + +// ValueTypesUnknownIntServerTransport connects instances of valuetypesgroup.ValueTypesUnknownIntClient to instances of ValueTypesUnknownIntServer. +// Don't use this type directly, use NewValueTypesUnknownIntServerTransport instead. +type ValueTypesUnknownIntServerTransport struct { + srv *ValueTypesUnknownIntServer +} + +// Do implements the policy.Transporter interface for ValueTypesUnknownIntServerTransport. +func (v *ValueTypesUnknownIntServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesUnknownIntServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesUnknownIntServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesUnknownIntServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesUnknownIntClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesUnknownIntClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesUnknownIntServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).UnknownIntProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesUnknownIntServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.UnknownIntProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesUnknownIntServerTransport +var valueTypesUnknownIntServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunknownstring_server.go b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunknownstring_server.go new file mode 100644 index 000000000000..cabdc9084f17 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/fake/zz_valuetypesunknownstring_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "valuetypesgroup" +) + +// ValueTypesUnknownStringServer is a fake server for instances of the valuetypesgroup.ValueTypesUnknownStringClient type. +type ValueTypesUnknownStringServer struct { + // Get is the fake for method ValueTypesUnknownStringClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *valuetypesgroup.ValueTypesUnknownStringClientGetOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesUnknownStringClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ValueTypesUnknownStringClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body valuetypesgroup.UnknownStringProperty, options *valuetypesgroup.ValueTypesUnknownStringClientPutOptions) (resp azfake.Responder[valuetypesgroup.ValueTypesUnknownStringClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewValueTypesUnknownStringServerTransport creates a new instance of ValueTypesUnknownStringServerTransport with the provided implementation. +// The returned ValueTypesUnknownStringServerTransport instance is connected to an instance of valuetypesgroup.ValueTypesUnknownStringClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewValueTypesUnknownStringServerTransport(srv *ValueTypesUnknownStringServer) *ValueTypesUnknownStringServerTransport { + return &ValueTypesUnknownStringServerTransport{srv: srv} +} + +// ValueTypesUnknownStringServerTransport connects instances of valuetypesgroup.ValueTypesUnknownStringClient to instances of ValueTypesUnknownStringServer. +// Don't use this type directly, use NewValueTypesUnknownStringServerTransport instead. +type ValueTypesUnknownStringServerTransport struct { + srv *ValueTypesUnknownStringServer +} + +// Do implements the policy.Transporter interface for ValueTypesUnknownStringServerTransport. +func (v *ValueTypesUnknownStringServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *ValueTypesUnknownStringServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if valueTypesUnknownStringServerTransportInterceptor != nil { + res.resp, res.err, intercepted = valueTypesUnknownStringServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ValueTypesUnknownStringClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "ValueTypesUnknownStringClient.Put": + res.resp, res.err = v.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *ValueTypesUnknownStringServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := v.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).UnknownStringProperty, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *ValueTypesUnknownStringServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if v.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[valuetypesgroup.UnknownStringProperty](req) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ValueTypesUnknownStringServerTransport +var valueTypesUnknownStringServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/property/valuetypesgroup/go.mod b/test/http-specs/type/property/valuetypesgroup/go.mod new file mode 100644 index 000000000000..5c134a66d44c --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/go.mod @@ -0,0 +1,17 @@ +module valuetypesgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/type/property/valuetypesgroup/go.sum b/test/http-specs/type/property/valuetypesgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/type/property/valuetypesgroup/testdata/_metadata.json b/test/http-specs/type/property/valuetypesgroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypesboolean_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypesboolean_client_test.go new file mode 100644 index 000000000000..24f6f1aa95ef --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypesboolean_client_test.go @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestValueTypesBooleanClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesBooleanClient().Get(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.True(t, *resp.Property) +} + +func TestValueTypesBooleanClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesBooleanClient().Put(context.Background(), valuetypesgroup.BooleanProperty{ + Property: to.Ptr(true), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypesbooleanliteral_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypesbooleanliteral_client_test.go new file mode 100644 index 000000000000..2c5ca5a2267d --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypesbooleanliteral_client_test.go @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/stretchr/testify/require" +) + +func TestValueTypesBooleanLiteralClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesBooleanLiteralClient().Get(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.True(t, *resp.Property) +} + +func TestValueTypesBooleanLiteralClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesBooleanLiteralClient().Put(context.Background(), valuetypesgroup.BooleanLiteralProperty{}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypesbytes_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypesbytes_client_test.go new file mode 100644 index 000000000000..5e88fc2d6099 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypesbytes_client_test.go @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/stretchr/testify/require" +) + +func TestValueTypesBytesClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesBytesClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, []byte("hello, world!"), resp.Property) +} + +func TestValueTypesBytesClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesBytesClient().Put(context.Background(), valuetypesgroup.BytesProperty{ + Property: []byte("hello, world!"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypescollectionsint_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypescollectionsint_client_test.go new file mode 100644 index 000000000000..d2e98dc28b2d --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypescollectionsint_client_test.go @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/stretchr/testify/require" +) + +func TestValueTypesCollectionsIntClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesCollectionsIntClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, []int32{1, 2}, resp.Property) +} + +func TestValueTypesCollectionsIntClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesCollectionsIntClient().Put(context.Background(), valuetypesgroup.CollectionsIntProperty{ + Property: []int32{1, 2}, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypescollectionsmodel_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypescollectionsmodel_client_test.go new file mode 100644 index 000000000000..e80614d6cda0 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypescollectionsmodel_client_test.go @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestValueTypesCollectionsModelClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesCollectionsModelClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, []valuetypesgroup.InnerModel{ + { + Property: to.Ptr("hello"), + }, + { + Property: to.Ptr("world"), + }, + }, resp.Property) +} + +func TestValueTypesCollectionsModelClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesCollectionsModelClient().Put(context.Background(), valuetypesgroup.CollectionsModelProperty{ + Property: []valuetypesgroup.InnerModel{ + { + Property: to.Ptr("hello"), + }, + { + Property: to.Ptr("world"), + }, + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypescollectionsstring_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypescollectionsstring_client_test.go new file mode 100644 index 000000000000..ab3be7f0ef6c --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypescollectionsstring_client_test.go @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/stretchr/testify/require" +) + +func TestValueTypesCollectionsStringClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesCollectionsStringClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, []string{"hello", "world"}, resp.Property) +} + +func TestValueTypesCollectionsStringClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesCollectionsStringClient().Put(context.Background(), valuetypesgroup.CollectionsStringProperty{ + Property: []string{"hello", "world"}, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypesdatetime_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypesdatetime_client_test.go new file mode 100644 index 000000000000..967a3790a7e6 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypesdatetime_client_test.go @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "time" + "valuetypesgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestValueTypesDatetimeClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesDatetimeClient().Get(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.EqualValues(t, time.Date(2022, 8, 26, 18, 38, 0, 0, time.UTC), *resp.Property) +} + +func TestValueTypesDatetimeClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesDatetimeClient().Put(context.Background(), valuetypesgroup.DatetimeProperty{ + Property: to.Ptr(time.Date(2022, 8, 26, 18, 38, 0, 0, time.UTC)), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypesdecimal128_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypesdecimal128_client_test.go new file mode 100644 index 000000000000..0dd42afa026d --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypesdecimal128_client_test.go @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestValueTypesDecimal128Client_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesDecimal128Client().Get(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.Equal(t, 0.33333, *resp.Property) +} + +func TestValueTypesDecimal128Client_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesDecimal128Client().Put(context.Background(), valuetypesgroup.Decimal128Property{ + Property: to.Ptr[float64](0.33333), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypesdecimal_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypesdecimal_client_test.go new file mode 100644 index 000000000000..42a48b1d0dee --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypesdecimal_client_test.go @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestValueTypesDecimalClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesDecimalClient().Get(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.Equal(t, 0.33333, *resp.Property) +} + +func TestValueTypesDecimalClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesDecimalClient().Put(context.Background(), valuetypesgroup.DecimalProperty{ + Property: to.Ptr[float64](0.33333), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypesdictionarystring_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypesdictionarystring_client_test.go new file mode 100644 index 000000000000..9e5cb6cba301 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypesdictionarystring_client_test.go @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestValueTypesDictionaryStringClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesDictionaryStringClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, map[string]*string{ + "k1": to.Ptr("hello"), + "k2": to.Ptr("world"), + }, resp.Property) +} + +func TestValueTypesDictionaryStringClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesDictionaryStringClient().Put(context.Background(), valuetypesgroup.DictionaryStringProperty{ + Property: map[string]*string{ + "k1": to.Ptr("hello"), + "k2": to.Ptr("world"), + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypesduration_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypesduration_client_test.go new file mode 100644 index 000000000000..f184afed6d24 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypesduration_client_test.go @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestValueTypesDurationClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesDurationClient().Get(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.EqualValues(t, "P123DT22H14M12.011S", *resp.Property) +} + +func TestValueTypesDurationClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesDurationClient().Put(context.Background(), valuetypesgroup.DurationProperty{ + Property: to.Ptr("P123DT22H14M12.011S"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypesenum_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypesenum_client_test.go new file mode 100644 index 000000000000..d21b8ecf8fdc --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypesenum_client_test.go @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestValueTypesEnumClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesEnumClient().Get(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.Equal(t, valuetypesgroup.FixedInnerEnumValueOne, *resp.Property) +} + +func TestValueTypesEnumClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesEnumClient().Put(context.Background(), valuetypesgroup.EnumProperty{ + Property: to.Ptr(valuetypesgroup.FixedInnerEnumValueOne), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypesextensibleenum_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypesextensibleenum_client_test.go new file mode 100644 index 000000000000..5039bc2ff56f --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypesextensibleenum_client_test.go @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestValueTypesExtensibleEnumClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesExtensibleEnumClient().Get(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.Equal(t, valuetypesgroup.InnerEnum("UnknownValue"), *resp.Property) +} + +func TestValueTypesExtensibleEnumClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesExtensibleEnumClient().Put(context.Background(), valuetypesgroup.ExtensibleEnumProperty{ + Property: to.Ptr(valuetypesgroup.InnerEnum("UnknownValue")), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypesfloat_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypesfloat_client_test.go new file mode 100644 index 000000000000..ac09d219abc0 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypesfloat_client_test.go @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestValueTypesFloatClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesFloatClient().Get(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.Equal(t, float32(43.125), *resp.Property) +} + +func TestValueTypesFloatClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesFloatClient().Put(context.Background(), valuetypesgroup.FloatProperty{ + Property: to.Ptr[float32](43.125), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypesfloatliteral_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypesfloatliteral_client_test.go new file mode 100644 index 000000000000..5381d83c4cbf --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypesfloatliteral_client_test.go @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestValueTypesFloatLiteralClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesFloatLiteralClient().Get(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.Equal(t, float32(43.125), *resp.Property) +} + +func TestValueTypesFloatLiteralClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesFloatLiteralClient().Put(context.Background(), valuetypesgroup.FloatLiteralProperty{ + Property: to.Ptr[float32](43.125), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypesint_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypesint_client_test.go new file mode 100644 index 000000000000..69c61e1dd7a2 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypesint_client_test.go @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestValueTypesIntClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesIntClient().Get(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.Equal(t, int32(42), *resp.Property) +} + +func TestValueTypesIntClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesIntClient().Put(context.Background(), valuetypesgroup.IntProperty{ + Property: to.Ptr[int32](42), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypesintliteral_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypesintliteral_client_test.go new file mode 100644 index 000000000000..5ce59da977c8 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypesintliteral_client_test.go @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/stretchr/testify/require" +) + +func TestValueTypesIntLiteralClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesIntLiteralClient().Get(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.Equal(t, int32(42), *resp.Property) +} + +func TestValueTypesIntLiteralClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesIntLiteralClient().Put(context.Background(), valuetypesgroup.IntLiteralProperty{}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypesmodel_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypesmodel_client_test.go new file mode 100644 index 000000000000..557ff70f3896 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypesmodel_client_test.go @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestValueTypesModelClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesModelClient().Get(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.Equal(t, valuetypesgroup.InnerModel{ + Property: to.Ptr("hello"), + }, *resp.Property) +} + +func TestValueTypesModelClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesModelClient().Put(context.Background(), valuetypesgroup.ModelProperty{ + Property: &valuetypesgroup.InnerModel{ + Property: to.Ptr("hello"), + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypesnever_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypesnever_client_test.go new file mode 100644 index 000000000000..1fcbd6a889c7 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypesnever_client_test.go @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/stretchr/testify/require" +) + +func TestValueTypesNeverClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesNeverClient().Get(context.Background(), nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestValueTypesNeverClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesNeverClient().Put(context.Background(), valuetypesgroup.NeverProperty{}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypesstring_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypesstring_client_test.go new file mode 100644 index 000000000000..746e526014c9 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypesstring_client_test.go @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestValueTypesStringClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesStringClient().Get(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.EqualValues(t, "hello", *resp.Property) +} + +func TestValueTypesStringClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesStringClient().Put(context.Background(), valuetypesgroup.StringProperty{ + Property: to.Ptr("hello"), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypesstringliteral_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypesstringliteral_client_test.go new file mode 100644 index 000000000000..62a02e6cf1ad --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypesstringliteral_client_test.go @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/stretchr/testify/require" +) + +func TestValueTypesStringLiteralClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesStringLiteralClient().Get(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.EqualValues(t, "hello", *resp.Property) +} + +func TestValueTypesStringLiteralClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesStringLiteralClient().Put(context.Background(), valuetypesgroup.StringLiteralProperty{}, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypesunionenumvalue_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypesunionenumvalue_client_test.go new file mode 100644 index 000000000000..69820dbad3a6 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypesunionenumvalue_client_test.go @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestValueTypesUnionEnumValueClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesUnionEnumValueClient().Get(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.Equal(t, valuetypesgroup.ExtendedEnumEnumValue2, *resp.Property) +} + +func TestValueTypesUnionEnumValueClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesUnionEnumValueClient().Put(context.Background(), valuetypesgroup.UnionEnumValueProperty{ + Property: to.Ptr(valuetypesgroup.ExtendedEnumEnumValue2), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypesunionfloatliteral_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypesunionfloatliteral_client_test.go new file mode 100644 index 000000000000..6e0f807548f5 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypesunionfloatliteral_client_test.go @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestValueTypesUnionFloatLiteralClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesUnionFloatLiteralClient().Get(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.Equal(t, valuetypesgroup.UnionFloatLiteralPropertyProperty46875, *resp.Property) +} + +func TestValueTypesUnionFloatLiteralClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesUnionFloatLiteralClient().Put(context.Background(), valuetypesgroup.UnionFloatLiteralProperty{ + Property: to.Ptr(valuetypesgroup.UnionFloatLiteralPropertyProperty46875), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypesunionintliteral_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypesunionintliteral_client_test.go new file mode 100644 index 000000000000..c725ab275ad4 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypesunionintliteral_client_test.go @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestValueTypesUnionIntLiteralClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesUnionIntLiteralClient().Get(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.Equal(t, valuetypesgroup.UnionIntLiteralPropertyProperty42, *resp.Property) +} + +func TestValueTypesUnionIntLiteralClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesUnionIntLiteralClient().Put(context.Background(), valuetypesgroup.UnionIntLiteralProperty{ + Property: to.Ptr(valuetypesgroup.UnionIntLiteralPropertyProperty42), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypesunionstringliteral_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypesunionstringliteral_client_test.go new file mode 100644 index 000000000000..b13ccd996a58 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypesunionstringliteral_client_test.go @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func TestValueTypesUnionStringLiteralClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesUnionStringLiteralClient().Get(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Property) + require.Equal(t, valuetypesgroup.UnionStringLiteralPropertyPropertyWorld, *resp.Property) +} + +func TestValueTypesUnionStringLiteralClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesUnionStringLiteralClient().Put(context.Background(), valuetypesgroup.UnionStringLiteralProperty{ + Property: to.Ptr(valuetypesgroup.UnionStringLiteralPropertyPropertyWorld), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypesunknownarray_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypesunknownarray_client_test.go new file mode 100644 index 000000000000..345394c20cd9 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypesunknownarray_client_test.go @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/stretchr/testify/require" +) + +func TestValueTypesUnknownArrayClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesUnknownArrayClient().Get(context.Background(), nil) + require.NoError(t, err) + require.Equal(t, []any{"hello", "world"}, resp.Property) +} + +func TestValueTypesUnknownArrayClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesUnknownArrayClient().Put(context.Background(), valuetypesgroup.UnknownArrayProperty{ + Property: []any{"hello", "world"}, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypesunknowndict_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypesunknowndict_client_test.go new file mode 100644 index 000000000000..6099f88e70ca --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypesunknowndict_client_test.go @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/stretchr/testify/require" +) + +func TestValueTypesUnknownDictClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesUnknownDictClient().Get(context.Background(), nil) + require.NoError(t, err) + require.Equal(t, map[string]any{ + "k1": "hello", + "k2": float64(42), + }, resp.Property) +} + +func TestValueTypesUnknownDictClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesUnknownDictClient().Put(context.Background(), valuetypesgroup.UnknownDictProperty{ + Property: map[string]any{ + "k1": "hello", + "k2": float64(42), + }, + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypesunknownint_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypesunknownint_client_test.go new file mode 100644 index 000000000000..d79694e5cab3 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypesunknownint_client_test.go @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/stretchr/testify/require" +) + +func TestValueTypesUnknownIntClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesUnknownIntClient().Get(context.Background(), nil) + require.NoError(t, err) + require.Equal(t, float64(42), resp.Property) +} + +func TestValueTypesUnknownIntClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesUnknownIntClient().Put(context.Background(), valuetypesgroup.UnknownIntProperty{ + Property: float64(42), + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/valuetypesunknownstring_client_test.go b/test/http-specs/type/property/valuetypesgroup/valuetypesunknownstring_client_test.go new file mode 100644 index 000000000000..ed94ba632718 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/valuetypesunknownstring_client_test.go @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package valuetypesgroup_test + +import ( + "context" + "testing" + "valuetypesgroup" + + "github.com/stretchr/testify/require" +) + +func TestValueTypesUnknownStringClient_Get(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesUnknownStringClient().Get(context.Background(), nil) + require.NoError(t, err) + require.Equal(t, "hello", resp.Property) +} + +func TestValueTypesUnknownStringClient_Put(t *testing.T) { + client, err := valuetypesgroup.NewValueTypesClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewValueTypesUnknownStringClient().Put(context.Background(), valuetypesgroup.UnknownStringProperty{ + Property: "hello", + }, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_constants.go b/test/http-specs/type/property/valuetypesgroup/zz_constants.go new file mode 100644 index 000000000000..ea9398b5311f --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_constants.go @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +type ExtendedEnum string + +const ( + ExtendedEnumEnumValue2 ExtendedEnum = "value2" +) + +// PossibleExtendedEnumValues returns the possible values for the ExtendedEnum const type. +func PossibleExtendedEnumValues() []ExtendedEnum { + return []ExtendedEnum{ + ExtendedEnumEnumValue2, + } +} + +// FixedInnerEnum - Enum that will be used as a property for model EnumProperty. Non-extensible. +type FixedInnerEnum string + +const ( + // FixedInnerEnumValueOne - First value. + FixedInnerEnumValueOne FixedInnerEnum = "ValueOne" + // FixedInnerEnumValueTwo - Second value. + FixedInnerEnumValueTwo FixedInnerEnum = "ValueTwo" +) + +// PossibleFixedInnerEnumValues returns the possible values for the FixedInnerEnum const type. +func PossibleFixedInnerEnumValues() []FixedInnerEnum { + return []FixedInnerEnum{ + FixedInnerEnumValueOne, + FixedInnerEnumValueTwo, + } +} + +// InnerEnum - Enum that will be used as a property for model EnumProperty. Extensible. +type InnerEnum string + +const ( + // InnerEnumValueOne - First value. + InnerEnumValueOne InnerEnum = "ValueOne" + // InnerEnumValueTwo - Second value. + InnerEnumValueTwo InnerEnum = "ValueTwo" +) + +// PossibleInnerEnumValues returns the possible values for the InnerEnum const type. +func PossibleInnerEnumValues() []InnerEnum { + return []InnerEnum{ + InnerEnumValueOne, + InnerEnumValueTwo, + } +} + +type UnionFloatLiteralPropertyProperty float32 + +const ( + UnionFloatLiteralPropertyProperty43125 UnionFloatLiteralPropertyProperty = 43.125 + UnionFloatLiteralPropertyProperty46875 UnionFloatLiteralPropertyProperty = 46.875 +) + +// PossibleUnionFloatLiteralPropertyPropertyValues returns the possible values for the UnionFloatLiteralPropertyProperty const type. +func PossibleUnionFloatLiteralPropertyPropertyValues() []UnionFloatLiteralPropertyProperty { + return []UnionFloatLiteralPropertyProperty{ + UnionFloatLiteralPropertyProperty43125, + UnionFloatLiteralPropertyProperty46875, + } +} + +type UnionIntLiteralPropertyProperty int32 + +const ( + UnionIntLiteralPropertyProperty42 UnionIntLiteralPropertyProperty = 42 + UnionIntLiteralPropertyProperty43 UnionIntLiteralPropertyProperty = 43 +) + +// PossibleUnionIntLiteralPropertyPropertyValues returns the possible values for the UnionIntLiteralPropertyProperty const type. +func PossibleUnionIntLiteralPropertyPropertyValues() []UnionIntLiteralPropertyProperty { + return []UnionIntLiteralPropertyProperty{ + UnionIntLiteralPropertyProperty42, + UnionIntLiteralPropertyProperty43, + } +} + +type UnionStringLiteralPropertyProperty string + +const ( + UnionStringLiteralPropertyPropertyHello UnionStringLiteralPropertyProperty = "hello" + UnionStringLiteralPropertyPropertyWorld UnionStringLiteralPropertyProperty = "world" +) + +// PossibleUnionStringLiteralPropertyPropertyValues returns the possible values for the UnionStringLiteralPropertyProperty const type. +func PossibleUnionStringLiteralPropertyPropertyValues() []UnionStringLiteralPropertyProperty { + return []UnionStringLiteralPropertyProperty{ + UnionStringLiteralPropertyPropertyHello, + UnionStringLiteralPropertyPropertyWorld, + } +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_models.go b/test/http-specs/type/property/valuetypesgroup/zz_models.go new file mode 100644 index 000000000000..f0a5de0bb1ba --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_models.go @@ -0,0 +1,191 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import "time" + +// BooleanLiteralProperty - Model with a boolean literal property. +type BooleanLiteralProperty struct { + // CONSTANT; Property + // Field has constant value true, any specified value is ignored. + Property *bool +} + +// BooleanProperty - Model with a boolean property +type BooleanProperty struct { + // REQUIRED; Property + Property *bool +} + +// BytesProperty - Model with a bytes property +type BytesProperty struct { + // REQUIRED; Property + Property []byte +} + +// CollectionsIntProperty - Model with collection int properties +type CollectionsIntProperty struct { + // REQUIRED; Property + Property []int32 +} + +// CollectionsModelProperty - Model with collection model properties +type CollectionsModelProperty struct { + // REQUIRED; Property + Property []InnerModel +} + +// CollectionsStringProperty - Model with collection string properties +type CollectionsStringProperty struct { + // REQUIRED; Property + Property []string +} + +// DatetimeProperty - Model with a datetime property +type DatetimeProperty struct { + // REQUIRED; Property + Property *time.Time +} + +// Decimal128Property - Model with a decimal128 property +type Decimal128Property struct { + // REQUIRED; Property + Property *float64 +} + +// DecimalProperty - Model with a decimal property +type DecimalProperty struct { + // REQUIRED; Property + Property *float64 +} + +// DictionaryStringProperty - Model with dictionary string properties +type DictionaryStringProperty struct { + // REQUIRED; Property + Property map[string]*string +} + +// DurationProperty - Model with a duration property +type DurationProperty struct { + // REQUIRED; Property + Property *string +} + +// EnumProperty - Model with enum properties +type EnumProperty struct { + // REQUIRED; Property + Property *FixedInnerEnum +} + +// ExtensibleEnumProperty - Model with extensible enum properties +type ExtensibleEnumProperty struct { + // REQUIRED; Property + Property *InnerEnum +} + +// FloatLiteralProperty - Model with a float literal property. +type FloatLiteralProperty struct { + // CONSTANT; Property + // Field has constant value 43.125, any specified value is ignored. + Property *float32 +} + +// FloatProperty - Model with a float property +type FloatProperty struct { + // REQUIRED; Property + Property *float32 +} + +// InnerModel - Inner model. Will be a property type for ModelWithModelProperties +type InnerModel struct { + // REQUIRED; Required string property + Property *string +} + +// IntLiteralProperty - Model with a int literal property. +type IntLiteralProperty struct { + // CONSTANT; Property + // Field has constant value 42, any specified value is ignored. + Property *int32 +} + +// IntProperty - Model with a int property +type IntProperty struct { + // REQUIRED; Property + Property *int32 +} + +// ModelProperty - Model with model properties +type ModelProperty struct { + // REQUIRED; Property + Property *InnerModel +} + +// NeverProperty - Model with a property never. (This property should not be included). +type NeverProperty struct { +} + +// StringLiteralProperty - Model with a string literal property. +type StringLiteralProperty struct { + // CONSTANT; Property + // Field has constant value "hello", any specified value is ignored. + Property *string +} + +// StringProperty - Model with a string property +type StringProperty struct { + // REQUIRED; Property + Property *string +} + +// UnionEnumValueProperty - Template type for testing models with specific properties. Pass in the type of the property you +// are looking for +type UnionEnumValueProperty struct { + // CONSTANT; Property + // Field has constant value ExtendedEnumEnumValue2, any specified value is ignored. + Property *ExtendedEnum +} + +// UnionFloatLiteralProperty - Model with a union of float literal as property. +type UnionFloatLiteralProperty struct { + // REQUIRED; Property + Property *UnionFloatLiteralPropertyProperty +} + +// UnionIntLiteralProperty - Model with a union of int literal as property. +type UnionIntLiteralProperty struct { + // REQUIRED; Property + Property *UnionIntLiteralPropertyProperty +} + +// UnionStringLiteralProperty - Model with a union of string literal as property. +type UnionStringLiteralProperty struct { + // REQUIRED; Property + Property *UnionStringLiteralPropertyProperty +} + +// UnknownArrayProperty - Model with a property unknown, and the data is an array. +type UnknownArrayProperty struct { + // REQUIRED; Property + Property any +} + +// UnknownDictProperty - Model with a property unknown, and the data is a dictionnary. +type UnknownDictProperty struct { + // REQUIRED; Property + Property any +} + +// UnknownIntProperty - Model with a property unknown, and the data is a int32. +type UnknownIntProperty struct { + // REQUIRED; Property + Property any +} + +// UnknownStringProperty - Model with a property unknown, and the data is a string. +type UnknownStringProperty struct { + // REQUIRED; Property + Property any +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_models_serde.go b/test/http-specs/type/property/valuetypesgroup/zz_models_serde.go new file mode 100644 index 000000000000..475bb0182f9b --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_models_serde.go @@ -0,0 +1,870 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type BooleanLiteralProperty. +func (b BooleanLiteralProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["property"] = true + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BooleanLiteralProperty. +func (b *BooleanLiteralProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &b.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BooleanProperty. +func (b BooleanProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "property", b.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BooleanProperty. +func (b *BooleanProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &b.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BytesProperty. +func (b BytesProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateByteArray(objectMap, "property", b.Property, func() any { + return runtime.EncodeByteArray(b.Property, runtime.Base64StdFormat) + }) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BytesProperty. +func (b *BytesProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &b.Property, runtime.Base64StdFormat) + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CollectionsIntProperty. +func (c CollectionsIntProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "property", c.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CollectionsIntProperty. +func (c *CollectionsIntProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &c.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CollectionsModelProperty. +func (c CollectionsModelProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "property", c.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CollectionsModelProperty. +func (c *CollectionsModelProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &c.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CollectionsStringProperty. +func (c CollectionsStringProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "property", c.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CollectionsStringProperty. +func (c *CollectionsStringProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &c.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DatetimeProperty. +func (d DatetimeProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "property", d.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DatetimeProperty. +func (d *DatetimeProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulateTime[datetime.RFC3339](val, "Property", &d.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Decimal128Property. +func (d Decimal128Property) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "property", d.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Decimal128Property. +func (d *Decimal128Property) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &d.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DecimalProperty. +func (d DecimalProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "property", d.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DecimalProperty. +func (d *DecimalProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &d.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DictionaryStringProperty. +func (d DictionaryStringProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "property", d.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DictionaryStringProperty. +func (d *DictionaryStringProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &d.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DurationProperty. +func (d DurationProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "property", d.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DurationProperty. +func (d *DurationProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &d.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EnumProperty. +func (e EnumProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "property", e.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EnumProperty. +func (e *EnumProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &e.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExtensibleEnumProperty. +func (e ExtensibleEnumProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "property", e.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExtensibleEnumProperty. +func (e *ExtensibleEnumProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &e.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FloatLiteralProperty. +func (f FloatLiteralProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["property"] = float32(43.125) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FloatLiteralProperty. +func (f *FloatLiteralProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &f.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FloatProperty. +func (f FloatProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "property", f.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FloatProperty. +func (f *FloatProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &f.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type InnerModel. +func (i InnerModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "property", i.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InnerModel. +func (i *InnerModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &i.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type IntLiteralProperty. +func (i IntLiteralProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["property"] = int32(42) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IntLiteralProperty. +func (i *IntLiteralProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &i.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type IntProperty. +func (i IntProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "property", i.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IntProperty. +func (i *IntProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &i.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ModelProperty. +func (m ModelProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "property", m.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ModelProperty. +func (m *ModelProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &m.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type StringLiteralProperty. +func (s StringLiteralProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["property"] = "hello" + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StringLiteralProperty. +func (s *StringLiteralProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &s.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type StringProperty. +func (s StringProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "property", s.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StringProperty. +func (s *StringProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &s.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UnionEnumValueProperty. +func (u UnionEnumValueProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["property"] = ExtendedEnumEnumValue2 + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UnionEnumValueProperty. +func (u *UnionEnumValueProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &u.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UnionFloatLiteralProperty. +func (u UnionFloatLiteralProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "property", u.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UnionFloatLiteralProperty. +func (u *UnionFloatLiteralProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &u.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UnionIntLiteralProperty. +func (u UnionIntLiteralProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "property", u.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UnionIntLiteralProperty. +func (u *UnionIntLiteralProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &u.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UnionStringLiteralProperty. +func (u UnionStringLiteralProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "property", u.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UnionStringLiteralProperty. +func (u *UnionStringLiteralProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &u.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UnknownArrayProperty. +func (u UnknownArrayProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateAny(objectMap, "property", u.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UnknownArrayProperty. +func (u *UnknownArrayProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &u.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UnknownDictProperty. +func (u UnknownDictProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateAny(objectMap, "property", u.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UnknownDictProperty. +func (u *UnknownDictProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &u.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UnknownIntProperty. +func (u UnknownIntProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateAny(objectMap, "property", u.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UnknownIntProperty. +func (u *UnknownIntProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &u.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UnknownStringProperty. +func (u UnknownStringProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateAny(objectMap, "property", u.Property) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UnknownStringProperty. +func (u *UnknownStringProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "property": + err = unpopulate(val, "Property", &u.Property) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func populateAny(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else { + m[k] = v + } +} + +func populateByteArray[T any](m map[string]any, k string, b []T, convert func() any) { + if azcore.IsNullValue(b) { + m[k] = nil + } else if len(b) == 0 { + return + } else { + m[k] = convert() + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_options.go b/test/http-specs/type/property/valuetypesgroup/zz_options.go new file mode 100644 index 000000000000..51027d0464ea --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_options.go @@ -0,0 +1,307 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +// ValueTypesBooleanClientGetOptions contains the optional parameters for the ValueTypesBooleanClient.Get method. +type ValueTypesBooleanClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesBooleanClientPutOptions contains the optional parameters for the ValueTypesBooleanClient.Put method. +type ValueTypesBooleanClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesBooleanLiteralClientGetOptions contains the optional parameters for the ValueTypesBooleanLiteralClient.Get method. +type ValueTypesBooleanLiteralClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesBooleanLiteralClientPutOptions contains the optional parameters for the ValueTypesBooleanLiteralClient.Put method. +type ValueTypesBooleanLiteralClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesBytesClientGetOptions contains the optional parameters for the ValueTypesBytesClient.Get method. +type ValueTypesBytesClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesBytesClientPutOptions contains the optional parameters for the ValueTypesBytesClient.Put method. +type ValueTypesBytesClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesCollectionsIntClientGetOptions contains the optional parameters for the ValueTypesCollectionsIntClient.Get method. +type ValueTypesCollectionsIntClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesCollectionsIntClientPutOptions contains the optional parameters for the ValueTypesCollectionsIntClient.Put method. +type ValueTypesCollectionsIntClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesCollectionsModelClientGetOptions contains the optional parameters for the ValueTypesCollectionsModelClient.Get +// method. +type ValueTypesCollectionsModelClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesCollectionsModelClientPutOptions contains the optional parameters for the ValueTypesCollectionsModelClient.Put +// method. +type ValueTypesCollectionsModelClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesCollectionsStringClientGetOptions contains the optional parameters for the ValueTypesCollectionsStringClient.Get +// method. +type ValueTypesCollectionsStringClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesCollectionsStringClientPutOptions contains the optional parameters for the ValueTypesCollectionsStringClient.Put +// method. +type ValueTypesCollectionsStringClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesDatetimeClientGetOptions contains the optional parameters for the ValueTypesDatetimeClient.Get method. +type ValueTypesDatetimeClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesDatetimeClientPutOptions contains the optional parameters for the ValueTypesDatetimeClient.Put method. +type ValueTypesDatetimeClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesDecimal128ClientGetOptions contains the optional parameters for the ValueTypesDecimal128Client.Get method. +type ValueTypesDecimal128ClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesDecimal128ClientPutOptions contains the optional parameters for the ValueTypesDecimal128Client.Put method. +type ValueTypesDecimal128ClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesDecimalClientGetOptions contains the optional parameters for the ValueTypesDecimalClient.Get method. +type ValueTypesDecimalClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesDecimalClientPutOptions contains the optional parameters for the ValueTypesDecimalClient.Put method. +type ValueTypesDecimalClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesDictionaryStringClientGetOptions contains the optional parameters for the ValueTypesDictionaryStringClient.Get +// method. +type ValueTypesDictionaryStringClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesDictionaryStringClientPutOptions contains the optional parameters for the ValueTypesDictionaryStringClient.Put +// method. +type ValueTypesDictionaryStringClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesDurationClientGetOptions contains the optional parameters for the ValueTypesDurationClient.Get method. +type ValueTypesDurationClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesDurationClientPutOptions contains the optional parameters for the ValueTypesDurationClient.Put method. +type ValueTypesDurationClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesEnumClientGetOptions contains the optional parameters for the ValueTypesEnumClient.Get method. +type ValueTypesEnumClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesEnumClientPutOptions contains the optional parameters for the ValueTypesEnumClient.Put method. +type ValueTypesEnumClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesExtensibleEnumClientGetOptions contains the optional parameters for the ValueTypesExtensibleEnumClient.Get method. +type ValueTypesExtensibleEnumClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesExtensibleEnumClientPutOptions contains the optional parameters for the ValueTypesExtensibleEnumClient.Put method. +type ValueTypesExtensibleEnumClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesFloatClientGetOptions contains the optional parameters for the ValueTypesFloatClient.Get method. +type ValueTypesFloatClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesFloatClientPutOptions contains the optional parameters for the ValueTypesFloatClient.Put method. +type ValueTypesFloatClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesFloatLiteralClientGetOptions contains the optional parameters for the ValueTypesFloatLiteralClient.Get method. +type ValueTypesFloatLiteralClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesFloatLiteralClientPutOptions contains the optional parameters for the ValueTypesFloatLiteralClient.Put method. +type ValueTypesFloatLiteralClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesIntClientGetOptions contains the optional parameters for the ValueTypesIntClient.Get method. +type ValueTypesIntClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesIntClientPutOptions contains the optional parameters for the ValueTypesIntClient.Put method. +type ValueTypesIntClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesIntLiteralClientGetOptions contains the optional parameters for the ValueTypesIntLiteralClient.Get method. +type ValueTypesIntLiteralClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesIntLiteralClientPutOptions contains the optional parameters for the ValueTypesIntLiteralClient.Put method. +type ValueTypesIntLiteralClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesModelClientGetOptions contains the optional parameters for the ValueTypesModelClient.Get method. +type ValueTypesModelClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesModelClientPutOptions contains the optional parameters for the ValueTypesModelClient.Put method. +type ValueTypesModelClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesNeverClientGetOptions contains the optional parameters for the ValueTypesNeverClient.Get method. +type ValueTypesNeverClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesNeverClientPutOptions contains the optional parameters for the ValueTypesNeverClient.Put method. +type ValueTypesNeverClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesStringClientGetOptions contains the optional parameters for the ValueTypesStringClient.Get method. +type ValueTypesStringClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesStringClientPutOptions contains the optional parameters for the ValueTypesStringClient.Put method. +type ValueTypesStringClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesStringLiteralClientGetOptions contains the optional parameters for the ValueTypesStringLiteralClient.Get method. +type ValueTypesStringLiteralClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesStringLiteralClientPutOptions contains the optional parameters for the ValueTypesStringLiteralClient.Put method. +type ValueTypesStringLiteralClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesUnionEnumValueClientGetOptions contains the optional parameters for the ValueTypesUnionEnumValueClient.Get method. +type ValueTypesUnionEnumValueClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesUnionEnumValueClientPutOptions contains the optional parameters for the ValueTypesUnionEnumValueClient.Put method. +type ValueTypesUnionEnumValueClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesUnionFloatLiteralClientGetOptions contains the optional parameters for the ValueTypesUnionFloatLiteralClient.Get +// method. +type ValueTypesUnionFloatLiteralClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesUnionFloatLiteralClientPutOptions contains the optional parameters for the ValueTypesUnionFloatLiteralClient.Put +// method. +type ValueTypesUnionFloatLiteralClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesUnionIntLiteralClientGetOptions contains the optional parameters for the ValueTypesUnionIntLiteralClient.Get +// method. +type ValueTypesUnionIntLiteralClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesUnionIntLiteralClientPutOptions contains the optional parameters for the ValueTypesUnionIntLiteralClient.Put +// method. +type ValueTypesUnionIntLiteralClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesUnionStringLiteralClientGetOptions contains the optional parameters for the ValueTypesUnionStringLiteralClient.Get +// method. +type ValueTypesUnionStringLiteralClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesUnionStringLiteralClientPutOptions contains the optional parameters for the ValueTypesUnionStringLiteralClient.Put +// method. +type ValueTypesUnionStringLiteralClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesUnknownArrayClientGetOptions contains the optional parameters for the ValueTypesUnknownArrayClient.Get method. +type ValueTypesUnknownArrayClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesUnknownArrayClientPutOptions contains the optional parameters for the ValueTypesUnknownArrayClient.Put method. +type ValueTypesUnknownArrayClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesUnknownDictClientGetOptions contains the optional parameters for the ValueTypesUnknownDictClient.Get method. +type ValueTypesUnknownDictClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesUnknownDictClientPutOptions contains the optional parameters for the ValueTypesUnknownDictClient.Put method. +type ValueTypesUnknownDictClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesUnknownIntClientGetOptions contains the optional parameters for the ValueTypesUnknownIntClient.Get method. +type ValueTypesUnknownIntClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesUnknownIntClientPutOptions contains the optional parameters for the ValueTypesUnknownIntClient.Put method. +type ValueTypesUnknownIntClientPutOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesUnknownStringClientGetOptions contains the optional parameters for the ValueTypesUnknownStringClient.Get method. +type ValueTypesUnknownStringClientGetOptions struct { + // placeholder for future optional parameters +} + +// ValueTypesUnknownStringClientPutOptions contains the optional parameters for the ValueTypesUnknownStringClient.Put method. +type ValueTypesUnknownStringClientPutOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_responses.go b/test/http-specs/type/property/valuetypesgroup/zz_responses.go new file mode 100644 index 000000000000..4841501c6f0a --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_responses.go @@ -0,0 +1,324 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +// ValueTypesBooleanClientGetResponse contains the response from method ValueTypesBooleanClient.Get. +type ValueTypesBooleanClientGetResponse struct { + // Model with a boolean property + BooleanProperty +} + +// ValueTypesBooleanClientPutResponse contains the response from method ValueTypesBooleanClient.Put. +type ValueTypesBooleanClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesBooleanLiteralClientGetResponse contains the response from method ValueTypesBooleanLiteralClient.Get. +type ValueTypesBooleanLiteralClientGetResponse struct { + // Model with a boolean literal property. + BooleanLiteralProperty +} + +// ValueTypesBooleanLiteralClientPutResponse contains the response from method ValueTypesBooleanLiteralClient.Put. +type ValueTypesBooleanLiteralClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesBytesClientGetResponse contains the response from method ValueTypesBytesClient.Get. +type ValueTypesBytesClientGetResponse struct { + // Model with a bytes property + BytesProperty +} + +// ValueTypesBytesClientPutResponse contains the response from method ValueTypesBytesClient.Put. +type ValueTypesBytesClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesCollectionsIntClientGetResponse contains the response from method ValueTypesCollectionsIntClient.Get. +type ValueTypesCollectionsIntClientGetResponse struct { + // Model with collection int properties + CollectionsIntProperty +} + +// ValueTypesCollectionsIntClientPutResponse contains the response from method ValueTypesCollectionsIntClient.Put. +type ValueTypesCollectionsIntClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesCollectionsModelClientGetResponse contains the response from method ValueTypesCollectionsModelClient.Get. +type ValueTypesCollectionsModelClientGetResponse struct { + // Model with collection model properties + CollectionsModelProperty +} + +// ValueTypesCollectionsModelClientPutResponse contains the response from method ValueTypesCollectionsModelClient.Put. +type ValueTypesCollectionsModelClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesCollectionsStringClientGetResponse contains the response from method ValueTypesCollectionsStringClient.Get. +type ValueTypesCollectionsStringClientGetResponse struct { + // Model with collection string properties + CollectionsStringProperty +} + +// ValueTypesCollectionsStringClientPutResponse contains the response from method ValueTypesCollectionsStringClient.Put. +type ValueTypesCollectionsStringClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesDatetimeClientGetResponse contains the response from method ValueTypesDatetimeClient.Get. +type ValueTypesDatetimeClientGetResponse struct { + // Model with a datetime property + DatetimeProperty +} + +// ValueTypesDatetimeClientPutResponse contains the response from method ValueTypesDatetimeClient.Put. +type ValueTypesDatetimeClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesDecimal128ClientGetResponse contains the response from method ValueTypesDecimal128Client.Get. +type ValueTypesDecimal128ClientGetResponse struct { + // Model with a decimal128 property + Decimal128Property +} + +// ValueTypesDecimal128ClientPutResponse contains the response from method ValueTypesDecimal128Client.Put. +type ValueTypesDecimal128ClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesDecimalClientGetResponse contains the response from method ValueTypesDecimalClient.Get. +type ValueTypesDecimalClientGetResponse struct { + // Model with a decimal property + DecimalProperty +} + +// ValueTypesDecimalClientPutResponse contains the response from method ValueTypesDecimalClient.Put. +type ValueTypesDecimalClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesDictionaryStringClientGetResponse contains the response from method ValueTypesDictionaryStringClient.Get. +type ValueTypesDictionaryStringClientGetResponse struct { + // Model with dictionary string properties + DictionaryStringProperty +} + +// ValueTypesDictionaryStringClientPutResponse contains the response from method ValueTypesDictionaryStringClient.Put. +type ValueTypesDictionaryStringClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesDurationClientGetResponse contains the response from method ValueTypesDurationClient.Get. +type ValueTypesDurationClientGetResponse struct { + // Model with a duration property + DurationProperty +} + +// ValueTypesDurationClientPutResponse contains the response from method ValueTypesDurationClient.Put. +type ValueTypesDurationClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesEnumClientGetResponse contains the response from method ValueTypesEnumClient.Get. +type ValueTypesEnumClientGetResponse struct { + // Model with enum properties + EnumProperty +} + +// ValueTypesEnumClientPutResponse contains the response from method ValueTypesEnumClient.Put. +type ValueTypesEnumClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesExtensibleEnumClientGetResponse contains the response from method ValueTypesExtensibleEnumClient.Get. +type ValueTypesExtensibleEnumClientGetResponse struct { + // Model with extensible enum properties + ExtensibleEnumProperty +} + +// ValueTypesExtensibleEnumClientPutResponse contains the response from method ValueTypesExtensibleEnumClient.Put. +type ValueTypesExtensibleEnumClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesFloatClientGetResponse contains the response from method ValueTypesFloatClient.Get. +type ValueTypesFloatClientGetResponse struct { + // Model with a float property + FloatProperty +} + +// ValueTypesFloatClientPutResponse contains the response from method ValueTypesFloatClient.Put. +type ValueTypesFloatClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesFloatLiteralClientGetResponse contains the response from method ValueTypesFloatLiteralClient.Get. +type ValueTypesFloatLiteralClientGetResponse struct { + // Model with a float literal property. + FloatLiteralProperty +} + +// ValueTypesFloatLiteralClientPutResponse contains the response from method ValueTypesFloatLiteralClient.Put. +type ValueTypesFloatLiteralClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesIntClientGetResponse contains the response from method ValueTypesIntClient.Get. +type ValueTypesIntClientGetResponse struct { + // Model with a int property + IntProperty +} + +// ValueTypesIntClientPutResponse contains the response from method ValueTypesIntClient.Put. +type ValueTypesIntClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesIntLiteralClientGetResponse contains the response from method ValueTypesIntLiteralClient.Get. +type ValueTypesIntLiteralClientGetResponse struct { + // Model with a int literal property. + IntLiteralProperty +} + +// ValueTypesIntLiteralClientPutResponse contains the response from method ValueTypesIntLiteralClient.Put. +type ValueTypesIntLiteralClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesModelClientGetResponse contains the response from method ValueTypesModelClient.Get. +type ValueTypesModelClientGetResponse struct { + // Model with model properties + ModelProperty +} + +// ValueTypesModelClientPutResponse contains the response from method ValueTypesModelClient.Put. +type ValueTypesModelClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesNeverClientGetResponse contains the response from method ValueTypesNeverClient.Get. +type ValueTypesNeverClientGetResponse struct { + // Model with a property never. (This property should not be included). + NeverProperty +} + +// ValueTypesNeverClientPutResponse contains the response from method ValueTypesNeverClient.Put. +type ValueTypesNeverClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesStringClientGetResponse contains the response from method ValueTypesStringClient.Get. +type ValueTypesStringClientGetResponse struct { + // Model with a string property + StringProperty +} + +// ValueTypesStringClientPutResponse contains the response from method ValueTypesStringClient.Put. +type ValueTypesStringClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesStringLiteralClientGetResponse contains the response from method ValueTypesStringLiteralClient.Get. +type ValueTypesStringLiteralClientGetResponse struct { + // Model with a string literal property. + StringLiteralProperty +} + +// ValueTypesStringLiteralClientPutResponse contains the response from method ValueTypesStringLiteralClient.Put. +type ValueTypesStringLiteralClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesUnionEnumValueClientGetResponse contains the response from method ValueTypesUnionEnumValueClient.Get. +type ValueTypesUnionEnumValueClientGetResponse struct { + // Template type for testing models with specific properties. Pass in the type of the property you are looking for + UnionEnumValueProperty +} + +// ValueTypesUnionEnumValueClientPutResponse contains the response from method ValueTypesUnionEnumValueClient.Put. +type ValueTypesUnionEnumValueClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesUnionFloatLiteralClientGetResponse contains the response from method ValueTypesUnionFloatLiteralClient.Get. +type ValueTypesUnionFloatLiteralClientGetResponse struct { + // Model with a union of float literal as property. + UnionFloatLiteralProperty +} + +// ValueTypesUnionFloatLiteralClientPutResponse contains the response from method ValueTypesUnionFloatLiteralClient.Put. +type ValueTypesUnionFloatLiteralClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesUnionIntLiteralClientGetResponse contains the response from method ValueTypesUnionIntLiteralClient.Get. +type ValueTypesUnionIntLiteralClientGetResponse struct { + // Model with a union of int literal as property. + UnionIntLiteralProperty +} + +// ValueTypesUnionIntLiteralClientPutResponse contains the response from method ValueTypesUnionIntLiteralClient.Put. +type ValueTypesUnionIntLiteralClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesUnionStringLiteralClientGetResponse contains the response from method ValueTypesUnionStringLiteralClient.Get. +type ValueTypesUnionStringLiteralClientGetResponse struct { + // Model with a union of string literal as property. + UnionStringLiteralProperty +} + +// ValueTypesUnionStringLiteralClientPutResponse contains the response from method ValueTypesUnionStringLiteralClient.Put. +type ValueTypesUnionStringLiteralClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesUnknownArrayClientGetResponse contains the response from method ValueTypesUnknownArrayClient.Get. +type ValueTypesUnknownArrayClientGetResponse struct { + // Model with a property unknown, and the data is an array. + UnknownArrayProperty +} + +// ValueTypesUnknownArrayClientPutResponse contains the response from method ValueTypesUnknownArrayClient.Put. +type ValueTypesUnknownArrayClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesUnknownDictClientGetResponse contains the response from method ValueTypesUnknownDictClient.Get. +type ValueTypesUnknownDictClientGetResponse struct { + // Model with a property unknown, and the data is a dictionnary. + UnknownDictProperty +} + +// ValueTypesUnknownDictClientPutResponse contains the response from method ValueTypesUnknownDictClient.Put. +type ValueTypesUnknownDictClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesUnknownIntClientGetResponse contains the response from method ValueTypesUnknownIntClient.Get. +type ValueTypesUnknownIntClientGetResponse struct { + // Model with a property unknown, and the data is a int32. + UnknownIntProperty +} + +// ValueTypesUnknownIntClientPutResponse contains the response from method ValueTypesUnknownIntClient.Put. +type ValueTypesUnknownIntClientPutResponse struct { + // placeholder for future response values +} + +// ValueTypesUnknownStringClientGetResponse contains the response from method ValueTypesUnknownStringClient.Get. +type ValueTypesUnknownStringClientGetResponse struct { + // Model with a property unknown, and the data is a string. + UnknownStringProperty +} + +// ValueTypesUnknownStringClientPutResponse contains the response from method ValueTypesUnknownStringClient.Put. +type ValueTypesUnknownStringClientPutResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypes_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypes_client.go new file mode 100644 index 000000000000..9a9110a20279 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypes_client.go @@ -0,0 +1,272 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// ValueTypesClient - Illustrates various property types for models +// Don't use this type directly, use NewValueTypesClientWithNoCredential() instead. +type ValueTypesClient struct { + internal *azcore.Client + endpoint string +} + +// ValueTypesClientOptions contains the optional values for creating a [ValueTypesClient]. +type ValueTypesClientOptions struct { + azcore.ClientOptions +} + +// NewValueTypesClientWithNoCredential creates a new instance of ValueTypesClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewValueTypesClientWithNoCredential(endpoint string, options *ValueTypesClientOptions) (*ValueTypesClient, error) { + if options == nil { + options = &ValueTypesClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &ValueTypesClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewValueTypesBooleanClient creates a new instance of [ValueTypesBooleanClient]. +func (client *ValueTypesClient) NewValueTypesBooleanClient() *ValueTypesBooleanClient { + return &ValueTypesBooleanClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesBooleanLiteralClient creates a new instance of [ValueTypesBooleanLiteralClient]. +func (client *ValueTypesClient) NewValueTypesBooleanLiteralClient() *ValueTypesBooleanLiteralClient { + return &ValueTypesBooleanLiteralClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesBytesClient creates a new instance of [ValueTypesBytesClient]. +func (client *ValueTypesClient) NewValueTypesBytesClient() *ValueTypesBytesClient { + return &ValueTypesBytesClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesCollectionsIntClient creates a new instance of [ValueTypesCollectionsIntClient]. +func (client *ValueTypesClient) NewValueTypesCollectionsIntClient() *ValueTypesCollectionsIntClient { + return &ValueTypesCollectionsIntClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesCollectionsModelClient creates a new instance of [ValueTypesCollectionsModelClient]. +func (client *ValueTypesClient) NewValueTypesCollectionsModelClient() *ValueTypesCollectionsModelClient { + return &ValueTypesCollectionsModelClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesCollectionsStringClient creates a new instance of [ValueTypesCollectionsStringClient]. +func (client *ValueTypesClient) NewValueTypesCollectionsStringClient() *ValueTypesCollectionsStringClient { + return &ValueTypesCollectionsStringClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesDatetimeClient creates a new instance of [ValueTypesDatetimeClient]. +func (client *ValueTypesClient) NewValueTypesDatetimeClient() *ValueTypesDatetimeClient { + return &ValueTypesDatetimeClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesDecimal128Client creates a new instance of [ValueTypesDecimal128Client]. +func (client *ValueTypesClient) NewValueTypesDecimal128Client() *ValueTypesDecimal128Client { + return &ValueTypesDecimal128Client{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesDecimalClient creates a new instance of [ValueTypesDecimalClient]. +func (client *ValueTypesClient) NewValueTypesDecimalClient() *ValueTypesDecimalClient { + return &ValueTypesDecimalClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesDictionaryStringClient creates a new instance of [ValueTypesDictionaryStringClient]. +func (client *ValueTypesClient) NewValueTypesDictionaryStringClient() *ValueTypesDictionaryStringClient { + return &ValueTypesDictionaryStringClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesDurationClient creates a new instance of [ValueTypesDurationClient]. +func (client *ValueTypesClient) NewValueTypesDurationClient() *ValueTypesDurationClient { + return &ValueTypesDurationClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesEnumClient creates a new instance of [ValueTypesEnumClient]. +func (client *ValueTypesClient) NewValueTypesEnumClient() *ValueTypesEnumClient { + return &ValueTypesEnumClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesExtensibleEnumClient creates a new instance of [ValueTypesExtensibleEnumClient]. +func (client *ValueTypesClient) NewValueTypesExtensibleEnumClient() *ValueTypesExtensibleEnumClient { + return &ValueTypesExtensibleEnumClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesFloatClient creates a new instance of [ValueTypesFloatClient]. +func (client *ValueTypesClient) NewValueTypesFloatClient() *ValueTypesFloatClient { + return &ValueTypesFloatClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesFloatLiteralClient creates a new instance of [ValueTypesFloatLiteralClient]. +func (client *ValueTypesClient) NewValueTypesFloatLiteralClient() *ValueTypesFloatLiteralClient { + return &ValueTypesFloatLiteralClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesIntClient creates a new instance of [ValueTypesIntClient]. +func (client *ValueTypesClient) NewValueTypesIntClient() *ValueTypesIntClient { + return &ValueTypesIntClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesIntLiteralClient creates a new instance of [ValueTypesIntLiteralClient]. +func (client *ValueTypesClient) NewValueTypesIntLiteralClient() *ValueTypesIntLiteralClient { + return &ValueTypesIntLiteralClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesModelClient creates a new instance of [ValueTypesModelClient]. +func (client *ValueTypesClient) NewValueTypesModelClient() *ValueTypesModelClient { + return &ValueTypesModelClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesNeverClient creates a new instance of [ValueTypesNeverClient]. +func (client *ValueTypesClient) NewValueTypesNeverClient() *ValueTypesNeverClient { + return &ValueTypesNeverClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesStringClient creates a new instance of [ValueTypesStringClient]. +func (client *ValueTypesClient) NewValueTypesStringClient() *ValueTypesStringClient { + return &ValueTypesStringClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesStringLiteralClient creates a new instance of [ValueTypesStringLiteralClient]. +func (client *ValueTypesClient) NewValueTypesStringLiteralClient() *ValueTypesStringLiteralClient { + return &ValueTypesStringLiteralClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesUnionEnumValueClient creates a new instance of [ValueTypesUnionEnumValueClient]. +func (client *ValueTypesClient) NewValueTypesUnionEnumValueClient() *ValueTypesUnionEnumValueClient { + return &ValueTypesUnionEnumValueClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesUnionFloatLiteralClient creates a new instance of [ValueTypesUnionFloatLiteralClient]. +func (client *ValueTypesClient) NewValueTypesUnionFloatLiteralClient() *ValueTypesUnionFloatLiteralClient { + return &ValueTypesUnionFloatLiteralClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesUnionIntLiteralClient creates a new instance of [ValueTypesUnionIntLiteralClient]. +func (client *ValueTypesClient) NewValueTypesUnionIntLiteralClient() *ValueTypesUnionIntLiteralClient { + return &ValueTypesUnionIntLiteralClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesUnionStringLiteralClient creates a new instance of [ValueTypesUnionStringLiteralClient]. +func (client *ValueTypesClient) NewValueTypesUnionStringLiteralClient() *ValueTypesUnionStringLiteralClient { + return &ValueTypesUnionStringLiteralClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesUnknownArrayClient creates a new instance of [ValueTypesUnknownArrayClient]. +func (client *ValueTypesClient) NewValueTypesUnknownArrayClient() *ValueTypesUnknownArrayClient { + return &ValueTypesUnknownArrayClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesUnknownDictClient creates a new instance of [ValueTypesUnknownDictClient]. +func (client *ValueTypesClient) NewValueTypesUnknownDictClient() *ValueTypesUnknownDictClient { + return &ValueTypesUnknownDictClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesUnknownIntClient creates a new instance of [ValueTypesUnknownIntClient]. +func (client *ValueTypesClient) NewValueTypesUnknownIntClient() *ValueTypesUnknownIntClient { + return &ValueTypesUnknownIntClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewValueTypesUnknownStringClient creates a new instance of [ValueTypesUnknownStringClient]. +func (client *ValueTypesClient) NewValueTypesUnknownStringClient() *ValueTypesUnknownStringClient { + return &ValueTypesUnknownStringClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypesboolean_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesboolean_client.go new file mode 100644 index 000000000000..a1d318a8979b --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesboolean_client.go @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesBooleanClient contains the methods for the ValueTypesBoolean group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesBooleanClient] instead. +type ValueTypesBooleanClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesBooleanClientGetOptions contains the optional parameters for the ValueTypesBooleanClient.Get method. +func (client *ValueTypesBooleanClient) Get(ctx context.Context, options *ValueTypesBooleanClientGetOptions) (ValueTypesBooleanClientGetResponse, error) { + var err error + const operationName = "ValueTypesBooleanClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesBooleanClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesBooleanClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesBooleanClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesBooleanClient) getCreateRequest(ctx context.Context, _ *ValueTypesBooleanClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/boolean" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesBooleanClient) getHandleResponse(resp *http.Response) (ValueTypesBooleanClientGetResponse, error) { + result := ValueTypesBooleanClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BooleanProperty); err != nil { + return ValueTypesBooleanClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesBooleanClientPutOptions contains the optional parameters for the ValueTypesBooleanClient.Put method. +func (client *ValueTypesBooleanClient) Put(ctx context.Context, body BooleanProperty, options *ValueTypesBooleanClientPutOptions) (ValueTypesBooleanClientPutResponse, error) { + var err error + const operationName = "ValueTypesBooleanClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesBooleanClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesBooleanClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesBooleanClientPutResponse{}, err + } + return ValueTypesBooleanClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesBooleanClient) putCreateRequest(ctx context.Context, body BooleanProperty, _ *ValueTypesBooleanClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/boolean" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypesbooleanliteral_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesbooleanliteral_client.go new file mode 100644 index 000000000000..858bf90e24d4 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesbooleanliteral_client.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesBooleanLiteralClient contains the methods for the ValueTypesBooleanLiteral group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesBooleanLiteralClient] instead. +type ValueTypesBooleanLiteralClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesBooleanLiteralClientGetOptions contains the optional parameters for the ValueTypesBooleanLiteralClient.Get +// method. +func (client *ValueTypesBooleanLiteralClient) Get(ctx context.Context, options *ValueTypesBooleanLiteralClientGetOptions) (ValueTypesBooleanLiteralClientGetResponse, error) { + var err error + const operationName = "ValueTypesBooleanLiteralClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesBooleanLiteralClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesBooleanLiteralClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesBooleanLiteralClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesBooleanLiteralClient) getCreateRequest(ctx context.Context, _ *ValueTypesBooleanLiteralClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/boolean/literal" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesBooleanLiteralClient) getHandleResponse(resp *http.Response) (ValueTypesBooleanLiteralClientGetResponse, error) { + result := ValueTypesBooleanLiteralClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BooleanLiteralProperty); err != nil { + return ValueTypesBooleanLiteralClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesBooleanLiteralClientPutOptions contains the optional parameters for the ValueTypesBooleanLiteralClient.Put +// method. +func (client *ValueTypesBooleanLiteralClient) Put(ctx context.Context, body BooleanLiteralProperty, options *ValueTypesBooleanLiteralClientPutOptions) (ValueTypesBooleanLiteralClientPutResponse, error) { + var err error + const operationName = "ValueTypesBooleanLiteralClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesBooleanLiteralClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesBooleanLiteralClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesBooleanLiteralClientPutResponse{}, err + } + return ValueTypesBooleanLiteralClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesBooleanLiteralClient) putCreateRequest(ctx context.Context, body BooleanLiteralProperty, _ *ValueTypesBooleanLiteralClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/boolean/literal" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypesbytes_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesbytes_client.go new file mode 100644 index 000000000000..7a09abd714a2 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesbytes_client.go @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesBytesClient contains the methods for the ValueTypesBytes group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesBytesClient] instead. +type ValueTypesBytesClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesBytesClientGetOptions contains the optional parameters for the ValueTypesBytesClient.Get method. +func (client *ValueTypesBytesClient) Get(ctx context.Context, options *ValueTypesBytesClientGetOptions) (ValueTypesBytesClientGetResponse, error) { + var err error + const operationName = "ValueTypesBytesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesBytesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesBytesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesBytesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesBytesClient) getCreateRequest(ctx context.Context, _ *ValueTypesBytesClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/bytes" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesBytesClient) getHandleResponse(resp *http.Response) (ValueTypesBytesClientGetResponse, error) { + result := ValueTypesBytesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BytesProperty); err != nil { + return ValueTypesBytesClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesBytesClientPutOptions contains the optional parameters for the ValueTypesBytesClient.Put method. +func (client *ValueTypesBytesClient) Put(ctx context.Context, body BytesProperty, options *ValueTypesBytesClientPutOptions) (ValueTypesBytesClientPutResponse, error) { + var err error + const operationName = "ValueTypesBytesClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesBytesClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesBytesClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesBytesClientPutResponse{}, err + } + return ValueTypesBytesClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesBytesClient) putCreateRequest(ctx context.Context, body BytesProperty, _ *ValueTypesBytesClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/bytes" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypescollectionsint_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypescollectionsint_client.go new file mode 100644 index 000000000000..22efdfa1c0a5 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypescollectionsint_client.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesCollectionsIntClient contains the methods for the ValueTypesCollectionsInt group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesCollectionsIntClient] instead. +type ValueTypesCollectionsIntClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesCollectionsIntClientGetOptions contains the optional parameters for the ValueTypesCollectionsIntClient.Get +// method. +func (client *ValueTypesCollectionsIntClient) Get(ctx context.Context, options *ValueTypesCollectionsIntClientGetOptions) (ValueTypesCollectionsIntClientGetResponse, error) { + var err error + const operationName = "ValueTypesCollectionsIntClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesCollectionsIntClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesCollectionsIntClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesCollectionsIntClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesCollectionsIntClient) getCreateRequest(ctx context.Context, _ *ValueTypesCollectionsIntClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/collections/int" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesCollectionsIntClient) getHandleResponse(resp *http.Response) (ValueTypesCollectionsIntClientGetResponse, error) { + result := ValueTypesCollectionsIntClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CollectionsIntProperty); err != nil { + return ValueTypesCollectionsIntClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesCollectionsIntClientPutOptions contains the optional parameters for the ValueTypesCollectionsIntClient.Put +// method. +func (client *ValueTypesCollectionsIntClient) Put(ctx context.Context, body CollectionsIntProperty, options *ValueTypesCollectionsIntClientPutOptions) (ValueTypesCollectionsIntClientPutResponse, error) { + var err error + const operationName = "ValueTypesCollectionsIntClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesCollectionsIntClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesCollectionsIntClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesCollectionsIntClientPutResponse{}, err + } + return ValueTypesCollectionsIntClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesCollectionsIntClient) putCreateRequest(ctx context.Context, body CollectionsIntProperty, _ *ValueTypesCollectionsIntClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/collections/int" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypescollectionsmodel_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypescollectionsmodel_client.go new file mode 100644 index 000000000000..65ef4f553589 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypescollectionsmodel_client.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesCollectionsModelClient contains the methods for the ValueTypesCollectionsModel group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesCollectionsModelClient] instead. +type ValueTypesCollectionsModelClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesCollectionsModelClientGetOptions contains the optional parameters for the ValueTypesCollectionsModelClient.Get +// method. +func (client *ValueTypesCollectionsModelClient) Get(ctx context.Context, options *ValueTypesCollectionsModelClientGetOptions) (ValueTypesCollectionsModelClientGetResponse, error) { + var err error + const operationName = "ValueTypesCollectionsModelClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesCollectionsModelClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesCollectionsModelClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesCollectionsModelClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesCollectionsModelClient) getCreateRequest(ctx context.Context, _ *ValueTypesCollectionsModelClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/collections/model" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesCollectionsModelClient) getHandleResponse(resp *http.Response) (ValueTypesCollectionsModelClientGetResponse, error) { + result := ValueTypesCollectionsModelClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CollectionsModelProperty); err != nil { + return ValueTypesCollectionsModelClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesCollectionsModelClientPutOptions contains the optional parameters for the ValueTypesCollectionsModelClient.Put +// method. +func (client *ValueTypesCollectionsModelClient) Put(ctx context.Context, body CollectionsModelProperty, options *ValueTypesCollectionsModelClientPutOptions) (ValueTypesCollectionsModelClientPutResponse, error) { + var err error + const operationName = "ValueTypesCollectionsModelClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesCollectionsModelClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesCollectionsModelClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesCollectionsModelClientPutResponse{}, err + } + return ValueTypesCollectionsModelClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesCollectionsModelClient) putCreateRequest(ctx context.Context, body CollectionsModelProperty, _ *ValueTypesCollectionsModelClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/collections/model" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypescollectionsstring_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypescollectionsstring_client.go new file mode 100644 index 000000000000..fed913329e5d --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypescollectionsstring_client.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesCollectionsStringClient contains the methods for the ValueTypesCollectionsString group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesCollectionsStringClient] instead. +type ValueTypesCollectionsStringClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesCollectionsStringClientGetOptions contains the optional parameters for the ValueTypesCollectionsStringClient.Get +// method. +func (client *ValueTypesCollectionsStringClient) Get(ctx context.Context, options *ValueTypesCollectionsStringClientGetOptions) (ValueTypesCollectionsStringClientGetResponse, error) { + var err error + const operationName = "ValueTypesCollectionsStringClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesCollectionsStringClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesCollectionsStringClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesCollectionsStringClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesCollectionsStringClient) getCreateRequest(ctx context.Context, _ *ValueTypesCollectionsStringClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/collections/string" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesCollectionsStringClient) getHandleResponse(resp *http.Response) (ValueTypesCollectionsStringClientGetResponse, error) { + result := ValueTypesCollectionsStringClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CollectionsStringProperty); err != nil { + return ValueTypesCollectionsStringClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesCollectionsStringClientPutOptions contains the optional parameters for the ValueTypesCollectionsStringClient.Put +// method. +func (client *ValueTypesCollectionsStringClient) Put(ctx context.Context, body CollectionsStringProperty, options *ValueTypesCollectionsStringClientPutOptions) (ValueTypesCollectionsStringClientPutResponse, error) { + var err error + const operationName = "ValueTypesCollectionsStringClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesCollectionsStringClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesCollectionsStringClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesCollectionsStringClientPutResponse{}, err + } + return ValueTypesCollectionsStringClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesCollectionsStringClient) putCreateRequest(ctx context.Context, body CollectionsStringProperty, _ *ValueTypesCollectionsStringClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/collections/string" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypesdatetime_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesdatetime_client.go new file mode 100644 index 000000000000..05b735f0f31f --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesdatetime_client.go @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesDatetimeClient contains the methods for the ValueTypesDatetime group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesDatetimeClient] instead. +type ValueTypesDatetimeClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesDatetimeClientGetOptions contains the optional parameters for the ValueTypesDatetimeClient.Get method. +func (client *ValueTypesDatetimeClient) Get(ctx context.Context, options *ValueTypesDatetimeClientGetOptions) (ValueTypesDatetimeClientGetResponse, error) { + var err error + const operationName = "ValueTypesDatetimeClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesDatetimeClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesDatetimeClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesDatetimeClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesDatetimeClient) getCreateRequest(ctx context.Context, _ *ValueTypesDatetimeClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/datetime" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesDatetimeClient) getHandleResponse(resp *http.Response) (ValueTypesDatetimeClientGetResponse, error) { + result := ValueTypesDatetimeClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DatetimeProperty); err != nil { + return ValueTypesDatetimeClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesDatetimeClientPutOptions contains the optional parameters for the ValueTypesDatetimeClient.Put method. +func (client *ValueTypesDatetimeClient) Put(ctx context.Context, body DatetimeProperty, options *ValueTypesDatetimeClientPutOptions) (ValueTypesDatetimeClientPutResponse, error) { + var err error + const operationName = "ValueTypesDatetimeClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesDatetimeClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesDatetimeClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesDatetimeClientPutResponse{}, err + } + return ValueTypesDatetimeClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesDatetimeClient) putCreateRequest(ctx context.Context, body DatetimeProperty, _ *ValueTypesDatetimeClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/datetime" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypesdecimal128_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesdecimal128_client.go new file mode 100644 index 000000000000..13a0d84ff2f2 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesdecimal128_client.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesDecimal128Client contains the methods for the ValueTypesDecimal128 group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesDecimal128Client] instead. +type ValueTypesDecimal128Client struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesDecimal128ClientGetOptions contains the optional parameters for the ValueTypesDecimal128Client.Get +// method. +func (client *ValueTypesDecimal128Client) Get(ctx context.Context, options *ValueTypesDecimal128ClientGetOptions) (ValueTypesDecimal128ClientGetResponse, error) { + var err error + const operationName = "ValueTypesDecimal128Client.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesDecimal128ClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesDecimal128ClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesDecimal128ClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesDecimal128Client) getCreateRequest(ctx context.Context, _ *ValueTypesDecimal128ClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/decimal128" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesDecimal128Client) getHandleResponse(resp *http.Response) (ValueTypesDecimal128ClientGetResponse, error) { + result := ValueTypesDecimal128ClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Decimal128Property); err != nil { + return ValueTypesDecimal128ClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesDecimal128ClientPutOptions contains the optional parameters for the ValueTypesDecimal128Client.Put +// method. +func (client *ValueTypesDecimal128Client) Put(ctx context.Context, body Decimal128Property, options *ValueTypesDecimal128ClientPutOptions) (ValueTypesDecimal128ClientPutResponse, error) { + var err error + const operationName = "ValueTypesDecimal128Client.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesDecimal128ClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesDecimal128ClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesDecimal128ClientPutResponse{}, err + } + return ValueTypesDecimal128ClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesDecimal128Client) putCreateRequest(ctx context.Context, body Decimal128Property, _ *ValueTypesDecimal128ClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/decimal128" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypesdecimal_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesdecimal_client.go new file mode 100644 index 000000000000..d350c0dce7d8 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesdecimal_client.go @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesDecimalClient contains the methods for the ValueTypesDecimal group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesDecimalClient] instead. +type ValueTypesDecimalClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesDecimalClientGetOptions contains the optional parameters for the ValueTypesDecimalClient.Get method. +func (client *ValueTypesDecimalClient) Get(ctx context.Context, options *ValueTypesDecimalClientGetOptions) (ValueTypesDecimalClientGetResponse, error) { + var err error + const operationName = "ValueTypesDecimalClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesDecimalClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesDecimalClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesDecimalClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesDecimalClient) getCreateRequest(ctx context.Context, _ *ValueTypesDecimalClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/decimal" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesDecimalClient) getHandleResponse(resp *http.Response) (ValueTypesDecimalClientGetResponse, error) { + result := ValueTypesDecimalClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DecimalProperty); err != nil { + return ValueTypesDecimalClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesDecimalClientPutOptions contains the optional parameters for the ValueTypesDecimalClient.Put method. +func (client *ValueTypesDecimalClient) Put(ctx context.Context, body DecimalProperty, options *ValueTypesDecimalClientPutOptions) (ValueTypesDecimalClientPutResponse, error) { + var err error + const operationName = "ValueTypesDecimalClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesDecimalClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesDecimalClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesDecimalClientPutResponse{}, err + } + return ValueTypesDecimalClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesDecimalClient) putCreateRequest(ctx context.Context, body DecimalProperty, _ *ValueTypesDecimalClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/decimal" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypesdictionarystring_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesdictionarystring_client.go new file mode 100644 index 000000000000..9f397be2bd8f --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesdictionarystring_client.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesDictionaryStringClient contains the methods for the ValueTypesDictionaryString group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesDictionaryStringClient] instead. +type ValueTypesDictionaryStringClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesDictionaryStringClientGetOptions contains the optional parameters for the ValueTypesDictionaryStringClient.Get +// method. +func (client *ValueTypesDictionaryStringClient) Get(ctx context.Context, options *ValueTypesDictionaryStringClientGetOptions) (ValueTypesDictionaryStringClientGetResponse, error) { + var err error + const operationName = "ValueTypesDictionaryStringClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesDictionaryStringClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesDictionaryStringClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesDictionaryStringClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesDictionaryStringClient) getCreateRequest(ctx context.Context, _ *ValueTypesDictionaryStringClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/dictionary/string" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesDictionaryStringClient) getHandleResponse(resp *http.Response) (ValueTypesDictionaryStringClientGetResponse, error) { + result := ValueTypesDictionaryStringClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DictionaryStringProperty); err != nil { + return ValueTypesDictionaryStringClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesDictionaryStringClientPutOptions contains the optional parameters for the ValueTypesDictionaryStringClient.Put +// method. +func (client *ValueTypesDictionaryStringClient) Put(ctx context.Context, body DictionaryStringProperty, options *ValueTypesDictionaryStringClientPutOptions) (ValueTypesDictionaryStringClientPutResponse, error) { + var err error + const operationName = "ValueTypesDictionaryStringClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesDictionaryStringClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesDictionaryStringClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesDictionaryStringClientPutResponse{}, err + } + return ValueTypesDictionaryStringClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesDictionaryStringClient) putCreateRequest(ctx context.Context, body DictionaryStringProperty, _ *ValueTypesDictionaryStringClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/dictionary/string" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypesduration_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesduration_client.go new file mode 100644 index 000000000000..d2e2370635b9 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesduration_client.go @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesDurationClient contains the methods for the ValueTypesDuration group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesDurationClient] instead. +type ValueTypesDurationClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesDurationClientGetOptions contains the optional parameters for the ValueTypesDurationClient.Get method. +func (client *ValueTypesDurationClient) Get(ctx context.Context, options *ValueTypesDurationClientGetOptions) (ValueTypesDurationClientGetResponse, error) { + var err error + const operationName = "ValueTypesDurationClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesDurationClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesDurationClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesDurationClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesDurationClient) getCreateRequest(ctx context.Context, _ *ValueTypesDurationClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/duration" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesDurationClient) getHandleResponse(resp *http.Response) (ValueTypesDurationClientGetResponse, error) { + result := ValueTypesDurationClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DurationProperty); err != nil { + return ValueTypesDurationClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesDurationClientPutOptions contains the optional parameters for the ValueTypesDurationClient.Put method. +func (client *ValueTypesDurationClient) Put(ctx context.Context, body DurationProperty, options *ValueTypesDurationClientPutOptions) (ValueTypesDurationClientPutResponse, error) { + var err error + const operationName = "ValueTypesDurationClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesDurationClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesDurationClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesDurationClientPutResponse{}, err + } + return ValueTypesDurationClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesDurationClient) putCreateRequest(ctx context.Context, body DurationProperty, _ *ValueTypesDurationClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/duration" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypesenum_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesenum_client.go new file mode 100644 index 000000000000..9d3ba044ecb6 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesenum_client.go @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesEnumClient contains the methods for the ValueTypesEnum group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesEnumClient] instead. +type ValueTypesEnumClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesEnumClientGetOptions contains the optional parameters for the ValueTypesEnumClient.Get method. +func (client *ValueTypesEnumClient) Get(ctx context.Context, options *ValueTypesEnumClientGetOptions) (ValueTypesEnumClientGetResponse, error) { + var err error + const operationName = "ValueTypesEnumClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesEnumClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesEnumClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesEnumClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesEnumClient) getCreateRequest(ctx context.Context, _ *ValueTypesEnumClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/enum" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesEnumClient) getHandleResponse(resp *http.Response) (ValueTypesEnumClientGetResponse, error) { + result := ValueTypesEnumClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.EnumProperty); err != nil { + return ValueTypesEnumClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesEnumClientPutOptions contains the optional parameters for the ValueTypesEnumClient.Put method. +func (client *ValueTypesEnumClient) Put(ctx context.Context, body EnumProperty, options *ValueTypesEnumClientPutOptions) (ValueTypesEnumClientPutResponse, error) { + var err error + const operationName = "ValueTypesEnumClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesEnumClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesEnumClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesEnumClientPutResponse{}, err + } + return ValueTypesEnumClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesEnumClient) putCreateRequest(ctx context.Context, body EnumProperty, _ *ValueTypesEnumClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/enum" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypesextensibleenum_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesextensibleenum_client.go new file mode 100644 index 000000000000..8aa4f7ce4889 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesextensibleenum_client.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesExtensibleEnumClient contains the methods for the ValueTypesExtensibleEnum group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesExtensibleEnumClient] instead. +type ValueTypesExtensibleEnumClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesExtensibleEnumClientGetOptions contains the optional parameters for the ValueTypesExtensibleEnumClient.Get +// method. +func (client *ValueTypesExtensibleEnumClient) Get(ctx context.Context, options *ValueTypesExtensibleEnumClientGetOptions) (ValueTypesExtensibleEnumClientGetResponse, error) { + var err error + const operationName = "ValueTypesExtensibleEnumClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesExtensibleEnumClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesExtensibleEnumClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesExtensibleEnumClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesExtensibleEnumClient) getCreateRequest(ctx context.Context, _ *ValueTypesExtensibleEnumClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/extensible-enum" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesExtensibleEnumClient) getHandleResponse(resp *http.Response) (ValueTypesExtensibleEnumClientGetResponse, error) { + result := ValueTypesExtensibleEnumClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExtensibleEnumProperty); err != nil { + return ValueTypesExtensibleEnumClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesExtensibleEnumClientPutOptions contains the optional parameters for the ValueTypesExtensibleEnumClient.Put +// method. +func (client *ValueTypesExtensibleEnumClient) Put(ctx context.Context, body ExtensibleEnumProperty, options *ValueTypesExtensibleEnumClientPutOptions) (ValueTypesExtensibleEnumClientPutResponse, error) { + var err error + const operationName = "ValueTypesExtensibleEnumClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesExtensibleEnumClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesExtensibleEnumClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesExtensibleEnumClientPutResponse{}, err + } + return ValueTypesExtensibleEnumClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesExtensibleEnumClient) putCreateRequest(ctx context.Context, body ExtensibleEnumProperty, _ *ValueTypesExtensibleEnumClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/extensible-enum" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypesfloat_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesfloat_client.go new file mode 100644 index 000000000000..3ceb43cce9f6 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesfloat_client.go @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesFloatClient contains the methods for the ValueTypesFloat group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesFloatClient] instead. +type ValueTypesFloatClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesFloatClientGetOptions contains the optional parameters for the ValueTypesFloatClient.Get method. +func (client *ValueTypesFloatClient) Get(ctx context.Context, options *ValueTypesFloatClientGetOptions) (ValueTypesFloatClientGetResponse, error) { + var err error + const operationName = "ValueTypesFloatClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesFloatClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesFloatClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesFloatClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesFloatClient) getCreateRequest(ctx context.Context, _ *ValueTypesFloatClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/float" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesFloatClient) getHandleResponse(resp *http.Response) (ValueTypesFloatClientGetResponse, error) { + result := ValueTypesFloatClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FloatProperty); err != nil { + return ValueTypesFloatClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesFloatClientPutOptions contains the optional parameters for the ValueTypesFloatClient.Put method. +func (client *ValueTypesFloatClient) Put(ctx context.Context, body FloatProperty, options *ValueTypesFloatClientPutOptions) (ValueTypesFloatClientPutResponse, error) { + var err error + const operationName = "ValueTypesFloatClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesFloatClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesFloatClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesFloatClientPutResponse{}, err + } + return ValueTypesFloatClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesFloatClient) putCreateRequest(ctx context.Context, body FloatProperty, _ *ValueTypesFloatClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/float" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypesfloatliteral_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesfloatliteral_client.go new file mode 100644 index 000000000000..309c9bd86732 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesfloatliteral_client.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesFloatLiteralClient contains the methods for the ValueTypesFloatLiteral group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesFloatLiteralClient] instead. +type ValueTypesFloatLiteralClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesFloatLiteralClientGetOptions contains the optional parameters for the ValueTypesFloatLiteralClient.Get +// method. +func (client *ValueTypesFloatLiteralClient) Get(ctx context.Context, options *ValueTypesFloatLiteralClientGetOptions) (ValueTypesFloatLiteralClientGetResponse, error) { + var err error + const operationName = "ValueTypesFloatLiteralClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesFloatLiteralClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesFloatLiteralClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesFloatLiteralClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesFloatLiteralClient) getCreateRequest(ctx context.Context, _ *ValueTypesFloatLiteralClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/float/literal" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesFloatLiteralClient) getHandleResponse(resp *http.Response) (ValueTypesFloatLiteralClientGetResponse, error) { + result := ValueTypesFloatLiteralClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FloatLiteralProperty); err != nil { + return ValueTypesFloatLiteralClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesFloatLiteralClientPutOptions contains the optional parameters for the ValueTypesFloatLiteralClient.Put +// method. +func (client *ValueTypesFloatLiteralClient) Put(ctx context.Context, body FloatLiteralProperty, options *ValueTypesFloatLiteralClientPutOptions) (ValueTypesFloatLiteralClientPutResponse, error) { + var err error + const operationName = "ValueTypesFloatLiteralClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesFloatLiteralClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesFloatLiteralClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesFloatLiteralClientPutResponse{}, err + } + return ValueTypesFloatLiteralClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesFloatLiteralClient) putCreateRequest(ctx context.Context, body FloatLiteralProperty, _ *ValueTypesFloatLiteralClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/float/literal" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypesint_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesint_client.go new file mode 100644 index 000000000000..e2d6ab3c92b5 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesint_client.go @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesIntClient contains the methods for the ValueTypesInt group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesIntClient] instead. +type ValueTypesIntClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesIntClientGetOptions contains the optional parameters for the ValueTypesIntClient.Get method. +func (client *ValueTypesIntClient) Get(ctx context.Context, options *ValueTypesIntClientGetOptions) (ValueTypesIntClientGetResponse, error) { + var err error + const operationName = "ValueTypesIntClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesIntClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesIntClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesIntClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesIntClient) getCreateRequest(ctx context.Context, _ *ValueTypesIntClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/int" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesIntClient) getHandleResponse(resp *http.Response) (ValueTypesIntClientGetResponse, error) { + result := ValueTypesIntClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.IntProperty); err != nil { + return ValueTypesIntClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesIntClientPutOptions contains the optional parameters for the ValueTypesIntClient.Put method. +func (client *ValueTypesIntClient) Put(ctx context.Context, body IntProperty, options *ValueTypesIntClientPutOptions) (ValueTypesIntClientPutResponse, error) { + var err error + const operationName = "ValueTypesIntClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesIntClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesIntClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesIntClientPutResponse{}, err + } + return ValueTypesIntClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesIntClient) putCreateRequest(ctx context.Context, body IntProperty, _ *ValueTypesIntClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/int" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypesintliteral_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesintliteral_client.go new file mode 100644 index 000000000000..102e1fb81b6b --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesintliteral_client.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesIntLiteralClient contains the methods for the ValueTypesIntLiteral group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesIntLiteralClient] instead. +type ValueTypesIntLiteralClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesIntLiteralClientGetOptions contains the optional parameters for the ValueTypesIntLiteralClient.Get +// method. +func (client *ValueTypesIntLiteralClient) Get(ctx context.Context, options *ValueTypesIntLiteralClientGetOptions) (ValueTypesIntLiteralClientGetResponse, error) { + var err error + const operationName = "ValueTypesIntLiteralClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesIntLiteralClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesIntLiteralClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesIntLiteralClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesIntLiteralClient) getCreateRequest(ctx context.Context, _ *ValueTypesIntLiteralClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/int/literal" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesIntLiteralClient) getHandleResponse(resp *http.Response) (ValueTypesIntLiteralClientGetResponse, error) { + result := ValueTypesIntLiteralClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.IntLiteralProperty); err != nil { + return ValueTypesIntLiteralClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesIntLiteralClientPutOptions contains the optional parameters for the ValueTypesIntLiteralClient.Put +// method. +func (client *ValueTypesIntLiteralClient) Put(ctx context.Context, body IntLiteralProperty, options *ValueTypesIntLiteralClientPutOptions) (ValueTypesIntLiteralClientPutResponse, error) { + var err error + const operationName = "ValueTypesIntLiteralClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesIntLiteralClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesIntLiteralClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesIntLiteralClientPutResponse{}, err + } + return ValueTypesIntLiteralClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesIntLiteralClient) putCreateRequest(ctx context.Context, body IntLiteralProperty, _ *ValueTypesIntLiteralClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/int/literal" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypesmodel_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesmodel_client.go new file mode 100644 index 000000000000..7dc56284a723 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesmodel_client.go @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesModelClient contains the methods for the ValueTypesModel group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesModelClient] instead. +type ValueTypesModelClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesModelClientGetOptions contains the optional parameters for the ValueTypesModelClient.Get method. +func (client *ValueTypesModelClient) Get(ctx context.Context, options *ValueTypesModelClientGetOptions) (ValueTypesModelClientGetResponse, error) { + var err error + const operationName = "ValueTypesModelClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesModelClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesModelClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesModelClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesModelClient) getCreateRequest(ctx context.Context, _ *ValueTypesModelClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/model" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesModelClient) getHandleResponse(resp *http.Response) (ValueTypesModelClientGetResponse, error) { + result := ValueTypesModelClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ModelProperty); err != nil { + return ValueTypesModelClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesModelClientPutOptions contains the optional parameters for the ValueTypesModelClient.Put method. +func (client *ValueTypesModelClient) Put(ctx context.Context, body ModelProperty, options *ValueTypesModelClientPutOptions) (ValueTypesModelClientPutResponse, error) { + var err error + const operationName = "ValueTypesModelClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesModelClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesModelClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesModelClientPutResponse{}, err + } + return ValueTypesModelClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesModelClient) putCreateRequest(ctx context.Context, body ModelProperty, _ *ValueTypesModelClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/model" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypesnever_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesnever_client.go new file mode 100644 index 000000000000..52eeea7dab69 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesnever_client.go @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesNeverClient contains the methods for the ValueTypesNever group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesNeverClient] instead. +type ValueTypesNeverClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesNeverClientGetOptions contains the optional parameters for the ValueTypesNeverClient.Get method. +func (client *ValueTypesNeverClient) Get(ctx context.Context, options *ValueTypesNeverClientGetOptions) (ValueTypesNeverClientGetResponse, error) { + var err error + const operationName = "ValueTypesNeverClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesNeverClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesNeverClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesNeverClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesNeverClient) getCreateRequest(ctx context.Context, _ *ValueTypesNeverClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/never" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesNeverClient) getHandleResponse(resp *http.Response) (ValueTypesNeverClientGetResponse, error) { + result := ValueTypesNeverClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.NeverProperty); err != nil { + return ValueTypesNeverClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesNeverClientPutOptions contains the optional parameters for the ValueTypesNeverClient.Put method. +func (client *ValueTypesNeverClient) Put(ctx context.Context, body NeverProperty, options *ValueTypesNeverClientPutOptions) (ValueTypesNeverClientPutResponse, error) { + var err error + const operationName = "ValueTypesNeverClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesNeverClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesNeverClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesNeverClientPutResponse{}, err + } + return ValueTypesNeverClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesNeverClient) putCreateRequest(ctx context.Context, body NeverProperty, _ *ValueTypesNeverClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/never" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypesstring_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesstring_client.go new file mode 100644 index 000000000000..b453dc60220c --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesstring_client.go @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesStringClient contains the methods for the ValueTypesString group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesStringClient] instead. +type ValueTypesStringClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesStringClientGetOptions contains the optional parameters for the ValueTypesStringClient.Get method. +func (client *ValueTypesStringClient) Get(ctx context.Context, options *ValueTypesStringClientGetOptions) (ValueTypesStringClientGetResponse, error) { + var err error + const operationName = "ValueTypesStringClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesStringClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesStringClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesStringClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesStringClient) getCreateRequest(ctx context.Context, _ *ValueTypesStringClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/string" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesStringClient) getHandleResponse(resp *http.Response) (ValueTypesStringClientGetResponse, error) { + result := ValueTypesStringClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.StringProperty); err != nil { + return ValueTypesStringClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesStringClientPutOptions contains the optional parameters for the ValueTypesStringClient.Put method. +func (client *ValueTypesStringClient) Put(ctx context.Context, body StringProperty, options *ValueTypesStringClientPutOptions) (ValueTypesStringClientPutResponse, error) { + var err error + const operationName = "ValueTypesStringClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesStringClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesStringClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesStringClientPutResponse{}, err + } + return ValueTypesStringClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesStringClient) putCreateRequest(ctx context.Context, body StringProperty, _ *ValueTypesStringClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/string" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypesstringliteral_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesstringliteral_client.go new file mode 100644 index 000000000000..eba6f6ab6833 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesstringliteral_client.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesStringLiteralClient contains the methods for the ValueTypesStringLiteral group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesStringLiteralClient] instead. +type ValueTypesStringLiteralClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesStringLiteralClientGetOptions contains the optional parameters for the ValueTypesStringLiteralClient.Get +// method. +func (client *ValueTypesStringLiteralClient) Get(ctx context.Context, options *ValueTypesStringLiteralClientGetOptions) (ValueTypesStringLiteralClientGetResponse, error) { + var err error + const operationName = "ValueTypesStringLiteralClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesStringLiteralClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesStringLiteralClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesStringLiteralClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesStringLiteralClient) getCreateRequest(ctx context.Context, _ *ValueTypesStringLiteralClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/string/literal" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesStringLiteralClient) getHandleResponse(resp *http.Response) (ValueTypesStringLiteralClientGetResponse, error) { + result := ValueTypesStringLiteralClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.StringLiteralProperty); err != nil { + return ValueTypesStringLiteralClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesStringLiteralClientPutOptions contains the optional parameters for the ValueTypesStringLiteralClient.Put +// method. +func (client *ValueTypesStringLiteralClient) Put(ctx context.Context, body StringLiteralProperty, options *ValueTypesStringLiteralClientPutOptions) (ValueTypesStringLiteralClientPutResponse, error) { + var err error + const operationName = "ValueTypesStringLiteralClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesStringLiteralClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesStringLiteralClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesStringLiteralClientPutResponse{}, err + } + return ValueTypesStringLiteralClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesStringLiteralClient) putCreateRequest(ctx context.Context, body StringLiteralProperty, _ *ValueTypesStringLiteralClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/string/literal" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypesunionenumvalue_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesunionenumvalue_client.go new file mode 100644 index 000000000000..3e4eaa8ae367 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesunionenumvalue_client.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesUnionEnumValueClient contains the methods for the ValueTypesUnionEnumValue group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesUnionEnumValueClient] instead. +type ValueTypesUnionEnumValueClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesUnionEnumValueClientGetOptions contains the optional parameters for the ValueTypesUnionEnumValueClient.Get +// method. +func (client *ValueTypesUnionEnumValueClient) Get(ctx context.Context, options *ValueTypesUnionEnumValueClientGetOptions) (ValueTypesUnionEnumValueClientGetResponse, error) { + var err error + const operationName = "ValueTypesUnionEnumValueClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesUnionEnumValueClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesUnionEnumValueClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesUnionEnumValueClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesUnionEnumValueClient) getCreateRequest(ctx context.Context, _ *ValueTypesUnionEnumValueClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/union-enum-value" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesUnionEnumValueClient) getHandleResponse(resp *http.Response) (ValueTypesUnionEnumValueClientGetResponse, error) { + result := ValueTypesUnionEnumValueClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.UnionEnumValueProperty); err != nil { + return ValueTypesUnionEnumValueClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesUnionEnumValueClientPutOptions contains the optional parameters for the ValueTypesUnionEnumValueClient.Put +// method. +func (client *ValueTypesUnionEnumValueClient) Put(ctx context.Context, body UnionEnumValueProperty, options *ValueTypesUnionEnumValueClientPutOptions) (ValueTypesUnionEnumValueClientPutResponse, error) { + var err error + const operationName = "ValueTypesUnionEnumValueClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesUnionEnumValueClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesUnionEnumValueClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesUnionEnumValueClientPutResponse{}, err + } + return ValueTypesUnionEnumValueClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesUnionEnumValueClient) putCreateRequest(ctx context.Context, body UnionEnumValueProperty, _ *ValueTypesUnionEnumValueClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/union-enum-value" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypesunionfloatliteral_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesunionfloatliteral_client.go new file mode 100644 index 000000000000..50424355ecc5 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesunionfloatliteral_client.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesUnionFloatLiteralClient contains the methods for the ValueTypesUnionFloatLiteral group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesUnionFloatLiteralClient] instead. +type ValueTypesUnionFloatLiteralClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesUnionFloatLiteralClientGetOptions contains the optional parameters for the ValueTypesUnionFloatLiteralClient.Get +// method. +func (client *ValueTypesUnionFloatLiteralClient) Get(ctx context.Context, options *ValueTypesUnionFloatLiteralClientGetOptions) (ValueTypesUnionFloatLiteralClientGetResponse, error) { + var err error + const operationName = "ValueTypesUnionFloatLiteralClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesUnionFloatLiteralClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesUnionFloatLiteralClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesUnionFloatLiteralClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesUnionFloatLiteralClient) getCreateRequest(ctx context.Context, _ *ValueTypesUnionFloatLiteralClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/union/float/literal" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesUnionFloatLiteralClient) getHandleResponse(resp *http.Response) (ValueTypesUnionFloatLiteralClientGetResponse, error) { + result := ValueTypesUnionFloatLiteralClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.UnionFloatLiteralProperty); err != nil { + return ValueTypesUnionFloatLiteralClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesUnionFloatLiteralClientPutOptions contains the optional parameters for the ValueTypesUnionFloatLiteralClient.Put +// method. +func (client *ValueTypesUnionFloatLiteralClient) Put(ctx context.Context, body UnionFloatLiteralProperty, options *ValueTypesUnionFloatLiteralClientPutOptions) (ValueTypesUnionFloatLiteralClientPutResponse, error) { + var err error + const operationName = "ValueTypesUnionFloatLiteralClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesUnionFloatLiteralClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesUnionFloatLiteralClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesUnionFloatLiteralClientPutResponse{}, err + } + return ValueTypesUnionFloatLiteralClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesUnionFloatLiteralClient) putCreateRequest(ctx context.Context, body UnionFloatLiteralProperty, _ *ValueTypesUnionFloatLiteralClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/union/float/literal" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypesunionintliteral_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesunionintliteral_client.go new file mode 100644 index 000000000000..cf50edaaa381 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesunionintliteral_client.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesUnionIntLiteralClient contains the methods for the ValueTypesUnionIntLiteral group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesUnionIntLiteralClient] instead. +type ValueTypesUnionIntLiteralClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesUnionIntLiteralClientGetOptions contains the optional parameters for the ValueTypesUnionIntLiteralClient.Get +// method. +func (client *ValueTypesUnionIntLiteralClient) Get(ctx context.Context, options *ValueTypesUnionIntLiteralClientGetOptions) (ValueTypesUnionIntLiteralClientGetResponse, error) { + var err error + const operationName = "ValueTypesUnionIntLiteralClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesUnionIntLiteralClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesUnionIntLiteralClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesUnionIntLiteralClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesUnionIntLiteralClient) getCreateRequest(ctx context.Context, _ *ValueTypesUnionIntLiteralClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/union/int/literal" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesUnionIntLiteralClient) getHandleResponse(resp *http.Response) (ValueTypesUnionIntLiteralClientGetResponse, error) { + result := ValueTypesUnionIntLiteralClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.UnionIntLiteralProperty); err != nil { + return ValueTypesUnionIntLiteralClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesUnionIntLiteralClientPutOptions contains the optional parameters for the ValueTypesUnionIntLiteralClient.Put +// method. +func (client *ValueTypesUnionIntLiteralClient) Put(ctx context.Context, body UnionIntLiteralProperty, options *ValueTypesUnionIntLiteralClientPutOptions) (ValueTypesUnionIntLiteralClientPutResponse, error) { + var err error + const operationName = "ValueTypesUnionIntLiteralClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesUnionIntLiteralClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesUnionIntLiteralClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesUnionIntLiteralClientPutResponse{}, err + } + return ValueTypesUnionIntLiteralClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesUnionIntLiteralClient) putCreateRequest(ctx context.Context, body UnionIntLiteralProperty, _ *ValueTypesUnionIntLiteralClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/union/int/literal" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypesunionstringliteral_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesunionstringliteral_client.go new file mode 100644 index 000000000000..552a2741afa6 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesunionstringliteral_client.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesUnionStringLiteralClient contains the methods for the ValueTypesUnionStringLiteral group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesUnionStringLiteralClient] instead. +type ValueTypesUnionStringLiteralClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesUnionStringLiteralClientGetOptions contains the optional parameters for the ValueTypesUnionStringLiteralClient.Get +// method. +func (client *ValueTypesUnionStringLiteralClient) Get(ctx context.Context, options *ValueTypesUnionStringLiteralClientGetOptions) (ValueTypesUnionStringLiteralClientGetResponse, error) { + var err error + const operationName = "ValueTypesUnionStringLiteralClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesUnionStringLiteralClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesUnionStringLiteralClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesUnionStringLiteralClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesUnionStringLiteralClient) getCreateRequest(ctx context.Context, _ *ValueTypesUnionStringLiteralClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/union/string/literal" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesUnionStringLiteralClient) getHandleResponse(resp *http.Response) (ValueTypesUnionStringLiteralClientGetResponse, error) { + result := ValueTypesUnionStringLiteralClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.UnionStringLiteralProperty); err != nil { + return ValueTypesUnionStringLiteralClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesUnionStringLiteralClientPutOptions contains the optional parameters for the ValueTypesUnionStringLiteralClient.Put +// method. +func (client *ValueTypesUnionStringLiteralClient) Put(ctx context.Context, body UnionStringLiteralProperty, options *ValueTypesUnionStringLiteralClientPutOptions) (ValueTypesUnionStringLiteralClientPutResponse, error) { + var err error + const operationName = "ValueTypesUnionStringLiteralClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesUnionStringLiteralClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesUnionStringLiteralClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesUnionStringLiteralClientPutResponse{}, err + } + return ValueTypesUnionStringLiteralClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesUnionStringLiteralClient) putCreateRequest(ctx context.Context, body UnionStringLiteralProperty, _ *ValueTypesUnionStringLiteralClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/union/string/literal" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypesunknownarray_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesunknownarray_client.go new file mode 100644 index 000000000000..0a22b9bb0141 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesunknownarray_client.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesUnknownArrayClient contains the methods for the ValueTypesUnknownArray group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesUnknownArrayClient] instead. +type ValueTypesUnknownArrayClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesUnknownArrayClientGetOptions contains the optional parameters for the ValueTypesUnknownArrayClient.Get +// method. +func (client *ValueTypesUnknownArrayClient) Get(ctx context.Context, options *ValueTypesUnknownArrayClientGetOptions) (ValueTypesUnknownArrayClientGetResponse, error) { + var err error + const operationName = "ValueTypesUnknownArrayClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesUnknownArrayClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesUnknownArrayClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesUnknownArrayClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesUnknownArrayClient) getCreateRequest(ctx context.Context, _ *ValueTypesUnknownArrayClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/unknown/array" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesUnknownArrayClient) getHandleResponse(resp *http.Response) (ValueTypesUnknownArrayClientGetResponse, error) { + result := ValueTypesUnknownArrayClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.UnknownArrayProperty); err != nil { + return ValueTypesUnknownArrayClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesUnknownArrayClientPutOptions contains the optional parameters for the ValueTypesUnknownArrayClient.Put +// method. +func (client *ValueTypesUnknownArrayClient) Put(ctx context.Context, body UnknownArrayProperty, options *ValueTypesUnknownArrayClientPutOptions) (ValueTypesUnknownArrayClientPutResponse, error) { + var err error + const operationName = "ValueTypesUnknownArrayClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesUnknownArrayClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesUnknownArrayClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesUnknownArrayClientPutResponse{}, err + } + return ValueTypesUnknownArrayClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesUnknownArrayClient) putCreateRequest(ctx context.Context, body UnknownArrayProperty, _ *ValueTypesUnknownArrayClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/unknown/array" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypesunknowndict_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesunknowndict_client.go new file mode 100644 index 000000000000..bd3883f53085 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesunknowndict_client.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesUnknownDictClient contains the methods for the ValueTypesUnknownDict group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesUnknownDictClient] instead. +type ValueTypesUnknownDictClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesUnknownDictClientGetOptions contains the optional parameters for the ValueTypesUnknownDictClient.Get +// method. +func (client *ValueTypesUnknownDictClient) Get(ctx context.Context, options *ValueTypesUnknownDictClientGetOptions) (ValueTypesUnknownDictClientGetResponse, error) { + var err error + const operationName = "ValueTypesUnknownDictClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesUnknownDictClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesUnknownDictClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesUnknownDictClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesUnknownDictClient) getCreateRequest(ctx context.Context, _ *ValueTypesUnknownDictClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/unknown/dict" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesUnknownDictClient) getHandleResponse(resp *http.Response) (ValueTypesUnknownDictClientGetResponse, error) { + result := ValueTypesUnknownDictClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.UnknownDictProperty); err != nil { + return ValueTypesUnknownDictClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesUnknownDictClientPutOptions contains the optional parameters for the ValueTypesUnknownDictClient.Put +// method. +func (client *ValueTypesUnknownDictClient) Put(ctx context.Context, body UnknownDictProperty, options *ValueTypesUnknownDictClientPutOptions) (ValueTypesUnknownDictClientPutResponse, error) { + var err error + const operationName = "ValueTypesUnknownDictClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesUnknownDictClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesUnknownDictClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesUnknownDictClientPutResponse{}, err + } + return ValueTypesUnknownDictClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesUnknownDictClient) putCreateRequest(ctx context.Context, body UnknownDictProperty, _ *ValueTypesUnknownDictClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/unknown/dict" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypesunknownint_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesunknownint_client.go new file mode 100644 index 000000000000..eeb6dc9e7d47 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesunknownint_client.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesUnknownIntClient contains the methods for the ValueTypesUnknownInt group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesUnknownIntClient] instead. +type ValueTypesUnknownIntClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesUnknownIntClientGetOptions contains the optional parameters for the ValueTypesUnknownIntClient.Get +// method. +func (client *ValueTypesUnknownIntClient) Get(ctx context.Context, options *ValueTypesUnknownIntClientGetOptions) (ValueTypesUnknownIntClientGetResponse, error) { + var err error + const operationName = "ValueTypesUnknownIntClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesUnknownIntClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesUnknownIntClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesUnknownIntClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesUnknownIntClient) getCreateRequest(ctx context.Context, _ *ValueTypesUnknownIntClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/unknown/int" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesUnknownIntClient) getHandleResponse(resp *http.Response) (ValueTypesUnknownIntClientGetResponse, error) { + result := ValueTypesUnknownIntClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.UnknownIntProperty); err != nil { + return ValueTypesUnknownIntClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesUnknownIntClientPutOptions contains the optional parameters for the ValueTypesUnknownIntClient.Put +// method. +func (client *ValueTypesUnknownIntClient) Put(ctx context.Context, body UnknownIntProperty, options *ValueTypesUnknownIntClientPutOptions) (ValueTypesUnknownIntClientPutResponse, error) { + var err error + const operationName = "ValueTypesUnknownIntClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesUnknownIntClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesUnknownIntClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesUnknownIntClientPutResponse{}, err + } + return ValueTypesUnknownIntClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesUnknownIntClient) putCreateRequest(ctx context.Context, body UnknownIntProperty, _ *ValueTypesUnknownIntClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/unknown/int" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_valuetypesunknownstring_client.go b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesunknownstring_client.go new file mode 100644 index 000000000000..12b5752bd1dc --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_valuetypesunknownstring_client.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package valuetypesgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ValueTypesUnknownStringClient contains the methods for the ValueTypesUnknownString group. +// Don't use this type directly, use [ValueTypesClient.NewValueTypesUnknownStringClient] instead. +type ValueTypesUnknownStringClient struct { + internal *azcore.Client + endpoint string +} + +// Get - Get call +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ValueTypesUnknownStringClientGetOptions contains the optional parameters for the ValueTypesUnknownStringClient.Get +// method. +func (client *ValueTypesUnknownStringClient) Get(ctx context.Context, options *ValueTypesUnknownStringClientGetOptions) (ValueTypesUnknownStringClientGetResponse, error) { + var err error + const operationName = "ValueTypesUnknownStringClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ValueTypesUnknownStringClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesUnknownStringClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ValueTypesUnknownStringClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ValueTypesUnknownStringClient) getCreateRequest(ctx context.Context, _ *ValueTypesUnknownStringClientGetOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/unknown/string" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ValueTypesUnknownStringClient) getHandleResponse(resp *http.Response) (ValueTypesUnknownStringClientGetResponse, error) { + result := ValueTypesUnknownStringClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.UnknownStringProperty); err != nil { + return ValueTypesUnknownStringClientGetResponse{}, err + } + return result, nil +} + +// Put - Put operation +// If the operation fails it returns an *azcore.ResponseError type. +// - body - body +// - options - ValueTypesUnknownStringClientPutOptions contains the optional parameters for the ValueTypesUnknownStringClient.Put +// method. +func (client *ValueTypesUnknownStringClient) Put(ctx context.Context, body UnknownStringProperty, options *ValueTypesUnknownStringClientPutOptions) (ValueTypesUnknownStringClientPutResponse, error) { + var err error + const operationName = "ValueTypesUnknownStringClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ValueTypesUnknownStringClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ValueTypesUnknownStringClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ValueTypesUnknownStringClientPutResponse{}, err + } + return ValueTypesUnknownStringClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ValueTypesUnknownStringClient) putCreateRequest(ctx context.Context, body UnknownStringProperty, _ *ValueTypesUnknownStringClientPutOptions) (*policy.Request, error) { + urlPath := "/type/property/value-types/unknown/string" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/property/valuetypesgroup/zz_version.go b/test/http-specs/type/property/valuetypesgroup/zz_version.go new file mode 100644 index 000000000000..56d4cf8fe387 --- /dev/null +++ b/test/http-specs/type/property/valuetypesgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package valuetypesgroup + +const ( + moduleName = "valuetypesgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/type/scalargroup/LICENSE.txt b/test/http-specs/type/scalargroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/type/scalargroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/type/scalargroup/boolean_client_test.go b/test/http-specs/type/scalargroup/boolean_client_test.go new file mode 100644 index 000000000000..c47bc1b46ec5 --- /dev/null +++ b/test/http-specs/type/scalargroup/boolean_client_test.go @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package scalargroup_test + +import ( + "context" + "scalargroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestBooleanClient_Get(t *testing.T) { + client, err := scalargroup.NewScalarClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewScalarBooleanClient().Get(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, *resp.Value, true) +} + +func TestBooleanClient_Put(t *testing.T) { + client, err := scalargroup.NewScalarClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewScalarBooleanClient().Put(context.Background(), true, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/scalargroup/decimal128type_client_test.go b/test/http-specs/type/scalargroup/decimal128type_client_test.go new file mode 100644 index 000000000000..ca66c54fa9b1 --- /dev/null +++ b/test/http-specs/type/scalargroup/decimal128type_client_test.go @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package scalargroup_test + +import ( + "context" + "scalargroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestDecimal128TypeClient_RequestBody(t *testing.T) { + client, err := scalargroup.NewScalarClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewScalarDecimal128TypeClient().RequestBody(context.Background(), 0.33333, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestDecimal128TypeClient_RequestParameter(t *testing.T) { + client, err := scalargroup.NewScalarClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewScalarDecimal128TypeClient().RequestParameter(context.Background(), 0.33333, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestDecimal128TypeClient_ResponseBody(t *testing.T) { + client, err := scalargroup.NewScalarClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewScalarDecimal128TypeClient().ResponseBody(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, 0.33333, *resp.Value) +} diff --git a/test/http-specs/type/scalargroup/decimal128verify_client_test.go b/test/http-specs/type/scalargroup/decimal128verify_client_test.go new file mode 100644 index 000000000000..5c6b31b8685b --- /dev/null +++ b/test/http-specs/type/scalargroup/decimal128verify_client_test.go @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package scalargroup_test + +import ( + "context" + "scalargroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestDecimal128VerifyClient_PrepareVerify(t *testing.T) { + client, err := scalargroup.NewScalarClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewScalarDecimal128VerifyClient().PrepareVerify(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, []float64{0.1, 0.1, 0.1}, resp.Float64Array) +} + +func TestDecimal128VerifyClient_Verify(t *testing.T) { + client, err := scalargroup.NewScalarClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewScalarDecimal128VerifyClient().Verify(context.Background(), 0.3, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/scalargroup/decimaltype_client_test.go b/test/http-specs/type/scalargroup/decimaltype_client_test.go new file mode 100644 index 000000000000..16fce47f4e81 --- /dev/null +++ b/test/http-specs/type/scalargroup/decimaltype_client_test.go @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package scalargroup_test + +import ( + "context" + "scalargroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestDecimalTypeClient_RequestBody(t *testing.T) { + client, err := scalargroup.NewScalarClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewScalarDecimalTypeClient().RequestBody(context.Background(), 0.33333, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestDecimalTypeClient_RequestParameter(t *testing.T) { + client, err := scalargroup.NewScalarClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewScalarDecimalTypeClient().RequestParameter(context.Background(), 0.33333, nil) + require.NoError(t, err) + require.Zero(t, resp) +} + +func TestDecimalTypeClient_ResponseBody(t *testing.T) { + client, err := scalargroup.NewScalarClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewScalarDecimalTypeClient().ResponseBody(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, 0.33333, *resp.Value) +} diff --git a/test/http-specs/type/scalargroup/decimalverify_client_test.go b/test/http-specs/type/scalargroup/decimalverify_client_test.go new file mode 100644 index 000000000000..e4c2d4ebe5c7 --- /dev/null +++ b/test/http-specs/type/scalargroup/decimalverify_client_test.go @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package scalargroup_test + +import ( + "context" + "scalargroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestDecimalVerifyClient_PrepareVerify(t *testing.T) { + client, err := scalargroup.NewScalarClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewScalarDecimalVerifyClient().PrepareVerify(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, []float64{0.1, 0.1, 0.1}, resp.Float64Array) +} + +func TestDecimalVerifyClient_Verify(t *testing.T) { + client, err := scalargroup.NewScalarClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewScalarDecimalVerifyClient().Verify(context.Background(), 0.3, nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/scalargroup/fake/zz_internal.go b/test/http-specs/type/scalargroup/fake/zz_internal.go new file mode 100644 index 000000000000..b22dd569d63c --- /dev/null +++ b/test/http-specs/type/scalargroup/fake/zz_internal.go @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func parseWithCast[T any](v string, parse func(v string) (T, error)) (T, error) { + t, err := parse(v) + if err != nil { + return *new(T), err + } + return t, err +} diff --git a/test/http-specs/type/scalargroup/fake/zz_scalar_server.go b/test/http-specs/type/scalargroup/fake/zz_scalar_server.go new file mode 100644 index 000000000000..99d9e9ca0853 --- /dev/null +++ b/test/http-specs/type/scalargroup/fake/zz_scalar_server.go @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ScalarServer is a fake server for instances of the scalargroup.ScalarClient type. +type ScalarServer struct { + // ScalarBooleanServer contains the fakes for client ScalarBooleanClient + ScalarBooleanServer ScalarBooleanServer + + // ScalarDecimal128TypeServer contains the fakes for client ScalarDecimal128TypeClient + ScalarDecimal128TypeServer ScalarDecimal128TypeServer + + // ScalarDecimal128VerifyServer contains the fakes for client ScalarDecimal128VerifyClient + ScalarDecimal128VerifyServer ScalarDecimal128VerifyServer + + // ScalarDecimalTypeServer contains the fakes for client ScalarDecimalTypeClient + ScalarDecimalTypeServer ScalarDecimalTypeServer + + // ScalarDecimalVerifyServer contains the fakes for client ScalarDecimalVerifyClient + ScalarDecimalVerifyServer ScalarDecimalVerifyServer + + // ScalarStringServer contains the fakes for client ScalarStringClient + ScalarStringServer ScalarStringServer + + // ScalarUnknownServer contains the fakes for client ScalarUnknownClient + ScalarUnknownServer ScalarUnknownServer +} + +// NewScalarServerTransport creates a new instance of ScalarServerTransport with the provided implementation. +// The returned ScalarServerTransport instance is connected to an instance of scalargroup.ScalarClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewScalarServerTransport(srv *ScalarServer) *ScalarServerTransport { + return &ScalarServerTransport{srv: srv} +} + +// ScalarServerTransport connects instances of scalargroup.ScalarClient to instances of ScalarServer. +// Don't use this type directly, use NewScalarServerTransport instead. +type ScalarServerTransport struct { + srv *ScalarServer + trMu sync.Mutex + trScalarBooleanServer *ScalarBooleanServerTransport + trScalarDecimal128TypeServer *ScalarDecimal128TypeServerTransport + trScalarDecimal128VerifyServer *ScalarDecimal128VerifyServerTransport + trScalarDecimalTypeServer *ScalarDecimalTypeServerTransport + trScalarDecimalVerifyServer *ScalarDecimalVerifyServerTransport + trScalarStringServer *ScalarStringServerTransport + trScalarUnknownServer *ScalarUnknownServerTransport +} + +// Do implements the policy.Transporter interface for ScalarServerTransport. +func (s *ScalarServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (s *ScalarServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "ScalarBooleanClient": + initServer(&s.trMu, &s.trScalarBooleanServer, func() *ScalarBooleanServerTransport { + return NewScalarBooleanServerTransport(&s.srv.ScalarBooleanServer) + }) + resp, err = s.trScalarBooleanServer.Do(req) + case "ScalarDecimal128TypeClient": + initServer(&s.trMu, &s.trScalarDecimal128TypeServer, func() *ScalarDecimal128TypeServerTransport { + return NewScalarDecimal128TypeServerTransport(&s.srv.ScalarDecimal128TypeServer) + }) + resp, err = s.trScalarDecimal128TypeServer.Do(req) + case "ScalarDecimal128VerifyClient": + initServer(&s.trMu, &s.trScalarDecimal128VerifyServer, func() *ScalarDecimal128VerifyServerTransport { + return NewScalarDecimal128VerifyServerTransport(&s.srv.ScalarDecimal128VerifyServer) + }) + resp, err = s.trScalarDecimal128VerifyServer.Do(req) + case "ScalarDecimalTypeClient": + initServer(&s.trMu, &s.trScalarDecimalTypeServer, func() *ScalarDecimalTypeServerTransport { + return NewScalarDecimalTypeServerTransport(&s.srv.ScalarDecimalTypeServer) + }) + resp, err = s.trScalarDecimalTypeServer.Do(req) + case "ScalarDecimalVerifyClient": + initServer(&s.trMu, &s.trScalarDecimalVerifyServer, func() *ScalarDecimalVerifyServerTransport { + return NewScalarDecimalVerifyServerTransport(&s.srv.ScalarDecimalVerifyServer) + }) + resp, err = s.trScalarDecimalVerifyServer.Do(req) + case "ScalarStringClient": + initServer(&s.trMu, &s.trScalarStringServer, func() *ScalarStringServerTransport { + return NewScalarStringServerTransport(&s.srv.ScalarStringServer) + }) + resp, err = s.trScalarStringServer.Do(req) + case "ScalarUnknownClient": + initServer(&s.trMu, &s.trScalarUnknownServer, func() *ScalarUnknownServerTransport { + return NewScalarUnknownServerTransport(&s.srv.ScalarUnknownServer) + }) + resp, err = s.trScalarUnknownServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to ScalarServerTransport +var scalarServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/scalargroup/fake/zz_scalarboolean_server.go b/test/http-specs/type/scalargroup/fake/zz_scalarboolean_server.go new file mode 100644 index 000000000000..4e0b89494c21 --- /dev/null +++ b/test/http-specs/type/scalargroup/fake/zz_scalarboolean_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "scalargroup" + "slices" +) + +// ScalarBooleanServer is a fake server for instances of the scalargroup.ScalarBooleanClient type. +type ScalarBooleanServer struct { + // Get is the fake for method ScalarBooleanClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *scalargroup.ScalarBooleanClientGetOptions) (resp azfake.Responder[scalargroup.ScalarBooleanClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ScalarBooleanClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body bool, options *scalargroup.ScalarBooleanClientPutOptions) (resp azfake.Responder[scalargroup.ScalarBooleanClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewScalarBooleanServerTransport creates a new instance of ScalarBooleanServerTransport with the provided implementation. +// The returned ScalarBooleanServerTransport instance is connected to an instance of scalargroup.ScalarBooleanClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewScalarBooleanServerTransport(srv *ScalarBooleanServer) *ScalarBooleanServerTransport { + return &ScalarBooleanServerTransport{srv: srv} +} + +// ScalarBooleanServerTransport connects instances of scalargroup.ScalarBooleanClient to instances of ScalarBooleanServer. +// Don't use this type directly, use NewScalarBooleanServerTransport instead. +type ScalarBooleanServerTransport struct { + srv *ScalarBooleanServer +} + +// Do implements the policy.Transporter interface for ScalarBooleanServerTransport. +func (s *ScalarBooleanServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ScalarBooleanServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if scalarBooleanServerTransportInterceptor != nil { + res.resp, res.err, intercepted = scalarBooleanServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ScalarBooleanClient.Get": + res.resp, res.err = s.dispatchGet(req) + case "ScalarBooleanClient.Put": + res.resp, res.err = s.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ScalarBooleanServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if s.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := s.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Value, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScalarBooleanServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if s.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[bool](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ScalarBooleanServerTransport +var scalarBooleanServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/scalargroup/fake/zz_scalardecimal128type_server.go b/test/http-specs/type/scalargroup/fake/zz_scalardecimal128type_server.go new file mode 100644 index 000000000000..43abea7d3ea5 --- /dev/null +++ b/test/http-specs/type/scalargroup/fake/zz_scalardecimal128type_server.go @@ -0,0 +1,161 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "scalargroup" + "slices" + "strconv" +) + +// ScalarDecimal128TypeServer is a fake server for instances of the scalargroup.ScalarDecimal128TypeClient type. +type ScalarDecimal128TypeServer struct { + // RequestBody is the fake for method ScalarDecimal128TypeClient.RequestBody + // HTTP status codes to indicate success: http.StatusNoContent + RequestBody func(ctx context.Context, body float64, options *scalargroup.ScalarDecimal128TypeClientRequestBodyOptions) (resp azfake.Responder[scalargroup.ScalarDecimal128TypeClientRequestBodyResponse], errResp azfake.ErrorResponder) + + // RequestParameter is the fake for method ScalarDecimal128TypeClient.RequestParameter + // HTTP status codes to indicate success: http.StatusNoContent + RequestParameter func(ctx context.Context, value float64, options *scalargroup.ScalarDecimal128TypeClientRequestParameterOptions) (resp azfake.Responder[scalargroup.ScalarDecimal128TypeClientRequestParameterResponse], errResp azfake.ErrorResponder) + + // ResponseBody is the fake for method ScalarDecimal128TypeClient.ResponseBody + // HTTP status codes to indicate success: http.StatusOK + ResponseBody func(ctx context.Context, options *scalargroup.ScalarDecimal128TypeClientResponseBodyOptions) (resp azfake.Responder[scalargroup.ScalarDecimal128TypeClientResponseBodyResponse], errResp azfake.ErrorResponder) +} + +// NewScalarDecimal128TypeServerTransport creates a new instance of ScalarDecimal128TypeServerTransport with the provided implementation. +// The returned ScalarDecimal128TypeServerTransport instance is connected to an instance of scalargroup.ScalarDecimal128TypeClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewScalarDecimal128TypeServerTransport(srv *ScalarDecimal128TypeServer) *ScalarDecimal128TypeServerTransport { + return &ScalarDecimal128TypeServerTransport{srv: srv} +} + +// ScalarDecimal128TypeServerTransport connects instances of scalargroup.ScalarDecimal128TypeClient to instances of ScalarDecimal128TypeServer. +// Don't use this type directly, use NewScalarDecimal128TypeServerTransport instead. +type ScalarDecimal128TypeServerTransport struct { + srv *ScalarDecimal128TypeServer +} + +// Do implements the policy.Transporter interface for ScalarDecimal128TypeServerTransport. +func (s *ScalarDecimal128TypeServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ScalarDecimal128TypeServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if scalarDecimal128TypeServerTransportInterceptor != nil { + res.resp, res.err, intercepted = scalarDecimal128TypeServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ScalarDecimal128TypeClient.RequestBody": + res.resp, res.err = s.dispatchRequestBody(req) + case "ScalarDecimal128TypeClient.RequestParameter": + res.resp, res.err = s.dispatchRequestParameter(req) + case "ScalarDecimal128TypeClient.ResponseBody": + res.resp, res.err = s.dispatchResponseBody(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ScalarDecimal128TypeServerTransport) dispatchRequestBody(req *http.Request) (*http.Response, error) { + if s.srv.RequestBody == nil { + return nil, &nonRetriableError{errors.New("fake for method RequestBody not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[float64](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.RequestBody(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScalarDecimal128TypeServerTransport) dispatchRequestParameter(req *http.Request) (*http.Response, error) { + if s.srv.RequestParameter == nil { + return nil, &nonRetriableError{errors.New("fake for method RequestParameter not implemented")} + } + qp := req.URL.Query() + valueParam, err := strconv.ParseFloat(qp.Get("value"), 64) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.RequestParameter(req.Context(), valueParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScalarDecimal128TypeServerTransport) dispatchResponseBody(req *http.Request) (*http.Response, error) { + if s.srv.ResponseBody == nil { + return nil, &nonRetriableError{errors.New("fake for method ResponseBody not implemented")} + } + respr, errRespr := s.srv.ResponseBody(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Value, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ScalarDecimal128TypeServerTransport +var scalarDecimal128TypeServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/scalargroup/fake/zz_scalardecimal128verify_server.go b/test/http-specs/type/scalargroup/fake/zz_scalardecimal128verify_server.go new file mode 100644 index 000000000000..26acffb50b7a --- /dev/null +++ b/test/http-specs/type/scalargroup/fake/zz_scalardecimal128verify_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "scalargroup" + "slices" +) + +// ScalarDecimal128VerifyServer is a fake server for instances of the scalargroup.ScalarDecimal128VerifyClient type. +type ScalarDecimal128VerifyServer struct { + // PrepareVerify is the fake for method ScalarDecimal128VerifyClient.PrepareVerify + // HTTP status codes to indicate success: http.StatusOK + PrepareVerify func(ctx context.Context, options *scalargroup.ScalarDecimal128VerifyClientPrepareVerifyOptions) (resp azfake.Responder[scalargroup.ScalarDecimal128VerifyClientPrepareVerifyResponse], errResp azfake.ErrorResponder) + + // Verify is the fake for method ScalarDecimal128VerifyClient.Verify + // HTTP status codes to indicate success: http.StatusNoContent + Verify func(ctx context.Context, body float64, options *scalargroup.ScalarDecimal128VerifyClientVerifyOptions) (resp azfake.Responder[scalargroup.ScalarDecimal128VerifyClientVerifyResponse], errResp azfake.ErrorResponder) +} + +// NewScalarDecimal128VerifyServerTransport creates a new instance of ScalarDecimal128VerifyServerTransport with the provided implementation. +// The returned ScalarDecimal128VerifyServerTransport instance is connected to an instance of scalargroup.ScalarDecimal128VerifyClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewScalarDecimal128VerifyServerTransport(srv *ScalarDecimal128VerifyServer) *ScalarDecimal128VerifyServerTransport { + return &ScalarDecimal128VerifyServerTransport{srv: srv} +} + +// ScalarDecimal128VerifyServerTransport connects instances of scalargroup.ScalarDecimal128VerifyClient to instances of ScalarDecimal128VerifyServer. +// Don't use this type directly, use NewScalarDecimal128VerifyServerTransport instead. +type ScalarDecimal128VerifyServerTransport struct { + srv *ScalarDecimal128VerifyServer +} + +// Do implements the policy.Transporter interface for ScalarDecimal128VerifyServerTransport. +func (s *ScalarDecimal128VerifyServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ScalarDecimal128VerifyServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if scalarDecimal128VerifyServerTransportInterceptor != nil { + res.resp, res.err, intercepted = scalarDecimal128VerifyServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ScalarDecimal128VerifyClient.PrepareVerify": + res.resp, res.err = s.dispatchPrepareVerify(req) + case "ScalarDecimal128VerifyClient.Verify": + res.resp, res.err = s.dispatchVerify(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ScalarDecimal128VerifyServerTransport) dispatchPrepareVerify(req *http.Request) (*http.Response, error) { + if s.srv.PrepareVerify == nil { + return nil, &nonRetriableError{errors.New("fake for method PrepareVerify not implemented")} + } + respr, errRespr := s.srv.PrepareVerify(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Float64Array, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScalarDecimal128VerifyServerTransport) dispatchVerify(req *http.Request) (*http.Response, error) { + if s.srv.Verify == nil { + return nil, &nonRetriableError{errors.New("fake for method Verify not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[float64](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Verify(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ScalarDecimal128VerifyServerTransport +var scalarDecimal128VerifyServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/scalargroup/fake/zz_scalardecimaltype_server.go b/test/http-specs/type/scalargroup/fake/zz_scalardecimaltype_server.go new file mode 100644 index 000000000000..2ce1ca3d4883 --- /dev/null +++ b/test/http-specs/type/scalargroup/fake/zz_scalardecimaltype_server.go @@ -0,0 +1,161 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "scalargroup" + "slices" + "strconv" +) + +// ScalarDecimalTypeServer is a fake server for instances of the scalargroup.ScalarDecimalTypeClient type. +type ScalarDecimalTypeServer struct { + // RequestBody is the fake for method ScalarDecimalTypeClient.RequestBody + // HTTP status codes to indicate success: http.StatusNoContent + RequestBody func(ctx context.Context, body float64, options *scalargroup.ScalarDecimalTypeClientRequestBodyOptions) (resp azfake.Responder[scalargroup.ScalarDecimalTypeClientRequestBodyResponse], errResp azfake.ErrorResponder) + + // RequestParameter is the fake for method ScalarDecimalTypeClient.RequestParameter + // HTTP status codes to indicate success: http.StatusNoContent + RequestParameter func(ctx context.Context, value float64, options *scalargroup.ScalarDecimalTypeClientRequestParameterOptions) (resp azfake.Responder[scalargroup.ScalarDecimalTypeClientRequestParameterResponse], errResp azfake.ErrorResponder) + + // ResponseBody is the fake for method ScalarDecimalTypeClient.ResponseBody + // HTTP status codes to indicate success: http.StatusOK + ResponseBody func(ctx context.Context, options *scalargroup.ScalarDecimalTypeClientResponseBodyOptions) (resp azfake.Responder[scalargroup.ScalarDecimalTypeClientResponseBodyResponse], errResp azfake.ErrorResponder) +} + +// NewScalarDecimalTypeServerTransport creates a new instance of ScalarDecimalTypeServerTransport with the provided implementation. +// The returned ScalarDecimalTypeServerTransport instance is connected to an instance of scalargroup.ScalarDecimalTypeClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewScalarDecimalTypeServerTransport(srv *ScalarDecimalTypeServer) *ScalarDecimalTypeServerTransport { + return &ScalarDecimalTypeServerTransport{srv: srv} +} + +// ScalarDecimalTypeServerTransport connects instances of scalargroup.ScalarDecimalTypeClient to instances of ScalarDecimalTypeServer. +// Don't use this type directly, use NewScalarDecimalTypeServerTransport instead. +type ScalarDecimalTypeServerTransport struct { + srv *ScalarDecimalTypeServer +} + +// Do implements the policy.Transporter interface for ScalarDecimalTypeServerTransport. +func (s *ScalarDecimalTypeServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ScalarDecimalTypeServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if scalarDecimalTypeServerTransportInterceptor != nil { + res.resp, res.err, intercepted = scalarDecimalTypeServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ScalarDecimalTypeClient.RequestBody": + res.resp, res.err = s.dispatchRequestBody(req) + case "ScalarDecimalTypeClient.RequestParameter": + res.resp, res.err = s.dispatchRequestParameter(req) + case "ScalarDecimalTypeClient.ResponseBody": + res.resp, res.err = s.dispatchResponseBody(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ScalarDecimalTypeServerTransport) dispatchRequestBody(req *http.Request) (*http.Response, error) { + if s.srv.RequestBody == nil { + return nil, &nonRetriableError{errors.New("fake for method RequestBody not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[float64](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.RequestBody(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScalarDecimalTypeServerTransport) dispatchRequestParameter(req *http.Request) (*http.Response, error) { + if s.srv.RequestParameter == nil { + return nil, &nonRetriableError{errors.New("fake for method RequestParameter not implemented")} + } + qp := req.URL.Query() + valueParam, err := strconv.ParseFloat(qp.Get("value"), 64) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.RequestParameter(req.Context(), valueParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScalarDecimalTypeServerTransport) dispatchResponseBody(req *http.Request) (*http.Response, error) { + if s.srv.ResponseBody == nil { + return nil, &nonRetriableError{errors.New("fake for method ResponseBody not implemented")} + } + respr, errRespr := s.srv.ResponseBody(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Value, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ScalarDecimalTypeServerTransport +var scalarDecimalTypeServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/scalargroup/fake/zz_scalardecimalverify_server.go b/test/http-specs/type/scalargroup/fake/zz_scalardecimalverify_server.go new file mode 100644 index 000000000000..f5346021cc1c --- /dev/null +++ b/test/http-specs/type/scalargroup/fake/zz_scalardecimalverify_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "scalargroup" + "slices" +) + +// ScalarDecimalVerifyServer is a fake server for instances of the scalargroup.ScalarDecimalVerifyClient type. +type ScalarDecimalVerifyServer struct { + // PrepareVerify is the fake for method ScalarDecimalVerifyClient.PrepareVerify + // HTTP status codes to indicate success: http.StatusOK + PrepareVerify func(ctx context.Context, options *scalargroup.ScalarDecimalVerifyClientPrepareVerifyOptions) (resp azfake.Responder[scalargroup.ScalarDecimalVerifyClientPrepareVerifyResponse], errResp azfake.ErrorResponder) + + // Verify is the fake for method ScalarDecimalVerifyClient.Verify + // HTTP status codes to indicate success: http.StatusNoContent + Verify func(ctx context.Context, body float64, options *scalargroup.ScalarDecimalVerifyClientVerifyOptions) (resp azfake.Responder[scalargroup.ScalarDecimalVerifyClientVerifyResponse], errResp azfake.ErrorResponder) +} + +// NewScalarDecimalVerifyServerTransport creates a new instance of ScalarDecimalVerifyServerTransport with the provided implementation. +// The returned ScalarDecimalVerifyServerTransport instance is connected to an instance of scalargroup.ScalarDecimalVerifyClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewScalarDecimalVerifyServerTransport(srv *ScalarDecimalVerifyServer) *ScalarDecimalVerifyServerTransport { + return &ScalarDecimalVerifyServerTransport{srv: srv} +} + +// ScalarDecimalVerifyServerTransport connects instances of scalargroup.ScalarDecimalVerifyClient to instances of ScalarDecimalVerifyServer. +// Don't use this type directly, use NewScalarDecimalVerifyServerTransport instead. +type ScalarDecimalVerifyServerTransport struct { + srv *ScalarDecimalVerifyServer +} + +// Do implements the policy.Transporter interface for ScalarDecimalVerifyServerTransport. +func (s *ScalarDecimalVerifyServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ScalarDecimalVerifyServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if scalarDecimalVerifyServerTransportInterceptor != nil { + res.resp, res.err, intercepted = scalarDecimalVerifyServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ScalarDecimalVerifyClient.PrepareVerify": + res.resp, res.err = s.dispatchPrepareVerify(req) + case "ScalarDecimalVerifyClient.Verify": + res.resp, res.err = s.dispatchVerify(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ScalarDecimalVerifyServerTransport) dispatchPrepareVerify(req *http.Request) (*http.Response, error) { + if s.srv.PrepareVerify == nil { + return nil, &nonRetriableError{errors.New("fake for method PrepareVerify not implemented")} + } + respr, errRespr := s.srv.PrepareVerify(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Float64Array, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScalarDecimalVerifyServerTransport) dispatchVerify(req *http.Request) (*http.Response, error) { + if s.srv.Verify == nil { + return nil, &nonRetriableError{errors.New("fake for method Verify not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[float64](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Verify(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ScalarDecimalVerifyServerTransport +var scalarDecimalVerifyServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/scalargroup/fake/zz_scalarstring_server.go b/test/http-specs/type/scalargroup/fake/zz_scalarstring_server.go new file mode 100644 index 000000000000..683f934f7478 --- /dev/null +++ b/test/http-specs/type/scalargroup/fake/zz_scalarstring_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "scalargroup" + "slices" +) + +// ScalarStringServer is a fake server for instances of the scalargroup.ScalarStringClient type. +type ScalarStringServer struct { + // Get is the fake for method ScalarStringClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *scalargroup.ScalarStringClientGetOptions) (resp azfake.Responder[scalargroup.ScalarStringClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ScalarStringClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body string, options *scalargroup.ScalarStringClientPutOptions) (resp azfake.Responder[scalargroup.ScalarStringClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewScalarStringServerTransport creates a new instance of ScalarStringServerTransport with the provided implementation. +// The returned ScalarStringServerTransport instance is connected to an instance of scalargroup.ScalarStringClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewScalarStringServerTransport(srv *ScalarStringServer) *ScalarStringServerTransport { + return &ScalarStringServerTransport{srv: srv} +} + +// ScalarStringServerTransport connects instances of scalargroup.ScalarStringClient to instances of ScalarStringServer. +// Don't use this type directly, use NewScalarStringServerTransport instead. +type ScalarStringServerTransport struct { + srv *ScalarStringServer +} + +// Do implements the policy.Transporter interface for ScalarStringServerTransport. +func (s *ScalarStringServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ScalarStringServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if scalarStringServerTransportInterceptor != nil { + res.resp, res.err, intercepted = scalarStringServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ScalarStringClient.Get": + res.resp, res.err = s.dispatchGet(req) + case "ScalarStringClient.Put": + res.resp, res.err = s.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ScalarStringServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if s.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := s.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Value, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScalarStringServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if s.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[string](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ScalarStringServerTransport +var scalarStringServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/scalargroup/fake/zz_scalarunknown_server.go b/test/http-specs/type/scalargroup/fake/zz_scalarunknown_server.go new file mode 100644 index 000000000000..22009cb57403 --- /dev/null +++ b/test/http-specs/type/scalargroup/fake/zz_scalarunknown_server.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "scalargroup" + "slices" +) + +// ScalarUnknownServer is a fake server for instances of the scalargroup.ScalarUnknownClient type. +type ScalarUnknownServer struct { + // Get is the fake for method ScalarUnknownClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *scalargroup.ScalarUnknownClientGetOptions) (resp azfake.Responder[scalargroup.ScalarUnknownClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method ScalarUnknownClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body any, options *scalargroup.ScalarUnknownClientPutOptions) (resp azfake.Responder[scalargroup.ScalarUnknownClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewScalarUnknownServerTransport creates a new instance of ScalarUnknownServerTransport with the provided implementation. +// The returned ScalarUnknownServerTransport instance is connected to an instance of scalargroup.ScalarUnknownClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewScalarUnknownServerTransport(srv *ScalarUnknownServer) *ScalarUnknownServerTransport { + return &ScalarUnknownServerTransport{srv: srv} +} + +// ScalarUnknownServerTransport connects instances of scalargroup.ScalarUnknownClient to instances of ScalarUnknownServer. +// Don't use this type directly, use NewScalarUnknownServerTransport instead. +type ScalarUnknownServerTransport struct { + srv *ScalarUnknownServer +} + +// Do implements the policy.Transporter interface for ScalarUnknownServerTransport. +func (s *ScalarUnknownServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ScalarUnknownServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if scalarUnknownServerTransportInterceptor != nil { + res.resp, res.err, intercepted = scalarUnknownServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ScalarUnknownClient.Get": + res.resp, res.err = s.dispatchGet(req) + case "ScalarUnknownClient.Put": + res.resp, res.err = s.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ScalarUnknownServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if s.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := s.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Interface, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScalarUnknownServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if s.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[any](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ScalarUnknownServerTransport +var scalarUnknownServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/type/scalargroup/go.mod b/test/http-specs/type/scalargroup/go.mod new file mode 100644 index 000000000000..a02d8194ccb9 --- /dev/null +++ b/test/http-specs/type/scalargroup/go.mod @@ -0,0 +1,17 @@ +module scalargroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/type/scalargroup/go.sum b/test/http-specs/type/scalargroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/type/scalargroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/type/scalargroup/string_client_test.go b/test/http-specs/type/scalargroup/string_client_test.go new file mode 100644 index 000000000000..8c8d942e4ca6 --- /dev/null +++ b/test/http-specs/type/scalargroup/string_client_test.go @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package scalargroup_test + +import ( + "context" + "scalargroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestStringClient_Get(t *testing.T) { + client, err := scalargroup.NewScalarClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewScalarStringClient().Get(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, "test", *resp.Value) +} + +func TestStringClient_Put(t *testing.T) { + client, err := scalargroup.NewScalarClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewScalarStringClient().Put(context.Background(), "test", nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/scalargroup/testdata/_metadata.json b/test/http-specs/type/scalargroup/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/http-specs/type/scalargroup/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/type/scalargroup/unknown_client_test.go b/test/http-specs/type/scalargroup/unknown_client_test.go new file mode 100644 index 000000000000..4b162c7e7412 --- /dev/null +++ b/test/http-specs/type/scalargroup/unknown_client_test.go @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package scalargroup_test + +import ( + "context" + "scalargroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestUnknownClient_Get(t *testing.T) { + client, err := scalargroup.NewScalarClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewScalarUnknownClient().Get(context.Background(), nil) + require.NoError(t, err) + require.EqualValues(t, "test", resp.Interface) +} + +func TestUnknownClient_Put(t *testing.T) { + client, err := scalargroup.NewScalarClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.NewScalarUnknownClient().Put(context.Background(), "test", nil) + require.NoError(t, err) + require.Zero(t, resp) +} diff --git a/test/http-specs/type/scalargroup/zz_options.go b/test/http-specs/type/scalargroup/zz_options.go new file mode 100644 index 000000000000..5e83c96d54ee --- /dev/null +++ b/test/http-specs/type/scalargroup/zz_options.go @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package scalargroup + +// ScalarBooleanClientGetOptions contains the optional parameters for the ScalarBooleanClient.Get method. +type ScalarBooleanClientGetOptions struct { + // placeholder for future optional parameters +} + +// ScalarBooleanClientPutOptions contains the optional parameters for the ScalarBooleanClient.Put method. +type ScalarBooleanClientPutOptions struct { + // placeholder for future optional parameters +} + +// ScalarDecimal128TypeClientRequestBodyOptions contains the optional parameters for the ScalarDecimal128TypeClient.RequestBody +// method. +type ScalarDecimal128TypeClientRequestBodyOptions struct { + // placeholder for future optional parameters +} + +// ScalarDecimal128TypeClientRequestParameterOptions contains the optional parameters for the ScalarDecimal128TypeClient.RequestParameter +// method. +type ScalarDecimal128TypeClientRequestParameterOptions struct { + // placeholder for future optional parameters +} + +// ScalarDecimal128TypeClientResponseBodyOptions contains the optional parameters for the ScalarDecimal128TypeClient.ResponseBody +// method. +type ScalarDecimal128TypeClientResponseBodyOptions struct { + // placeholder for future optional parameters +} + +// ScalarDecimal128VerifyClientPrepareVerifyOptions contains the optional parameters for the ScalarDecimal128VerifyClient.PrepareVerify +// method. +type ScalarDecimal128VerifyClientPrepareVerifyOptions struct { + // placeholder for future optional parameters +} + +// ScalarDecimal128VerifyClientVerifyOptions contains the optional parameters for the ScalarDecimal128VerifyClient.Verify +// method. +type ScalarDecimal128VerifyClientVerifyOptions struct { + // placeholder for future optional parameters +} + +// ScalarDecimalTypeClientRequestBodyOptions contains the optional parameters for the ScalarDecimalTypeClient.RequestBody +// method. +type ScalarDecimalTypeClientRequestBodyOptions struct { + // placeholder for future optional parameters +} + +// ScalarDecimalTypeClientRequestParameterOptions contains the optional parameters for the ScalarDecimalTypeClient.RequestParameter +// method. +type ScalarDecimalTypeClientRequestParameterOptions struct { + // placeholder for future optional parameters +} + +// ScalarDecimalTypeClientResponseBodyOptions contains the optional parameters for the ScalarDecimalTypeClient.ResponseBody +// method. +type ScalarDecimalTypeClientResponseBodyOptions struct { + // placeholder for future optional parameters +} + +// ScalarDecimalVerifyClientPrepareVerifyOptions contains the optional parameters for the ScalarDecimalVerifyClient.PrepareVerify +// method. +type ScalarDecimalVerifyClientPrepareVerifyOptions struct { + // placeholder for future optional parameters +} + +// ScalarDecimalVerifyClientVerifyOptions contains the optional parameters for the ScalarDecimalVerifyClient.Verify method. +type ScalarDecimalVerifyClientVerifyOptions struct { + // placeholder for future optional parameters +} + +// ScalarStringClientGetOptions contains the optional parameters for the ScalarStringClient.Get method. +type ScalarStringClientGetOptions struct { + // placeholder for future optional parameters +} + +// ScalarStringClientPutOptions contains the optional parameters for the ScalarStringClient.Put method. +type ScalarStringClientPutOptions struct { + // placeholder for future optional parameters +} + +// ScalarUnknownClientGetOptions contains the optional parameters for the ScalarUnknownClient.Get method. +type ScalarUnknownClientGetOptions struct { + // placeholder for future optional parameters +} + +// ScalarUnknownClientPutOptions contains the optional parameters for the ScalarUnknownClient.Put method. +type ScalarUnknownClientPutOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/type/scalargroup/zz_responses.go b/test/http-specs/type/scalargroup/zz_responses.go new file mode 100644 index 000000000000..f2681dfcc60d --- /dev/null +++ b/test/http-specs/type/scalargroup/zz_responses.go @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package scalargroup + +// ScalarBooleanClientGetResponse contains the response from method ScalarBooleanClient.Get. +type ScalarBooleanClientGetResponse struct { + Value *bool +} + +// ScalarBooleanClientPutResponse contains the response from method ScalarBooleanClient.Put. +type ScalarBooleanClientPutResponse struct { + // placeholder for future response values +} + +// ScalarDecimal128TypeClientRequestBodyResponse contains the response from method ScalarDecimal128TypeClient.RequestBody. +type ScalarDecimal128TypeClientRequestBodyResponse struct { + // placeholder for future response values +} + +// ScalarDecimal128TypeClientRequestParameterResponse contains the response from method ScalarDecimal128TypeClient.RequestParameter. +type ScalarDecimal128TypeClientRequestParameterResponse struct { + // placeholder for future response values +} + +// ScalarDecimal128TypeClientResponseBodyResponse contains the response from method ScalarDecimal128TypeClient.ResponseBody. +type ScalarDecimal128TypeClientResponseBodyResponse struct { + Value *float64 +} + +// ScalarDecimal128VerifyClientPrepareVerifyResponse contains the response from method ScalarDecimal128VerifyClient.PrepareVerify. +type ScalarDecimal128VerifyClientPrepareVerifyResponse struct { + Float64Array []float64 +} + +// ScalarDecimal128VerifyClientVerifyResponse contains the response from method ScalarDecimal128VerifyClient.Verify. +type ScalarDecimal128VerifyClientVerifyResponse struct { + // placeholder for future response values +} + +// ScalarDecimalTypeClientRequestBodyResponse contains the response from method ScalarDecimalTypeClient.RequestBody. +type ScalarDecimalTypeClientRequestBodyResponse struct { + // placeholder for future response values +} + +// ScalarDecimalTypeClientRequestParameterResponse contains the response from method ScalarDecimalTypeClient.RequestParameter. +type ScalarDecimalTypeClientRequestParameterResponse struct { + // placeholder for future response values +} + +// ScalarDecimalTypeClientResponseBodyResponse contains the response from method ScalarDecimalTypeClient.ResponseBody. +type ScalarDecimalTypeClientResponseBodyResponse struct { + Value *float64 +} + +// ScalarDecimalVerifyClientPrepareVerifyResponse contains the response from method ScalarDecimalVerifyClient.PrepareVerify. +type ScalarDecimalVerifyClientPrepareVerifyResponse struct { + Float64Array []float64 +} + +// ScalarDecimalVerifyClientVerifyResponse contains the response from method ScalarDecimalVerifyClient.Verify. +type ScalarDecimalVerifyClientVerifyResponse struct { + // placeholder for future response values +} + +// ScalarStringClientGetResponse contains the response from method ScalarStringClient.Get. +type ScalarStringClientGetResponse struct { + Value *string +} + +// ScalarStringClientPutResponse contains the response from method ScalarStringClient.Put. +type ScalarStringClientPutResponse struct { + // placeholder for future response values +} + +// ScalarUnknownClientGetResponse contains the response from method ScalarUnknownClient.Get. +type ScalarUnknownClientGetResponse struct { + Interface any +} + +// ScalarUnknownClientPutResponse contains the response from method ScalarUnknownClient.Put. +type ScalarUnknownClientPutResponse struct { + // placeholder for future response values +} diff --git a/test/http-specs/type/scalargroup/zz_scalar_client.go b/test/http-specs/type/scalargroup/zz_scalar_client.go new file mode 100644 index 000000000000..c35321d65f71 --- /dev/null +++ b/test/http-specs/type/scalargroup/zz_scalar_client.go @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package scalargroup + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// ScalarClient contains the methods for the Scalar group. +// Don't use this type directly, use NewScalarClientWithNoCredential() instead. +type ScalarClient struct { + internal *azcore.Client + endpoint string +} + +// ScalarClientOptions contains the optional values for creating a [ScalarClient]. +type ScalarClientOptions struct { + azcore.ClientOptions +} + +// NewScalarClientWithNoCredential creates a new instance of ScalarClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewScalarClientWithNoCredential(endpoint string, options *ScalarClientOptions) (*ScalarClient, error) { + if options == nil { + options = &ScalarClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &ScalarClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewScalarBooleanClient creates a new instance of [ScalarBooleanClient]. +func (client *ScalarClient) NewScalarBooleanClient() *ScalarBooleanClient { + return &ScalarBooleanClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewScalarDecimal128TypeClient creates a new instance of [ScalarDecimal128TypeClient]. +func (client *ScalarClient) NewScalarDecimal128TypeClient() *ScalarDecimal128TypeClient { + return &ScalarDecimal128TypeClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewScalarDecimal128VerifyClient creates a new instance of [ScalarDecimal128VerifyClient]. +func (client *ScalarClient) NewScalarDecimal128VerifyClient() *ScalarDecimal128VerifyClient { + return &ScalarDecimal128VerifyClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewScalarDecimalTypeClient creates a new instance of [ScalarDecimalTypeClient]. +func (client *ScalarClient) NewScalarDecimalTypeClient() *ScalarDecimalTypeClient { + return &ScalarDecimalTypeClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewScalarDecimalVerifyClient creates a new instance of [ScalarDecimalVerifyClient]. +func (client *ScalarClient) NewScalarDecimalVerifyClient() *ScalarDecimalVerifyClient { + return &ScalarDecimalVerifyClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewScalarStringClient creates a new instance of [ScalarStringClient]. +func (client *ScalarClient) NewScalarStringClient() *ScalarStringClient { + return &ScalarStringClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewScalarUnknownClient creates a new instance of [ScalarUnknownClient]. +func (client *ScalarClient) NewScalarUnknownClient() *ScalarUnknownClient { + return &ScalarUnknownClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/http-specs/type/scalargroup/zz_scalarboolean_client.go b/test/http-specs/type/scalargroup/zz_scalarboolean_client.go new file mode 100644 index 000000000000..e3fb8c28a542 --- /dev/null +++ b/test/http-specs/type/scalargroup/zz_scalarboolean_client.go @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package scalargroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ScalarBooleanClient contains the methods for the ScalarBoolean group. +// Don't use this type directly, use [ScalarClient.NewScalarBooleanClient] instead. +type ScalarBooleanClient struct { + internal *azcore.Client + endpoint string +} + +// Get - get boolean value +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ScalarBooleanClientGetOptions contains the optional parameters for the ScalarBooleanClient.Get method. +func (client *ScalarBooleanClient) Get(ctx context.Context, options *ScalarBooleanClientGetOptions) (ScalarBooleanClientGetResponse, error) { + var err error + const operationName = "ScalarBooleanClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ScalarBooleanClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScalarBooleanClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScalarBooleanClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ScalarBooleanClient) getCreateRequest(ctx context.Context, _ *ScalarBooleanClientGetOptions) (*policy.Request, error) { + urlPath := "/type/scalar/boolean" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ScalarBooleanClient) getHandleResponse(resp *http.Response) (ScalarBooleanClientGetResponse, error) { + result := ScalarBooleanClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Value); err != nil { + return ScalarBooleanClientGetResponse{}, err + } + return result, nil +} + +// Put - put boolean value +// If the operation fails it returns an *azcore.ResponseError type. +// - body - _ +// - options - ScalarBooleanClientPutOptions contains the optional parameters for the ScalarBooleanClient.Put method. +func (client *ScalarBooleanClient) Put(ctx context.Context, body bool, options *ScalarBooleanClientPutOptions) (ScalarBooleanClientPutResponse, error) { + var err error + const operationName = "ScalarBooleanClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ScalarBooleanClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScalarBooleanClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ScalarBooleanClientPutResponse{}, err + } + return ScalarBooleanClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ScalarBooleanClient) putCreateRequest(ctx context.Context, body bool, _ *ScalarBooleanClientPutOptions) (*policy.Request, error) { + urlPath := "/type/scalar/boolean" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/scalargroup/zz_scalardecimal128type_client.go b/test/http-specs/type/scalargroup/zz_scalardecimal128type_client.go new file mode 100644 index 000000000000..26d445fb6828 --- /dev/null +++ b/test/http-specs/type/scalargroup/zz_scalardecimal128type_client.go @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package scalargroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strconv" + "strings" +) + +// ScalarDecimal128TypeClient - Decimal128 type +// Don't use this type directly, use [ScalarClient.NewScalarDecimal128TypeClient] instead. +type ScalarDecimal128TypeClient struct { + internal *azcore.Client + endpoint string +} + +// RequestBody - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ScalarDecimal128TypeClientRequestBodyOptions contains the optional parameters for the ScalarDecimal128TypeClient.RequestBody +// method. +func (client *ScalarDecimal128TypeClient) RequestBody(ctx context.Context, body float64, options *ScalarDecimal128TypeClientRequestBodyOptions) (ScalarDecimal128TypeClientRequestBodyResponse, error) { + var err error + const operationName = "ScalarDecimal128TypeClient.RequestBody" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.requestBodyCreateRequest(ctx, body, options) + if err != nil { + return ScalarDecimal128TypeClientRequestBodyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScalarDecimal128TypeClientRequestBodyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ScalarDecimal128TypeClientRequestBodyResponse{}, err + } + return ScalarDecimal128TypeClientRequestBodyResponse{}, nil +} + +// requestBodyCreateRequest creates the RequestBody request. +func (client *ScalarDecimal128TypeClient) requestBodyCreateRequest(ctx context.Context, body float64, _ *ScalarDecimal128TypeClientRequestBodyOptions) (*policy.Request, error) { + urlPath := "/type/scalar/decimal128/resquest_body" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// RequestParameter - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ScalarDecimal128TypeClientRequestParameterOptions contains the optional parameters for the ScalarDecimal128TypeClient.RequestParameter +// method. +func (client *ScalarDecimal128TypeClient) RequestParameter(ctx context.Context, value float64, options *ScalarDecimal128TypeClientRequestParameterOptions) (ScalarDecimal128TypeClientRequestParameterResponse, error) { + var err error + const operationName = "ScalarDecimal128TypeClient.RequestParameter" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.requestParameterCreateRequest(ctx, value, options) + if err != nil { + return ScalarDecimal128TypeClientRequestParameterResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScalarDecimal128TypeClientRequestParameterResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ScalarDecimal128TypeClientRequestParameterResponse{}, err + } + return ScalarDecimal128TypeClientRequestParameterResponse{}, nil +} + +// requestParameterCreateRequest creates the RequestParameter request. +func (client *ScalarDecimal128TypeClient) requestParameterCreateRequest(ctx context.Context, value float64, _ *ScalarDecimal128TypeClientRequestParameterOptions) (*policy.Request, error) { + urlPath := "/type/scalar/decimal128/request_parameter" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("value", strconv.FormatFloat(value, 'f', -1, 64)) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// ResponseBody - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ScalarDecimal128TypeClientResponseBodyOptions contains the optional parameters for the ScalarDecimal128TypeClient.ResponseBody +// method. +func (client *ScalarDecimal128TypeClient) ResponseBody(ctx context.Context, options *ScalarDecimal128TypeClientResponseBodyOptions) (ScalarDecimal128TypeClientResponseBodyResponse, error) { + var err error + const operationName = "ScalarDecimal128TypeClient.ResponseBody" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.responseBodyCreateRequest(ctx, options) + if err != nil { + return ScalarDecimal128TypeClientResponseBodyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScalarDecimal128TypeClientResponseBodyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScalarDecimal128TypeClientResponseBodyResponse{}, err + } + resp, err := client.responseBodyHandleResponse(httpResp) + return resp, err +} + +// responseBodyCreateRequest creates the ResponseBody request. +func (client *ScalarDecimal128TypeClient) responseBodyCreateRequest(ctx context.Context, _ *ScalarDecimal128TypeClientResponseBodyOptions) (*policy.Request, error) { + urlPath := "/type/scalar/decimal128/response_body" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// responseBodyHandleResponse handles the ResponseBody response. +func (client *ScalarDecimal128TypeClient) responseBodyHandleResponse(resp *http.Response) (ScalarDecimal128TypeClientResponseBodyResponse, error) { + result := ScalarDecimal128TypeClientResponseBodyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Value); err != nil { + return ScalarDecimal128TypeClientResponseBodyResponse{}, err + } + return result, nil +} diff --git a/test/http-specs/type/scalargroup/zz_scalardecimal128verify_client.go b/test/http-specs/type/scalargroup/zz_scalardecimal128verify_client.go new file mode 100644 index 000000000000..c6c136edd9eb --- /dev/null +++ b/test/http-specs/type/scalargroup/zz_scalardecimal128verify_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package scalargroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ScalarDecimal128VerifyClient - Decimal128 type verification +// Don't use this type directly, use [ScalarClient.NewScalarDecimal128VerifyClient] instead. +type ScalarDecimal128VerifyClient struct { + internal *azcore.Client + endpoint string +} + +// PrepareVerify - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ScalarDecimal128VerifyClientPrepareVerifyOptions contains the optional parameters for the ScalarDecimal128VerifyClient.PrepareVerify +// method. +func (client *ScalarDecimal128VerifyClient) PrepareVerify(ctx context.Context, options *ScalarDecimal128VerifyClientPrepareVerifyOptions) (ScalarDecimal128VerifyClientPrepareVerifyResponse, error) { + var err error + const operationName = "ScalarDecimal128VerifyClient.PrepareVerify" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.prepareVerifyCreateRequest(ctx, options) + if err != nil { + return ScalarDecimal128VerifyClientPrepareVerifyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScalarDecimal128VerifyClientPrepareVerifyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScalarDecimal128VerifyClientPrepareVerifyResponse{}, err + } + resp, err := client.prepareVerifyHandleResponse(httpResp) + return resp, err +} + +// prepareVerifyCreateRequest creates the PrepareVerify request. +func (client *ScalarDecimal128VerifyClient) prepareVerifyCreateRequest(ctx context.Context, _ *ScalarDecimal128VerifyClientPrepareVerifyOptions) (*policy.Request, error) { + urlPath := "/type/scalar/decimal128/prepare_verify" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// prepareVerifyHandleResponse handles the PrepareVerify response. +func (client *ScalarDecimal128VerifyClient) prepareVerifyHandleResponse(resp *http.Response) (ScalarDecimal128VerifyClientPrepareVerifyResponse, error) { + result := ScalarDecimal128VerifyClientPrepareVerifyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Float64Array); err != nil { + return ScalarDecimal128VerifyClientPrepareVerifyResponse{}, err + } + return result, nil +} + +// Verify - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ScalarDecimal128VerifyClientVerifyOptions contains the optional parameters for the ScalarDecimal128VerifyClient.Verify +// method. +func (client *ScalarDecimal128VerifyClient) Verify(ctx context.Context, body float64, options *ScalarDecimal128VerifyClientVerifyOptions) (ScalarDecimal128VerifyClientVerifyResponse, error) { + var err error + const operationName = "ScalarDecimal128VerifyClient.Verify" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.verifyCreateRequest(ctx, body, options) + if err != nil { + return ScalarDecimal128VerifyClientVerifyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScalarDecimal128VerifyClientVerifyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ScalarDecimal128VerifyClientVerifyResponse{}, err + } + return ScalarDecimal128VerifyClientVerifyResponse{}, nil +} + +// verifyCreateRequest creates the Verify request. +func (client *ScalarDecimal128VerifyClient) verifyCreateRequest(ctx context.Context, body float64, _ *ScalarDecimal128VerifyClientVerifyOptions) (*policy.Request, error) { + urlPath := "/type/scalar/decimal128/verify" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/scalargroup/zz_scalardecimaltype_client.go b/test/http-specs/type/scalargroup/zz_scalardecimaltype_client.go new file mode 100644 index 000000000000..2ca37d0cb64f --- /dev/null +++ b/test/http-specs/type/scalargroup/zz_scalardecimaltype_client.go @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package scalargroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strconv" + "strings" +) + +// ScalarDecimalTypeClient - Decimal type +// Don't use this type directly, use [ScalarClient.NewScalarDecimalTypeClient] instead. +type ScalarDecimalTypeClient struct { + internal *azcore.Client + endpoint string +} + +// RequestBody - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ScalarDecimalTypeClientRequestBodyOptions contains the optional parameters for the ScalarDecimalTypeClient.RequestBody +// method. +func (client *ScalarDecimalTypeClient) RequestBody(ctx context.Context, body float64, options *ScalarDecimalTypeClientRequestBodyOptions) (ScalarDecimalTypeClientRequestBodyResponse, error) { + var err error + const operationName = "ScalarDecimalTypeClient.RequestBody" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.requestBodyCreateRequest(ctx, body, options) + if err != nil { + return ScalarDecimalTypeClientRequestBodyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScalarDecimalTypeClientRequestBodyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ScalarDecimalTypeClientRequestBodyResponse{}, err + } + return ScalarDecimalTypeClientRequestBodyResponse{}, nil +} + +// requestBodyCreateRequest creates the RequestBody request. +func (client *ScalarDecimalTypeClient) requestBodyCreateRequest(ctx context.Context, body float64, _ *ScalarDecimalTypeClientRequestBodyOptions) (*policy.Request, error) { + urlPath := "/type/scalar/decimal/resquest_body" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// RequestParameter - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ScalarDecimalTypeClientRequestParameterOptions contains the optional parameters for the ScalarDecimalTypeClient.RequestParameter +// method. +func (client *ScalarDecimalTypeClient) RequestParameter(ctx context.Context, value float64, options *ScalarDecimalTypeClientRequestParameterOptions) (ScalarDecimalTypeClientRequestParameterResponse, error) { + var err error + const operationName = "ScalarDecimalTypeClient.RequestParameter" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.requestParameterCreateRequest(ctx, value, options) + if err != nil { + return ScalarDecimalTypeClientRequestParameterResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScalarDecimalTypeClientRequestParameterResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ScalarDecimalTypeClientRequestParameterResponse{}, err + } + return ScalarDecimalTypeClientRequestParameterResponse{}, nil +} + +// requestParameterCreateRequest creates the RequestParameter request. +func (client *ScalarDecimalTypeClient) requestParameterCreateRequest(ctx context.Context, value float64, _ *ScalarDecimalTypeClientRequestParameterOptions) (*policy.Request, error) { + urlPath := "/type/scalar/decimal/request_parameter" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("value", strconv.FormatFloat(value, 'f', -1, 64)) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// ResponseBody - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ScalarDecimalTypeClientResponseBodyOptions contains the optional parameters for the ScalarDecimalTypeClient.ResponseBody +// method. +func (client *ScalarDecimalTypeClient) ResponseBody(ctx context.Context, options *ScalarDecimalTypeClientResponseBodyOptions) (ScalarDecimalTypeClientResponseBodyResponse, error) { + var err error + const operationName = "ScalarDecimalTypeClient.ResponseBody" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.responseBodyCreateRequest(ctx, options) + if err != nil { + return ScalarDecimalTypeClientResponseBodyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScalarDecimalTypeClientResponseBodyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScalarDecimalTypeClientResponseBodyResponse{}, err + } + resp, err := client.responseBodyHandleResponse(httpResp) + return resp, err +} + +// responseBodyCreateRequest creates the ResponseBody request. +func (client *ScalarDecimalTypeClient) responseBodyCreateRequest(ctx context.Context, _ *ScalarDecimalTypeClientResponseBodyOptions) (*policy.Request, error) { + urlPath := "/type/scalar/decimal/response_body" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// responseBodyHandleResponse handles the ResponseBody response. +func (client *ScalarDecimalTypeClient) responseBodyHandleResponse(resp *http.Response) (ScalarDecimalTypeClientResponseBodyResponse, error) { + result := ScalarDecimalTypeClientResponseBodyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Value); err != nil { + return ScalarDecimalTypeClientResponseBodyResponse{}, err + } + return result, nil +} diff --git a/test/http-specs/type/scalargroup/zz_scalardecimalverify_client.go b/test/http-specs/type/scalargroup/zz_scalardecimalverify_client.go new file mode 100644 index 000000000000..d44d9efdb867 --- /dev/null +++ b/test/http-specs/type/scalargroup/zz_scalardecimalverify_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package scalargroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ScalarDecimalVerifyClient - Decimal type verification +// Don't use this type directly, use [ScalarClient.NewScalarDecimalVerifyClient] instead. +type ScalarDecimalVerifyClient struct { + internal *azcore.Client + endpoint string +} + +// PrepareVerify - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ScalarDecimalVerifyClientPrepareVerifyOptions contains the optional parameters for the ScalarDecimalVerifyClient.PrepareVerify +// method. +func (client *ScalarDecimalVerifyClient) PrepareVerify(ctx context.Context, options *ScalarDecimalVerifyClientPrepareVerifyOptions) (ScalarDecimalVerifyClientPrepareVerifyResponse, error) { + var err error + const operationName = "ScalarDecimalVerifyClient.PrepareVerify" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.prepareVerifyCreateRequest(ctx, options) + if err != nil { + return ScalarDecimalVerifyClientPrepareVerifyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScalarDecimalVerifyClientPrepareVerifyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScalarDecimalVerifyClientPrepareVerifyResponse{}, err + } + resp, err := client.prepareVerifyHandleResponse(httpResp) + return resp, err +} + +// prepareVerifyCreateRequest creates the PrepareVerify request. +func (client *ScalarDecimalVerifyClient) prepareVerifyCreateRequest(ctx context.Context, _ *ScalarDecimalVerifyClientPrepareVerifyOptions) (*policy.Request, error) { + urlPath := "/type/scalar/decimal/prepare_verify" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// prepareVerifyHandleResponse handles the PrepareVerify response. +func (client *ScalarDecimalVerifyClient) prepareVerifyHandleResponse(resp *http.Response) (ScalarDecimalVerifyClientPrepareVerifyResponse, error) { + result := ScalarDecimalVerifyClientPrepareVerifyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Float64Array); err != nil { + return ScalarDecimalVerifyClientPrepareVerifyResponse{}, err + } + return result, nil +} + +// Verify - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ScalarDecimalVerifyClientVerifyOptions contains the optional parameters for the ScalarDecimalVerifyClient.Verify +// method. +func (client *ScalarDecimalVerifyClient) Verify(ctx context.Context, body float64, options *ScalarDecimalVerifyClientVerifyOptions) (ScalarDecimalVerifyClientVerifyResponse, error) { + var err error + const operationName = "ScalarDecimalVerifyClient.Verify" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.verifyCreateRequest(ctx, body, options) + if err != nil { + return ScalarDecimalVerifyClientVerifyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScalarDecimalVerifyClientVerifyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ScalarDecimalVerifyClientVerifyResponse{}, err + } + return ScalarDecimalVerifyClientVerifyResponse{}, nil +} + +// verifyCreateRequest creates the Verify request. +func (client *ScalarDecimalVerifyClient) verifyCreateRequest(ctx context.Context, body float64, _ *ScalarDecimalVerifyClientVerifyOptions) (*policy.Request, error) { + urlPath := "/type/scalar/decimal/verify" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/scalargroup/zz_scalarstring_client.go b/test/http-specs/type/scalargroup/zz_scalarstring_client.go new file mode 100644 index 000000000000..7071fb2ba210 --- /dev/null +++ b/test/http-specs/type/scalargroup/zz_scalarstring_client.go @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package scalargroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ScalarStringClient contains the methods for the ScalarString group. +// Don't use this type directly, use [ScalarClient.NewScalarStringClient] instead. +type ScalarStringClient struct { + internal *azcore.Client + endpoint string +} + +// Get - get string value +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ScalarStringClientGetOptions contains the optional parameters for the ScalarStringClient.Get method. +func (client *ScalarStringClient) Get(ctx context.Context, options *ScalarStringClientGetOptions) (ScalarStringClientGetResponse, error) { + var err error + const operationName = "ScalarStringClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ScalarStringClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScalarStringClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScalarStringClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ScalarStringClient) getCreateRequest(ctx context.Context, _ *ScalarStringClientGetOptions) (*policy.Request, error) { + urlPath := "/type/scalar/string" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ScalarStringClient) getHandleResponse(resp *http.Response) (ScalarStringClientGetResponse, error) { + result := ScalarStringClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Value); err != nil { + return ScalarStringClientGetResponse{}, err + } + return result, nil +} + +// Put - put string value +// If the operation fails it returns an *azcore.ResponseError type. +// - body - _ +// - options - ScalarStringClientPutOptions contains the optional parameters for the ScalarStringClient.Put method. +func (client *ScalarStringClient) Put(ctx context.Context, body string, options *ScalarStringClientPutOptions) (ScalarStringClientPutResponse, error) { + var err error + const operationName = "ScalarStringClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ScalarStringClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScalarStringClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ScalarStringClientPutResponse{}, err + } + return ScalarStringClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ScalarStringClient) putCreateRequest(ctx context.Context, body string, _ *ScalarStringClientPutOptions) (*policy.Request, error) { + urlPath := "/type/scalar/string" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/scalargroup/zz_scalarunknown_client.go b/test/http-specs/type/scalargroup/zz_scalarunknown_client.go new file mode 100644 index 000000000000..429781ae1286 --- /dev/null +++ b/test/http-specs/type/scalargroup/zz_scalarunknown_client.go @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package scalargroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// ScalarUnknownClient contains the methods for the ScalarUnknown group. +// Don't use this type directly, use [ScalarClient.NewScalarUnknownClient] instead. +type ScalarUnknownClient struct { + internal *azcore.Client + endpoint string +} + +// Get - get unknown value +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ScalarUnknownClientGetOptions contains the optional parameters for the ScalarUnknownClient.Get method. +func (client *ScalarUnknownClient) Get(ctx context.Context, options *ScalarUnknownClientGetOptions) (ScalarUnknownClientGetResponse, error) { + var err error + const operationName = "ScalarUnknownClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return ScalarUnknownClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScalarUnknownClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScalarUnknownClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ScalarUnknownClient) getCreateRequest(ctx context.Context, _ *ScalarUnknownClientGetOptions) (*policy.Request, error) { + urlPath := "/type/scalar/unknown" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ScalarUnknownClient) getHandleResponse(resp *http.Response) (ScalarUnknownClientGetResponse, error) { + result := ScalarUnknownClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Interface); err != nil { + return ScalarUnknownClientGetResponse{}, err + } + return result, nil +} + +// Put - put unknown value +// If the operation fails it returns an *azcore.ResponseError type. +// - body - _ +// - options - ScalarUnknownClientPutOptions contains the optional parameters for the ScalarUnknownClient.Put method. +func (client *ScalarUnknownClient) Put(ctx context.Context, body any, options *ScalarUnknownClientPutOptions) (ScalarUnknownClientPutResponse, error) { + var err error + const operationName = "ScalarUnknownClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ScalarUnknownClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScalarUnknownClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ScalarUnknownClientPutResponse{}, err + } + return ScalarUnknownClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *ScalarUnknownClient) putCreateRequest(ctx context.Context, body any, _ *ScalarUnknownClientPutOptions) (*policy.Request, error) { + urlPath := "/type/scalar/unknown" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/http-specs/type/scalargroup/zz_version.go b/test/http-specs/type/scalargroup/zz_version.go new file mode 100644 index 000000000000..74ea49df1d02 --- /dev/null +++ b/test/http-specs/type/scalargroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package scalargroup + +const ( + moduleName = "scalargroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/versioning/madeoptionalgroup/LICENSE.txt b/test/http-specs/versioning/madeoptionalgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/versioning/madeoptionalgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/versioning/madeoptionalgroup/fake/zz_internal.go b/test/http-specs/versioning/madeoptionalgroup/fake/zz_internal.go new file mode 100644 index 000000000000..53ec711308cc --- /dev/null +++ b/test/http-specs/versioning/madeoptionalgroup/fake/zz_internal.go @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "reflect" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getOptional[T any](v T) *T { + if reflect.ValueOf(v).IsZero() { + return nil + } + return &v +} diff --git a/test/http-specs/versioning/madeoptionalgroup/fake/zz_madeoptional_server.go b/test/http-specs/versioning/madeoptionalgroup/fake/zz_madeoptional_server.go new file mode 100644 index 000000000000..b8a5232c2b60 --- /dev/null +++ b/test/http-specs/versioning/madeoptionalgroup/fake/zz_madeoptional_server.go @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "madeoptionalgroup" + "net/http" + "slices" +) + +// MadeOptionalServer is a fake server for instances of the madeoptionalgroup.MadeOptionalClient type. +type MadeOptionalServer struct { + // Test is the fake for method MadeOptionalClient.Test + // HTTP status codes to indicate success: http.StatusOK + Test func(ctx context.Context, body madeoptionalgroup.TestModel, options *madeoptionalgroup.MadeOptionalClientTestOptions) (resp azfake.Responder[madeoptionalgroup.MadeOptionalClientTestResponse], errResp azfake.ErrorResponder) +} + +// NewMadeOptionalServerTransport creates a new instance of MadeOptionalServerTransport with the provided implementation. +// The returned MadeOptionalServerTransport instance is connected to an instance of madeoptionalgroup.MadeOptionalClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewMadeOptionalServerTransport(srv *MadeOptionalServer) *MadeOptionalServerTransport { + return &MadeOptionalServerTransport{srv: srv} +} + +// MadeOptionalServerTransport connects instances of madeoptionalgroup.MadeOptionalClient to instances of MadeOptionalServer. +// Don't use this type directly, use NewMadeOptionalServerTransport instead. +type MadeOptionalServerTransport struct { + srv *MadeOptionalServer +} + +// Do implements the policy.Transporter interface for MadeOptionalServerTransport. +func (m *MadeOptionalServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToMethodFake(req, method) +} + +func (m *MadeOptionalServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if madeOptionalServerTransportInterceptor != nil { + res.resp, res.err, intercepted = madeOptionalServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "MadeOptionalClient.Test": + res.resp, res.err = m.dispatchTest(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *MadeOptionalServerTransport) dispatchTest(req *http.Request) (*http.Response, error) { + if m.srv.Test == nil { + return nil, &nonRetriableError{errors.New("fake for method Test not implemented")} + } + qp := req.URL.Query() + body, err := server.UnmarshalRequestAsJSON[madeoptionalgroup.TestModel](req) + if err != nil { + return nil, err + } + paramParam := getOptional(qp.Get("param")) + var options *madeoptionalgroup.MadeOptionalClientTestOptions + if paramParam != nil { + options = &madeoptionalgroup.MadeOptionalClientTestOptions{ + Param: paramParam, + } + } + respr, errRespr := m.srv.Test(req.Context(), body, options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).TestModel, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to MadeOptionalServerTransport +var madeOptionalServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/versioning/madeoptionalgroup/go.mod b/test/http-specs/versioning/madeoptionalgroup/go.mod new file mode 100644 index 000000000000..c72b3bcdc64e --- /dev/null +++ b/test/http-specs/versioning/madeoptionalgroup/go.mod @@ -0,0 +1,17 @@ +module madeoptionalgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/versioning/madeoptionalgroup/go.sum b/test/http-specs/versioning/madeoptionalgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/versioning/madeoptionalgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/versioning/madeoptionalgroup/madeoptional_client_test.go b/test/http-specs/versioning/madeoptionalgroup/madeoptional_client_test.go new file mode 100644 index 000000000000..9cce489655bc --- /dev/null +++ b/test/http-specs/versioning/madeoptionalgroup/madeoptional_client_test.go @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package madeoptionalgroup_test + +import ( + "context" + "madeoptionalgroup" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func Test_Test(t *testing.T) { + client, err := madeoptionalgroup.NewMadeOptionalClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.Test(context.Background(), madeoptionalgroup.TestModel{ + Prop: to.Ptr("foo"), + }, nil) + require.NoError(t, err) + require.Equal(t, madeoptionalgroup.MadeOptionalClientTestResponse{ + TestModel: madeoptionalgroup.TestModel{ + Prop: to.Ptr("foo"), + }, + }, resp) +} diff --git a/test/http-specs/versioning/madeoptionalgroup/testdata/_metadata.json b/test/http-specs/versioning/madeoptionalgroup/testdata/_metadata.json new file mode 100644 index 000000000000..663a4e2ef519 --- /dev/null +++ b/test/http-specs/versioning/madeoptionalgroup/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Versioning.MadeOptional": "v2" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/versioning/madeoptionalgroup/zz_madeoptional_client.go b/test/http-specs/versioning/madeoptionalgroup/zz_madeoptional_client.go new file mode 100644 index 000000000000..d8acc28febdd --- /dev/null +++ b/test/http-specs/versioning/madeoptionalgroup/zz_madeoptional_client.go @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package madeoptionalgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// MadeOptionalClient - Test for the `@madeOptional` decorator. +// Don't use this type directly, use NewMadeOptionalClientWithNoCredential() instead. +type MadeOptionalClient struct { + internal *azcore.Client + endpoint string +} + +// MadeOptionalClientOptions contains the optional values for creating a [MadeOptionalClient]. +type MadeOptionalClientOptions struct { + azcore.ClientOptions +} + +// NewMadeOptionalClientWithNoCredential creates a new instance of MadeOptionalClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewMadeOptionalClientWithNoCredential(endpoint string, options *MadeOptionalClientOptions) (*MadeOptionalClient, error) { + if options == nil { + options = &MadeOptionalClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{ + APIVersion: runtime.APIVersionOptions{ + Location: runtime.APIVersionLocationPath, + }, + }, &options.ClientOptions) + if err != nil { + return nil, err + } + version := "v2" + if options.APIVersion != "" { + version = options.APIVersion + } + host := "versioning/made-optional/api-version:{version}" + host = strings.ReplaceAll(host, "{version}", version) + endpoint = runtime.JoinPaths(endpoint, host) + client := &MadeOptionalClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// Test - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - MadeOptionalClientTestOptions contains the optional parameters for the MadeOptionalClient.Test method. +func (client *MadeOptionalClient) Test(ctx context.Context, body TestModel, options *MadeOptionalClientTestOptions) (MadeOptionalClientTestResponse, error) { + var err error + const operationName = "MadeOptionalClient.Test" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.testCreateRequest(ctx, body, options) + if err != nil { + return MadeOptionalClientTestResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MadeOptionalClientTestResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return MadeOptionalClientTestResponse{}, err + } + resp, err := client.testHandleResponse(httpResp) + return resp, err +} + +// testCreateRequest creates the Test request. +func (client *MadeOptionalClient) testCreateRequest(ctx context.Context, body TestModel, options *MadeOptionalClientTestOptions) (*policy.Request, error) { + urlPath := "/test" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Param != nil { + reqQP.Set("param", *options.Param) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// testHandleResponse handles the Test response. +func (client *MadeOptionalClient) testHandleResponse(resp *http.Response) (MadeOptionalClientTestResponse, error) { + result := MadeOptionalClientTestResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.TestModel); err != nil { + return MadeOptionalClientTestResponse{}, err + } + return result, nil +} diff --git a/test/http-specs/versioning/madeoptionalgroup/zz_models.go b/test/http-specs/versioning/madeoptionalgroup/zz_models.go new file mode 100644 index 000000000000..eaabbecb5a3e --- /dev/null +++ b/test/http-specs/versioning/madeoptionalgroup/zz_models.go @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package madeoptionalgroup + +type TestModel struct { + // REQUIRED + Prop *string + ChangedProp *string +} diff --git a/test/http-specs/versioning/madeoptionalgroup/zz_models_serde.go b/test/http-specs/versioning/madeoptionalgroup/zz_models_serde.go new file mode 100644 index 000000000000..5fb52de62183 --- /dev/null +++ b/test/http-specs/versioning/madeoptionalgroup/zz_models_serde.go @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package madeoptionalgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type TestModel. +func (t TestModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "changedProp", t.ChangedProp) + populate(objectMap, "prop", t.Prop) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TestModel. +func (t *TestModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "changedProp": + err = unpopulate(val, "ChangedProp", &t.ChangedProp) + delete(rawMsg, key) + case "prop": + err = unpopulate(val, "Prop", &t.Prop) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/http-specs/versioning/madeoptionalgroup/zz_options.go b/test/http-specs/versioning/madeoptionalgroup/zz_options.go new file mode 100644 index 000000000000..b40dc6da79ad --- /dev/null +++ b/test/http-specs/versioning/madeoptionalgroup/zz_options.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package madeoptionalgroup + +// MadeOptionalClientTestOptions contains the optional parameters for the MadeOptionalClient.Test method. +type MadeOptionalClientTestOptions struct { + Param *string +} diff --git a/test/http-specs/versioning/madeoptionalgroup/zz_responses.go b/test/http-specs/versioning/madeoptionalgroup/zz_responses.go new file mode 100644 index 000000000000..e0ca5d6dd4d4 --- /dev/null +++ b/test/http-specs/versioning/madeoptionalgroup/zz_responses.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package madeoptionalgroup + +// MadeOptionalClientTestResponse contains the response from method MadeOptionalClient.Test. +type MadeOptionalClientTestResponse struct { + TestModel +} diff --git a/test/http-specs/versioning/madeoptionalgroup/zz_version.go b/test/http-specs/versioning/madeoptionalgroup/zz_version.go new file mode 100644 index 000000000000..99015c05abd8 --- /dev/null +++ b/test/http-specs/versioning/madeoptionalgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package madeoptionalgroup + +const ( + moduleName = "madeoptionalgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/versioning/rettypechangedfromgroup/LICENSE.txt b/test/http-specs/versioning/rettypechangedfromgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/versioning/rettypechangedfromgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/versioning/rettypechangedfromgroup/fake/zz_internal.go b/test/http-specs/versioning/rettypechangedfromgroup/fake/zz_internal.go new file mode 100644 index 000000000000..705f81eacafe --- /dev/null +++ b/test/http-specs/versioning/rettypechangedfromgroup/fake/zz_internal.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import "net/http" + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} diff --git a/test/http-specs/versioning/rettypechangedfromgroup/fake/zz_returntypechangedfrom_server.go b/test/http-specs/versioning/rettypechangedfromgroup/fake/zz_returntypechangedfrom_server.go new file mode 100644 index 000000000000..d45d965c517f --- /dev/null +++ b/test/http-specs/versioning/rettypechangedfromgroup/fake/zz_returntypechangedfrom_server.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "rettypechangedfromgroup" + "slices" +) + +// ReturnTypeChangedFromServer is a fake server for instances of the rettypechangedfromgroup.ReturnTypeChangedFromClient type. +type ReturnTypeChangedFromServer struct { + // Test is the fake for method ReturnTypeChangedFromClient.Test + // HTTP status codes to indicate success: http.StatusOK + Test func(ctx context.Context, body string, options *rettypechangedfromgroup.ReturnTypeChangedFromClientTestOptions) (resp azfake.Responder[rettypechangedfromgroup.ReturnTypeChangedFromClientTestResponse], errResp azfake.ErrorResponder) +} + +// NewReturnTypeChangedFromServerTransport creates a new instance of ReturnTypeChangedFromServerTransport with the provided implementation. +// The returned ReturnTypeChangedFromServerTransport instance is connected to an instance of rettypechangedfromgroup.ReturnTypeChangedFromClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewReturnTypeChangedFromServerTransport(srv *ReturnTypeChangedFromServer) *ReturnTypeChangedFromServerTransport { + return &ReturnTypeChangedFromServerTransport{srv: srv} +} + +// ReturnTypeChangedFromServerTransport connects instances of rettypechangedfromgroup.ReturnTypeChangedFromClient to instances of ReturnTypeChangedFromServer. +// Don't use this type directly, use NewReturnTypeChangedFromServerTransport instead. +type ReturnTypeChangedFromServerTransport struct { + srv *ReturnTypeChangedFromServer +} + +// Do implements the policy.Transporter interface for ReturnTypeChangedFromServerTransport. +func (r *ReturnTypeChangedFromServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return r.dispatchToMethodFake(req, method) +} + +func (r *ReturnTypeChangedFromServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if returnTypeChangedFromServerTransportInterceptor != nil { + res.resp, res.err, intercepted = returnTypeChangedFromServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ReturnTypeChangedFromClient.Test": + res.resp, res.err = r.dispatchTest(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (r *ReturnTypeChangedFromServerTransport) dispatchTest(req *http.Request) (*http.Response, error) { + if r.srv.Test == nil { + return nil, &nonRetriableError{errors.New("fake for method Test not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[string](req) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.Test(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Value, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ReturnTypeChangedFromServerTransport +var returnTypeChangedFromServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/versioning/rettypechangedfromgroup/go.mod b/test/http-specs/versioning/rettypechangedfromgroup/go.mod new file mode 100644 index 000000000000..8f9ae3df6de8 --- /dev/null +++ b/test/http-specs/versioning/rettypechangedfromgroup/go.mod @@ -0,0 +1,17 @@ +module rettypechangedfromgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/versioning/rettypechangedfromgroup/go.sum b/test/http-specs/versioning/rettypechangedfromgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/versioning/rettypechangedfromgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/versioning/rettypechangedfromgroup/returntypechangedfrom_client_test.go b/test/http-specs/versioning/rettypechangedfromgroup/returntypechangedfrom_client_test.go new file mode 100644 index 000000000000..14e5acfd06be --- /dev/null +++ b/test/http-specs/versioning/rettypechangedfromgroup/returntypechangedfrom_client_test.go @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package rettypechangedfromgroup_test + +import ( + "context" + "rettypechangedfromgroup" + "testing" + + "github.com/stretchr/testify/require" +) + +func Test_Test(t *testing.T) { + client, err := rettypechangedfromgroup.NewReturnTypeChangedFromClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.Test(context.Background(), "test", nil) + require.NoError(t, err) + require.NotNil(t, resp.Value) + require.EqualValues(t, "test", *resp.Value) +} diff --git a/test/http-specs/versioning/rettypechangedfromgroup/testdata/_metadata.json b/test/http-specs/versioning/rettypechangedfromgroup/testdata/_metadata.json new file mode 100644 index 000000000000..53196f912e06 --- /dev/null +++ b/test/http-specs/versioning/rettypechangedfromgroup/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Versioning.ReturnTypeChangedFrom": "v2" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/versioning/rettypechangedfromgroup/zz_options.go b/test/http-specs/versioning/rettypechangedfromgroup/zz_options.go new file mode 100644 index 000000000000..ded6b9d7c9f6 --- /dev/null +++ b/test/http-specs/versioning/rettypechangedfromgroup/zz_options.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package rettypechangedfromgroup + +// ReturnTypeChangedFromClientTestOptions contains the optional parameters for the ReturnTypeChangedFromClient.Test method. +type ReturnTypeChangedFromClientTestOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/versioning/rettypechangedfromgroup/zz_responses.go b/test/http-specs/versioning/rettypechangedfromgroup/zz_responses.go new file mode 100644 index 000000000000..5033529514e2 --- /dev/null +++ b/test/http-specs/versioning/rettypechangedfromgroup/zz_responses.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package rettypechangedfromgroup + +// ReturnTypeChangedFromClientTestResponse contains the response from method ReturnTypeChangedFromClient.Test. +type ReturnTypeChangedFromClientTestResponse struct { + Value *string +} diff --git a/test/http-specs/versioning/rettypechangedfromgroup/zz_returntypechangedfrom_client.go b/test/http-specs/versioning/rettypechangedfromgroup/zz_returntypechangedfrom_client.go new file mode 100644 index 000000000000..b87f8b99ffc8 --- /dev/null +++ b/test/http-specs/versioning/rettypechangedfromgroup/zz_returntypechangedfrom_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package rettypechangedfromgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// ReturnTypeChangedFromClient - Test for the `@returnTypeChangedFrom` decorator. +// Don't use this type directly, use NewReturnTypeChangedFromClientWithNoCredential() instead. +type ReturnTypeChangedFromClient struct { + internal *azcore.Client + endpoint string +} + +// ReturnTypeChangedFromClientOptions contains the optional values for creating a [ReturnTypeChangedFromClient]. +type ReturnTypeChangedFromClientOptions struct { + azcore.ClientOptions +} + +// NewReturnTypeChangedFromClientWithNoCredential creates a new instance of ReturnTypeChangedFromClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewReturnTypeChangedFromClientWithNoCredential(endpoint string, options *ReturnTypeChangedFromClientOptions) (*ReturnTypeChangedFromClient, error) { + if options == nil { + options = &ReturnTypeChangedFromClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{ + APIVersion: runtime.APIVersionOptions{ + Location: runtime.APIVersionLocationPath, + }, + }, &options.ClientOptions) + if err != nil { + return nil, err + } + version := "v2" + if options.APIVersion != "" { + version = options.APIVersion + } + host := "versioning/return-type-changed-from/api-version:{version}" + host = strings.ReplaceAll(host, "{version}", version) + endpoint = runtime.JoinPaths(endpoint, host) + client := &ReturnTypeChangedFromClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// Test - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ReturnTypeChangedFromClientTestOptions contains the optional parameters for the ReturnTypeChangedFromClient.Test +// method. +func (client *ReturnTypeChangedFromClient) Test(ctx context.Context, body string, options *ReturnTypeChangedFromClientTestOptions) (ReturnTypeChangedFromClientTestResponse, error) { + var err error + const operationName = "ReturnTypeChangedFromClient.Test" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.testCreateRequest(ctx, body, options) + if err != nil { + return ReturnTypeChangedFromClientTestResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ReturnTypeChangedFromClientTestResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ReturnTypeChangedFromClientTestResponse{}, err + } + resp, err := client.testHandleResponse(httpResp) + return resp, err +} + +// testCreateRequest creates the Test request. +func (client *ReturnTypeChangedFromClient) testCreateRequest(ctx context.Context, body string, _ *ReturnTypeChangedFromClientTestOptions) (*policy.Request, error) { + urlPath := "/test" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// testHandleResponse handles the Test response. +func (client *ReturnTypeChangedFromClient) testHandleResponse(resp *http.Response) (ReturnTypeChangedFromClientTestResponse, error) { + result := ReturnTypeChangedFromClientTestResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Value); err != nil { + return ReturnTypeChangedFromClientTestResponse{}, err + } + return result, nil +} diff --git a/test/http-specs/versioning/rettypechangedfromgroup/zz_version.go b/test/http-specs/versioning/rettypechangedfromgroup/zz_version.go new file mode 100644 index 000000000000..ff862c062ec0 --- /dev/null +++ b/test/http-specs/versioning/rettypechangedfromgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package rettypechangedfromgroup + +const ( + moduleName = "rettypechangedfromgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/http-specs/versioning/typechangedfromgroup/LICENSE.txt b/test/http-specs/versioning/typechangedfromgroup/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/http-specs/versioning/typechangedfromgroup/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/http-specs/versioning/typechangedfromgroup/fake/zz_internal.go b/test/http-specs/versioning/typechangedfromgroup/fake/zz_internal.go new file mode 100644 index 000000000000..705f81eacafe --- /dev/null +++ b/test/http-specs/versioning/typechangedfromgroup/fake/zz_internal.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import "net/http" + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} diff --git a/test/http-specs/versioning/typechangedfromgroup/fake/zz_typechangedfrom_server.go b/test/http-specs/versioning/typechangedfromgroup/fake/zz_typechangedfrom_server.go new file mode 100644 index 000000000000..286bfed6f509 --- /dev/null +++ b/test/http-specs/versioning/typechangedfromgroup/fake/zz_typechangedfrom_server.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" + "typechangedfromgroup" +) + +// TypeChangedFromServer is a fake server for instances of the typechangedfromgroup.TypeChangedFromClient type. +type TypeChangedFromServer struct { + // Test is the fake for method TypeChangedFromClient.Test + // HTTP status codes to indicate success: http.StatusOK + Test func(ctx context.Context, body typechangedfromgroup.TestModel, param string, options *typechangedfromgroup.TypeChangedFromClientTestOptions) (resp azfake.Responder[typechangedfromgroup.TypeChangedFromClientTestResponse], errResp azfake.ErrorResponder) +} + +// NewTypeChangedFromServerTransport creates a new instance of TypeChangedFromServerTransport with the provided implementation. +// The returned TypeChangedFromServerTransport instance is connected to an instance of typechangedfromgroup.TypeChangedFromClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewTypeChangedFromServerTransport(srv *TypeChangedFromServer) *TypeChangedFromServerTransport { + return &TypeChangedFromServerTransport{srv: srv} +} + +// TypeChangedFromServerTransport connects instances of typechangedfromgroup.TypeChangedFromClient to instances of TypeChangedFromServer. +// Don't use this type directly, use NewTypeChangedFromServerTransport instead. +type TypeChangedFromServerTransport struct { + srv *TypeChangedFromServer +} + +// Do implements the policy.Transporter interface for TypeChangedFromServerTransport. +func (t *TypeChangedFromServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return t.dispatchToMethodFake(req, method) +} + +func (t *TypeChangedFromServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if typeChangedFromServerTransportInterceptor != nil { + res.resp, res.err, intercepted = typeChangedFromServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "TypeChangedFromClient.Test": + res.resp, res.err = t.dispatchTest(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (t *TypeChangedFromServerTransport) dispatchTest(req *http.Request) (*http.Response, error) { + if t.srv.Test == nil { + return nil, &nonRetriableError{errors.New("fake for method Test not implemented")} + } + qp := req.URL.Query() + body, err := server.UnmarshalRequestAsJSON[typechangedfromgroup.TestModel](req) + if err != nil { + return nil, err + } + respr, errRespr := t.srv.Test(req.Context(), body, qp.Get("param"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).TestModel, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to TypeChangedFromServerTransport +var typeChangedFromServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/http-specs/versioning/typechangedfromgroup/go.mod b/test/http-specs/versioning/typechangedfromgroup/go.mod new file mode 100644 index 000000000000..b12955db6608 --- /dev/null +++ b/test/http-specs/versioning/typechangedfromgroup/go.mod @@ -0,0 +1,17 @@ +module typechangedfromgroup + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/http-specs/versioning/typechangedfromgroup/go.sum b/test/http-specs/versioning/typechangedfromgroup/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/http-specs/versioning/typechangedfromgroup/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/http-specs/versioning/typechangedfromgroup/testdata/_metadata.json b/test/http-specs/versioning/typechangedfromgroup/testdata/_metadata.json new file mode 100644 index 000000000000..f03075ac4c04 --- /dev/null +++ b/test/http-specs/versioning/typechangedfromgroup/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Versioning.TypeChangedFrom": "v2" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/http-specs/versioning/typechangedfromgroup/typechangedfrom_client_test.go b/test/http-specs/versioning/typechangedfromgroup/typechangedfrom_client_test.go new file mode 100644 index 000000000000..b52b7d95c78d --- /dev/null +++ b/test/http-specs/versioning/typechangedfromgroup/typechangedfrom_client_test.go @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package typechangedfromgroup_test + +import ( + "context" + "testing" + "typechangedfromgroup" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func Test_Test(t *testing.T) { + client, err := typechangedfromgroup.NewTypeChangedFromClientWithNoCredential("http://localhost:3000", nil) + require.NoError(t, err) + resp, err := client.Test(context.Background(), typechangedfromgroup.TestModel{ + Prop: to.Ptr("foo"), + ChangedProp: to.Ptr("bar"), + }, "baz", nil) + require.NoError(t, err) + require.Equal(t, typechangedfromgroup.TypeChangedFromClientTestResponse{ + TestModel: typechangedfromgroup.TestModel{ + Prop: to.Ptr("foo"), + ChangedProp: to.Ptr("bar"), + }, + }, resp) +} diff --git a/test/http-specs/versioning/typechangedfromgroup/zz_models.go b/test/http-specs/versioning/typechangedfromgroup/zz_models.go new file mode 100644 index 000000000000..b95aafd19b5b --- /dev/null +++ b/test/http-specs/versioning/typechangedfromgroup/zz_models.go @@ -0,0 +1,13 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package typechangedfromgroup + +type TestModel struct { + // REQUIRED + ChangedProp *string + + // REQUIRED + Prop *string +} diff --git a/test/http-specs/versioning/typechangedfromgroup/zz_models_serde.go b/test/http-specs/versioning/typechangedfromgroup/zz_models_serde.go new file mode 100644 index 000000000000..0a881d4354b6 --- /dev/null +++ b/test/http-specs/versioning/typechangedfromgroup/zz_models_serde.go @@ -0,0 +1,63 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package typechangedfromgroup + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type TestModel. +func (t TestModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "changedProp", t.ChangedProp) + populate(objectMap, "prop", t.Prop) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TestModel. +func (t *TestModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "changedProp": + err = unpopulate(val, "ChangedProp", &t.ChangedProp) + delete(rawMsg, key) + case "prop": + err = unpopulate(val, "Prop", &t.Prop) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/http-specs/versioning/typechangedfromgroup/zz_options.go b/test/http-specs/versioning/typechangedfromgroup/zz_options.go new file mode 100644 index 000000000000..a091e1327699 --- /dev/null +++ b/test/http-specs/versioning/typechangedfromgroup/zz_options.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package typechangedfromgroup + +// TypeChangedFromClientTestOptions contains the optional parameters for the TypeChangedFromClient.Test method. +type TypeChangedFromClientTestOptions struct { + // placeholder for future optional parameters +} diff --git a/test/http-specs/versioning/typechangedfromgroup/zz_responses.go b/test/http-specs/versioning/typechangedfromgroup/zz_responses.go new file mode 100644 index 000000000000..d139df33dae6 --- /dev/null +++ b/test/http-specs/versioning/typechangedfromgroup/zz_responses.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package typechangedfromgroup + +// TypeChangedFromClientTestResponse contains the response from method TypeChangedFromClient.Test. +type TypeChangedFromClientTestResponse struct { + TestModel +} diff --git a/test/http-specs/versioning/typechangedfromgroup/zz_typechangedfrom_client.go b/test/http-specs/versioning/typechangedfromgroup/zz_typechangedfrom_client.go new file mode 100644 index 000000000000..b4f7412c489b --- /dev/null +++ b/test/http-specs/versioning/typechangedfromgroup/zz_typechangedfrom_client.go @@ -0,0 +1,107 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package typechangedfromgroup + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// TypeChangedFromClient - Test for the `@typeChangedFrom` decorator. +// Don't use this type directly, use NewTypeChangedFromClientWithNoCredential() instead. +type TypeChangedFromClient struct { + internal *azcore.Client + endpoint string +} + +// TypeChangedFromClientOptions contains the optional values for creating a [TypeChangedFromClient]. +type TypeChangedFromClientOptions struct { + azcore.ClientOptions +} + +// NewTypeChangedFromClientWithNoCredential creates a new instance of TypeChangedFromClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewTypeChangedFromClientWithNoCredential(endpoint string, options *TypeChangedFromClientOptions) (*TypeChangedFromClient, error) { + if options == nil { + options = &TypeChangedFromClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{ + APIVersion: runtime.APIVersionOptions{ + Location: runtime.APIVersionLocationPath, + }, + }, &options.ClientOptions) + if err != nil { + return nil, err + } + version := "v2" + if options.APIVersion != "" { + version = options.APIVersion + } + host := "versioning/type-changed-from/api-version:{version}" + host = strings.ReplaceAll(host, "{version}", version) + endpoint = runtime.JoinPaths(endpoint, host) + client := &TypeChangedFromClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// Test - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - TypeChangedFromClientTestOptions contains the optional parameters for the TypeChangedFromClient.Test method. +func (client *TypeChangedFromClient) Test(ctx context.Context, body TestModel, param string, options *TypeChangedFromClientTestOptions) (TypeChangedFromClientTestResponse, error) { + var err error + const operationName = "TypeChangedFromClient.Test" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.testCreateRequest(ctx, body, param, options) + if err != nil { + return TypeChangedFromClientTestResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TypeChangedFromClientTestResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return TypeChangedFromClientTestResponse{}, err + } + resp, err := client.testHandleResponse(httpResp) + return resp, err +} + +// testCreateRequest creates the Test request. +func (client *TypeChangedFromClient) testCreateRequest(ctx context.Context, body TestModel, param string, _ *TypeChangedFromClientTestOptions) (*policy.Request, error) { + urlPath := "/test" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("param", param) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// testHandleResponse handles the Test response. +func (client *TypeChangedFromClient) testHandleResponse(resp *http.Response) (TypeChangedFromClientTestResponse, error) { + result := TypeChangedFromClientTestResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.TestModel); err != nil { + return TypeChangedFromClientTestResponse{}, err + } + return result, nil +} diff --git a/test/http-specs/versioning/typechangedfromgroup/zz_version.go b/test/http-specs/versioning/typechangedfromgroup/zz_version.go new file mode 100644 index 000000000000..d8c45800a774 --- /dev/null +++ b/test/http-specs/versioning/typechangedfromgroup/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package typechangedfromgroup + +const ( + moduleName = "typechangedfromgroup" + moduleVersion = "v0.1.0" +) diff --git a/test/local/armapicenter/LICENSE.txt b/test/local/armapicenter/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/local/armapicenter/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/local/armapicenter/fake/zz_apidefinitions_server.go b/test/local/armapicenter/fake/zz_apidefinitions_server.go new file mode 100644 index 000000000000..25450ee19ab5 --- /dev/null +++ b/test/local/armapicenter/fake/zz_apidefinitions_server.go @@ -0,0 +1,520 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armapicenter" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// APIDefinitionsServer is a fake server for instances of the armapicenter.APIDefinitionsClient type. +type APIDefinitionsServer struct { + // CreateOrUpdate is the fake for method APIDefinitionsClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, definitionName string, payload armapicenter.APIDefinition, options *armapicenter.APIDefinitionsClientCreateOrUpdateOptions) (resp azfake.Responder[armapicenter.APIDefinitionsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method APIDefinitionsClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, definitionName string, options *armapicenter.APIDefinitionsClientDeleteOptions) (resp azfake.Responder[armapicenter.APIDefinitionsClientDeleteResponse], errResp azfake.ErrorResponder) + + // BeginExportSpecification is the fake for method APIDefinitionsClient.BeginExportSpecification + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginExportSpecification func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, definitionName string, options *armapicenter.APIDefinitionsClientBeginExportSpecificationOptions) (resp azfake.PollerResponder[armapicenter.APIDefinitionsClientExportSpecificationResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method APIDefinitionsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, definitionName string, options *armapicenter.APIDefinitionsClientGetOptions) (resp azfake.Responder[armapicenter.APIDefinitionsClientGetResponse], errResp azfake.ErrorResponder) + + // Head is the fake for method APIDefinitionsClient.Head + // HTTP status codes to indicate success: http.StatusOK + Head func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, definitionName string, options *armapicenter.APIDefinitionsClientHeadOptions) (resp azfake.Responder[armapicenter.APIDefinitionsClientHeadResponse], errResp azfake.ErrorResponder) + + // BeginImportSpecification is the fake for method APIDefinitionsClient.BeginImportSpecification + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginImportSpecification func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, definitionName string, body armapicenter.APISpecImportRequest, options *armapicenter.APIDefinitionsClientBeginImportSpecificationOptions) (resp azfake.PollerResponder[armapicenter.APIDefinitionsClientImportSpecificationResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method APIDefinitionsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, options *armapicenter.APIDefinitionsClientListOptions) (resp azfake.PagerResponder[armapicenter.APIDefinitionsClientListResponse]) +} + +// NewAPIDefinitionsServerTransport creates a new instance of APIDefinitionsServerTransport with the provided implementation. +// The returned APIDefinitionsServerTransport instance is connected to an instance of armapicenter.APIDefinitionsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAPIDefinitionsServerTransport(srv *APIDefinitionsServer) *APIDefinitionsServerTransport { + return &APIDefinitionsServerTransport{ + srv: srv, + beginExportSpecification: newTracker[azfake.PollerResponder[armapicenter.APIDefinitionsClientExportSpecificationResponse]](), + beginImportSpecification: newTracker[azfake.PollerResponder[armapicenter.APIDefinitionsClientImportSpecificationResponse]](), + newListPager: newTracker[azfake.PagerResponder[armapicenter.APIDefinitionsClientListResponse]](), + } +} + +// APIDefinitionsServerTransport connects instances of armapicenter.APIDefinitionsClient to instances of APIDefinitionsServer. +// Don't use this type directly, use NewAPIDefinitionsServerTransport instead. +type APIDefinitionsServerTransport struct { + srv *APIDefinitionsServer + beginExportSpecification *tracker[azfake.PollerResponder[armapicenter.APIDefinitionsClientExportSpecificationResponse]] + beginImportSpecification *tracker[azfake.PollerResponder[armapicenter.APIDefinitionsClientImportSpecificationResponse]] + newListPager *tracker[azfake.PagerResponder[armapicenter.APIDefinitionsClientListResponse]] +} + +// Do implements the policy.Transporter interface for APIDefinitionsServerTransport. +func (a *APIDefinitionsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *APIDefinitionsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if apiDefinitionsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = apiDefinitionsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "APIDefinitionsClient.CreateOrUpdate": + res.resp, res.err = a.dispatchCreateOrUpdate(req) + case "APIDefinitionsClient.Delete": + res.resp, res.err = a.dispatchDelete(req) + case "APIDefinitionsClient.BeginExportSpecification": + res.resp, res.err = a.dispatchBeginExportSpecification(req) + case "APIDefinitionsClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "APIDefinitionsClient.Head": + res.resp, res.err = a.dispatchHead(req) + case "APIDefinitionsClient.BeginImportSpecification": + res.resp, res.err = a.dispatchBeginImportSpecification(req) + case "APIDefinitionsClient.NewListPager": + res.resp, res.err = a.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *APIDefinitionsServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if a.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/apis/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/versions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/definitions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 8 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armapicenter.APIDefinition](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + apiNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("apiName")]) + if err != nil { + return nil, err + } + versionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("versionName")]) + if err != nil { + return nil, err + } + definitionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("definitionName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, apiNameParam, versionNameParam, definitionNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).APIDefinition, req) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).EtagHeader; val != nil { + resp.Header.Set("ETag", *val) + } + return resp, nil +} + +func (a *APIDefinitionsServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if a.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/apis/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/versions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/definitions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 8 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + apiNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("apiName")]) + if err != nil { + return nil, err + } + versionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("versionName")]) + if err != nil { + return nil, err + } + definitionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("definitionName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Delete(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, apiNameParam, versionNameParam, definitionNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *APIDefinitionsServerTransport) dispatchBeginExportSpecification(req *http.Request) (*http.Response, error) { + if a.srv.BeginExportSpecification == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginExportSpecification not implemented")} + } + beginExportSpecification := a.beginExportSpecification.get(req) + if beginExportSpecification == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/apis/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/versions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/definitions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/exportSpecification` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 8 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + apiNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("apiName")]) + if err != nil { + return nil, err + } + versionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("versionName")]) + if err != nil { + return nil, err + } + definitionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("definitionName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginExportSpecification(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, apiNameParam, versionNameParam, definitionNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginExportSpecification = &respr + a.beginExportSpecification.add(req, beginExportSpecification) + } + + resp, err := server.PollerResponderNext(beginExportSpecification, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + a.beginExportSpecification.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginExportSpecification) { + a.beginExportSpecification.remove(req) + } + + return resp, nil +} + +func (a *APIDefinitionsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/apis/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/versions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/definitions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 8 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + apiNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("apiName")]) + if err != nil { + return nil, err + } + versionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("versionName")]) + if err != nil { + return nil, err + } + definitionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("definitionName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Get(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, apiNameParam, versionNameParam, definitionNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).APIDefinition, req) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).EtagHeader; val != nil { + resp.Header.Set("ETag", *val) + } + return resp, nil +} + +func (a *APIDefinitionsServerTransport) dispatchHead(req *http.Request) (*http.Response, error) { + if a.srv.Head == nil { + return nil, &nonRetriableError{errors.New("fake for method Head not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/apis/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/versions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/definitions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 8 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + apiNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("apiName")]) + if err != nil { + return nil, err + } + versionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("versionName")]) + if err != nil { + return nil, err + } + definitionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("definitionName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Head(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, apiNameParam, versionNameParam, definitionNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *APIDefinitionsServerTransport) dispatchBeginImportSpecification(req *http.Request) (*http.Response, error) { + if a.srv.BeginImportSpecification == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginImportSpecification not implemented")} + } + beginImportSpecification := a.beginImportSpecification.get(req) + if beginImportSpecification == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/apis/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/versions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/definitions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/importSpecification` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 8 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armapicenter.APISpecImportRequest](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + apiNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("apiName")]) + if err != nil { + return nil, err + } + versionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("versionName")]) + if err != nil { + return nil, err + } + definitionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("definitionName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginImportSpecification(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, apiNameParam, versionNameParam, definitionNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginImportSpecification = &respr + a.beginImportSpecification.add(req, beginImportSpecification) + } + + resp, err := server.PollerResponderNext(beginImportSpecification, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + a.beginImportSpecification.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginImportSpecification) { + a.beginImportSpecification.remove(req) + } + + return resp, nil +} + +func (a *APIDefinitionsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if a.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := a.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/apis/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/versions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/definitions` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 7 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + apiNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("apiName")]) + if err != nil { + return nil, err + } + versionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("versionName")]) + if err != nil { + return nil, err + } + filterParam := getOptional(qp.Get("$filter")) + var options *armapicenter.APIDefinitionsClientListOptions + if filterParam != nil { + options = &armapicenter.APIDefinitionsClientListOptions{ + Filter: filterParam, + } + } + resp := a.srv.NewListPager(resourceGroupNameParam, serviceNameParam, workspaceNameParam, apiNameParam, versionNameParam, options) + newListPager = &resp + a.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armapicenter.APIDefinitionsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + a.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to APIDefinitionsServerTransport +var apiDefinitionsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armapicenter/fake/zz_apis_server.go b/test/local/armapicenter/fake/zz_apis_server.go new file mode 100644 index 000000000000..6a3556a01876 --- /dev/null +++ b/test/local/armapicenter/fake/zz_apis_server.go @@ -0,0 +1,340 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armapicenter" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// ApisServer is a fake server for instances of the armapicenter.ApisClient type. +type ApisServer struct { + // CreateOrUpdate is the fake for method ApisClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, payload armapicenter.API, options *armapicenter.ApisClientCreateOrUpdateOptions) (resp azfake.Responder[armapicenter.ApisClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method ApisClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, options *armapicenter.ApisClientDeleteOptions) (resp azfake.Responder[armapicenter.ApisClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method ApisClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, options *armapicenter.ApisClientGetOptions) (resp azfake.Responder[armapicenter.ApisClientGetResponse], errResp azfake.ErrorResponder) + + // Head is the fake for method ApisClient.Head + // HTTP status codes to indicate success: http.StatusOK + Head func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, options *armapicenter.ApisClientHeadOptions) (resp azfake.Responder[armapicenter.ApisClientHeadResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method ApisClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, serviceName string, workspaceName string, options *armapicenter.ApisClientListOptions) (resp azfake.PagerResponder[armapicenter.ApisClientListResponse]) +} + +// NewApisServerTransport creates a new instance of ApisServerTransport with the provided implementation. +// The returned ApisServerTransport instance is connected to an instance of armapicenter.ApisClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewApisServerTransport(srv *ApisServer) *ApisServerTransport { + return &ApisServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armapicenter.ApisClientListResponse]](), + } +} + +// ApisServerTransport connects instances of armapicenter.ApisClient to instances of ApisServer. +// Don't use this type directly, use NewApisServerTransport instead. +type ApisServerTransport struct { + srv *ApisServer + newListPager *tracker[azfake.PagerResponder[armapicenter.ApisClientListResponse]] +} + +// Do implements the policy.Transporter interface for ApisServerTransport. +func (a *ApisServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *ApisServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if apisServerTransportInterceptor != nil { + res.resp, res.err, intercepted = apisServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ApisClient.CreateOrUpdate": + res.resp, res.err = a.dispatchCreateOrUpdate(req) + case "ApisClient.Delete": + res.resp, res.err = a.dispatchDelete(req) + case "ApisClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "ApisClient.Head": + res.resp, res.err = a.dispatchHead(req) + case "ApisClient.NewListPager": + res.resp, res.err = a.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *ApisServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if a.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/apis/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armapicenter.API](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + apiNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("apiName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, apiNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).API, req) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).EtagHeader; val != nil { + resp.Header.Set("ETag", *val) + } + return resp, nil +} + +func (a *ApisServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if a.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/apis/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + apiNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("apiName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Delete(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, apiNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *ApisServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/apis/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + apiNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("apiName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Get(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, apiNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).API, req) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).EtagHeader; val != nil { + resp.Header.Set("ETag", *val) + } + return resp, nil +} + +func (a *ApisServerTransport) dispatchHead(req *http.Request) (*http.Response, error) { + if a.srv.Head == nil { + return nil, &nonRetriableError{errors.New("fake for method Head not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/apis/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + apiNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("apiName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Head(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, apiNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *ApisServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if a.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := a.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/apis` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + filterParam := getOptional(qp.Get("$filter")) + var options *armapicenter.ApisClientListOptions + if filterParam != nil { + options = &armapicenter.ApisClientListOptions{ + Filter: filterParam, + } + } + resp := a.srv.NewListPager(resourceGroupNameParam, serviceNameParam, workspaceNameParam, options) + newListPager = &resp + a.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armapicenter.ApisClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + a.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ApisServerTransport +var apisServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armapicenter/fake/zz_apisources_server.go b/test/local/armapicenter/fake/zz_apisources_server.go new file mode 100644 index 000000000000..be26e0a0fef3 --- /dev/null +++ b/test/local/armapicenter/fake/zz_apisources_server.go @@ -0,0 +1,340 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armapicenter" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// APISourcesServer is a fake server for instances of the armapicenter.APISourcesClient type. +type APISourcesServer struct { + // CreateOrUpdate is the fake for method APISourcesClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiSourceName string, resource armapicenter.APISource, options *armapicenter.APISourcesClientCreateOrUpdateOptions) (resp azfake.Responder[armapicenter.APISourcesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method APISourcesClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiSourceName string, options *armapicenter.APISourcesClientDeleteOptions) (resp azfake.Responder[armapicenter.APISourcesClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method APISourcesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiSourceName string, options *armapicenter.APISourcesClientGetOptions) (resp azfake.Responder[armapicenter.APISourcesClientGetResponse], errResp azfake.ErrorResponder) + + // Head is the fake for method APISourcesClient.Head + // HTTP status codes to indicate success: http.StatusOK + Head func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiSourceName string, options *armapicenter.APISourcesClientHeadOptions) (resp azfake.Responder[armapicenter.APISourcesClientHeadResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method APISourcesClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, serviceName string, workspaceName string, options *armapicenter.APISourcesClientListOptions) (resp azfake.PagerResponder[armapicenter.APISourcesClientListResponse]) +} + +// NewAPISourcesServerTransport creates a new instance of APISourcesServerTransport with the provided implementation. +// The returned APISourcesServerTransport instance is connected to an instance of armapicenter.APISourcesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAPISourcesServerTransport(srv *APISourcesServer) *APISourcesServerTransport { + return &APISourcesServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armapicenter.APISourcesClientListResponse]](), + } +} + +// APISourcesServerTransport connects instances of armapicenter.APISourcesClient to instances of APISourcesServer. +// Don't use this type directly, use NewAPISourcesServerTransport instead. +type APISourcesServerTransport struct { + srv *APISourcesServer + newListPager *tracker[azfake.PagerResponder[armapicenter.APISourcesClientListResponse]] +} + +// Do implements the policy.Transporter interface for APISourcesServerTransport. +func (a *APISourcesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *APISourcesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if apiSourcesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = apiSourcesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "APISourcesClient.CreateOrUpdate": + res.resp, res.err = a.dispatchCreateOrUpdate(req) + case "APISourcesClient.Delete": + res.resp, res.err = a.dispatchDelete(req) + case "APISourcesClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "APISourcesClient.Head": + res.resp, res.err = a.dispatchHead(req) + case "APISourcesClient.NewListPager": + res.resp, res.err = a.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *APISourcesServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if a.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/apiSources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armapicenter.APISource](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + apiSourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("apiSourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, apiSourceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).APISource, req) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).EtagHeader; val != nil { + resp.Header.Set("ETag", *val) + } + return resp, nil +} + +func (a *APISourcesServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if a.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/apiSources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + apiSourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("apiSourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Delete(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, apiSourceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *APISourcesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/apiSources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + apiSourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("apiSourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Get(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, apiSourceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).APISource, req) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).EtagHeader; val != nil { + resp.Header.Set("ETag", *val) + } + return resp, nil +} + +func (a *APISourcesServerTransport) dispatchHead(req *http.Request) (*http.Response, error) { + if a.srv.Head == nil { + return nil, &nonRetriableError{errors.New("fake for method Head not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/apiSources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + apiSourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("apiSourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Head(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, apiSourceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *APISourcesServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if a.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := a.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/apiSources` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + filterParam := getOptional(qp.Get("$filter")) + var options *armapicenter.APISourcesClientListOptions + if filterParam != nil { + options = &armapicenter.APISourcesClientListOptions{ + Filter: filterParam, + } + } + resp := a.srv.NewListPager(resourceGroupNameParam, serviceNameParam, workspaceNameParam, options) + newListPager = &resp + a.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armapicenter.APISourcesClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + a.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to APISourcesServerTransport +var apiSourcesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armapicenter/fake/zz_apiversions_server.go b/test/local/armapicenter/fake/zz_apiversions_server.go new file mode 100644 index 000000000000..2177f6f56ead --- /dev/null +++ b/test/local/armapicenter/fake/zz_apiversions_server.go @@ -0,0 +1,360 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armapicenter" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// APIVersionsServer is a fake server for instances of the armapicenter.APIVersionsClient type. +type APIVersionsServer struct { + // CreateOrUpdate is the fake for method APIVersionsClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, payload armapicenter.APIVersion, options *armapicenter.APIVersionsClientCreateOrUpdateOptions) (resp azfake.Responder[armapicenter.APIVersionsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method APIVersionsClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, options *armapicenter.APIVersionsClientDeleteOptions) (resp azfake.Responder[armapicenter.APIVersionsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method APIVersionsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, options *armapicenter.APIVersionsClientGetOptions) (resp azfake.Responder[armapicenter.APIVersionsClientGetResponse], errResp azfake.ErrorResponder) + + // Head is the fake for method APIVersionsClient.Head + // HTTP status codes to indicate success: http.StatusOK + Head func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, options *armapicenter.APIVersionsClientHeadOptions) (resp azfake.Responder[armapicenter.APIVersionsClientHeadResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method APIVersionsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, serviceName string, workspaceName string, apiName string, options *armapicenter.APIVersionsClientListOptions) (resp azfake.PagerResponder[armapicenter.APIVersionsClientListResponse]) +} + +// NewAPIVersionsServerTransport creates a new instance of APIVersionsServerTransport with the provided implementation. +// The returned APIVersionsServerTransport instance is connected to an instance of armapicenter.APIVersionsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAPIVersionsServerTransport(srv *APIVersionsServer) *APIVersionsServerTransport { + return &APIVersionsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armapicenter.APIVersionsClientListResponse]](), + } +} + +// APIVersionsServerTransport connects instances of armapicenter.APIVersionsClient to instances of APIVersionsServer. +// Don't use this type directly, use NewAPIVersionsServerTransport instead. +type APIVersionsServerTransport struct { + srv *APIVersionsServer + newListPager *tracker[azfake.PagerResponder[armapicenter.APIVersionsClientListResponse]] +} + +// Do implements the policy.Transporter interface for APIVersionsServerTransport. +func (a *APIVersionsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *APIVersionsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if apiVersionsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = apiVersionsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "APIVersionsClient.CreateOrUpdate": + res.resp, res.err = a.dispatchCreateOrUpdate(req) + case "APIVersionsClient.Delete": + res.resp, res.err = a.dispatchDelete(req) + case "APIVersionsClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "APIVersionsClient.Head": + res.resp, res.err = a.dispatchHead(req) + case "APIVersionsClient.NewListPager": + res.resp, res.err = a.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *APIVersionsServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if a.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/apis/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/versions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 7 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armapicenter.APIVersion](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + apiNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("apiName")]) + if err != nil { + return nil, err + } + versionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("versionName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, apiNameParam, versionNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).APIVersion, req) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).EtagHeader; val != nil { + resp.Header.Set("ETag", *val) + } + return resp, nil +} + +func (a *APIVersionsServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if a.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/apis/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/versions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 7 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + apiNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("apiName")]) + if err != nil { + return nil, err + } + versionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("versionName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Delete(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, apiNameParam, versionNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *APIVersionsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/apis/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/versions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 7 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + apiNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("apiName")]) + if err != nil { + return nil, err + } + versionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("versionName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Get(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, apiNameParam, versionNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).APIVersion, req) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).EtagHeader; val != nil { + resp.Header.Set("ETag", *val) + } + return resp, nil +} + +func (a *APIVersionsServerTransport) dispatchHead(req *http.Request) (*http.Response, error) { + if a.srv.Head == nil { + return nil, &nonRetriableError{errors.New("fake for method Head not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/apis/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/versions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 7 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + apiNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("apiName")]) + if err != nil { + return nil, err + } + versionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("versionName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Head(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, apiNameParam, versionNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *APIVersionsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if a.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := a.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/apis/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/versions` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + apiNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("apiName")]) + if err != nil { + return nil, err + } + filterParam := getOptional(qp.Get("$filter")) + var options *armapicenter.APIVersionsClientListOptions + if filterParam != nil { + options = &armapicenter.APIVersionsClientListOptions{ + Filter: filterParam, + } + } + resp := a.srv.NewListPager(resourceGroupNameParam, serviceNameParam, workspaceNameParam, apiNameParam, options) + newListPager = &resp + a.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armapicenter.APIVersionsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + a.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to APIVersionsServerTransport +var apiVersionsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armapicenter/fake/zz_deletedservices_server.go b/test/local/armapicenter/fake/zz_deletedservices_server.go new file mode 100644 index 000000000000..bf8bde8689ca --- /dev/null +++ b/test/local/armapicenter/fake/zz_deletedservices_server.go @@ -0,0 +1,256 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armapicenter" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// DeletedServicesServer is a fake server for instances of the armapicenter.DeletedServicesClient type. +type DeletedServicesServer struct { + // Delete is the fake for method DeletedServicesClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceGroupName string, deletedServiceName string, options *armapicenter.DeletedServicesClientDeleteOptions) (resp azfake.Responder[armapicenter.DeletedServicesClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method DeletedServicesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, deletedServiceName string, options *armapicenter.DeletedServicesClientGetOptions) (resp azfake.Responder[armapicenter.DeletedServicesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method DeletedServicesClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, options *armapicenter.DeletedServicesClientListOptions) (resp azfake.PagerResponder[armapicenter.DeletedServicesClientListResponse]) + + // NewListBySubscriptionPager is the fake for method DeletedServicesClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armapicenter.DeletedServicesClientListBySubscriptionOptions) (resp azfake.PagerResponder[armapicenter.DeletedServicesClientListBySubscriptionResponse]) +} + +// NewDeletedServicesServerTransport creates a new instance of DeletedServicesServerTransport with the provided implementation. +// The returned DeletedServicesServerTransport instance is connected to an instance of armapicenter.DeletedServicesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDeletedServicesServerTransport(srv *DeletedServicesServer) *DeletedServicesServerTransport { + return &DeletedServicesServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armapicenter.DeletedServicesClientListResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armapicenter.DeletedServicesClientListBySubscriptionResponse]](), + } +} + +// DeletedServicesServerTransport connects instances of armapicenter.DeletedServicesClient to instances of DeletedServicesServer. +// Don't use this type directly, use NewDeletedServicesServerTransport instead. +type DeletedServicesServerTransport struct { + srv *DeletedServicesServer + newListPager *tracker[azfake.PagerResponder[armapicenter.DeletedServicesClientListResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armapicenter.DeletedServicesClientListBySubscriptionResponse]] +} + +// Do implements the policy.Transporter interface for DeletedServicesServerTransport. +func (d *DeletedServicesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DeletedServicesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if deletedServicesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = deletedServicesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DeletedServicesClient.Delete": + res.resp, res.err = d.dispatchDelete(req) + case "DeletedServicesClient.Get": + res.resp, res.err = d.dispatchGet(req) + case "DeletedServicesClient.NewListPager": + res.resp, res.err = d.dispatchNewListPager(req) + case "DeletedServicesClient.NewListBySubscriptionPager": + res.resp, res.err = d.dispatchNewListBySubscriptionPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DeletedServicesServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if d.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/deletedServices/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + deletedServiceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("deletedServiceName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Delete(req.Context(), resourceGroupNameParam, deletedServiceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DeletedServicesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/deletedServices/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + deletedServiceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("deletedServiceName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Get(req.Context(), resourceGroupNameParam, deletedServiceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DeletedService, req) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).EtagHeader; val != nil { + resp.Header.Set("ETag", *val) + } + return resp, nil +} + +func (d *DeletedServicesServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if d.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := d.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/deletedServices` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + filterParam := getOptional(qp.Get("$filter")) + var options *armapicenter.DeletedServicesClientListOptions + if filterParam != nil { + options = &armapicenter.DeletedServicesClientListOptions{ + Filter: filterParam, + } + } + resp := d.srv.NewListPager(resourceGroupNameParam, options) + newListPager = &resp + d.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armapicenter.DeletedServicesClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + d.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + d.newListPager.remove(req) + } + return resp, nil +} + +func (d *DeletedServicesServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if d.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := d.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/deletedServices` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := d.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + d.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armapicenter.DeletedServicesClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + d.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + d.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DeletedServicesServerTransport +var deletedServicesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armapicenter/fake/zz_deployments_server.go b/test/local/armapicenter/fake/zz_deployments_server.go new file mode 100644 index 000000000000..b44b538599d7 --- /dev/null +++ b/test/local/armapicenter/fake/zz_deployments_server.go @@ -0,0 +1,360 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armapicenter" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// DeploymentsServer is a fake server for instances of the armapicenter.DeploymentsClient type. +type DeploymentsServer struct { + // CreateOrUpdate is the fake for method DeploymentsClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, deploymentName string, payload armapicenter.Deployment, options *armapicenter.DeploymentsClientCreateOrUpdateOptions) (resp azfake.Responder[armapicenter.DeploymentsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method DeploymentsClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, deploymentName string, options *armapicenter.DeploymentsClientDeleteOptions) (resp azfake.Responder[armapicenter.DeploymentsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method DeploymentsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, deploymentName string, options *armapicenter.DeploymentsClientGetOptions) (resp azfake.Responder[armapicenter.DeploymentsClientGetResponse], errResp azfake.ErrorResponder) + + // Head is the fake for method DeploymentsClient.Head + // HTTP status codes to indicate success: http.StatusOK + Head func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, deploymentName string, options *armapicenter.DeploymentsClientHeadOptions) (resp azfake.Responder[armapicenter.DeploymentsClientHeadResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method DeploymentsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, serviceName string, workspaceName string, apiName string, options *armapicenter.DeploymentsClientListOptions) (resp azfake.PagerResponder[armapicenter.DeploymentsClientListResponse]) +} + +// NewDeploymentsServerTransport creates a new instance of DeploymentsServerTransport with the provided implementation. +// The returned DeploymentsServerTransport instance is connected to an instance of armapicenter.DeploymentsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDeploymentsServerTransport(srv *DeploymentsServer) *DeploymentsServerTransport { + return &DeploymentsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armapicenter.DeploymentsClientListResponse]](), + } +} + +// DeploymentsServerTransport connects instances of armapicenter.DeploymentsClient to instances of DeploymentsServer. +// Don't use this type directly, use NewDeploymentsServerTransport instead. +type DeploymentsServerTransport struct { + srv *DeploymentsServer + newListPager *tracker[azfake.PagerResponder[armapicenter.DeploymentsClientListResponse]] +} + +// Do implements the policy.Transporter interface for DeploymentsServerTransport. +func (d *DeploymentsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DeploymentsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if deploymentsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = deploymentsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DeploymentsClient.CreateOrUpdate": + res.resp, res.err = d.dispatchCreateOrUpdate(req) + case "DeploymentsClient.Delete": + res.resp, res.err = d.dispatchDelete(req) + case "DeploymentsClient.Get": + res.resp, res.err = d.dispatchGet(req) + case "DeploymentsClient.Head": + res.resp, res.err = d.dispatchHead(req) + case "DeploymentsClient.NewListPager": + res.resp, res.err = d.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DeploymentsServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if d.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/apis/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/deployments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 7 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armapicenter.Deployment](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + apiNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("apiName")]) + if err != nil { + return nil, err + } + deploymentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("deploymentName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, apiNameParam, deploymentNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Deployment, req) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).EtagHeader; val != nil { + resp.Header.Set("ETag", *val) + } + return resp, nil +} + +func (d *DeploymentsServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if d.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/apis/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/deployments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 7 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + apiNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("apiName")]) + if err != nil { + return nil, err + } + deploymentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("deploymentName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Delete(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, apiNameParam, deploymentNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DeploymentsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/apis/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/deployments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 7 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + apiNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("apiName")]) + if err != nil { + return nil, err + } + deploymentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("deploymentName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Get(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, apiNameParam, deploymentNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Deployment, req) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).EtagHeader; val != nil { + resp.Header.Set("ETag", *val) + } + return resp, nil +} + +func (d *DeploymentsServerTransport) dispatchHead(req *http.Request) (*http.Response, error) { + if d.srv.Head == nil { + return nil, &nonRetriableError{errors.New("fake for method Head not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/apis/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/deployments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 7 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + apiNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("apiName")]) + if err != nil { + return nil, err + } + deploymentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("deploymentName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Head(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, apiNameParam, deploymentNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DeploymentsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if d.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := d.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/apis/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/deployments` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + apiNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("apiName")]) + if err != nil { + return nil, err + } + filterParam := getOptional(qp.Get("$filter")) + var options *armapicenter.DeploymentsClientListOptions + if filterParam != nil { + options = &armapicenter.DeploymentsClientListOptions{ + Filter: filterParam, + } + } + resp := d.srv.NewListPager(resourceGroupNameParam, serviceNameParam, workspaceNameParam, apiNameParam, options) + newListPager = &resp + d.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armapicenter.DeploymentsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + d.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + d.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DeploymentsServerTransport +var deploymentsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armapicenter/fake/zz_environments_server.go b/test/local/armapicenter/fake/zz_environments_server.go new file mode 100644 index 000000000000..8dd0ea261c91 --- /dev/null +++ b/test/local/armapicenter/fake/zz_environments_server.go @@ -0,0 +1,340 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armapicenter" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// EnvironmentsServer is a fake server for instances of the armapicenter.EnvironmentsClient type. +type EnvironmentsServer struct { + // CreateOrUpdate is the fake for method EnvironmentsClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, environmentName string, payload armapicenter.Environment, options *armapicenter.EnvironmentsClientCreateOrUpdateOptions) (resp azfake.Responder[armapicenter.EnvironmentsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method EnvironmentsClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, environmentName string, options *armapicenter.EnvironmentsClientDeleteOptions) (resp azfake.Responder[armapicenter.EnvironmentsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method EnvironmentsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, environmentName string, options *armapicenter.EnvironmentsClientGetOptions) (resp azfake.Responder[armapicenter.EnvironmentsClientGetResponse], errResp azfake.ErrorResponder) + + // Head is the fake for method EnvironmentsClient.Head + // HTTP status codes to indicate success: http.StatusOK + Head func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, environmentName string, options *armapicenter.EnvironmentsClientHeadOptions) (resp azfake.Responder[armapicenter.EnvironmentsClientHeadResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method EnvironmentsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, serviceName string, workspaceName string, options *armapicenter.EnvironmentsClientListOptions) (resp azfake.PagerResponder[armapicenter.EnvironmentsClientListResponse]) +} + +// NewEnvironmentsServerTransport creates a new instance of EnvironmentsServerTransport with the provided implementation. +// The returned EnvironmentsServerTransport instance is connected to an instance of armapicenter.EnvironmentsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewEnvironmentsServerTransport(srv *EnvironmentsServer) *EnvironmentsServerTransport { + return &EnvironmentsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armapicenter.EnvironmentsClientListResponse]](), + } +} + +// EnvironmentsServerTransport connects instances of armapicenter.EnvironmentsClient to instances of EnvironmentsServer. +// Don't use this type directly, use NewEnvironmentsServerTransport instead. +type EnvironmentsServerTransport struct { + srv *EnvironmentsServer + newListPager *tracker[azfake.PagerResponder[armapicenter.EnvironmentsClientListResponse]] +} + +// Do implements the policy.Transporter interface for EnvironmentsServerTransport. +func (e *EnvironmentsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return e.dispatchToMethodFake(req, method) +} + +func (e *EnvironmentsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if environmentsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = environmentsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "EnvironmentsClient.CreateOrUpdate": + res.resp, res.err = e.dispatchCreateOrUpdate(req) + case "EnvironmentsClient.Delete": + res.resp, res.err = e.dispatchDelete(req) + case "EnvironmentsClient.Get": + res.resp, res.err = e.dispatchGet(req) + case "EnvironmentsClient.Head": + res.resp, res.err = e.dispatchHead(req) + case "EnvironmentsClient.NewListPager": + res.resp, res.err = e.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (e *EnvironmentsServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if e.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/environments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armapicenter.Environment](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + environmentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("environmentName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, environmentNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Environment, req) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).EtagHeader; val != nil { + resp.Header.Set("ETag", *val) + } + return resp, nil +} + +func (e *EnvironmentsServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if e.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/environments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + environmentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("environmentName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.Delete(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, environmentNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *EnvironmentsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if e.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/environments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + environmentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("environmentName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.Get(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, environmentNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Environment, req) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).EtagHeader; val != nil { + resp.Header.Set("ETag", *val) + } + return resp, nil +} + +func (e *EnvironmentsServerTransport) dispatchHead(req *http.Request) (*http.Response, error) { + if e.srv.Head == nil { + return nil, &nonRetriableError{errors.New("fake for method Head not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/environments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + environmentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("environmentName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.Head(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, environmentNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *EnvironmentsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if e.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := e.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/environments` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + filterParam := getOptional(qp.Get("$filter")) + var options *armapicenter.EnvironmentsClientListOptions + if filterParam != nil { + options = &armapicenter.EnvironmentsClientListOptions{ + Filter: filterParam, + } + } + resp := e.srv.NewListPager(resourceGroupNameParam, serviceNameParam, workspaceNameParam, options) + newListPager = &resp + e.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armapicenter.EnvironmentsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + e.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + e.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to EnvironmentsServerTransport +var environmentsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armapicenter/fake/zz_internal.go b/test/local/armapicenter/fake/zz_internal.go new file mode 100644 index 000000000000..a5a90f7ae323 --- /dev/null +++ b/test/local/armapicenter/fake/zz_internal.go @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "reflect" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getOptional[T any](v T) *T { + if reflect.ValueOf(v).IsZero() { + return nil + } + return &v +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/local/armapicenter/fake/zz_metadataschemas_server.go b/test/local/armapicenter/fake/zz_metadataschemas_server.go new file mode 100644 index 000000000000..167363bbf88b --- /dev/null +++ b/test/local/armapicenter/fake/zz_metadataschemas_server.go @@ -0,0 +1,320 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armapicenter" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// MetadataSchemasServer is a fake server for instances of the armapicenter.MetadataSchemasClient type. +type MetadataSchemasServer struct { + // CreateOrUpdate is the fake for method MetadataSchemasClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, serviceName string, metadataSchemaName string, payload armapicenter.MetadataSchema, options *armapicenter.MetadataSchemasClientCreateOrUpdateOptions) (resp azfake.Responder[armapicenter.MetadataSchemasClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method MetadataSchemasClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceGroupName string, serviceName string, metadataSchemaName string, options *armapicenter.MetadataSchemasClientDeleteOptions) (resp azfake.Responder[armapicenter.MetadataSchemasClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method MetadataSchemasClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, serviceName string, metadataSchemaName string, options *armapicenter.MetadataSchemasClientGetOptions) (resp azfake.Responder[armapicenter.MetadataSchemasClientGetResponse], errResp azfake.ErrorResponder) + + // Head is the fake for method MetadataSchemasClient.Head + // HTTP status codes to indicate success: http.StatusOK + Head func(ctx context.Context, resourceGroupName string, serviceName string, metadataSchemaName string, options *armapicenter.MetadataSchemasClientHeadOptions) (resp azfake.Responder[armapicenter.MetadataSchemasClientHeadResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method MetadataSchemasClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, serviceName string, options *armapicenter.MetadataSchemasClientListOptions) (resp azfake.PagerResponder[armapicenter.MetadataSchemasClientListResponse]) +} + +// NewMetadataSchemasServerTransport creates a new instance of MetadataSchemasServerTransport with the provided implementation. +// The returned MetadataSchemasServerTransport instance is connected to an instance of armapicenter.MetadataSchemasClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewMetadataSchemasServerTransport(srv *MetadataSchemasServer) *MetadataSchemasServerTransport { + return &MetadataSchemasServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armapicenter.MetadataSchemasClientListResponse]](), + } +} + +// MetadataSchemasServerTransport connects instances of armapicenter.MetadataSchemasClient to instances of MetadataSchemasServer. +// Don't use this type directly, use NewMetadataSchemasServerTransport instead. +type MetadataSchemasServerTransport struct { + srv *MetadataSchemasServer + newListPager *tracker[azfake.PagerResponder[armapicenter.MetadataSchemasClientListResponse]] +} + +// Do implements the policy.Transporter interface for MetadataSchemasServerTransport. +func (m *MetadataSchemasServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToMethodFake(req, method) +} + +func (m *MetadataSchemasServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if metadataSchemasServerTransportInterceptor != nil { + res.resp, res.err, intercepted = metadataSchemasServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "MetadataSchemasClient.CreateOrUpdate": + res.resp, res.err = m.dispatchCreateOrUpdate(req) + case "MetadataSchemasClient.Delete": + res.resp, res.err = m.dispatchDelete(req) + case "MetadataSchemasClient.Get": + res.resp, res.err = m.dispatchGet(req) + case "MetadataSchemasClient.Head": + res.resp, res.err = m.dispatchHead(req) + case "MetadataSchemasClient.NewListPager": + res.resp, res.err = m.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *MetadataSchemasServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if m.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/metadataSchemas/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armapicenter.MetadataSchema](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + metadataSchemaNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("metadataSchemaName")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, serviceNameParam, metadataSchemaNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).MetadataSchema, req) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).EtagHeader; val != nil { + resp.Header.Set("ETag", *val) + } + return resp, nil +} + +func (m *MetadataSchemasServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if m.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/metadataSchemas/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + metadataSchemaNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("metadataSchemaName")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.Delete(req.Context(), resourceGroupNameParam, serviceNameParam, metadataSchemaNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *MetadataSchemasServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if m.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/metadataSchemas/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + metadataSchemaNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("metadataSchemaName")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.Get(req.Context(), resourceGroupNameParam, serviceNameParam, metadataSchemaNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).MetadataSchema, req) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).EtagHeader; val != nil { + resp.Header.Set("ETag", *val) + } + return resp, nil +} + +func (m *MetadataSchemasServerTransport) dispatchHead(req *http.Request) (*http.Response, error) { + if m.srv.Head == nil { + return nil, &nonRetriableError{errors.New("fake for method Head not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/metadataSchemas/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + metadataSchemaNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("metadataSchemaName")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.Head(req.Context(), resourceGroupNameParam, serviceNameParam, metadataSchemaNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *MetadataSchemasServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if m.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := m.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/metadataSchemas` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + filterParam := getOptional(qp.Get("$filter")) + var options *armapicenter.MetadataSchemasClientListOptions + if filterParam != nil { + options = &armapicenter.MetadataSchemasClientListOptions{ + Filter: filterParam, + } + } + resp := m.srv.NewListPager(resourceGroupNameParam, serviceNameParam, options) + newListPager = &resp + m.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armapicenter.MetadataSchemasClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + m.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + m.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to MetadataSchemasServerTransport +var metadataSchemasServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armapicenter/fake/zz_operations_server.go b/test/local/armapicenter/fake/zz_operations_server.go new file mode 100644 index 000000000000..0776508934d4 --- /dev/null +++ b/test/local/armapicenter/fake/zz_operations_server.go @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armapicenter" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "slices" +) + +// OperationsServer is a fake server for instances of the armapicenter.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armapicenter.OperationsClientListOptions) (resp azfake.PagerResponder[armapicenter.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of armapicenter.OperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOperationsServerTransport(srv *OperationsServer) *OperationsServerTransport { + return &OperationsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armapicenter.OperationsClientListResponse]](), + } +} + +// OperationsServerTransport connects instances of armapicenter.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[armapicenter.OperationsClientListResponse]] +} + +// Do implements the policy.Transporter interface for OperationsServerTransport. +func (o *OperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if operationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = operationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OperationsClient.NewListPager": + res.resp, res.err = o.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OperationsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := o.newListPager.get(req) + if newListPager == nil { + resp := o.srv.NewListPager(nil) + newListPager = &resp + o.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armapicenter.OperationsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + o.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + o.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OperationsServerTransport +var operationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armapicenter/fake/zz_server_factory.go b/test/local/armapicenter/fake/zz_server_factory.go new file mode 100644 index 000000000000..1d5994b813cc --- /dev/null +++ b/test/local/armapicenter/fake/zz_server_factory.go @@ -0,0 +1,140 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armapicenter.ClientFactory type. +type ServerFactory struct { + // APIDefinitionsServer contains the fakes for client APIDefinitionsClient + APIDefinitionsServer APIDefinitionsServer + + // APISourcesServer contains the fakes for client APISourcesClient + APISourcesServer APISourcesServer + + // APIVersionsServer contains the fakes for client APIVersionsClient + APIVersionsServer APIVersionsServer + + // ApisServer contains the fakes for client ApisClient + ApisServer ApisServer + + // DeletedServicesServer contains the fakes for client DeletedServicesClient + DeletedServicesServer DeletedServicesServer + + // DeploymentsServer contains the fakes for client DeploymentsClient + DeploymentsServer DeploymentsServer + + // EnvironmentsServer contains the fakes for client EnvironmentsClient + EnvironmentsServer EnvironmentsServer + + // MetadataSchemasServer contains the fakes for client MetadataSchemasClient + MetadataSchemasServer MetadataSchemasServer + + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer + + // ServicesServer contains the fakes for client ServicesClient + ServicesServer ServicesServer + + // WorkspacesServer contains the fakes for client WorkspacesClient + WorkspacesServer WorkspacesServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armapicenter.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of armapicenter.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trAPIDefinitionsServer *APIDefinitionsServerTransport + trAPISourcesServer *APISourcesServerTransport + trAPIVersionsServer *APIVersionsServerTransport + trApisServer *ApisServerTransport + trDeletedServicesServer *DeletedServicesServerTransport + trDeploymentsServer *DeploymentsServerTransport + trEnvironmentsServer *EnvironmentsServerTransport + trMetadataSchemasServer *MetadataSchemasServerTransport + trOperationsServer *OperationsServerTransport + trServicesServer *ServicesServerTransport + trWorkspacesServer *WorkspacesServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "APIDefinitionsClient": + initServer(&s.trMu, &s.trAPIDefinitionsServer, func() *APIDefinitionsServerTransport { + return NewAPIDefinitionsServerTransport(&s.srv.APIDefinitionsServer) + }) + resp, err = s.trAPIDefinitionsServer.Do(req) + case "APISourcesClient": + initServer(&s.trMu, &s.trAPISourcesServer, func() *APISourcesServerTransport { return NewAPISourcesServerTransport(&s.srv.APISourcesServer) }) + resp, err = s.trAPISourcesServer.Do(req) + case "APIVersionsClient": + initServer(&s.trMu, &s.trAPIVersionsServer, func() *APIVersionsServerTransport { return NewAPIVersionsServerTransport(&s.srv.APIVersionsServer) }) + resp, err = s.trAPIVersionsServer.Do(req) + case "ApisClient": + initServer(&s.trMu, &s.trApisServer, func() *ApisServerTransport { return NewApisServerTransport(&s.srv.ApisServer) }) + resp, err = s.trApisServer.Do(req) + case "DeletedServicesClient": + initServer(&s.trMu, &s.trDeletedServicesServer, func() *DeletedServicesServerTransport { + return NewDeletedServicesServerTransport(&s.srv.DeletedServicesServer) + }) + resp, err = s.trDeletedServicesServer.Do(req) + case "DeploymentsClient": + initServer(&s.trMu, &s.trDeploymentsServer, func() *DeploymentsServerTransport { return NewDeploymentsServerTransport(&s.srv.DeploymentsServer) }) + resp, err = s.trDeploymentsServer.Do(req) + case "EnvironmentsClient": + initServer(&s.trMu, &s.trEnvironmentsServer, func() *EnvironmentsServerTransport { return NewEnvironmentsServerTransport(&s.srv.EnvironmentsServer) }) + resp, err = s.trEnvironmentsServer.Do(req) + case "MetadataSchemasClient": + initServer(&s.trMu, &s.trMetadataSchemasServer, func() *MetadataSchemasServerTransport { + return NewMetadataSchemasServerTransport(&s.srv.MetadataSchemasServer) + }) + resp, err = s.trMetadataSchemasServer.Do(req) + case "OperationsClient": + initServer(&s.trMu, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + resp, err = s.trOperationsServer.Do(req) + case "ServicesClient": + initServer(&s.trMu, &s.trServicesServer, func() *ServicesServerTransport { return NewServicesServerTransport(&s.srv.ServicesServer) }) + resp, err = s.trServicesServer.Do(req) + case "WorkspacesClient": + initServer(&s.trMu, &s.trWorkspacesServer, func() *WorkspacesServerTransport { return NewWorkspacesServerTransport(&s.srv.WorkspacesServer) }) + resp, err = s.trWorkspacesServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} diff --git a/test/local/armapicenter/fake/zz_services_server.go b/test/local/armapicenter/fake/zz_services_server.go new file mode 100644 index 000000000000..20997ae6a178 --- /dev/null +++ b/test/local/armapicenter/fake/zz_services_server.go @@ -0,0 +1,387 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armapicenter" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// ServicesServer is a fake server for instances of the armapicenter.ServicesClient type. +type ServicesServer struct { + // CreateOrUpdate is the fake for method ServicesClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, serviceName string, resource armapicenter.Service, options *armapicenter.ServicesClientCreateOrUpdateOptions) (resp azfake.Responder[armapicenter.ServicesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method ServicesClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceGroupName string, serviceName string, options *armapicenter.ServicesClientDeleteOptions) (resp azfake.Responder[armapicenter.ServicesClientDeleteResponse], errResp azfake.ErrorResponder) + + // BeginExportMetadataSchema is the fake for method ServicesClient.BeginExportMetadataSchema + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginExportMetadataSchema func(ctx context.Context, resourceGroupName string, serviceName string, payload armapicenter.MetadataSchemaExportRequest, options *armapicenter.ServicesClientBeginExportMetadataSchemaOptions) (resp azfake.PollerResponder[armapicenter.ServicesClientExportMetadataSchemaResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method ServicesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, serviceName string, options *armapicenter.ServicesClientGetOptions) (resp azfake.Responder[armapicenter.ServicesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method ServicesClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armapicenter.ServicesClientListByResourceGroupOptions) (resp azfake.PagerResponder[armapicenter.ServicesClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method ServicesClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armapicenter.ServicesClientListBySubscriptionOptions) (resp azfake.PagerResponder[armapicenter.ServicesClientListBySubscriptionResponse]) + + // Update is the fake for method ServicesClient.Update + // HTTP status codes to indicate success: http.StatusOK + Update func(ctx context.Context, resourceGroupName string, serviceName string, payload armapicenter.ServiceUpdate, options *armapicenter.ServicesClientUpdateOptions) (resp azfake.Responder[armapicenter.ServicesClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewServicesServerTransport creates a new instance of ServicesServerTransport with the provided implementation. +// The returned ServicesServerTransport instance is connected to an instance of armapicenter.ServicesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServicesServerTransport(srv *ServicesServer) *ServicesServerTransport { + return &ServicesServerTransport{ + srv: srv, + beginExportMetadataSchema: newTracker[azfake.PollerResponder[armapicenter.ServicesClientExportMetadataSchemaResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armapicenter.ServicesClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armapicenter.ServicesClientListBySubscriptionResponse]](), + } +} + +// ServicesServerTransport connects instances of armapicenter.ServicesClient to instances of ServicesServer. +// Don't use this type directly, use NewServicesServerTransport instead. +type ServicesServerTransport struct { + srv *ServicesServer + beginExportMetadataSchema *tracker[azfake.PollerResponder[armapicenter.ServicesClientExportMetadataSchemaResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armapicenter.ServicesClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armapicenter.ServicesClientListBySubscriptionResponse]] +} + +// Do implements the policy.Transporter interface for ServicesServerTransport. +func (s *ServicesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ServicesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if servicesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = servicesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ServicesClient.CreateOrUpdate": + res.resp, res.err = s.dispatchCreateOrUpdate(req) + case "ServicesClient.Delete": + res.resp, res.err = s.dispatchDelete(req) + case "ServicesClient.BeginExportMetadataSchema": + res.resp, res.err = s.dispatchBeginExportMetadataSchema(req) + case "ServicesClient.Get": + res.resp, res.err = s.dispatchGet(req) + case "ServicesClient.NewListByResourceGroupPager": + res.resp, res.err = s.dispatchNewListByResourceGroupPager(req) + case "ServicesClient.NewListBySubscriptionPager": + res.resp, res.err = s.dispatchNewListBySubscriptionPager(req) + case "ServicesClient.Update": + res.resp, res.err = s.dispatchUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ServicesServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if s.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armapicenter.Service](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, serviceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Service, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServicesServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if s.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Delete(req.Context(), resourceGroupNameParam, serviceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServicesServerTransport) dispatchBeginExportMetadataSchema(req *http.Request) (*http.Response, error) { + if s.srv.BeginExportMetadataSchema == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginExportMetadataSchema not implemented")} + } + beginExportMetadataSchema := s.beginExportMetadataSchema.get(req) + if beginExportMetadataSchema == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/exportMetadataSchema` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armapicenter.MetadataSchemaExportRequest](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.BeginExportMetadataSchema(req.Context(), resourceGroupNameParam, serviceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginExportMetadataSchema = &respr + s.beginExportMetadataSchema.add(req, beginExportMetadataSchema) + } + + resp, err := server.PollerResponderNext(beginExportMetadataSchema, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + s.beginExportMetadataSchema.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginExportMetadataSchema) { + s.beginExportMetadataSchema.remove(req) + } + + return resp, nil +} + +func (s *ServicesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if s.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Get(req.Context(), resourceGroupNameParam, serviceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Service, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServicesServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if s.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := s.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := s.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + s.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armapicenter.ServicesClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + s.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + s.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (s *ServicesServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if s.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := s.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := s.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + s.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armapicenter.ServicesClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + s.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + s.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (s *ServicesServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) { + if s.srv.Update == nil { + return nil, &nonRetriableError{errors.New("fake for method Update not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armapicenter.ServiceUpdate](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Update(req.Context(), resourceGroupNameParam, serviceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Service, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ServicesServerTransport +var servicesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armapicenter/fake/zz_workspaces_server.go b/test/local/armapicenter/fake/zz_workspaces_server.go new file mode 100644 index 000000000000..37ff454a1c00 --- /dev/null +++ b/test/local/armapicenter/fake/zz_workspaces_server.go @@ -0,0 +1,320 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armapicenter" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// WorkspacesServer is a fake server for instances of the armapicenter.WorkspacesClient type. +type WorkspacesServer struct { + // CreateOrUpdate is the fake for method WorkspacesClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, payload armapicenter.Workspace, options *armapicenter.WorkspacesClientCreateOrUpdateOptions) (resp azfake.Responder[armapicenter.WorkspacesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method WorkspacesClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, options *armapicenter.WorkspacesClientDeleteOptions) (resp azfake.Responder[armapicenter.WorkspacesClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method WorkspacesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, options *armapicenter.WorkspacesClientGetOptions) (resp azfake.Responder[armapicenter.WorkspacesClientGetResponse], errResp azfake.ErrorResponder) + + // Head is the fake for method WorkspacesClient.Head + // HTTP status codes to indicate success: http.StatusOK + Head func(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, options *armapicenter.WorkspacesClientHeadOptions) (resp azfake.Responder[armapicenter.WorkspacesClientHeadResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method WorkspacesClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, serviceName string, options *armapicenter.WorkspacesClientListOptions) (resp azfake.PagerResponder[armapicenter.WorkspacesClientListResponse]) +} + +// NewWorkspacesServerTransport creates a new instance of WorkspacesServerTransport with the provided implementation. +// The returned WorkspacesServerTransport instance is connected to an instance of armapicenter.WorkspacesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewWorkspacesServerTransport(srv *WorkspacesServer) *WorkspacesServerTransport { + return &WorkspacesServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armapicenter.WorkspacesClientListResponse]](), + } +} + +// WorkspacesServerTransport connects instances of armapicenter.WorkspacesClient to instances of WorkspacesServer. +// Don't use this type directly, use NewWorkspacesServerTransport instead. +type WorkspacesServerTransport struct { + srv *WorkspacesServer + newListPager *tracker[azfake.PagerResponder[armapicenter.WorkspacesClientListResponse]] +} + +// Do implements the policy.Transporter interface for WorkspacesServerTransport. +func (w *WorkspacesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return w.dispatchToMethodFake(req, method) +} + +func (w *WorkspacesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if workspacesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = workspacesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "WorkspacesClient.CreateOrUpdate": + res.resp, res.err = w.dispatchCreateOrUpdate(req) + case "WorkspacesClient.Delete": + res.resp, res.err = w.dispatchDelete(req) + case "WorkspacesClient.Get": + res.resp, res.err = w.dispatchGet(req) + case "WorkspacesClient.Head": + res.resp, res.err = w.dispatchHead(req) + case "WorkspacesClient.NewListPager": + res.resp, res.err = w.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (w *WorkspacesServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if w.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armapicenter.Workspace](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + respr, errRespr := w.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Workspace, req) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).EtagHeader; val != nil { + resp.Header.Set("ETag", *val) + } + return resp, nil +} + +func (w *WorkspacesServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if w.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + respr, errRespr := w.srv.Delete(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (w *WorkspacesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if w.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + respr, errRespr := w.srv.Get(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Workspace, req) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).EtagHeader; val != nil { + resp.Header.Set("ETag", *val) + } + return resp, nil +} + +func (w *WorkspacesServerTransport) dispatchHead(req *http.Request) (*http.Response, error) { + if w.srv.Head == nil { + return nil, &nonRetriableError{errors.New("fake for method Head not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + workspaceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("workspaceName")]) + if err != nil { + return nil, err + } + respr, errRespr := w.srv.Head(req.Context(), resourceGroupNameParam, serviceNameParam, workspaceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (w *WorkspacesServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if w.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := w.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ApiCenter/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/workspaces` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + filterParam := getOptional(qp.Get("$filter")) + var options *armapicenter.WorkspacesClientListOptions + if filterParam != nil { + options = &armapicenter.WorkspacesClientListOptions{ + Filter: filterParam, + } + } + resp := w.srv.NewListPager(resourceGroupNameParam, serviceNameParam, options) + newListPager = &resp + w.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armapicenter.WorkspacesClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + w.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + w.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to WorkspacesServerTransport +var workspacesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armapicenter/go.mod b/test/local/armapicenter/go.mod new file mode 100644 index 000000000000..870e004c0744 --- /dev/null +++ b/test/local/armapicenter/go.mod @@ -0,0 +1,11 @@ +module armapicenter + +go 1.25.0 + +require github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect +) diff --git a/test/local/armapicenter/go.sum b/test/local/armapicenter/go.sum new file mode 100644 index 000000000000..3fdb64caf441 --- /dev/null +++ b/test/local/armapicenter/go.sum @@ -0,0 +1,16 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/local/armapicenter/testdata/_metadata.json b/test/local/armapicenter/testdata/_metadata.json new file mode 100644 index 000000000000..c60ef7ed934c --- /dev/null +++ b/test/local/armapicenter/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Microsoft.ApiCenter": "2024-06-01-preview" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/local/armapicenter/zz_apidefinitions_client.go b/test/local/armapicenter/zz_apidefinitions_client.go new file mode 100644 index 000000000000..d87173a0fee5 --- /dev/null +++ b/test/local/armapicenter/zz_apidefinitions_client.go @@ -0,0 +1,627 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armapicenter + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// APIDefinitionsClient contains the methods for the APIDefinitions group. +// Don't use this type directly, use NewAPIDefinitionsClient() instead. +// +// Generated from API version 2024-06-01-preview +type APIDefinitionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAPIDefinitionsClient creates a new instance of APIDefinitionsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewAPIDefinitionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*APIDefinitionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &APIDefinitionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Creates new or updates existing API definition. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - apiName - The name of the API. +// - versionName - The name of the API version. +// - definitionName - The name of the API definition. +// - payload - Resource create parameters. +// - options - APIDefinitionsClientCreateOrUpdateOptions contains the optional parameters for the APIDefinitionsClient.CreateOrUpdate +// method. +func (client *APIDefinitionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, definitionName string, payload APIDefinition, options *APIDefinitionsClientCreateOrUpdateOptions) (APIDefinitionsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "APIDefinitionsClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, apiName, versionName, definitionName, payload, options) + if err != nil { + return APIDefinitionsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return APIDefinitionsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return APIDefinitionsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *APIDefinitionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, definitionName string, payload APIDefinition, _ *APIDefinitionsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/apis/{apiName}/versions/{versionName}/definitions/{definitionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if apiName == "" { + return nil, errors.New("parameter apiName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{apiName}", url.PathEscape(apiName)) + if versionName == "" { + return nil, errors.New("parameter versionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{versionName}", url.PathEscape(versionName)) + if definitionName == "" { + return nil, errors.New("parameter definitionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{definitionName}", url.PathEscape(definitionName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, payload); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *APIDefinitionsClient) createOrUpdateHandleResponse(resp *http.Response) (APIDefinitionsClientCreateOrUpdateResponse, error) { + result := APIDefinitionsClientCreateOrUpdateResponse{} + if val := resp.Header.Get("ETag"); val != "" { + result.EtagHeader = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.APIDefinition); err != nil { + return APIDefinitionsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Deletes specified API definition. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - apiName - The name of the API. +// - versionName - The name of the API version. +// - definitionName - The name of the API definition. +// - options - APIDefinitionsClientDeleteOptions contains the optional parameters for the APIDefinitionsClient.Delete method. +func (client *APIDefinitionsClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, definitionName string, options *APIDefinitionsClientDeleteOptions) (APIDefinitionsClientDeleteResponse, error) { + var err error + const operationName = "APIDefinitionsClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, apiName, versionName, definitionName, options) + if err != nil { + return APIDefinitionsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return APIDefinitionsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return APIDefinitionsClientDeleteResponse{}, err + } + return APIDefinitionsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *APIDefinitionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, definitionName string, _ *APIDefinitionsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/apis/{apiName}/versions/{versionName}/definitions/{definitionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if apiName == "" { + return nil, errors.New("parameter apiName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{apiName}", url.PathEscape(apiName)) + if versionName == "" { + return nil, errors.New("parameter versionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{versionName}", url.PathEscape(versionName)) + if definitionName == "" { + return nil, errors.New("parameter definitionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{definitionName}", url.PathEscape(definitionName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// BeginExportSpecification - Exports the API specification. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - apiName - The name of the API. +// - versionName - The name of the API version. +// - definitionName - The name of the API definition. +// - options - APIDefinitionsClientBeginExportSpecificationOptions contains the optional parameters for the APIDefinitionsClient.BeginExportSpecification +// method. +func (client *APIDefinitionsClient) BeginExportSpecification(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, definitionName string, options *APIDefinitionsClientBeginExportSpecificationOptions) (*runtime.Poller[APIDefinitionsClientExportSpecificationResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.exportSpecification(ctx, resourceGroupName, serviceName, workspaceName, apiName, versionName, definitionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[APIDefinitionsClientExportSpecificationResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[APIDefinitionsClientExportSpecificationResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ExportSpecification - Exports the API specification. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *APIDefinitionsClient) exportSpecification(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, definitionName string, options *APIDefinitionsClientBeginExportSpecificationOptions) (*http.Response, error) { + var err error + const operationName = "APIDefinitionsClient.BeginExportSpecification" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.exportSpecificationCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, apiName, versionName, definitionName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// exportSpecificationCreateRequest creates the ExportSpecification request. +func (client *APIDefinitionsClient) exportSpecificationCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, definitionName string, _ *APIDefinitionsClientBeginExportSpecificationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/apis/{apiName}/versions/{versionName}/definitions/{definitionName}/exportSpecification" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if apiName == "" { + return nil, errors.New("parameter apiName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{apiName}", url.PathEscape(apiName)) + if versionName == "" { + return nil, errors.New("parameter versionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{versionName}", url.PathEscape(versionName)) + if definitionName == "" { + return nil, errors.New("parameter definitionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{definitionName}", url.PathEscape(definitionName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Get - Returns details of the API definition. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - apiName - The name of the API. +// - versionName - The name of the API version. +// - definitionName - The name of the API definition. +// - options - APIDefinitionsClientGetOptions contains the optional parameters for the APIDefinitionsClient.Get method. +func (client *APIDefinitionsClient) Get(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, definitionName string, options *APIDefinitionsClientGetOptions) (APIDefinitionsClientGetResponse, error) { + var err error + const operationName = "APIDefinitionsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, apiName, versionName, definitionName, options) + if err != nil { + return APIDefinitionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return APIDefinitionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return APIDefinitionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *APIDefinitionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, definitionName string, _ *APIDefinitionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/apis/{apiName}/versions/{versionName}/definitions/{definitionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if apiName == "" { + return nil, errors.New("parameter apiName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{apiName}", url.PathEscape(apiName)) + if versionName == "" { + return nil, errors.New("parameter versionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{versionName}", url.PathEscape(versionName)) + if definitionName == "" { + return nil, errors.New("parameter definitionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{definitionName}", url.PathEscape(definitionName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *APIDefinitionsClient) getHandleResponse(resp *http.Response) (APIDefinitionsClientGetResponse, error) { + result := APIDefinitionsClientGetResponse{} + if val := resp.Header.Get("ETag"); val != "" { + result.EtagHeader = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.APIDefinition); err != nil { + return APIDefinitionsClientGetResponse{}, err + } + return result, nil +} + +// Head - Checks if specified API definition exists. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - apiName - The name of the API. +// - versionName - The name of the API version. +// - definitionName - The name of the API definition. +// - options - APIDefinitionsClientHeadOptions contains the optional parameters for the APIDefinitionsClient.Head method. +func (client *APIDefinitionsClient) Head(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, definitionName string, options *APIDefinitionsClientHeadOptions) (APIDefinitionsClientHeadResponse, error) { + var err error + const operationName = "APIDefinitionsClient.Head" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.headCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, apiName, versionName, definitionName, options) + if err != nil { + return APIDefinitionsClientHeadResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return APIDefinitionsClientHeadResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return APIDefinitionsClientHeadResponse{}, err + } + return APIDefinitionsClientHeadResponse{Success: httpResp.StatusCode >= 200 && httpResp.StatusCode < 300}, nil +} + +// headCreateRequest creates the Head request. +func (client *APIDefinitionsClient) headCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, definitionName string, _ *APIDefinitionsClientHeadOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/apis/{apiName}/versions/{versionName}/definitions/{definitionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if apiName == "" { + return nil, errors.New("parameter apiName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{apiName}", url.PathEscape(apiName)) + if versionName == "" { + return nil, errors.New("parameter versionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{versionName}", url.PathEscape(versionName)) + if definitionName == "" { + return nil, errors.New("parameter definitionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{definitionName}", url.PathEscape(definitionName)) + req, err := runtime.NewRequest(ctx, http.MethodHead, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// BeginImportSpecification - Imports the API specification. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - apiName - The name of the API. +// - versionName - The name of the API version. +// - definitionName - The name of the API definition. +// - body - The content of the action request +// - options - APIDefinitionsClientBeginImportSpecificationOptions contains the optional parameters for the APIDefinitionsClient.BeginImportSpecification +// method. +func (client *APIDefinitionsClient) BeginImportSpecification(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, definitionName string, body APISpecImportRequest, options *APIDefinitionsClientBeginImportSpecificationOptions) (*runtime.Poller[APIDefinitionsClientImportSpecificationResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.importSpecification(ctx, resourceGroupName, serviceName, workspaceName, apiName, versionName, definitionName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[APIDefinitionsClientImportSpecificationResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[APIDefinitionsClientImportSpecificationResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ImportSpecification - Imports the API specification. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *APIDefinitionsClient) importSpecification(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, definitionName string, body APISpecImportRequest, options *APIDefinitionsClientBeginImportSpecificationOptions) (*http.Response, error) { + var err error + const operationName = "APIDefinitionsClient.BeginImportSpecification" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.importSpecificationCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, apiName, versionName, definitionName, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// importSpecificationCreateRequest creates the ImportSpecification request. +func (client *APIDefinitionsClient) importSpecificationCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, definitionName string, body APISpecImportRequest, _ *APIDefinitionsClientBeginImportSpecificationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/apis/{apiName}/versions/{versionName}/definitions/{definitionName}/importSpecification" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if apiName == "" { + return nil, errors.New("parameter apiName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{apiName}", url.PathEscape(apiName)) + if versionName == "" { + return nil, errors.New("parameter versionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{versionName}", url.PathEscape(versionName)) + if definitionName == "" { + return nil, errors.New("parameter definitionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{definitionName}", url.PathEscape(definitionName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// NewListPager - Returns a collection of API definitions. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - apiName - The name of the API. +// - versionName - The name of the API version. +// - options - APIDefinitionsClientListOptions contains the optional parameters for the APIDefinitionsClient.NewListPager method. +func (client *APIDefinitionsClient) NewListPager(resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, options *APIDefinitionsClientListOptions) *runtime.Pager[APIDefinitionsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[APIDefinitionsClientListResponse]{ + More: func(page APIDefinitionsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *APIDefinitionsClientListResponse) (APIDefinitionsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "APIDefinitionsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, apiName, versionName, options) + }, nil) + if err != nil { + return APIDefinitionsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *APIDefinitionsClient) listCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, options *APIDefinitionsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/apis/{apiName}/versions/{versionName}/definitions" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if apiName == "" { + return nil, errors.New("parameter apiName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{apiName}", url.PathEscape(apiName)) + if versionName == "" { + return nil, errors.New("parameter versionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{versionName}", url.PathEscape(versionName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *APIDefinitionsClient) listHandleResponse(resp *http.Response) (APIDefinitionsClientListResponse, error) { + result := APIDefinitionsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.APIDefinitionListResult); err != nil { + return APIDefinitionsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armapicenter/zz_apis_client.go b/test/local/armapicenter/zz_apis_client.go new file mode 100644 index 000000000000..10aac60b1f42 --- /dev/null +++ b/test/local/armapicenter/zz_apis_client.go @@ -0,0 +1,388 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armapicenter + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ApisClient contains the methods for the Apis group. +// Don't use this type directly, use NewApisClient() instead. +// +// Generated from API version 2024-06-01-preview +type ApisClient struct { + internal *arm.Client + subscriptionID string +} + +// NewApisClient creates a new instance of ApisClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewApisClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ApisClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ApisClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Creates new or updates existing API. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - apiName - The name of the API. +// - payload - Resource create parameters. +// - options - ApisClientCreateOrUpdateOptions contains the optional parameters for the ApisClient.CreateOrUpdate method. +func (client *ApisClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, payload API, options *ApisClientCreateOrUpdateOptions) (ApisClientCreateOrUpdateResponse, error) { + var err error + const operationName = "ApisClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, apiName, payload, options) + if err != nil { + return ApisClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ApisClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return ApisClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *ApisClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, payload API, _ *ApisClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/apis/{apiName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if apiName == "" { + return nil, errors.New("parameter apiName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{apiName}", url.PathEscape(apiName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, payload); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *ApisClient) createOrUpdateHandleResponse(resp *http.Response) (ApisClientCreateOrUpdateResponse, error) { + result := ApisClientCreateOrUpdateResponse{} + if val := resp.Header.Get("ETag"); val != "" { + result.EtagHeader = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.API); err != nil { + return ApisClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Deletes specified API. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - apiName - The name of the API. +// - options - ApisClientDeleteOptions contains the optional parameters for the ApisClient.Delete method. +func (client *ApisClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, options *ApisClientDeleteOptions) (ApisClientDeleteResponse, error) { + var err error + const operationName = "ApisClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, apiName, options) + if err != nil { + return ApisClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ApisClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ApisClientDeleteResponse{}, err + } + return ApisClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ApisClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, _ *ApisClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/apis/{apiName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if apiName == "" { + return nil, errors.New("parameter apiName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{apiName}", url.PathEscape(apiName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Returns details of the API. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - apiName - The name of the API. +// - options - ApisClientGetOptions contains the optional parameters for the ApisClient.Get method. +func (client *ApisClient) Get(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, options *ApisClientGetOptions) (ApisClientGetResponse, error) { + var err error + const operationName = "ApisClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, apiName, options) + if err != nil { + return ApisClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ApisClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ApisClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ApisClient) getCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, _ *ApisClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/apis/{apiName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if apiName == "" { + return nil, errors.New("parameter apiName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{apiName}", url.PathEscape(apiName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ApisClient) getHandleResponse(resp *http.Response) (ApisClientGetResponse, error) { + result := ApisClientGetResponse{} + if val := resp.Header.Get("ETag"); val != "" { + result.EtagHeader = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.API); err != nil { + return ApisClientGetResponse{}, err + } + return result, nil +} + +// Head - Checks if specified API exists. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - apiName - The name of the API. +// - options - ApisClientHeadOptions contains the optional parameters for the ApisClient.Head method. +func (client *ApisClient) Head(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, options *ApisClientHeadOptions) (ApisClientHeadResponse, error) { + var err error + const operationName = "ApisClient.Head" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.headCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, apiName, options) + if err != nil { + return ApisClientHeadResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ApisClientHeadResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ApisClientHeadResponse{}, err + } + return ApisClientHeadResponse{Success: httpResp.StatusCode >= 200 && httpResp.StatusCode < 300}, nil +} + +// headCreateRequest creates the Head request. +func (client *ApisClient) headCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, _ *ApisClientHeadOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/apis/{apiName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if apiName == "" { + return nil, errors.New("parameter apiName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{apiName}", url.PathEscape(apiName)) + req, err := runtime.NewRequest(ctx, http.MethodHead, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// NewListPager - Returns a collection of APIs. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - options - ApisClientListOptions contains the optional parameters for the ApisClient.NewListPager method. +func (client *ApisClient) NewListPager(resourceGroupName string, serviceName string, workspaceName string, options *ApisClientListOptions) *runtime.Pager[ApisClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ApisClientListResponse]{ + More: func(page ApisClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ApisClientListResponse) (ApisClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ApisClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, options) + }, nil) + if err != nil { + return ApisClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ApisClient) listCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, options *ApisClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/apis" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ApisClient) listHandleResponse(resp *http.Response) (ApisClientListResponse, error) { + result := ApisClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.APIListResult); err != nil { + return ApisClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armapicenter/zz_apisources_client.go b/test/local/armapicenter/zz_apisources_client.go new file mode 100644 index 000000000000..6e8f6b9a1acb --- /dev/null +++ b/test/local/armapicenter/zz_apisources_client.go @@ -0,0 +1,389 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armapicenter + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// APISourcesClient contains the methods for the APISources group. +// Don't use this type directly, use NewAPISourcesClient() instead. +// +// Generated from API version 2024-06-01-preview +type APISourcesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAPISourcesClient creates a new instance of APISourcesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewAPISourcesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*APISourcesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &APISourcesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Creates new or updates existing API source. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - apiSourceName - The name of the API. +// - resource - Resource create parameters. +// - options - APISourcesClientCreateOrUpdateOptions contains the optional parameters for the APISourcesClient.CreateOrUpdate +// method. +func (client *APISourcesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiSourceName string, resource APISource, options *APISourcesClientCreateOrUpdateOptions) (APISourcesClientCreateOrUpdateResponse, error) { + var err error + const operationName = "APISourcesClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, apiSourceName, resource, options) + if err != nil { + return APISourcesClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return APISourcesClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return APISourcesClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *APISourcesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiSourceName string, resource APISource, _ *APISourcesClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/apiSources/{apiSourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if apiSourceName == "" { + return nil, errors.New("parameter apiSourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{apiSourceName}", url.PathEscape(apiSourceName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *APISourcesClient) createOrUpdateHandleResponse(resp *http.Response) (APISourcesClientCreateOrUpdateResponse, error) { + result := APISourcesClientCreateOrUpdateResponse{} + if val := resp.Header.Get("ETag"); val != "" { + result.EtagHeader = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.APISource); err != nil { + return APISourcesClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Deletes specified API source. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - apiSourceName - The name of the API. +// - options - APISourcesClientDeleteOptions contains the optional parameters for the APISourcesClient.Delete method. +func (client *APISourcesClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiSourceName string, options *APISourcesClientDeleteOptions) (APISourcesClientDeleteResponse, error) { + var err error + const operationName = "APISourcesClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, apiSourceName, options) + if err != nil { + return APISourcesClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return APISourcesClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return APISourcesClientDeleteResponse{}, err + } + return APISourcesClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *APISourcesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiSourceName string, _ *APISourcesClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/apiSources/{apiSourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if apiSourceName == "" { + return nil, errors.New("parameter apiSourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{apiSourceName}", url.PathEscape(apiSourceName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Returns details of the API source. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - apiSourceName - The name of the API. +// - options - APISourcesClientGetOptions contains the optional parameters for the APISourcesClient.Get method. +func (client *APISourcesClient) Get(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiSourceName string, options *APISourcesClientGetOptions) (APISourcesClientGetResponse, error) { + var err error + const operationName = "APISourcesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, apiSourceName, options) + if err != nil { + return APISourcesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return APISourcesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return APISourcesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *APISourcesClient) getCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiSourceName string, _ *APISourcesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/apiSources/{apiSourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if apiSourceName == "" { + return nil, errors.New("parameter apiSourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{apiSourceName}", url.PathEscape(apiSourceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *APISourcesClient) getHandleResponse(resp *http.Response) (APISourcesClientGetResponse, error) { + result := APISourcesClientGetResponse{} + if val := resp.Header.Get("ETag"); val != "" { + result.EtagHeader = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.APISource); err != nil { + return APISourcesClientGetResponse{}, err + } + return result, nil +} + +// Head - Checks if specified API source exists. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - apiSourceName - The name of the API. +// - options - APISourcesClientHeadOptions contains the optional parameters for the APISourcesClient.Head method. +func (client *APISourcesClient) Head(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiSourceName string, options *APISourcesClientHeadOptions) (APISourcesClientHeadResponse, error) { + var err error + const operationName = "APISourcesClient.Head" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.headCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, apiSourceName, options) + if err != nil { + return APISourcesClientHeadResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return APISourcesClientHeadResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return APISourcesClientHeadResponse{}, err + } + return APISourcesClientHeadResponse{Success: httpResp.StatusCode >= 200 && httpResp.StatusCode < 300}, nil +} + +// headCreateRequest creates the Head request. +func (client *APISourcesClient) headCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiSourceName string, _ *APISourcesClientHeadOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/apiSources/{apiSourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if apiSourceName == "" { + return nil, errors.New("parameter apiSourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{apiSourceName}", url.PathEscape(apiSourceName)) + req, err := runtime.NewRequest(ctx, http.MethodHead, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// NewListPager - Returns a collection of API sources. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - options - APISourcesClientListOptions contains the optional parameters for the APISourcesClient.NewListPager method. +func (client *APISourcesClient) NewListPager(resourceGroupName string, serviceName string, workspaceName string, options *APISourcesClientListOptions) *runtime.Pager[APISourcesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[APISourcesClientListResponse]{ + More: func(page APISourcesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *APISourcesClientListResponse) (APISourcesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "APISourcesClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, options) + }, nil) + if err != nil { + return APISourcesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *APISourcesClient) listCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, options *APISourcesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/apiSources" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *APISourcesClient) listHandleResponse(resp *http.Response) (APISourcesClientListResponse, error) { + result := APISourcesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.APISourceListResult); err != nil { + return APISourcesClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armapicenter/zz_apiversions_client.go b/test/local/armapicenter/zz_apiversions_client.go new file mode 100644 index 000000000000..81495e72b500 --- /dev/null +++ b/test/local/armapicenter/zz_apiversions_client.go @@ -0,0 +1,414 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armapicenter + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// APIVersionsClient contains the methods for the APIVersions group. +// Don't use this type directly, use NewAPIVersionsClient() instead. +// +// Generated from API version 2024-06-01-preview +type APIVersionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAPIVersionsClient creates a new instance of APIVersionsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewAPIVersionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*APIVersionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &APIVersionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Creates new or updates existing API version. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - apiName - The name of the API. +// - versionName - The name of the API version. +// - payload - Resource create parameters. +// - options - APIVersionsClientCreateOrUpdateOptions contains the optional parameters for the APIVersionsClient.CreateOrUpdate +// method. +func (client *APIVersionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, payload APIVersion, options *APIVersionsClientCreateOrUpdateOptions) (APIVersionsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "APIVersionsClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, apiName, versionName, payload, options) + if err != nil { + return APIVersionsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return APIVersionsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return APIVersionsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *APIVersionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, payload APIVersion, _ *APIVersionsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/apis/{apiName}/versions/{versionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if apiName == "" { + return nil, errors.New("parameter apiName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{apiName}", url.PathEscape(apiName)) + if versionName == "" { + return nil, errors.New("parameter versionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{versionName}", url.PathEscape(versionName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, payload); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *APIVersionsClient) createOrUpdateHandleResponse(resp *http.Response) (APIVersionsClientCreateOrUpdateResponse, error) { + result := APIVersionsClientCreateOrUpdateResponse{} + if val := resp.Header.Get("ETag"); val != "" { + result.EtagHeader = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.APIVersion); err != nil { + return APIVersionsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Deletes specified API version +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - apiName - The name of the API. +// - versionName - The name of the API version. +// - options - APIVersionsClientDeleteOptions contains the optional parameters for the APIVersionsClient.Delete method. +func (client *APIVersionsClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, options *APIVersionsClientDeleteOptions) (APIVersionsClientDeleteResponse, error) { + var err error + const operationName = "APIVersionsClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, apiName, versionName, options) + if err != nil { + return APIVersionsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return APIVersionsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return APIVersionsClientDeleteResponse{}, err + } + return APIVersionsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *APIVersionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, _ *APIVersionsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/apis/{apiName}/versions/{versionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if apiName == "" { + return nil, errors.New("parameter apiName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{apiName}", url.PathEscape(apiName)) + if versionName == "" { + return nil, errors.New("parameter versionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{versionName}", url.PathEscape(versionName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Returns details of the API version. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - apiName - The name of the API. +// - versionName - The name of the API version. +// - options - APIVersionsClientGetOptions contains the optional parameters for the APIVersionsClient.Get method. +func (client *APIVersionsClient) Get(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, options *APIVersionsClientGetOptions) (APIVersionsClientGetResponse, error) { + var err error + const operationName = "APIVersionsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, apiName, versionName, options) + if err != nil { + return APIVersionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return APIVersionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return APIVersionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *APIVersionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, _ *APIVersionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/apis/{apiName}/versions/{versionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if apiName == "" { + return nil, errors.New("parameter apiName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{apiName}", url.PathEscape(apiName)) + if versionName == "" { + return nil, errors.New("parameter versionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{versionName}", url.PathEscape(versionName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *APIVersionsClient) getHandleResponse(resp *http.Response) (APIVersionsClientGetResponse, error) { + result := APIVersionsClientGetResponse{} + if val := resp.Header.Get("ETag"); val != "" { + result.EtagHeader = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.APIVersion); err != nil { + return APIVersionsClientGetResponse{}, err + } + return result, nil +} + +// Head - Checks if specified API version exists. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - apiName - The name of the API. +// - versionName - The name of the API version. +// - options - APIVersionsClientHeadOptions contains the optional parameters for the APIVersionsClient.Head method. +func (client *APIVersionsClient) Head(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, options *APIVersionsClientHeadOptions) (APIVersionsClientHeadResponse, error) { + var err error + const operationName = "APIVersionsClient.Head" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.headCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, apiName, versionName, options) + if err != nil { + return APIVersionsClientHeadResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return APIVersionsClientHeadResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return APIVersionsClientHeadResponse{}, err + } + return APIVersionsClientHeadResponse{Success: httpResp.StatusCode >= 200 && httpResp.StatusCode < 300}, nil +} + +// headCreateRequest creates the Head request. +func (client *APIVersionsClient) headCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, versionName string, _ *APIVersionsClientHeadOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/apis/{apiName}/versions/{versionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if apiName == "" { + return nil, errors.New("parameter apiName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{apiName}", url.PathEscape(apiName)) + if versionName == "" { + return nil, errors.New("parameter versionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{versionName}", url.PathEscape(versionName)) + req, err := runtime.NewRequest(ctx, http.MethodHead, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// NewListPager - Returns a collection of API versions. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - apiName - The name of the API. +// - options - APIVersionsClientListOptions contains the optional parameters for the APIVersionsClient.NewListPager method. +func (client *APIVersionsClient) NewListPager(resourceGroupName string, serviceName string, workspaceName string, apiName string, options *APIVersionsClientListOptions) *runtime.Pager[APIVersionsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[APIVersionsClientListResponse]{ + More: func(page APIVersionsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *APIVersionsClientListResponse) (APIVersionsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "APIVersionsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, apiName, options) + }, nil) + if err != nil { + return APIVersionsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *APIVersionsClient) listCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, options *APIVersionsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/apis/{apiName}/versions" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if apiName == "" { + return nil, errors.New("parameter apiName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{apiName}", url.PathEscape(apiName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *APIVersionsClient) listHandleResponse(resp *http.Response) (APIVersionsClientListResponse, error) { + result := APIVersionsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.APIVersionListResult); err != nil { + return APIVersionsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armapicenter/zz_client_factory.go b/test/local/armapicenter/zz_client_factory.go new file mode 100644 index 000000000000..a7fa953a4aeb --- /dev/null +++ b/test/local/armapicenter/zz_client_factory.go @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armapicenter + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + subscriptionID string + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, + internal: internal, + }, nil +} + +// NewAPIDefinitionsClient creates a new instance of APIDefinitionsClient. +func (c *ClientFactory) NewAPIDefinitionsClient() *APIDefinitionsClient { + return &APIDefinitionsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewAPISourcesClient creates a new instance of APISourcesClient. +func (c *ClientFactory) NewAPISourcesClient() *APISourcesClient { + return &APISourcesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewAPIVersionsClient creates a new instance of APIVersionsClient. +func (c *ClientFactory) NewAPIVersionsClient() *APIVersionsClient { + return &APIVersionsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewApisClient creates a new instance of ApisClient. +func (c *ClientFactory) NewApisClient() *ApisClient { + return &ApisClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewDeletedServicesClient creates a new instance of DeletedServicesClient. +func (c *ClientFactory) NewDeletedServicesClient() *DeletedServicesClient { + return &DeletedServicesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewDeploymentsClient creates a new instance of DeploymentsClient. +func (c *ClientFactory) NewDeploymentsClient() *DeploymentsClient { + return &DeploymentsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewEnvironmentsClient creates a new instance of EnvironmentsClient. +func (c *ClientFactory) NewEnvironmentsClient() *EnvironmentsClient { + return &EnvironmentsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewMetadataSchemasClient creates a new instance of MetadataSchemasClient. +func (c *ClientFactory) NewMetadataSchemasClient() *MetadataSchemasClient { + return &MetadataSchemasClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: c.internal, + } +} + +// NewServicesClient creates a new instance of ServicesClient. +func (c *ClientFactory) NewServicesClient() *ServicesClient { + return &ServicesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewWorkspacesClient creates a new instance of WorkspacesClient. +func (c *ClientFactory) NewWorkspacesClient() *WorkspacesClient { + return &WorkspacesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} diff --git a/test/local/armapicenter/zz_constants.go b/test/local/armapicenter/zz_constants.go new file mode 100644 index 000000000000..12b208a48539 --- /dev/null +++ b/test/local/armapicenter/zz_constants.go @@ -0,0 +1,375 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armapicenter + +const ( + version20240601Preview string = "2024-06-01-preview" +) + +// APIKind - The kind of the API +type APIKind string + +const ( + // APIKindGraphql - A Graph query language Api + APIKindGraphql APIKind = "graphql" + // APIKindGrpc - A gRPC Api + APIKindGrpc APIKind = "grpc" + // APIKindRest - A Representational State Transfer Api + APIKindRest APIKind = "rest" + // APIKindSoap - A SOAP Api + APIKindSoap APIKind = "soap" + // APIKindWebhook - Web Hook + APIKindWebhook APIKind = "webhook" + // APIKindWebsocket - Web Socket + APIKindWebsocket APIKind = "websocket" +) + +// PossibleAPIKindValues returns the possible values for the APIKind const type. +func PossibleAPIKindValues() []APIKind { + return []APIKind{ + APIKindGraphql, + APIKindGrpc, + APIKindRest, + APIKindSoap, + APIKindWebhook, + APIKindWebsocket, + } +} + +// APISourceLinkState - The API source link state. +type APISourceLinkState string + +const ( + // APISourceLinkStateDeleting - The API source is being deleted. + APISourceLinkStateDeleting APISourceLinkState = "deleting" + // APISourceLinkStateError - The API source sync is blocked due to an error. + APISourceLinkStateError APISourceLinkState = "error" + // APISourceLinkStateInitializing - The API source link is initializing. + APISourceLinkStateInitializing APISourceLinkState = "initializing" + // APISourceLinkStateSyncing - * + // The API source is syncing. + APISourceLinkStateSyncing APISourceLinkState = "syncing" +) + +// PossibleAPISourceLinkStateValues returns the possible values for the APISourceLinkState const type. +func PossibleAPISourceLinkStateValues() []APISourceLinkState { + return []APISourceLinkState{ + APISourceLinkStateDeleting, + APISourceLinkStateError, + APISourceLinkStateInitializing, + APISourceLinkStateSyncing, + } +} + +// APISpecExportResultFormat - Result format for exported Api spec +type APISpecExportResultFormat string + +const ( + // APISpecExportResultFormatInline - The inlined content of a specification document. + APISpecExportResultFormatInline APISpecExportResultFormat = "inline" + // APISpecExportResultFormatLink - The link to the result of the export operation. The URL is valid for 5 minutes. + APISpecExportResultFormatLink APISpecExportResultFormat = "link" +) + +// PossibleAPISpecExportResultFormatValues returns the possible values for the APISpecExportResultFormat const type. +func PossibleAPISpecExportResultFormatValues() []APISpecExportResultFormat { + return []APISpecExportResultFormat{ + APISpecExportResultFormatInline, + APISpecExportResultFormatLink, + } +} + +// APISpecImportSourceFormat - Source format for imported Api spec +type APISpecImportSourceFormat string + +const ( + // APISpecImportSourceFormatInline - The inlined content of a specification document. + APISpecImportSourceFormatInline APISpecImportSourceFormat = "inline" + // APISpecImportSourceFormatLink - The link to a specification document hosted on a publicly accessible internet + // address. + APISpecImportSourceFormatLink APISpecImportSourceFormat = "link" +) + +// PossibleAPISpecImportSourceFormatValues returns the possible values for the APISpecImportSourceFormat const type. +func PossibleAPISpecImportSourceFormatValues() []APISpecImportSourceFormat { + return []APISpecImportSourceFormat{ + APISpecImportSourceFormatInline, + APISpecImportSourceFormatLink, + } +} + +// ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +type ActionType string + +const ( + // ActionTypeInternal - Actions are for internal-only APIs. + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// DeploymentState - State of the Deployment +type DeploymentState string + +const ( + // DeploymentStateActive - Active State + DeploymentStateActive DeploymentState = "active" + // DeploymentStateInactive - Inactive State + DeploymentStateInactive DeploymentState = "inactive" +) + +// PossibleDeploymentStateValues returns the possible values for the DeploymentState const type. +func PossibleDeploymentStateValues() []DeploymentState { + return []DeploymentState{ + DeploymentStateActive, + DeploymentStateInactive, + } +} + +// EnvironmentKind - The kind of environment +type EnvironmentKind string + +const ( + // EnvironmentKindDevelopment - Development environment + EnvironmentKindDevelopment EnvironmentKind = "development" + // EnvironmentKindProduction - Production environment + EnvironmentKindProduction EnvironmentKind = "production" + // EnvironmentKindStaging - Staging environment + EnvironmentKindStaging EnvironmentKind = "staging" + // EnvironmentKindTesting - Testing environment + EnvironmentKindTesting EnvironmentKind = "testing" +) + +// PossibleEnvironmentKindValues returns the possible values for the EnvironmentKind const type. +func PossibleEnvironmentKindValues() []EnvironmentKind { + return []EnvironmentKind{ + EnvironmentKindDevelopment, + EnvironmentKindProduction, + EnvironmentKindStaging, + EnvironmentKindTesting, + } +} + +// EnvironmentServerType - The type of environment server +type EnvironmentServerType string + +const ( + // EnvironmentServerTypeAWSAPIGateway - AWS Api Gateway server + EnvironmentServerTypeAWSAPIGateway EnvironmentServerType = "AWS API Gateway" + // EnvironmentServerTypeApigeeAPIManagement - Apigee server + EnvironmentServerTypeApigeeAPIManagement EnvironmentServerType = "Apigee API Management" + // EnvironmentServerTypeAzureAPIManagement - Api Management Server + EnvironmentServerTypeAzureAPIManagement EnvironmentServerType = "Azure API Management" + // EnvironmentServerTypeAzureComputeService - Compute server + EnvironmentServerTypeAzureComputeService EnvironmentServerType = "Azure compute service" + // EnvironmentServerTypeKongAPIGateway - Kong API Gateway server + EnvironmentServerTypeKongAPIGateway EnvironmentServerType = "Kong API Gateway" + // EnvironmentServerTypeKubernetes - Kubernetes server + EnvironmentServerTypeKubernetes EnvironmentServerType = "Kubernetes" + // EnvironmentServerTypeMuleSoftAPIManagement - Mulesoft Api Management server + EnvironmentServerTypeMuleSoftAPIManagement EnvironmentServerType = "MuleSoft API Management" +) + +// PossibleEnvironmentServerTypeValues returns the possible values for the EnvironmentServerType const type. +func PossibleEnvironmentServerTypeValues() []EnvironmentServerType { + return []EnvironmentServerType{ + EnvironmentServerTypeAWSAPIGateway, + EnvironmentServerTypeApigeeAPIManagement, + EnvironmentServerTypeAzureAPIManagement, + EnvironmentServerTypeAzureComputeService, + EnvironmentServerTypeKongAPIGateway, + EnvironmentServerTypeKubernetes, + EnvironmentServerTypeMuleSoftAPIManagement, + } +} + +// ImportSpecificationOptions - The API source specification import options. +type ImportSpecificationOptions string + +const ( + // ImportSpecificationOptionsAlways - Indicates that the specification should always be imported along with metadata. + ImportSpecificationOptionsAlways ImportSpecificationOptions = "always" + // ImportSpecificationOptionsNever - Indicates that the specification should be never be imported. + ImportSpecificationOptionsNever ImportSpecificationOptions = "never" + // ImportSpecificationOptionsOnDemand - Indicates that the specification should be imported only by request. + ImportSpecificationOptionsOnDemand ImportSpecificationOptions = "ondemand" +) + +// PossibleImportSpecificationOptionsValues returns the possible values for the ImportSpecificationOptions const type. +func PossibleImportSpecificationOptionsValues() []ImportSpecificationOptions { + return []ImportSpecificationOptions{ + ImportSpecificationOptionsAlways, + ImportSpecificationOptionsNever, + ImportSpecificationOptionsOnDemand, + } +} + +// LifecycleStage - The stage of the Api development lifecycle +type LifecycleStage string + +const ( + // LifecycleStageDeprecated - deprecated stage + LifecycleStageDeprecated LifecycleStage = "deprecated" + // LifecycleStageDesign - design stage + LifecycleStageDesign LifecycleStage = "design" + // LifecycleStageDevelopment - development stage + LifecycleStageDevelopment LifecycleStage = "development" + // LifecycleStagePreview - In preview + LifecycleStagePreview LifecycleStage = "preview" + // LifecycleStageProduction - In production + LifecycleStageProduction LifecycleStage = "production" + // LifecycleStageRetired - Retired stage + LifecycleStageRetired LifecycleStage = "retired" + // LifecycleStageTesting - testing stage + LifecycleStageTesting LifecycleStage = "testing" +) + +// PossibleLifecycleStageValues returns the possible values for the LifecycleStage const type. +func PossibleLifecycleStageValues() []LifecycleStage { + return []LifecycleStage{ + LifecycleStageDeprecated, + LifecycleStageDesign, + LifecycleStageDevelopment, + LifecycleStagePreview, + LifecycleStageProduction, + LifecycleStageRetired, + LifecycleStageTesting, + } +} + +// ManagedServiceIdentityType - Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). +type ManagedServiceIdentityType string + +const ( + // ManagedServiceIdentityTypeNone - No managed identity. + ManagedServiceIdentityTypeNone ManagedServiceIdentityType = "None" + // ManagedServiceIdentityTypeSystemAssigned - System assigned managed identity. + ManagedServiceIdentityTypeSystemAssigned ManagedServiceIdentityType = "SystemAssigned" + // ManagedServiceIdentityTypeSystemAssignedUserAssigned - System and user assigned managed identity. + ManagedServiceIdentityTypeSystemAssignedUserAssigned ManagedServiceIdentityType = "SystemAssigned,UserAssigned" + // ManagedServiceIdentityTypeUserAssigned - User assigned managed identity. + ManagedServiceIdentityTypeUserAssigned ManagedServiceIdentityType = "UserAssigned" +) + +// PossibleManagedServiceIdentityTypeValues returns the possible values for the ManagedServiceIdentityType const type. +func PossibleManagedServiceIdentityTypeValues() []ManagedServiceIdentityType { + return []ManagedServiceIdentityType{ + ManagedServiceIdentityTypeNone, + ManagedServiceIdentityTypeSystemAssigned, + ManagedServiceIdentityTypeSystemAssignedUserAssigned, + ManagedServiceIdentityTypeUserAssigned, + } +} + +// MetadataAssignmentEntity - Assignment entity for Metadata +type MetadataAssignmentEntity string + +const ( + // MetadataAssignmentEntityAPI - Assigned to API + MetadataAssignmentEntityAPI MetadataAssignmentEntity = "api" + // MetadataAssignmentEntityDeployment - Assigned to Deployment + MetadataAssignmentEntityDeployment MetadataAssignmentEntity = "deployment" + // MetadataAssignmentEntityEnvironment - Assigned to Environment + MetadataAssignmentEntityEnvironment MetadataAssignmentEntity = "environment" +) + +// PossibleMetadataAssignmentEntityValues returns the possible values for the MetadataAssignmentEntity const type. +func PossibleMetadataAssignmentEntityValues() []MetadataAssignmentEntity { + return []MetadataAssignmentEntity{ + MetadataAssignmentEntityAPI, + MetadataAssignmentEntityDeployment, + MetadataAssignmentEntityEnvironment, + } +} + +// MetadataSchemaExportFormat - The format for schema export +type MetadataSchemaExportFormat string + +const ( + // MetadataSchemaExportFormatInline - The inlined content of a schema document. + MetadataSchemaExportFormatInline MetadataSchemaExportFormat = "inline" + // MetadataSchemaExportFormatLink - The link to a schema document. The URL is valid for 5 minutes. + MetadataSchemaExportFormatLink MetadataSchemaExportFormat = "link" +) + +// PossibleMetadataSchemaExportFormatValues returns the possible values for the MetadataSchemaExportFormat const type. +func PossibleMetadataSchemaExportFormatValues() []MetadataSchemaExportFormat { + return []MetadataSchemaExportFormat{ + MetadataSchemaExportFormatInline, + MetadataSchemaExportFormatLink, + } +} + +// Origin - The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default +// value is "user,system" +type Origin string + +const ( + // OriginSystem - Indicates the operation is initiated by a system. + OriginSystem Origin = "system" + // OriginUser - Indicates the operation is initiated by a user. + OriginUser Origin = "user" + // OriginUserSystem - Indicates the operation is initiated by a user or system. + OriginUserSystem Origin = "user,system" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginSystem, + OriginUser, + OriginUserSystem, + } +} + +// ProvisioningState - The provisioning state of the resource +type ProvisioningState string + +const ( + // ProvisioningStateCanceled - Resource creation was canceled. + ProvisioningStateCanceled ProvisioningState = "Canceled" + // ProvisioningStateFailed - Resource creation failed. + ProvisioningStateFailed ProvisioningState = "Failed" + // ProvisioningStateSucceeded - Resource has been created. + ProvisioningStateSucceeded ProvisioningState = "Succeeded" +) + +// PossibleProvisioningStateValues returns the possible values for the ProvisioningState const type. +func PossibleProvisioningStateValues() []ProvisioningState { + return []ProvisioningState{ + ProvisioningStateCanceled, + ProvisioningStateFailed, + ProvisioningStateSucceeded, + } +} diff --git a/test/local/armapicenter/zz_deletedservices_client.go b/test/local/armapicenter/zz_deletedservices_client.go new file mode 100644 index 000000000000..752e6b7820da --- /dev/null +++ b/test/local/armapicenter/zz_deletedservices_client.go @@ -0,0 +1,272 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armapicenter + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// DeletedServicesClient contains the methods for the DeletedServices group. +// Don't use this type directly, use NewDeletedServicesClient() instead. +// +// Generated from API version 2024-06-01-preview +type DeletedServicesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDeletedServicesClient creates a new instance of DeletedServicesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewDeletedServicesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DeletedServicesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DeletedServicesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Delete - Permanently deletes specified service. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - deletedServiceName - The name of the deleted service. +// - options - DeletedServicesClientDeleteOptions contains the optional parameters for the DeletedServicesClient.Delete method. +func (client *DeletedServicesClient) Delete(ctx context.Context, resourceGroupName string, deletedServiceName string, options *DeletedServicesClientDeleteOptions) (DeletedServicesClientDeleteResponse, error) { + var err error + const operationName = "DeletedServicesClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, deletedServiceName, options) + if err != nil { + return DeletedServicesClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DeletedServicesClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DeletedServicesClientDeleteResponse{}, err + } + return DeletedServicesClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *DeletedServicesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, deletedServiceName string, _ *DeletedServicesClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/deletedServices/{deletedServiceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if deletedServiceName == "" { + return nil, errors.New("parameter deletedServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{deletedServiceName}", url.PathEscape(deletedServiceName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Returns details of the soft-deleted service. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - deletedServiceName - The name of the deleted service. +// - options - DeletedServicesClientGetOptions contains the optional parameters for the DeletedServicesClient.Get method. +func (client *DeletedServicesClient) Get(ctx context.Context, resourceGroupName string, deletedServiceName string, options *DeletedServicesClientGetOptions) (DeletedServicesClientGetResponse, error) { + var err error + const operationName = "DeletedServicesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, deletedServiceName, options) + if err != nil { + return DeletedServicesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DeletedServicesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DeletedServicesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DeletedServicesClient) getCreateRequest(ctx context.Context, resourceGroupName string, deletedServiceName string, _ *DeletedServicesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/deletedServices/{deletedServiceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if deletedServiceName == "" { + return nil, errors.New("parameter deletedServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{deletedServiceName}", url.PathEscape(deletedServiceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DeletedServicesClient) getHandleResponse(resp *http.Response) (DeletedServicesClientGetResponse, error) { + result := DeletedServicesClientGetResponse{} + if val := resp.Header.Get("ETag"); val != "" { + result.EtagHeader = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.DeletedService); err != nil { + return DeletedServicesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists soft-deleted services. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - DeletedServicesClientListOptions contains the optional parameters for the DeletedServicesClient.NewListPager +// method. +func (client *DeletedServicesClient) NewListPager(resourceGroupName string, options *DeletedServicesClientListOptions) *runtime.Pager[DeletedServicesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[DeletedServicesClientListResponse]{ + More: func(page DeletedServicesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DeletedServicesClientListResponse) (DeletedServicesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DeletedServicesClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return DeletedServicesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *DeletedServicesClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *DeletedServicesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/deletedServices" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *DeletedServicesClient) listHandleResponse(resp *http.Response) (DeletedServicesClientListResponse, error) { + result := DeletedServicesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DeletedServiceListResult); err != nil { + return DeletedServicesClientListResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - Lists services within an Azure subscription. +// - options - DeletedServicesClientListBySubscriptionOptions contains the optional parameters for the DeletedServicesClient.NewListBySubscriptionPager +// method. +func (client *DeletedServicesClient) NewListBySubscriptionPager(options *DeletedServicesClientListBySubscriptionOptions) *runtime.Pager[DeletedServicesClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[DeletedServicesClientListBySubscriptionResponse]{ + More: func(page DeletedServicesClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DeletedServicesClientListBySubscriptionResponse) (DeletedServicesClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DeletedServicesClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return DeletedServicesClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *DeletedServicesClient) listBySubscriptionCreateRequest(ctx context.Context, _ *DeletedServicesClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ApiCenter/deletedServices" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *DeletedServicesClient) listBySubscriptionHandleResponse(resp *http.Response) (DeletedServicesClientListBySubscriptionResponse, error) { + result := DeletedServicesClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DeletedServiceListResult); err != nil { + return DeletedServicesClientListBySubscriptionResponse{}, err + } + return result, nil +} diff --git a/test/local/armapicenter/zz_deployments_client.go b/test/local/armapicenter/zz_deployments_client.go new file mode 100644 index 000000000000..cfa7bb1ca78b --- /dev/null +++ b/test/local/armapicenter/zz_deployments_client.go @@ -0,0 +1,414 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armapicenter + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// DeploymentsClient contains the methods for the Deployments group. +// Don't use this type directly, use NewDeploymentsClient() instead. +// +// Generated from API version 2024-06-01-preview +type DeploymentsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDeploymentsClient creates a new instance of DeploymentsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewDeploymentsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DeploymentsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DeploymentsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Creates new or updates existing API deployment. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - apiName - The name of the API. +// - deploymentName - The name of the API deployment. +// - payload - Resource create parameters. +// - options - DeploymentsClientCreateOrUpdateOptions contains the optional parameters for the DeploymentsClient.CreateOrUpdate +// method. +func (client *DeploymentsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, deploymentName string, payload Deployment, options *DeploymentsClientCreateOrUpdateOptions) (DeploymentsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "DeploymentsClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, apiName, deploymentName, payload, options) + if err != nil { + return DeploymentsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DeploymentsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return DeploymentsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *DeploymentsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, deploymentName string, payload Deployment, _ *DeploymentsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/apis/{apiName}/deployments/{deploymentName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if apiName == "" { + return nil, errors.New("parameter apiName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{apiName}", url.PathEscape(apiName)) + if deploymentName == "" { + return nil, errors.New("parameter deploymentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{deploymentName}", url.PathEscape(deploymentName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, payload); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *DeploymentsClient) createOrUpdateHandleResponse(resp *http.Response) (DeploymentsClientCreateOrUpdateResponse, error) { + result := DeploymentsClientCreateOrUpdateResponse{} + if val := resp.Header.Get("ETag"); val != "" { + result.EtagHeader = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.Deployment); err != nil { + return DeploymentsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Deletes API deployment. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - apiName - The name of the API. +// - deploymentName - The name of the API deployment. +// - options - DeploymentsClientDeleteOptions contains the optional parameters for the DeploymentsClient.Delete method. +func (client *DeploymentsClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, deploymentName string, options *DeploymentsClientDeleteOptions) (DeploymentsClientDeleteResponse, error) { + var err error + const operationName = "DeploymentsClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, apiName, deploymentName, options) + if err != nil { + return DeploymentsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DeploymentsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return DeploymentsClientDeleteResponse{}, err + } + return DeploymentsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *DeploymentsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, deploymentName string, _ *DeploymentsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/apis/{apiName}/deployments/{deploymentName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if apiName == "" { + return nil, errors.New("parameter apiName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{apiName}", url.PathEscape(apiName)) + if deploymentName == "" { + return nil, errors.New("parameter deploymentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{deploymentName}", url.PathEscape(deploymentName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Returns details of the API deployment. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - apiName - The name of the API. +// - deploymentName - The name of the API deployment. +// - options - DeploymentsClientGetOptions contains the optional parameters for the DeploymentsClient.Get method. +func (client *DeploymentsClient) Get(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, deploymentName string, options *DeploymentsClientGetOptions) (DeploymentsClientGetResponse, error) { + var err error + const operationName = "DeploymentsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, apiName, deploymentName, options) + if err != nil { + return DeploymentsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DeploymentsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DeploymentsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DeploymentsClient) getCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, deploymentName string, _ *DeploymentsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/apis/{apiName}/deployments/{deploymentName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if apiName == "" { + return nil, errors.New("parameter apiName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{apiName}", url.PathEscape(apiName)) + if deploymentName == "" { + return nil, errors.New("parameter deploymentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{deploymentName}", url.PathEscape(deploymentName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DeploymentsClient) getHandleResponse(resp *http.Response) (DeploymentsClientGetResponse, error) { + result := DeploymentsClientGetResponse{} + if val := resp.Header.Get("ETag"); val != "" { + result.EtagHeader = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.Deployment); err != nil { + return DeploymentsClientGetResponse{}, err + } + return result, nil +} + +// Head - Checks if specified API deployment exists. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - apiName - The name of the API. +// - deploymentName - The name of the API deployment. +// - options - DeploymentsClientHeadOptions contains the optional parameters for the DeploymentsClient.Head method. +func (client *DeploymentsClient) Head(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, deploymentName string, options *DeploymentsClientHeadOptions) (DeploymentsClientHeadResponse, error) { + var err error + const operationName = "DeploymentsClient.Head" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.headCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, apiName, deploymentName, options) + if err != nil { + return DeploymentsClientHeadResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DeploymentsClientHeadResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DeploymentsClientHeadResponse{}, err + } + return DeploymentsClientHeadResponse{Success: httpResp.StatusCode >= 200 && httpResp.StatusCode < 300}, nil +} + +// headCreateRequest creates the Head request. +func (client *DeploymentsClient) headCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, deploymentName string, _ *DeploymentsClientHeadOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/apis/{apiName}/deployments/{deploymentName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if apiName == "" { + return nil, errors.New("parameter apiName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{apiName}", url.PathEscape(apiName)) + if deploymentName == "" { + return nil, errors.New("parameter deploymentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{deploymentName}", url.PathEscape(deploymentName)) + req, err := runtime.NewRequest(ctx, http.MethodHead, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// NewListPager - Returns a collection of API deployments. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - apiName - The name of the API. +// - options - DeploymentsClientListOptions contains the optional parameters for the DeploymentsClient.NewListPager method. +func (client *DeploymentsClient) NewListPager(resourceGroupName string, serviceName string, workspaceName string, apiName string, options *DeploymentsClientListOptions) *runtime.Pager[DeploymentsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[DeploymentsClientListResponse]{ + More: func(page DeploymentsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DeploymentsClientListResponse) (DeploymentsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DeploymentsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, apiName, options) + }, nil) + if err != nil { + return DeploymentsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *DeploymentsClient) listCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, apiName string, options *DeploymentsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/apis/{apiName}/deployments" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if apiName == "" { + return nil, errors.New("parameter apiName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{apiName}", url.PathEscape(apiName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *DeploymentsClient) listHandleResponse(resp *http.Response) (DeploymentsClientListResponse, error) { + result := DeploymentsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DeploymentListResult); err != nil { + return DeploymentsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armapicenter/zz_environments_client.go b/test/local/armapicenter/zz_environments_client.go new file mode 100644 index 000000000000..25be5a20b8a5 --- /dev/null +++ b/test/local/armapicenter/zz_environments_client.go @@ -0,0 +1,389 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armapicenter + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// EnvironmentsClient contains the methods for the Environments group. +// Don't use this type directly, use NewEnvironmentsClient() instead. +// +// Generated from API version 2024-06-01-preview +type EnvironmentsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewEnvironmentsClient creates a new instance of EnvironmentsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewEnvironmentsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*EnvironmentsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &EnvironmentsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Creates new or updates existing environment. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - environmentName - The name of the environment. +// - payload - Resource create parameters. +// - options - EnvironmentsClientCreateOrUpdateOptions contains the optional parameters for the EnvironmentsClient.CreateOrUpdate +// method. +func (client *EnvironmentsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, environmentName string, payload Environment, options *EnvironmentsClientCreateOrUpdateOptions) (EnvironmentsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "EnvironmentsClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, environmentName, payload, options) + if err != nil { + return EnvironmentsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EnvironmentsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return EnvironmentsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *EnvironmentsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, environmentName string, payload Environment, _ *EnvironmentsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/environments/{environmentName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if environmentName == "" { + return nil, errors.New("parameter environmentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{environmentName}", url.PathEscape(environmentName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, payload); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *EnvironmentsClient) createOrUpdateHandleResponse(resp *http.Response) (EnvironmentsClientCreateOrUpdateResponse, error) { + result := EnvironmentsClientCreateOrUpdateResponse{} + if val := resp.Header.Get("ETag"); val != "" { + result.EtagHeader = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.Environment); err != nil { + return EnvironmentsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Deletes the environment. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - environmentName - The name of the environment. +// - options - EnvironmentsClientDeleteOptions contains the optional parameters for the EnvironmentsClient.Delete method. +func (client *EnvironmentsClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, environmentName string, options *EnvironmentsClientDeleteOptions) (EnvironmentsClientDeleteResponse, error) { + var err error + const operationName = "EnvironmentsClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, environmentName, options) + if err != nil { + return EnvironmentsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EnvironmentsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return EnvironmentsClientDeleteResponse{}, err + } + return EnvironmentsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *EnvironmentsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, environmentName string, _ *EnvironmentsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/environments/{environmentName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if environmentName == "" { + return nil, errors.New("parameter environmentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{environmentName}", url.PathEscape(environmentName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Returns details of the environment. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - environmentName - The name of the environment. +// - options - EnvironmentsClientGetOptions contains the optional parameters for the EnvironmentsClient.Get method. +func (client *EnvironmentsClient) Get(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, environmentName string, options *EnvironmentsClientGetOptions) (EnvironmentsClientGetResponse, error) { + var err error + const operationName = "EnvironmentsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, environmentName, options) + if err != nil { + return EnvironmentsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EnvironmentsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return EnvironmentsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *EnvironmentsClient) getCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, environmentName string, _ *EnvironmentsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/environments/{environmentName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if environmentName == "" { + return nil, errors.New("parameter environmentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{environmentName}", url.PathEscape(environmentName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *EnvironmentsClient) getHandleResponse(resp *http.Response) (EnvironmentsClientGetResponse, error) { + result := EnvironmentsClientGetResponse{} + if val := resp.Header.Get("ETag"); val != "" { + result.EtagHeader = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.Environment); err != nil { + return EnvironmentsClientGetResponse{}, err + } + return result, nil +} + +// Head - Checks if specified environment exists. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - environmentName - The name of the environment. +// - options - EnvironmentsClientHeadOptions contains the optional parameters for the EnvironmentsClient.Head method. +func (client *EnvironmentsClient) Head(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, environmentName string, options *EnvironmentsClientHeadOptions) (EnvironmentsClientHeadResponse, error) { + var err error + const operationName = "EnvironmentsClient.Head" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.headCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, environmentName, options) + if err != nil { + return EnvironmentsClientHeadResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EnvironmentsClientHeadResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return EnvironmentsClientHeadResponse{}, err + } + return EnvironmentsClientHeadResponse{Success: httpResp.StatusCode >= 200 && httpResp.StatusCode < 300}, nil +} + +// headCreateRequest creates the Head request. +func (client *EnvironmentsClient) headCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, environmentName string, _ *EnvironmentsClientHeadOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/environments/{environmentName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if environmentName == "" { + return nil, errors.New("parameter environmentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{environmentName}", url.PathEscape(environmentName)) + req, err := runtime.NewRequest(ctx, http.MethodHead, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// NewListPager - Returns a collection of environments. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - options - EnvironmentsClientListOptions contains the optional parameters for the EnvironmentsClient.NewListPager method. +func (client *EnvironmentsClient) NewListPager(resourceGroupName string, serviceName string, workspaceName string, options *EnvironmentsClientListOptions) *runtime.Pager[EnvironmentsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[EnvironmentsClientListResponse]{ + More: func(page EnvironmentsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *EnvironmentsClientListResponse) (EnvironmentsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "EnvironmentsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, options) + }, nil) + if err != nil { + return EnvironmentsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *EnvironmentsClient) listCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, options *EnvironmentsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}/environments" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *EnvironmentsClient) listHandleResponse(resp *http.Response) (EnvironmentsClientListResponse, error) { + result := EnvironmentsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.EnvironmentListResult); err != nil { + return EnvironmentsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armapicenter/zz_metadataschemas_client.go b/test/local/armapicenter/zz_metadataschemas_client.go new file mode 100644 index 000000000000..65f3bf6e2aa9 --- /dev/null +++ b/test/local/armapicenter/zz_metadataschemas_client.go @@ -0,0 +1,365 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armapicenter + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// MetadataSchemasClient contains the methods for the MetadataSchemas group. +// Don't use this type directly, use NewMetadataSchemasClient() instead. +// +// Generated from API version 2024-06-01-preview +type MetadataSchemasClient struct { + internal *arm.Client + subscriptionID string +} + +// NewMetadataSchemasClient creates a new instance of MetadataSchemasClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewMetadataSchemasClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*MetadataSchemasClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &MetadataSchemasClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Creates new or updates existing metadata schema. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - metadataSchemaName - The name of the metadata schema. +// - payload - Resource create parameters. +// - options - MetadataSchemasClientCreateOrUpdateOptions contains the optional parameters for the MetadataSchemasClient.CreateOrUpdate +// method. +func (client *MetadataSchemasClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, metadataSchemaName string, payload MetadataSchema, options *MetadataSchemasClientCreateOrUpdateOptions) (MetadataSchemasClientCreateOrUpdateResponse, error) { + var err error + const operationName = "MetadataSchemasClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, serviceName, metadataSchemaName, payload, options) + if err != nil { + return MetadataSchemasClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MetadataSchemasClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return MetadataSchemasClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *MetadataSchemasClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, metadataSchemaName string, payload MetadataSchema, _ *MetadataSchemasClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/metadataSchemas/{metadataSchemaName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if metadataSchemaName == "" { + return nil, errors.New("parameter metadataSchemaName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{metadataSchemaName}", url.PathEscape(metadataSchemaName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, payload); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *MetadataSchemasClient) createOrUpdateHandleResponse(resp *http.Response) (MetadataSchemasClientCreateOrUpdateResponse, error) { + result := MetadataSchemasClientCreateOrUpdateResponse{} + if val := resp.Header.Get("ETag"); val != "" { + result.EtagHeader = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.MetadataSchema); err != nil { + return MetadataSchemasClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Deletes specified metadata schema. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - metadataSchemaName - The name of the metadata schema. +// - options - MetadataSchemasClientDeleteOptions contains the optional parameters for the MetadataSchemasClient.Delete method. +func (client *MetadataSchemasClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, metadataSchemaName string, options *MetadataSchemasClientDeleteOptions) (MetadataSchemasClientDeleteResponse, error) { + var err error + const operationName = "MetadataSchemasClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, serviceName, metadataSchemaName, options) + if err != nil { + return MetadataSchemasClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MetadataSchemasClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return MetadataSchemasClientDeleteResponse{}, err + } + return MetadataSchemasClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *MetadataSchemasClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, metadataSchemaName string, _ *MetadataSchemasClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/metadataSchemas/{metadataSchemaName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if metadataSchemaName == "" { + return nil, errors.New("parameter metadataSchemaName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{metadataSchemaName}", url.PathEscape(metadataSchemaName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Returns details of the metadata schema. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - metadataSchemaName - The name of the metadata schema. +// - options - MetadataSchemasClientGetOptions contains the optional parameters for the MetadataSchemasClient.Get method. +func (client *MetadataSchemasClient) Get(ctx context.Context, resourceGroupName string, serviceName string, metadataSchemaName string, options *MetadataSchemasClientGetOptions) (MetadataSchemasClientGetResponse, error) { + var err error + const operationName = "MetadataSchemasClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, serviceName, metadataSchemaName, options) + if err != nil { + return MetadataSchemasClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MetadataSchemasClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return MetadataSchemasClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *MetadataSchemasClient) getCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, metadataSchemaName string, _ *MetadataSchemasClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/metadataSchemas/{metadataSchemaName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if metadataSchemaName == "" { + return nil, errors.New("parameter metadataSchemaName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{metadataSchemaName}", url.PathEscape(metadataSchemaName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *MetadataSchemasClient) getHandleResponse(resp *http.Response) (MetadataSchemasClientGetResponse, error) { + result := MetadataSchemasClientGetResponse{} + if val := resp.Header.Get("ETag"); val != "" { + result.EtagHeader = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.MetadataSchema); err != nil { + return MetadataSchemasClientGetResponse{}, err + } + return result, nil +} + +// Head - Checks if specified metadata schema exists. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - metadataSchemaName - The name of the metadata schema. +// - options - MetadataSchemasClientHeadOptions contains the optional parameters for the MetadataSchemasClient.Head method. +func (client *MetadataSchemasClient) Head(ctx context.Context, resourceGroupName string, serviceName string, metadataSchemaName string, options *MetadataSchemasClientHeadOptions) (MetadataSchemasClientHeadResponse, error) { + var err error + const operationName = "MetadataSchemasClient.Head" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.headCreateRequest(ctx, resourceGroupName, serviceName, metadataSchemaName, options) + if err != nil { + return MetadataSchemasClientHeadResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MetadataSchemasClientHeadResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return MetadataSchemasClientHeadResponse{}, err + } + return MetadataSchemasClientHeadResponse{Success: httpResp.StatusCode >= 200 && httpResp.StatusCode < 300}, nil +} + +// headCreateRequest creates the Head request. +func (client *MetadataSchemasClient) headCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, metadataSchemaName string, _ *MetadataSchemasClientHeadOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/metadataSchemas/{metadataSchemaName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if metadataSchemaName == "" { + return nil, errors.New("parameter metadataSchemaName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{metadataSchemaName}", url.PathEscape(metadataSchemaName)) + req, err := runtime.NewRequest(ctx, http.MethodHead, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// NewListPager - Returns a collection of metadata schemas. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - options - MetadataSchemasClientListOptions contains the optional parameters for the MetadataSchemasClient.NewListPager +// method. +func (client *MetadataSchemasClient) NewListPager(resourceGroupName string, serviceName string, options *MetadataSchemasClientListOptions) *runtime.Pager[MetadataSchemasClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[MetadataSchemasClientListResponse]{ + More: func(page MetadataSchemasClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *MetadataSchemasClientListResponse) (MetadataSchemasClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "MetadataSchemasClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, serviceName, options) + }, nil) + if err != nil { + return MetadataSchemasClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *MetadataSchemasClient) listCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, options *MetadataSchemasClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/metadataSchemas" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *MetadataSchemasClient) listHandleResponse(resp *http.Response) (MetadataSchemasClientListResponse, error) { + result := MetadataSchemasClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.MetadataSchemaListResult); err != nil { + return MetadataSchemasClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armapicenter/zz_models.go b/test/local/armapicenter/zz_models.go new file mode 100644 index 000000000000..db9521ffab2b --- /dev/null +++ b/test/local/armapicenter/zz_models.go @@ -0,0 +1,717 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armapicenter + +import "time" + +// API entity. +type API struct { + // The resource-specific properties for this resource. + Properties *APIProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// APIDefinition - API definition entity. +type APIDefinition struct { + // The resource-specific properties for this resource. + Properties *APIDefinitionProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// APIDefinitionListResult - The response of a ApiDefinition list operation. +type APIDefinitionListResult struct { + // READ-ONLY; The ApiDefinition items on this page + Value []*APIDefinition + + // READ-ONLY; The link to the next page of items + NextLink *string +} + +// APIDefinitionProperties - API definition properties entity. +type APIDefinitionProperties struct { + // REQUIRED; API definition title. + Title *string + + // API definition description. + Description *string + + // READ-ONLY; API specification details. + Specification *APIDefinitionPropertiesSpecification +} + +// APIDefinitionPropertiesSpecification - API specification details. +type APIDefinitionPropertiesSpecification struct { + // Specification name. + Name *string + + // Specification version. + Version *string +} + +// APIListResult - The response of a Api list operation. +type APIListResult struct { + // READ-ONLY; The Api items on this page + Value []*API + + // READ-ONLY; The link to the next page of items + NextLink *string +} + +// APIProperties - API properties. +type APIProperties struct { + // REQUIRED; Kind of API. For example, REST or GraphQL. + Kind *APIKind + + // REQUIRED; API title. + Title *string + + // The set of contacts + Contacts []*Contact + + // The custom metadata defined for API catalog entities. + CustomProperties *CustomProperties + + // Description of the API. + Description *string + + // The set of external documentation + ExternalDocumentation []*ExternalDocumentation + + // The license information for the API. + License *License + + // Short description of the API. + Summary *string + + // Terms of service for the API. + TermsOfService *TermsOfService + + // READ-ONLY; Current lifecycle stage of the API. + LifecycleStage *LifecycleStage +} + +// APISource - API source entity. +type APISource struct { + // The resource-specific properties for this resource. + Properties *APISourceProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// APISourceListResult - The response of a ApiSource list operation. +type APISourceListResult struct { + // READ-ONLY; The ApiSource items on this page + Value []*APISource + + // READ-ONLY; The link to the next page of items + NextLink *string +} + +// APISourceProperties - API source properties. +type APISourceProperties struct { + // API source configuration for Azure API Management. + AzureAPIManagementSource *AzureAPIManagementSource + + // Indicates if the specification should be imported along with metadata. + ImportSpecification *ImportSpecificationOptions + + // The target environment resource ID. + TargetEnvironmentID *string + + // The target lifecycle stage. + TargetLifecycleStage *LifecycleStage + + // READ-ONLY; The state of the API source link + LinkState *LinkState +} + +// APISpecExportResult - The API specification export result. +type APISpecExportResult struct { + // The format of exported result + Format *APISpecExportResultFormat + + // The result of the export operation. + Value *string +} + +// APISpecImportRequest - The API specification source entity properties. +type APISpecImportRequest struct { + // Format of the API specification source. + Format *APISpecImportSourceFormat + + // API specification details. + Specification *APISpecImportRequestSpecification + + // Value of the API specification source. + Value *string +} + +// APISpecImportRequestSpecification - API specification details. +type APISpecImportRequestSpecification struct { + // Specification name. + Name *string + + // Specification version. + Version *string +} + +// APIVersion - API version entity. +type APIVersion struct { + // The resource-specific properties for this resource. + Properties *APIVersionProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// APIVersionListResult - The response of a ApiVersion list operation. +type APIVersionListResult struct { + // READ-ONLY; The ApiVersion items on this page + Value []*APIVersion + + // READ-ONLY; The link to the next page of items + NextLink *string +} + +// APIVersionProperties - API version properties entity. +type APIVersionProperties struct { + // REQUIRED; Current lifecycle stage of the API. + LifecycleStage *LifecycleStage + + // REQUIRED; API version title. + Title *string +} + +// AzureAPIManagementSource - API source configuration for Azure API Management. +type AzureAPIManagementSource struct { + // REQUIRED; API Management service resource ID. + ResourceID *string + + // The resource ID of the managed identity that has access to the API Management instance. + MsiResourceID *string +} + +// Contact information +type Contact struct { + // Email address of the contact. + Email *string + + // Name of the contact. + Name *string + + // URL for the contact. + URL *string +} + +// CustomProperties - Custom Properties +// +// The custom metadata defined for API catalog entities. +type CustomProperties struct { +} + +// DeletedService - Soft-deleted service entity. +type DeletedService struct { + // The resource-specific properties for this resource. + Properties *DeletedServiceProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// DeletedServiceListResult - The response of a DeletedService list operation. +type DeletedServiceListResult struct { + // READ-ONLY; The DeletedService items on this page + Value []*DeletedService + + // READ-ONLY; The link to the next page of items + NextLink *string +} + +// DeletedServiceProperties - Deleted service properties. +type DeletedServiceProperties struct { + // UTC date and time when the service will be automatically purged. The date conforms to the following format: yyyy-MM-ddTHH:mm:ssZ + // as specified by the ISO 8601 standard. + ScheduledPurgeDate *time.Time + + // UTC date and time when the service was soft-deleted. The date conforms to the following format: yyyy-MM-ddTHH:mm:ssZ as + // specified by the ISO 8601 standard. + SoftDeletionDate *time.Time +} + +// Deployment - API deployment entity. +type Deployment struct { + // The resource-specific properties for this resource. + Properties *DeploymentProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// DeploymentListResult - The response of a Deployment list operation. +type DeploymentListResult struct { + // READ-ONLY; The Deployment items on this page + Value []*Deployment + + // READ-ONLY; The link to the next page of items + NextLink *string +} + +// DeploymentProperties - API deployment entity properties. +type DeploymentProperties struct { + // The custom metadata defined for API catalog entities. + CustomProperties *CustomProperties + + // API center-scoped definition resource ID. + DefinitionID *string + + // Description of the deployment. + Description *string + + // API center-scoped environment resource ID. + EnvironmentID *string + + // The deployment server + Server *DeploymentServer + + // State of API deployment. + State *DeploymentState + + // API deployment title + Title *string +} + +// DeploymentServer - Server +type DeploymentServer struct { + // Base runtime URLs for this deployment. + RuntimeURI []*string +} + +// Environment entity. +type Environment struct { + // The resource-specific properties for this resource. + Properties *EnvironmentProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// EnvironmentListResult - The response of a Environment list operation. +type EnvironmentListResult struct { + // READ-ONLY; The Environment items on this page + Value []*Environment + + // READ-ONLY; The link to the next page of items + NextLink *string +} + +// EnvironmentProperties - Environment properties entity. +type EnvironmentProperties struct { + // REQUIRED; Environment kind. + Kind *EnvironmentKind + + // REQUIRED; Environment title. + Title *string + + // The custom metadata defined for API catalog entities. + CustomProperties *CustomProperties + + // The environment description. + Description *string + + // Environment onboarding information + Onboarding *Onboarding + + // Server information of the environment. + Server *EnvironmentServer +} + +// EnvironmentServer - Server information of the environment. +type EnvironmentServer struct { + // The location of the management portal + ManagementPortalURI []*string + + // Type of the server that represents the environment. + Type *EnvironmentServerType +} + +// ExternalDocumentation - Additional, external documentation for the API. +type ExternalDocumentation struct { + // REQUIRED; URL pointing to the documentation. + URL *string + + // Description of the documentation. + Description *string + + // Title of the documentation. + Title *string +} + +// License - The license information for the API. +type License struct { + // SPDX license information for the API. The identifier field is mutually + // exclusive of the URL field. + Identifier *string + + // Name of the license. + Name *string + + // URL pointing to the license details. The URL field is mutually exclusive of the + // identifier field. + URL *string +} + +// LinkState - The link state. +type LinkState struct { + // REQUIRED; The timestamp of the last update of the link state. + LastUpdatedOn *time.Time + + // The state message. + Message *string + + // The state of the link. + State *APISourceLinkState +} + +// ManagedServiceIdentity - Managed service identity (system assigned and/or user assigned identities) +type ManagedServiceIdentity struct { + // REQUIRED; The type of managed identity assigned to this resource. + Type *ManagedServiceIdentityType + + // The identities assigned to this resource by the user. + UserAssignedIdentities map[string]*UserAssignedIdentity + + // READ-ONLY; The service principal ID of the system assigned identity. This property will only be provided for a system assigned + // identity. + PrincipalID *string + + // READ-ONLY; The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + TenantID *string +} + +// MetadataAssignment - Assignment metadata +type MetadataAssignment struct { + // Deprecated assignment + Deprecated *bool + + // The entities this metadata schema component gets applied to. + Entity *MetadataAssignmentEntity + + // Required assignment + Required *bool +} + +// MetadataSchema - Metadata schema entity. Used to define metadata for the entities in API catalog. +type MetadataSchema struct { + // The resource-specific properties for this resource. + Properties *MetadataSchemaProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// MetadataSchemaExportRequest - The metadata schema export request. +type MetadataSchemaExportRequest struct { + // An entity the metadata schema is requested for. + AssignedTo *MetadataAssignmentEntity +} + +// MetadataSchemaExportResult - The metadata schema export result. +type MetadataSchemaExportResult struct { + // The export format for the schema + Format *MetadataSchemaExportFormat + + // The result of the export operation. + Value *string +} + +// MetadataSchemaListResult - The response of a MetadataSchema list operation. +type MetadataSchemaListResult struct { + // READ-ONLY; The MetadataSchema items on this page + Value []*MetadataSchema + + // READ-ONLY; The link to the next page of items + NextLink *string +} + +// MetadataSchemaProperties - Metadata schema properties. +type MetadataSchemaProperties struct { + // REQUIRED; The schema defining the type. + Schema *string + + // The assignees + AssignedTo []*MetadataAssignment +} + +// Onboarding information +type Onboarding struct { + // The location of the development portal + DeveloperPortalURI []*string + + // Onboarding guide. + Instructions *string +} + +// Operation - REST API Operation +// +// Details of a REST API operation, returned from the Resource Provider Operations API +type Operation struct { + // Localized display information for this particular operation. + Display *OperationDisplay + + // READ-ONLY; Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + ActionType *ActionType + + // READ-ONLY; Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure + // Resource Manager/control-plane operations. + IsDataAction *bool + + // READ-ONLY; The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + // "Microsoft.Compute/virtualMachines/capture/action" + Name *string + + // READ-ONLY; The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default + // value is "user,system" + Origin *Origin +} + +// OperationDisplay - Localized display information for an operation. +type OperationDisplay struct { + // READ-ONLY; The short, localized friendly description of the operation; suitable for tool tips and detailed views. + Description *string + + // READ-ONLY; The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual + // Machine", "Restart Virtual Machine". + Operation *string + + // READ-ONLY; The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft + // Compute". + Provider *string + + // READ-ONLY; The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job + // Schedule Collections". + Resource *string +} + +// OperationListResult - A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to +// get the next set of results. +type OperationListResult struct { + // READ-ONLY; The Operation items on this page + Value []*Operation + + // READ-ONLY; The link to the next page of items + NextLink *string +} + +// Service - The service entity. +type Service struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The managed service identities assigned to this resource. + Identity *ManagedServiceIdentity + + // The resource-specific properties for this resource. + Properties *ServiceProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ServiceListResult - The response of a Service list operation. +type ServiceListResult struct { + // READ-ONLY; The Service items on this page + Value []*Service + + // READ-ONLY; The link to the next page of items + NextLink *string +} + +// ServiceProperties - The properties of the service. +type ServiceProperties struct { + // Flag used to restore soft-deleted API Center service. If specified and set to 'true' all other properties will be ignored. + Restore *bool + + // READ-ONLY; Provisioning state of the service. + ProvisioningState *ProvisioningState +} + +// ServiceUpdate - The type used for update operations of the Service. +type ServiceUpdate struct { + // The managed service identities assigned to this resource. + Identity *ManagedServiceIdentity + + // The resource-specific properties for this resource. + Properties *ServiceUpdateProperties + + // Resource tags. + Tags map[string]*string +} + +// ServiceUpdateProperties - The updatable properties of the Service. +type ServiceUpdateProperties struct { + // Flag used to restore soft-deleted API Center service. If specified and set to 'true' all other properties will be ignored. + Restore *bool +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time + + // The identity that created the resource. + CreatedBy *string + + // The type of identity that created the resource. + CreatedByType *CreatedByType + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time + + // The identity that last modified the resource. + LastModifiedBy *string + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType +} + +// TermsOfService - Terms of service for the API. +type TermsOfService struct { + // REQUIRED; URL pointing to the terms of service. + URL *string +} + +// UserAssignedIdentity - User assigned identity properties +type UserAssignedIdentity struct { + // READ-ONLY; The client ID of the assigned identity. + ClientID *string + + // READ-ONLY; The principal ID of the assigned identity. + PrincipalID *string +} + +// Workspace entity. +type Workspace struct { + // The resource-specific properties for this resource. + Properties *WorkspaceProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// WorkspaceListResult - The response of a Workspace list operation. +type WorkspaceListResult struct { + // READ-ONLY; The Workspace items on this page + Value []*Workspace + + // READ-ONLY; The link to the next page of items + NextLink *string +} + +// WorkspaceProperties - Workspace properties. +type WorkspaceProperties struct { + // REQUIRED; Workspace title. + Title *string + + // Workspace description. + Description *string +} diff --git a/test/local/armapicenter/zz_models_serde.go b/test/local/armapicenter/zz_models_serde.go new file mode 100644 index 000000000000..33ffe5fd2208 --- /dev/null +++ b/test/local/armapicenter/zz_models_serde.go @@ -0,0 +1,2008 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armapicenter + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type API. +func (a API) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type API. +func (a *API) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &a.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type APIDefinition. +func (a APIDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APIDefinition. +func (a *APIDefinition) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &a.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type APIDefinitionListResult. +func (a APIDefinitionListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APIDefinitionListResult. +func (a *APIDefinitionListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &a.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type APIDefinitionProperties. +func (a APIDefinitionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", a.Description) + populate(objectMap, "specification", a.Specification) + populate(objectMap, "title", a.Title) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APIDefinitionProperties. +func (a *APIDefinitionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &a.Description) + delete(rawMsg, key) + case "specification": + err = unpopulate(val, "Specification", &a.Specification) + delete(rawMsg, key) + case "title": + err = unpopulate(val, "Title", &a.Title) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type APIDefinitionPropertiesSpecification. +func (a APIDefinitionPropertiesSpecification) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", a.Name) + populate(objectMap, "version", a.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APIDefinitionPropertiesSpecification. +func (a *APIDefinitionPropertiesSpecification) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &a.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type APIListResult. +func (a APIListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APIListResult. +func (a *APIListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &a.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type APIProperties. +func (a APIProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "contacts", a.Contacts) + populate(objectMap, "customProperties", a.CustomProperties) + populate(objectMap, "description", a.Description) + populate(objectMap, "externalDocumentation", a.ExternalDocumentation) + populate(objectMap, "kind", a.Kind) + populate(objectMap, "license", a.License) + populate(objectMap, "lifecycleStage", a.LifecycleStage) + populate(objectMap, "summary", a.Summary) + populate(objectMap, "termsOfService", a.TermsOfService) + populate(objectMap, "title", a.Title) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APIProperties. +func (a *APIProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "contacts": + err = unpopulate(val, "Contacts", &a.Contacts) + delete(rawMsg, key) + case "customProperties": + err = unpopulate(val, "CustomProperties", &a.CustomProperties) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &a.Description) + delete(rawMsg, key) + case "externalDocumentation": + err = unpopulate(val, "ExternalDocumentation", &a.ExternalDocumentation) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &a.Kind) + delete(rawMsg, key) + case "license": + err = unpopulate(val, "License", &a.License) + delete(rawMsg, key) + case "lifecycleStage": + err = unpopulate(val, "LifecycleStage", &a.LifecycleStage) + delete(rawMsg, key) + case "summary": + err = unpopulate(val, "Summary", &a.Summary) + delete(rawMsg, key) + case "termsOfService": + err = unpopulate(val, "TermsOfService", &a.TermsOfService) + delete(rawMsg, key) + case "title": + err = unpopulate(val, "Title", &a.Title) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type APISource. +func (a APISource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APISource. +func (a *APISource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &a.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type APISourceListResult. +func (a APISourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APISourceListResult. +func (a *APISourceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &a.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type APISourceProperties. +func (a APISourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "azureApiManagementSource", a.AzureAPIManagementSource) + populate(objectMap, "importSpecification", a.ImportSpecification) + populate(objectMap, "linkState", a.LinkState) + populate(objectMap, "targetEnvironmentId", a.TargetEnvironmentID) + populate(objectMap, "targetLifecycleStage", a.TargetLifecycleStage) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APISourceProperties. +func (a *APISourceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "azureApiManagementSource": + err = unpopulate(val, "AzureAPIManagementSource", &a.AzureAPIManagementSource) + delete(rawMsg, key) + case "importSpecification": + err = unpopulate(val, "ImportSpecification", &a.ImportSpecification) + delete(rawMsg, key) + case "linkState": + err = unpopulate(val, "LinkState", &a.LinkState) + delete(rawMsg, key) + case "targetEnvironmentId": + err = unpopulate(val, "TargetEnvironmentID", &a.TargetEnvironmentID) + delete(rawMsg, key) + case "targetLifecycleStage": + err = unpopulate(val, "TargetLifecycleStage", &a.TargetLifecycleStage) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type APISpecExportResult. +func (a APISpecExportResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "format", a.Format) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APISpecExportResult. +func (a *APISpecExportResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "format": + err = unpopulate(val, "Format", &a.Format) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type APISpecImportRequest. +func (a APISpecImportRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "format", a.Format) + populate(objectMap, "specification", a.Specification) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APISpecImportRequest. +func (a *APISpecImportRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "format": + err = unpopulate(val, "Format", &a.Format) + delete(rawMsg, key) + case "specification": + err = unpopulate(val, "Specification", &a.Specification) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type APISpecImportRequestSpecification. +func (a APISpecImportRequestSpecification) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", a.Name) + populate(objectMap, "version", a.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APISpecImportRequestSpecification. +func (a *APISpecImportRequestSpecification) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &a.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type APIVersion. +func (a APIVersion) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APIVersion. +func (a *APIVersion) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &a.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type APIVersionListResult. +func (a APIVersionListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APIVersionListResult. +func (a *APIVersionListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &a.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type APIVersionProperties. +func (a APIVersionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "lifecycleStage", a.LifecycleStage) + populate(objectMap, "title", a.Title) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APIVersionProperties. +func (a *APIVersionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "lifecycleStage": + err = unpopulate(val, "LifecycleStage", &a.LifecycleStage) + delete(rawMsg, key) + case "title": + err = unpopulate(val, "Title", &a.Title) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AzureAPIManagementSource. +func (a AzureAPIManagementSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "msiResourceId", a.MsiResourceID) + populate(objectMap, "resourceId", a.ResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureAPIManagementSource. +func (a *AzureAPIManagementSource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "msiResourceId": + err = unpopulate(val, "MsiResourceID", &a.MsiResourceID) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &a.ResourceID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Contact. +func (c Contact) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "email", c.Email) + populate(objectMap, "name", c.Name) + populate(objectMap, "url", c.URL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Contact. +func (c *Contact) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "email": + err = unpopulate(val, "Email", &c.Email) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "url": + err = unpopulate(val, "URL", &c.URL) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeletedService. +func (d DeletedService) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", d.ID) + populate(objectMap, "name", d.Name) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "systemData", d.SystemData) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeletedService. +func (d *DeletedService) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &d.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &d.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &d.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeletedServiceListResult. +func (d DeletedServiceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", d.NextLink) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeletedServiceListResult. +func (d *DeletedServiceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &d.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &d.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeletedServiceProperties. +func (d DeletedServiceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "scheduledPurgeDate", d.ScheduledPurgeDate) + populateTime[datetime.RFC3339](objectMap, "softDeletionDate", d.SoftDeletionDate) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeletedServiceProperties. +func (d *DeletedServiceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "scheduledPurgeDate": + err = unpopulateTime[datetime.RFC3339](val, "ScheduledPurgeDate", &d.ScheduledPurgeDate) + delete(rawMsg, key) + case "softDeletionDate": + err = unpopulateTime[datetime.RFC3339](val, "SoftDeletionDate", &d.SoftDeletionDate) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Deployment. +func (d Deployment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", d.ID) + populate(objectMap, "name", d.Name) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "systemData", d.SystemData) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Deployment. +func (d *Deployment) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &d.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &d.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &d.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeploymentListResult. +func (d DeploymentListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", d.NextLink) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeploymentListResult. +func (d *DeploymentListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &d.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &d.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeploymentProperties. +func (d DeploymentProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "customProperties", d.CustomProperties) + populate(objectMap, "definitionId", d.DefinitionID) + populate(objectMap, "description", d.Description) + populate(objectMap, "environmentId", d.EnvironmentID) + populate(objectMap, "server", d.Server) + populate(objectMap, "state", d.State) + populate(objectMap, "title", d.Title) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeploymentProperties. +func (d *DeploymentProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "customProperties": + err = unpopulate(val, "CustomProperties", &d.CustomProperties) + delete(rawMsg, key) + case "definitionId": + err = unpopulate(val, "DefinitionID", &d.DefinitionID) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &d.Description) + delete(rawMsg, key) + case "environmentId": + err = unpopulate(val, "EnvironmentID", &d.EnvironmentID) + delete(rawMsg, key) + case "server": + err = unpopulate(val, "Server", &d.Server) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &d.State) + delete(rawMsg, key) + case "title": + err = unpopulate(val, "Title", &d.Title) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeploymentServer. +func (d DeploymentServer) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "runtimeUri", d.RuntimeURI) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeploymentServer. +func (d *DeploymentServer) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "runtimeUri": + err = unpopulate(val, "RuntimeURI", &d.RuntimeURI) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Environment. +func (e Environment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", e.ID) + populate(objectMap, "name", e.Name) + populate(objectMap, "properties", e.Properties) + populate(objectMap, "systemData", e.SystemData) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Environment. +func (e *Environment) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &e.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &e.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &e.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &e.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &e.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EnvironmentListResult. +func (e EnvironmentListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", e.NextLink) + populate(objectMap, "value", e.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EnvironmentListResult. +func (e *EnvironmentListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &e.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &e.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EnvironmentProperties. +func (e EnvironmentProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "customProperties", e.CustomProperties) + populate(objectMap, "description", e.Description) + populate(objectMap, "kind", e.Kind) + populate(objectMap, "onboarding", e.Onboarding) + populate(objectMap, "server", e.Server) + populate(objectMap, "title", e.Title) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EnvironmentProperties. +func (e *EnvironmentProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "customProperties": + err = unpopulate(val, "CustomProperties", &e.CustomProperties) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &e.Description) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &e.Kind) + delete(rawMsg, key) + case "onboarding": + err = unpopulate(val, "Onboarding", &e.Onboarding) + delete(rawMsg, key) + case "server": + err = unpopulate(val, "Server", &e.Server) + delete(rawMsg, key) + case "title": + err = unpopulate(val, "Title", &e.Title) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EnvironmentServer. +func (e EnvironmentServer) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "managementPortalUri", e.ManagementPortalURI) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EnvironmentServer. +func (e *EnvironmentServer) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "managementPortalUri": + err = unpopulate(val, "ManagementPortalURI", &e.ManagementPortalURI) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &e.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExternalDocumentation. +func (e ExternalDocumentation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", e.Description) + populate(objectMap, "title", e.Title) + populate(objectMap, "url", e.URL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExternalDocumentation. +func (e *ExternalDocumentation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &e.Description) + delete(rawMsg, key) + case "title": + err = unpopulate(val, "Title", &e.Title) + delete(rawMsg, key) + case "url": + err = unpopulate(val, "URL", &e.URL) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type License. +func (l License) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identifier", l.Identifier) + populate(objectMap, "name", l.Name) + populate(objectMap, "url", l.URL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type License. +func (l *License) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "identifier": + err = unpopulate(val, "Identifier", &l.Identifier) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &l.Name) + delete(rawMsg, key) + case "url": + err = unpopulate(val, "URL", &l.URL) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LinkState. +func (l LinkState) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "lastUpdatedOn", l.LastUpdatedOn) + populate(objectMap, "message", l.Message) + populate(objectMap, "state", l.State) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LinkState. +func (l *LinkState) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "lastUpdatedOn": + err = unpopulateTime[datetime.RFC3339](val, "LastUpdatedOn", &l.LastUpdatedOn) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &l.Message) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &l.State) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedServiceIdentity. +func (m ManagedServiceIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "principalId", m.PrincipalID) + populate(objectMap, "tenantId", m.TenantID) + populate(objectMap, "type", m.Type) + populate(objectMap, "userAssignedIdentities", m.UserAssignedIdentities) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedServiceIdentity. +func (m *ManagedServiceIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "principalId": + err = unpopulate(val, "PrincipalID", &m.PrincipalID) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &m.TenantID) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + case "userAssignedIdentities": + err = unpopulate(val, "UserAssignedIdentities", &m.UserAssignedIdentities) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MetadataAssignment. +func (m MetadataAssignment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "deprecated", m.Deprecated) + populate(objectMap, "entity", m.Entity) + populate(objectMap, "required", m.Required) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MetadataAssignment. +func (m *MetadataAssignment) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "deprecated": + err = unpopulate(val, "Deprecated", &m.Deprecated) + delete(rawMsg, key) + case "entity": + err = unpopulate(val, "Entity", &m.Entity) + delete(rawMsg, key) + case "required": + err = unpopulate(val, "Required", &m.Required) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MetadataSchema. +func (m MetadataSchema) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", m.ID) + populate(objectMap, "name", m.Name) + populate(objectMap, "properties", m.Properties) + populate(objectMap, "systemData", m.SystemData) + populate(objectMap, "type", m.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MetadataSchema. +func (m *MetadataSchema) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &m.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &m.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &m.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &m.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MetadataSchemaExportRequest. +func (m MetadataSchemaExportRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "assignedTo", m.AssignedTo) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MetadataSchemaExportRequest. +func (m *MetadataSchemaExportRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "assignedTo": + err = unpopulate(val, "AssignedTo", &m.AssignedTo) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MetadataSchemaExportResult. +func (m MetadataSchemaExportResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "format", m.Format) + populate(objectMap, "value", m.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MetadataSchemaExportResult. +func (m *MetadataSchemaExportResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "format": + err = unpopulate(val, "Format", &m.Format) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &m.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MetadataSchemaListResult. +func (m MetadataSchemaListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", m.NextLink) + populate(objectMap, "value", m.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MetadataSchemaListResult. +func (m *MetadataSchemaListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &m.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &m.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MetadataSchemaProperties. +func (m MetadataSchemaProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "assignedTo", m.AssignedTo) + populate(objectMap, "schema", m.Schema) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MetadataSchemaProperties. +func (m *MetadataSchemaProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "assignedTo": + err = unpopulate(val, "AssignedTo", &m.AssignedTo) + delete(rawMsg, key) + case "schema": + err = unpopulate(val, "Schema", &m.Schema) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Onboarding. +func (o Onboarding) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "developerPortalUri", o.DeveloperPortalURI) + populate(objectMap, "instructions", o.Instructions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Onboarding. +func (o *Onboarding) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "developerPortalUri": + err = unpopulate(val, "DeveloperPortalURI", &o.DeveloperPortalURI) + delete(rawMsg, key) + case "instructions": + err = unpopulate(val, "Instructions", &o.Instructions) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Operation. +func (o Operation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionType", o.ActionType) + populate(objectMap, "display", o.Display) + populate(objectMap, "isDataAction", o.IsDataAction) + populate(objectMap, "name", o.Name) + populate(objectMap, "origin", o.Origin) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Operation. +func (o *Operation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionType": + err = unpopulate(val, "ActionType", &o.ActionType) + delete(rawMsg, key) + case "display": + err = unpopulate(val, "Display", &o.Display) + delete(rawMsg, key) + case "isDataAction": + err = unpopulate(val, "IsDataAction", &o.IsDataAction) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "origin": + err = unpopulate(val, "Origin", &o.Origin) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationDisplay. +func (o OperationDisplay) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", o.Description) + populate(objectMap, "operation", o.Operation) + populate(objectMap, "provider", o.Provider) + populate(objectMap, "resource", o.Resource) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationDisplay. +func (o *OperationDisplay) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &o.Description) + delete(rawMsg, key) + case "operation": + err = unpopulate(val, "Operation", &o.Operation) + delete(rawMsg, key) + case "provider": + err = unpopulate(val, "Provider", &o.Provider) + delete(rawMsg, key) + case "resource": + err = unpopulate(val, "Resource", &o.Resource) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationListResult. +func (o *OperationListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &o.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Service. +func (s Service) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + populate(objectMap, "identity", s.Identity) + populate(objectMap, "location", s.Location) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "systemData", s.SystemData) + populate(objectMap, "tags", s.Tags) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Service. +func (s *Service) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &s.Identity) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &s.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &s.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &s.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ServiceListResult. +func (s ServiceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceListResult. +func (s *ServiceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &s.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ServiceProperties. +func (s ServiceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "restore", s.Restore) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceProperties. +func (s *ServiceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + case "restore": + err = unpopulate(val, "Restore", &s.Restore) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ServiceUpdate. +func (s ServiceUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identity", s.Identity) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "tags", s.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceUpdate. +func (s *ServiceUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "identity": + err = unpopulate(val, "Identity", &s.Identity) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &s.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ServiceUpdateProperties. +func (s ServiceUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "restore", s.Restore) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceUpdateProperties. +func (s *ServiceUpdateProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "restore": + err = unpopulate(val, "Restore", &s.Restore) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateTime[datetime.RFC3339](objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateTime[datetime.RFC3339](val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateTime[datetime.RFC3339](val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TermsOfService. +func (t TermsOfService) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "url", t.URL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TermsOfService. +func (t *TermsOfService) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "url": + err = unpopulate(val, "URL", &t.URL) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserAssignedIdentity. +func (u UserAssignedIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clientId", u.ClientID) + populate(objectMap, "principalId", u.PrincipalID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserAssignedIdentity. +func (u *UserAssignedIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "clientId": + err = unpopulate(val, "ClientID", &u.ClientID) + delete(rawMsg, key) + case "principalId": + err = unpopulate(val, "PrincipalID", &u.PrincipalID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Workspace. +func (w Workspace) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", w.ID) + populate(objectMap, "name", w.Name) + populate(objectMap, "properties", w.Properties) + populate(objectMap, "systemData", w.SystemData) + populate(objectMap, "type", w.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Workspace. +func (w *Workspace) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &w.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &w.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &w.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &w.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &w.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type WorkspaceListResult. +func (w WorkspaceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", w.NextLink) + populate(objectMap, "value", w.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WorkspaceListResult. +func (w *WorkspaceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &w.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &w.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type WorkspaceProperties. +func (w WorkspaceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", w.Description) + populate(objectMap, "title", w.Title) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WorkspaceProperties. +func (w *WorkspaceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &w.Description) + delete(rawMsg, key) + case "title": + err = unpopulate(val, "Title", &w.Title) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/local/armapicenter/zz_operations_client.go b/test/local/armapicenter/zz_operations_client.go new file mode 100644 index 000000000000..53438c5f2e23 --- /dev/null +++ b/test/local/armapicenter/zz_operations_client.go @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armapicenter + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +// +// Generated from API version 2024-06-01-preview +type OperationsClient struct { + internal *arm.Client +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*OperationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OperationsClient{ + internal: cl, + } + return client, nil +} + +// NewListPager - List the operations for the provider +// - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ + More: func(page OperationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OperationsClientListResponse) (OperationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OperationsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return OperationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, _ *OperationsClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.ApiCenter/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsClientListResponse, error) { + result := OperationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armapicenter/zz_options.go b/test/local/armapicenter/zz_options.go new file mode 100644 index 000000000000..818a9f1539bf --- /dev/null +++ b/test/local/armapicenter/zz_options.go @@ -0,0 +1,295 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armapicenter + +// APIDefinitionsClientBeginExportSpecificationOptions contains the optional parameters for the APIDefinitionsClient.BeginExportSpecification +// method. +type APIDefinitionsClientBeginExportSpecificationOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// APIDefinitionsClientBeginImportSpecificationOptions contains the optional parameters for the APIDefinitionsClient.BeginImportSpecification +// method. +type APIDefinitionsClientBeginImportSpecificationOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// APIDefinitionsClientCreateOrUpdateOptions contains the optional parameters for the APIDefinitionsClient.CreateOrUpdate +// method. +type APIDefinitionsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// APIDefinitionsClientDeleteOptions contains the optional parameters for the APIDefinitionsClient.Delete method. +type APIDefinitionsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// APIDefinitionsClientGetOptions contains the optional parameters for the APIDefinitionsClient.Get method. +type APIDefinitionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// APIDefinitionsClientHeadOptions contains the optional parameters for the APIDefinitionsClient.Head method. +type APIDefinitionsClientHeadOptions struct { + // placeholder for future optional parameters +} + +// APIDefinitionsClientListOptions contains the optional parameters for the APIDefinitionsClient.NewListPager method. +type APIDefinitionsClientListOptions struct { + // OData filter parameter. + Filter *string +} + +// APISourcesClientCreateOrUpdateOptions contains the optional parameters for the APISourcesClient.CreateOrUpdate method. +type APISourcesClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// APISourcesClientDeleteOptions contains the optional parameters for the APISourcesClient.Delete method. +type APISourcesClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// APISourcesClientGetOptions contains the optional parameters for the APISourcesClient.Get method. +type APISourcesClientGetOptions struct { + // placeholder for future optional parameters +} + +// APISourcesClientHeadOptions contains the optional parameters for the APISourcesClient.Head method. +type APISourcesClientHeadOptions struct { + // placeholder for future optional parameters +} + +// APISourcesClientListOptions contains the optional parameters for the APISourcesClient.NewListPager method. +type APISourcesClientListOptions struct { + // OData filter parameter. + Filter *string +} + +// APIVersionsClientCreateOrUpdateOptions contains the optional parameters for the APIVersionsClient.CreateOrUpdate method. +type APIVersionsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// APIVersionsClientDeleteOptions contains the optional parameters for the APIVersionsClient.Delete method. +type APIVersionsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// APIVersionsClientGetOptions contains the optional parameters for the APIVersionsClient.Get method. +type APIVersionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// APIVersionsClientHeadOptions contains the optional parameters for the APIVersionsClient.Head method. +type APIVersionsClientHeadOptions struct { + // placeholder for future optional parameters +} + +// APIVersionsClientListOptions contains the optional parameters for the APIVersionsClient.NewListPager method. +type APIVersionsClientListOptions struct { + // OData filter parameter. + Filter *string +} + +// ApisClientCreateOrUpdateOptions contains the optional parameters for the ApisClient.CreateOrUpdate method. +type ApisClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// ApisClientDeleteOptions contains the optional parameters for the ApisClient.Delete method. +type ApisClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// ApisClientGetOptions contains the optional parameters for the ApisClient.Get method. +type ApisClientGetOptions struct { + // placeholder for future optional parameters +} + +// ApisClientHeadOptions contains the optional parameters for the ApisClient.Head method. +type ApisClientHeadOptions struct { + // placeholder for future optional parameters +} + +// ApisClientListOptions contains the optional parameters for the ApisClient.NewListPager method. +type ApisClientListOptions struct { + // OData filter parameter. + Filter *string +} + +// DeletedServicesClientDeleteOptions contains the optional parameters for the DeletedServicesClient.Delete method. +type DeletedServicesClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// DeletedServicesClientGetOptions contains the optional parameters for the DeletedServicesClient.Get method. +type DeletedServicesClientGetOptions struct { + // placeholder for future optional parameters +} + +// DeletedServicesClientListBySubscriptionOptions contains the optional parameters for the DeletedServicesClient.NewListBySubscriptionPager +// method. +type DeletedServicesClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// DeletedServicesClientListOptions contains the optional parameters for the DeletedServicesClient.NewListPager method. +type DeletedServicesClientListOptions struct { + // OData filter parameter. + Filter *string +} + +// DeploymentsClientCreateOrUpdateOptions contains the optional parameters for the DeploymentsClient.CreateOrUpdate method. +type DeploymentsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// DeploymentsClientDeleteOptions contains the optional parameters for the DeploymentsClient.Delete method. +type DeploymentsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// DeploymentsClientGetOptions contains the optional parameters for the DeploymentsClient.Get method. +type DeploymentsClientGetOptions struct { + // placeholder for future optional parameters +} + +// DeploymentsClientHeadOptions contains the optional parameters for the DeploymentsClient.Head method. +type DeploymentsClientHeadOptions struct { + // placeholder for future optional parameters +} + +// DeploymentsClientListOptions contains the optional parameters for the DeploymentsClient.NewListPager method. +type DeploymentsClientListOptions struct { + // OData filter parameter. + Filter *string +} + +// EnvironmentsClientCreateOrUpdateOptions contains the optional parameters for the EnvironmentsClient.CreateOrUpdate method. +type EnvironmentsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// EnvironmentsClientDeleteOptions contains the optional parameters for the EnvironmentsClient.Delete method. +type EnvironmentsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// EnvironmentsClientGetOptions contains the optional parameters for the EnvironmentsClient.Get method. +type EnvironmentsClientGetOptions struct { + // placeholder for future optional parameters +} + +// EnvironmentsClientHeadOptions contains the optional parameters for the EnvironmentsClient.Head method. +type EnvironmentsClientHeadOptions struct { + // placeholder for future optional parameters +} + +// EnvironmentsClientListOptions contains the optional parameters for the EnvironmentsClient.NewListPager method. +type EnvironmentsClientListOptions struct { + // OData filter parameter. + Filter *string +} + +// MetadataSchemasClientCreateOrUpdateOptions contains the optional parameters for the MetadataSchemasClient.CreateOrUpdate +// method. +type MetadataSchemasClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// MetadataSchemasClientDeleteOptions contains the optional parameters for the MetadataSchemasClient.Delete method. +type MetadataSchemasClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// MetadataSchemasClientGetOptions contains the optional parameters for the MetadataSchemasClient.Get method. +type MetadataSchemasClientGetOptions struct { + // placeholder for future optional parameters +} + +// MetadataSchemasClientHeadOptions contains the optional parameters for the MetadataSchemasClient.Head method. +type MetadataSchemasClientHeadOptions struct { + // placeholder for future optional parameters +} + +// MetadataSchemasClientListOptions contains the optional parameters for the MetadataSchemasClient.NewListPager method. +type MetadataSchemasClientListOptions struct { + // OData filter parameter. + Filter *string +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} + +// ServicesClientBeginExportMetadataSchemaOptions contains the optional parameters for the ServicesClient.BeginExportMetadataSchema +// method. +type ServicesClientBeginExportMetadataSchemaOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ServicesClientCreateOrUpdateOptions contains the optional parameters for the ServicesClient.CreateOrUpdate method. +type ServicesClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// ServicesClientDeleteOptions contains the optional parameters for the ServicesClient.Delete method. +type ServicesClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// ServicesClientGetOptions contains the optional parameters for the ServicesClient.Get method. +type ServicesClientGetOptions struct { + // placeholder for future optional parameters +} + +// ServicesClientListByResourceGroupOptions contains the optional parameters for the ServicesClient.NewListByResourceGroupPager +// method. +type ServicesClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// ServicesClientListBySubscriptionOptions contains the optional parameters for the ServicesClient.NewListBySubscriptionPager +// method. +type ServicesClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// ServicesClientUpdateOptions contains the optional parameters for the ServicesClient.Update method. +type ServicesClientUpdateOptions struct { + // placeholder for future optional parameters +} + +// WorkspacesClientCreateOrUpdateOptions contains the optional parameters for the WorkspacesClient.CreateOrUpdate method. +type WorkspacesClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// WorkspacesClientDeleteOptions contains the optional parameters for the WorkspacesClient.Delete method. +type WorkspacesClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// WorkspacesClientGetOptions contains the optional parameters for the WorkspacesClient.Get method. +type WorkspacesClientGetOptions struct { + // placeholder for future optional parameters +} + +// WorkspacesClientHeadOptions contains the optional parameters for the WorkspacesClient.Head method. +type WorkspacesClientHeadOptions struct { + // placeholder for future optional parameters +} + +// WorkspacesClientListOptions contains the optional parameters for the WorkspacesClient.NewListPager method. +type WorkspacesClientListOptions struct { + // OData filter parameter. + Filter *string +} diff --git a/test/local/armapicenter/zz_responses.go b/test/local/armapicenter/zz_responses.go new file mode 100644 index 000000000000..29ffbe3c49b0 --- /dev/null +++ b/test/local/armapicenter/zz_responses.go @@ -0,0 +1,369 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armapicenter + +// APIDefinitionsClientCreateOrUpdateResponse contains the response from method APIDefinitionsClient.CreateOrUpdate. +type APIDefinitionsClientCreateOrUpdateResponse struct { + // API definition entity. + APIDefinition + + // The entity tag for the response. + EtagHeader *string +} + +// APIDefinitionsClientDeleteResponse contains the response from method APIDefinitionsClient.Delete. +type APIDefinitionsClientDeleteResponse struct { + // placeholder for future response values +} + +// APIDefinitionsClientExportSpecificationResponse contains the response from method APIDefinitionsClient.BeginExportSpecification. +type APIDefinitionsClientExportSpecificationResponse struct { + // The API specification export result. + APISpecExportResult +} + +// APIDefinitionsClientGetResponse contains the response from method APIDefinitionsClient.Get. +type APIDefinitionsClientGetResponse struct { + // API definition entity. + APIDefinition + + // The entity tag for the response. + EtagHeader *string +} + +// APIDefinitionsClientHeadResponse contains the response from method APIDefinitionsClient.Head. +type APIDefinitionsClientHeadResponse struct { + // Success indicates if the operation succeeded or failed. + Success bool +} + +// APIDefinitionsClientImportSpecificationResponse contains the response from method APIDefinitionsClient.BeginImportSpecification. +type APIDefinitionsClientImportSpecificationResponse struct { + // placeholder for future response values +} + +// APIDefinitionsClientListResponse contains the response from method APIDefinitionsClient.NewListPager. +type APIDefinitionsClientListResponse struct { + // The response of a ApiDefinition list operation. + APIDefinitionListResult +} + +// APISourcesClientCreateOrUpdateResponse contains the response from method APISourcesClient.CreateOrUpdate. +type APISourcesClientCreateOrUpdateResponse struct { + // API source entity. + APISource + + // The entity tag for the response. + EtagHeader *string +} + +// APISourcesClientDeleteResponse contains the response from method APISourcesClient.Delete. +type APISourcesClientDeleteResponse struct { + // placeholder for future response values +} + +// APISourcesClientGetResponse contains the response from method APISourcesClient.Get. +type APISourcesClientGetResponse struct { + // API source entity. + APISource + + // The entity tag for the response. + EtagHeader *string +} + +// APISourcesClientHeadResponse contains the response from method APISourcesClient.Head. +type APISourcesClientHeadResponse struct { + // Success indicates if the operation succeeded or failed. + Success bool +} + +// APISourcesClientListResponse contains the response from method APISourcesClient.NewListPager. +type APISourcesClientListResponse struct { + // The response of a ApiSource list operation. + APISourceListResult +} + +// APIVersionsClientCreateOrUpdateResponse contains the response from method APIVersionsClient.CreateOrUpdate. +type APIVersionsClientCreateOrUpdateResponse struct { + // API version entity. + APIVersion + + // The entity tag for the response. + EtagHeader *string +} + +// APIVersionsClientDeleteResponse contains the response from method APIVersionsClient.Delete. +type APIVersionsClientDeleteResponse struct { + // placeholder for future response values +} + +// APIVersionsClientGetResponse contains the response from method APIVersionsClient.Get. +type APIVersionsClientGetResponse struct { + // API version entity. + APIVersion + + // The entity tag for the response. + EtagHeader *string +} + +// APIVersionsClientHeadResponse contains the response from method APIVersionsClient.Head. +type APIVersionsClientHeadResponse struct { + // Success indicates if the operation succeeded or failed. + Success bool +} + +// APIVersionsClientListResponse contains the response from method APIVersionsClient.NewListPager. +type APIVersionsClientListResponse struct { + // The response of a ApiVersion list operation. + APIVersionListResult +} + +// ApisClientCreateOrUpdateResponse contains the response from method ApisClient.CreateOrUpdate. +type ApisClientCreateOrUpdateResponse struct { + // API entity. + API + + // The entity tag for the response. + EtagHeader *string +} + +// ApisClientDeleteResponse contains the response from method ApisClient.Delete. +type ApisClientDeleteResponse struct { + // placeholder for future response values +} + +// ApisClientGetResponse contains the response from method ApisClient.Get. +type ApisClientGetResponse struct { + // API entity. + API + + // The entity tag for the response. + EtagHeader *string +} + +// ApisClientHeadResponse contains the response from method ApisClient.Head. +type ApisClientHeadResponse struct { + // Success indicates if the operation succeeded or failed. + Success bool +} + +// ApisClientListResponse contains the response from method ApisClient.NewListPager. +type ApisClientListResponse struct { + // The response of a Api list operation. + APIListResult +} + +// DeletedServicesClientDeleteResponse contains the response from method DeletedServicesClient.Delete. +type DeletedServicesClientDeleteResponse struct { + // placeholder for future response values +} + +// DeletedServicesClientGetResponse contains the response from method DeletedServicesClient.Get. +type DeletedServicesClientGetResponse struct { + // Soft-deleted service entity. + DeletedService + + // The entity tag for the response. + EtagHeader *string +} + +// DeletedServicesClientListBySubscriptionResponse contains the response from method DeletedServicesClient.NewListBySubscriptionPager. +type DeletedServicesClientListBySubscriptionResponse struct { + // The response of a DeletedService list operation. + DeletedServiceListResult +} + +// DeletedServicesClientListResponse contains the response from method DeletedServicesClient.NewListPager. +type DeletedServicesClientListResponse struct { + // The response of a DeletedService list operation. + DeletedServiceListResult +} + +// DeploymentsClientCreateOrUpdateResponse contains the response from method DeploymentsClient.CreateOrUpdate. +type DeploymentsClientCreateOrUpdateResponse struct { + // API deployment entity. + Deployment + + // The entity tag for the response. + EtagHeader *string +} + +// DeploymentsClientDeleteResponse contains the response from method DeploymentsClient.Delete. +type DeploymentsClientDeleteResponse struct { + // placeholder for future response values +} + +// DeploymentsClientGetResponse contains the response from method DeploymentsClient.Get. +type DeploymentsClientGetResponse struct { + // API deployment entity. + Deployment + + // The entity tag for the response. + EtagHeader *string +} + +// DeploymentsClientHeadResponse contains the response from method DeploymentsClient.Head. +type DeploymentsClientHeadResponse struct { + // Success indicates if the operation succeeded or failed. + Success bool +} + +// DeploymentsClientListResponse contains the response from method DeploymentsClient.NewListPager. +type DeploymentsClientListResponse struct { + // The response of a Deployment list operation. + DeploymentListResult +} + +// EnvironmentsClientCreateOrUpdateResponse contains the response from method EnvironmentsClient.CreateOrUpdate. +type EnvironmentsClientCreateOrUpdateResponse struct { + // Environment entity. + Environment + + // The entity tag for the response. + EtagHeader *string +} + +// EnvironmentsClientDeleteResponse contains the response from method EnvironmentsClient.Delete. +type EnvironmentsClientDeleteResponse struct { + // placeholder for future response values +} + +// EnvironmentsClientGetResponse contains the response from method EnvironmentsClient.Get. +type EnvironmentsClientGetResponse struct { + // Environment entity. + Environment + + // The entity tag for the response. + EtagHeader *string +} + +// EnvironmentsClientHeadResponse contains the response from method EnvironmentsClient.Head. +type EnvironmentsClientHeadResponse struct { + // Success indicates if the operation succeeded or failed. + Success bool +} + +// EnvironmentsClientListResponse contains the response from method EnvironmentsClient.NewListPager. +type EnvironmentsClientListResponse struct { + // The response of a Environment list operation. + EnvironmentListResult +} + +// MetadataSchemasClientCreateOrUpdateResponse contains the response from method MetadataSchemasClient.CreateOrUpdate. +type MetadataSchemasClientCreateOrUpdateResponse struct { + // Metadata schema entity. Used to define metadata for the entities in API catalog. + MetadataSchema + + // The entity tag for the response. + EtagHeader *string +} + +// MetadataSchemasClientDeleteResponse contains the response from method MetadataSchemasClient.Delete. +type MetadataSchemasClientDeleteResponse struct { + // placeholder for future response values +} + +// MetadataSchemasClientGetResponse contains the response from method MetadataSchemasClient.Get. +type MetadataSchemasClientGetResponse struct { + // Metadata schema entity. Used to define metadata for the entities in API catalog. + MetadataSchema + + // The entity tag for the response. + EtagHeader *string +} + +// MetadataSchemasClientHeadResponse contains the response from method MetadataSchemasClient.Head. +type MetadataSchemasClientHeadResponse struct { + // Success indicates if the operation succeeded or failed. + Success bool +} + +// MetadataSchemasClientListResponse contains the response from method MetadataSchemasClient.NewListPager. +type MetadataSchemasClientListResponse struct { + // The response of a MetadataSchema list operation. + MetadataSchemaListResult +} + +// OperationsClientListResponse contains the response from method OperationsClient.NewListPager. +type OperationsClientListResponse struct { + // A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. + OperationListResult +} + +// ServicesClientCreateOrUpdateResponse contains the response from method ServicesClient.CreateOrUpdate. +type ServicesClientCreateOrUpdateResponse struct { + // The service entity. + Service +} + +// ServicesClientDeleteResponse contains the response from method ServicesClient.Delete. +type ServicesClientDeleteResponse struct { + // placeholder for future response values +} + +// ServicesClientExportMetadataSchemaResponse contains the response from method ServicesClient.BeginExportMetadataSchema. +type ServicesClientExportMetadataSchemaResponse struct { + // The metadata schema export result. + MetadataSchemaExportResult +} + +// ServicesClientGetResponse contains the response from method ServicesClient.Get. +type ServicesClientGetResponse struct { + // The service entity. + Service +} + +// ServicesClientListByResourceGroupResponse contains the response from method ServicesClient.NewListByResourceGroupPager. +type ServicesClientListByResourceGroupResponse struct { + // The response of a Service list operation. + ServiceListResult +} + +// ServicesClientListBySubscriptionResponse contains the response from method ServicesClient.NewListBySubscriptionPager. +type ServicesClientListBySubscriptionResponse struct { + // The response of a Service list operation. + ServiceListResult +} + +// ServicesClientUpdateResponse contains the response from method ServicesClient.Update. +type ServicesClientUpdateResponse struct { + // The service entity. + Service +} + +// WorkspacesClientCreateOrUpdateResponse contains the response from method WorkspacesClient.CreateOrUpdate. +type WorkspacesClientCreateOrUpdateResponse struct { + // Workspace entity. + Workspace + + // The entity tag for the response. + EtagHeader *string +} + +// WorkspacesClientDeleteResponse contains the response from method WorkspacesClient.Delete. +type WorkspacesClientDeleteResponse struct { + // placeholder for future response values +} + +// WorkspacesClientGetResponse contains the response from method WorkspacesClient.Get. +type WorkspacesClientGetResponse struct { + // Workspace entity. + Workspace + + // The entity tag for the response. + EtagHeader *string +} + +// WorkspacesClientHeadResponse contains the response from method WorkspacesClient.Head. +type WorkspacesClientHeadResponse struct { + // Success indicates if the operation succeeded or failed. + Success bool +} + +// WorkspacesClientListResponse contains the response from method WorkspacesClient.NewListPager. +type WorkspacesClientListResponse struct { + // The response of a Workspace list operation. + WorkspaceListResult +} diff --git a/test/local/armapicenter/zz_services_client.go b/test/local/armapicenter/zz_services_client.go new file mode 100644 index 000000000000..d2b24f746306 --- /dev/null +++ b/test/local/armapicenter/zz_services_client.go @@ -0,0 +1,477 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armapicenter + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ServicesClient contains the methods for the Services group. +// Don't use this type directly, use NewServicesClient() instead. +// +// Generated from API version 2024-06-01-preview +type ServicesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewServicesClient creates a new instance of ServicesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewServicesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ServicesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ServicesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Creates new or updates existing API. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - resource - Resource create parameters. +// - options - ServicesClientCreateOrUpdateOptions contains the optional parameters for the ServicesClient.CreateOrUpdate method. +func (client *ServicesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, resource Service, options *ServicesClientCreateOrUpdateOptions) (ServicesClientCreateOrUpdateResponse, error) { + var err error + const operationName = "ServicesClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, serviceName, resource, options) + if err != nil { + return ServicesClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServicesClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return ServicesClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *ServicesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, resource Service, _ *ServicesClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *ServicesClient) createOrUpdateHandleResponse(resp *http.Response) (ServicesClientCreateOrUpdateResponse, error) { + result := ServicesClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Service); err != nil { + return ServicesClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Deletes specified service. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - options - ServicesClientDeleteOptions contains the optional parameters for the ServicesClient.Delete method. +func (client *ServicesClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, options *ServicesClientDeleteOptions) (ServicesClientDeleteResponse, error) { + var err error + const operationName = "ServicesClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, serviceName, options) + if err != nil { + return ServicesClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServicesClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ServicesClientDeleteResponse{}, err + } + return ServicesClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ServicesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, _ *ServicesClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// BeginExportMetadataSchema - Exports the effective metadata schema. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - payload - The content of the action request +// - options - ServicesClientBeginExportMetadataSchemaOptions contains the optional parameters for the ServicesClient.BeginExportMetadataSchema +// method. +func (client *ServicesClient) BeginExportMetadataSchema(ctx context.Context, resourceGroupName string, serviceName string, payload MetadataSchemaExportRequest, options *ServicesClientBeginExportMetadataSchemaOptions) (*runtime.Poller[ServicesClientExportMetadataSchemaResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.exportMetadataSchema(ctx, resourceGroupName, serviceName, payload, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ServicesClientExportMetadataSchemaResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ServicesClientExportMetadataSchemaResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ExportMetadataSchema - Exports the effective metadata schema. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ServicesClient) exportMetadataSchema(ctx context.Context, resourceGroupName string, serviceName string, payload MetadataSchemaExportRequest, options *ServicesClientBeginExportMetadataSchemaOptions) (*http.Response, error) { + var err error + const operationName = "ServicesClient.BeginExportMetadataSchema" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.exportMetadataSchemaCreateRequest(ctx, resourceGroupName, serviceName, payload, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// exportMetadataSchemaCreateRequest creates the ExportMetadataSchema request. +func (client *ServicesClient) exportMetadataSchemaCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, payload MetadataSchemaExportRequest, _ *ServicesClientBeginExportMetadataSchemaOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/exportMetadataSchema" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, payload); err != nil { + return nil, err + } + return req, nil +} + +// Get - Returns details of the service. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - options - ServicesClientGetOptions contains the optional parameters for the ServicesClient.Get method. +func (client *ServicesClient) Get(ctx context.Context, resourceGroupName string, serviceName string, options *ServicesClientGetOptions) (ServicesClientGetResponse, error) { + var err error + const operationName = "ServicesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, serviceName, options) + if err != nil { + return ServicesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServicesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ServicesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ServicesClient) getCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, _ *ServicesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ServicesClient) getHandleResponse(resp *http.Response) (ServicesClientGetResponse, error) { + result := ServicesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Service); err != nil { + return ServicesClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Returns a collection of services within the resource group. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - ServicesClientListByResourceGroupOptions contains the optional parameters for the ServicesClient.NewListByResourceGroupPager +// method. +func (client *ServicesClient) NewListByResourceGroupPager(resourceGroupName string, options *ServicesClientListByResourceGroupOptions) *runtime.Pager[ServicesClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[ServicesClientListByResourceGroupResponse]{ + More: func(page ServicesClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ServicesClientListByResourceGroupResponse) (ServicesClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ServicesClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return ServicesClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *ServicesClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *ServicesClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *ServicesClient) listByResourceGroupHandleResponse(resp *http.Response) (ServicesClientListByResourceGroupResponse, error) { + result := ServicesClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ServiceListResult); err != nil { + return ServicesClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - Lists services within an Azure subscription. +// - options - ServicesClientListBySubscriptionOptions contains the optional parameters for the ServicesClient.NewListBySubscriptionPager +// method. +func (client *ServicesClient) NewListBySubscriptionPager(options *ServicesClientListBySubscriptionOptions) *runtime.Pager[ServicesClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[ServicesClientListBySubscriptionResponse]{ + More: func(page ServicesClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ServicesClientListBySubscriptionResponse) (ServicesClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ServicesClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return ServicesClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *ServicesClient) listBySubscriptionCreateRequest(ctx context.Context, _ *ServicesClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ApiCenter/services" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *ServicesClient) listBySubscriptionHandleResponse(resp *http.Response) (ServicesClientListBySubscriptionResponse, error) { + result := ServicesClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ServiceListResult); err != nil { + return ServicesClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// Update - Updates existing service. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - payload - The resource properties to be updated. +// - options - ServicesClientUpdateOptions contains the optional parameters for the ServicesClient.Update method. +func (client *ServicesClient) Update(ctx context.Context, resourceGroupName string, serviceName string, payload ServiceUpdate, options *ServicesClientUpdateOptions) (ServicesClientUpdateResponse, error) { + var err error + const operationName = "ServicesClient.Update" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, serviceName, payload, options) + if err != nil { + return ServicesClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServicesClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ServicesClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *ServicesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, payload ServiceUpdate, _ *ServicesClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, payload); err != nil { + return nil, err + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *ServicesClient) updateHandleResponse(resp *http.Response) (ServicesClientUpdateResponse, error) { + result := ServicesClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Service); err != nil { + return ServicesClientUpdateResponse{}, err + } + return result, nil +} diff --git a/test/local/armapicenter/zz_version.go b/test/local/armapicenter/zz_version.go new file mode 100644 index 000000000000..838be8a4b1f3 --- /dev/null +++ b/test/local/armapicenter/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package armapicenter + +const ( + moduleName = "armapicenter" + moduleVersion = "v0.1.0" +) diff --git a/test/local/armapicenter/zz_workspaces_client.go b/test/local/armapicenter/zz_workspaces_client.go new file mode 100644 index 000000000000..0a56cbcbd14b --- /dev/null +++ b/test/local/armapicenter/zz_workspaces_client.go @@ -0,0 +1,364 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armapicenter + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// WorkspacesClient contains the methods for the Workspaces group. +// Don't use this type directly, use NewWorkspacesClient() instead. +// +// Generated from API version 2024-06-01-preview +type WorkspacesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewWorkspacesClient creates a new instance of WorkspacesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewWorkspacesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*WorkspacesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &WorkspacesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Creates new or updates existing workspace. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - payload - Resource create parameters. +// - options - WorkspacesClientCreateOrUpdateOptions contains the optional parameters for the WorkspacesClient.CreateOrUpdate +// method. +func (client *WorkspacesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, payload Workspace, options *WorkspacesClientCreateOrUpdateOptions) (WorkspacesClientCreateOrUpdateResponse, error) { + var err error + const operationName = "WorkspacesClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, payload, options) + if err != nil { + return WorkspacesClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return WorkspacesClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return WorkspacesClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *WorkspacesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, payload Workspace, _ *WorkspacesClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, payload); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *WorkspacesClient) createOrUpdateHandleResponse(resp *http.Response) (WorkspacesClientCreateOrUpdateResponse, error) { + result := WorkspacesClientCreateOrUpdateResponse{} + if val := resp.Header.Get("ETag"); val != "" { + result.EtagHeader = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.Workspace); err != nil { + return WorkspacesClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Deletes specified workspace. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - options - WorkspacesClientDeleteOptions contains the optional parameters for the WorkspacesClient.Delete method. +func (client *WorkspacesClient) Delete(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, options *WorkspacesClientDeleteOptions) (WorkspacesClientDeleteResponse, error) { + var err error + const operationName = "WorkspacesClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, options) + if err != nil { + return WorkspacesClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return WorkspacesClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return WorkspacesClientDeleteResponse{}, err + } + return WorkspacesClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *WorkspacesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, _ *WorkspacesClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Returns details of the workspace. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - options - WorkspacesClientGetOptions contains the optional parameters for the WorkspacesClient.Get method. +func (client *WorkspacesClient) Get(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, options *WorkspacesClientGetOptions) (WorkspacesClientGetResponse, error) { + var err error + const operationName = "WorkspacesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, options) + if err != nil { + return WorkspacesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return WorkspacesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return WorkspacesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *WorkspacesClient) getCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, _ *WorkspacesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *WorkspacesClient) getHandleResponse(resp *http.Response) (WorkspacesClientGetResponse, error) { + result := WorkspacesClientGetResponse{} + if val := resp.Header.Get("ETag"); val != "" { + result.EtagHeader = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.Workspace); err != nil { + return WorkspacesClientGetResponse{}, err + } + return result, nil +} + +// Head - Checks if specified workspace exists. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - workspaceName - The name of the workspace. +// - options - WorkspacesClientHeadOptions contains the optional parameters for the WorkspacesClient.Head method. +func (client *WorkspacesClient) Head(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, options *WorkspacesClientHeadOptions) (WorkspacesClientHeadResponse, error) { + var err error + const operationName = "WorkspacesClient.Head" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.headCreateRequest(ctx, resourceGroupName, serviceName, workspaceName, options) + if err != nil { + return WorkspacesClientHeadResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return WorkspacesClientHeadResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return WorkspacesClientHeadResponse{}, err + } + return WorkspacesClientHeadResponse{Success: httpResp.StatusCode >= 200 && httpResp.StatusCode < 300}, nil +} + +// headCreateRequest creates the Head request. +func (client *WorkspacesClient) headCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, workspaceName string, _ *WorkspacesClientHeadOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces/{workspaceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + req, err := runtime.NewRequest(ctx, http.MethodHead, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// NewListPager - Returns a collection of workspaces. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - serviceName - The name of Azure API Center service. +// - options - WorkspacesClientListOptions contains the optional parameters for the WorkspacesClient.NewListPager method. +func (client *WorkspacesClient) NewListPager(resourceGroupName string, serviceName string, options *WorkspacesClientListOptions) *runtime.Pager[WorkspacesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[WorkspacesClientListResponse]{ + More: func(page WorkspacesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *WorkspacesClientListResponse) (WorkspacesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "WorkspacesClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, serviceName, options) + }, nil) + if err != nil { + return WorkspacesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *WorkspacesClient) listCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, options *WorkspacesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiCenter/services/{serviceName}/workspaces" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + reqQP.Set("api-version", version20240601Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *WorkspacesClient) listHandleResponse(resp *http.Response) (WorkspacesClientListResponse, error) { + result := WorkspacesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.WorkspaceListResult); err != nil { + return WorkspacesClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armbillingbenefits/LICENSE.txt b/test/local/armbillingbenefits/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/local/armbillingbenefits/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/local/armbillingbenefits/fake/zz_applicablemaccs_server.go b/test/local/armbillingbenefits/fake/zz_applicablemaccs_server.go new file mode 100644 index 000000000000..36ae4c1dd9ac --- /dev/null +++ b/test/local/armbillingbenefits/fake/zz_applicablemaccs_server.go @@ -0,0 +1,125 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armbillingbenefits" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// ApplicableMaccsServer is a fake server for instances of the armbillingbenefits.ApplicableMaccsClient type. +type ApplicableMaccsServer struct { + // NewListPager is the fake for method ApplicableMaccsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(billingAccountID string, options *armbillingbenefits.ApplicableMaccsClientListOptions) (resp azfake.PagerResponder[armbillingbenefits.ApplicableMaccsClientListResponse]) +} + +// NewApplicableMaccsServerTransport creates a new instance of ApplicableMaccsServerTransport with the provided implementation. +// The returned ApplicableMaccsServerTransport instance is connected to an instance of armbillingbenefits.ApplicableMaccsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewApplicableMaccsServerTransport(srv *ApplicableMaccsServer) *ApplicableMaccsServerTransport { + return &ApplicableMaccsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armbillingbenefits.ApplicableMaccsClientListResponse]](), + } +} + +// ApplicableMaccsServerTransport connects instances of armbillingbenefits.ApplicableMaccsClient to instances of ApplicableMaccsServer. +// Don't use this type directly, use NewApplicableMaccsServerTransport instead. +type ApplicableMaccsServerTransport struct { + srv *ApplicableMaccsServer + newListPager *tracker[azfake.PagerResponder[armbillingbenefits.ApplicableMaccsClientListResponse]] +} + +// Do implements the policy.Transporter interface for ApplicableMaccsServerTransport. +func (a *ApplicableMaccsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *ApplicableMaccsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if applicableMaccsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = applicableMaccsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ApplicableMaccsClient.NewListPager": + res.resp, res.err = a.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *ApplicableMaccsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if a.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := a.newListPager.get(req) + if newListPager == nil { + const regexStr = `/providers/microsoft\.Billing/billingAccounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/applicableMaccs` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + billingAccountIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("billingAccountId")]) + if err != nil { + return nil, err + } + resp := a.srv.NewListPager(billingAccountIDParam, nil) + newListPager = &resp + a.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armbillingbenefits.ApplicableMaccsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + a.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ApplicableMaccsServerTransport +var applicableMaccsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armbillingbenefits/fake/zz_conditionalcreditcontributors_server.go b/test/local/armbillingbenefits/fake/zz_conditionalcreditcontributors_server.go new file mode 100644 index 000000000000..cb8f0458da4d --- /dev/null +++ b/test/local/armbillingbenefits/fake/zz_conditionalcreditcontributors_server.go @@ -0,0 +1,222 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armbillingbenefits" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// ConditionalCreditContributorsServer is a fake server for instances of the armbillingbenefits.ConditionalCreditContributorsClient type. +type ConditionalCreditContributorsServer struct { + // GetFromPrimary is the fake for method ConditionalCreditContributorsClient.GetFromPrimary + // HTTP status codes to indicate success: http.StatusOK + GetFromPrimary func(ctx context.Context, resourceGroupName string, conditionalCreditName string, contributorName string, options *armbillingbenefits.ConditionalCreditContributorsClientGetFromPrimaryOptions) (resp azfake.Responder[armbillingbenefits.ConditionalCreditContributorsClientGetFromPrimaryResponse], errResp azfake.ErrorResponder) + + // NewListFromApplicableConditionalCreditPager is the fake for method ConditionalCreditContributorsClient.NewListFromApplicableConditionalCreditPager + // HTTP status codes to indicate success: http.StatusOK + NewListFromApplicableConditionalCreditPager func(billingAccountID string, systemID string, options *armbillingbenefits.ConditionalCreditContributorsClientListFromApplicableConditionalCreditOptions) (resp azfake.PagerResponder[armbillingbenefits.ConditionalCreditContributorsClientListFromApplicableConditionalCreditResponse]) + + // NewListFromPrimaryPager is the fake for method ConditionalCreditContributorsClient.NewListFromPrimaryPager + // HTTP status codes to indicate success: http.StatusOK + NewListFromPrimaryPager func(resourceGroupName string, conditionalCreditName string, options *armbillingbenefits.ConditionalCreditContributorsClientListFromPrimaryOptions) (resp azfake.PagerResponder[armbillingbenefits.ConditionalCreditContributorsClientListFromPrimaryResponse]) +} + +// NewConditionalCreditContributorsServerTransport creates a new instance of ConditionalCreditContributorsServerTransport with the provided implementation. +// The returned ConditionalCreditContributorsServerTransport instance is connected to an instance of armbillingbenefits.ConditionalCreditContributorsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewConditionalCreditContributorsServerTransport(srv *ConditionalCreditContributorsServer) *ConditionalCreditContributorsServerTransport { + return &ConditionalCreditContributorsServerTransport{ + srv: srv, + newListFromApplicableConditionalCreditPager: newTracker[azfake.PagerResponder[armbillingbenefits.ConditionalCreditContributorsClientListFromApplicableConditionalCreditResponse]](), + newListFromPrimaryPager: newTracker[azfake.PagerResponder[armbillingbenefits.ConditionalCreditContributorsClientListFromPrimaryResponse]](), + } +} + +// ConditionalCreditContributorsServerTransport connects instances of armbillingbenefits.ConditionalCreditContributorsClient to instances of ConditionalCreditContributorsServer. +// Don't use this type directly, use NewConditionalCreditContributorsServerTransport instead. +type ConditionalCreditContributorsServerTransport struct { + srv *ConditionalCreditContributorsServer + newListFromApplicableConditionalCreditPager *tracker[azfake.PagerResponder[armbillingbenefits.ConditionalCreditContributorsClientListFromApplicableConditionalCreditResponse]] + newListFromPrimaryPager *tracker[azfake.PagerResponder[armbillingbenefits.ConditionalCreditContributorsClientListFromPrimaryResponse]] +} + +// Do implements the policy.Transporter interface for ConditionalCreditContributorsServerTransport. +func (c *ConditionalCreditContributorsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *ConditionalCreditContributorsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if conditionalCreditContributorsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = conditionalCreditContributorsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ConditionalCreditContributorsClient.GetFromPrimary": + res.resp, res.err = c.dispatchGetFromPrimary(req) + case "ConditionalCreditContributorsClient.NewListFromApplicableConditionalCreditPager": + res.resp, res.err = c.dispatchNewListFromApplicableConditionalCreditPager(req) + case "ConditionalCreditContributorsClient.NewListFromPrimaryPager": + res.resp, res.err = c.dispatchNewListFromPrimaryPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *ConditionalCreditContributorsServerTransport) dispatchGetFromPrimary(req *http.Request) (*http.Response, error) { + if c.srv.GetFromPrimary == nil { + return nil, &nonRetriableError{errors.New("fake for method GetFromPrimary not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/conditionalCredits/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/contributors/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + conditionalCreditNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("conditionalCreditName")]) + if err != nil { + return nil, err + } + contributorNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("contributorName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.GetFromPrimary(req.Context(), resourceGroupNameParam, conditionalCreditNameParam, contributorNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ConditionalCreditContributor, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *ConditionalCreditContributorsServerTransport) dispatchNewListFromApplicableConditionalCreditPager(req *http.Request) (*http.Response, error) { + if c.srv.NewListFromApplicableConditionalCreditPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListFromApplicableConditionalCreditPager not implemented")} + } + newListFromApplicableConditionalCreditPager := c.newListFromApplicableConditionalCreditPager.get(req) + if newListFromApplicableConditionalCreditPager == nil { + const regexStr = `/providers/microsoft\.Billing/billingAccounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/applicableConditionalCredits/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/microsoft\.BillingBenefits/applicableContributors` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + billingAccountIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("billingAccountId")]) + if err != nil { + return nil, err + } + systemIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("systemId")]) + if err != nil { + return nil, err + } + resp := c.srv.NewListFromApplicableConditionalCreditPager(billingAccountIDParam, systemIDParam, nil) + newListFromApplicableConditionalCreditPager = &resp + c.newListFromApplicableConditionalCreditPager.add(req, newListFromApplicableConditionalCreditPager) + server.PagerResponderInjectNextLinks(newListFromApplicableConditionalCreditPager, req, func(page *armbillingbenefits.ConditionalCreditContributorsClientListFromApplicableConditionalCreditResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListFromApplicableConditionalCreditPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + c.newListFromApplicableConditionalCreditPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListFromApplicableConditionalCreditPager) { + c.newListFromApplicableConditionalCreditPager.remove(req) + } + return resp, nil +} + +func (c *ConditionalCreditContributorsServerTransport) dispatchNewListFromPrimaryPager(req *http.Request) (*http.Response, error) { + if c.srv.NewListFromPrimaryPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListFromPrimaryPager not implemented")} + } + newListFromPrimaryPager := c.newListFromPrimaryPager.get(req) + if newListFromPrimaryPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/conditionalCredits/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/contributors` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + conditionalCreditNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("conditionalCreditName")]) + if err != nil { + return nil, err + } + resp := c.srv.NewListFromPrimaryPager(resourceGroupNameParam, conditionalCreditNameParam, nil) + newListFromPrimaryPager = &resp + c.newListFromPrimaryPager.add(req, newListFromPrimaryPager) + server.PagerResponderInjectNextLinks(newListFromPrimaryPager, req, func(page *armbillingbenefits.ConditionalCreditContributorsClientListFromPrimaryResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListFromPrimaryPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + c.newListFromPrimaryPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListFromPrimaryPager) { + c.newListFromPrimaryPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ConditionalCreditContributorsServerTransport +var conditionalCreditContributorsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armbillingbenefits/fake/zz_conditionalcredits_server.go b/test/local/armbillingbenefits/fake/zz_conditionalcredits_server.go new file mode 100644 index 000000000000..9e462c5bf9e8 --- /dev/null +++ b/test/local/armbillingbenefits/fake/zz_conditionalcredits_server.go @@ -0,0 +1,467 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armbillingbenefits" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// ConditionalCreditsServer is a fake server for instances of the armbillingbenefits.ConditionalCreditsClient type. +type ConditionalCreditsServer struct { + // BeginCancel is the fake for method ConditionalCreditsClient.BeginCancel + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginCancel func(ctx context.Context, resourceGroupName string, conditionalCreditName string, options *armbillingbenefits.ConditionalCreditsClientBeginCancelOptions) (resp azfake.PollerResponder[armbillingbenefits.ConditionalCreditsClientCancelResponse], errResp azfake.ErrorResponder) + + // BeginCreateOrUpdate is the fake for method ConditionalCreditsClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, conditionalCreditName string, body armbillingbenefits.ConditionalCredit, options *armbillingbenefits.ConditionalCreditsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armbillingbenefits.ConditionalCreditsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method ConditionalCreditsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, conditionalCreditName string, options *armbillingbenefits.ConditionalCreditsClientBeginDeleteOptions) (resp azfake.PollerResponder[armbillingbenefits.ConditionalCreditsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method ConditionalCreditsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, conditionalCreditName string, options *armbillingbenefits.ConditionalCreditsClientGetOptions) (resp azfake.Responder[armbillingbenefits.ConditionalCreditsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method ConditionalCreditsClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armbillingbenefits.ConditionalCreditsClientListByResourceGroupOptions) (resp azfake.PagerResponder[armbillingbenefits.ConditionalCreditsClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method ConditionalCreditsClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armbillingbenefits.ConditionalCreditsClientListBySubscriptionOptions) (resp azfake.PagerResponder[armbillingbenefits.ConditionalCreditsClientListBySubscriptionResponse]) + + // NewScopeListPager is the fake for method ConditionalCreditsClient.NewScopeListPager + // HTTP status codes to indicate success: http.StatusOK + NewScopeListPager func(scope string, options *armbillingbenefits.ConditionalCreditsClientScopeListOptions) (resp azfake.PagerResponder[armbillingbenefits.ConditionalCreditsClientScopeListResponse]) + + // BeginUpdate is the fake for method ConditionalCreditsClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, conditionalCreditName string, body armbillingbenefits.ConditionalCreditPatchRequest, options *armbillingbenefits.ConditionalCreditsClientBeginUpdateOptions) (resp azfake.PollerResponder[armbillingbenefits.ConditionalCreditsClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewConditionalCreditsServerTransport creates a new instance of ConditionalCreditsServerTransport with the provided implementation. +// The returned ConditionalCreditsServerTransport instance is connected to an instance of armbillingbenefits.ConditionalCreditsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewConditionalCreditsServerTransport(srv *ConditionalCreditsServer) *ConditionalCreditsServerTransport { + return &ConditionalCreditsServerTransport{ + srv: srv, + beginCancel: newTracker[azfake.PollerResponder[armbillingbenefits.ConditionalCreditsClientCancelResponse]](), + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armbillingbenefits.ConditionalCreditsClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armbillingbenefits.ConditionalCreditsClientDeleteResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armbillingbenefits.ConditionalCreditsClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armbillingbenefits.ConditionalCreditsClientListBySubscriptionResponse]](), + newScopeListPager: newTracker[azfake.PagerResponder[armbillingbenefits.ConditionalCreditsClientScopeListResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armbillingbenefits.ConditionalCreditsClientUpdateResponse]](), + } +} + +// ConditionalCreditsServerTransport connects instances of armbillingbenefits.ConditionalCreditsClient to instances of ConditionalCreditsServer. +// Don't use this type directly, use NewConditionalCreditsServerTransport instead. +type ConditionalCreditsServerTransport struct { + srv *ConditionalCreditsServer + beginCancel *tracker[azfake.PollerResponder[armbillingbenefits.ConditionalCreditsClientCancelResponse]] + beginCreateOrUpdate *tracker[azfake.PollerResponder[armbillingbenefits.ConditionalCreditsClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armbillingbenefits.ConditionalCreditsClientDeleteResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armbillingbenefits.ConditionalCreditsClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armbillingbenefits.ConditionalCreditsClientListBySubscriptionResponse]] + newScopeListPager *tracker[azfake.PagerResponder[armbillingbenefits.ConditionalCreditsClientScopeListResponse]] + beginUpdate *tracker[azfake.PollerResponder[armbillingbenefits.ConditionalCreditsClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for ConditionalCreditsServerTransport. +func (c *ConditionalCreditsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *ConditionalCreditsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if conditionalCreditsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = conditionalCreditsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ConditionalCreditsClient.BeginCancel": + res.resp, res.err = c.dispatchBeginCancel(req) + case "ConditionalCreditsClient.BeginCreateOrUpdate": + res.resp, res.err = c.dispatchBeginCreateOrUpdate(req) + case "ConditionalCreditsClient.BeginDelete": + res.resp, res.err = c.dispatchBeginDelete(req) + case "ConditionalCreditsClient.Get": + res.resp, res.err = c.dispatchGet(req) + case "ConditionalCreditsClient.NewListByResourceGroupPager": + res.resp, res.err = c.dispatchNewListByResourceGroupPager(req) + case "ConditionalCreditsClient.NewListBySubscriptionPager": + res.resp, res.err = c.dispatchNewListBySubscriptionPager(req) + case "ConditionalCreditsClient.NewScopeListPager": + res.resp, res.err = c.dispatchNewScopeListPager(req) + case "ConditionalCreditsClient.BeginUpdate": + res.resp, res.err = c.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *ConditionalCreditsServerTransport) dispatchBeginCancel(req *http.Request) (*http.Response, error) { + if c.srv.BeginCancel == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCancel not implemented")} + } + beginCancel := c.beginCancel.get(req) + if beginCancel == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/conditionalCredits/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/cancel` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + conditionalCreditNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("conditionalCreditName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginCancel(req.Context(), resourceGroupNameParam, conditionalCreditNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCancel = &respr + c.beginCancel.add(req, beginCancel) + } + + resp, err := server.PollerResponderNext(beginCancel, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + c.beginCancel.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCancel) { + c.beginCancel.remove(req) + } + + return resp, nil +} + +func (c *ConditionalCreditsServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if c.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := c.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/conditionalCredits/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armbillingbenefits.ConditionalCredit](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + conditionalCreditNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("conditionalCreditName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, conditionalCreditNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + c.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + c.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + c.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (c *ConditionalCreditsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if c.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := c.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/conditionalCredits/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + conditionalCreditNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("conditionalCreditName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginDelete(req.Context(), resourceGroupNameParam, conditionalCreditNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + c.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + c.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + c.beginDelete.remove(req) + } + + return resp, nil +} + +func (c *ConditionalCreditsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if c.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/conditionalCredits/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + conditionalCreditNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("conditionalCreditName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.Get(req.Context(), resourceGroupNameParam, conditionalCreditNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ConditionalCredit, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *ConditionalCreditsServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if c.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := c.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/conditionalCredits` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := c.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + c.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armbillingbenefits.ConditionalCreditsClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + c.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + c.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (c *ConditionalCreditsServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if c.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := c.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/conditionalCredits` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := c.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + c.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armbillingbenefits.ConditionalCreditsClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + c.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + c.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (c *ConditionalCreditsServerTransport) dispatchNewScopeListPager(req *http.Request) (*http.Response, error) { + if c.srv.NewScopeListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewScopeListPager not implemented")} + } + newScopeListPager := c.newScopeListPager.get(req) + if newScopeListPager == nil { + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/applicableConditionalCredits` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + scopeParam, err := url.PathUnescape(matches[regex.SubexpIndex("scope")]) + if err != nil { + return nil, err + } + resp := c.srv.NewScopeListPager(scopeParam, nil) + newScopeListPager = &resp + c.newScopeListPager.add(req, newScopeListPager) + server.PagerResponderInjectNextLinks(newScopeListPager, req, func(page *armbillingbenefits.ConditionalCreditsClientScopeListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newScopeListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + c.newScopeListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newScopeListPager) { + c.newScopeListPager.remove(req) + } + return resp, nil +} + +func (c *ConditionalCreditsServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if c.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := c.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/conditionalCredits/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armbillingbenefits.ConditionalCreditPatchRequest](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + conditionalCreditNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("conditionalCreditName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginUpdate(req.Context(), resourceGroupNameParam, conditionalCreditNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + c.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + c.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + c.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to ConditionalCreditsServerTransport +var conditionalCreditsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armbillingbenefits/fake/zz_contributors_server.go b/test/local/armbillingbenefits/fake/zz_contributors_server.go new file mode 100644 index 000000000000..73d9674aa2ef --- /dev/null +++ b/test/local/armbillingbenefits/fake/zz_contributors_server.go @@ -0,0 +1,222 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armbillingbenefits" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// ContributorsServer is a fake server for instances of the armbillingbenefits.ContributorsClient type. +type ContributorsServer struct { + // GetFromPrimary is the fake for method ContributorsClient.GetFromPrimary + // HTTP status codes to indicate success: http.StatusOK + GetFromPrimary func(ctx context.Context, resourceGroupName string, maccName string, contributorName string, options *armbillingbenefits.ContributorsClientGetFromPrimaryOptions) (resp azfake.Responder[armbillingbenefits.ContributorsClientGetFromPrimaryResponse], errResp azfake.ErrorResponder) + + // NewListFromApplicableMaccPager is the fake for method ContributorsClient.NewListFromApplicableMaccPager + // HTTP status codes to indicate success: http.StatusOK + NewListFromApplicableMaccPager func(billingAccountID string, systemID string, options *armbillingbenefits.ContributorsClientListFromApplicableMaccOptions) (resp azfake.PagerResponder[armbillingbenefits.ContributorsClientListFromApplicableMaccResponse]) + + // NewListFromPrimaryPager is the fake for method ContributorsClient.NewListFromPrimaryPager + // HTTP status codes to indicate success: http.StatusOK + NewListFromPrimaryPager func(resourceGroupName string, maccName string, options *armbillingbenefits.ContributorsClientListFromPrimaryOptions) (resp azfake.PagerResponder[armbillingbenefits.ContributorsClientListFromPrimaryResponse]) +} + +// NewContributorsServerTransport creates a new instance of ContributorsServerTransport with the provided implementation. +// The returned ContributorsServerTransport instance is connected to an instance of armbillingbenefits.ContributorsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewContributorsServerTransport(srv *ContributorsServer) *ContributorsServerTransport { + return &ContributorsServerTransport{ + srv: srv, + newListFromApplicableMaccPager: newTracker[azfake.PagerResponder[armbillingbenefits.ContributorsClientListFromApplicableMaccResponse]](), + newListFromPrimaryPager: newTracker[azfake.PagerResponder[armbillingbenefits.ContributorsClientListFromPrimaryResponse]](), + } +} + +// ContributorsServerTransport connects instances of armbillingbenefits.ContributorsClient to instances of ContributorsServer. +// Don't use this type directly, use NewContributorsServerTransport instead. +type ContributorsServerTransport struct { + srv *ContributorsServer + newListFromApplicableMaccPager *tracker[azfake.PagerResponder[armbillingbenefits.ContributorsClientListFromApplicableMaccResponse]] + newListFromPrimaryPager *tracker[azfake.PagerResponder[armbillingbenefits.ContributorsClientListFromPrimaryResponse]] +} + +// Do implements the policy.Transporter interface for ContributorsServerTransport. +func (c *ContributorsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *ContributorsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if contributorsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = contributorsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ContributorsClient.GetFromPrimary": + res.resp, res.err = c.dispatchGetFromPrimary(req) + case "ContributorsClient.NewListFromApplicableMaccPager": + res.resp, res.err = c.dispatchNewListFromApplicableMaccPager(req) + case "ContributorsClient.NewListFromPrimaryPager": + res.resp, res.err = c.dispatchNewListFromPrimaryPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *ContributorsServerTransport) dispatchGetFromPrimary(req *http.Request) (*http.Response, error) { + if c.srv.GetFromPrimary == nil { + return nil, &nonRetriableError{errors.New("fake for method GetFromPrimary not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/maccs/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/contributors/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + maccNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("maccName")]) + if err != nil { + return nil, err + } + contributorNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("contributorName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.GetFromPrimary(req.Context(), resourceGroupNameParam, maccNameParam, contributorNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Contributor, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *ContributorsServerTransport) dispatchNewListFromApplicableMaccPager(req *http.Request) (*http.Response, error) { + if c.srv.NewListFromApplicableMaccPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListFromApplicableMaccPager not implemented")} + } + newListFromApplicableMaccPager := c.newListFromApplicableMaccPager.get(req) + if newListFromApplicableMaccPager == nil { + const regexStr = `/providers/microsoft\.Billing/billingAccounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/applicableMaccs/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/microsoft\.BillingBenefits/applicableContributors` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + billingAccountIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("billingAccountId")]) + if err != nil { + return nil, err + } + systemIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("systemId")]) + if err != nil { + return nil, err + } + resp := c.srv.NewListFromApplicableMaccPager(billingAccountIDParam, systemIDParam, nil) + newListFromApplicableMaccPager = &resp + c.newListFromApplicableMaccPager.add(req, newListFromApplicableMaccPager) + server.PagerResponderInjectNextLinks(newListFromApplicableMaccPager, req, func(page *armbillingbenefits.ContributorsClientListFromApplicableMaccResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListFromApplicableMaccPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + c.newListFromApplicableMaccPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListFromApplicableMaccPager) { + c.newListFromApplicableMaccPager.remove(req) + } + return resp, nil +} + +func (c *ContributorsServerTransport) dispatchNewListFromPrimaryPager(req *http.Request) (*http.Response, error) { + if c.srv.NewListFromPrimaryPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListFromPrimaryPager not implemented")} + } + newListFromPrimaryPager := c.newListFromPrimaryPager.get(req) + if newListFromPrimaryPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/maccs/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/contributors` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + maccNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("maccName")]) + if err != nil { + return nil, err + } + resp := c.srv.NewListFromPrimaryPager(resourceGroupNameParam, maccNameParam, nil) + newListFromPrimaryPager = &resp + c.newListFromPrimaryPager.add(req, newListFromPrimaryPager) + server.PagerResponderInjectNextLinks(newListFromPrimaryPager, req, func(page *armbillingbenefits.ContributorsClientListFromPrimaryResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListFromPrimaryPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + c.newListFromPrimaryPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListFromPrimaryPager) { + c.newListFromPrimaryPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ContributorsServerTransport +var contributorsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armbillingbenefits/fake/zz_credits_server.go b/test/local/armbillingbenefits/fake/zz_credits_server.go new file mode 100644 index 000000000000..94967bb1c611 --- /dev/null +++ b/test/local/armbillingbenefits/fake/zz_credits_server.go @@ -0,0 +1,467 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armbillingbenefits" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// CreditsServer is a fake server for instances of the armbillingbenefits.CreditsClient type. +type CreditsServer struct { + // BeginCancel is the fake for method CreditsClient.BeginCancel + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginCancel func(ctx context.Context, resourceGroupName string, creditName string, options *armbillingbenefits.CreditsClientBeginCancelOptions) (resp azfake.PollerResponder[armbillingbenefits.CreditsClientCancelResponse], errResp azfake.ErrorResponder) + + // BeginCreate is the fake for method CreditsClient.BeginCreate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreate func(ctx context.Context, resourceGroupName string, creditName string, body armbillingbenefits.Credit, options *armbillingbenefits.CreditsClientBeginCreateOptions) (resp azfake.PollerResponder[armbillingbenefits.CreditsClientCreateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method CreditsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, creditName string, options *armbillingbenefits.CreditsClientBeginDeleteOptions) (resp azfake.PollerResponder[armbillingbenefits.CreditsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method CreditsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, creditName string, options *armbillingbenefits.CreditsClientGetOptions) (resp azfake.Responder[armbillingbenefits.CreditsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListApplicablePager is the fake for method CreditsClient.NewListApplicablePager + // HTTP status codes to indicate success: http.StatusOK + NewListApplicablePager func(scope string, options *armbillingbenefits.CreditsClientListApplicableOptions) (resp azfake.PagerResponder[armbillingbenefits.CreditsClientListApplicableResponse]) + + // NewListByResourceGroupPager is the fake for method CreditsClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armbillingbenefits.CreditsClientListByResourceGroupOptions) (resp azfake.PagerResponder[armbillingbenefits.CreditsClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method CreditsClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armbillingbenefits.CreditsClientListBySubscriptionOptions) (resp azfake.PagerResponder[armbillingbenefits.CreditsClientListBySubscriptionResponse]) + + // BeginUpdate is the fake for method CreditsClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, creditName string, body armbillingbenefits.CreditPatchRequest, options *armbillingbenefits.CreditsClientBeginUpdateOptions) (resp azfake.PollerResponder[armbillingbenefits.CreditsClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewCreditsServerTransport creates a new instance of CreditsServerTransport with the provided implementation. +// The returned CreditsServerTransport instance is connected to an instance of armbillingbenefits.CreditsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewCreditsServerTransport(srv *CreditsServer) *CreditsServerTransport { + return &CreditsServerTransport{ + srv: srv, + beginCancel: newTracker[azfake.PollerResponder[armbillingbenefits.CreditsClientCancelResponse]](), + beginCreate: newTracker[azfake.PollerResponder[armbillingbenefits.CreditsClientCreateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armbillingbenefits.CreditsClientDeleteResponse]](), + newListApplicablePager: newTracker[azfake.PagerResponder[armbillingbenefits.CreditsClientListApplicableResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armbillingbenefits.CreditsClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armbillingbenefits.CreditsClientListBySubscriptionResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armbillingbenefits.CreditsClientUpdateResponse]](), + } +} + +// CreditsServerTransport connects instances of armbillingbenefits.CreditsClient to instances of CreditsServer. +// Don't use this type directly, use NewCreditsServerTransport instead. +type CreditsServerTransport struct { + srv *CreditsServer + beginCancel *tracker[azfake.PollerResponder[armbillingbenefits.CreditsClientCancelResponse]] + beginCreate *tracker[azfake.PollerResponder[armbillingbenefits.CreditsClientCreateResponse]] + beginDelete *tracker[azfake.PollerResponder[armbillingbenefits.CreditsClientDeleteResponse]] + newListApplicablePager *tracker[azfake.PagerResponder[armbillingbenefits.CreditsClientListApplicableResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armbillingbenefits.CreditsClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armbillingbenefits.CreditsClientListBySubscriptionResponse]] + beginUpdate *tracker[azfake.PollerResponder[armbillingbenefits.CreditsClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for CreditsServerTransport. +func (c *CreditsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *CreditsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if creditsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = creditsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "CreditsClient.BeginCancel": + res.resp, res.err = c.dispatchBeginCancel(req) + case "CreditsClient.BeginCreate": + res.resp, res.err = c.dispatchBeginCreate(req) + case "CreditsClient.BeginDelete": + res.resp, res.err = c.dispatchBeginDelete(req) + case "CreditsClient.Get": + res.resp, res.err = c.dispatchGet(req) + case "CreditsClient.NewListApplicablePager": + res.resp, res.err = c.dispatchNewListApplicablePager(req) + case "CreditsClient.NewListByResourceGroupPager": + res.resp, res.err = c.dispatchNewListByResourceGroupPager(req) + case "CreditsClient.NewListBySubscriptionPager": + res.resp, res.err = c.dispatchNewListBySubscriptionPager(req) + case "CreditsClient.BeginUpdate": + res.resp, res.err = c.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *CreditsServerTransport) dispatchBeginCancel(req *http.Request) (*http.Response, error) { + if c.srv.BeginCancel == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCancel not implemented")} + } + beginCancel := c.beginCancel.get(req) + if beginCancel == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/credits/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/cancel` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + creditNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("creditName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginCancel(req.Context(), resourceGroupNameParam, creditNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCancel = &respr + c.beginCancel.add(req, beginCancel) + } + + resp, err := server.PollerResponderNext(beginCancel, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + c.beginCancel.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCancel) { + c.beginCancel.remove(req) + } + + return resp, nil +} + +func (c *CreditsServerTransport) dispatchBeginCreate(req *http.Request) (*http.Response, error) { + if c.srv.BeginCreate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreate not implemented")} + } + beginCreate := c.beginCreate.get(req) + if beginCreate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/credits/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armbillingbenefits.Credit](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + creditNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("creditName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginCreate(req.Context(), resourceGroupNameParam, creditNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreate = &respr + c.beginCreate.add(req, beginCreate) + } + + resp, err := server.PollerResponderNext(beginCreate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + c.beginCreate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreate) { + c.beginCreate.remove(req) + } + + return resp, nil +} + +func (c *CreditsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if c.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := c.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/credits/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + creditNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("creditName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginDelete(req.Context(), resourceGroupNameParam, creditNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + c.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + c.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + c.beginDelete.remove(req) + } + + return resp, nil +} + +func (c *CreditsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if c.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/credits/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + creditNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("creditName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.Get(req.Context(), resourceGroupNameParam, creditNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Credit, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *CreditsServerTransport) dispatchNewListApplicablePager(req *http.Request) (*http.Response, error) { + if c.srv.NewListApplicablePager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListApplicablePager not implemented")} + } + newListApplicablePager := c.newListApplicablePager.get(req) + if newListApplicablePager == nil { + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/applicableCredits` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + scopeParam, err := url.PathUnescape(matches[regex.SubexpIndex("scope")]) + if err != nil { + return nil, err + } + resp := c.srv.NewListApplicablePager(scopeParam, nil) + newListApplicablePager = &resp + c.newListApplicablePager.add(req, newListApplicablePager) + server.PagerResponderInjectNextLinks(newListApplicablePager, req, func(page *armbillingbenefits.CreditsClientListApplicableResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListApplicablePager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + c.newListApplicablePager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListApplicablePager) { + c.newListApplicablePager.remove(req) + } + return resp, nil +} + +func (c *CreditsServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if c.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := c.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/credits` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := c.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + c.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armbillingbenefits.CreditsClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + c.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + c.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (c *CreditsServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if c.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := c.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/credits` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := c.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + c.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armbillingbenefits.CreditsClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + c.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + c.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (c *CreditsServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if c.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := c.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/credits/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armbillingbenefits.CreditPatchRequest](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + creditNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("creditName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginUpdate(req.Context(), resourceGroupNameParam, creditNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + c.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + c.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + c.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to CreditsServerTransport +var creditsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armbillingbenefits/fake/zz_discount_server.go b/test/local/armbillingbenefits/fake/zz_discount_server.go new file mode 100644 index 000000000000..9c93360c2fe1 --- /dev/null +++ b/test/local/armbillingbenefits/fake/zz_discount_server.go @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armbillingbenefits" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// DiscountServer is a fake server for instances of the armbillingbenefits.DiscountClient type. +type DiscountServer struct { + // Get is the fake for method DiscountClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, discountName string, options *armbillingbenefits.DiscountClientGetOptions) (resp azfake.Responder[armbillingbenefits.DiscountClientGetResponse], errResp azfake.ErrorResponder) + + // BeginUpdate is the fake for method DiscountClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, discountName string, body armbillingbenefits.DiscountPatchRequest, options *armbillingbenefits.DiscountClientBeginUpdateOptions) (resp azfake.PollerResponder[armbillingbenefits.DiscountClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewDiscountServerTransport creates a new instance of DiscountServerTransport with the provided implementation. +// The returned DiscountServerTransport instance is connected to an instance of armbillingbenefits.DiscountClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDiscountServerTransport(srv *DiscountServer) *DiscountServerTransport { + return &DiscountServerTransport{ + srv: srv, + beginUpdate: newTracker[azfake.PollerResponder[armbillingbenefits.DiscountClientUpdateResponse]](), + } +} + +// DiscountServerTransport connects instances of armbillingbenefits.DiscountClient to instances of DiscountServer. +// Don't use this type directly, use NewDiscountServerTransport instead. +type DiscountServerTransport struct { + srv *DiscountServer + beginUpdate *tracker[azfake.PollerResponder[armbillingbenefits.DiscountClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for DiscountServerTransport. +func (d *DiscountServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DiscountServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if discountServerTransportInterceptor != nil { + res.resp, res.err, intercepted = discountServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DiscountClient.Get": + res.resp, res.err = d.dispatchGet(req) + case "DiscountClient.BeginUpdate": + res.resp, res.err = d.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DiscountServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/discounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + discountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("discountName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Get(req.Context(), resourceGroupNameParam, discountNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Discount, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DiscountServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if d.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := d.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/discounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armbillingbenefits.DiscountPatchRequest](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + discountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("discountName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.BeginUpdate(req.Context(), resourceGroupNameParam, discountNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + d.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + d.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + d.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to DiscountServerTransport +var discountServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armbillingbenefits/fake/zz_discounts_server.go b/test/local/armbillingbenefits/fake/zz_discounts_server.go new file mode 100644 index 000000000000..2f0a6e87cfff --- /dev/null +++ b/test/local/armbillingbenefits/fake/zz_discounts_server.go @@ -0,0 +1,372 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armbillingbenefits" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// DiscountsServer is a fake server for instances of the armbillingbenefits.DiscountsClient type. +type DiscountsServer struct { + // BeginCancel is the fake for method DiscountsClient.BeginCancel + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginCancel func(ctx context.Context, resourceGroupName string, discountName string, options *armbillingbenefits.DiscountsClientBeginCancelOptions) (resp azfake.PollerResponder[armbillingbenefits.DiscountsClientCancelResponse], errResp azfake.ErrorResponder) + + // BeginCreate is the fake for method DiscountsClient.BeginCreate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreate func(ctx context.Context, resourceGroupName string, discountName string, body armbillingbenefits.Discount, options *armbillingbenefits.DiscountsClientBeginCreateOptions) (resp azfake.PollerResponder[armbillingbenefits.DiscountsClientCreateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method DiscountsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, discountName string, options *armbillingbenefits.DiscountsClientBeginDeleteOptions) (resp azfake.PollerResponder[armbillingbenefits.DiscountsClientDeleteResponse], errResp azfake.ErrorResponder) + + // NewResourceGroupListPager is the fake for method DiscountsClient.NewResourceGroupListPager + // HTTP status codes to indicate success: http.StatusOK + NewResourceGroupListPager func(resourceGroupName string, options *armbillingbenefits.DiscountsClientResourceGroupListOptions) (resp azfake.PagerResponder[armbillingbenefits.DiscountsClientResourceGroupListResponse]) + + // NewScopeListPager is the fake for method DiscountsClient.NewScopeListPager + // HTTP status codes to indicate success: http.StatusOK + NewScopeListPager func(scope string, options *armbillingbenefits.DiscountsClientScopeListOptions) (resp azfake.PagerResponder[armbillingbenefits.DiscountsClientScopeListResponse]) + + // NewSubscriptionListPager is the fake for method DiscountsClient.NewSubscriptionListPager + // HTTP status codes to indicate success: http.StatusOK + NewSubscriptionListPager func(options *armbillingbenefits.DiscountsClientSubscriptionListOptions) (resp azfake.PagerResponder[armbillingbenefits.DiscountsClientSubscriptionListResponse]) +} + +// NewDiscountsServerTransport creates a new instance of DiscountsServerTransport with the provided implementation. +// The returned DiscountsServerTransport instance is connected to an instance of armbillingbenefits.DiscountsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDiscountsServerTransport(srv *DiscountsServer) *DiscountsServerTransport { + return &DiscountsServerTransport{ + srv: srv, + beginCancel: newTracker[azfake.PollerResponder[armbillingbenefits.DiscountsClientCancelResponse]](), + beginCreate: newTracker[azfake.PollerResponder[armbillingbenefits.DiscountsClientCreateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armbillingbenefits.DiscountsClientDeleteResponse]](), + newResourceGroupListPager: newTracker[azfake.PagerResponder[armbillingbenefits.DiscountsClientResourceGroupListResponse]](), + newScopeListPager: newTracker[azfake.PagerResponder[armbillingbenefits.DiscountsClientScopeListResponse]](), + newSubscriptionListPager: newTracker[azfake.PagerResponder[armbillingbenefits.DiscountsClientSubscriptionListResponse]](), + } +} + +// DiscountsServerTransport connects instances of armbillingbenefits.DiscountsClient to instances of DiscountsServer. +// Don't use this type directly, use NewDiscountsServerTransport instead. +type DiscountsServerTransport struct { + srv *DiscountsServer + beginCancel *tracker[azfake.PollerResponder[armbillingbenefits.DiscountsClientCancelResponse]] + beginCreate *tracker[azfake.PollerResponder[armbillingbenefits.DiscountsClientCreateResponse]] + beginDelete *tracker[azfake.PollerResponder[armbillingbenefits.DiscountsClientDeleteResponse]] + newResourceGroupListPager *tracker[azfake.PagerResponder[armbillingbenefits.DiscountsClientResourceGroupListResponse]] + newScopeListPager *tracker[azfake.PagerResponder[armbillingbenefits.DiscountsClientScopeListResponse]] + newSubscriptionListPager *tracker[azfake.PagerResponder[armbillingbenefits.DiscountsClientSubscriptionListResponse]] +} + +// Do implements the policy.Transporter interface for DiscountsServerTransport. +func (d *DiscountsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DiscountsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if discountsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = discountsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DiscountsClient.BeginCancel": + res.resp, res.err = d.dispatchBeginCancel(req) + case "DiscountsClient.BeginCreate": + res.resp, res.err = d.dispatchBeginCreate(req) + case "DiscountsClient.BeginDelete": + res.resp, res.err = d.dispatchBeginDelete(req) + case "DiscountsClient.NewResourceGroupListPager": + res.resp, res.err = d.dispatchNewResourceGroupListPager(req) + case "DiscountsClient.NewScopeListPager": + res.resp, res.err = d.dispatchNewScopeListPager(req) + case "DiscountsClient.NewSubscriptionListPager": + res.resp, res.err = d.dispatchNewSubscriptionListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DiscountsServerTransport) dispatchBeginCancel(req *http.Request) (*http.Response, error) { + if d.srv.BeginCancel == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCancel not implemented")} + } + beginCancel := d.beginCancel.get(req) + if beginCancel == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/discounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/cancel` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + discountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("discountName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.BeginCancel(req.Context(), resourceGroupNameParam, discountNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCancel = &respr + d.beginCancel.add(req, beginCancel) + } + + resp, err := server.PollerResponderNext(beginCancel, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + d.beginCancel.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCancel) { + d.beginCancel.remove(req) + } + + return resp, nil +} + +func (d *DiscountsServerTransport) dispatchBeginCreate(req *http.Request) (*http.Response, error) { + if d.srv.BeginCreate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreate not implemented")} + } + beginCreate := d.beginCreate.get(req) + if beginCreate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/discounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armbillingbenefits.Discount](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + discountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("discountName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.BeginCreate(req.Context(), resourceGroupNameParam, discountNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreate = &respr + d.beginCreate.add(req, beginCreate) + } + + resp, err := server.PollerResponderNext(beginCreate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + d.beginCreate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreate) { + d.beginCreate.remove(req) + } + + return resp, nil +} + +func (d *DiscountsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if d.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := d.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/discounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + discountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("discountName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.BeginDelete(req.Context(), resourceGroupNameParam, discountNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + d.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + d.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + d.beginDelete.remove(req) + } + + return resp, nil +} + +func (d *DiscountsServerTransport) dispatchNewResourceGroupListPager(req *http.Request) (*http.Response, error) { + if d.srv.NewResourceGroupListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewResourceGroupListPager not implemented")} + } + newResourceGroupListPager := d.newResourceGroupListPager.get(req) + if newResourceGroupListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/discounts` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := d.srv.NewResourceGroupListPager(resourceGroupNameParam, nil) + newResourceGroupListPager = &resp + d.newResourceGroupListPager.add(req, newResourceGroupListPager) + server.PagerResponderInjectNextLinks(newResourceGroupListPager, req, func(page *armbillingbenefits.DiscountsClientResourceGroupListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newResourceGroupListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + d.newResourceGroupListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newResourceGroupListPager) { + d.newResourceGroupListPager.remove(req) + } + return resp, nil +} + +func (d *DiscountsServerTransport) dispatchNewScopeListPager(req *http.Request) (*http.Response, error) { + if d.srv.NewScopeListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewScopeListPager not implemented")} + } + newScopeListPager := d.newScopeListPager.get(req) + if newScopeListPager == nil { + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/applicableDiscounts` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + scopeParam, err := url.PathUnescape(matches[regex.SubexpIndex("scope")]) + if err != nil { + return nil, err + } + resp := d.srv.NewScopeListPager(scopeParam, nil) + newScopeListPager = &resp + d.newScopeListPager.add(req, newScopeListPager) + server.PagerResponderInjectNextLinks(newScopeListPager, req, func(page *armbillingbenefits.DiscountsClientScopeListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newScopeListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + d.newScopeListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newScopeListPager) { + d.newScopeListPager.remove(req) + } + return resp, nil +} + +func (d *DiscountsServerTransport) dispatchNewSubscriptionListPager(req *http.Request) (*http.Response, error) { + if d.srv.NewSubscriptionListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewSubscriptionListPager not implemented")} + } + newSubscriptionListPager := d.newSubscriptionListPager.get(req) + if newSubscriptionListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/discounts` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := d.srv.NewSubscriptionListPager(nil) + newSubscriptionListPager = &resp + d.newSubscriptionListPager.add(req, newSubscriptionListPager) + server.PagerResponderInjectNextLinks(newSubscriptionListPager, req, func(page *armbillingbenefits.DiscountsClientSubscriptionListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newSubscriptionListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + d.newSubscriptionListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newSubscriptionListPager) { + d.newSubscriptionListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DiscountsServerTransport +var discountsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armbillingbenefits/fake/zz_freeservices_server.go b/test/local/armbillingbenefits/fake/zz_freeservices_server.go new file mode 100644 index 000000000000..b0ed1640d6c3 --- /dev/null +++ b/test/local/armbillingbenefits/fake/zz_freeservices_server.go @@ -0,0 +1,370 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armbillingbenefits" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// FreeServicesServer is a fake server for instances of the armbillingbenefits.FreeServicesClient type. +type FreeServicesServer struct { + // BeginCreate is the fake for method FreeServicesClient.BeginCreate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreate func(ctx context.Context, resourceGroupName string, freeServiceName string, body armbillingbenefits.FreeServices, options *armbillingbenefits.FreeServicesClientBeginCreateOptions) (resp azfake.PollerResponder[armbillingbenefits.FreeServicesClientCreateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method FreeServicesClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, freeServiceName string, options *armbillingbenefits.FreeServicesClientBeginDeleteOptions) (resp azfake.PollerResponder[armbillingbenefits.FreeServicesClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method FreeServicesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, freeServiceName string, options *armbillingbenefits.FreeServicesClientGetOptions) (resp azfake.Responder[armbillingbenefits.FreeServicesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method FreeServicesClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armbillingbenefits.FreeServicesClientListByResourceGroupOptions) (resp azfake.PagerResponder[armbillingbenefits.FreeServicesClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method FreeServicesClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armbillingbenefits.FreeServicesClientListBySubscriptionOptions) (resp azfake.PagerResponder[armbillingbenefits.FreeServicesClientListBySubscriptionResponse]) + + // BeginUpdate is the fake for method FreeServicesClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, freeServiceName string, body armbillingbenefits.FreeServicesPatchRequest, options *armbillingbenefits.FreeServicesClientBeginUpdateOptions) (resp azfake.PollerResponder[armbillingbenefits.FreeServicesClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewFreeServicesServerTransport creates a new instance of FreeServicesServerTransport with the provided implementation. +// The returned FreeServicesServerTransport instance is connected to an instance of armbillingbenefits.FreeServicesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewFreeServicesServerTransport(srv *FreeServicesServer) *FreeServicesServerTransport { + return &FreeServicesServerTransport{ + srv: srv, + beginCreate: newTracker[azfake.PollerResponder[armbillingbenefits.FreeServicesClientCreateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armbillingbenefits.FreeServicesClientDeleteResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armbillingbenefits.FreeServicesClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armbillingbenefits.FreeServicesClientListBySubscriptionResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armbillingbenefits.FreeServicesClientUpdateResponse]](), + } +} + +// FreeServicesServerTransport connects instances of armbillingbenefits.FreeServicesClient to instances of FreeServicesServer. +// Don't use this type directly, use NewFreeServicesServerTransport instead. +type FreeServicesServerTransport struct { + srv *FreeServicesServer + beginCreate *tracker[azfake.PollerResponder[armbillingbenefits.FreeServicesClientCreateResponse]] + beginDelete *tracker[azfake.PollerResponder[armbillingbenefits.FreeServicesClientDeleteResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armbillingbenefits.FreeServicesClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armbillingbenefits.FreeServicesClientListBySubscriptionResponse]] + beginUpdate *tracker[azfake.PollerResponder[armbillingbenefits.FreeServicesClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for FreeServicesServerTransport. +func (f *FreeServicesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return f.dispatchToMethodFake(req, method) +} + +func (f *FreeServicesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if freeServicesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = freeServicesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "FreeServicesClient.BeginCreate": + res.resp, res.err = f.dispatchBeginCreate(req) + case "FreeServicesClient.BeginDelete": + res.resp, res.err = f.dispatchBeginDelete(req) + case "FreeServicesClient.Get": + res.resp, res.err = f.dispatchGet(req) + case "FreeServicesClient.NewListByResourceGroupPager": + res.resp, res.err = f.dispatchNewListByResourceGroupPager(req) + case "FreeServicesClient.NewListBySubscriptionPager": + res.resp, res.err = f.dispatchNewListBySubscriptionPager(req) + case "FreeServicesClient.BeginUpdate": + res.resp, res.err = f.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (f *FreeServicesServerTransport) dispatchBeginCreate(req *http.Request) (*http.Response, error) { + if f.srv.BeginCreate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreate not implemented")} + } + beginCreate := f.beginCreate.get(req) + if beginCreate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/freeServices/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armbillingbenefits.FreeServices](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + freeServiceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("freeServiceName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.BeginCreate(req.Context(), resourceGroupNameParam, freeServiceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreate = &respr + f.beginCreate.add(req, beginCreate) + } + + resp, err := server.PollerResponderNext(beginCreate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + f.beginCreate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreate) { + f.beginCreate.remove(req) + } + + return resp, nil +} + +func (f *FreeServicesServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if f.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := f.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/freeServices/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + freeServiceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("freeServiceName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.BeginDelete(req.Context(), resourceGroupNameParam, freeServiceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + f.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + f.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + f.beginDelete.remove(req) + } + + return resp, nil +} + +func (f *FreeServicesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if f.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/freeServices/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + freeServiceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("freeServiceName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.Get(req.Context(), resourceGroupNameParam, freeServiceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).FreeServices, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (f *FreeServicesServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if f.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := f.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/freeServices` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := f.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + f.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armbillingbenefits.FreeServicesClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + f.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + f.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (f *FreeServicesServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if f.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := f.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/freeServices` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := f.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + f.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armbillingbenefits.FreeServicesClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + f.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + f.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (f *FreeServicesServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if f.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := f.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/freeServices/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armbillingbenefits.FreeServicesPatchRequest](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + freeServiceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("freeServiceName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.BeginUpdate(req.Context(), resourceGroupNameParam, freeServiceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + f.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + f.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + f.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to FreeServicesServerTransport +var freeServicesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armbillingbenefits/fake/zz_internal.go b/test/local/armbillingbenefits/fake/zz_internal.go new file mode 100644 index 000000000000..504fffe54caa --- /dev/null +++ b/test/local/armbillingbenefits/fake/zz_internal.go @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "reflect" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getOptional[T any](v T) *T { + if reflect.ValueOf(v).IsZero() { + return nil + } + return &v +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func parseOptional[T any](v string, parse func(v string) (T, error)) (*T, error) { + if v == "" { + return nil, nil + } + t, err := parse(v) + if err != nil { + return nil, err + } + return &t, nil +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/local/armbillingbenefits/fake/zz_maccs_server.go b/test/local/armbillingbenefits/fake/zz_maccs_server.go new file mode 100644 index 000000000000..fa6750b36782 --- /dev/null +++ b/test/local/armbillingbenefits/fake/zz_maccs_server.go @@ -0,0 +1,530 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armbillingbenefits" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// MaccsServer is a fake server for instances of the armbillingbenefits.MaccsClient type. +type MaccsServer struct { + // BeginCancel is the fake for method MaccsClient.BeginCancel + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginCancel func(ctx context.Context, resourceGroupName string, maccName string, options *armbillingbenefits.MaccsClientBeginCancelOptions) (resp azfake.PollerResponder[armbillingbenefits.MaccsClientCancelResponse], errResp azfake.ErrorResponder) + + // BeginChargeShortfall is the fake for method MaccsClient.BeginChargeShortfall + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginChargeShortfall func(ctx context.Context, resourceGroupName string, maccName string, body armbillingbenefits.ChargeShortfallRequest, options *armbillingbenefits.MaccsClientBeginChargeShortfallOptions) (resp azfake.PollerResponder[armbillingbenefits.MaccsClientChargeShortfallResponse], errResp azfake.ErrorResponder) + + // BeginCreate is the fake for method MaccsClient.BeginCreate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreate func(ctx context.Context, resourceGroupName string, maccName string, body armbillingbenefits.Macc, options *armbillingbenefits.MaccsClientBeginCreateOptions) (resp azfake.PollerResponder[armbillingbenefits.MaccsClientCreateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method MaccsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, maccName string, options *armbillingbenefits.MaccsClientBeginDeleteOptions) (resp azfake.PollerResponder[armbillingbenefits.MaccsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method MaccsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, maccName string, options *armbillingbenefits.MaccsClientGetOptions) (resp azfake.Responder[armbillingbenefits.MaccsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method MaccsClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armbillingbenefits.MaccsClientListByResourceGroupOptions) (resp azfake.PagerResponder[armbillingbenefits.MaccsClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method MaccsClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armbillingbenefits.MaccsClientListBySubscriptionOptions) (resp azfake.PagerResponder[armbillingbenefits.MaccsClientListBySubscriptionResponse]) + + // BeginUpdate is the fake for method MaccsClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, maccName string, body armbillingbenefits.MaccPatchRequest, options *armbillingbenefits.MaccsClientBeginUpdateOptions) (resp azfake.PollerResponder[armbillingbenefits.MaccsClientUpdateResponse], errResp azfake.ErrorResponder) + + // BeginWriteOff is the fake for method MaccsClient.BeginWriteOff + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginWriteOff func(ctx context.Context, resourceGroupName string, maccName string, options *armbillingbenefits.MaccsClientBeginWriteOffOptions) (resp azfake.PollerResponder[armbillingbenefits.MaccsClientWriteOffResponse], errResp azfake.ErrorResponder) +} + +// NewMaccsServerTransport creates a new instance of MaccsServerTransport with the provided implementation. +// The returned MaccsServerTransport instance is connected to an instance of armbillingbenefits.MaccsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewMaccsServerTransport(srv *MaccsServer) *MaccsServerTransport { + return &MaccsServerTransport{ + srv: srv, + beginCancel: newTracker[azfake.PollerResponder[armbillingbenefits.MaccsClientCancelResponse]](), + beginChargeShortfall: newTracker[azfake.PollerResponder[armbillingbenefits.MaccsClientChargeShortfallResponse]](), + beginCreate: newTracker[azfake.PollerResponder[armbillingbenefits.MaccsClientCreateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armbillingbenefits.MaccsClientDeleteResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armbillingbenefits.MaccsClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armbillingbenefits.MaccsClientListBySubscriptionResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armbillingbenefits.MaccsClientUpdateResponse]](), + beginWriteOff: newTracker[azfake.PollerResponder[armbillingbenefits.MaccsClientWriteOffResponse]](), + } +} + +// MaccsServerTransport connects instances of armbillingbenefits.MaccsClient to instances of MaccsServer. +// Don't use this type directly, use NewMaccsServerTransport instead. +type MaccsServerTransport struct { + srv *MaccsServer + beginCancel *tracker[azfake.PollerResponder[armbillingbenefits.MaccsClientCancelResponse]] + beginChargeShortfall *tracker[azfake.PollerResponder[armbillingbenefits.MaccsClientChargeShortfallResponse]] + beginCreate *tracker[azfake.PollerResponder[armbillingbenefits.MaccsClientCreateResponse]] + beginDelete *tracker[azfake.PollerResponder[armbillingbenefits.MaccsClientDeleteResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armbillingbenefits.MaccsClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armbillingbenefits.MaccsClientListBySubscriptionResponse]] + beginUpdate *tracker[azfake.PollerResponder[armbillingbenefits.MaccsClientUpdateResponse]] + beginWriteOff *tracker[azfake.PollerResponder[armbillingbenefits.MaccsClientWriteOffResponse]] +} + +// Do implements the policy.Transporter interface for MaccsServerTransport. +func (m *MaccsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToMethodFake(req, method) +} + +func (m *MaccsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if maccsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = maccsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "MaccsClient.BeginCancel": + res.resp, res.err = m.dispatchBeginCancel(req) + case "MaccsClient.BeginChargeShortfall": + res.resp, res.err = m.dispatchBeginChargeShortfall(req) + case "MaccsClient.BeginCreate": + res.resp, res.err = m.dispatchBeginCreate(req) + case "MaccsClient.BeginDelete": + res.resp, res.err = m.dispatchBeginDelete(req) + case "MaccsClient.Get": + res.resp, res.err = m.dispatchGet(req) + case "MaccsClient.NewListByResourceGroupPager": + res.resp, res.err = m.dispatchNewListByResourceGroupPager(req) + case "MaccsClient.NewListBySubscriptionPager": + res.resp, res.err = m.dispatchNewListBySubscriptionPager(req) + case "MaccsClient.BeginUpdate": + res.resp, res.err = m.dispatchBeginUpdate(req) + case "MaccsClient.BeginWriteOff": + res.resp, res.err = m.dispatchBeginWriteOff(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *MaccsServerTransport) dispatchBeginCancel(req *http.Request) (*http.Response, error) { + if m.srv.BeginCancel == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCancel not implemented")} + } + beginCancel := m.beginCancel.get(req) + if beginCancel == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/maccs/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/cancel` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + maccNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("maccName")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.BeginCancel(req.Context(), resourceGroupNameParam, maccNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCancel = &respr + m.beginCancel.add(req, beginCancel) + } + + resp, err := server.PollerResponderNext(beginCancel, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + m.beginCancel.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCancel) { + m.beginCancel.remove(req) + } + + return resp, nil +} + +func (m *MaccsServerTransport) dispatchBeginChargeShortfall(req *http.Request) (*http.Response, error) { + if m.srv.BeginChargeShortfall == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginChargeShortfall not implemented")} + } + beginChargeShortfall := m.beginChargeShortfall.get(req) + if beginChargeShortfall == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/maccs/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/chargeShortfall` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armbillingbenefits.ChargeShortfallRequest](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + maccNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("maccName")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.BeginChargeShortfall(req.Context(), resourceGroupNameParam, maccNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginChargeShortfall = &respr + m.beginChargeShortfall.add(req, beginChargeShortfall) + } + + resp, err := server.PollerResponderNext(beginChargeShortfall, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + m.beginChargeShortfall.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginChargeShortfall) { + m.beginChargeShortfall.remove(req) + } + + return resp, nil +} + +func (m *MaccsServerTransport) dispatchBeginCreate(req *http.Request) (*http.Response, error) { + if m.srv.BeginCreate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreate not implemented")} + } + beginCreate := m.beginCreate.get(req) + if beginCreate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/maccs/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armbillingbenefits.Macc](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + maccNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("maccName")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.BeginCreate(req.Context(), resourceGroupNameParam, maccNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreate = &respr + m.beginCreate.add(req, beginCreate) + } + + resp, err := server.PollerResponderNext(beginCreate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + m.beginCreate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreate) { + m.beginCreate.remove(req) + } + + return resp, nil +} + +func (m *MaccsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if m.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := m.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/maccs/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + maccNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("maccName")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.BeginDelete(req.Context(), resourceGroupNameParam, maccNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + m.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + m.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + m.beginDelete.remove(req) + } + + return resp, nil +} + +func (m *MaccsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if m.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/maccs/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + maccNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("maccName")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.Get(req.Context(), resourceGroupNameParam, maccNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Macc, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *MaccsServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if m.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := m.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/maccs` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := m.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + m.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armbillingbenefits.MaccsClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + m.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + m.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (m *MaccsServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if m.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := m.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/maccs` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := m.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + m.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armbillingbenefits.MaccsClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + m.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + m.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (m *MaccsServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if m.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := m.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/maccs/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armbillingbenefits.MaccPatchRequest](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + maccNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("maccName")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.BeginUpdate(req.Context(), resourceGroupNameParam, maccNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + m.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + m.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + m.beginUpdate.remove(req) + } + + return resp, nil +} + +func (m *MaccsServerTransport) dispatchBeginWriteOff(req *http.Request) (*http.Response, error) { + if m.srv.BeginWriteOff == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginWriteOff not implemented")} + } + beginWriteOff := m.beginWriteOff.get(req) + if beginWriteOff == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/maccs/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/writeOff` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + maccNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("maccName")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.BeginWriteOff(req.Context(), resourceGroupNameParam, maccNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginWriteOff = &respr + m.beginWriteOff.add(req, beginWriteOff) + } + + resp, err := server.PollerResponderNext(beginWriteOff, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + m.beginWriteOff.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginWriteOff) { + m.beginWriteOff.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to MaccsServerTransport +var maccsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armbillingbenefits/fake/zz_operations_server.go b/test/local/armbillingbenefits/fake/zz_operations_server.go new file mode 100644 index 000000000000..ce36e58d12fb --- /dev/null +++ b/test/local/armbillingbenefits/fake/zz_operations_server.go @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armbillingbenefits" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "slices" +) + +// OperationsServer is a fake server for instances of the armbillingbenefits.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armbillingbenefits.OperationsClientListOptions) (resp azfake.PagerResponder[armbillingbenefits.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of armbillingbenefits.OperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOperationsServerTransport(srv *OperationsServer) *OperationsServerTransport { + return &OperationsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armbillingbenefits.OperationsClientListResponse]](), + } +} + +// OperationsServerTransport connects instances of armbillingbenefits.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[armbillingbenefits.OperationsClientListResponse]] +} + +// Do implements the policy.Transporter interface for OperationsServerTransport. +func (o *OperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if operationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = operationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OperationsClient.NewListPager": + res.resp, res.err = o.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OperationsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := o.newListPager.get(req) + if newListPager == nil { + resp := o.srv.NewListPager(nil) + newListPager = &resp + o.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armbillingbenefits.OperationsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + o.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + o.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OperationsServerTransport +var operationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armbillingbenefits/fake/zz_reservationorderalias_server.go b/test/local/armbillingbenefits/fake/zz_reservationorderalias_server.go new file mode 100644 index 000000000000..0cd208b8ca9b --- /dev/null +++ b/test/local/armbillingbenefits/fake/zz_reservationorderalias_server.go @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armbillingbenefits" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// ReservationOrderAliasServer is a fake server for instances of the armbillingbenefits.ReservationOrderAliasClient type. +type ReservationOrderAliasServer struct { + // BeginCreate is the fake for method ReservationOrderAliasClient.BeginCreate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreate func(ctx context.Context, reservationOrderAliasName string, body armbillingbenefits.ReservationOrderAliasRequest, options *armbillingbenefits.ReservationOrderAliasClientBeginCreateOptions) (resp azfake.PollerResponder[armbillingbenefits.ReservationOrderAliasClientCreateResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method ReservationOrderAliasClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, reservationOrderAliasName string, options *armbillingbenefits.ReservationOrderAliasClientGetOptions) (resp azfake.Responder[armbillingbenefits.ReservationOrderAliasClientGetResponse], errResp azfake.ErrorResponder) +} + +// NewReservationOrderAliasServerTransport creates a new instance of ReservationOrderAliasServerTransport with the provided implementation. +// The returned ReservationOrderAliasServerTransport instance is connected to an instance of armbillingbenefits.ReservationOrderAliasClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewReservationOrderAliasServerTransport(srv *ReservationOrderAliasServer) *ReservationOrderAliasServerTransport { + return &ReservationOrderAliasServerTransport{ + srv: srv, + beginCreate: newTracker[azfake.PollerResponder[armbillingbenefits.ReservationOrderAliasClientCreateResponse]](), + } +} + +// ReservationOrderAliasServerTransport connects instances of armbillingbenefits.ReservationOrderAliasClient to instances of ReservationOrderAliasServer. +// Don't use this type directly, use NewReservationOrderAliasServerTransport instead. +type ReservationOrderAliasServerTransport struct { + srv *ReservationOrderAliasServer + beginCreate *tracker[azfake.PollerResponder[armbillingbenefits.ReservationOrderAliasClientCreateResponse]] +} + +// Do implements the policy.Transporter interface for ReservationOrderAliasServerTransport. +func (r *ReservationOrderAliasServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return r.dispatchToMethodFake(req, method) +} + +func (r *ReservationOrderAliasServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if reservationOrderAliasServerTransportInterceptor != nil { + res.resp, res.err, intercepted = reservationOrderAliasServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ReservationOrderAliasClient.BeginCreate": + res.resp, res.err = r.dispatchBeginCreate(req) + case "ReservationOrderAliasClient.Get": + res.resp, res.err = r.dispatchGet(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (r *ReservationOrderAliasServerTransport) dispatchBeginCreate(req *http.Request) (*http.Response, error) { + if r.srv.BeginCreate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreate not implemented")} + } + beginCreate := r.beginCreate.get(req) + if beginCreate == nil { + const regexStr = `/providers/Microsoft\.BillingBenefits/reservationOrderAliases/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armbillingbenefits.ReservationOrderAliasRequest](req) + if err != nil { + return nil, err + } + reservationOrderAliasNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("reservationOrderAliasName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.BeginCreate(req.Context(), reservationOrderAliasNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreate = &respr + r.beginCreate.add(req, beginCreate) + } + + resp, err := server.PollerResponderNext(beginCreate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + r.beginCreate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreate) { + r.beginCreate.remove(req) + } + + return resp, nil +} + +func (r *ReservationOrderAliasServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if r.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/providers/Microsoft\.BillingBenefits/reservationOrderAliases/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + reservationOrderAliasNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("reservationOrderAliasName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.Get(req.Context(), reservationOrderAliasNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ReservationOrderAliasResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ReservationOrderAliasServerTransport +var reservationOrderAliasServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armbillingbenefits/fake/zz_rp_server.go b/test/local/armbillingbenefits/fake/zz_rp_server.go new file mode 100644 index 000000000000..787229580b5b --- /dev/null +++ b/test/local/armbillingbenefits/fake/zz_rp_server.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armbillingbenefits" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// RPServer is a fake server for instances of the armbillingbenefits.RPClient type. +type RPServer struct { + // Validate is the fake for method RPClient.Validate + // HTTP status codes to indicate success: http.StatusOK + Validate func(ctx context.Context, body armbillingbenefits.BenefitValidateRequest, options *armbillingbenefits.RPClientValidateOptions) (resp azfake.Responder[armbillingbenefits.RPClientValidateResponse], errResp azfake.ErrorResponder) +} + +// NewRPServerTransport creates a new instance of RPServerTransport with the provided implementation. +// The returned RPServerTransport instance is connected to an instance of armbillingbenefits.RPClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewRPServerTransport(srv *RPServer) *RPServerTransport { + return &RPServerTransport{srv: srv} +} + +// RPServerTransport connects instances of armbillingbenefits.RPClient to instances of RPServer. +// Don't use this type directly, use NewRPServerTransport instead. +type RPServerTransport struct { + srv *RPServer +} + +// Do implements the policy.Transporter interface for RPServerTransport. +func (r *RPServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return r.dispatchToMethodFake(req, method) +} + +func (r *RPServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if rpServerTransportInterceptor != nil { + res.resp, res.err, intercepted = rpServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "RPClient.Validate": + res.resp, res.err = r.dispatchValidate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (r *RPServerTransport) dispatchValidate(req *http.Request) (*http.Response, error) { + if r.srv.Validate == nil { + return nil, &nonRetriableError{errors.New("fake for method Validate not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[armbillingbenefits.BenefitValidateRequest](req) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.Validate(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BenefitValidateResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to RPServerTransport +var rpServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armbillingbenefits/fake/zz_savingsplan_server.go b/test/local/armbillingbenefits/fake/zz_savingsplan_server.go new file mode 100644 index 000000000000..57069ababbb8 --- /dev/null +++ b/test/local/armbillingbenefits/fake/zz_savingsplan_server.go @@ -0,0 +1,344 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armbillingbenefits" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" + "strconv" +) + +// SavingsPlanServer is a fake server for instances of the armbillingbenefits.SavingsPlanClient type. +type SavingsPlanServer struct { + // Get is the fake for method SavingsPlanClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, savingsPlanOrderID string, savingsPlanID string, options *armbillingbenefits.SavingsPlanClientGetOptions) (resp azfake.Responder[armbillingbenefits.SavingsPlanClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method SavingsPlanClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(savingsPlanOrderID string, options *armbillingbenefits.SavingsPlanClientListOptions) (resp azfake.PagerResponder[armbillingbenefits.SavingsPlanClientListResponse]) + + // NewListAllPager is the fake for method SavingsPlanClient.NewListAllPager + // HTTP status codes to indicate success: http.StatusOK + NewListAllPager func(options *armbillingbenefits.SavingsPlanClientListAllOptions) (resp azfake.PagerResponder[armbillingbenefits.SavingsPlanClientListAllResponse]) + + // BeginUpdate is the fake for method SavingsPlanClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, savingsPlanOrderID string, savingsPlanID string, body armbillingbenefits.SavingsPlanUpdateRequest, options *armbillingbenefits.SavingsPlanClientBeginUpdateOptions) (resp azfake.PollerResponder[armbillingbenefits.SavingsPlanClientUpdateResponse], errResp azfake.ErrorResponder) + + // ValidateUpdate is the fake for method SavingsPlanClient.ValidateUpdate + // HTTP status codes to indicate success: http.StatusOK + ValidateUpdate func(ctx context.Context, savingsPlanOrderID string, savingsPlanID string, body armbillingbenefits.SavingsPlanUpdateValidateRequest, options *armbillingbenefits.SavingsPlanClientValidateUpdateOptions) (resp azfake.Responder[armbillingbenefits.SavingsPlanClientValidateUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewSavingsPlanServerTransport creates a new instance of SavingsPlanServerTransport with the provided implementation. +// The returned SavingsPlanServerTransport instance is connected to an instance of armbillingbenefits.SavingsPlanClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSavingsPlanServerTransport(srv *SavingsPlanServer) *SavingsPlanServerTransport { + return &SavingsPlanServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armbillingbenefits.SavingsPlanClientListResponse]](), + newListAllPager: newTracker[azfake.PagerResponder[armbillingbenefits.SavingsPlanClientListAllResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armbillingbenefits.SavingsPlanClientUpdateResponse]](), + } +} + +// SavingsPlanServerTransport connects instances of armbillingbenefits.SavingsPlanClient to instances of SavingsPlanServer. +// Don't use this type directly, use NewSavingsPlanServerTransport instead. +type SavingsPlanServerTransport struct { + srv *SavingsPlanServer + newListPager *tracker[azfake.PagerResponder[armbillingbenefits.SavingsPlanClientListResponse]] + newListAllPager *tracker[azfake.PagerResponder[armbillingbenefits.SavingsPlanClientListAllResponse]] + beginUpdate *tracker[azfake.PollerResponder[armbillingbenefits.SavingsPlanClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for SavingsPlanServerTransport. +func (s *SavingsPlanServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *SavingsPlanServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if savingsPlanServerTransportInterceptor != nil { + res.resp, res.err, intercepted = savingsPlanServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SavingsPlanClient.Get": + res.resp, res.err = s.dispatchGet(req) + case "SavingsPlanClient.NewListPager": + res.resp, res.err = s.dispatchNewListPager(req) + case "SavingsPlanClient.NewListAllPager": + res.resp, res.err = s.dispatchNewListAllPager(req) + case "SavingsPlanClient.BeginUpdate": + res.resp, res.err = s.dispatchBeginUpdate(req) + case "SavingsPlanClient.ValidateUpdate": + res.resp, res.err = s.dispatchValidateUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *SavingsPlanServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if s.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/providers/Microsoft\.BillingBenefits/savingsPlanOrders/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/savingsPlans/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + savingsPlanOrderIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("savingsPlanOrderId")]) + if err != nil { + return nil, err + } + savingsPlanIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("savingsPlanId")]) + if err != nil { + return nil, err + } + expandParam := getOptional(qp.Get("$expand")) + var options *armbillingbenefits.SavingsPlanClientGetOptions + if expandParam != nil { + options = &armbillingbenefits.SavingsPlanClientGetOptions{ + Expand: expandParam, + } + } + respr, errRespr := s.srv.Get(req.Context(), savingsPlanOrderIDParam, savingsPlanIDParam, options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).SavingsPlanModel, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SavingsPlanServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if s.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := s.newListPager.get(req) + if newListPager == nil { + const regexStr = `/providers/Microsoft\.BillingBenefits/savingsPlanOrders/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/savingsPlans` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + savingsPlanOrderIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("savingsPlanOrderId")]) + if err != nil { + return nil, err + } + resp := s.srv.NewListPager(savingsPlanOrderIDParam, nil) + newListPager = &resp + s.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armbillingbenefits.SavingsPlanClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + s.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + s.newListPager.remove(req) + } + return resp, nil +} + +func (s *SavingsPlanServerTransport) dispatchNewListAllPager(req *http.Request) (*http.Response, error) { + if s.srv.NewListAllPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListAllPager not implemented")} + } + newListAllPager := s.newListAllPager.get(req) + if newListAllPager == nil { + qp := req.URL.Query() + filterParam := getOptional(qp.Get("$filter")) + orderbyParam := getOptional(qp.Get("$orderby")) + refreshSummaryParam := getOptional(qp.Get("refreshSummary")) + skiptokenParam, err := parseOptional(qp.Get("$skiptoken"), func(v string) (float32, error) { + p, parseErr := strconv.ParseFloat(v, 32) + if parseErr != nil { + return 0, parseErr + } + return float32(p), nil + }) + if err != nil { + return nil, err + } + selectedStateParam := getOptional(qp.Get("selectedState")) + takeParam, err := parseOptional(qp.Get("take"), func(v string) (float32, error) { + p, parseErr := strconv.ParseFloat(v, 32) + if parseErr != nil { + return 0, parseErr + } + return float32(p), nil + }) + if err != nil { + return nil, err + } + var options *armbillingbenefits.SavingsPlanClientListAllOptions + if filterParam != nil || orderbyParam != nil || refreshSummaryParam != nil || skiptokenParam != nil || selectedStateParam != nil || takeParam != nil { + options = &armbillingbenefits.SavingsPlanClientListAllOptions{ + Filter: filterParam, + Orderby: orderbyParam, + RefreshSummary: refreshSummaryParam, + Skiptoken: skiptokenParam, + SelectedState: selectedStateParam, + Take: takeParam, + } + } + resp := s.srv.NewListAllPager(options) + newListAllPager = &resp + s.newListAllPager.add(req, newListAllPager) + server.PagerResponderInjectNextLinks(newListAllPager, req, func(page *armbillingbenefits.SavingsPlanClientListAllResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListAllPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + s.newListAllPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListAllPager) { + s.newListAllPager.remove(req) + } + return resp, nil +} + +func (s *SavingsPlanServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if s.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := s.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/providers/Microsoft\.BillingBenefits/savingsPlanOrders/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/savingsPlans/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armbillingbenefits.SavingsPlanUpdateRequest](req) + if err != nil { + return nil, err + } + savingsPlanOrderIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("savingsPlanOrderId")]) + if err != nil { + return nil, err + } + savingsPlanIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("savingsPlanId")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.BeginUpdate(req.Context(), savingsPlanOrderIDParam, savingsPlanIDParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + s.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + s.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + s.beginUpdate.remove(req) + } + + return resp, nil +} + +func (s *SavingsPlanServerTransport) dispatchValidateUpdate(req *http.Request) (*http.Response, error) { + if s.srv.ValidateUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method ValidateUpdate not implemented")} + } + const regexStr = `/providers/Microsoft\.BillingBenefits/savingsPlanOrders/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/savingsPlans/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/validate` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armbillingbenefits.SavingsPlanUpdateValidateRequest](req) + if err != nil { + return nil, err + } + savingsPlanOrderIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("savingsPlanOrderId")]) + if err != nil { + return nil, err + } + savingsPlanIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("savingsPlanId")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.ValidateUpdate(req.Context(), savingsPlanOrderIDParam, savingsPlanIDParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).SavingsPlanValidateResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SavingsPlanServerTransport +var savingsPlanServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armbillingbenefits/fake/zz_savingsplanorder_server.go b/test/local/armbillingbenefits/fake/zz_savingsplanorder_server.go new file mode 100644 index 000000000000..e43066372e2e --- /dev/null +++ b/test/local/armbillingbenefits/fake/zz_savingsplanorder_server.go @@ -0,0 +1,194 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armbillingbenefits" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// SavingsPlanOrderServer is a fake server for instances of the armbillingbenefits.SavingsPlanOrderClient type. +type SavingsPlanOrderServer struct { + // Elevate is the fake for method SavingsPlanOrderClient.Elevate + // HTTP status codes to indicate success: http.StatusOK + Elevate func(ctx context.Context, savingsPlanOrderID string, options *armbillingbenefits.SavingsPlanOrderClientElevateOptions) (resp azfake.Responder[armbillingbenefits.SavingsPlanOrderClientElevateResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method SavingsPlanOrderClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, savingsPlanOrderID string, options *armbillingbenefits.SavingsPlanOrderClientGetOptions) (resp azfake.Responder[armbillingbenefits.SavingsPlanOrderClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method SavingsPlanOrderClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armbillingbenefits.SavingsPlanOrderClientListOptions) (resp azfake.PagerResponder[armbillingbenefits.SavingsPlanOrderClientListResponse]) +} + +// NewSavingsPlanOrderServerTransport creates a new instance of SavingsPlanOrderServerTransport with the provided implementation. +// The returned SavingsPlanOrderServerTransport instance is connected to an instance of armbillingbenefits.SavingsPlanOrderClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSavingsPlanOrderServerTransport(srv *SavingsPlanOrderServer) *SavingsPlanOrderServerTransport { + return &SavingsPlanOrderServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armbillingbenefits.SavingsPlanOrderClientListResponse]](), + } +} + +// SavingsPlanOrderServerTransport connects instances of armbillingbenefits.SavingsPlanOrderClient to instances of SavingsPlanOrderServer. +// Don't use this type directly, use NewSavingsPlanOrderServerTransport instead. +type SavingsPlanOrderServerTransport struct { + srv *SavingsPlanOrderServer + newListPager *tracker[azfake.PagerResponder[armbillingbenefits.SavingsPlanOrderClientListResponse]] +} + +// Do implements the policy.Transporter interface for SavingsPlanOrderServerTransport. +func (s *SavingsPlanOrderServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *SavingsPlanOrderServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if savingsPlanOrderServerTransportInterceptor != nil { + res.resp, res.err, intercepted = savingsPlanOrderServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SavingsPlanOrderClient.Elevate": + res.resp, res.err = s.dispatchElevate(req) + case "SavingsPlanOrderClient.Get": + res.resp, res.err = s.dispatchGet(req) + case "SavingsPlanOrderClient.NewListPager": + res.resp, res.err = s.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *SavingsPlanOrderServerTransport) dispatchElevate(req *http.Request) (*http.Response, error) { + if s.srv.Elevate == nil { + return nil, &nonRetriableError{errors.New("fake for method Elevate not implemented")} + } + const regexStr = `/providers/Microsoft\.BillingBenefits/savingsPlanOrders/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/elevate` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + savingsPlanOrderIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("savingsPlanOrderId")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Elevate(req.Context(), savingsPlanOrderIDParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RoleAssignmentEntity, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SavingsPlanOrderServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if s.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/providers/Microsoft\.BillingBenefits/savingsPlanOrders/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + savingsPlanOrderIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("savingsPlanOrderId")]) + if err != nil { + return nil, err + } + expandParam := getOptional(qp.Get("$expand")) + var options *armbillingbenefits.SavingsPlanOrderClientGetOptions + if expandParam != nil { + options = &armbillingbenefits.SavingsPlanOrderClientGetOptions{ + Expand: expandParam, + } + } + respr, errRespr := s.srv.Get(req.Context(), savingsPlanOrderIDParam, options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).SavingsPlanOrderModel, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SavingsPlanOrderServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if s.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := s.newListPager.get(req) + if newListPager == nil { + resp := s.srv.NewListPager(nil) + newListPager = &resp + s.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armbillingbenefits.SavingsPlanOrderClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + s.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + s.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SavingsPlanOrderServerTransport +var savingsPlanOrderServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armbillingbenefits/fake/zz_savingsplanorderalias_server.go b/test/local/armbillingbenefits/fake/zz_savingsplanorderalias_server.go new file mode 100644 index 000000000000..ddbc96989a45 --- /dev/null +++ b/test/local/armbillingbenefits/fake/zz_savingsplanorderalias_server.go @@ -0,0 +1,167 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armbillingbenefits" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// SavingsPlanOrderAliasServer is a fake server for instances of the armbillingbenefits.SavingsPlanOrderAliasClient type. +type SavingsPlanOrderAliasServer struct { + // BeginCreate is the fake for method SavingsPlanOrderAliasClient.BeginCreate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreate func(ctx context.Context, savingsPlanOrderAliasName string, body armbillingbenefits.SavingsPlanOrderAliasModel, options *armbillingbenefits.SavingsPlanOrderAliasClientBeginCreateOptions) (resp azfake.PollerResponder[armbillingbenefits.SavingsPlanOrderAliasClientCreateResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method SavingsPlanOrderAliasClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, savingsPlanOrderAliasName string, options *armbillingbenefits.SavingsPlanOrderAliasClientGetOptions) (resp azfake.Responder[armbillingbenefits.SavingsPlanOrderAliasClientGetResponse], errResp azfake.ErrorResponder) +} + +// NewSavingsPlanOrderAliasServerTransport creates a new instance of SavingsPlanOrderAliasServerTransport with the provided implementation. +// The returned SavingsPlanOrderAliasServerTransport instance is connected to an instance of armbillingbenefits.SavingsPlanOrderAliasClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSavingsPlanOrderAliasServerTransport(srv *SavingsPlanOrderAliasServer) *SavingsPlanOrderAliasServerTransport { + return &SavingsPlanOrderAliasServerTransport{ + srv: srv, + beginCreate: newTracker[azfake.PollerResponder[armbillingbenefits.SavingsPlanOrderAliasClientCreateResponse]](), + } +} + +// SavingsPlanOrderAliasServerTransport connects instances of armbillingbenefits.SavingsPlanOrderAliasClient to instances of SavingsPlanOrderAliasServer. +// Don't use this type directly, use NewSavingsPlanOrderAliasServerTransport instead. +type SavingsPlanOrderAliasServerTransport struct { + srv *SavingsPlanOrderAliasServer + beginCreate *tracker[azfake.PollerResponder[armbillingbenefits.SavingsPlanOrderAliasClientCreateResponse]] +} + +// Do implements the policy.Transporter interface for SavingsPlanOrderAliasServerTransport. +func (s *SavingsPlanOrderAliasServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *SavingsPlanOrderAliasServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if savingsPlanOrderAliasServerTransportInterceptor != nil { + res.resp, res.err, intercepted = savingsPlanOrderAliasServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SavingsPlanOrderAliasClient.BeginCreate": + res.resp, res.err = s.dispatchBeginCreate(req) + case "SavingsPlanOrderAliasClient.Get": + res.resp, res.err = s.dispatchGet(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *SavingsPlanOrderAliasServerTransport) dispatchBeginCreate(req *http.Request) (*http.Response, error) { + if s.srv.BeginCreate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreate not implemented")} + } + beginCreate := s.beginCreate.get(req) + if beginCreate == nil { + const regexStr = `/providers/Microsoft\.BillingBenefits/savingsPlanOrderAliases/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armbillingbenefits.SavingsPlanOrderAliasModel](req) + if err != nil { + return nil, err + } + savingsPlanOrderAliasNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("savingsPlanOrderAliasName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.BeginCreate(req.Context(), savingsPlanOrderAliasNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreate = &respr + s.beginCreate.add(req, beginCreate) + } + + resp, err := server.PollerResponderNext(beginCreate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + s.beginCreate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreate) { + s.beginCreate.remove(req) + } + + return resp, nil +} + +func (s *SavingsPlanOrderAliasServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if s.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/providers/Microsoft\.BillingBenefits/savingsPlanOrderAliases/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + savingsPlanOrderAliasNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("savingsPlanOrderAliasName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Get(req.Context(), savingsPlanOrderAliasNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).SavingsPlanOrderAliasModel, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SavingsPlanOrderAliasServerTransport +var savingsPlanOrderAliasServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armbillingbenefits/fake/zz_sellerresource_server.go b/test/local/armbillingbenefits/fake/zz_sellerresource_server.go new file mode 100644 index 000000000000..6b4fa74d91dc --- /dev/null +++ b/test/local/armbillingbenefits/fake/zz_sellerresource_server.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armbillingbenefits" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// SellerResourceServer is a fake server for instances of the armbillingbenefits.SellerResourceClient type. +type SellerResourceServer struct { + // List is the fake for method SellerResourceClient.List + // HTTP status codes to indicate success: http.StatusOK + List func(ctx context.Context, body armbillingbenefits.SellerResourceListRequest, options *armbillingbenefits.SellerResourceClientListOptions) (resp azfake.Responder[armbillingbenefits.SellerResourceClientListResponse], errResp azfake.ErrorResponder) +} + +// NewSellerResourceServerTransport creates a new instance of SellerResourceServerTransport with the provided implementation. +// The returned SellerResourceServerTransport instance is connected to an instance of armbillingbenefits.SellerResourceClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSellerResourceServerTransport(srv *SellerResourceServer) *SellerResourceServerTransport { + return &SellerResourceServerTransport{srv: srv} +} + +// SellerResourceServerTransport connects instances of armbillingbenefits.SellerResourceClient to instances of SellerResourceServer. +// Don't use this type directly, use NewSellerResourceServerTransport instead. +type SellerResourceServerTransport struct { + srv *SellerResourceServer +} + +// Do implements the policy.Transporter interface for SellerResourceServerTransport. +func (s *SellerResourceServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *SellerResourceServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if sellerResourceServerTransportInterceptor != nil { + res.resp, res.err, intercepted = sellerResourceServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SellerResourceClient.List": + res.resp, res.err = s.dispatchList(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *SellerResourceServerTransport) dispatchList(req *http.Request) (*http.Response, error) { + if s.srv.List == nil { + return nil, &nonRetriableError{errors.New("fake for method List not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[armbillingbenefits.SellerResourceListRequest](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.List(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).MaccArray, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SellerResourceServerTransport +var sellerResourceServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armbillingbenefits/fake/zz_server_factory.go b/test/local/armbillingbenefits/fake/zz_server_factory.go new file mode 100644 index 000000000000..fe0354b0dbb8 --- /dev/null +++ b/test/local/armbillingbenefits/fake/zz_server_factory.go @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armbillingbenefits.ClientFactory type. +type ServerFactory struct { + // ApplicableMaccsServer contains the fakes for client ApplicableMaccsClient + ApplicableMaccsServer ApplicableMaccsServer + + // ConditionalCreditContributorsServer contains the fakes for client ConditionalCreditContributorsClient + ConditionalCreditContributorsServer ConditionalCreditContributorsServer + + // ConditionalCreditsServer contains the fakes for client ConditionalCreditsClient + ConditionalCreditsServer ConditionalCreditsServer + + // ContributorsServer contains the fakes for client ContributorsClient + ContributorsServer ContributorsServer + + // CreditsServer contains the fakes for client CreditsClient + CreditsServer CreditsServer + + // DiscountServer contains the fakes for client DiscountClient + DiscountServer DiscountServer + + // DiscountsServer contains the fakes for client DiscountsClient + DiscountsServer DiscountsServer + + // FreeServicesServer contains the fakes for client FreeServicesClient + FreeServicesServer FreeServicesServer + + // MaccsServer contains the fakes for client MaccsClient + MaccsServer MaccsServer + + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer + + // RPServer contains the fakes for client RPClient + RPServer RPServer + + // ReservationOrderAliasServer contains the fakes for client ReservationOrderAliasClient + ReservationOrderAliasServer ReservationOrderAliasServer + + // SavingsPlanServer contains the fakes for client SavingsPlanClient + SavingsPlanServer SavingsPlanServer + + // SavingsPlanOrderAliasServer contains the fakes for client SavingsPlanOrderAliasClient + SavingsPlanOrderAliasServer SavingsPlanOrderAliasServer + + // SavingsPlanOrderServer contains the fakes for client SavingsPlanOrderClient + SavingsPlanOrderServer SavingsPlanOrderServer + + // SellerResourceServer contains the fakes for client SellerResourceClient + SellerResourceServer SellerResourceServer + + // SourcesServer contains the fakes for client SourcesClient + SourcesServer SourcesServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armbillingbenefits.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of armbillingbenefits.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trApplicableMaccsServer *ApplicableMaccsServerTransport + trConditionalCreditContributorsServer *ConditionalCreditContributorsServerTransport + trConditionalCreditsServer *ConditionalCreditsServerTransport + trContributorsServer *ContributorsServerTransport + trCreditsServer *CreditsServerTransport + trDiscountServer *DiscountServerTransport + trDiscountsServer *DiscountsServerTransport + trFreeServicesServer *FreeServicesServerTransport + trMaccsServer *MaccsServerTransport + trOperationsServer *OperationsServerTransport + trRPServer *RPServerTransport + trReservationOrderAliasServer *ReservationOrderAliasServerTransport + trSavingsPlanServer *SavingsPlanServerTransport + trSavingsPlanOrderAliasServer *SavingsPlanOrderAliasServerTransport + trSavingsPlanOrderServer *SavingsPlanOrderServerTransport + trSellerResourceServer *SellerResourceServerTransport + trSourcesServer *SourcesServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "ApplicableMaccsClient": + initServer(&s.trMu, &s.trApplicableMaccsServer, func() *ApplicableMaccsServerTransport { + return NewApplicableMaccsServerTransport(&s.srv.ApplicableMaccsServer) + }) + resp, err = s.trApplicableMaccsServer.Do(req) + case "ConditionalCreditContributorsClient": + initServer(&s.trMu, &s.trConditionalCreditContributorsServer, func() *ConditionalCreditContributorsServerTransport { + return NewConditionalCreditContributorsServerTransport(&s.srv.ConditionalCreditContributorsServer) + }) + resp, err = s.trConditionalCreditContributorsServer.Do(req) + case "ConditionalCreditsClient": + initServer(&s.trMu, &s.trConditionalCreditsServer, func() *ConditionalCreditsServerTransport { + return NewConditionalCreditsServerTransport(&s.srv.ConditionalCreditsServer) + }) + resp, err = s.trConditionalCreditsServer.Do(req) + case "ContributorsClient": + initServer(&s.trMu, &s.trContributorsServer, func() *ContributorsServerTransport { return NewContributorsServerTransport(&s.srv.ContributorsServer) }) + resp, err = s.trContributorsServer.Do(req) + case "CreditsClient": + initServer(&s.trMu, &s.trCreditsServer, func() *CreditsServerTransport { return NewCreditsServerTransport(&s.srv.CreditsServer) }) + resp, err = s.trCreditsServer.Do(req) + case "DiscountClient": + initServer(&s.trMu, &s.trDiscountServer, func() *DiscountServerTransport { return NewDiscountServerTransport(&s.srv.DiscountServer) }) + resp, err = s.trDiscountServer.Do(req) + case "DiscountsClient": + initServer(&s.trMu, &s.trDiscountsServer, func() *DiscountsServerTransport { return NewDiscountsServerTransport(&s.srv.DiscountsServer) }) + resp, err = s.trDiscountsServer.Do(req) + case "FreeServicesClient": + initServer(&s.trMu, &s.trFreeServicesServer, func() *FreeServicesServerTransport { return NewFreeServicesServerTransport(&s.srv.FreeServicesServer) }) + resp, err = s.trFreeServicesServer.Do(req) + case "MaccsClient": + initServer(&s.trMu, &s.trMaccsServer, func() *MaccsServerTransport { return NewMaccsServerTransport(&s.srv.MaccsServer) }) + resp, err = s.trMaccsServer.Do(req) + case "OperationsClient": + initServer(&s.trMu, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + resp, err = s.trOperationsServer.Do(req) + case "RPClient": + initServer(&s.trMu, &s.trRPServer, func() *RPServerTransport { return NewRPServerTransport(&s.srv.RPServer) }) + resp, err = s.trRPServer.Do(req) + case "ReservationOrderAliasClient": + initServer(&s.trMu, &s.trReservationOrderAliasServer, func() *ReservationOrderAliasServerTransport { + return NewReservationOrderAliasServerTransport(&s.srv.ReservationOrderAliasServer) + }) + resp, err = s.trReservationOrderAliasServer.Do(req) + case "SavingsPlanClient": + initServer(&s.trMu, &s.trSavingsPlanServer, func() *SavingsPlanServerTransport { return NewSavingsPlanServerTransport(&s.srv.SavingsPlanServer) }) + resp, err = s.trSavingsPlanServer.Do(req) + case "SavingsPlanOrderAliasClient": + initServer(&s.trMu, &s.trSavingsPlanOrderAliasServer, func() *SavingsPlanOrderAliasServerTransport { + return NewSavingsPlanOrderAliasServerTransport(&s.srv.SavingsPlanOrderAliasServer) + }) + resp, err = s.trSavingsPlanOrderAliasServer.Do(req) + case "SavingsPlanOrderClient": + initServer(&s.trMu, &s.trSavingsPlanOrderServer, func() *SavingsPlanOrderServerTransport { + return NewSavingsPlanOrderServerTransport(&s.srv.SavingsPlanOrderServer) + }) + resp, err = s.trSavingsPlanOrderServer.Do(req) + case "SellerResourceClient": + initServer(&s.trMu, &s.trSellerResourceServer, func() *SellerResourceServerTransport { + return NewSellerResourceServerTransport(&s.srv.SellerResourceServer) + }) + resp, err = s.trSellerResourceServer.Do(req) + case "SourcesClient": + initServer(&s.trMu, &s.trSourcesServer, func() *SourcesServerTransport { return NewSourcesServerTransport(&s.srv.SourcesServer) }) + resp, err = s.trSourcesServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} diff --git a/test/local/armbillingbenefits/fake/zz_sources_server.go b/test/local/armbillingbenefits/fake/zz_sources_server.go new file mode 100644 index 000000000000..e001fe106b27 --- /dev/null +++ b/test/local/armbillingbenefits/fake/zz_sources_server.go @@ -0,0 +1,310 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armbillingbenefits" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// SourcesServer is a fake server for instances of the armbillingbenefits.SourcesClient type. +type SourcesServer struct { + // Create is the fake for method SourcesClient.Create + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + Create func(ctx context.Context, resourceGroupName string, creditName string, sourceName string, body armbillingbenefits.CreditSource, options *armbillingbenefits.SourcesClientCreateOptions) (resp azfake.Responder[armbillingbenefits.SourcesClientCreateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method SourcesClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceGroupName string, creditName string, sourceName string, options *armbillingbenefits.SourcesClientDeleteOptions) (resp azfake.Responder[armbillingbenefits.SourcesClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method SourcesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, creditName string, sourceName string, options *armbillingbenefits.SourcesClientGetOptions) (resp azfake.Responder[armbillingbenefits.SourcesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByCreditPager is the fake for method SourcesClient.NewListByCreditPager + // HTTP status codes to indicate success: http.StatusOK + NewListByCreditPager func(resourceGroupName string, creditName string, options *armbillingbenefits.SourcesClientListByCreditOptions) (resp azfake.PagerResponder[armbillingbenefits.SourcesClientListByCreditResponse]) + + // Update is the fake for method SourcesClient.Update + // HTTP status codes to indicate success: http.StatusOK + Update func(ctx context.Context, resourceGroupName string, creditName string, sourceName string, body armbillingbenefits.CreditSourcePatchRequest, options *armbillingbenefits.SourcesClientUpdateOptions) (resp azfake.Responder[armbillingbenefits.SourcesClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewSourcesServerTransport creates a new instance of SourcesServerTransport with the provided implementation. +// The returned SourcesServerTransport instance is connected to an instance of armbillingbenefits.SourcesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSourcesServerTransport(srv *SourcesServer) *SourcesServerTransport { + return &SourcesServerTransport{ + srv: srv, + newListByCreditPager: newTracker[azfake.PagerResponder[armbillingbenefits.SourcesClientListByCreditResponse]](), + } +} + +// SourcesServerTransport connects instances of armbillingbenefits.SourcesClient to instances of SourcesServer. +// Don't use this type directly, use NewSourcesServerTransport instead. +type SourcesServerTransport struct { + srv *SourcesServer + newListByCreditPager *tracker[azfake.PagerResponder[armbillingbenefits.SourcesClientListByCreditResponse]] +} + +// Do implements the policy.Transporter interface for SourcesServerTransport. +func (s *SourcesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *SourcesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if sourcesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = sourcesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SourcesClient.Create": + res.resp, res.err = s.dispatchCreate(req) + case "SourcesClient.Delete": + res.resp, res.err = s.dispatchDelete(req) + case "SourcesClient.Get": + res.resp, res.err = s.dispatchGet(req) + case "SourcesClient.NewListByCreditPager": + res.resp, res.err = s.dispatchNewListByCreditPager(req) + case "SourcesClient.Update": + res.resp, res.err = s.dispatchUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *SourcesServerTransport) dispatchCreate(req *http.Request) (*http.Response, error) { + if s.srv.Create == nil { + return nil, &nonRetriableError{errors.New("fake for method Create not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/credits/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/sources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armbillingbenefits.CreditSource](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + creditNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("creditName")]) + if err != nil { + return nil, err + } + sourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("sourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Create(req.Context(), resourceGroupNameParam, creditNameParam, sourceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CreditSource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SourcesServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if s.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/credits/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/sources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + creditNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("creditName")]) + if err != nil { + return nil, err + } + sourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("sourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Delete(req.Context(), resourceGroupNameParam, creditNameParam, sourceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SourcesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if s.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/credits/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/sources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + creditNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("creditName")]) + if err != nil { + return nil, err + } + sourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("sourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Get(req.Context(), resourceGroupNameParam, creditNameParam, sourceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CreditSource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SourcesServerTransport) dispatchNewListByCreditPager(req *http.Request) (*http.Response, error) { + if s.srv.NewListByCreditPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByCreditPager not implemented")} + } + newListByCreditPager := s.newListByCreditPager.get(req) + if newListByCreditPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/credits/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/sources` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + creditNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("creditName")]) + if err != nil { + return nil, err + } + resp := s.srv.NewListByCreditPager(resourceGroupNameParam, creditNameParam, nil) + newListByCreditPager = &resp + s.newListByCreditPager.add(req, newListByCreditPager) + server.PagerResponderInjectNextLinks(newListByCreditPager, req, func(page *armbillingbenefits.SourcesClientListByCreditResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByCreditPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + s.newListByCreditPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByCreditPager) { + s.newListByCreditPager.remove(req) + } + return resp, nil +} + +func (s *SourcesServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) { + if s.srv.Update == nil { + return nil, &nonRetriableError{errors.New("fake for method Update not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.BillingBenefits/credits/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/sources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armbillingbenefits.CreditSourcePatchRequest](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + creditNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("creditName")]) + if err != nil { + return nil, err + } + sourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("sourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Update(req.Context(), resourceGroupNameParam, creditNameParam, sourceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CreditSource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SourcesServerTransport +var sourcesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armbillingbenefits/go.mod b/test/local/armbillingbenefits/go.mod new file mode 100644 index 000000000000..16d1f9e43568 --- /dev/null +++ b/test/local/armbillingbenefits/go.mod @@ -0,0 +1,11 @@ +module armbillingbenefits + +go 1.25.0 + +require github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect +) diff --git a/test/local/armbillingbenefits/go.sum b/test/local/armbillingbenefits/go.sum new file mode 100644 index 000000000000..3fdb64caf441 --- /dev/null +++ b/test/local/armbillingbenefits/go.sum @@ -0,0 +1,16 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/local/armbillingbenefits/testdata/_metadata.json b/test/local/armbillingbenefits/testdata/_metadata.json new file mode 100644 index 000000000000..88cd7138861b --- /dev/null +++ b/test/local/armbillingbenefits/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Microsoft.BillingBenefits": "2025-12-01-preview" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/local/armbillingbenefits/zz_applicablemaccs_client.go b/test/local/armbillingbenefits/zz_applicablemaccs_client.go new file mode 100644 index 000000000000..60408c9f28b4 --- /dev/null +++ b/test/local/armbillingbenefits/zz_applicablemaccs_client.go @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armbillingbenefits + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ApplicableMaccsClient contains the methods for the ApplicableMaccs group. +// Don't use this type directly, use NewApplicableMaccsClient() instead. +// +// Generated from API version 2025-12-01-preview +type ApplicableMaccsClient struct { + internal *arm.Client +} + +// NewApplicableMaccsClient creates a new instance of ApplicableMaccsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewApplicableMaccsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*ApplicableMaccsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ApplicableMaccsClient{ + internal: cl, + } + return client, nil +} + +// NewListPager - List maccs that are applicable for a given billing account. +// - billingAccountID - The billing account Id at which the benefits are listed. Accepted format is: {rootId:orgId}. +// - options - ApplicableMaccsClientListOptions contains the optional parameters for the ApplicableMaccsClient.NewListPager +// method. +func (client *ApplicableMaccsClient) NewListPager(billingAccountID string, options *ApplicableMaccsClientListOptions) *runtime.Pager[ApplicableMaccsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ApplicableMaccsClientListResponse]{ + More: func(page ApplicableMaccsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ApplicableMaccsClientListResponse) (ApplicableMaccsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ApplicableMaccsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, billingAccountID, options) + }, nil) + if err != nil { + return ApplicableMaccsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ApplicableMaccsClient) listCreateRequest(ctx context.Context, billingAccountID string, _ *ApplicableMaccsClientListOptions) (*policy.Request, error) { + urlPath := "/providers/microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.BillingBenefits/applicableMaccs" + if billingAccountID == "" { + return nil, errors.New("parameter billingAccountID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{billingAccountId}", url.PathEscape(billingAccountID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ApplicableMaccsClient) listHandleResponse(resp *http.Response) (ApplicableMaccsClientListResponse, error) { + result := ApplicableMaccsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ApplicableMaccList); err != nil { + return ApplicableMaccsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armbillingbenefits/zz_client_factory.go b/test/local/armbillingbenefits/zz_client_factory.go new file mode 100644 index 000000000000..4b3134017efe --- /dev/null +++ b/test/local/armbillingbenefits/zz_client_factory.go @@ -0,0 +1,161 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armbillingbenefits + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + subscriptionID string + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, + internal: internal, + }, nil +} + +// NewApplicableMaccsClient creates a new instance of ApplicableMaccsClient. +func (c *ClientFactory) NewApplicableMaccsClient() *ApplicableMaccsClient { + return &ApplicableMaccsClient{ + internal: c.internal, + } +} + +// NewConditionalCreditContributorsClient creates a new instance of ConditionalCreditContributorsClient. +func (c *ClientFactory) NewConditionalCreditContributorsClient() *ConditionalCreditContributorsClient { + return &ConditionalCreditContributorsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewConditionalCreditsClient creates a new instance of ConditionalCreditsClient. +func (c *ClientFactory) NewConditionalCreditsClient() *ConditionalCreditsClient { + return &ConditionalCreditsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewContributorsClient creates a new instance of ContributorsClient. +func (c *ClientFactory) NewContributorsClient() *ContributorsClient { + return &ContributorsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewCreditsClient creates a new instance of CreditsClient. +func (c *ClientFactory) NewCreditsClient() *CreditsClient { + return &CreditsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewDiscountClient creates a new instance of DiscountClient. +func (c *ClientFactory) NewDiscountClient() *DiscountClient { + return &DiscountClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewDiscountsClient creates a new instance of DiscountsClient. +func (c *ClientFactory) NewDiscountsClient() *DiscountsClient { + return &DiscountsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewFreeServicesClient creates a new instance of FreeServicesClient. +func (c *ClientFactory) NewFreeServicesClient() *FreeServicesClient { + return &FreeServicesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewMaccsClient creates a new instance of MaccsClient. +func (c *ClientFactory) NewMaccsClient() *MaccsClient { + return &MaccsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: c.internal, + } +} + +// NewRPClient creates a new instance of RPClient. +func (c *ClientFactory) NewRPClient() *RPClient { + return &RPClient{ + internal: c.internal, + } +} + +// NewReservationOrderAliasClient creates a new instance of ReservationOrderAliasClient. +func (c *ClientFactory) NewReservationOrderAliasClient() *ReservationOrderAliasClient { + return &ReservationOrderAliasClient{ + internal: c.internal, + } +} + +// NewSavingsPlanClient creates a new instance of SavingsPlanClient. +func (c *ClientFactory) NewSavingsPlanClient() *SavingsPlanClient { + return &SavingsPlanClient{ + internal: c.internal, + } +} + +// NewSavingsPlanOrderAliasClient creates a new instance of SavingsPlanOrderAliasClient. +func (c *ClientFactory) NewSavingsPlanOrderAliasClient() *SavingsPlanOrderAliasClient { + return &SavingsPlanOrderAliasClient{ + internal: c.internal, + } +} + +// NewSavingsPlanOrderClient creates a new instance of SavingsPlanOrderClient. +func (c *ClientFactory) NewSavingsPlanOrderClient() *SavingsPlanOrderClient { + return &SavingsPlanOrderClient{ + internal: c.internal, + } +} + +// NewSellerResourceClient creates a new instance of SellerResourceClient. +func (c *ClientFactory) NewSellerResourceClient() *SellerResourceClient { + return &SellerResourceClient{ + internal: c.internal, + } +} + +// NewSourcesClient creates a new instance of SourcesClient. +func (c *ClientFactory) NewSourcesClient() *SourcesClient { + return &SourcesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} diff --git a/test/local/armbillingbenefits/zz_conditionalcreditcontributors_client.go b/test/local/armbillingbenefits/zz_conditionalcreditcontributors_client.go new file mode 100644 index 000000000000..afd8c5b84014 --- /dev/null +++ b/test/local/armbillingbenefits/zz_conditionalcreditcontributors_client.go @@ -0,0 +1,233 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armbillingbenefits + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ConditionalCreditContributorsClient contains the methods for the ConditionalCreditContributors group. +// Don't use this type directly, use NewConditionalCreditContributorsClient() instead. +// +// Generated from API version 2025-12-01-preview +type ConditionalCreditContributorsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewConditionalCreditContributorsClient creates a new instance of ConditionalCreditContributorsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewConditionalCreditContributorsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ConditionalCreditContributorsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ConditionalCreditContributorsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// GetFromPrimary - Get a conditional credit contributor for primary service admin +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - conditionalCreditName - Name of the conditional credit +// - contributorName - Unique name of contributor in the format {contributorCloudSubId}_{resourceGroupName}_{nameInContributorTenant}. +// - options - ConditionalCreditContributorsClientGetFromPrimaryOptions contains the optional parameters for the ConditionalCreditContributorsClient.GetFromPrimary +// method. +func (client *ConditionalCreditContributorsClient) GetFromPrimary(ctx context.Context, resourceGroupName string, conditionalCreditName string, contributorName string, options *ConditionalCreditContributorsClientGetFromPrimaryOptions) (ConditionalCreditContributorsClientGetFromPrimaryResponse, error) { + var err error + const operationName = "ConditionalCreditContributorsClient.GetFromPrimary" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getFromPrimaryCreateRequest(ctx, resourceGroupName, conditionalCreditName, contributorName, options) + if err != nil { + return ConditionalCreditContributorsClientGetFromPrimaryResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ConditionalCreditContributorsClientGetFromPrimaryResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ConditionalCreditContributorsClientGetFromPrimaryResponse{}, err + } + resp, err := client.getFromPrimaryHandleResponse(httpResp) + return resp, err +} + +// getFromPrimaryCreateRequest creates the GetFromPrimary request. +func (client *ConditionalCreditContributorsClient) getFromPrimaryCreateRequest(ctx context.Context, resourceGroupName string, conditionalCreditName string, contributorName string, _ *ConditionalCreditContributorsClientGetFromPrimaryOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/conditionalCredits/{conditionalCreditName}/contributors/{contributorName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if conditionalCreditName == "" { + return nil, errors.New("parameter conditionalCreditName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{conditionalCreditName}", url.PathEscape(conditionalCreditName)) + if contributorName == "" { + return nil, errors.New("parameter contributorName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{contributorName}", url.PathEscape(contributorName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getFromPrimaryHandleResponse handles the GetFromPrimary response. +func (client *ConditionalCreditContributorsClient) getFromPrimaryHandleResponse(resp *http.Response) (ConditionalCreditContributorsClientGetFromPrimaryResponse, error) { + result := ConditionalCreditContributorsClientGetFromPrimaryResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ConditionalCreditContributor); err != nil { + return ConditionalCreditContributorsClientGetFromPrimaryResponse{}, err + } + return result, nil +} + +// NewListFromApplicableConditionalCreditPager - List contributors under applicable conditional credits for a given billing +// account. +// - billingAccountID - The billing account Id at which the benefits are listed. Accepted format is: {rootId:orgId}. +// - systemID - System ID of the primary MACC. +// - options - ConditionalCreditContributorsClientListFromApplicableConditionalCreditOptions contains the optional parameters +// for the ConditionalCreditContributorsClient.NewListFromApplicableConditionalCreditPager method. +func (client *ConditionalCreditContributorsClient) NewListFromApplicableConditionalCreditPager(billingAccountID string, systemID string, options *ConditionalCreditContributorsClientListFromApplicableConditionalCreditOptions) *runtime.Pager[ConditionalCreditContributorsClientListFromApplicableConditionalCreditResponse] { + return runtime.NewPager(runtime.PagingHandler[ConditionalCreditContributorsClientListFromApplicableConditionalCreditResponse]{ + More: func(page ConditionalCreditContributorsClientListFromApplicableConditionalCreditResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ConditionalCreditContributorsClientListFromApplicableConditionalCreditResponse) (ConditionalCreditContributorsClientListFromApplicableConditionalCreditResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ConditionalCreditContributorsClient.NewListFromApplicableConditionalCreditPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listFromApplicableConditionalCreditCreateRequest(ctx, billingAccountID, systemID, options) + }, nil) + if err != nil { + return ConditionalCreditContributorsClientListFromApplicableConditionalCreditResponse{}, err + } + return client.listFromApplicableConditionalCreditHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listFromApplicableConditionalCreditCreateRequest creates the ListFromApplicableConditionalCredit request. +func (client *ConditionalCreditContributorsClient) listFromApplicableConditionalCreditCreateRequest(ctx context.Context, billingAccountID string, systemID string, _ *ConditionalCreditContributorsClientListFromApplicableConditionalCreditOptions) (*policy.Request, error) { + urlPath := "/providers/microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.BillingBenefits/applicableConditionalCredits/{systemId}/providers/microsoft.BillingBenefits/applicableContributors" + if billingAccountID == "" { + return nil, errors.New("parameter billingAccountID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{billingAccountId}", url.PathEscape(billingAccountID)) + if systemID == "" { + return nil, errors.New("parameter systemID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{systemId}", url.PathEscape(systemID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listFromApplicableConditionalCreditHandleResponse handles the ListFromApplicableConditionalCredit response. +func (client *ConditionalCreditContributorsClient) listFromApplicableConditionalCreditHandleResponse(resp *http.Response) (ConditionalCreditContributorsClientListFromApplicableConditionalCreditResponse, error) { + result := ConditionalCreditContributorsClientListFromApplicableConditionalCreditResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ConditionalCreditContributorList); err != nil { + return ConditionalCreditContributorsClientListFromApplicableConditionalCreditResponse{}, err + } + return result, nil +} + +// NewListFromPrimaryPager - List contributors under a primary conditional credit for primary service admin +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - conditionalCreditName - Name of the conditional credit +// - options - ConditionalCreditContributorsClientListFromPrimaryOptions contains the optional parameters for the ConditionalCreditContributorsClient.NewListFromPrimaryPager +// method. +func (client *ConditionalCreditContributorsClient) NewListFromPrimaryPager(resourceGroupName string, conditionalCreditName string, options *ConditionalCreditContributorsClientListFromPrimaryOptions) *runtime.Pager[ConditionalCreditContributorsClientListFromPrimaryResponse] { + return runtime.NewPager(runtime.PagingHandler[ConditionalCreditContributorsClientListFromPrimaryResponse]{ + More: func(page ConditionalCreditContributorsClientListFromPrimaryResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ConditionalCreditContributorsClientListFromPrimaryResponse) (ConditionalCreditContributorsClientListFromPrimaryResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ConditionalCreditContributorsClient.NewListFromPrimaryPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listFromPrimaryCreateRequest(ctx, resourceGroupName, conditionalCreditName, options) + }, nil) + if err != nil { + return ConditionalCreditContributorsClientListFromPrimaryResponse{}, err + } + return client.listFromPrimaryHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listFromPrimaryCreateRequest creates the ListFromPrimary request. +func (client *ConditionalCreditContributorsClient) listFromPrimaryCreateRequest(ctx context.Context, resourceGroupName string, conditionalCreditName string, _ *ConditionalCreditContributorsClientListFromPrimaryOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/conditionalCredits/{conditionalCreditName}/contributors" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if conditionalCreditName == "" { + return nil, errors.New("parameter conditionalCreditName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{conditionalCreditName}", url.PathEscape(conditionalCreditName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listFromPrimaryHandleResponse handles the ListFromPrimary response. +func (client *ConditionalCreditContributorsClient) listFromPrimaryHandleResponse(resp *http.Response) (ConditionalCreditContributorsClientListFromPrimaryResponse, error) { + result := ConditionalCreditContributorsClientListFromPrimaryResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ConditionalCreditContributorList); err != nil { + return ConditionalCreditContributorsClientListFromPrimaryResponse{}, err + } + return result, nil +} diff --git a/test/local/armbillingbenefits/zz_conditionalcredits_client.go b/test/local/armbillingbenefits/zz_conditionalcredits_client.go new file mode 100644 index 000000000000..de050be66558 --- /dev/null +++ b/test/local/armbillingbenefits/zz_conditionalcredits_client.go @@ -0,0 +1,569 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armbillingbenefits + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ConditionalCreditsClient contains the methods for the ConditionalCredits group. +// Don't use this type directly, use NewConditionalCreditsClient() instead. +// +// Generated from API version 2025-12-01-preview +type ConditionalCreditsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewConditionalCreditsClient creates a new instance of ConditionalCreditsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewConditionalCreditsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ConditionalCreditsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ConditionalCreditsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCancel - Cancel conditional credit. Stops applying the benefit. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - conditionalCreditName - Name of the conditional credit +// - options - ConditionalCreditsClientBeginCancelOptions contains the optional parameters for the ConditionalCreditsClient.BeginCancel +// method. +func (client *ConditionalCreditsClient) BeginCancel(ctx context.Context, resourceGroupName string, conditionalCreditName string, options *ConditionalCreditsClientBeginCancelOptions) (*runtime.Poller[ConditionalCreditsClientCancelResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.cancel(ctx, resourceGroupName, conditionalCreditName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ConditionalCreditsClientCancelResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ConditionalCreditsClientCancelResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Cancel - Cancel conditional credit. Stops applying the benefit. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ConditionalCreditsClient) cancel(ctx context.Context, resourceGroupName string, conditionalCreditName string, options *ConditionalCreditsClientBeginCancelOptions) (*http.Response, error) { + var err error + const operationName = "ConditionalCreditsClient.BeginCancel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.cancelCreateRequest(ctx, resourceGroupName, conditionalCreditName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// cancelCreateRequest creates the Cancel request. +func (client *ConditionalCreditsClient) cancelCreateRequest(ctx context.Context, resourceGroupName string, conditionalCreditName string, _ *ConditionalCreditsClientBeginCancelOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/conditionalCredits/{conditionalCreditName}/cancel" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if conditionalCreditName == "" { + return nil, errors.New("parameter conditionalCreditName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{conditionalCreditName}", url.PathEscape(conditionalCreditName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginCreateOrUpdate - Create or update a conditional credit. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - conditionalCreditName - Name of the conditional credit +// - body - Request body for creating a conditional credit +// - options - ConditionalCreditsClientBeginCreateOrUpdateOptions contains the optional parameters for the ConditionalCreditsClient.BeginCreateOrUpdate +// method. +func (client *ConditionalCreditsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, conditionalCreditName string, body ConditionalCredit, options *ConditionalCreditsClientBeginCreateOrUpdateOptions) (*runtime.Poller[ConditionalCreditsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, conditionalCreditName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ConditionalCreditsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ConditionalCreditsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create or update a conditional credit. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ConditionalCreditsClient) createOrUpdate(ctx context.Context, resourceGroupName string, conditionalCreditName string, body ConditionalCredit, options *ConditionalCreditsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ConditionalCreditsClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, conditionalCreditName, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *ConditionalCreditsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, conditionalCreditName string, body ConditionalCredit, _ *ConditionalCreditsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/conditionalCredits/{conditionalCreditName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if conditionalCreditName == "" { + return nil, errors.New("parameter conditionalCreditName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{conditionalCreditName}", url.PathEscape(conditionalCreditName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a conditional credit. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - conditionalCreditName - Name of the conditional credit +// - options - ConditionalCreditsClientBeginDeleteOptions contains the optional parameters for the ConditionalCreditsClient.BeginDelete +// method. +func (client *ConditionalCreditsClient) BeginDelete(ctx context.Context, resourceGroupName string, conditionalCreditName string, options *ConditionalCreditsClientBeginDeleteOptions) (*runtime.Poller[ConditionalCreditsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, conditionalCreditName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ConditionalCreditsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ConditionalCreditsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a conditional credit. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ConditionalCreditsClient) deleteOperation(ctx context.Context, resourceGroupName string, conditionalCreditName string, options *ConditionalCreditsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ConditionalCreditsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, conditionalCreditName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ConditionalCreditsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, conditionalCreditName string, _ *ConditionalCreditsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/conditionalCredits/{conditionalCreditName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if conditionalCreditName == "" { + return nil, errors.New("parameter conditionalCreditName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{conditionalCreditName}", url.PathEscape(conditionalCreditName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a conditional credit. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - conditionalCreditName - Name of the conditional credit +// - options - ConditionalCreditsClientGetOptions contains the optional parameters for the ConditionalCreditsClient.Get method. +func (client *ConditionalCreditsClient) Get(ctx context.Context, resourceGroupName string, conditionalCreditName string, options *ConditionalCreditsClientGetOptions) (ConditionalCreditsClientGetResponse, error) { + var err error + const operationName = "ConditionalCreditsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, conditionalCreditName, options) + if err != nil { + return ConditionalCreditsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ConditionalCreditsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ConditionalCreditsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ConditionalCreditsClient) getCreateRequest(ctx context.Context, resourceGroupName string, conditionalCreditName string, _ *ConditionalCreditsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/conditionalCredits/{conditionalCreditName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if conditionalCreditName == "" { + return nil, errors.New("parameter conditionalCreditName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{conditionalCreditName}", url.PathEscape(conditionalCreditName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ConditionalCreditsClient) getHandleResponse(resp *http.Response) (ConditionalCreditsClientGetResponse, error) { + result := ConditionalCreditsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ConditionalCredit); err != nil { + return ConditionalCreditsClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - List conditional credits by resource group. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - ConditionalCreditsClientListByResourceGroupOptions contains the optional parameters for the ConditionalCreditsClient.NewListByResourceGroupPager +// method. +func (client *ConditionalCreditsClient) NewListByResourceGroupPager(resourceGroupName string, options *ConditionalCreditsClientListByResourceGroupOptions) *runtime.Pager[ConditionalCreditsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[ConditionalCreditsClientListByResourceGroupResponse]{ + More: func(page ConditionalCreditsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ConditionalCreditsClientListByResourceGroupResponse) (ConditionalCreditsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ConditionalCreditsClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return ConditionalCreditsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *ConditionalCreditsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *ConditionalCreditsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/conditionalCredits" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *ConditionalCreditsClient) listByResourceGroupHandleResponse(resp *http.Response) (ConditionalCreditsClientListByResourceGroupResponse, error) { + result := ConditionalCreditsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ConditionalCreditList); err != nil { + return ConditionalCreditsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - List conditional credits by subscription. +// - options - ConditionalCreditsClientListBySubscriptionOptions contains the optional parameters for the ConditionalCreditsClient.NewListBySubscriptionPager +// method. +func (client *ConditionalCreditsClient) NewListBySubscriptionPager(options *ConditionalCreditsClientListBySubscriptionOptions) *runtime.Pager[ConditionalCreditsClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[ConditionalCreditsClientListBySubscriptionResponse]{ + More: func(page ConditionalCreditsClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ConditionalCreditsClientListBySubscriptionResponse) (ConditionalCreditsClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ConditionalCreditsClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return ConditionalCreditsClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *ConditionalCreditsClient) listBySubscriptionCreateRequest(ctx context.Context, _ *ConditionalCreditsClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.BillingBenefits/conditionalCredits" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *ConditionalCreditsClient) listBySubscriptionHandleResponse(resp *http.Response) (ConditionalCreditsClientListBySubscriptionResponse, error) { + result := ConditionalCreditsClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ConditionalCreditList); err != nil { + return ConditionalCreditsClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// NewScopeListPager - List conditional credits that are applicable for a given scope. Currently supported scopes: billing +// accounts +// - scope - The scope at which the benefits are listed. +// - options - ConditionalCreditsClientScopeListOptions contains the optional parameters for the ConditionalCreditsClient.NewScopeListPager +// method. +func (client *ConditionalCreditsClient) NewScopeListPager(scope string, options *ConditionalCreditsClientScopeListOptions) *runtime.Pager[ConditionalCreditsClientScopeListResponse] { + return runtime.NewPager(runtime.PagingHandler[ConditionalCreditsClientScopeListResponse]{ + More: func(page ConditionalCreditsClientScopeListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ConditionalCreditsClientScopeListResponse) (ConditionalCreditsClientScopeListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ConditionalCreditsClient.NewScopeListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.scopeListCreateRequest(ctx, scope, options) + }, nil) + if err != nil { + return ConditionalCreditsClientScopeListResponse{}, err + } + return client.scopeListHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// scopeListCreateRequest creates the ScopeList request. +func (client *ConditionalCreditsClient) scopeListCreateRequest(ctx context.Context, scope string, _ *ConditionalCreditsClientScopeListOptions) (*policy.Request, error) { + urlPath := "/{scope}/providers/Microsoft.BillingBenefits/applicableConditionalCredits" + if scope == "" { + return nil, errors.New("parameter scope cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scope}", url.PathEscape(scope)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// scopeListHandleResponse handles the ScopeList response. +func (client *ConditionalCreditsClient) scopeListHandleResponse(resp *http.Response) (ConditionalCreditsClientScopeListResponse, error) { + result := ConditionalCreditsClientScopeListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ConditionalCreditList); err != nil { + return ConditionalCreditsClientScopeListResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update a conditional credit. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - conditionalCreditName - Name of the conditional credit +// - body - Request body for updating a conditional credit +// - options - ConditionalCreditsClientBeginUpdateOptions contains the optional parameters for the ConditionalCreditsClient.BeginUpdate +// method. +func (client *ConditionalCreditsClient) BeginUpdate(ctx context.Context, resourceGroupName string, conditionalCreditName string, body ConditionalCreditPatchRequest, options *ConditionalCreditsClientBeginUpdateOptions) (*runtime.Poller[ConditionalCreditsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, conditionalCreditName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ConditionalCreditsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ConditionalCreditsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a conditional credit. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ConditionalCreditsClient) update(ctx context.Context, resourceGroupName string, conditionalCreditName string, body ConditionalCreditPatchRequest, options *ConditionalCreditsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ConditionalCreditsClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, conditionalCreditName, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *ConditionalCreditsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, conditionalCreditName string, body ConditionalCreditPatchRequest, _ *ConditionalCreditsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/conditionalCredits/{conditionalCreditName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if conditionalCreditName == "" { + return nil, errors.New("parameter conditionalCreditName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{conditionalCreditName}", url.PathEscape(conditionalCreditName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armbillingbenefits/zz_constants.go b/test/local/armbillingbenefits/zz_constants.go new file mode 100644 index 000000000000..091a3c15980f --- /dev/null +++ b/test/local/armbillingbenefits/zz_constants.go @@ -0,0 +1,836 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armbillingbenefits + +const ( + version20251201Preview string = "2025-12-01-preview" +) + +// ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +type ActionType string + +const ( + // ActionTypeInternal - Actions are for internal-only APIs. + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// AppliedScopeType - Type of the Applied Scope. +type AppliedScopeType string + +const ( + AppliedScopeTypeManagementGroup AppliedScopeType = "ManagementGroup" + AppliedScopeTypeShared AppliedScopeType = "Shared" + AppliedScopeTypeSingle AppliedScopeType = "Single" +) + +// PossibleAppliedScopeTypeValues returns the possible values for the AppliedScopeType const type. +func PossibleAppliedScopeTypeValues() []AppliedScopeType { + return []AppliedScopeType{ + AppliedScopeTypeManagementGroup, + AppliedScopeTypeShared, + AppliedScopeTypeSingle, + } +} + +// ApplyDiscountOn - The customer action on which the discount is applied. Supported values are Purchase, Consume, and Renew. +// Validation: Required, one of supported values. +type ApplyDiscountOn string + +const ( + ApplyDiscountOnConsume ApplyDiscountOn = "Consume" + ApplyDiscountOnPurchase ApplyDiscountOn = "Purchase" + ApplyDiscountOnRenew ApplyDiscountOn = "Renew" +) + +// PossibleApplyDiscountOnValues returns the possible values for the ApplyDiscountOn const type. +func PossibleApplyDiscountOnValues() []ApplyDiscountOn { + return []ApplyDiscountOn{ + ApplyDiscountOnConsume, + ApplyDiscountOnPurchase, + ApplyDiscountOnRenew, + } +} + +// BenefitType - Represents benefit model type for validation. +type BenefitType string + +const ( + BenefitTypeConditionalCredits BenefitType = "ConditionalCredits" + BenefitTypeCredits BenefitType = "Credits" + BenefitTypeMACC BenefitType = "MACC" + BenefitTypeSavingsPlan BenefitType = "SavingsPlan" +) + +// PossibleBenefitTypeValues returns the possible values for the BenefitType const type. +func PossibleBenefitTypeValues() []BenefitType { + return []BenefitType{ + BenefitTypeConditionalCredits, + BenefitTypeCredits, + BenefitTypeMACC, + BenefitTypeSavingsPlan, + } +} + +// BillingPlan - Represents the billing plan in ISO 8601 format. Required only for monthly billing plans. +type BillingPlan string + +const ( + BillingPlanP1M BillingPlan = "P1M" +) + +// PossibleBillingPlanValues returns the possible values for the BillingPlan const type. +func PossibleBillingPlanValues() []BillingPlan { + return []BillingPlan{ + BillingPlanP1M, + } +} + +// CommitmentGrain - Grain. +type CommitmentGrain string + +const ( + CommitmentGrainFullTerm CommitmentGrain = "FullTerm" + CommitmentGrainHourly CommitmentGrain = "Hourly" + CommitmentGrainUnknown CommitmentGrain = "Unknown" +) + +// PossibleCommitmentGrainValues returns the possible values for the CommitmentGrain const type. +func PossibleCommitmentGrainValues() []CommitmentGrain { + return []CommitmentGrain{ + CommitmentGrainFullTerm, + CommitmentGrainHourly, + CommitmentGrainUnknown, + } +} + +// ConditionalCreditEntityType - Type of conditional credit entity +type ConditionalCreditEntityType string + +const ( + ConditionalCreditEntityTypeContributor ConditionalCreditEntityType = "Contributor" + ConditionalCreditEntityTypePrimary ConditionalCreditEntityType = "Primary" +) + +// PossibleConditionalCreditEntityTypeValues returns the possible values for the ConditionalCreditEntityType const type. +func PossibleConditionalCreditEntityTypeValues() []ConditionalCreditEntityType { + return []ConditionalCreditEntityType{ + ConditionalCreditEntityTypeContributor, + ConditionalCreditEntityTypePrimary, + } +} + +// ConditionalCreditStatus - The status of the conditional credit +type ConditionalCreditStatus string + +const ( + ConditionalCreditStatusActive ConditionalCreditStatus = "Active" + ConditionalCreditStatusCanceled ConditionalCreditStatus = "Canceled" + ConditionalCreditStatusCompleted ConditionalCreditStatus = "Completed" + ConditionalCreditStatusFailed ConditionalCreditStatus = "Failed" + ConditionalCreditStatusPending ConditionalCreditStatus = "Pending" + ConditionalCreditStatusPendingSettlement ConditionalCreditStatus = "PendingSettlement" + ConditionalCreditStatusScheduled ConditionalCreditStatus = "Scheduled" + ConditionalCreditStatusStopped ConditionalCreditStatus = "Stopped" + ConditionalCreditStatusUnknown ConditionalCreditStatus = "Unknown" +) + +// PossibleConditionalCreditStatusValues returns the possible values for the ConditionalCreditStatus const type. +func PossibleConditionalCreditStatusValues() []ConditionalCreditStatus { + return []ConditionalCreditStatus{ + ConditionalCreditStatusActive, + ConditionalCreditStatusCanceled, + ConditionalCreditStatusCompleted, + ConditionalCreditStatusFailed, + ConditionalCreditStatusPending, + ConditionalCreditStatusPendingSettlement, + ConditionalCreditStatusScheduled, + ConditionalCreditStatusStopped, + ConditionalCreditStatusUnknown, + } +} + +// ConditionalCreditsProvisioningState - The provisioning state of the resource +type ConditionalCreditsProvisioningState string + +const ( + ConditionalCreditsProvisioningStateCanceled ConditionalCreditsProvisioningState = "Canceled" + ConditionalCreditsProvisioningStateFailed ConditionalCreditsProvisioningState = "Failed" + ConditionalCreditsProvisioningStatePending ConditionalCreditsProvisioningState = "Pending" + ConditionalCreditsProvisioningStateSucceeded ConditionalCreditsProvisioningState = "Succeeded" + ConditionalCreditsProvisioningStateUnknown ConditionalCreditsProvisioningState = "Unknown" +) + +// PossibleConditionalCreditsProvisioningStateValues returns the possible values for the ConditionalCreditsProvisioningState const type. +func PossibleConditionalCreditsProvisioningStateValues() []ConditionalCreditsProvisioningState { + return []ConditionalCreditsProvisioningState{ + ConditionalCreditsProvisioningStateCanceled, + ConditionalCreditsProvisioningStateFailed, + ConditionalCreditsProvisioningStatePending, + ConditionalCreditsProvisioningStateSucceeded, + ConditionalCreditsProvisioningStateUnknown, + } +} + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// CreditExpirationPolicy - Expiration policy of the Credit +type CreditExpirationPolicy string + +const ( + // CreditExpirationPolicyNone - No policy applied to the expiration of this credit + CreditExpirationPolicyNone CreditExpirationPolicy = "None" + // CreditExpirationPolicySuspendBillingProfile - Billing profile is suspended when the credit expires + CreditExpirationPolicySuspendBillingProfile CreditExpirationPolicy = "SuspendBillingProfile" +) + +// PossibleCreditExpirationPolicyValues returns the possible values for the CreditExpirationPolicy const type. +func PossibleCreditExpirationPolicyValues() []CreditExpirationPolicy { + return []CreditExpirationPolicy{ + CreditExpirationPolicyNone, + CreditExpirationPolicySuspendBillingProfile, + } +} + +// CreditRedemptionPolicy - Redemption policy of the Credit +type CreditRedemptionPolicy string + +const ( + // CreditRedemptionPolicyAutoRedeem - Credit is automatically redeemed + CreditRedemptionPolicyAutoRedeem CreditRedemptionPolicy = "AutoRedeem" + // CreditRedemptionPolicyManualRedeem - Credit is manually redeemed + CreditRedemptionPolicyManualRedeem CreditRedemptionPolicy = "ManualRedeem" + // CreditRedemptionPolicyNotApplicable - Redemption policy is not applicable for this credit + CreditRedemptionPolicyNotApplicable CreditRedemptionPolicy = "NotApplicable" +) + +// PossibleCreditRedemptionPolicyValues returns the possible values for the CreditRedemptionPolicy const type. +func PossibleCreditRedemptionPolicyValues() []CreditRedemptionPolicy { + return []CreditRedemptionPolicy{ + CreditRedemptionPolicyAutoRedeem, + CreditRedemptionPolicyManualRedeem, + CreditRedemptionPolicyNotApplicable, + } +} + +// CreditStatus - Status of the credit +type CreditStatus string + +const ( + // CreditStatusActive - Credit is active and available for use + CreditStatusActive CreditStatus = "Active" + // CreditStatusCanceled - Credit has been cancelled + CreditStatusCanceled CreditStatus = "Canceled" + // CreditStatusExhausted - Credit has been fully consumed + CreditStatusExhausted CreditStatus = "Exhausted" + // CreditStatusExpired - Credit has expired + CreditStatusExpired CreditStatus = "Expired" + // CreditStatusFailed - Credit operation failed + CreditStatusFailed CreditStatus = "Failed" + // CreditStatusNotStarted - Credit application has not started yet + CreditStatusNotStarted CreditStatus = "NotStarted" + // CreditStatusPending - Credit is pending activation + CreditStatusPending CreditStatus = "Pending" + // CreditStatusSucceeded - Credit operation succeeded + CreditStatusSucceeded CreditStatus = "Succeeded" + // CreditStatusUnknown - Credit status is unknown + CreditStatusUnknown CreditStatus = "Unknown" +) + +// PossibleCreditStatusValues returns the possible values for the CreditStatus const type. +func PossibleCreditStatusValues() []CreditStatus { + return []CreditStatus{ + CreditStatusActive, + CreditStatusCanceled, + CreditStatusExhausted, + CreditStatusExpired, + CreditStatusFailed, + CreditStatusNotStarted, + CreditStatusPending, + CreditStatusSucceeded, + CreditStatusUnknown, + } +} + +// DiscountAppliedScopeType - List of applied scopes supported for discounts. +type DiscountAppliedScopeType string + +const ( + DiscountAppliedScopeTypeBillingAccount DiscountAppliedScopeType = "BillingAccount" + DiscountAppliedScopeTypeBillingProfile DiscountAppliedScopeType = "BillingProfile" + DiscountAppliedScopeTypeCustomer DiscountAppliedScopeType = "Customer" +) + +// PossibleDiscountAppliedScopeTypeValues returns the possible values for the DiscountAppliedScopeType const type. +func PossibleDiscountAppliedScopeTypeValues() []DiscountAppliedScopeType { + return []DiscountAppliedScopeType{ + DiscountAppliedScopeTypeBillingAccount, + DiscountAppliedScopeTypeBillingProfile, + DiscountAppliedScopeTypeCustomer, + } +} + +// DiscountCombinationRule - The discount combination rule when there are multiple applicable custom prices. Validation: Required. +// Supported values are Stackable and BestOf. +type DiscountCombinationRule string + +const ( + DiscountCombinationRuleBestOf DiscountCombinationRule = "BestOf" + DiscountCombinationRuleStackable DiscountCombinationRule = "Stackable" +) + +// PossibleDiscountCombinationRuleValues returns the possible values for the DiscountCombinationRule const type. +func PossibleDiscountCombinationRuleValues() []DiscountCombinationRule { + return []DiscountCombinationRule{ + DiscountCombinationRuleBestOf, + DiscountCombinationRuleStackable, + } +} + +// DiscountEntityType - This defines whether the entity being created is primary or affiliate. Supported values: primary, +// affiliate. Validation: Required, must match one of the 2 values. +type DiscountEntityType string + +const ( + DiscountEntityTypeAffiliate DiscountEntityType = "Affiliate" + DiscountEntityTypePrimary DiscountEntityType = "Primary" +) + +// PossibleDiscountEntityTypeValues returns the possible values for the DiscountEntityType const type. +func PossibleDiscountEntityTypeValues() []DiscountEntityType { + return []DiscountEntityType{ + DiscountEntityTypeAffiliate, + DiscountEntityTypePrimary, + } +} + +// DiscountProvisioningState - Provisioning states of Discount. +type DiscountProvisioningState string + +const ( + DiscountProvisioningStateCanceled DiscountProvisioningState = "Canceled" + DiscountProvisioningStateFailed DiscountProvisioningState = "Failed" + DiscountProvisioningStatePending DiscountProvisioningState = "Pending" + DiscountProvisioningStateSucceeded DiscountProvisioningState = "Succeeded" + DiscountProvisioningStateUnknown DiscountProvisioningState = "Unknown" +) + +// PossibleDiscountProvisioningStateValues returns the possible values for the DiscountProvisioningState const type. +func PossibleDiscountProvisioningStateValues() []DiscountProvisioningState { + return []DiscountProvisioningState{ + DiscountProvisioningStateCanceled, + DiscountProvisioningStateFailed, + DiscountProvisioningStatePending, + DiscountProvisioningStateSucceeded, + DiscountProvisioningStateUnknown, + } +} + +// DiscountRuleType - The type of the priceable node pricing rule. Validation: Required. Supported values are fixedPriceLock, +// fixedListPrice, and priceCeiling. +type DiscountRuleType string + +const ( + DiscountRuleTypeFixedListPrice DiscountRuleType = "FixedListPrice" + DiscountRuleTypeFixedPriceLock DiscountRuleType = "FixedPriceLock" + DiscountRuleTypePriceCeiling DiscountRuleType = "PriceCeiling" +) + +// PossibleDiscountRuleTypeValues returns the possible values for the DiscountRuleType const type. +func PossibleDiscountRuleTypeValues() []DiscountRuleType { + return []DiscountRuleType{ + DiscountRuleTypeFixedListPrice, + DiscountRuleTypeFixedPriceLock, + DiscountRuleTypePriceCeiling, + } +} + +// DiscountStatus - Represents the current status of the discount. +type DiscountStatus string + +const ( + DiscountStatusActive DiscountStatus = "Active" + DiscountStatusCanceled DiscountStatus = "Canceled" + DiscountStatusExpired DiscountStatus = "Expired" + DiscountStatusFailed DiscountStatus = "Failed" + DiscountStatusPending DiscountStatus = "Pending" +) + +// PossibleDiscountStatusValues returns the possible values for the DiscountStatus const type. +func PossibleDiscountStatusValues() []DiscountStatus { + return []DiscountStatus{ + DiscountStatusActive, + DiscountStatusCanceled, + DiscountStatusExpired, + DiscountStatusFailed, + DiscountStatusPending, + } +} + +// DiscountTypeEnum - Defines the type of discount. Supported values are ProductFamily, Product, Sku, CustomPrice, and CustomPriceMultiCurrency. +type DiscountTypeEnum string + +const ( + DiscountTypeEnumCustomPrice DiscountTypeEnum = "CustomPrice" + DiscountTypeEnumCustomPriceMultiCurrency DiscountTypeEnum = "CustomPriceMultiCurrency" + DiscountTypeEnumProduct DiscountTypeEnum = "Product" + DiscountTypeEnumProductFamily DiscountTypeEnum = "ProductFamily" + DiscountTypeEnumSKU DiscountTypeEnum = "Sku" +) + +// PossibleDiscountTypeEnumValues returns the possible values for the DiscountTypeEnum const type. +func PossibleDiscountTypeEnumValues() []DiscountTypeEnum { + return []DiscountTypeEnum{ + DiscountTypeEnumCustomPrice, + DiscountTypeEnumCustomPriceMultiCurrency, + DiscountTypeEnumProduct, + DiscountTypeEnumProductFamily, + DiscountTypeEnumSKU, + } +} + +// EnablementMode - Represents the enablement status of a feature or settings. +type EnablementMode string + +const ( + EnablementModeDisabled EnablementMode = "Disabled" + EnablementModeEnabled EnablementMode = "Enabled" + EnablementModeUnknown EnablementMode = "Unknown" +) + +// PossibleEnablementModeValues returns the possible values for the EnablementMode const type. +func PossibleEnablementModeValues() []EnablementMode { + return []EnablementMode{ + EnablementModeDisabled, + EnablementModeEnabled, + EnablementModeUnknown, + } +} + +// FreeServicesStatus - Status of the free services +type FreeServicesStatus string + +const ( + // FreeServicesStatusActive - Free services are active + FreeServicesStatusActive FreeServicesStatus = "Active" + // FreeServicesStatusCanceled - Free services have been canceled + FreeServicesStatusCanceled FreeServicesStatus = "Canceled" + // FreeServicesStatusCompleted - Free services have been fully consumed or completed + FreeServicesStatusCompleted FreeServicesStatus = "Completed" + // FreeServicesStatusPending - Free services are pending activation + FreeServicesStatusPending FreeServicesStatus = "Pending" + // FreeServicesStatusUnknown - Free services status is unknown + FreeServicesStatusUnknown FreeServicesStatus = "Unknown" +) + +// PossibleFreeServicesStatusValues returns the possible values for the FreeServicesStatus const type. +func PossibleFreeServicesStatusValues() []FreeServicesStatus { + return []FreeServicesStatus{ + FreeServicesStatusActive, + FreeServicesStatusCanceled, + FreeServicesStatusCompleted, + FreeServicesStatusPending, + FreeServicesStatusUnknown, + } +} + +// InstanceFlexibility - Turning this on will apply the reservation discount to other VMs in the same VM size group. +type InstanceFlexibility string + +const ( + InstanceFlexibilityOff InstanceFlexibility = "Off" + InstanceFlexibilityOn InstanceFlexibility = "On" +) + +// PossibleInstanceFlexibilityValues returns the possible values for the InstanceFlexibility const type. +func PossibleInstanceFlexibilityValues() []InstanceFlexibility { + return []InstanceFlexibility{ + InstanceFlexibilityOff, + InstanceFlexibilityOn, + } +} + +// MaccEntityType - Represents type of the object being operated on. Possible values are primary or contributor. +type MaccEntityType string + +const ( + MaccEntityTypeContributor MaccEntityType = "Contributor" + MaccEntityTypePrimary MaccEntityType = "Primary" +) + +// PossibleMaccEntityTypeValues returns the possible values for the MaccEntityType const type. +func PossibleMaccEntityTypeValues() []MaccEntityType { + return []MaccEntityType{ + MaccEntityTypeContributor, + MaccEntityTypePrimary, + } +} + +// MaccMilestoneStatus - Represents the current status of the Milestone. +type MaccMilestoneStatus string + +const ( + MaccMilestoneStatusActive MaccMilestoneStatus = "Active" + MaccMilestoneStatusCanceled MaccMilestoneStatus = "Canceled" + MaccMilestoneStatusCompleted MaccMilestoneStatus = "Completed" + MaccMilestoneStatusFailed MaccMilestoneStatus = "Failed" + MaccMilestoneStatusPending MaccMilestoneStatus = "Pending" + MaccMilestoneStatusPendingSettlement MaccMilestoneStatus = "PendingSettlement" + MaccMilestoneStatusRemoved MaccMilestoneStatus = "Removed" + MaccMilestoneStatusScheduled MaccMilestoneStatus = "Scheduled" + MaccMilestoneStatusShortfallCharged MaccMilestoneStatus = "ShortfallCharged" + MaccMilestoneStatusShortfallWaived MaccMilestoneStatus = "ShortfallWaived" + MaccMilestoneStatusUnknown MaccMilestoneStatus = "Unknown" +) + +// PossibleMaccMilestoneStatusValues returns the possible values for the MaccMilestoneStatus const type. +func PossibleMaccMilestoneStatusValues() []MaccMilestoneStatus { + return []MaccMilestoneStatus{ + MaccMilestoneStatusActive, + MaccMilestoneStatusCanceled, + MaccMilestoneStatusCompleted, + MaccMilestoneStatusFailed, + MaccMilestoneStatusPending, + MaccMilestoneStatusPendingSettlement, + MaccMilestoneStatusRemoved, + MaccMilestoneStatusScheduled, + MaccMilestoneStatusShortfallCharged, + MaccMilestoneStatusShortfallWaived, + MaccMilestoneStatusUnknown, + } +} + +// MaccStatus - Represents the current status of the MACC. +type MaccStatus string + +const ( + MaccStatusActive MaccStatus = "Active" + MaccStatusCanceled MaccStatus = "Canceled" + MaccStatusCompleted MaccStatus = "Completed" + MaccStatusFailed MaccStatus = "Failed" + MaccStatusPending MaccStatus = "Pending" + MaccStatusPendingSettlement MaccStatus = "PendingSettlement" + MaccStatusScheduled MaccStatus = "Scheduled" + MaccStatusShortfallCharged MaccStatus = "ShortfallCharged" + MaccStatusShortfallWaived MaccStatus = "ShortfallWaived" + MaccStatusStopped MaccStatus = "Stopped" + MaccStatusUnknown MaccStatus = "Unknown" +) + +// PossibleMaccStatusValues returns the possible values for the MaccStatus const type. +func PossibleMaccStatusValues() []MaccStatus { + return []MaccStatus{ + MaccStatusActive, + MaccStatusCanceled, + MaccStatusCompleted, + MaccStatusFailed, + MaccStatusPending, + MaccStatusPendingSettlement, + MaccStatusScheduled, + MaccStatusShortfallCharged, + MaccStatusShortfallWaived, + MaccStatusStopped, + MaccStatusUnknown, + } +} + +// ManagedServiceIdentityType - Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). +type ManagedServiceIdentityType string + +const ( + // ManagedServiceIdentityTypeNone - No managed identity. + ManagedServiceIdentityTypeNone ManagedServiceIdentityType = "None" + // ManagedServiceIdentityTypeSystemAssigned - System assigned managed identity. + ManagedServiceIdentityTypeSystemAssigned ManagedServiceIdentityType = "SystemAssigned" + // ManagedServiceIdentityTypeSystemAssignedUserAssigned - System and user assigned managed identity. + ManagedServiceIdentityTypeSystemAssignedUserAssigned ManagedServiceIdentityType = "SystemAssigned,UserAssigned" + // ManagedServiceIdentityTypeUserAssigned - User assigned managed identity. + ManagedServiceIdentityTypeUserAssigned ManagedServiceIdentityType = "UserAssigned" +) + +// PossibleManagedServiceIdentityTypeValues returns the possible values for the ManagedServiceIdentityType const type. +func PossibleManagedServiceIdentityTypeValues() []ManagedServiceIdentityType { + return []ManagedServiceIdentityType{ + ManagedServiceIdentityTypeNone, + ManagedServiceIdentityTypeSystemAssigned, + ManagedServiceIdentityTypeSystemAssignedUserAssigned, + ManagedServiceIdentityTypeUserAssigned, + } +} + +// MilestoneStatus - Current status of the milestone +type MilestoneStatus string + +const ( + MilestoneStatusActive MilestoneStatus = "Active" + MilestoneStatusCanceled MilestoneStatus = "Canceled" + MilestoneStatusCompleted MilestoneStatus = "Completed" + MilestoneStatusFailed MilestoneStatus = "Failed" + MilestoneStatusMissed MilestoneStatus = "Missed" + MilestoneStatusPending MilestoneStatus = "Pending" + MilestoneStatusPendingSettlement MilestoneStatus = "PendingSettlement" + MilestoneStatusRemoved MilestoneStatus = "Removed" + MilestoneStatusScheduled MilestoneStatus = "Scheduled" + MilestoneStatusUnknown MilestoneStatus = "Unknown" +) + +// PossibleMilestoneStatusValues returns the possible values for the MilestoneStatus const type. +func PossibleMilestoneStatusValues() []MilestoneStatus { + return []MilestoneStatus{ + MilestoneStatusActive, + MilestoneStatusCanceled, + MilestoneStatusCompleted, + MilestoneStatusFailed, + MilestoneStatusMissed, + MilestoneStatusPending, + MilestoneStatusPendingSettlement, + MilestoneStatusRemoved, + MilestoneStatusScheduled, + MilestoneStatusUnknown, + } +} + +// Origin - The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default +// value is "user,system" +type Origin string + +const ( + // OriginSystem - Indicates the operation is initiated by a system. + OriginSystem Origin = "system" + // OriginUser - Indicates the operation is initiated by a user. + OriginUser Origin = "user" + // OriginUserSystem - Indicates the operation is initiated by a user or system. + OriginUserSystem Origin = "user,system" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginSystem, + OriginUser, + OriginUserSystem, + } +} + +// PaymentStatus - Describes whether the payment is completed, failed, cancelled or scheduled in the future. +type PaymentStatus string + +const ( + PaymentStatusCancelled PaymentStatus = "Cancelled" + PaymentStatusFailed PaymentStatus = "Failed" + PaymentStatusScheduled PaymentStatus = "Scheduled" + PaymentStatusSucceeded PaymentStatus = "Succeeded" +) + +// PossiblePaymentStatusValues returns the possible values for the PaymentStatus const type. +func PossiblePaymentStatusValues() []PaymentStatus { + return []PaymentStatus{ + PaymentStatusCancelled, + PaymentStatusFailed, + PaymentStatusScheduled, + PaymentStatusSucceeded, + } +} + +// PricingPolicy - Supported values: Protected, Locked +type PricingPolicy string + +const ( + PricingPolicyLocked PricingPolicy = "Locked" + PricingPolicyProtected PricingPolicy = "Protected" +) + +// PossiblePricingPolicyValues returns the possible values for the PricingPolicy const type. +func PossiblePricingPolicyValues() []PricingPolicy { + return []PricingPolicy{ + PricingPolicyLocked, + PricingPolicyProtected, + } +} + +// ProvisioningState - Provisioning state +type ProvisioningState string + +const ( + ProvisioningStateCancelled ProvisioningState = "Cancelled" + ProvisioningStateConfirmedBilling ProvisioningState = "ConfirmedBilling" + ProvisioningStateCreated ProvisioningState = "Created" + ProvisioningStateCreating ProvisioningState = "Creating" + ProvisioningStateExpired ProvisioningState = "Expired" + ProvisioningStateFailed ProvisioningState = "Failed" + ProvisioningStatePendingBilling ProvisioningState = "PendingBilling" + ProvisioningStateSucceeded ProvisioningState = "Succeeded" +) + +// PossibleProvisioningStateValues returns the possible values for the ProvisioningState const type. +func PossibleProvisioningStateValues() []ProvisioningState { + return []ProvisioningState{ + ProvisioningStateCancelled, + ProvisioningStateConfirmedBilling, + ProvisioningStateCreated, + ProvisioningStateCreating, + ProvisioningStateExpired, + ProvisioningStateFailed, + ProvisioningStatePendingBilling, + ProvisioningStateSucceeded, + } +} + +// ReservedResourceType - The type of the resource that is being reserved. +type ReservedResourceType string + +const ( + ReservedResourceTypeAVS ReservedResourceType = "AVS" + ReservedResourceTypeAppService ReservedResourceType = "AppService" + ReservedResourceTypeAzureDataExplorer ReservedResourceType = "AzureDataExplorer" + ReservedResourceTypeAzureFiles ReservedResourceType = "AzureFiles" + ReservedResourceTypeBlockBlob ReservedResourceType = "BlockBlob" + ReservedResourceTypeCosmosDb ReservedResourceType = "CosmosDb" + ReservedResourceTypeDataFactory ReservedResourceType = "DataFactory" + ReservedResourceTypeDatabricks ReservedResourceType = "Databricks" + ReservedResourceTypeDedicatedHost ReservedResourceType = "DedicatedHost" + ReservedResourceTypeManagedDisk ReservedResourceType = "ManagedDisk" + ReservedResourceTypeMariaDb ReservedResourceType = "MariaDb" + ReservedResourceTypeMySQL ReservedResourceType = "MySql" + ReservedResourceTypeNetAppStorage ReservedResourceType = "NetAppStorage" + ReservedResourceTypePostgreSQL ReservedResourceType = "PostgreSql" + ReservedResourceTypeRedHat ReservedResourceType = "RedHat" + ReservedResourceTypeRedHatOsa ReservedResourceType = "RedHatOsa" + ReservedResourceTypeRedisCache ReservedResourceType = "RedisCache" + ReservedResourceTypeSQLAzureHybridBenefit ReservedResourceType = "SqlAzureHybridBenefit" + ReservedResourceTypeSQLDataWarehouse ReservedResourceType = "SqlDataWarehouse" + ReservedResourceTypeSQLDatabases ReservedResourceType = "SqlDatabases" + ReservedResourceTypeSQLEdge ReservedResourceType = "SqlEdge" + ReservedResourceTypeSapHana ReservedResourceType = "SapHana" + ReservedResourceTypeSuseLinux ReservedResourceType = "SuseLinux" + ReservedResourceTypeVMwareCloudSimple ReservedResourceType = "VMwareCloudSimple" + ReservedResourceTypeVirtualMachineSoftware ReservedResourceType = "VirtualMachineSoftware" + ReservedResourceTypeVirtualMachines ReservedResourceType = "VirtualMachines" +) + +// PossibleReservedResourceTypeValues returns the possible values for the ReservedResourceType const type. +func PossibleReservedResourceTypeValues() []ReservedResourceType { + return []ReservedResourceType{ + ReservedResourceTypeAVS, + ReservedResourceTypeAppService, + ReservedResourceTypeAzureDataExplorer, + ReservedResourceTypeAzureFiles, + ReservedResourceTypeBlockBlob, + ReservedResourceTypeCosmosDb, + ReservedResourceTypeDataFactory, + ReservedResourceTypeDatabricks, + ReservedResourceTypeDedicatedHost, + ReservedResourceTypeManagedDisk, + ReservedResourceTypeMariaDb, + ReservedResourceTypeMySQL, + ReservedResourceTypeNetAppStorage, + ReservedResourceTypePostgreSQL, + ReservedResourceTypeRedHat, + ReservedResourceTypeRedHatOsa, + ReservedResourceTypeRedisCache, + ReservedResourceTypeSQLAzureHybridBenefit, + ReservedResourceTypeSQLDataWarehouse, + ReservedResourceTypeSQLDatabases, + ReservedResourceTypeSQLEdge, + ReservedResourceTypeSapHana, + ReservedResourceTypeSuseLinux, + ReservedResourceTypeVMwareCloudSimple, + ReservedResourceTypeVirtualMachineSoftware, + ReservedResourceTypeVirtualMachines, + } +} + +// SKUTier - This field is required to be implemented by the Resource Provider if the service has more than one tier, but +// is not required on a PUT. +type SKUTier string + +const ( + // SKUTierBasic - The Basic service tier. + SKUTierBasic SKUTier = "Basic" + // SKUTierFree - The Free service tier. + SKUTierFree SKUTier = "Free" + // SKUTierPremium - The Premium service tier. + SKUTierPremium SKUTier = "Premium" + // SKUTierStandard - The Standard service tier. + SKUTierStandard SKUTier = "Standard" +) + +// PossibleSKUTierValues returns the possible values for the SKUTier const type. +func PossibleSKUTierValues() []SKUTier { + return []SKUTier{ + SKUTierBasic, + SKUTierFree, + SKUTierPremium, + SKUTierStandard, + } +} + +// ServiceManagedIdentityType - Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). +type ServiceManagedIdentityType string + +const ( + ServiceManagedIdentityTypeNone ServiceManagedIdentityType = "None" + ServiceManagedIdentityTypeSystemAssigned ServiceManagedIdentityType = "SystemAssigned" + ServiceManagedIdentityTypeSystemAssignedUserAssigned ServiceManagedIdentityType = "SystemAssigned,UserAssigned" + ServiceManagedIdentityTypeUserAssigned ServiceManagedIdentityType = "UserAssigned" +) + +// PossibleServiceManagedIdentityTypeValues returns the possible values for the ServiceManagedIdentityType const type. +func PossibleServiceManagedIdentityTypeValues() []ServiceManagedIdentityType { + return []ServiceManagedIdentityType{ + ServiceManagedIdentityTypeNone, + ServiceManagedIdentityTypeSystemAssigned, + ServiceManagedIdentityTypeSystemAssignedUserAssigned, + ServiceManagedIdentityTypeUserAssigned, + } +} + +// Term - Represent benefit term in ISO 8601 format. +type Term string + +const ( + TermP1M Term = "P1M" + TermP1Y Term = "P1Y" + TermP3Y Term = "P3Y" + TermP5Y Term = "P5Y" +) + +// PossibleTermValues returns the possible values for the Term const type. +func PossibleTermValues() []Term { + return []Term{ + TermP1M, + TermP1Y, + TermP3Y, + TermP5Y, + } +} diff --git a/test/local/armbillingbenefits/zz_contributors_client.go b/test/local/armbillingbenefits/zz_contributors_client.go new file mode 100644 index 000000000000..c95a5d3b8963 --- /dev/null +++ b/test/local/armbillingbenefits/zz_contributors_client.go @@ -0,0 +1,232 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armbillingbenefits + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ContributorsClient contains the methods for the Contributors group. +// Don't use this type directly, use NewContributorsClient() instead. +// +// Generated from API version 2025-12-01-preview +type ContributorsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewContributorsClient creates a new instance of ContributorsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewContributorsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ContributorsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ContributorsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// GetFromPrimary - Get a contributor for primary service admin +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - maccName - Name of primary MACC. +// - contributorName - Unique name of contributor in the format {contributorCloudSubId}_{resourceGroupName}_{nameInContributorTenant}. +// - options - ContributorsClientGetFromPrimaryOptions contains the optional parameters for the ContributorsClient.GetFromPrimary +// method. +func (client *ContributorsClient) GetFromPrimary(ctx context.Context, resourceGroupName string, maccName string, contributorName string, options *ContributorsClientGetFromPrimaryOptions) (ContributorsClientGetFromPrimaryResponse, error) { + var err error + const operationName = "ContributorsClient.GetFromPrimary" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getFromPrimaryCreateRequest(ctx, resourceGroupName, maccName, contributorName, options) + if err != nil { + return ContributorsClientGetFromPrimaryResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ContributorsClientGetFromPrimaryResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ContributorsClientGetFromPrimaryResponse{}, err + } + resp, err := client.getFromPrimaryHandleResponse(httpResp) + return resp, err +} + +// getFromPrimaryCreateRequest creates the GetFromPrimary request. +func (client *ContributorsClient) getFromPrimaryCreateRequest(ctx context.Context, resourceGroupName string, maccName string, contributorName string, _ *ContributorsClientGetFromPrimaryOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/maccs/{maccName}/contributors/{contributorName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if maccName == "" { + return nil, errors.New("parameter maccName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{maccName}", url.PathEscape(maccName)) + if contributorName == "" { + return nil, errors.New("parameter contributorName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{contributorName}", url.PathEscape(contributorName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getFromPrimaryHandleResponse handles the GetFromPrimary response. +func (client *ContributorsClient) getFromPrimaryHandleResponse(resp *http.Response) (ContributorsClientGetFromPrimaryResponse, error) { + result := ContributorsClientGetFromPrimaryResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Contributor); err != nil { + return ContributorsClientGetFromPrimaryResponse{}, err + } + return result, nil +} + +// NewListFromApplicableMaccPager - List contributors under applicable MACCs for a given billing account. +// - billingAccountID - The billing account Id at which the benefits are listed. Accepted format is: {rootId:orgId}. +// - systemID - System ID of the primary MACC. +// - options - ContributorsClientListFromApplicableMaccOptions contains the optional parameters for the ContributorsClient.NewListFromApplicableMaccPager +// method. +func (client *ContributorsClient) NewListFromApplicableMaccPager(billingAccountID string, systemID string, options *ContributorsClientListFromApplicableMaccOptions) *runtime.Pager[ContributorsClientListFromApplicableMaccResponse] { + return runtime.NewPager(runtime.PagingHandler[ContributorsClientListFromApplicableMaccResponse]{ + More: func(page ContributorsClientListFromApplicableMaccResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ContributorsClientListFromApplicableMaccResponse) (ContributorsClientListFromApplicableMaccResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ContributorsClient.NewListFromApplicableMaccPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listFromApplicableMaccCreateRequest(ctx, billingAccountID, systemID, options) + }, nil) + if err != nil { + return ContributorsClientListFromApplicableMaccResponse{}, err + } + return client.listFromApplicableMaccHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listFromApplicableMaccCreateRequest creates the ListFromApplicableMacc request. +func (client *ContributorsClient) listFromApplicableMaccCreateRequest(ctx context.Context, billingAccountID string, systemID string, _ *ContributorsClientListFromApplicableMaccOptions) (*policy.Request, error) { + urlPath := "/providers/microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.BillingBenefits/applicableMaccs/{systemId}/providers/microsoft.BillingBenefits/applicableContributors" + if billingAccountID == "" { + return nil, errors.New("parameter billingAccountID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{billingAccountId}", url.PathEscape(billingAccountID)) + if systemID == "" { + return nil, errors.New("parameter systemID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{systemId}", url.PathEscape(systemID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listFromApplicableMaccHandleResponse handles the ListFromApplicableMacc response. +func (client *ContributorsClient) listFromApplicableMaccHandleResponse(resp *http.Response) (ContributorsClientListFromApplicableMaccResponse, error) { + result := ContributorsClientListFromApplicableMaccResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ContributorList); err != nil { + return ContributorsClientListFromApplicableMaccResponse{}, err + } + return result, nil +} + +// NewListFromPrimaryPager - List contributors under a MACC for primary service admin +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - maccName - Name of primary MACC. +// - options - ContributorsClientListFromPrimaryOptions contains the optional parameters for the ContributorsClient.NewListFromPrimaryPager +// method. +func (client *ContributorsClient) NewListFromPrimaryPager(resourceGroupName string, maccName string, options *ContributorsClientListFromPrimaryOptions) *runtime.Pager[ContributorsClientListFromPrimaryResponse] { + return runtime.NewPager(runtime.PagingHandler[ContributorsClientListFromPrimaryResponse]{ + More: func(page ContributorsClientListFromPrimaryResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ContributorsClientListFromPrimaryResponse) (ContributorsClientListFromPrimaryResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ContributorsClient.NewListFromPrimaryPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listFromPrimaryCreateRequest(ctx, resourceGroupName, maccName, options) + }, nil) + if err != nil { + return ContributorsClientListFromPrimaryResponse{}, err + } + return client.listFromPrimaryHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listFromPrimaryCreateRequest creates the ListFromPrimary request. +func (client *ContributorsClient) listFromPrimaryCreateRequest(ctx context.Context, resourceGroupName string, maccName string, _ *ContributorsClientListFromPrimaryOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/maccs/{maccName}/contributors" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if maccName == "" { + return nil, errors.New("parameter maccName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{maccName}", url.PathEscape(maccName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listFromPrimaryHandleResponse handles the ListFromPrimary response. +func (client *ContributorsClient) listFromPrimaryHandleResponse(resp *http.Response) (ContributorsClientListFromPrimaryResponse, error) { + result := ContributorsClientListFromPrimaryResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ContributorList); err != nil { + return ContributorsClientListFromPrimaryResponse{}, err + } + return result, nil +} diff --git a/test/local/armbillingbenefits/zz_credits_client.go b/test/local/armbillingbenefits/zz_credits_client.go new file mode 100644 index 000000000000..a6fc395faa9d --- /dev/null +++ b/test/local/armbillingbenefits/zz_credits_client.go @@ -0,0 +1,564 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armbillingbenefits + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// CreditsClient contains the methods for the Credits group. +// Don't use this type directly, use NewCreditsClient() instead. +// +// Generated from API version 2025-12-01-preview +type CreditsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewCreditsClient creates a new instance of CreditsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewCreditsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CreditsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CreditsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCancel - Cancels a credit. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - creditName - Name of the credit +// - options - CreditsClientBeginCancelOptions contains the optional parameters for the CreditsClient.BeginCancel method. +func (client *CreditsClient) BeginCancel(ctx context.Context, resourceGroupName string, creditName string, options *CreditsClientBeginCancelOptions) (*runtime.Poller[CreditsClientCancelResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.cancel(ctx, resourceGroupName, creditName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CreditsClientCancelResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CreditsClientCancelResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Cancel - Cancels a credit. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CreditsClient) cancel(ctx context.Context, resourceGroupName string, creditName string, options *CreditsClientBeginCancelOptions) (*http.Response, error) { + var err error + const operationName = "CreditsClient.BeginCancel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.cancelCreateRequest(ctx, resourceGroupName, creditName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// cancelCreateRequest creates the Cancel request. +func (client *CreditsClient) cancelCreateRequest(ctx context.Context, resourceGroupName string, creditName string, _ *CreditsClientBeginCancelOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/credits/{creditName}/cancel" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if creditName == "" { + return nil, errors.New("parameter creditName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{creditName}", url.PathEscape(creditName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginCreate - Create a credit. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - creditName - Name of the credit +// - body - Credit create request +// - options - CreditsClientBeginCreateOptions contains the optional parameters for the CreditsClient.BeginCreate method. +func (client *CreditsClient) BeginCreate(ctx context.Context, resourceGroupName string, creditName string, body Credit, options *CreditsClientBeginCreateOptions) (*runtime.Poller[CreditsClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, resourceGroupName, creditName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CreditsClientCreateResponse]{ + FinalStateVia: runtime.FinalStateViaOriginalURI, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CreditsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Create a credit. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CreditsClient) create(ctx context.Context, resourceGroupName string, creditName string, body Credit, options *CreditsClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "CreditsClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, creditName, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *CreditsClient) createCreateRequest(ctx context.Context, resourceGroupName string, creditName string, body Credit, _ *CreditsClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/credits/{creditName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if creditName == "" { + return nil, errors.New("parameter creditName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{creditName}", url.PathEscape(creditName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a credit. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - creditName - Name of the credit +// - options - CreditsClientBeginDeleteOptions contains the optional parameters for the CreditsClient.BeginDelete method. +func (client *CreditsClient) BeginDelete(ctx context.Context, resourceGroupName string, creditName string, options *CreditsClientBeginDeleteOptions) (*runtime.Poller[CreditsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, creditName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CreditsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CreditsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a credit. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CreditsClient) deleteOperation(ctx context.Context, resourceGroupName string, creditName string, options *CreditsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "CreditsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, creditName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *CreditsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, creditName string, _ *CreditsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/credits/{creditName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if creditName == "" { + return nil, errors.New("parameter creditName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{creditName}", url.PathEscape(creditName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a credit. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - creditName - Name of the credit +// - options - CreditsClientGetOptions contains the optional parameters for the CreditsClient.Get method. +func (client *CreditsClient) Get(ctx context.Context, resourceGroupName string, creditName string, options *CreditsClientGetOptions) (CreditsClientGetResponse, error) { + var err error + const operationName = "CreditsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, creditName, options) + if err != nil { + return CreditsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CreditsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CreditsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *CreditsClient) getCreateRequest(ctx context.Context, resourceGroupName string, creditName string, _ *CreditsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/credits/{creditName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if creditName == "" { + return nil, errors.New("parameter creditName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{creditName}", url.PathEscape(creditName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *CreditsClient) getHandleResponse(resp *http.Response) (CreditsClientGetResponse, error) { + result := CreditsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Credit); err != nil { + return CreditsClientGetResponse{}, err + } + return result, nil +} + +// NewListApplicablePager - List applicable credits for the provided scope. Currently supported scopes: BillingAccountResourceId +// - scope - The scope at which the benefits are listed. +// - options - CreditsClientListApplicableOptions contains the optional parameters for the CreditsClient.NewListApplicablePager +// method. +func (client *CreditsClient) NewListApplicablePager(scope string, options *CreditsClientListApplicableOptions) *runtime.Pager[CreditsClientListApplicableResponse] { + return runtime.NewPager(runtime.PagingHandler[CreditsClientListApplicableResponse]{ + More: func(page CreditsClientListApplicableResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CreditsClientListApplicableResponse) (CreditsClientListApplicableResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CreditsClient.NewListApplicablePager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listApplicableCreateRequest(ctx, scope, options) + }, nil) + if err != nil { + return CreditsClientListApplicableResponse{}, err + } + return client.listApplicableHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listApplicableCreateRequest creates the ListApplicable request. +func (client *CreditsClient) listApplicableCreateRequest(ctx context.Context, scope string, _ *CreditsClientListApplicableOptions) (*policy.Request, error) { + urlPath := "/{scope}/providers/Microsoft.BillingBenefits/applicableCredits" + if scope == "" { + return nil, errors.New("parameter scope cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scope}", url.PathEscape(scope)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listApplicableHandleResponse handles the ListApplicable response. +func (client *CreditsClient) listApplicableHandleResponse(resp *http.Response) (CreditsClientListApplicableResponse, error) { + result := CreditsClientListApplicableResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CreditsList); err != nil { + return CreditsClientListApplicableResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - List Credits under a resource group from primary service admin. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - CreditsClientListByResourceGroupOptions contains the optional parameters for the CreditsClient.NewListByResourceGroupPager +// method. +func (client *CreditsClient) NewListByResourceGroupPager(resourceGroupName string, options *CreditsClientListByResourceGroupOptions) *runtime.Pager[CreditsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[CreditsClientListByResourceGroupResponse]{ + More: func(page CreditsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CreditsClientListByResourceGroupResponse) (CreditsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CreditsClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return CreditsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *CreditsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *CreditsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/credits" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *CreditsClient) listByResourceGroupHandleResponse(resp *http.Response) (CreditsClientListByResourceGroupResponse, error) { + result := CreditsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CreditsList); err != nil { + return CreditsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - List credits under a subscription from primary service tenant. +// - options - CreditsClientListBySubscriptionOptions contains the optional parameters for the CreditsClient.NewListBySubscriptionPager +// method. +func (client *CreditsClient) NewListBySubscriptionPager(options *CreditsClientListBySubscriptionOptions) *runtime.Pager[CreditsClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[CreditsClientListBySubscriptionResponse]{ + More: func(page CreditsClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CreditsClientListBySubscriptionResponse) (CreditsClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CreditsClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return CreditsClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *CreditsClient) listBySubscriptionCreateRequest(ctx context.Context, _ *CreditsClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.BillingBenefits/credits" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *CreditsClient) listBySubscriptionHandleResponse(resp *http.Response) (CreditsClientListBySubscriptionResponse, error) { + result := CreditsClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CreditsList); err != nil { + return CreditsClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update a credit. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - creditName - Name of the credit +// - body - Credit patch request +// - options - CreditsClientBeginUpdateOptions contains the optional parameters for the CreditsClient.BeginUpdate method. +func (client *CreditsClient) BeginUpdate(ctx context.Context, resourceGroupName string, creditName string, body CreditPatchRequest, options *CreditsClientBeginUpdateOptions) (*runtime.Poller[CreditsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, creditName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CreditsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CreditsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a credit. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CreditsClient) update(ctx context.Context, resourceGroupName string, creditName string, body CreditPatchRequest, options *CreditsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "CreditsClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, creditName, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *CreditsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, creditName string, body CreditPatchRequest, _ *CreditsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/credits/{creditName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if creditName == "" { + return nil, errors.New("parameter creditName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{creditName}", url.PathEscape(creditName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armbillingbenefits/zz_discount_client.go b/test/local/armbillingbenefits/zz_discount_client.go new file mode 100644 index 000000000000..68795abe4125 --- /dev/null +++ b/test/local/armbillingbenefits/zz_discount_client.go @@ -0,0 +1,181 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armbillingbenefits + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// DiscountClient contains the methods for the Discount group. +// Don't use this type directly, use NewDiscountClient() instead. +// +// Generated from API version 2025-12-01-preview +type DiscountClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDiscountClient creates a new instance of DiscountClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewDiscountClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DiscountClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DiscountClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get discount at resource group level +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - discountName - Name of the discount +// - options - DiscountClientGetOptions contains the optional parameters for the DiscountClient.Get method. +func (client *DiscountClient) Get(ctx context.Context, resourceGroupName string, discountName string, options *DiscountClientGetOptions) (DiscountClientGetResponse, error) { + var err error + const operationName = "DiscountClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, discountName, options) + if err != nil { + return DiscountClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DiscountClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DiscountClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DiscountClient) getCreateRequest(ctx context.Context, resourceGroupName string, discountName string, _ *DiscountClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/discounts/{discountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if discountName == "" { + return nil, errors.New("parameter discountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{discountName}", url.PathEscape(discountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DiscountClient) getHandleResponse(resp *http.Response) (DiscountClientGetResponse, error) { + result := DiscountClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Discount); err != nil { + return DiscountClientGetResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update discounts +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - discountName - Name of the discount +// - body - Request body for updating discounts +// - options - DiscountClientBeginUpdateOptions contains the optional parameters for the DiscountClient.BeginUpdate method. +func (client *DiscountClient) BeginUpdate(ctx context.Context, resourceGroupName string, discountName string, body DiscountPatchRequest, options *DiscountClientBeginUpdateOptions) (*runtime.Poller[DiscountClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, discountName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DiscountClientUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DiscountClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update discounts +// If the operation fails it returns an *azcore.ResponseError type. +func (client *DiscountClient) update(ctx context.Context, resourceGroupName string, discountName string, body DiscountPatchRequest, options *DiscountClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "DiscountClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, discountName, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *DiscountClient) updateCreateRequest(ctx context.Context, resourceGroupName string, discountName string, body DiscountPatchRequest, _ *DiscountClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/discounts/{discountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if discountName == "" { + return nil, errors.New("parameter discountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{discountName}", url.PathEscape(discountName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armbillingbenefits/zz_discounts_client.go b/test/local/armbillingbenefits/zz_discounts_client.go new file mode 100644 index 000000000000..519d78953175 --- /dev/null +++ b/test/local/armbillingbenefits/zz_discounts_client.go @@ -0,0 +1,425 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armbillingbenefits + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// DiscountsClient contains the methods for the Discounts group. +// Don't use this type directly, use NewDiscountsClient() instead. +// +// Generated from API version 2025-12-01-preview +type DiscountsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDiscountsClient creates a new instance of DiscountsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewDiscountsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DiscountsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DiscountsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCancel - Cancel discount. Stops applying the benefit. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - discountName - Name of the discount +// - options - DiscountsClientBeginCancelOptions contains the optional parameters for the DiscountsClient.BeginCancel method. +func (client *DiscountsClient) BeginCancel(ctx context.Context, resourceGroupName string, discountName string, options *DiscountsClientBeginCancelOptions) (*runtime.Poller[DiscountsClientCancelResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.cancel(ctx, resourceGroupName, discountName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DiscountsClientCancelResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DiscountsClientCancelResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Cancel - Cancel discount. Stops applying the benefit. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *DiscountsClient) cancel(ctx context.Context, resourceGroupName string, discountName string, options *DiscountsClientBeginCancelOptions) (*http.Response, error) { + var err error + const operationName = "DiscountsClient.BeginCancel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.cancelCreateRequest(ctx, resourceGroupName, discountName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// cancelCreateRequest creates the Cancel request. +func (client *DiscountsClient) cancelCreateRequest(ctx context.Context, resourceGroupName string, discountName string, _ *DiscountsClientBeginCancelOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/discounts/{discountName}/cancel" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if discountName == "" { + return nil, errors.New("parameter discountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{discountName}", url.PathEscape(discountName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginCreate - Create discount. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - discountName - Name of the discount +// - body - Request body for creating a discount. +// - options - DiscountsClientBeginCreateOptions contains the optional parameters for the DiscountsClient.BeginCreate method. +func (client *DiscountsClient) BeginCreate(ctx context.Context, resourceGroupName string, discountName string, body Discount, options *DiscountsClientBeginCreateOptions) (*runtime.Poller[DiscountsClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, resourceGroupName, discountName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DiscountsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DiscountsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Create discount. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *DiscountsClient) create(ctx context.Context, resourceGroupName string, discountName string, body Discount, options *DiscountsClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "DiscountsClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, discountName, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *DiscountsClient) createCreateRequest(ctx context.Context, resourceGroupName string, discountName string, body Discount, _ *DiscountsClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/discounts/{discountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if discountName == "" { + return nil, errors.New("parameter discountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{discountName}", url.PathEscape(discountName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete discount. Clears the metadata from the user's view. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - discountName - Name of the discount +// - options - DiscountsClientBeginDeleteOptions contains the optional parameters for the DiscountsClient.BeginDelete method. +func (client *DiscountsClient) BeginDelete(ctx context.Context, resourceGroupName string, discountName string, options *DiscountsClientBeginDeleteOptions) (*runtime.Poller[DiscountsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, discountName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DiscountsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DiscountsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete discount. Clears the metadata from the user's view. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *DiscountsClient) deleteOperation(ctx context.Context, resourceGroupName string, discountName string, options *DiscountsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "DiscountsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, discountName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *DiscountsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, discountName string, _ *DiscountsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/discounts/{discountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if discountName == "" { + return nil, errors.New("parameter discountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{discountName}", url.PathEscape(discountName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// NewResourceGroupListPager - List discounts at resource group level +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - DiscountsClientResourceGroupListOptions contains the optional parameters for the DiscountsClient.NewResourceGroupListPager +// method. +func (client *DiscountsClient) NewResourceGroupListPager(resourceGroupName string, options *DiscountsClientResourceGroupListOptions) *runtime.Pager[DiscountsClientResourceGroupListResponse] { + return runtime.NewPager(runtime.PagingHandler[DiscountsClientResourceGroupListResponse]{ + More: func(page DiscountsClientResourceGroupListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DiscountsClientResourceGroupListResponse) (DiscountsClientResourceGroupListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DiscountsClient.NewResourceGroupListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.resourceGroupListCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return DiscountsClientResourceGroupListResponse{}, err + } + return client.resourceGroupListHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// resourceGroupListCreateRequest creates the ResourceGroupList request. +func (client *DiscountsClient) resourceGroupListCreateRequest(ctx context.Context, resourceGroupName string, _ *DiscountsClientResourceGroupListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/discounts" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// resourceGroupListHandleResponse handles the ResourceGroupList response. +func (client *DiscountsClient) resourceGroupListHandleResponse(resp *http.Response) (DiscountsClientResourceGroupListResponse, error) { + result := DiscountsClientResourceGroupListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DiscountList); err != nil { + return DiscountsClientResourceGroupListResponse{}, err + } + return result, nil +} + +// NewScopeListPager - List discounts that are applicable for a given scope. Currently supported scopes: billing accounts +// - scope - The scope at which the benefits are listed. +// - options - DiscountsClientScopeListOptions contains the optional parameters for the DiscountsClient.NewScopeListPager method. +func (client *DiscountsClient) NewScopeListPager(scope string, options *DiscountsClientScopeListOptions) *runtime.Pager[DiscountsClientScopeListResponse] { + return runtime.NewPager(runtime.PagingHandler[DiscountsClientScopeListResponse]{ + More: func(page DiscountsClientScopeListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DiscountsClientScopeListResponse) (DiscountsClientScopeListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DiscountsClient.NewScopeListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.scopeListCreateRequest(ctx, scope, options) + }, nil) + if err != nil { + return DiscountsClientScopeListResponse{}, err + } + return client.scopeListHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// scopeListCreateRequest creates the ScopeList request. +func (client *DiscountsClient) scopeListCreateRequest(ctx context.Context, scope string, _ *DiscountsClientScopeListOptions) (*policy.Request, error) { + urlPath := "/{scope}/providers/Microsoft.BillingBenefits/applicableDiscounts" + if scope == "" { + return nil, errors.New("parameter scope cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scope}", url.PathEscape(scope)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// scopeListHandleResponse handles the ScopeList response. +func (client *DiscountsClient) scopeListHandleResponse(resp *http.Response) (DiscountsClientScopeListResponse, error) { + result := DiscountsClientScopeListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DiscountList); err != nil { + return DiscountsClientScopeListResponse{}, err + } + return result, nil +} + +// NewSubscriptionListPager - List discounts at subscription level +// - options - DiscountsClientSubscriptionListOptions contains the optional parameters for the DiscountsClient.NewSubscriptionListPager +// method. +func (client *DiscountsClient) NewSubscriptionListPager(options *DiscountsClientSubscriptionListOptions) *runtime.Pager[DiscountsClientSubscriptionListResponse] { + return runtime.NewPager(runtime.PagingHandler[DiscountsClientSubscriptionListResponse]{ + More: func(page DiscountsClientSubscriptionListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DiscountsClientSubscriptionListResponse) (DiscountsClientSubscriptionListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DiscountsClient.NewSubscriptionListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.subscriptionListCreateRequest(ctx, options) + }, nil) + if err != nil { + return DiscountsClientSubscriptionListResponse{}, err + } + return client.subscriptionListHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// subscriptionListCreateRequest creates the SubscriptionList request. +func (client *DiscountsClient) subscriptionListCreateRequest(ctx context.Context, _ *DiscountsClientSubscriptionListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.BillingBenefits/discounts" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// subscriptionListHandleResponse handles the SubscriptionList response. +func (client *DiscountsClient) subscriptionListHandleResponse(resp *http.Response) (DiscountsClientSubscriptionListResponse, error) { + result := DiscountsClientSubscriptionListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DiscountList); err != nil { + return DiscountsClientSubscriptionListResponse{}, err + } + return result, nil +} diff --git a/test/local/armbillingbenefits/zz_freeservices_client.go b/test/local/armbillingbenefits/zz_freeservices_client.go new file mode 100644 index 000000000000..4698d2f22f49 --- /dev/null +++ b/test/local/armbillingbenefits/zz_freeservices_client.go @@ -0,0 +1,443 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armbillingbenefits + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// FreeServicesClient contains the methods for the FreeServices group. +// Don't use this type directly, use NewFreeServicesClient() instead. +// +// Generated from API version 2025-12-01-preview +type FreeServicesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewFreeServicesClient creates a new instance of FreeServicesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewFreeServicesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*FreeServicesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &FreeServicesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreate - This operation creates or updates free services in Azure +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - freeServiceName - Name of the free service +// - body - Free services create request +// - options - FreeServicesClientBeginCreateOptions contains the optional parameters for the FreeServicesClient.BeginCreate +// method. +func (client *FreeServicesClient) BeginCreate(ctx context.Context, resourceGroupName string, freeServiceName string, body FreeServices, options *FreeServicesClientBeginCreateOptions) (*runtime.Poller[FreeServicesClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, resourceGroupName, freeServiceName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FreeServicesClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FreeServicesClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - This operation creates or updates free services in Azure +// If the operation fails it returns an *azcore.ResponseError type. +func (client *FreeServicesClient) create(ctx context.Context, resourceGroupName string, freeServiceName string, body FreeServices, options *FreeServicesClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "FreeServicesClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, freeServiceName, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *FreeServicesClient) createCreateRequest(ctx context.Context, resourceGroupName string, freeServiceName string, body FreeServices, _ *FreeServicesClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/freeServices/{freeServiceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if freeServiceName == "" { + return nil, errors.New("parameter freeServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{freeServiceName}", url.PathEscape(freeServiceName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - This operation deletes free services from the subscription. Only free services that are in an expired or +// cancelled states can be deleted. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - freeServiceName - Name of the free service +// - options - FreeServicesClientBeginDeleteOptions contains the optional parameters for the FreeServicesClient.BeginDelete +// method. +func (client *FreeServicesClient) BeginDelete(ctx context.Context, resourceGroupName string, freeServiceName string, options *FreeServicesClientBeginDeleteOptions) (*runtime.Poller[FreeServicesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, freeServiceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FreeServicesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FreeServicesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - This operation deletes free services from the subscription. Only free services that are in an expired or cancelled +// states can be deleted. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *FreeServicesClient) deleteOperation(ctx context.Context, resourceGroupName string, freeServiceName string, options *FreeServicesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "FreeServicesClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, freeServiceName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *FreeServicesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, freeServiceName string, _ *FreeServicesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/freeServices/{freeServiceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if freeServiceName == "" { + return nil, errors.New("parameter freeServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{freeServiceName}", url.PathEscape(freeServiceName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - This operation retrieves properties for free services. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - freeServiceName - Name of the free service +// - options - FreeServicesClientGetOptions contains the optional parameters for the FreeServicesClient.Get method. +func (client *FreeServicesClient) Get(ctx context.Context, resourceGroupName string, freeServiceName string, options *FreeServicesClientGetOptions) (FreeServicesClientGetResponse, error) { + var err error + const operationName = "FreeServicesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, freeServiceName, options) + if err != nil { + return FreeServicesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FreeServicesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FreeServicesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *FreeServicesClient) getCreateRequest(ctx context.Context, resourceGroupName string, freeServiceName string, _ *FreeServicesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/freeServices/{freeServiceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if freeServiceName == "" { + return nil, errors.New("parameter freeServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{freeServiceName}", url.PathEscape(freeServiceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *FreeServicesClient) getHandleResponse(resp *http.Response) (FreeServicesClientGetResponse, error) { + result := FreeServicesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FreeServices); err != nil { + return FreeServicesClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - This operation lists the free services that are available under the specified resource group. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - FreeServicesClientListByResourceGroupOptions contains the optional parameters for the FreeServicesClient.NewListByResourceGroupPager +// method. +func (client *FreeServicesClient) NewListByResourceGroupPager(resourceGroupName string, options *FreeServicesClientListByResourceGroupOptions) *runtime.Pager[FreeServicesClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[FreeServicesClientListByResourceGroupResponse]{ + More: func(page FreeServicesClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *FreeServicesClientListByResourceGroupResponse) (FreeServicesClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "FreeServicesClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return FreeServicesClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *FreeServicesClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *FreeServicesClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/freeServices" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *FreeServicesClient) listByResourceGroupHandleResponse(resp *http.Response) (FreeServicesClientListByResourceGroupResponse, error) { + result := FreeServicesClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FreeServicesList); err != nil { + return FreeServicesClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - This operation lists free services that are available under the specified subscription. +// - options - FreeServicesClientListBySubscriptionOptions contains the optional parameters for the FreeServicesClient.NewListBySubscriptionPager +// method. +func (client *FreeServicesClient) NewListBySubscriptionPager(options *FreeServicesClientListBySubscriptionOptions) *runtime.Pager[FreeServicesClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[FreeServicesClientListBySubscriptionResponse]{ + More: func(page FreeServicesClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *FreeServicesClientListBySubscriptionResponse) (FreeServicesClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "FreeServicesClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return FreeServicesClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *FreeServicesClient) listBySubscriptionCreateRequest(ctx context.Context, _ *FreeServicesClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.BillingBenefits/freeServices" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *FreeServicesClient) listBySubscriptionHandleResponse(resp *http.Response) (FreeServicesClientListBySubscriptionResponse, error) { + result := FreeServicesClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FreeServicesList); err != nil { + return FreeServicesClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// BeginUpdate - This operation updates free services in Azure. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - freeServiceName - Name of the free service +// - body - Free services patch request +// - options - FreeServicesClientBeginUpdateOptions contains the optional parameters for the FreeServicesClient.BeginUpdate +// method. +func (client *FreeServicesClient) BeginUpdate(ctx context.Context, resourceGroupName string, freeServiceName string, body FreeServicesPatchRequest, options *FreeServicesClientBeginUpdateOptions) (*runtime.Poller[FreeServicesClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, freeServiceName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FreeServicesClientUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FreeServicesClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - This operation updates free services in Azure. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *FreeServicesClient) update(ctx context.Context, resourceGroupName string, freeServiceName string, body FreeServicesPatchRequest, options *FreeServicesClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "FreeServicesClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, freeServiceName, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *FreeServicesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, freeServiceName string, body FreeServicesPatchRequest, _ *FreeServicesClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/freeServices/{freeServiceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if freeServiceName == "" { + return nil, errors.New("parameter freeServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{freeServiceName}", url.PathEscape(freeServiceName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armbillingbenefits/zz_interfaces.go b/test/local/armbillingbenefits/zz_interfaces.go new file mode 100644 index 000000000000..e434be681381 --- /dev/null +++ b/test/local/armbillingbenefits/zz_interfaces.go @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armbillingbenefits + +// BenefitValidateModelClassification provides polymorphic access to related types. +// Call the interface's GetBenefitValidateModel() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *BenefitValidateModel, *ConditionalCreditsValidateModel, *CreditsValidateModel, *MaccValidateModel, *SavingsPlanValidateModel +type BenefitValidateModelClassification interface { + // GetBenefitValidateModel returns the BenefitValidateModel content of the underlying type. + GetBenefitValidateModel() *BenefitValidateModel +} + +// ConditionalCreditPropertiesClassification provides polymorphic access to related types. +// Call the interface's GetConditionalCreditProperties() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *ConditionalCreditProperties, *ContributorConditionalCreditProperties, *PrimaryConditionalCreditProperties +type ConditionalCreditPropertiesClassification interface { + // GetConditionalCreditProperties returns the ConditionalCreditProperties content of the underlying type. + GetConditionalCreditProperties() *ConditionalCreditProperties +} + +// DiscountPropertiesClassification provides polymorphic access to related types. +// Call the interface's GetDiscountProperties() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *DiscountProperties, *EntityTypeAffiliateDiscount, *EntityTypePrimaryDiscount +type DiscountPropertiesClassification interface { + // GetDiscountProperties returns the DiscountProperties content of the underlying type. + GetDiscountProperties() *DiscountProperties +} + +// DiscountTypeCustomPriceClassification provides polymorphic access to related types. +// Call the interface's GetDiscountTypeCustomPrice() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *DiscountTypeCustomPrice, *DiscountTypeCustomPriceMultiCurrency +type DiscountTypeCustomPriceClassification interface { + DiscountTypePropertiesClassification + // GetDiscountTypeCustomPrice returns the DiscountTypeCustomPrice content of the underlying type. + GetDiscountTypeCustomPrice() *DiscountTypeCustomPrice +} + +// DiscountTypePropertiesClassification provides polymorphic access to related types. +// Call the interface's GetDiscountTypeProperties() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *DiscountTypeCustomPrice, *DiscountTypeCustomPriceMultiCurrency, *DiscountTypeProduct, *DiscountTypeProductFamily, *DiscountTypeProductSKU, +// - *DiscountTypeProperties +type DiscountTypePropertiesClassification interface { + // GetDiscountTypeProperties returns the DiscountTypeProperties content of the underlying type. + GetDiscountTypeProperties() *DiscountTypeProperties +} diff --git a/test/local/armbillingbenefits/zz_maccs_client.go b/test/local/armbillingbenefits/zz_maccs_client.go new file mode 100644 index 000000000000..f39567482434 --- /dev/null +++ b/test/local/armbillingbenefits/zz_maccs_client.go @@ -0,0 +1,667 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armbillingbenefits + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// MaccsClient contains the methods for the Maccs group. +// Don't use this type directly, use NewMaccsClient() instead. +// +// Generated from API version 2025-12-01-preview +type MaccsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewMaccsClient creates a new instance of MaccsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewMaccsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*MaccsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &MaccsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCancel - Represents an operation to cancel MACC contract. This operation does not indicate deletion of the MACC, but +// rather stops applying the benefit to the account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - maccName - Name of primary MACC. +// - options - MaccsClientBeginCancelOptions contains the optional parameters for the MaccsClient.BeginCancel method. +func (client *MaccsClient) BeginCancel(ctx context.Context, resourceGroupName string, maccName string, options *MaccsClientBeginCancelOptions) (*runtime.Poller[MaccsClientCancelResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.cancel(ctx, resourceGroupName, maccName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[MaccsClientCancelResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[MaccsClientCancelResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Cancel - Represents an operation to cancel MACC contract. This operation does not indicate deletion of the MACC, but rather +// stops applying the benefit to the account. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *MaccsClient) cancel(ctx context.Context, resourceGroupName string, maccName string, options *MaccsClientBeginCancelOptions) (*http.Response, error) { + var err error + const operationName = "MaccsClient.BeginCancel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.cancelCreateRequest(ctx, resourceGroupName, maccName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// cancelCreateRequest creates the Cancel request. +func (client *MaccsClient) cancelCreateRequest(ctx context.Context, resourceGroupName string, maccName string, _ *MaccsClientBeginCancelOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/maccs/{maccName}/cancel" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if maccName == "" { + return nil, errors.New("parameter maccName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{maccName}", url.PathEscape(maccName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginChargeShortfall - Operation to charge shortfall to a customer's account, ensuring they are charged for the outstanding +// amount of MACC credit. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - maccName - Name of primary MACC. +// - body - Request body for charging shortfall. +// - options - MaccsClientBeginChargeShortfallOptions contains the optional parameters for the MaccsClient.BeginChargeShortfall +// method. +func (client *MaccsClient) BeginChargeShortfall(ctx context.Context, resourceGroupName string, maccName string, body ChargeShortfallRequest, options *MaccsClientBeginChargeShortfallOptions) (*runtime.Poller[MaccsClientChargeShortfallResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.chargeShortfall(ctx, resourceGroupName, maccName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[MaccsClientChargeShortfallResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[MaccsClientChargeShortfallResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ChargeShortfall - Operation to charge shortfall to a customer's account, ensuring they are charged for the outstanding +// amount of MACC credit. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *MaccsClient) chargeShortfall(ctx context.Context, resourceGroupName string, maccName string, body ChargeShortfallRequest, options *MaccsClientBeginChargeShortfallOptions) (*http.Response, error) { + var err error + const operationName = "MaccsClient.BeginChargeShortfall" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.chargeShortfallCreateRequest(ctx, resourceGroupName, maccName, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// chargeShortfallCreateRequest creates the ChargeShortfall request. +func (client *MaccsClient) chargeShortfallCreateRequest(ctx context.Context, resourceGroupName string, maccName string, body ChargeShortfallRequest, _ *MaccsClientBeginChargeShortfallOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/maccs/{maccName}/chargeShortfall" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if maccName == "" { + return nil, errors.New("parameter maccName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{maccName}", url.PathEscape(maccName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// BeginCreate - Create MACC. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - maccName - Name of primary MACC. +// - body - Request body for creating MACC. +// - options - MaccsClientBeginCreateOptions contains the optional parameters for the MaccsClient.BeginCreate method. +func (client *MaccsClient) BeginCreate(ctx context.Context, resourceGroupName string, maccName string, body Macc, options *MaccsClientBeginCreateOptions) (*runtime.Poller[MaccsClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, resourceGroupName, maccName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[MaccsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[MaccsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Create MACC. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *MaccsClient) create(ctx context.Context, resourceGroupName string, maccName string, body Macc, options *MaccsClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "MaccsClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, maccName, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *MaccsClient) createCreateRequest(ctx context.Context, resourceGroupName string, maccName string, body Macc, _ *MaccsClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/maccs/{maccName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if maccName == "" { + return nil, errors.New("parameter maccName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{maccName}", url.PathEscape(maccName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete MACC. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - maccName - Name of primary MACC. +// - options - MaccsClientBeginDeleteOptions contains the optional parameters for the MaccsClient.BeginDelete method. +func (client *MaccsClient) BeginDelete(ctx context.Context, resourceGroupName string, maccName string, options *MaccsClientBeginDeleteOptions) (*runtime.Poller[MaccsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, maccName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[MaccsClientDeleteResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[MaccsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete MACC. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *MaccsClient) deleteOperation(ctx context.Context, resourceGroupName string, maccName string, options *MaccsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "MaccsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, maccName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *MaccsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, maccName string, _ *MaccsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/maccs/{maccName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if maccName == "" { + return nil, errors.New("parameter maccName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{maccName}", url.PathEscape(maccName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a MACC. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - maccName - Name of primary MACC. +// - options - MaccsClientGetOptions contains the optional parameters for the MaccsClient.Get method. +func (client *MaccsClient) Get(ctx context.Context, resourceGroupName string, maccName string, options *MaccsClientGetOptions) (MaccsClientGetResponse, error) { + var err error + const operationName = "MaccsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, maccName, options) + if err != nil { + return MaccsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MaccsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return MaccsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *MaccsClient) getCreateRequest(ctx context.Context, resourceGroupName string, maccName string, _ *MaccsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/maccs/{maccName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if maccName == "" { + return nil, errors.New("parameter maccName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{maccName}", url.PathEscape(maccName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *MaccsClient) getHandleResponse(resp *http.Response) (MaccsClientGetResponse, error) { + result := MaccsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Macc); err != nil { + return MaccsClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - List MACCs under a resource group for primary service admin. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - MaccsClientListByResourceGroupOptions contains the optional parameters for the MaccsClient.NewListByResourceGroupPager +// method. +func (client *MaccsClient) NewListByResourceGroupPager(resourceGroupName string, options *MaccsClientListByResourceGroupOptions) *runtime.Pager[MaccsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[MaccsClientListByResourceGroupResponse]{ + More: func(page MaccsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *MaccsClientListByResourceGroupResponse) (MaccsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "MaccsClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return MaccsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *MaccsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *MaccsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/maccs" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *MaccsClient) listByResourceGroupHandleResponse(resp *http.Response) (MaccsClientListByResourceGroupResponse, error) { + result := MaccsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.MaccList); err != nil { + return MaccsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - List MACCs under a subscription from primary service tenant. +// - options - MaccsClientListBySubscriptionOptions contains the optional parameters for the MaccsClient.NewListBySubscriptionPager +// method. +func (client *MaccsClient) NewListBySubscriptionPager(options *MaccsClientListBySubscriptionOptions) *runtime.Pager[MaccsClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[MaccsClientListBySubscriptionResponse]{ + More: func(page MaccsClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *MaccsClientListBySubscriptionResponse) (MaccsClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "MaccsClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return MaccsClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *MaccsClient) listBySubscriptionCreateRequest(ctx context.Context, _ *MaccsClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.BillingBenefits/maccs" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *MaccsClient) listBySubscriptionHandleResponse(resp *http.Response) (MaccsClientListBySubscriptionResponse, error) { + result := MaccsClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.MaccList); err != nil { + return MaccsClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update MACC. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - maccName - Name of primary MACC. +// - body - Request body for updating MACC. +// - options - MaccsClientBeginUpdateOptions contains the optional parameters for the MaccsClient.BeginUpdate method. +func (client *MaccsClient) BeginUpdate(ctx context.Context, resourceGroupName string, maccName string, body MaccPatchRequest, options *MaccsClientBeginUpdateOptions) (*runtime.Poller[MaccsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, maccName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[MaccsClientUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[MaccsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update MACC. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *MaccsClient) update(ctx context.Context, resourceGroupName string, maccName string, body MaccPatchRequest, options *MaccsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "MaccsClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, maccName, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *MaccsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, maccName string, body MaccPatchRequest, _ *MaccsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/maccs/{maccName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if maccName == "" { + return nil, errors.New("parameter maccName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{maccName}", url.PathEscape(maccName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// BeginWriteOff - Operation to waive a customer's pending MACC balance (Shortfall) from their account, ensuring they are +// not charged for the outstanding amount. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - maccName - Name of primary MACC. +// - options - MaccsClientBeginWriteOffOptions contains the optional parameters for the MaccsClient.BeginWriteOff method. +func (client *MaccsClient) BeginWriteOff(ctx context.Context, resourceGroupName string, maccName string, options *MaccsClientBeginWriteOffOptions) (*runtime.Poller[MaccsClientWriteOffResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.writeOff(ctx, resourceGroupName, maccName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[MaccsClientWriteOffResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[MaccsClientWriteOffResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// WriteOff - Operation to waive a customer's pending MACC balance (Shortfall) from their account, ensuring they are not charged +// for the outstanding amount. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *MaccsClient) writeOff(ctx context.Context, resourceGroupName string, maccName string, options *MaccsClientBeginWriteOffOptions) (*http.Response, error) { + var err error + const operationName = "MaccsClient.BeginWriteOff" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.writeOffCreateRequest(ctx, resourceGroupName, maccName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// writeOffCreateRequest creates the WriteOff request. +func (client *MaccsClient) writeOffCreateRequest(ctx context.Context, resourceGroupName string, maccName string, _ *MaccsClientBeginWriteOffOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/maccs/{maccName}/writeOff" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if maccName == "" { + return nil, errors.New("parameter maccName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{maccName}", url.PathEscape(maccName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} diff --git a/test/local/armbillingbenefits/zz_models.go b/test/local/armbillingbenefits/zz_models.go new file mode 100644 index 000000000000..a7ae446d7564 --- /dev/null +++ b/test/local/armbillingbenefits/zz_models.go @@ -0,0 +1,2491 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armbillingbenefits + +import "time" + +// ApplicableMacc - Applicable MACC. +type ApplicableMacc struct { + // Applicable MACC properties + Properties *MaccModelProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ApplicableMaccList - Applicable MACC list +type ApplicableMaccList struct { + // Url to get the next page. + NextLink *string + + // List Applicable MACCs. + Value []*ApplicableMacc +} + +// AppliedScopeProperties - Properties specific to applied scope type. Not required if not applicable. +type AppliedScopeProperties struct { + // Display name + DisplayName *string + + // Fully-qualified identifier of the management group where the benefit must be applied. + ManagementGroupID *string + + // Fully-qualified identifier of the resource group. + ResourceGroupID *string + + // Fully-qualified identifier of the subscription. + SubscriptionID *string + + // Tenant ID where the benefit is applied. + TenantID *string +} + +// AutomaticShortfallSuppressReason - Optional field to record suppression reason for automatic shortfall. +type AutomaticShortfallSuppressReason struct { + // Code for the suppression reason. + Code *string + + // Message for suppression reason. + Message *string +} + +// Award details for milestone completion +type Award struct { + // Credit amount to be awarded + Credit *Commitment + + // Duration for which the benefit is active. Will be in format P{int}M or P{int}Y. Any values representing up to 12 years + // are valid. Upper limit examples: P144M, P12Y. + Duration *Term + + // End date when the credit expires + EndAt *time.Time + + // Start date when the credit becomes effective + StartAt *time.Time + + // READ-ONLY; Points to BalanceVersion document that indicates the remaining commitment balance when the credit was created. + BalanceVersion *float32 + + // READ-ONLY; Resource ID for the awarded credit. + ResourceID *string + + // READ-ONLY; This is the globally unique identifier of the credit which will not change for its lifetime. + SystemID *string +} + +// BenefitValidateModel - Abstract benefit model to validate. +type BenefitValidateModel struct { + // REQUIRED; Type of benefit to validate. This is used to determine the model type for validation. + BenefitType *BenefitType +} + +// GetBenefitValidateModel implements the BenefitValidateModelClassification interface for type BenefitValidateModel. +func (b *BenefitValidateModel) GetBenefitValidateModel() *BenefitValidateModel { return b } + +// BenefitValidateRequest - Request to validate any benefit. +type BenefitValidateRequest struct { + // Defines benefits for validation. + Benefits []BenefitValidateModelClassification +} + +// BenefitValidateResponse - Benefit validate response. +type BenefitValidateResponse struct { + // Defines benefit validation response for benefits. + Benefits []*BenefitValidateResponseProperty + + // Url to get the next page. + NextLink *string +} + +// BenefitValidateResponseProperty - Benefit validate response property +type BenefitValidateResponseProperty struct { + // Failure reason if the provided input was invalid + Reason *string + + // Failure reason code if the provided input was invalid + ReasonCode *string + + // Resource identifier of the benefit that was validated. + ResourceID *string + + // Indicates if the provided input was valid + Valid *bool +} + +// BillingPlanInformation - Information describing the type of billing plan for this savings plan. +type BillingPlanInformation struct { + // For recurring billing plans, indicates the date when next payment will be processed. Null when total is paid off. + NextPaymentDueDate *time.Time + + // Amount of money to be paid for the Order. Tax is not included. + PricingCurrencyTotal *Price + + // Date when the billing plan has started. + StartDate *time.Time + Transactions []*PaymentDetail +} + +// CatalogClaimsItem - Catalog claim for a discount. +type CatalogClaimsItem struct { + CatalogClaimsItemType *string + Value *string +} + +// ChargeShortfallRequest - Charge shortfall request +type ChargeShortfallRequest struct { + // Charge shortfall request properties + Properties *Shortfall +} + +// Commitment towards the benefit. +type Commitment struct { + Amount *float64 + + // The ISO 4217 3-letter currency code for the currency used by this purchase record. + CurrencyCode *string + + // The grain of the commitment. + Grain *CommitmentGrain +} + +// ConditionalCredit - Resource definition for Conditional Credits. +type ConditionalCredit struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // Managed service identity (system assigned and/or user assigned identities) + Identity *ManagedServiceIdentity + + // Metadata used by portal/tooling/etc to render different UX experiences for resources of the same type. E.g. ApiApps are + // a kind of Microsoft.Web/sites type. If supported, the resource provider must validate and persist this value. + Kind *string + + // The fully qualified resource ID of the resource that manages this resource. Indicates if this resource is managed by another + // Azure resource. If this is present, complete mode deployment will not delete the resource if it is removed from the template + // since it is managed by another resource. + ManagedBy *string + + // Plan for the resource. + Plan *Plan + + // Conditional credit properties + Properties ConditionalCreditPropertiesClassification + + // The resource model definition representing SKU + SKU *SKU + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; The etag field is *not* required. If it is provided in the response body, it must also be provided as a header + // per the normal etag convention. Entity tags are used for comparing two or more entities from the same requested resource. + // HTTP/1.1 uses entity tags in the etag (section 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range + // (section 14.27) header fields. + Etag *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ConditionalCreditContributor - Conditional credit contributor +type ConditionalCreditContributor struct { + // Conditional credit contributor properties + Properties *ContributorConditionalCreditProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ConditionalCreditContributorList - Conditional credit contributor list +type ConditionalCreditContributorList struct { + // REQUIRED; The ConditionalCreditContributor items on this page + Value []*ConditionalCreditContributor + + // The link to the next page of items + NextLink *string +} + +// ConditionalCreditList - List of applicable conditional credits +type ConditionalCreditList struct { + // REQUIRED; The ConditionalCredit items on this page + Value []*ConditionalCredit + + // The link to the next page of items + NextLink *string +} + +// ConditionalCreditMilestone - Milestone definition within a conditional credit +type ConditionalCreditMilestone struct { + // Award details for this milestone + Award *Award + + // End date for this milestone + EndAt *time.Time + + // Unique identifier for the milestone + MilestoneID *string + + // Display name for the milestone + Name *string + + // Spend target for this milestone + SpendTarget *Price + + // Current status of the milestone + Status *MilestoneStatus +} + +// ConditionalCreditPatchRequest - Conditional credit patch request +type ConditionalCreditPatchRequest struct { + // Conditional credit patch request properties + Properties *ConditionalCreditPatchRequestProperties + + // Resource tags. + Tags map[string]*string +} + +// ConditionalCreditPatchRequestProperties - Conditional credit patch request properties +type ConditionalCreditPatchRequestProperties struct { + // Whether this conditional credit allows contributor billing accounts + AllowContributors *EnablementMode + + // Display name for the conditional credit + DisplayName *string + + // End DateTime in UTC. + EndAt *time.Time + + // Updated milestones list (only applicable for primary conditional credits) + Milestones []*ConditionalCreditMilestone +} + +// ConditionalCreditProperties - Properties belonging to conditional credits. +type ConditionalCreditProperties struct { + // REQUIRED; Type of conditional credit entity + EntityType *ConditionalCreditEntityType + + // The billing account resource ID + BillingAccountResourceID *string + + // Display name for the conditional credit + DisplayName *string + + // End date of the conditional credit (derived from last milestone) + EndAt *time.Time + + // Product code for the conditional credit + ProductCode *string + + // Fully-qualified resource identifier of the resource. Format: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/{benefitType}/{benefitName}. + ResourceID *string + + // Start date of the conditional credit + StartAt *time.Time + + // The status of the conditional credit + Status *ConditionalCreditStatus + + // READ-ONLY; Fully-qualified identifier of the benefit under applicable benefit list. + BenefitResourceID *string + + // READ-ONLY; The provisioning state of the resource + ProvisioningState *ConditionalCreditsProvisioningState +} + +// GetConditionalCreditProperties implements the ConditionalCreditPropertiesClassification interface for type ConditionalCreditProperties. +func (c *ConditionalCreditProperties) GetConditionalCreditProperties() *ConditionalCreditProperties { + return c +} + +// ConditionalCreditsValidateModel - Conditional Credits validate model +type ConditionalCreditsValidateModel struct { + // CONSTANT; Type of benefit to validate. This is used to determine the model type for validation. + // Field has constant value BenefitTypeConditionalCredits, any specified value is ignored. + BenefitType *BenefitType + + // Conditional Credits validate properties + Properties ConditionalCreditPropertiesClassification +} + +// GetBenefitValidateModel implements the BenefitValidateModelClassification interface for type ConditionalCreditsValidateModel. +func (c *ConditionalCreditsValidateModel) GetBenefitValidateModel() *BenefitValidateModel { + return &BenefitValidateModel{ + BenefitType: c.BenefitType, + } +} + +// ConditionsItem - Condition for a discount. +type ConditionsItem struct { + ConditionName *string + Type *string + + // These items are open-ended strings. + Value []*string +} + +// Contributor - MACC contributor +type Contributor struct { + // MACC contributor properties + Properties *MaccModelProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ContributorConditionalCreditMilestone - Milestone definition for contributor conditional credit (excludes award details) +type ContributorConditionalCreditMilestone struct { + // Award details for this milestone (only present for primary conditional credits) + Award *Award + + // End date for this milestone + EndAt *time.Time + + // Unique identifier for the milestone + MilestoneID *string + + // Display name for the milestone + Name *string + + // Spend target for this milestone + SpendTarget *Price + + // Current status of the milestone + Status *MilestoneStatus +} + +// ContributorConditionalCreditProperties - Properties for contributor conditional credit. +type ContributorConditionalCreditProperties struct { + // CONSTANT; Type of conditional credit entity + // Field has constant value ConditionalCreditEntityTypeContributor, any specified value is ignored. + EntityType *ConditionalCreditEntityType + + // The billing account resource ID + BillingAccountResourceID *string + + // Display name for the conditional credit + DisplayName *string + + // End date of the conditional credit (derived from last milestone) + EndAt *time.Time + + // Fully-qualified billing account resource identifier of the primary CACO. Format must be Azure Resource ID: /providers/Microsoft.Billing/billingAccounts/{acctId:orgId}. + PrimaryBillingAccountResourceID *string + + // Resource ID of the primary conditional credit (required for contributors) + PrimaryResourceID *string + + // Product code for the contributor conditional credit + ProductCode *string + + // Fully-qualified resource identifier of the resource. Format: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/{benefitType}/{benefitName}. + ResourceID *string + + // Start date for the contributor conditional credit + StartAt *time.Time + + // The status of the conditional credit + Status *ConditionalCreditStatus + + // System identifier shared between primary and contributor conditional credits representing the same conditional credit program + SystemID *string + + // READ-ONLY; Fully-qualified identifier of the benefit under applicable benefit list. + BenefitResourceID *string + + // READ-ONLY; List of milestones copied from primary conditional credit (excludes award details) + Milestones []*ContributorConditionalCreditMilestone + + // READ-ONLY; The provisioning state of the resource + ProvisioningState *ConditionalCreditsProvisioningState +} + +// GetConditionalCreditProperties implements the ConditionalCreditPropertiesClassification interface for type ContributorConditionalCreditProperties. +func (c *ContributorConditionalCreditProperties) GetConditionalCreditProperties() *ConditionalCreditProperties { + return &ConditionalCreditProperties{ + BenefitResourceID: c.BenefitResourceID, + BillingAccountResourceID: c.BillingAccountResourceID, + DisplayName: c.DisplayName, + EndAt: c.EndAt, + EntityType: c.EntityType, + ProductCode: c.ProductCode, + ProvisioningState: c.ProvisioningState, + ResourceID: c.ResourceID, + StartAt: c.StartAt, + Status: c.Status, + } +} + +// ContributorList - Contributor list +type ContributorList struct { + // REQUIRED; The Contributor items on this page + Value []*Contributor + + // The link to the next page of items + NextLink *string +} + +// Credit resource definition +type Credit struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // Managed service identity (system assigned and/or user assigned identities) + Identity *ManagedServiceIdentity + + // Metadata used by portal/tooling/etc to render different UX experiences for resources of the same type. E.g. ApiApps are + // a kind of Microsoft.Web/sites type. If supported, the resource provider must validate and persist this value. + Kind *string + + // The fully qualified resource ID of the resource that manages this resource. Indicates if this resource is managed by another + // Azure resource. If this is present, complete mode deployment will not delete the resource if it is removed from the template + // since it is managed by another resource. + ManagedBy *string + + // Plan for the resource. + Plan *Plan + + // Credit properties + Properties *CreditProperties + + // The resource model definition representing SKU + SKU *SKU + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; The etag field is *not* required. If it is provided in the response body, it must also be provided as a header + // per the normal etag convention. Entity tags are used for comparing two or more entities from the same requested resource. + // HTTP/1.1 uses entity tags in the etag (section 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range + // (section 14.27) header fields. + Etag *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// CreditBreakdownItem - Credit breakdown item representing a milestone, line-item, or no-charge service +type CreditBreakdownItem struct { + // Allocation details including currency and amount for this breakdown item + Allocation *Commitment + + // Key-value pairs for additional parameters and metadata + Dimensions []*CreditDimension + + // End DateTime in UTC. + EndAt *time.Time + + // Start DateTime. + StartAt *time.Time +} + +// CreditDimension - Key-value pair for additional credit parameters and metadata +type CreditDimension struct { + // REQUIRED; The dimension key (e.g., productFamily, description, creditType) + Key *string + + // REQUIRED; The dimension value + Value *string +} + +// CreditPatchProperties - Credit patch properties +type CreditPatchProperties struct { + // Credit line-items/milestones/no-charge services breakdown. Entire breakdown will be replaced in a PATCH operation. + Breakdown []*CreditBreakdownItem + + // The entire investment amount for the credit contract, including currency and amount. Only amount can be modified. + Credit *Commitment + + // End DateTime in UTC. + EndAt *time.Time +} + +// CreditPatchRequest - Credit patch request +type CreditPatchRequest struct { + // Credit patch properties + Properties *CreditPatchProperties + + // Resource tags + Tags map[string]*string +} + +// CreditPolicies - Credit breakdown item representing a milestone, line-item, or no-charge service +type CreditPolicies struct { + // Expiration policy of the Credit + Expiration *CreditExpirationPolicy + + // Redemption policy of the Credit + Redemption *CreditRedemptionPolicy +} + +// CreditProperties - Properties of a credit +type CreditProperties struct { + // Fully-qualified identifier of the billing account where the benefit is applied. Present only for Enterprise Agreement customers. + BillingAccountResourceID *string + + // Credit line-items/milestones/no-charge services breakdown + Breakdown []*CreditBreakdownItem + + // The entire investment amount for the credit contract, including currency and amount + Credit *Commitment + + // End DateTime in UTC. + EndAt *time.Time + + // Credit breakdown item representing a milestone, line-item, or no-charge service + Policies *CreditPolicies + + // Product UPN for the credit type + ProductCode *string + + // The reason for the credit. Not required if not applicable. + Reason *CreditReason + + // Fully-qualified resource identifier of the resource. Format: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/{benefitType}/{benefitName}. + ResourceID *string + + // Start DateTime. + StartAt *time.Time + + // Status of the credit + Status *CreditStatus + + // System identifier + SystemID *string + + // READ-ONLY; Fully-qualified identifier of the billing profile where the benefit is applied. Present only for Field-led or + // Customer-led customers. + BillingProfileResourceID *string + + // READ-ONLY; Fully-qualified identifier of the customer where the savings plan is applied. Present only for Partner-led customers. + // Format is /providers/Microsoft.Billing/billingAccounts/{acctId:orgId} + CustomerID *string + + // READ-ONLY; Provisioning state + ProvisioningState *ProvisioningState +} + +// CreditReason - The reason for the credit. Not required if not applicable. +type CreditReason struct { + // The reason code for credit. + Code *string + + // The free string description of the credit. + Description *string +} + +// CreditSource - Credit source resource definition +type CreditSource struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // Managed service identity (system assigned and/or user assigned identities) + Identity *ManagedServiceIdentity + + // Metadata used by portal/tooling/etc to render different UX experiences for resources of the same type. E.g. ApiApps are + // a kind of Microsoft.Web/sites type. If supported, the resource provider must validate and persist this value. + Kind *string + + // The fully qualified resource ID of the resource that manages this resource. Indicates if this resource is managed by another + // Azure resource. If this is present, complete mode deployment will not delete the resource if it is removed from the template + // since it is managed by another resource. + ManagedBy *string + + // Plan for the resource. + Plan *Plan + + // Credit source properties + Properties *CreditSourceProperties + + // The resource model definition representing SKU + SKU *SKU + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; The etag field is *not* required. If it is provided in the response body, it must also be provided as a header + // per the normal etag convention. Entity tags are used for comparing two or more entities from the same requested resource. + // HTTP/1.1 uses entity tags in the etag (section 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range + // (section 14.27) header fields. + Etag *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// CreditSourcePatchRequest - Credit patch request +type CreditSourcePatchRequest struct { + // Resource Tags + Tags map[string]*string +} + +// CreditSourceProperties - Properties of a credit source +type CreditSourceProperties struct { + // Commitment towards the benefit. + Credit *Commitment + + // The billing period of the impact for the resource. Format YYYYMM + ImpactedBillingPeriod *string + + // The uri of the resource impacted which lead to the grant of the credit. + SourceResourceID *string + + // Status of the credit + Status *CreditStatus +} + +// CreditSourcesList - List of credit sources +type CreditSourcesList struct { + // REQUIRED; The CreditSource items on this page + Value []*CreditSource + + // The link to the next page of items + NextLink *string +} + +// CreditsList - List of credits +type CreditsList struct { + // REQUIRED; The Credit items on this page + Value []*Credit + + // The link to the next page of items + NextLink *string +} + +// CreditsValidateModel - Credits validate model +type CreditsValidateModel struct { + // CONSTANT; Type of benefit to validate. This is used to determine the model type for validation. + // Field has constant value BenefitTypeCredits, any specified value is ignored. + BenefitType *BenefitType + + // Credits validate properties + Properties *Credit +} + +// GetBenefitValidateModel implements the BenefitValidateModelClassification interface for type CreditsValidateModel. +func (c *CreditsValidateModel) GetBenefitValidateModel() *BenefitValidateModel { + return &BenefitValidateModel{ + BenefitType: c.BenefitType, + } +} + +// CustomPriceProperties - Custom price properties for a given discount. +type CustomPriceProperties struct { + // REQUIRED; The set of BigCat claims. Validation: Required. Must contain AgreementType, NationalCloud, and PricingAudience + // claims. Additionally requires AccessPass claim when creating custom price with action == consume on the pricing instructions. + CatalogClaims []*CatalogClaimsItem + + // REQUIRED; The catalog instance where the priceable node lives. Validation: Required. No defined format, will vary per team. + CatalogID *string + + // REQUIRED; The set of market set prices of the priceable node. Validation: Required. Must contain at least one element. + MarketSetPrices []*MarketSetPricesItems + + // REQUIRED; The type of the priceable node pricing rule. Validation: Required. Supported values are fixedPriceLock, fixedListPrice, + // and priceCeiling. + RuleType *DiscountRuleType + + // The billing period of the priceable node. Validation: Optional, Maximum length 128 characters. Only allowed if the availability + // derived by market, product, sku, and claims has terms and at least one of those terms has a billing period. When specified, + // termUnits must be specified. + BillingPeriod *string + + // Must be present if the market, product, sku, and claims, and optional term information resolves to multiple availabilities + // that only differ by meter type. Validation: Maximum length 128 characters. + MeterType *string + + // The term units for the priceable node. Validation: Optional, Maximum length 128 characters. Must be present if and only + // if the availability derived by market, product, sku, and claims has terms. + TermUnits *string +} + +// Discount - Resource definition for Discounts. +type Discount struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // Managed service identity (system assigned and/or user assigned identities) + Identity *ServiceManagedIdentity + + // Metadata used by portal/tooling/etc to render different UX experiences for resources of the same type. E.g. ApiApps are + // a kind of Microsoft.Web/sites type. If supported, the resource provider must validate and persist this value. + Kind *string + + // The fully qualified resource ID of the resource that manages this resource. Indicates if this resource is managed by another + // Azure resource. If this is present, complete mode deployment will not delete the resource if it is removed from the template + // since it is managed by another resource. + ManagedBy *string + + // Plan for the resource. + Plan *Plan + + // Discount properties + Properties DiscountPropertiesClassification + + // The resource model definition representing SKU + SKU *SKU + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; The etag field is *not* required. If it is provided in the response body, it must also be provided as a header + // per the normal etag convention. Entity tags are used for comparing two or more entities from the same requested resource. + // HTTP/1.1 uses entity tags in the etag (section 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range + // (section 14.27) header fields. + Etag *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// DiscountList - Discount list +type DiscountList struct { + // REQUIRED; The Discount items on this page + Value []*Discount + + // The link to the next page of items + NextLink *string +} + +// DiscountPatchRequest - Discounts patch request +type DiscountPatchRequest struct { + // Discounts patch request properties + Properties *DiscountPatchRequestProperties + + // Resource tags. + Tags map[string]*string +} + +// DiscountPatchRequestProperties - Discounts patch request properties +type DiscountPatchRequestProperties struct { + // Display name + DisplayName *string +} + +// DiscountProperties - Properties belonging to discounts. +type DiscountProperties struct { + // REQUIRED; This defines whether the entity being created is primary or affiliate. Supported values: primary, affiliate. + // Validation: Required, must match one of the 2 values. + EntityType *DiscountEntityType + + // REQUIRED; This is the catalog UPN for the product. + ProductCode *string + + // REQUIRED; Start date of the discount. Value is the date the discount started or will start in the future. + StartAt *time.Time + + // List of applied scopes supported for discounts. + AppliedScopeType *DiscountAppliedScopeType + + // This defines a user friendly display name for the discount. + DisplayName *string + + // This is the globally unique identifier of the Discount which will not change for the lifetime of the Discount. + SystemID *string + + // READ-ONLY; Fully-qualified identifier of the benefit under applicable benefit list. + BenefitResourceID *string + + // READ-ONLY; Billing account resource id where the discount metadata is present. + BillingAccountResourceID *string + + // READ-ONLY; Billing profile resource id where the discount is scoped to. + BillingProfileResourceID *string + + // READ-ONLY; Customer resource id where the discount is scoped to. + CustomerResourceID *string + + // READ-ONLY; The state of the resource. Supported values are Pending, Failed, Succeeded, Canceled. + ProvisioningState *DiscountProvisioningState + + // READ-ONLY; Represents the current status of the discount. + Status *DiscountStatus +} + +// GetDiscountProperties implements the DiscountPropertiesClassification interface for type DiscountProperties. +func (d *DiscountProperties) GetDiscountProperties() *DiscountProperties { return d } + +// DiscountTypeCustomPrice - Discount type properties including product family name, product id, sku, and custom price properties. +// Allows a single entry in marketSetPrices. +type DiscountTypeCustomPrice struct { + // REQUIRED; The customer action on which the discount is applied. Supported values are Purchase, Consume, and Renew. Validation: + // Required, one of supported values. + ApplyDiscountOn *ApplyDiscountOn + + // CONSTANT; Defines the type of discount. Supported values are ProductFamily, Product, Sku, CustomPrice, and CustomPriceMultiCurrency. + // Field has constant value DiscountTypeEnumCustomPrice, any specified value is ignored. + DiscountType *DiscountTypeEnum + + // Array of conditions for the discount. Validation: Optional. Maximum length is 1000. + Conditions []*ConditionsItem + + // Custom price properties for a given discount. + CustomPriceProperties *CustomPriceProperties + + // The discount combination rule when there are multiple applicable custom prices. Validation: Required. Supported values + // are Stackable and BestOf. + DiscountCombinationRule *DiscountCombinationRule + + // Discount percentage provided for the customer. Validation: Required unless this is a price rule. + DiscountPercentage *float64 + + // Set only in price guarantee scenario. + PriceGuaranteeProperties *PriceGuaranteeProperties + + // Product family for which the discount is given. Validation: Optional + ProductFamilyName *string + + // Product ID for which the discount is given. Validation: Optional. No specific format, example: DZH318Z09V6F + ProductID *string + + // ResourceSku for the given discount. Validation: Optional. + SKUID *string +} + +// GetDiscountTypeCustomPrice implements the DiscountTypeCustomPriceClassification interface for type DiscountTypeCustomPrice. +func (d *DiscountTypeCustomPrice) GetDiscountTypeCustomPrice() *DiscountTypeCustomPrice { return d } + +// GetDiscountTypeProperties implements the DiscountTypePropertiesClassification interface for type DiscountTypeCustomPrice. +func (d *DiscountTypeCustomPrice) GetDiscountTypeProperties() *DiscountTypeProperties { + return &DiscountTypeProperties{ + ApplyDiscountOn: d.ApplyDiscountOn, + Conditions: d.Conditions, + DiscountCombinationRule: d.DiscountCombinationRule, + DiscountPercentage: d.DiscountPercentage, + DiscountType: d.DiscountType, + PriceGuaranteeProperties: d.PriceGuaranteeProperties, + } +} + +// DiscountTypeCustomPriceMultiCurrency - Discount type properties including product family name, product id, sku, and custom +// price properties. Allows multiple entries in marketSetPrices. +type DiscountTypeCustomPriceMultiCurrency struct { + // REQUIRED; The customer action on which the discount is applied. Supported values are Purchase, Consume, and Renew. Validation: + // Required, one of supported values. + ApplyDiscountOn *ApplyDiscountOn + + // CONSTANT; Defines the type of discount. Supported values are ProductFamily, Product, Sku, CustomPrice, and CustomPriceMultiCurrency. + // Field has constant value DiscountTypeEnumCustomPriceMultiCurrency, any specified value is ignored. + DiscountType *DiscountTypeEnum + + // Array of conditions for the discount. Validation: Optional. Maximum length is 1000. + Conditions []*ConditionsItem + + // Custom price properties for a given discount. + CustomPriceProperties *CustomPriceProperties + + // The discount combination rule when there are multiple applicable custom prices. Validation: Required. Supported values + // are Stackable and BestOf. + DiscountCombinationRule *DiscountCombinationRule + + // Discount percentage provided for the customer. Validation: Required unless this is a price rule. + DiscountPercentage *float64 + + // Set only in price guarantee scenario. + PriceGuaranteeProperties *PriceGuaranteeProperties + + // Product family for which the discount is given. Validation: Optional + ProductFamilyName *string + + // Product ID for which the discount is given. Validation: Optional. No specific format, example: DZH318Z09V6F + ProductID *string + + // ResourceSku for the given discount. Validation: Optional. + SKUID *string +} + +// GetDiscountTypeCustomPrice implements the DiscountTypeCustomPriceClassification interface for type DiscountTypeCustomPriceMultiCurrency. +func (d *DiscountTypeCustomPriceMultiCurrency) GetDiscountTypeCustomPrice() *DiscountTypeCustomPrice { + return &DiscountTypeCustomPrice{ + ApplyDiscountOn: d.ApplyDiscountOn, + Conditions: d.Conditions, + CustomPriceProperties: d.CustomPriceProperties, + DiscountCombinationRule: d.DiscountCombinationRule, + DiscountPercentage: d.DiscountPercentage, + DiscountType: d.DiscountType, + PriceGuaranteeProperties: d.PriceGuaranteeProperties, + ProductFamilyName: d.ProductFamilyName, + ProductID: d.ProductID, + SKUID: d.SKUID, + } +} + +// GetDiscountTypeProperties implements the DiscountTypePropertiesClassification interface for type DiscountTypeCustomPriceMultiCurrency. +func (d *DiscountTypeCustomPriceMultiCurrency) GetDiscountTypeProperties() *DiscountTypeProperties { + return &DiscountTypeProperties{ + ApplyDiscountOn: d.ApplyDiscountOn, + Conditions: d.Conditions, + DiscountCombinationRule: d.DiscountCombinationRule, + DiscountPercentage: d.DiscountPercentage, + DiscountType: d.DiscountType, + PriceGuaranteeProperties: d.PriceGuaranteeProperties, + } +} + +// DiscountTypeProduct - Discount type properties including product family name and product id. +type DiscountTypeProduct struct { + // REQUIRED; The customer action on which the discount is applied. Supported values are Purchase, Consume, and Renew. Validation: + // Required, one of supported values. + ApplyDiscountOn *ApplyDiscountOn + + // CONSTANT; Defines the type of discount. Supported values are ProductFamily, Product, Sku, CustomPrice, and CustomPriceMultiCurrency. + // Field has constant value DiscountTypeEnumProduct, any specified value is ignored. + DiscountType *DiscountTypeEnum + + // Array of conditions for the discount. Validation: Optional. Maximum length is 1000. + Conditions []*ConditionsItem + + // The discount combination rule when there are multiple applicable custom prices. Validation: Required. Supported values + // are Stackable and BestOf. + DiscountCombinationRule *DiscountCombinationRule + + // Discount percentage provided for the customer. Validation: Required unless this is a price rule. + DiscountPercentage *float64 + + // Set only in price guarantee scenario. + PriceGuaranteeProperties *PriceGuaranteeProperties + + // Product family for which the discount is given. Validation: Optional + ProductFamilyName *string + + // Product ID for which the discount is given. Validation: Optional. No specific format, example: DZH318Z09V6F + ProductID *string +} + +// GetDiscountTypeProperties implements the DiscountTypePropertiesClassification interface for type DiscountTypeProduct. +func (d *DiscountTypeProduct) GetDiscountTypeProperties() *DiscountTypeProperties { + return &DiscountTypeProperties{ + ApplyDiscountOn: d.ApplyDiscountOn, + Conditions: d.Conditions, + DiscountCombinationRule: d.DiscountCombinationRule, + DiscountPercentage: d.DiscountPercentage, + DiscountType: d.DiscountType, + PriceGuaranteeProperties: d.PriceGuaranteeProperties, + } +} + +// DiscountTypeProductFamily - Discount type properties including product family name +type DiscountTypeProductFamily struct { + // REQUIRED; The customer action on which the discount is applied. Supported values are Purchase, Consume, and Renew. Validation: + // Required, one of supported values. + ApplyDiscountOn *ApplyDiscountOn + + // CONSTANT; Defines the type of discount. Supported values are ProductFamily, Product, Sku, CustomPrice, and CustomPriceMultiCurrency. + // Field has constant value DiscountTypeEnumProductFamily, any specified value is ignored. + DiscountType *DiscountTypeEnum + + // Array of conditions for the discount. Validation: Optional. Maximum length is 1000. + Conditions []*ConditionsItem + + // The discount combination rule when there are multiple applicable custom prices. Validation: Required. Supported values + // are Stackable and BestOf. + DiscountCombinationRule *DiscountCombinationRule + + // Discount percentage provided for the customer. Validation: Required unless this is a price rule. + DiscountPercentage *float64 + + // Set only in price guarantee scenario. + PriceGuaranteeProperties *PriceGuaranteeProperties + + // Product family for which the discount is given. Validation: Optional + ProductFamilyName *string +} + +// GetDiscountTypeProperties implements the DiscountTypePropertiesClassification interface for type DiscountTypeProductFamily. +func (d *DiscountTypeProductFamily) GetDiscountTypeProperties() *DiscountTypeProperties { + return &DiscountTypeProperties{ + ApplyDiscountOn: d.ApplyDiscountOn, + Conditions: d.Conditions, + DiscountCombinationRule: d.DiscountCombinationRule, + DiscountPercentage: d.DiscountPercentage, + DiscountType: d.DiscountType, + PriceGuaranteeProperties: d.PriceGuaranteeProperties, + } +} + +// DiscountTypeProductSKU - Discount type properties including product family name, product id, and sku id. +type DiscountTypeProductSKU struct { + // REQUIRED; The customer action on which the discount is applied. Supported values are Purchase, Consume, and Renew. Validation: + // Required, one of supported values. + ApplyDiscountOn *ApplyDiscountOn + + // CONSTANT; Defines the type of discount. Supported values are ProductFamily, Product, Sku, CustomPrice, and CustomPriceMultiCurrency. + // Field has constant value DiscountTypeEnumSKU, any specified value is ignored. + DiscountType *DiscountTypeEnum + + // Array of conditions for the discount. Validation: Optional. Maximum length is 1000. + Conditions []*ConditionsItem + + // The discount combination rule when there are multiple applicable custom prices. Validation: Required. Supported values + // are Stackable and BestOf. + DiscountCombinationRule *DiscountCombinationRule + + // Discount percentage provided for the customer. Validation: Required unless this is a price rule. + DiscountPercentage *float64 + + // Set only in price guarantee scenario. + PriceGuaranteeProperties *PriceGuaranteeProperties + + // Product family for which the discount is given. Validation: Optional + ProductFamilyName *string + + // Product ID for which the discount is given. Validation: Optional. No specific format, example: DZH318Z09V6F + ProductID *string + + // ResourceSku for the given discount. Validation: Optional. + SKUID *string +} + +// GetDiscountTypeProperties implements the DiscountTypePropertiesClassification interface for type DiscountTypeProductSKU. +func (d *DiscountTypeProductSKU) GetDiscountTypeProperties() *DiscountTypeProperties { + return &DiscountTypeProperties{ + ApplyDiscountOn: d.ApplyDiscountOn, + Conditions: d.Conditions, + DiscountCombinationRule: d.DiscountCombinationRule, + DiscountPercentage: d.DiscountPercentage, + DiscountType: d.DiscountType, + PriceGuaranteeProperties: d.PriceGuaranteeProperties, + } +} + +// DiscountTypeProperties - This defines the conditions for a given discount type. +type DiscountTypeProperties struct { + // REQUIRED; The customer action on which the discount is applied. Supported values are Purchase, Consume, and Renew. Validation: + // Required, one of supported values. + ApplyDiscountOn *ApplyDiscountOn + + // REQUIRED; Defines the type of discount. Supported values are ProductFamily, Product, Sku, CustomPrice, and CustomPriceMultiCurrency. + DiscountType *DiscountTypeEnum + + // Array of conditions for the discount. Validation: Optional. Maximum length is 1000. + Conditions []*ConditionsItem + + // The discount combination rule when there are multiple applicable custom prices. Validation: Required. Supported values + // are Stackable and BestOf. + DiscountCombinationRule *DiscountCombinationRule + + // Discount percentage provided for the customer. Validation: Required unless this is a price rule. + DiscountPercentage *float64 + + // Set only in price guarantee scenario. + PriceGuaranteeProperties *PriceGuaranteeProperties +} + +// GetDiscountTypeProperties implements the DiscountTypePropertiesClassification interface for type DiscountTypeProperties. +func (d *DiscountTypeProperties) GetDiscountTypeProperties() *DiscountTypeProperties { return d } + +// EntityTypeAffiliateDiscount - Entity type for affiliate discounts +type EntityTypeAffiliateDiscount struct { + // CONSTANT; This defines whether the entity being created is primary or affiliate. Supported values: primary, affiliate. + // Validation: Required, must match one of the 2 values. + // Field has constant value DiscountEntityTypeAffiliate, any specified value is ignored. + EntityType *DiscountEntityType + + // REQUIRED; This is the catalog UPN for the product. + ProductCode *string + + // REQUIRED; Start date of the discount. Value is the date the discount started or will start in the future. + StartAt *time.Time + + // List of applied scopes supported for discounts. + AppliedScopeType *DiscountAppliedScopeType + + // This defines a user friendly display name for the discount. + DisplayName *string + + // This is the globally unique identifier of the Discount which will not change for the lifetime of the Discount. + SystemID *string + + // READ-ONLY; Fully-qualified identifier of the benefit under applicable benefit list. + BenefitResourceID *string + + // READ-ONLY; Billing account resource id where the discount metadata is present. + BillingAccountResourceID *string + + // READ-ONLY; Billing profile resource id where the discount is scoped to. + BillingProfileResourceID *string + + // READ-ONLY; Customer resource id where the discount is scoped to. + CustomerResourceID *string + + // READ-ONLY; End date of the discount. No duration will be supported. Allowed value is any date greater than or equal to + // startDate. + EndAt *time.Time + + // READ-ONLY; This will be present in the response if the primary has a resource ID + PrimaryResourceID *string + + // READ-ONLY; The state of the resource. Supported values are Pending, Failed, Succeeded, Canceled. + ProvisioningState *DiscountProvisioningState + + // READ-ONLY; Represents the current status of the discount. + Status *DiscountStatus +} + +// GetDiscountProperties implements the DiscountPropertiesClassification interface for type EntityTypeAffiliateDiscount. +func (e *EntityTypeAffiliateDiscount) GetDiscountProperties() *DiscountProperties { + return &DiscountProperties{ + AppliedScopeType: e.AppliedScopeType, + BenefitResourceID: e.BenefitResourceID, + BillingAccountResourceID: e.BillingAccountResourceID, + BillingProfileResourceID: e.BillingProfileResourceID, + CustomerResourceID: e.CustomerResourceID, + DisplayName: e.DisplayName, + EntityType: e.EntityType, + ProductCode: e.ProductCode, + ProvisioningState: e.ProvisioningState, + StartAt: e.StartAt, + Status: e.Status, + SystemID: e.SystemID, + } +} + +// EntityTypePrimaryDiscount - Entity type for primary discounts +type EntityTypePrimaryDiscount struct { + // REQUIRED; End date of the discount. No duration will be supported. Allowed value is any date greater than or equal to startDate. + EndAt *time.Time + + // CONSTANT; This defines whether the entity being created is primary or affiliate. Supported values: primary, affiliate. + // Validation: Required, must match one of the 2 values. + // Field has constant value DiscountEntityTypePrimary, any specified value is ignored. + EntityType *DiscountEntityType + + // REQUIRED; This is the catalog UPN for the product. + ProductCode *string + + // REQUIRED; Start date of the discount. Value is the date the discount started or will start in the future. + StartAt *time.Time + + // List of applied scopes supported for discounts. + AppliedScopeType *DiscountAppliedScopeType + + // This defines the conditions for a given discount type. + DiscountTypeProperties DiscountTypePropertiesClassification + + // This defines a user friendly display name for the discount. + DisplayName *string + + // This is the globally unique identifier of the Discount which will not change for the lifetime of the Discount. + SystemID *string + + // READ-ONLY; Fully-qualified identifier of the benefit under applicable benefit list. + BenefitResourceID *string + + // READ-ONLY; Billing account resource id where the discount metadata is present. + BillingAccountResourceID *string + + // READ-ONLY; Billing profile resource id where the discount is scoped to. + BillingProfileResourceID *string + + // READ-ONLY; Customer resource id where the discount is scoped to. + CustomerResourceID *string + + // READ-ONLY; The state of the resource. Supported values are Pending, Failed, Succeeded, Canceled. + ProvisioningState *DiscountProvisioningState + + // READ-ONLY; Represents the current status of the discount. + Status *DiscountStatus +} + +// GetDiscountProperties implements the DiscountPropertiesClassification interface for type EntityTypePrimaryDiscount. +func (e *EntityTypePrimaryDiscount) GetDiscountProperties() *DiscountProperties { + return &DiscountProperties{ + AppliedScopeType: e.AppliedScopeType, + BenefitResourceID: e.BenefitResourceID, + BillingAccountResourceID: e.BillingAccountResourceID, + BillingProfileResourceID: e.BillingProfileResourceID, + CustomerResourceID: e.CustomerResourceID, + DisplayName: e.DisplayName, + EntityType: e.EntityType, + ProductCode: e.ProductCode, + ProvisioningState: e.ProvisioningState, + StartAt: e.StartAt, + Status: e.Status, + SystemID: e.SystemID, + } +} + +type ExtendedStatusInfo struct { + // The message giving detailed information about the status code. + Message *string + + // Status code providing additional information. + StatusCode *string +} + +// FreeServices - Free Services resource definition +type FreeServices struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // Managed service identity (system assigned and/or user assigned identities) + Identity *ManagedServiceIdentity + + // Metadata used by portal/tooling/etc to render different UX experiences for resources of the same type. E.g. ApiApps are + // a kind of Microsoft.Web/sites type. If supported, the resource provider must validate and persist this value. + Kind *string + + // The fully qualified resource ID of the resource that manages this resource. Indicates if this resource is managed by another + // Azure resource. If this is present, complete mode deployment will not delete the resource if it is removed from the template + // since it is managed by another resource. + ManagedBy *string + + // Plan for the resource. + Plan *Plan + + // Free services properties + Properties *FreeServicesProperties + + // The resource model definition representing SKU + SKU *SKU + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; The etag field is *not* required. If it is provided in the response body, it must also be provided as a header + // per the normal etag convention. Entity tags are used for comparing two or more entities from the same requested resource. + // HTTP/1.1 uses entity tags in the etag (section 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range + // (section 14.27) header fields. + Etag *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// FreeServicesList - This operation lists the free services that are available under the specified subscription. +type FreeServicesList struct { + // The list of free services + Value []*FreeServices + + // READ-ONLY; The URL to get the next set of results + NextLink *string +} + +// FreeServicesPatchRequest - Free services patch request +type FreeServicesPatchRequest struct { + // Free services patch request properties + Properties *FreeServicesPatchRequestProperties + + // Resource tags. + Tags map[string]*string +} + +// FreeServicesPatchRequestProperties - Free services patch request properties +type FreeServicesPatchRequestProperties struct { + // Updated expiration date and time of the free services + EndAt *time.Time +} + +// FreeServicesProperties - Properties of free services +type FreeServicesProperties struct { + // Expiration date and time of the free services + EndAt *time.Time + + // This is the catalog UPN for the product. + ProductCode *string + + // Date and time when the free services become active + StartAt *time.Time + + // Current status of the free services + Status *FreeServicesStatus + + // This is the globally unique identifier of the free services which will not change for its lifetime. + SystemID *string + + // READ-ONLY; Billing account resource id where the free services metadata is present. + BillingAccountResourceID *string + + // READ-ONLY; Billing profile resource id where the free services are scoped to. + BillingProfileResourceID *string + + // READ-ONLY; Customer resource id where the free services are scoped to. + CustomerResourceID *string + + // READ-ONLY; Provisioning state of Free Services as assigned by RPaaS. This indicates the last operation's status. For all + // practical purposes, this can be ignored. For current status of Free Services resource, refer to FreeServicesStatus. + ProvisioningState *string +} + +// Macc - Microsoft Azure Consumption Commitment. +type Macc struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // Managed service identity (system assigned and/or user assigned identities) + Identity *ManagedServiceIdentity + + // Metadata used by portal/tooling/etc to render different UX experiences for resources of the same type. E.g. ApiApps are + // a kind of Microsoft.Web/sites type. If supported, the resource provider must validate and persist this value. + Kind *string + + // The fully qualified resource ID of the resource that manages this resource. Indicates if this resource is managed by another + // Azure resource. If this is present, complete mode deployment will not delete the resource if it is removed from the template + // since it is managed by another resource. + ManagedBy *string + + // Plan for the resource. + Plan *Plan + + // MACC properties + Properties *MaccModelProperties + + // The resource model definition representing SKU + SKU *SKU + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; The etag field is *not* required. If it is provided in the response body, it must also be provided as a header + // per the normal etag convention. Entity tags are used for comparing two or more entities from the same requested resource. + // HTTP/1.1 uses entity tags in the etag (section 14.19), If-Match (section 14.24), If-None-Match (section 14.26), and If-Range + // (section 14.27) header fields. + Etag *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// MaccList - MACC list +type MaccList struct { + // REQUIRED; The Macc items on this page + Value []*Macc + + // The link to the next page of items + NextLink *string +} + +// MaccMilestone - MACC milestone represents interim targets within the period of MACC. +type MaccMilestone struct { + // Setting this to 'Enable' enables automatic shortfall invoicing when milestone commitment is not met. + AutomaticShortfall *EnablementMode + + // Optional field to record suppression reason for automatic shortfall. + AutomaticShortfallSuppressReason *AutomaticShortfallSuppressReason + + // Commitment associated with this milestone. + Commitment *Price + + // End date time for the milestone. Timestamp must be in the ISO date format YYYY-MM-DDT23:59:59Z. + EndAt *time.Time + + // Globally unique identifier for the milestone. Format: {guid} + MilestoneID *string + + // Details of the shortfall associated with this milestone. + Shortfall *Shortfall + + // Represents the current status of the Milestone. + Status *MaccMilestoneStatus +} + +// MaccModelProperties - MACC properties +type MaccModelProperties struct { + // REQUIRED; Represents type of the object being operated on. Possible values are primary or contributor. + EntityType *MaccEntityType + + // Setting this to true means multi-entity. + AllowContributors *bool + + // Setting this to 'Enable' enables automatic shortfall charging when commitment is not met. + AutomaticShortfall *EnablementMode + + // Optional field to record suppression reason for automatic shortfall. + AutomaticShortfallSuppressReason *AutomaticShortfallSuppressReason + + // Fully-qualified identifier of the billing account where the MACC is applied. Present only for Enterprise Agreement customers. + // Format must be Azure Resource ID: /providers/Microsoft.Billing/billingAccounts/{acctId:orgId} + BillingAccountResourceID *string + + // Commitment towards the benefit. + Commitment *Commitment + + // Display name + DisplayName *string + + // Must be end of month. Timestamp must be in the ISO date format YYYY-MM-DDT23:59:59Z. + EndAt *time.Time + + // List of milestones associated with this MACC. + Milestones []*MaccMilestone + + // Fully-qualified billing account resource identifier of the primary MACC. Format must be Azure Resource ID: /providers/Microsoft.Billing/billingAccounts/{acctId:orgId}. + PrimaryBillingAccountResourceID *string + + // Fully-qualified resource identifier of the primary MACC. Format: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/maccs/{maccName}. + PrimaryResourceID *string + + // Represents catalog UPN. + ProductCode *string + + // This is the resource identifier of either the primary MACC or the contributor. Format: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/maccs/{maccName}. + ResourceID *string + + // MACC shortfall + Shortfall *Shortfall + + // Must be start of month. Timestamp must be in the ISO date format YYYY-MM-DDT00:00:00Z. + StartAt *time.Time + + // Represents the current status of the MACC. + Status *MaccStatus + + // This is the globally unique identifier of the MACC which will not change for the lifetime of the MACC. + SystemID *string + + // READ-ONLY; Provisioning state of MACC as assigned by RPaaS. This indicates the last operation's status. For all practical + // purposes, this can be ignored. For current status of MACC resource, refer to MaccStatus. + ProvisioningState *string +} + +// MaccPatchRequest - Macc patch request +type MaccPatchRequest struct { + // Macc patch request properties + Properties *MaccPatchRequestProperties + + // Resource tags. + Tags map[string]*string +} + +// MaccPatchRequestProperties - Macc patch request properties +type MaccPatchRequestProperties struct { + // Setting this to true means multi-entity. + AllowContributors *bool + + // Represents the enablement status of a feature or settings. + AutomaticShortfall *EnablementMode + + // Optional field to record suppression reason for automatic shortfall. + AutomaticShortfallSuppressReason *AutomaticShortfallSuppressReason + + // Commitment towards the benefit. + Commitment *Commitment + + // Display name + DisplayName *string + + // End DateTime in UTC. + EndAt *time.Time + + // List of milestones to update or add. + Milestones []*MaccMilestone + + // Fully-qualified billing account resource identifier of the primary MACC. Format must be Azure Resource ID: /providers/Microsoft.Billing/billingAccounts/{acctId:orgId}. + PrimaryBillingAccountResourceID *string + + // Fully-qualified resource identifier of the primary MACC. Format: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/maccs/{maccName}. + PrimaryResourceID *string + + // Represents the current status of the Milestone. + Status *MaccMilestoneStatus +} + +// MaccValidateModel - MACC validate model +type MaccValidateModel struct { + // CONSTANT; Type of benefit to validate. This is used to determine the model type for validation. + // Field has constant value BenefitTypeMACC, any specified value is ignored. + BenefitType *BenefitType + + // MACC validate properties + Properties *MaccModelProperties +} + +// GetBenefitValidateModel implements the BenefitValidateModelClassification interface for type MaccValidateModel. +func (m *MaccValidateModel) GetBenefitValidateModel() *BenefitValidateModel { + return &BenefitValidateModel{ + BenefitType: m.BenefitType, + } +} + +// ManagedServiceIdentity - Managed service identity (system assigned and/or user assigned identities) +type ManagedServiceIdentity struct { + // REQUIRED; The type of managed identity assigned to this resource. + Type *ManagedServiceIdentityType + + // The identities assigned to this resource by the user. + UserAssignedIdentities map[string]*UserAssignedIdentity + + // READ-ONLY; The service principal ID of the system assigned identity. This property will only be provided for a system assigned + // identity. + PrincipalID *string + + // READ-ONLY; The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + TenantID *string +} + +// MarketSetPricesItems - Items in the MarketSetPrices array. +type MarketSetPricesItems struct { + // REQUIRED; The currency of the locked price value. Validation: Required. Must be a valid ISO 4217 3-letter currency code. + Currency *string + + // REQUIRED + Markets []*string + + // REQUIRED; The locked price for the priceable node. Validation: Required. Must be greater than or equal to 0. If the case + // of billing plans. This represents the price for each cycle charge. + Value *float32 +} + +// Operation - REST API Operation +// +// Details of a REST API operation, returned from the Resource Provider Operations API +type Operation struct { + // Localized display information for this particular operation. + Display *OperationDisplay + + // READ-ONLY; Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + ActionType *ActionType + + // READ-ONLY; Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure + // Resource Manager/control-plane operations. + IsDataAction *bool + + // READ-ONLY; The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + // "Microsoft.Compute/virtualMachines/capture/action" + Name *string + + // READ-ONLY; The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default + // value is "user,system" + Origin *Origin +} + +// OperationDisplay - Localized display information for an operation. +type OperationDisplay struct { + // READ-ONLY; The short, localized friendly description of the operation; suitable for tool tips and detailed views. + Description *string + + // READ-ONLY; The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual + // Machine", "Restart Virtual Machine". + Operation *string + + // READ-ONLY; The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft + // Compute". + Provider *string + + // READ-ONLY; The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job + // Schedule Collections". + Resource *string +} + +// OperationListResult - A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to +// get the next set of results. +type OperationListResult struct { + // REQUIRED; The Operation items on this page + Value []*Operation + + // The link to the next page of items + NextLink *string +} + +// PaymentDetail - Information about payment related to a savings plan order. +type PaymentDetail struct { + // Billing account + BillingAccount *string + + // Amount charged in Billing currency. Tax not included. Is null for future payments + BillingCurrencyTotal *Price + + // Date when the payment needs to be done. + DueDate *time.Time + + // Date when the transaction is completed. Is null when it is scheduled. + PaymentDate *time.Time + + // Amount in pricing currency. Tax not included. + PricingCurrencyTotal *Price + + // Describes whether the payment is completed, failed, cancelled or scheduled in the future. + Status *PaymentStatus + + // READ-ONLY + ExtendedStatusInfo *ExtendedStatusInfo +} + +// Plan for the resource. +type Plan struct { + // REQUIRED; A user defined name of the 3rd Party Artifact that is being procured. + Name *string + + // REQUIRED; The 3rd Party artifact that is being procured. E.g. NewRelic. Product maps to the OfferID specified for the artifact + // at the time of Data Market onboarding. + Product *string + + // REQUIRED; The publisher of the 3rd Party Artifact that is being bought. E.g. NewRelic + Publisher *string + + // A publisher provided promotion code as provisioned in Data Market for the said product/artifact. + PromotionCode *string + + // The version of the desired product/artifact. + Version *string +} + +type Price struct { + Amount *float64 + + // The ISO 4217 3-letter currency code for the currency used by this purchase record. + CurrencyCode *string +} + +// PriceGuaranteeProperties - Set only in price guarantee scenario. +type PriceGuaranteeProperties struct { + // The date on which prices are to be used for guarantee calculation. Validation: expected to be 00 hours, Format: 2024-09-30T00:00:00Z. + // Must be in UTC. + PriceGuaranteeDate *time.Time + + // Supported values: Protected, Locked + PricingPolicy *PricingPolicy +} + +// PrimaryConditionalCreditProperties - Properties for primary conditional credit. +type PrimaryConditionalCreditProperties struct { + // CONSTANT; Type of conditional credit entity + // Field has constant value ConditionalCreditEntityTypePrimary, any specified value is ignored. + EntityType *ConditionalCreditEntityType + + // Whether this conditional credit allows contributor billing accounts + AllowContributors *EnablementMode + + // The billing account resource ID + BillingAccountResourceID *string + + // Display name for the conditional credit + DisplayName *string + + // End date of the conditional credit (derived from last milestone) + EndAt *time.Time + + // List of milestones for this conditional credit (must include awards) + Milestones []*ConditionalCreditMilestone + + // Product code for the conditional credit + ProductCode *string + + // Fully-qualified resource identifier of the resource. Format: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/{benefitType}/{benefitName}. + ResourceID *string + + // Start date of the conditional credit + StartAt *time.Time + + // The status of the conditional credit + Status *ConditionalCreditStatus + + // System identifier shared between primary and contributor conditional credits representing the same conditional credit program + SystemID *string + + // READ-ONLY; Fully-qualified identifier of the benefit under applicable benefit list. + BenefitResourceID *string + + // READ-ONLY; The provisioning state of the resource + ProvisioningState *ConditionalCreditsProvisioningState +} + +// GetConditionalCreditProperties implements the ConditionalCreditPropertiesClassification interface for type PrimaryConditionalCreditProperties. +func (p *PrimaryConditionalCreditProperties) GetConditionalCreditProperties() *ConditionalCreditProperties { + return &ConditionalCreditProperties{ + BenefitResourceID: p.BenefitResourceID, + BillingAccountResourceID: p.BillingAccountResourceID, + DisplayName: p.DisplayName, + EndAt: p.EndAt, + EntityType: p.EntityType, + ProductCode: p.ProductCode, + ProvisioningState: p.ProvisioningState, + ResourceID: p.ResourceID, + StartAt: p.StartAt, + Status: p.Status, + } +} + +type PurchaseRequest struct { + Properties *PurchaseRequestProperties + + // The SKU to be applied for this resource + SKU *ResourceSKU +} + +type PurchaseRequestProperties struct { + // Properties specific to applied scope type. Not required if not applicable. + AppliedScopeProperties *AppliedScopeProperties + + // Type of the Applied Scope. + AppliedScopeType *AppliedScopeType + + // Represents the billing plan in ISO 8601 format. Required only for monthly billing plans. + BillingPlan *BillingPlan + + // Subscription that will be charged for purchasing the benefit + BillingScopeID *string + + // Commitment towards the benefit. + Commitment *Commitment + + // Friendly name of the savings plan + DisplayName *string + + // Setting this to true will automatically purchase a new benefit on the expiration date time. + Renew *bool + + // Represent benefit term in ISO 8601 format. + Term *Term + + // READ-ONLY; DateTime of the savings plan starts providing benefit from. + EffectiveDateTime *time.Time +} + +type RenewProperties struct { + PurchaseProperties *PurchaseRequest +} + +// ReservationOrderAliasRequest - Reservation order alias +type ReservationOrderAliasRequest struct { + // REQUIRED; Reservation order SKU + SKU *ResourceSKU + + // The Azure Region where the reservation benefits are applied to. + Location *string + + // Reservation order alias request properties + Properties *ReservationOrderAliasRequestProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ReservationOrderAliasRequestProperties - Reservation properties +type ReservationOrderAliasRequestProperties struct { + // Properties specific to applied scope type. Not required if not applicable. + AppliedScopeProperties *AppliedScopeProperties + + // Type of the Applied Scope. + AppliedScopeType *AppliedScopeType + + // Represents the billing plan in ISO 8601 format. Required only for monthly billing plans. + BillingPlan *BillingPlan + + // Subscription that will be charged for purchasing the benefit + BillingScopeID *string + + // Display name + DisplayName *string + + // Total Quantity of the SKUs purchased in the Reservation. + Quantity *int32 + + // Setting this to true will automatically purchase a new benefit on the expiration date time. + Renew *bool + + // Properties specific to each reserved resource type. Not required if not applicable. + ReservedResourceProperties *ReservationOrderAliasRequestPropertiesReservedResourceProperties + + // The type of the resource that is being reserved. + ReservedResourceType *ReservedResourceType + + // This is the date-time when the Azure Hybrid Benefit needs to be reviewed. + ReviewDateTime *time.Time + + // Represent benefit term in ISO 8601 format. + Term *Term +} + +// ReservationOrderAliasRequestPropertiesReservedResourceProperties - Properties specific to each reserved resource type. +// Not required if not applicable. +type ReservationOrderAliasRequestPropertiesReservedResourceProperties struct { + // Turning this on will apply the reservation discount to other VMs in the same VM size group. + InstanceFlexibility *InstanceFlexibility +} + +// ReservationOrderAliasResponse - Reservation order alias +type ReservationOrderAliasResponse struct { + // REQUIRED; Reservation order SKU + SKU *ResourceSKU + + // The Azure Region where the reserved resource lives. + Location *string + + // Reservation order alias response properties + Properties *ReservationOrderAliasResponseProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ReservationOrderAliasResponseProperties - Reservation properties +type ReservationOrderAliasResponseProperties struct { + // Properties specific to applied scope type. Not required if not applicable. + AppliedScopeProperties *AppliedScopeProperties + + // Type of the Applied Scope. + AppliedScopeType *AppliedScopeType + + // Represents the billing plan in ISO 8601 format. Required only for monthly billing plans. + BillingPlan *BillingPlan + + // Subscription that will be charged for purchasing the benefit + BillingScopeID *string + + // Display name + DisplayName *string + + // Total Quantity of the SKUs purchased in the Reservation. + Quantity *int32 + + // Setting this to true will automatically purchase a new benefit on the expiration date time. + Renew *bool + + // Properties specific to each reserved resource type. Not required if not applicable. + ReservedResourceProperties *ReservationOrderAliasResponsePropertiesReservedResourceProperties + + // The type of the resource that is being reserved. + ReservedResourceType *ReservedResourceType + + // This is the date-time when the Reservation needs to be reviewed. + ReviewDateTime *time.Time + + // Represent benefit term in ISO 8601 format. + Term *Term + + // READ-ONLY; Provisioning state + ProvisioningState *ProvisioningState + + // READ-ONLY; Identifier of the reservation order created + ReservationOrderID *string +} + +// ReservationOrderAliasResponsePropertiesReservedResourceProperties - Properties specific to each reserved resource type. +// Not required if not applicable. +type ReservationOrderAliasResponsePropertiesReservedResourceProperties struct { + // Turning this on will apply the reservation discount to other VMs in the same VM size group. + InstanceFlexibility *InstanceFlexibility +} + +type ResourceSKU struct { + Name *string +} + +// RoleAssignmentEntity - Role assignment entity +type RoleAssignmentEntity struct { + // Role assignment entity id + ID *string + + // Role assignment entity name + Name *string + + // Role assignment entity properties + Properties *RoleAssignmentEntityProperties +} + +// RoleAssignmentEntityProperties - Role assignment entity properties +type RoleAssignmentEntityProperties struct { + // Principal Id + PrincipalID *string + + // Role definition id + RoleDefinitionID *string + + // Scope of the role assignment entity + Scope *string +} + +// SKU - The resource model definition representing SKU +type SKU struct { + // REQUIRED; The name of the SKU. E.g. P3. It is typically a letter+number code + Name *string + + // If the SKU supports scale out/in then the capacity integer should be included. If scale out/in is not possible for the + // resource this may be omitted. + Capacity *int32 + + // If the service has different generations of hardware, for the same SKU, then that can be captured here. + Family *string + + // The SKU size. When the name field is the combination of tier and some other value, this would be the standalone code. + Size *string + + // This field is required to be implemented by the Resource Provider if the service has more than one tier, but is not required + // on a PUT. + Tier *SKUTier +} + +// SavingsPlanModel - Savings plan +type SavingsPlanModel struct { + // REQUIRED; Savings plan SKU + SKU *ResourceSKU + + // Savings plan properties + Properties *SavingsPlanModelProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// SavingsPlanModelList - Paged collection of SavingsPlanModel items +type SavingsPlanModelList struct { + // REQUIRED; The SavingsPlanModel items on this page + Value []*SavingsPlanModel + + // The link to the next page of items + NextLink *string +} + +// SavingsPlanModelListResult - Represents the result of listing savings plan models +type SavingsPlanModelListResult struct { + // READ-ONLY; The roll out count summary of the savings plans + AdditionalProperties []*SavingsPlanSummary + + // READ-ONLY; Url to get the next page. + NextLink *string + + // READ-ONLY; The list of savings plans. + Value []*SavingsPlanModel +} + +// SavingsPlanModelProperties - Savings plan properties +type SavingsPlanModelProperties struct { + // Properties specific to applied scope type. Not required if not applicable. + AppliedScopeProperties *AppliedScopeProperties + + // Type of the Applied Scope. + AppliedScopeType *AppliedScopeType + + // This is the DateTime when the savings plan benefit started. + BenefitStartTime *time.Time + + // Represents the billing plan in ISO 8601 format. Required only for monthly billing plans. + BillingPlan *BillingPlan + + // Subscription that will be charged for purchasing the benefit + BillingScopeID *string + + // Commitment towards the benefit. + Commitment *Commitment + + // Display name + DisplayName *string + + // Setting this to true will automatically purchase a new benefit on the expiration date time. + Renew *bool + + // SavingsPlan Id of the SavingsPlan which is purchased because of renew. + RenewDestination *string + RenewProperties *RenewProperties + + // SavingsPlan Id of the SavingsPlan from which this SavingsPlan is renewed. + RenewSource *string + + // Represent benefit term in ISO 8601 format. + Term *Term + + // READ-ONLY; Fully-qualified identifier of the billing account where the benefit is applied. Present only for Enterprise + // Agreement customers. + BillingAccountID *string + + // READ-ONLY; Fully-qualified identifier of the billing profile where the benefit is applied. Present only for Field-led or + // Customer-led customers. + BillingProfileID *string + + // READ-ONLY; Fully-qualified identifier of the customer where the savings plan is applied. Present only for Partner-led customers. + CustomerID *string + + // READ-ONLY; The provisioning state of the savings plan for display, e.g. Succeeded + DisplayProvisioningState *string + + // READ-ONLY; DateTime of the savings plan starts providing benefit from. + EffectiveDateTime *time.Time + + // READ-ONLY; Expiry date time + ExpiryDateTime *time.Time + + // READ-ONLY + ExtendedStatusInfo *ExtendedStatusInfo + + // READ-ONLY; Provisioning state + ProvisioningState *ProvisioningState + + // READ-ONLY; Date time when the savings plan was purchased + PurchaseDateTime *time.Time + + // READ-ONLY; The applied scope type of the savings plan for display, e.g. Shared + UserFriendlyAppliedScopeType *string + + // READ-ONLY; Savings plan utilization + Utilization *Utilization +} + +// SavingsPlanOrderAliasModel - Savings plan order alias +type SavingsPlanOrderAliasModel struct { + // REQUIRED; Savings plan SKU + SKU *ResourceSKU + + // Resource provider kind + Kind *string + + // Savings plan order alias properties + Properties *SavingsPlanOrderAliasProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// SavingsPlanOrderAliasProperties - Savings plan properties +type SavingsPlanOrderAliasProperties struct { + // Properties specific to applied scope type. Not required if not applicable. + AppliedScopeProperties *AppliedScopeProperties + + // Type of the Applied Scope. + AppliedScopeType *AppliedScopeType + + // Represents the billing plan in ISO 8601 format. Required only for monthly billing plans. + BillingPlan *BillingPlan + + // Subscription that will be charged for purchasing the benefit + BillingScopeID *string + + // Commitment towards the benefit. + Commitment *Commitment + + // Display name + DisplayName *string + + // Setting this to true will automatically purchase a new benefit on the expiration date time. + Renew *bool + + // Represent benefit term in ISO 8601 format. + Term *Term + + // READ-ONLY; Provisioning state + ProvisioningState *ProvisioningState + + // READ-ONLY; Identifier of the savings plan created + SavingsPlanOrderID *string +} + +// SavingsPlanOrderModel - Savings plan order +type SavingsPlanOrderModel struct { + // REQUIRED; Savings plan SKU + SKU *ResourceSKU + + // Savings plan order properties + Properties *SavingsPlanOrderModelProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// SavingsPlanOrderModelList - Paged collection of SavingsPlanOrderModel items +type SavingsPlanOrderModelList struct { + // REQUIRED; The SavingsPlanOrderModel items on this page + Value []*SavingsPlanOrderModel + + // The link to the next page of items + NextLink *string +} + +// SavingsPlanOrderModelProperties - Savings plan order properties +type SavingsPlanOrderModelProperties struct { + // This is the DateTime when the savings plan benefit started. + BenefitStartTime *time.Time + + // Represents the billing plan in ISO 8601 format. Required only for monthly billing plans. + BillingPlan *BillingPlan + + // Subscription that will be charged for purchasing the benefit + BillingScopeID *string + + // Display name + DisplayName *string + + // Information describing the type of billing plan for this savings plan. + PlanInformation *BillingPlanInformation + SavingsPlans []*string + + // Represent benefit term in ISO 8601 format. + Term *Term + + // READ-ONLY; Fully-qualified identifier of the billing account where the benefit is applied. Present only for Enterprise + // Agreement customers. + BillingAccountID *string + + // READ-ONLY; Fully-qualified identifier of the billing profile where the benefit is applied. Present only for Field-led or + // Customer-led customers. + BillingProfileID *string + + // READ-ONLY; Fully-qualified identifier of the customer where the savings plan is applied. Present only for Partner-led customers. + CustomerID *string + + // READ-ONLY; Expiry date time + ExpiryDateTime *time.Time + + // READ-ONLY + ExtendedStatusInfo *ExtendedStatusInfo + + // READ-ONLY; Provisioning state + ProvisioningState *ProvisioningState +} + +// SavingsPlanSummary - Savings plans list summary +type SavingsPlanSummary struct { + // The roll up count summary of savings plans in each state + Value *SavingsPlanSummaryCount + + // READ-ONLY; This property has value 'summary' + Name *string +} + +// SavingsPlanSummaryCount - The roll up count summary of savings plans in each state +type SavingsPlanSummaryCount struct { + // READ-ONLY; The number of savings plans in Cancelled state + CancelledCount *float32 + + // READ-ONLY; The number of savings plans in Expired state + ExpiredCount *float32 + + // READ-ONLY; The number of savings plans in Expiring state + ExpiringCount *float32 + + // READ-ONLY; The number of savings plans in Failed state + FailedCount *float32 + + // READ-ONLY; The number of savings plans in No Benefit state + NoBenefitCount *float32 + + // READ-ONLY; The number of savings plans in Pending state + PendingCount *float32 + + // READ-ONLY; The number of savings plans in Processing state + ProcessingCount *float32 + + // READ-ONLY; The number of savings plans in Succeeded state + SucceededCount *float32 + + // READ-ONLY; The number of savings plans in Warning state + WarningCount *float32 +} + +// SavingsPlanUpdateRequest - Savings plan patch request +type SavingsPlanUpdateRequest struct { + // Savings plan patch request + Properties *SavingsPlanUpdateRequestProperties +} + +// SavingsPlanUpdateRequestProperties - Savings plan patch request +type SavingsPlanUpdateRequestProperties struct { + // Properties specific to applied scope type. Not required if not applicable. + AppliedScopeProperties *AppliedScopeProperties + + // Type of the Applied Scope. + AppliedScopeType *AppliedScopeType + + // Display name + DisplayName *string + + // Setting this to true will automatically purchase a new benefit on the expiration date time. + Renew *bool + RenewProperties *RenewProperties +} + +type SavingsPlanUpdateValidateRequest struct { + Benefits []*SavingsPlanUpdateRequestProperties +} + +// SavingsPlanValidResponseProperty - Benefit scope response property +type SavingsPlanValidResponseProperty struct { + // Failure reason if the provided input was invalid + Reason *string + + // Failure reason code if the provided input was invalid + ReasonCode *string + + // Indicates if the provided input was valid + Valid *bool +} + +// SavingsPlanValidateModel - Savings plan validate model +type SavingsPlanValidateModel struct { + // CONSTANT; Type of benefit to validate. This is used to determine the model type for validation. + // Field has constant value BenefitTypeSavingsPlan, any specified value is ignored. + BenefitType *BenefitType + + // REQUIRED; Savings plan SKU + SKU *ResourceSKU + + // Resource provider kind + Kind *string + + // Savings plan order alias properties + Properties *SavingsPlanOrderAliasProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// GetBenefitValidateModel implements the BenefitValidateModelClassification interface for type SavingsPlanValidateModel. +func (s *SavingsPlanValidateModel) GetBenefitValidateModel() *BenefitValidateModel { + return &BenefitValidateModel{ + BenefitType: s.BenefitType, + } +} + +type SavingsPlanValidateResponse struct { + Benefits []*SavingsPlanValidResponseProperty + + // Url to get the next page. + NextLink *string +} + +// SellerResourceListRequest - List MACCs under a billing account +type SellerResourceListRequest struct { + // Request properties to list maccs under a billing account + Properties *SellerResourceListRequestProperties +} + +// SellerResourceListRequestProperties - Request properties to list maccs under a billing account +type SellerResourceListRequestProperties struct { + // REQUIRED; Fully-qualified billing account resource identifier where the benefit is applied. Present only for Enterprise + // Agreement customers. + BillingAccountResourceID *string + + // Setting it to true will return the list of contributors associated with the MACC. + Contributors *bool + + // This is an OData expresssion to filter the list of MACCs based on the properties of MACC passed in the filter. + Filter *string + + // Setting it to true will return the list of milestones associated with the MACC. + Milestones *bool + + // Fully-qualified resource identifier of the primary MACC. Format: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/maccs/{maccName}. + PrimaryResourceID *string +} + +// ServiceManagedIdentity - Managed service identity (system assigned and/or user assigned identities) +type ServiceManagedIdentity struct { + // REQUIRED; Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). + Type *ServiceManagedIdentityType + + // The set of user assigned identities associated with the resource. The userAssignedIdentities dictionary keys will be ARM + // resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. + // The dictionary values can be empty objects ({}) in requests. + UserAssignedIdentities map[string]*UserAssignedIdentity + + // READ-ONLY; The service principal ID of the system assigned identity. This property will only be provided for a system assigned + // identity. + PrincipalID *string + + // READ-ONLY; The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + TenantID *string +} + +// Shortfall - MACC shortfall +type Shortfall struct { + // Points to BalanceVersion document that indicates the remaining commitment balance when the credit was created. + BalanceVersion *float32 + + // Shortfall amount with grain. + Charge *Commitment + + // End DateTime in UTC. + EndAt *time.Time + + // Represents catalog UPN. + ProductCode *string + + // Fully-qualified resource identifier of the credits associated with the shortfall. + ResourceID *string + + // Start DateTime. + StartAt *time.Time + + // This is an identifier of the shortfall which will not change for its lifetime. + SystemID *string +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time + + // The identity that created the resource. + CreatedBy *string + + // The type of identity that created the resource. + CreatedByType *CreatedByType + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time + + // The identity that last modified the resource. + LastModifiedBy *string + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType +} + +// UserAssignedIdentity - User assigned identity properties +type UserAssignedIdentity struct { + // READ-ONLY; The client ID of the assigned identity. + ClientID *string + + // READ-ONLY; The principal ID of the assigned identity. + PrincipalID *string +} + +// Utilization - Savings plan utilization +type Utilization struct { + // The array of aggregates of a savings plan's utilization + Aggregates []*UtilizationAggregates + + // READ-ONLY; The number of days trend for a savings plan + Trend *string +} + +// UtilizationAggregates - The aggregate values of savings plan utilization +type UtilizationAggregates struct { + // READ-ONLY; The grain of the aggregate + Grain *float32 + + // READ-ONLY; The grain unit of the aggregate + GrainUnit *string + + // READ-ONLY; The aggregate value + Value *float32 + + // READ-ONLY; The aggregate value unit + ValueUnit *string +} diff --git a/test/local/armbillingbenefits/zz_models_serde.go b/test/local/armbillingbenefits/zz_models_serde.go new file mode 100644 index 000000000000..341798076018 --- /dev/null +++ b/test/local/armbillingbenefits/zz_models_serde.go @@ -0,0 +1,5226 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armbillingbenefits + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type ApplicableMacc. +func (a ApplicableMacc) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicableMacc. +func (a *ApplicableMacc) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &a.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ApplicableMaccList. +func (a ApplicableMaccList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicableMaccList. +func (a *ApplicableMaccList) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &a.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AppliedScopeProperties. +func (a AppliedScopeProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "displayName", a.DisplayName) + populate(objectMap, "managementGroupId", a.ManagementGroupID) + populate(objectMap, "resourceGroupId", a.ResourceGroupID) + populate(objectMap, "subscriptionId", a.SubscriptionID) + populate(objectMap, "tenantId", a.TenantID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AppliedScopeProperties. +func (a *AppliedScopeProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "displayName": + err = unpopulate(val, "DisplayName", &a.DisplayName) + delete(rawMsg, key) + case "managementGroupId": + err = unpopulate(val, "ManagementGroupID", &a.ManagementGroupID) + delete(rawMsg, key) + case "resourceGroupId": + err = unpopulate(val, "ResourceGroupID", &a.ResourceGroupID) + delete(rawMsg, key) + case "subscriptionId": + err = unpopulate(val, "SubscriptionID", &a.SubscriptionID) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &a.TenantID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutomaticShortfallSuppressReason. +func (a AutomaticShortfallSuppressReason) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", a.Code) + populate(objectMap, "message", a.Message) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutomaticShortfallSuppressReason. +func (a *AutomaticShortfallSuppressReason) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "code": + err = unpopulate(val, "Code", &a.Code) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &a.Message) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Award. +func (a Award) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "balanceVersion", a.BalanceVersion) + populate(objectMap, "credit", a.Credit) + populate(objectMap, "duration", a.Duration) + populateTime[datetime.RFC3339](objectMap, "endAt", a.EndAt) + populate(objectMap, "resourceId", a.ResourceID) + populateTime[datetime.RFC3339](objectMap, "startAt", a.StartAt) + populate(objectMap, "systemId", a.SystemID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Award. +func (a *Award) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "balanceVersion": + err = unpopulate(val, "BalanceVersion", &a.BalanceVersion) + delete(rawMsg, key) + case "credit": + err = unpopulate(val, "Credit", &a.Credit) + delete(rawMsg, key) + case "duration": + err = unpopulate(val, "Duration", &a.Duration) + delete(rawMsg, key) + case "endAt": + err = unpopulateTime[datetime.RFC3339](val, "EndAt", &a.EndAt) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &a.ResourceID) + delete(rawMsg, key) + case "startAt": + err = unpopulateTime[datetime.RFC3339](val, "StartAt", &a.StartAt) + delete(rawMsg, key) + case "systemId": + err = unpopulate(val, "SystemID", &a.SystemID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BenefitValidateModel. +func (b BenefitValidateModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "benefitType", b.BenefitType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BenefitValidateModel. +func (b *BenefitValidateModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "benefitType": + err = unpopulate(val, "BenefitType", &b.BenefitType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BenefitValidateRequest. +func (b BenefitValidateRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "benefits", b.Benefits) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BenefitValidateRequest. +func (b *BenefitValidateRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "benefits": + b.Benefits, err = unmarshalBenefitValidateModelClassificationArray(val) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BenefitValidateResponse. +func (b BenefitValidateResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "benefits", b.Benefits) + populate(objectMap, "nextLink", b.NextLink) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BenefitValidateResponse. +func (b *BenefitValidateResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "benefits": + err = unpopulate(val, "Benefits", &b.Benefits) + delete(rawMsg, key) + case "nextLink": + err = unpopulate(val, "NextLink", &b.NextLink) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BenefitValidateResponseProperty. +func (b BenefitValidateResponseProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "reason", b.Reason) + populate(objectMap, "reasonCode", b.ReasonCode) + populate(objectMap, "resourceId", b.ResourceID) + populate(objectMap, "valid", b.Valid) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BenefitValidateResponseProperty. +func (b *BenefitValidateResponseProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "reason": + err = unpopulate(val, "Reason", &b.Reason) + delete(rawMsg, key) + case "reasonCode": + err = unpopulate(val, "ReasonCode", &b.ReasonCode) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &b.ResourceID) + delete(rawMsg, key) + case "valid": + err = unpopulate(val, "Valid", &b.Valid) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BillingPlanInformation. +func (b BillingPlanInformation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.PlainDate](objectMap, "nextPaymentDueDate", b.NextPaymentDueDate) + populate(objectMap, "pricingCurrencyTotal", b.PricingCurrencyTotal) + populateTime[datetime.PlainDate](objectMap, "startDate", b.StartDate) + populate(objectMap, "transactions", b.Transactions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BillingPlanInformation. +func (b *BillingPlanInformation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextPaymentDueDate": + err = unpopulateTime[datetime.PlainDate](val, "NextPaymentDueDate", &b.NextPaymentDueDate) + delete(rawMsg, key) + case "pricingCurrencyTotal": + err = unpopulate(val, "PricingCurrencyTotal", &b.PricingCurrencyTotal) + delete(rawMsg, key) + case "startDate": + err = unpopulateTime[datetime.PlainDate](val, "StartDate", &b.StartDate) + delete(rawMsg, key) + case "transactions": + err = unpopulate(val, "Transactions", &b.Transactions) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CatalogClaimsItem. +func (c CatalogClaimsItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "catalogClaimsItemType", c.CatalogClaimsItemType) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CatalogClaimsItem. +func (c *CatalogClaimsItem) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "catalogClaimsItemType": + err = unpopulate(val, "CatalogClaimsItemType", &c.CatalogClaimsItemType) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &c.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ChargeShortfallRequest. +func (c ChargeShortfallRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", c.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ChargeShortfallRequest. +func (c *ChargeShortfallRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Commitment. +func (c Commitment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "amount", c.Amount) + populate(objectMap, "currencyCode", c.CurrencyCode) + populate(objectMap, "grain", c.Grain) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Commitment. +func (c *Commitment) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "amount": + err = unpopulate(val, "Amount", &c.Amount) + delete(rawMsg, key) + case "currencyCode": + err = unpopulate(val, "CurrencyCode", &c.CurrencyCode) + delete(rawMsg, key) + case "grain": + err = unpopulate(val, "Grain", &c.Grain) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConditionalCredit. +func (c ConditionalCredit) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", c.Etag) + populate(objectMap, "id", c.ID) + populate(objectMap, "identity", c.Identity) + populate(objectMap, "kind", c.Kind) + populate(objectMap, "location", c.Location) + populate(objectMap, "managedBy", c.ManagedBy) + populate(objectMap, "name", c.Name) + populate(objectMap, "plan", c.Plan) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "sku", c.SKU) + populate(objectMap, "systemData", c.SystemData) + populate(objectMap, "tags", c.Tags) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConditionalCredit. +func (c *ConditionalCredit) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &c.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &c.Identity) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &c.Kind) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &c.Location) + delete(rawMsg, key) + case "managedBy": + err = unpopulate(val, "ManagedBy", &c.ManagedBy) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "plan": + err = unpopulate(val, "Plan", &c.Plan) + delete(rawMsg, key) + case "properties": + c.Properties, err = unmarshalConditionalCreditPropertiesClassification(val) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &c.SKU) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &c.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &c.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConditionalCreditContributor. +func (c ConditionalCreditContributor) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", c.ID) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "systemData", c.SystemData) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConditionalCreditContributor. +func (c *ConditionalCreditContributor) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &c.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConditionalCreditContributorList. +func (c ConditionalCreditContributorList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", c.NextLink) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConditionalCreditContributorList. +func (c *ConditionalCreditContributorList) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &c.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &c.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConditionalCreditList. +func (c ConditionalCreditList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", c.NextLink) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConditionalCreditList. +func (c *ConditionalCreditList) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &c.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &c.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConditionalCreditMilestone. +func (c ConditionalCreditMilestone) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "award", c.Award) + populateTime[datetime.RFC3339](objectMap, "endAt", c.EndAt) + populate(objectMap, "milestoneId", c.MilestoneID) + populate(objectMap, "name", c.Name) + populate(objectMap, "spendTarget", c.SpendTarget) + populate(objectMap, "status", c.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConditionalCreditMilestone. +func (c *ConditionalCreditMilestone) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "award": + err = unpopulate(val, "Award", &c.Award) + delete(rawMsg, key) + case "endAt": + err = unpopulateTime[datetime.RFC3339](val, "EndAt", &c.EndAt) + delete(rawMsg, key) + case "milestoneId": + err = unpopulate(val, "MilestoneID", &c.MilestoneID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "spendTarget": + err = unpopulate(val, "SpendTarget", &c.SpendTarget) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &c.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConditionalCreditPatchRequest. +func (c ConditionalCreditPatchRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "tags", c.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConditionalCreditPatchRequest. +func (c *ConditionalCreditPatchRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &c.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConditionalCreditPatchRequestProperties. +func (c ConditionalCreditPatchRequestProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowContributors", c.AllowContributors) + populate(objectMap, "displayName", c.DisplayName) + populateTime[datetime.RFC3339](objectMap, "endAt", c.EndAt) + populate(objectMap, "milestones", c.Milestones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConditionalCreditPatchRequestProperties. +func (c *ConditionalCreditPatchRequestProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "allowContributors": + err = unpopulate(val, "AllowContributors", &c.AllowContributors) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &c.DisplayName) + delete(rawMsg, key) + case "endAt": + err = unpopulateTime[datetime.RFC3339](val, "EndAt", &c.EndAt) + delete(rawMsg, key) + case "milestones": + err = unpopulate(val, "Milestones", &c.Milestones) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConditionalCreditProperties. +func (c ConditionalCreditProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "benefitResourceId", c.BenefitResourceID) + populate(objectMap, "billingAccountResourceId", c.BillingAccountResourceID) + populate(objectMap, "displayName", c.DisplayName) + populateTime[datetime.RFC3339](objectMap, "endAt", c.EndAt) + populate(objectMap, "entityType", c.EntityType) + populate(objectMap, "productCode", c.ProductCode) + populate(objectMap, "provisioningState", c.ProvisioningState) + populate(objectMap, "resourceId", c.ResourceID) + populateTime[datetime.RFC3339](objectMap, "startAt", c.StartAt) + populate(objectMap, "status", c.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConditionalCreditProperties. +func (c *ConditionalCreditProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "benefitResourceId": + err = unpopulate(val, "BenefitResourceID", &c.BenefitResourceID) + delete(rawMsg, key) + case "billingAccountResourceId": + err = unpopulate(val, "BillingAccountResourceID", &c.BillingAccountResourceID) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &c.DisplayName) + delete(rawMsg, key) + case "endAt": + err = unpopulateTime[datetime.RFC3339](val, "EndAt", &c.EndAt) + delete(rawMsg, key) + case "entityType": + err = unpopulate(val, "EntityType", &c.EntityType) + delete(rawMsg, key) + case "productCode": + err = unpopulate(val, "ProductCode", &c.ProductCode) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &c.ProvisioningState) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &c.ResourceID) + delete(rawMsg, key) + case "startAt": + err = unpopulateTime[datetime.RFC3339](val, "StartAt", &c.StartAt) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &c.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConditionalCreditsValidateModel. +func (c ConditionalCreditsValidateModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["benefitType"] = BenefitTypeConditionalCredits + populate(objectMap, "properties", c.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConditionalCreditsValidateModel. +func (c *ConditionalCreditsValidateModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "benefitType": + err = unpopulate(val, "BenefitType", &c.BenefitType) + delete(rawMsg, key) + case "properties": + c.Properties, err = unmarshalConditionalCreditPropertiesClassification(val) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConditionsItem. +func (c ConditionsItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "conditionName", c.ConditionName) + populate(objectMap, "type", c.Type) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConditionsItem. +func (c *ConditionsItem) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "conditionName": + err = unpopulate(val, "ConditionName", &c.ConditionName) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &c.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Contributor. +func (c Contributor) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", c.ID) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "systemData", c.SystemData) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Contributor. +func (c *Contributor) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &c.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ContributorConditionalCreditMilestone. +func (c ContributorConditionalCreditMilestone) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "award", c.Award) + populateTime[datetime.RFC3339](objectMap, "endAt", c.EndAt) + populate(objectMap, "milestoneId", c.MilestoneID) + populate(objectMap, "name", c.Name) + populate(objectMap, "spendTarget", c.SpendTarget) + populate(objectMap, "status", c.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContributorConditionalCreditMilestone. +func (c *ContributorConditionalCreditMilestone) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "award": + err = unpopulate(val, "Award", &c.Award) + delete(rawMsg, key) + case "endAt": + err = unpopulateTime[datetime.RFC3339](val, "EndAt", &c.EndAt) + delete(rawMsg, key) + case "milestoneId": + err = unpopulate(val, "MilestoneID", &c.MilestoneID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "spendTarget": + err = unpopulate(val, "SpendTarget", &c.SpendTarget) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &c.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ContributorConditionalCreditProperties. +func (c ContributorConditionalCreditProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "benefitResourceId", c.BenefitResourceID) + populate(objectMap, "billingAccountResourceId", c.BillingAccountResourceID) + populate(objectMap, "displayName", c.DisplayName) + populateTime[datetime.RFC3339](objectMap, "endAt", c.EndAt) + objectMap["entityType"] = ConditionalCreditEntityTypeContributor + populate(objectMap, "milestones", c.Milestones) + populate(objectMap, "primaryBillingAccountResourceId", c.PrimaryBillingAccountResourceID) + populate(objectMap, "primaryResourceId", c.PrimaryResourceID) + populate(objectMap, "productCode", c.ProductCode) + populate(objectMap, "provisioningState", c.ProvisioningState) + populate(objectMap, "resourceId", c.ResourceID) + populateTime[datetime.RFC3339](objectMap, "startAt", c.StartAt) + populate(objectMap, "status", c.Status) + populate(objectMap, "systemId", c.SystemID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContributorConditionalCreditProperties. +func (c *ContributorConditionalCreditProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "benefitResourceId": + err = unpopulate(val, "BenefitResourceID", &c.BenefitResourceID) + delete(rawMsg, key) + case "billingAccountResourceId": + err = unpopulate(val, "BillingAccountResourceID", &c.BillingAccountResourceID) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &c.DisplayName) + delete(rawMsg, key) + case "endAt": + err = unpopulateTime[datetime.RFC3339](val, "EndAt", &c.EndAt) + delete(rawMsg, key) + case "entityType": + err = unpopulate(val, "EntityType", &c.EntityType) + delete(rawMsg, key) + case "milestones": + err = unpopulate(val, "Milestones", &c.Milestones) + delete(rawMsg, key) + case "primaryBillingAccountResourceId": + err = unpopulate(val, "PrimaryBillingAccountResourceID", &c.PrimaryBillingAccountResourceID) + delete(rawMsg, key) + case "primaryResourceId": + err = unpopulate(val, "PrimaryResourceID", &c.PrimaryResourceID) + delete(rawMsg, key) + case "productCode": + err = unpopulate(val, "ProductCode", &c.ProductCode) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &c.ProvisioningState) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &c.ResourceID) + delete(rawMsg, key) + case "startAt": + err = unpopulateTime[datetime.RFC3339](val, "StartAt", &c.StartAt) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &c.Status) + delete(rawMsg, key) + case "systemId": + err = unpopulate(val, "SystemID", &c.SystemID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ContributorList. +func (c ContributorList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", c.NextLink) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContributorList. +func (c *ContributorList) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &c.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &c.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Credit. +func (c Credit) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", c.Etag) + populate(objectMap, "id", c.ID) + populate(objectMap, "identity", c.Identity) + populate(objectMap, "kind", c.Kind) + populate(objectMap, "location", c.Location) + populate(objectMap, "managedBy", c.ManagedBy) + populate(objectMap, "name", c.Name) + populate(objectMap, "plan", c.Plan) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "sku", c.SKU) + populate(objectMap, "systemData", c.SystemData) + populate(objectMap, "tags", c.Tags) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Credit. +func (c *Credit) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &c.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &c.Identity) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &c.Kind) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &c.Location) + delete(rawMsg, key) + case "managedBy": + err = unpopulate(val, "ManagedBy", &c.ManagedBy) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "plan": + err = unpopulate(val, "Plan", &c.Plan) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &c.SKU) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &c.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &c.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CreditBreakdownItem. +func (c CreditBreakdownItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allocation", c.Allocation) + populate(objectMap, "dimensions", c.Dimensions) + populateTime[datetime.RFC3339](objectMap, "endAt", c.EndAt) + populateTime[datetime.RFC3339](objectMap, "startAt", c.StartAt) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CreditBreakdownItem. +func (c *CreditBreakdownItem) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "allocation": + err = unpopulate(val, "Allocation", &c.Allocation) + delete(rawMsg, key) + case "dimensions": + err = unpopulate(val, "Dimensions", &c.Dimensions) + delete(rawMsg, key) + case "endAt": + err = unpopulateTime[datetime.RFC3339](val, "EndAt", &c.EndAt) + delete(rawMsg, key) + case "startAt": + err = unpopulateTime[datetime.RFC3339](val, "StartAt", &c.StartAt) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CreditDimension. +func (c CreditDimension) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "key", c.Key) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CreditDimension. +func (c *CreditDimension) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "key": + err = unpopulate(val, "Key", &c.Key) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &c.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CreditPatchProperties. +func (c CreditPatchProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "breakdown", c.Breakdown) + populate(objectMap, "credit", c.Credit) + populateTime[datetime.RFC3339](objectMap, "endAt", c.EndAt) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CreditPatchProperties. +func (c *CreditPatchProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "breakdown": + err = unpopulate(val, "Breakdown", &c.Breakdown) + delete(rawMsg, key) + case "credit": + err = unpopulate(val, "Credit", &c.Credit) + delete(rawMsg, key) + case "endAt": + err = unpopulateTime[datetime.RFC3339](val, "EndAt", &c.EndAt) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CreditPatchRequest. +func (c CreditPatchRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "tags", c.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CreditPatchRequest. +func (c *CreditPatchRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &c.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CreditPolicies. +func (c CreditPolicies) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "expiration", c.Expiration) + populate(objectMap, "redemption", c.Redemption) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CreditPolicies. +func (c *CreditPolicies) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "expiration": + err = unpopulate(val, "Expiration", &c.Expiration) + delete(rawMsg, key) + case "redemption": + err = unpopulate(val, "Redemption", &c.Redemption) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CreditProperties. +func (c CreditProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "billingAccountResourceId", c.BillingAccountResourceID) + populate(objectMap, "billingProfileResourceId", c.BillingProfileResourceID) + populate(objectMap, "breakdown", c.Breakdown) + populate(objectMap, "credit", c.Credit) + populate(objectMap, "customerId", c.CustomerID) + populateTime[datetime.RFC3339](objectMap, "endAt", c.EndAt) + populate(objectMap, "policies", c.Policies) + populate(objectMap, "productCode", c.ProductCode) + populate(objectMap, "provisioningState", c.ProvisioningState) + populate(objectMap, "reason", c.Reason) + populate(objectMap, "resourceId", c.ResourceID) + populateTime[datetime.RFC3339](objectMap, "startAt", c.StartAt) + populate(objectMap, "status", c.Status) + populate(objectMap, "systemId", c.SystemID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CreditProperties. +func (c *CreditProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "billingAccountResourceId": + err = unpopulate(val, "BillingAccountResourceID", &c.BillingAccountResourceID) + delete(rawMsg, key) + case "billingProfileResourceId": + err = unpopulate(val, "BillingProfileResourceID", &c.BillingProfileResourceID) + delete(rawMsg, key) + case "breakdown": + err = unpopulate(val, "Breakdown", &c.Breakdown) + delete(rawMsg, key) + case "credit": + err = unpopulate(val, "Credit", &c.Credit) + delete(rawMsg, key) + case "customerId": + err = unpopulate(val, "CustomerID", &c.CustomerID) + delete(rawMsg, key) + case "endAt": + err = unpopulateTime[datetime.RFC3339](val, "EndAt", &c.EndAt) + delete(rawMsg, key) + case "policies": + err = unpopulate(val, "Policies", &c.Policies) + delete(rawMsg, key) + case "productCode": + err = unpopulate(val, "ProductCode", &c.ProductCode) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &c.ProvisioningState) + delete(rawMsg, key) + case "reason": + err = unpopulate(val, "Reason", &c.Reason) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &c.ResourceID) + delete(rawMsg, key) + case "startAt": + err = unpopulateTime[datetime.RFC3339](val, "StartAt", &c.StartAt) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &c.Status) + delete(rawMsg, key) + case "systemId": + err = unpopulate(val, "SystemID", &c.SystemID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CreditReason. +func (c CreditReason) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", c.Code) + populate(objectMap, "description", c.Description) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CreditReason. +func (c *CreditReason) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "code": + err = unpopulate(val, "Code", &c.Code) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &c.Description) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CreditSource. +func (c CreditSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", c.Etag) + populate(objectMap, "id", c.ID) + populate(objectMap, "identity", c.Identity) + populate(objectMap, "kind", c.Kind) + populate(objectMap, "location", c.Location) + populate(objectMap, "managedBy", c.ManagedBy) + populate(objectMap, "name", c.Name) + populate(objectMap, "plan", c.Plan) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "sku", c.SKU) + populate(objectMap, "systemData", c.SystemData) + populate(objectMap, "tags", c.Tags) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CreditSource. +func (c *CreditSource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &c.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &c.Identity) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &c.Kind) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &c.Location) + delete(rawMsg, key) + case "managedBy": + err = unpopulate(val, "ManagedBy", &c.ManagedBy) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "plan": + err = unpopulate(val, "Plan", &c.Plan) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &c.SKU) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &c.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &c.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CreditSourcePatchRequest. +func (c CreditSourcePatchRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "tags", c.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CreditSourcePatchRequest. +func (c *CreditSourcePatchRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "tags": + err = unpopulate(val, "Tags", &c.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CreditSourceProperties. +func (c CreditSourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "credit", c.Credit) + populate(objectMap, "impactedBillingPeriod", c.ImpactedBillingPeriod) + populate(objectMap, "sourceResourceId", c.SourceResourceID) + populate(objectMap, "status", c.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CreditSourceProperties. +func (c *CreditSourceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "credit": + err = unpopulate(val, "Credit", &c.Credit) + delete(rawMsg, key) + case "impactedBillingPeriod": + err = unpopulate(val, "ImpactedBillingPeriod", &c.ImpactedBillingPeriod) + delete(rawMsg, key) + case "sourceResourceId": + err = unpopulate(val, "SourceResourceID", &c.SourceResourceID) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &c.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CreditSourcesList. +func (c CreditSourcesList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", c.NextLink) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CreditSourcesList. +func (c *CreditSourcesList) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &c.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &c.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CreditsList. +func (c CreditsList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", c.NextLink) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CreditsList. +func (c *CreditsList) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &c.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &c.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CreditsValidateModel. +func (c CreditsValidateModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["benefitType"] = BenefitTypeCredits + populate(objectMap, "properties", c.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CreditsValidateModel. +func (c *CreditsValidateModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "benefitType": + err = unpopulate(val, "BenefitType", &c.BenefitType) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CustomPriceProperties. +func (c CustomPriceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "billingPeriod", c.BillingPeriod) + populate(objectMap, "catalogClaims", c.CatalogClaims) + populate(objectMap, "catalogId", c.CatalogID) + populate(objectMap, "marketSetPrices", c.MarketSetPrices) + populate(objectMap, "meterType", c.MeterType) + populate(objectMap, "ruleType", c.RuleType) + populate(objectMap, "termUnits", c.TermUnits) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CustomPriceProperties. +func (c *CustomPriceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "billingPeriod": + err = unpopulate(val, "BillingPeriod", &c.BillingPeriod) + delete(rawMsg, key) + case "catalogClaims": + err = unpopulate(val, "CatalogClaims", &c.CatalogClaims) + delete(rawMsg, key) + case "catalogId": + err = unpopulate(val, "CatalogID", &c.CatalogID) + delete(rawMsg, key) + case "marketSetPrices": + err = unpopulate(val, "MarketSetPrices", &c.MarketSetPrices) + delete(rawMsg, key) + case "meterType": + err = unpopulate(val, "MeterType", &c.MeterType) + delete(rawMsg, key) + case "ruleType": + err = unpopulate(val, "RuleType", &c.RuleType) + delete(rawMsg, key) + case "termUnits": + err = unpopulate(val, "TermUnits", &c.TermUnits) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Discount. +func (d Discount) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", d.Etag) + populate(objectMap, "id", d.ID) + populate(objectMap, "identity", d.Identity) + populate(objectMap, "kind", d.Kind) + populate(objectMap, "location", d.Location) + populate(objectMap, "managedBy", d.ManagedBy) + populate(objectMap, "name", d.Name) + populate(objectMap, "plan", d.Plan) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "sku", d.SKU) + populate(objectMap, "systemData", d.SystemData) + populate(objectMap, "tags", d.Tags) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Discount. +func (d *Discount) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &d.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &d.Identity) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &d.Kind) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &d.Location) + delete(rawMsg, key) + case "managedBy": + err = unpopulate(val, "ManagedBy", &d.ManagedBy) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "plan": + err = unpopulate(val, "Plan", &d.Plan) + delete(rawMsg, key) + case "properties": + d.Properties, err = unmarshalDiscountPropertiesClassification(val) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &d.SKU) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &d.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &d.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &d.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DiscountList. +func (d DiscountList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", d.NextLink) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiscountList. +func (d *DiscountList) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &d.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &d.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DiscountPatchRequest. +func (d DiscountPatchRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "tags", d.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiscountPatchRequest. +func (d *DiscountPatchRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &d.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &d.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DiscountPatchRequestProperties. +func (d DiscountPatchRequestProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "displayName", d.DisplayName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiscountPatchRequestProperties. +func (d *DiscountPatchRequestProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "displayName": + err = unpopulate(val, "DisplayName", &d.DisplayName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DiscountProperties. +func (d DiscountProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "appliedScopeType", d.AppliedScopeType) + populate(objectMap, "benefitResourceId", d.BenefitResourceID) + populate(objectMap, "billingAccountResourceId", d.BillingAccountResourceID) + populate(objectMap, "billingProfileResourceId", d.BillingProfileResourceID) + populate(objectMap, "customerResourceId", d.CustomerResourceID) + populate(objectMap, "displayName", d.DisplayName) + populate(objectMap, "entityType", d.EntityType) + populate(objectMap, "productCode", d.ProductCode) + populate(objectMap, "provisioningState", d.ProvisioningState) + populateTime[datetime.RFC3339](objectMap, "startAt", d.StartAt) + populate(objectMap, "status", d.Status) + populate(objectMap, "systemId", d.SystemID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiscountProperties. +func (d *DiscountProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "appliedScopeType": + err = unpopulate(val, "AppliedScopeType", &d.AppliedScopeType) + delete(rawMsg, key) + case "benefitResourceId": + err = unpopulate(val, "BenefitResourceID", &d.BenefitResourceID) + delete(rawMsg, key) + case "billingAccountResourceId": + err = unpopulate(val, "BillingAccountResourceID", &d.BillingAccountResourceID) + delete(rawMsg, key) + case "billingProfileResourceId": + err = unpopulate(val, "BillingProfileResourceID", &d.BillingProfileResourceID) + delete(rawMsg, key) + case "customerResourceId": + err = unpopulate(val, "CustomerResourceID", &d.CustomerResourceID) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &d.DisplayName) + delete(rawMsg, key) + case "entityType": + err = unpopulate(val, "EntityType", &d.EntityType) + delete(rawMsg, key) + case "productCode": + err = unpopulate(val, "ProductCode", &d.ProductCode) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &d.ProvisioningState) + delete(rawMsg, key) + case "startAt": + err = unpopulateTime[datetime.RFC3339](val, "StartAt", &d.StartAt) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &d.Status) + delete(rawMsg, key) + case "systemId": + err = unpopulate(val, "SystemID", &d.SystemID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DiscountTypeCustomPrice. +func (d DiscountTypeCustomPrice) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "applyDiscountOn", d.ApplyDiscountOn) + populate(objectMap, "conditions", d.Conditions) + populate(objectMap, "customPriceProperties", d.CustomPriceProperties) + populate(objectMap, "discountCombinationRule", d.DiscountCombinationRule) + populate(objectMap, "discountPercentage", d.DiscountPercentage) + objectMap["discountType"] = DiscountTypeEnumCustomPrice + populate(objectMap, "priceGuaranteeProperties", d.PriceGuaranteeProperties) + populate(objectMap, "productFamilyName", d.ProductFamilyName) + populate(objectMap, "productId", d.ProductID) + populate(objectMap, "skuId", d.SKUID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiscountTypeCustomPrice. +func (d *DiscountTypeCustomPrice) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "applyDiscountOn": + err = unpopulate(val, "ApplyDiscountOn", &d.ApplyDiscountOn) + delete(rawMsg, key) + case "conditions": + err = unpopulate(val, "Conditions", &d.Conditions) + delete(rawMsg, key) + case "customPriceProperties": + err = unpopulate(val, "CustomPriceProperties", &d.CustomPriceProperties) + delete(rawMsg, key) + case "discountCombinationRule": + err = unpopulate(val, "DiscountCombinationRule", &d.DiscountCombinationRule) + delete(rawMsg, key) + case "discountPercentage": + err = unpopulate(val, "DiscountPercentage", &d.DiscountPercentage) + delete(rawMsg, key) + case "discountType": + err = unpopulate(val, "DiscountType", &d.DiscountType) + delete(rawMsg, key) + case "priceGuaranteeProperties": + err = unpopulate(val, "PriceGuaranteeProperties", &d.PriceGuaranteeProperties) + delete(rawMsg, key) + case "productFamilyName": + err = unpopulate(val, "ProductFamilyName", &d.ProductFamilyName) + delete(rawMsg, key) + case "productId": + err = unpopulate(val, "ProductID", &d.ProductID) + delete(rawMsg, key) + case "skuId": + err = unpopulate(val, "SKUID", &d.SKUID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DiscountTypeCustomPriceMultiCurrency. +func (d DiscountTypeCustomPriceMultiCurrency) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "applyDiscountOn", d.ApplyDiscountOn) + populate(objectMap, "conditions", d.Conditions) + populate(objectMap, "customPriceProperties", d.CustomPriceProperties) + populate(objectMap, "discountCombinationRule", d.DiscountCombinationRule) + populate(objectMap, "discountPercentage", d.DiscountPercentage) + objectMap["discountType"] = DiscountTypeEnumCustomPriceMultiCurrency + populate(objectMap, "priceGuaranteeProperties", d.PriceGuaranteeProperties) + populate(objectMap, "productFamilyName", d.ProductFamilyName) + populate(objectMap, "productId", d.ProductID) + populate(objectMap, "skuId", d.SKUID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiscountTypeCustomPriceMultiCurrency. +func (d *DiscountTypeCustomPriceMultiCurrency) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "applyDiscountOn": + err = unpopulate(val, "ApplyDiscountOn", &d.ApplyDiscountOn) + delete(rawMsg, key) + case "conditions": + err = unpopulate(val, "Conditions", &d.Conditions) + delete(rawMsg, key) + case "customPriceProperties": + err = unpopulate(val, "CustomPriceProperties", &d.CustomPriceProperties) + delete(rawMsg, key) + case "discountCombinationRule": + err = unpopulate(val, "DiscountCombinationRule", &d.DiscountCombinationRule) + delete(rawMsg, key) + case "discountPercentage": + err = unpopulate(val, "DiscountPercentage", &d.DiscountPercentage) + delete(rawMsg, key) + case "discountType": + err = unpopulate(val, "DiscountType", &d.DiscountType) + delete(rawMsg, key) + case "priceGuaranteeProperties": + err = unpopulate(val, "PriceGuaranteeProperties", &d.PriceGuaranteeProperties) + delete(rawMsg, key) + case "productFamilyName": + err = unpopulate(val, "ProductFamilyName", &d.ProductFamilyName) + delete(rawMsg, key) + case "productId": + err = unpopulate(val, "ProductID", &d.ProductID) + delete(rawMsg, key) + case "skuId": + err = unpopulate(val, "SKUID", &d.SKUID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DiscountTypeProduct. +func (d DiscountTypeProduct) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "applyDiscountOn", d.ApplyDiscountOn) + populate(objectMap, "conditions", d.Conditions) + populate(objectMap, "discountCombinationRule", d.DiscountCombinationRule) + populate(objectMap, "discountPercentage", d.DiscountPercentage) + objectMap["discountType"] = DiscountTypeEnumProduct + populate(objectMap, "priceGuaranteeProperties", d.PriceGuaranteeProperties) + populate(objectMap, "productFamilyName", d.ProductFamilyName) + populate(objectMap, "productId", d.ProductID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiscountTypeProduct. +func (d *DiscountTypeProduct) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "applyDiscountOn": + err = unpopulate(val, "ApplyDiscountOn", &d.ApplyDiscountOn) + delete(rawMsg, key) + case "conditions": + err = unpopulate(val, "Conditions", &d.Conditions) + delete(rawMsg, key) + case "discountCombinationRule": + err = unpopulate(val, "DiscountCombinationRule", &d.DiscountCombinationRule) + delete(rawMsg, key) + case "discountPercentage": + err = unpopulate(val, "DiscountPercentage", &d.DiscountPercentage) + delete(rawMsg, key) + case "discountType": + err = unpopulate(val, "DiscountType", &d.DiscountType) + delete(rawMsg, key) + case "priceGuaranteeProperties": + err = unpopulate(val, "PriceGuaranteeProperties", &d.PriceGuaranteeProperties) + delete(rawMsg, key) + case "productFamilyName": + err = unpopulate(val, "ProductFamilyName", &d.ProductFamilyName) + delete(rawMsg, key) + case "productId": + err = unpopulate(val, "ProductID", &d.ProductID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DiscountTypeProductFamily. +func (d DiscountTypeProductFamily) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "applyDiscountOn", d.ApplyDiscountOn) + populate(objectMap, "conditions", d.Conditions) + populate(objectMap, "discountCombinationRule", d.DiscountCombinationRule) + populate(objectMap, "discountPercentage", d.DiscountPercentage) + objectMap["discountType"] = DiscountTypeEnumProductFamily + populate(objectMap, "priceGuaranteeProperties", d.PriceGuaranteeProperties) + populate(objectMap, "productFamilyName", d.ProductFamilyName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiscountTypeProductFamily. +func (d *DiscountTypeProductFamily) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "applyDiscountOn": + err = unpopulate(val, "ApplyDiscountOn", &d.ApplyDiscountOn) + delete(rawMsg, key) + case "conditions": + err = unpopulate(val, "Conditions", &d.Conditions) + delete(rawMsg, key) + case "discountCombinationRule": + err = unpopulate(val, "DiscountCombinationRule", &d.DiscountCombinationRule) + delete(rawMsg, key) + case "discountPercentage": + err = unpopulate(val, "DiscountPercentage", &d.DiscountPercentage) + delete(rawMsg, key) + case "discountType": + err = unpopulate(val, "DiscountType", &d.DiscountType) + delete(rawMsg, key) + case "priceGuaranteeProperties": + err = unpopulate(val, "PriceGuaranteeProperties", &d.PriceGuaranteeProperties) + delete(rawMsg, key) + case "productFamilyName": + err = unpopulate(val, "ProductFamilyName", &d.ProductFamilyName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DiscountTypeProductSKU. +func (d DiscountTypeProductSKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "applyDiscountOn", d.ApplyDiscountOn) + populate(objectMap, "conditions", d.Conditions) + populate(objectMap, "discountCombinationRule", d.DiscountCombinationRule) + populate(objectMap, "discountPercentage", d.DiscountPercentage) + objectMap["discountType"] = DiscountTypeEnumSKU + populate(objectMap, "priceGuaranteeProperties", d.PriceGuaranteeProperties) + populate(objectMap, "productFamilyName", d.ProductFamilyName) + populate(objectMap, "productId", d.ProductID) + populate(objectMap, "skuId", d.SKUID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiscountTypeProductSKU. +func (d *DiscountTypeProductSKU) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "applyDiscountOn": + err = unpopulate(val, "ApplyDiscountOn", &d.ApplyDiscountOn) + delete(rawMsg, key) + case "conditions": + err = unpopulate(val, "Conditions", &d.Conditions) + delete(rawMsg, key) + case "discountCombinationRule": + err = unpopulate(val, "DiscountCombinationRule", &d.DiscountCombinationRule) + delete(rawMsg, key) + case "discountPercentage": + err = unpopulate(val, "DiscountPercentage", &d.DiscountPercentage) + delete(rawMsg, key) + case "discountType": + err = unpopulate(val, "DiscountType", &d.DiscountType) + delete(rawMsg, key) + case "priceGuaranteeProperties": + err = unpopulate(val, "PriceGuaranteeProperties", &d.PriceGuaranteeProperties) + delete(rawMsg, key) + case "productFamilyName": + err = unpopulate(val, "ProductFamilyName", &d.ProductFamilyName) + delete(rawMsg, key) + case "productId": + err = unpopulate(val, "ProductID", &d.ProductID) + delete(rawMsg, key) + case "skuId": + err = unpopulate(val, "SKUID", &d.SKUID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DiscountTypeProperties. +func (d DiscountTypeProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "applyDiscountOn", d.ApplyDiscountOn) + populate(objectMap, "conditions", d.Conditions) + populate(objectMap, "discountCombinationRule", d.DiscountCombinationRule) + populate(objectMap, "discountPercentage", d.DiscountPercentage) + populate(objectMap, "discountType", d.DiscountType) + populate(objectMap, "priceGuaranteeProperties", d.PriceGuaranteeProperties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiscountTypeProperties. +func (d *DiscountTypeProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "applyDiscountOn": + err = unpopulate(val, "ApplyDiscountOn", &d.ApplyDiscountOn) + delete(rawMsg, key) + case "conditions": + err = unpopulate(val, "Conditions", &d.Conditions) + delete(rawMsg, key) + case "discountCombinationRule": + err = unpopulate(val, "DiscountCombinationRule", &d.DiscountCombinationRule) + delete(rawMsg, key) + case "discountPercentage": + err = unpopulate(val, "DiscountPercentage", &d.DiscountPercentage) + delete(rawMsg, key) + case "discountType": + err = unpopulate(val, "DiscountType", &d.DiscountType) + delete(rawMsg, key) + case "priceGuaranteeProperties": + err = unpopulate(val, "PriceGuaranteeProperties", &d.PriceGuaranteeProperties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EntityTypeAffiliateDiscount. +func (e EntityTypeAffiliateDiscount) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "appliedScopeType", e.AppliedScopeType) + populate(objectMap, "benefitResourceId", e.BenefitResourceID) + populate(objectMap, "billingAccountResourceId", e.BillingAccountResourceID) + populate(objectMap, "billingProfileResourceId", e.BillingProfileResourceID) + populate(objectMap, "customerResourceId", e.CustomerResourceID) + populate(objectMap, "displayName", e.DisplayName) + populateTime[datetime.RFC3339](objectMap, "endAt", e.EndAt) + objectMap["entityType"] = DiscountEntityTypeAffiliate + populate(objectMap, "primaryResourceId", e.PrimaryResourceID) + populate(objectMap, "productCode", e.ProductCode) + populate(objectMap, "provisioningState", e.ProvisioningState) + populateTime[datetime.RFC3339](objectMap, "startAt", e.StartAt) + populate(objectMap, "status", e.Status) + populate(objectMap, "systemId", e.SystemID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EntityTypeAffiliateDiscount. +func (e *EntityTypeAffiliateDiscount) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "appliedScopeType": + err = unpopulate(val, "AppliedScopeType", &e.AppliedScopeType) + delete(rawMsg, key) + case "benefitResourceId": + err = unpopulate(val, "BenefitResourceID", &e.BenefitResourceID) + delete(rawMsg, key) + case "billingAccountResourceId": + err = unpopulate(val, "BillingAccountResourceID", &e.BillingAccountResourceID) + delete(rawMsg, key) + case "billingProfileResourceId": + err = unpopulate(val, "BillingProfileResourceID", &e.BillingProfileResourceID) + delete(rawMsg, key) + case "customerResourceId": + err = unpopulate(val, "CustomerResourceID", &e.CustomerResourceID) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &e.DisplayName) + delete(rawMsg, key) + case "endAt": + err = unpopulateTime[datetime.RFC3339](val, "EndAt", &e.EndAt) + delete(rawMsg, key) + case "entityType": + err = unpopulate(val, "EntityType", &e.EntityType) + delete(rawMsg, key) + case "primaryResourceId": + err = unpopulate(val, "PrimaryResourceID", &e.PrimaryResourceID) + delete(rawMsg, key) + case "productCode": + err = unpopulate(val, "ProductCode", &e.ProductCode) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &e.ProvisioningState) + delete(rawMsg, key) + case "startAt": + err = unpopulateTime[datetime.RFC3339](val, "StartAt", &e.StartAt) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &e.Status) + delete(rawMsg, key) + case "systemId": + err = unpopulate(val, "SystemID", &e.SystemID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EntityTypePrimaryDiscount. +func (e EntityTypePrimaryDiscount) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "appliedScopeType", e.AppliedScopeType) + populate(objectMap, "benefitResourceId", e.BenefitResourceID) + populate(objectMap, "billingAccountResourceId", e.BillingAccountResourceID) + populate(objectMap, "billingProfileResourceId", e.BillingProfileResourceID) + populate(objectMap, "customerResourceId", e.CustomerResourceID) + populate(objectMap, "discountTypeProperties", e.DiscountTypeProperties) + populate(objectMap, "displayName", e.DisplayName) + populateTime[datetime.RFC3339](objectMap, "endAt", e.EndAt) + objectMap["entityType"] = DiscountEntityTypePrimary + populate(objectMap, "productCode", e.ProductCode) + populate(objectMap, "provisioningState", e.ProvisioningState) + populateTime[datetime.RFC3339](objectMap, "startAt", e.StartAt) + populate(objectMap, "status", e.Status) + populate(objectMap, "systemId", e.SystemID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EntityTypePrimaryDiscount. +func (e *EntityTypePrimaryDiscount) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "appliedScopeType": + err = unpopulate(val, "AppliedScopeType", &e.AppliedScopeType) + delete(rawMsg, key) + case "benefitResourceId": + err = unpopulate(val, "BenefitResourceID", &e.BenefitResourceID) + delete(rawMsg, key) + case "billingAccountResourceId": + err = unpopulate(val, "BillingAccountResourceID", &e.BillingAccountResourceID) + delete(rawMsg, key) + case "billingProfileResourceId": + err = unpopulate(val, "BillingProfileResourceID", &e.BillingProfileResourceID) + delete(rawMsg, key) + case "customerResourceId": + err = unpopulate(val, "CustomerResourceID", &e.CustomerResourceID) + delete(rawMsg, key) + case "discountTypeProperties": + e.DiscountTypeProperties, err = unmarshalDiscountTypePropertiesClassification(val) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &e.DisplayName) + delete(rawMsg, key) + case "endAt": + err = unpopulateTime[datetime.RFC3339](val, "EndAt", &e.EndAt) + delete(rawMsg, key) + case "entityType": + err = unpopulate(val, "EntityType", &e.EntityType) + delete(rawMsg, key) + case "productCode": + err = unpopulate(val, "ProductCode", &e.ProductCode) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &e.ProvisioningState) + delete(rawMsg, key) + case "startAt": + err = unpopulateTime[datetime.RFC3339](val, "StartAt", &e.StartAt) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &e.Status) + delete(rawMsg, key) + case "systemId": + err = unpopulate(val, "SystemID", &e.SystemID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExtendedStatusInfo. +func (e ExtendedStatusInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "message", e.Message) + populate(objectMap, "statusCode", e.StatusCode) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExtendedStatusInfo. +func (e *ExtendedStatusInfo) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "message": + err = unpopulate(val, "Message", &e.Message) + delete(rawMsg, key) + case "statusCode": + err = unpopulate(val, "StatusCode", &e.StatusCode) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FreeServices. +func (f FreeServices) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", f.Etag) + populate(objectMap, "id", f.ID) + populate(objectMap, "identity", f.Identity) + populate(objectMap, "kind", f.Kind) + populate(objectMap, "location", f.Location) + populate(objectMap, "managedBy", f.ManagedBy) + populate(objectMap, "name", f.Name) + populate(objectMap, "plan", f.Plan) + populate(objectMap, "properties", f.Properties) + populate(objectMap, "sku", f.SKU) + populate(objectMap, "systemData", f.SystemData) + populate(objectMap, "tags", f.Tags) + populate(objectMap, "type", f.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FreeServices. +func (f *FreeServices) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &f.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &f.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &f.Identity) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &f.Kind) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &f.Location) + delete(rawMsg, key) + case "managedBy": + err = unpopulate(val, "ManagedBy", &f.ManagedBy) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &f.Name) + delete(rawMsg, key) + case "plan": + err = unpopulate(val, "Plan", &f.Plan) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &f.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &f.SKU) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &f.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &f.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &f.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FreeServicesList. +func (f FreeServicesList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", f.NextLink) + populate(objectMap, "value", f.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FreeServicesList. +func (f *FreeServicesList) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &f.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &f.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FreeServicesPatchRequest. +func (f FreeServicesPatchRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", f.Properties) + populate(objectMap, "tags", f.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FreeServicesPatchRequest. +func (f *FreeServicesPatchRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &f.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &f.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FreeServicesPatchRequestProperties. +func (f FreeServicesPatchRequestProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "endAt", f.EndAt) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FreeServicesPatchRequestProperties. +func (f *FreeServicesPatchRequestProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "endAt": + err = unpopulateTime[datetime.RFC3339](val, "EndAt", &f.EndAt) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FreeServicesProperties. +func (f FreeServicesProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "billingAccountResourceId", f.BillingAccountResourceID) + populate(objectMap, "billingProfileResourceId", f.BillingProfileResourceID) + populate(objectMap, "customerResourceId", f.CustomerResourceID) + populateTime[datetime.RFC3339](objectMap, "endAt", f.EndAt) + populate(objectMap, "productCode", f.ProductCode) + populate(objectMap, "provisioningState", f.ProvisioningState) + populateTime[datetime.RFC3339](objectMap, "startAt", f.StartAt) + populate(objectMap, "status", f.Status) + populate(objectMap, "systemId", f.SystemID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FreeServicesProperties. +func (f *FreeServicesProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "billingAccountResourceId": + err = unpopulate(val, "BillingAccountResourceID", &f.BillingAccountResourceID) + delete(rawMsg, key) + case "billingProfileResourceId": + err = unpopulate(val, "BillingProfileResourceID", &f.BillingProfileResourceID) + delete(rawMsg, key) + case "customerResourceId": + err = unpopulate(val, "CustomerResourceID", &f.CustomerResourceID) + delete(rawMsg, key) + case "endAt": + err = unpopulateTime[datetime.RFC3339](val, "EndAt", &f.EndAt) + delete(rawMsg, key) + case "productCode": + err = unpopulate(val, "ProductCode", &f.ProductCode) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &f.ProvisioningState) + delete(rawMsg, key) + case "startAt": + err = unpopulateTime[datetime.RFC3339](val, "StartAt", &f.StartAt) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &f.Status) + delete(rawMsg, key) + case "systemId": + err = unpopulate(val, "SystemID", &f.SystemID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Macc. +func (m Macc) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", m.Etag) + populate(objectMap, "id", m.ID) + populate(objectMap, "identity", m.Identity) + populate(objectMap, "kind", m.Kind) + populate(objectMap, "location", m.Location) + populate(objectMap, "managedBy", m.ManagedBy) + populate(objectMap, "name", m.Name) + populate(objectMap, "plan", m.Plan) + populate(objectMap, "properties", m.Properties) + populate(objectMap, "sku", m.SKU) + populate(objectMap, "systemData", m.SystemData) + populate(objectMap, "tags", m.Tags) + populate(objectMap, "type", m.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Macc. +func (m *Macc) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &m.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &m.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &m.Identity) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &m.Kind) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &m.Location) + delete(rawMsg, key) + case "managedBy": + err = unpopulate(val, "ManagedBy", &m.ManagedBy) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &m.Name) + delete(rawMsg, key) + case "plan": + err = unpopulate(val, "Plan", &m.Plan) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &m.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &m.SKU) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &m.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &m.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MaccList. +func (m MaccList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", m.NextLink) + populate(objectMap, "value", m.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MaccList. +func (m *MaccList) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &m.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &m.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MaccMilestone. +func (m MaccMilestone) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "automaticShortfall", m.AutomaticShortfall) + populate(objectMap, "automaticShortfallSuppressReason", m.AutomaticShortfallSuppressReason) + populate(objectMap, "commitment", m.Commitment) + populateTime[datetime.RFC3339](objectMap, "endAt", m.EndAt) + populate(objectMap, "milestoneId", m.MilestoneID) + populate(objectMap, "shortfall", m.Shortfall) + populate(objectMap, "status", m.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MaccMilestone. +func (m *MaccMilestone) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "automaticShortfall": + err = unpopulate(val, "AutomaticShortfall", &m.AutomaticShortfall) + delete(rawMsg, key) + case "automaticShortfallSuppressReason": + err = unpopulate(val, "AutomaticShortfallSuppressReason", &m.AutomaticShortfallSuppressReason) + delete(rawMsg, key) + case "commitment": + err = unpopulate(val, "Commitment", &m.Commitment) + delete(rawMsg, key) + case "endAt": + err = unpopulateTime[datetime.RFC3339](val, "EndAt", &m.EndAt) + delete(rawMsg, key) + case "milestoneId": + err = unpopulate(val, "MilestoneID", &m.MilestoneID) + delete(rawMsg, key) + case "shortfall": + err = unpopulate(val, "Shortfall", &m.Shortfall) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &m.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MaccModelProperties. +func (m MaccModelProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowContributors", m.AllowContributors) + populate(objectMap, "automaticShortfall", m.AutomaticShortfall) + populate(objectMap, "automaticShortfallSuppressReason", m.AutomaticShortfallSuppressReason) + populate(objectMap, "billingAccountResourceId", m.BillingAccountResourceID) + populate(objectMap, "commitment", m.Commitment) + populate(objectMap, "displayName", m.DisplayName) + populateTime[datetime.RFC3339](objectMap, "endAt", m.EndAt) + populate(objectMap, "entityType", m.EntityType) + populate(objectMap, "milestones", m.Milestones) + populate(objectMap, "primaryBillingAccountResourceId", m.PrimaryBillingAccountResourceID) + populate(objectMap, "primaryResourceId", m.PrimaryResourceID) + populate(objectMap, "productCode", m.ProductCode) + populate(objectMap, "provisioningState", m.ProvisioningState) + populate(objectMap, "resourceId", m.ResourceID) + populate(objectMap, "shortfall", m.Shortfall) + populateTime[datetime.RFC3339](objectMap, "startAt", m.StartAt) + populate(objectMap, "status", m.Status) + populate(objectMap, "systemId", m.SystemID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MaccModelProperties. +func (m *MaccModelProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "allowContributors": + err = unpopulate(val, "AllowContributors", &m.AllowContributors) + delete(rawMsg, key) + case "automaticShortfall": + err = unpopulate(val, "AutomaticShortfall", &m.AutomaticShortfall) + delete(rawMsg, key) + case "automaticShortfallSuppressReason": + err = unpopulate(val, "AutomaticShortfallSuppressReason", &m.AutomaticShortfallSuppressReason) + delete(rawMsg, key) + case "billingAccountResourceId": + err = unpopulate(val, "BillingAccountResourceID", &m.BillingAccountResourceID) + delete(rawMsg, key) + case "commitment": + err = unpopulate(val, "Commitment", &m.Commitment) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &m.DisplayName) + delete(rawMsg, key) + case "endAt": + err = unpopulateTime[datetime.RFC3339](val, "EndAt", &m.EndAt) + delete(rawMsg, key) + case "entityType": + err = unpopulate(val, "EntityType", &m.EntityType) + delete(rawMsg, key) + case "milestones": + err = unpopulate(val, "Milestones", &m.Milestones) + delete(rawMsg, key) + case "primaryBillingAccountResourceId": + err = unpopulate(val, "PrimaryBillingAccountResourceID", &m.PrimaryBillingAccountResourceID) + delete(rawMsg, key) + case "primaryResourceId": + err = unpopulate(val, "PrimaryResourceID", &m.PrimaryResourceID) + delete(rawMsg, key) + case "productCode": + err = unpopulate(val, "ProductCode", &m.ProductCode) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &m.ProvisioningState) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &m.ResourceID) + delete(rawMsg, key) + case "shortfall": + err = unpopulate(val, "Shortfall", &m.Shortfall) + delete(rawMsg, key) + case "startAt": + err = unpopulateTime[datetime.RFC3339](val, "StartAt", &m.StartAt) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &m.Status) + delete(rawMsg, key) + case "systemId": + err = unpopulate(val, "SystemID", &m.SystemID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MaccPatchRequest. +func (m MaccPatchRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", m.Properties) + populate(objectMap, "tags", m.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MaccPatchRequest. +func (m *MaccPatchRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &m.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &m.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MaccPatchRequestProperties. +func (m MaccPatchRequestProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowContributors", m.AllowContributors) + populate(objectMap, "automaticShortfall", m.AutomaticShortfall) + populate(objectMap, "automaticShortfallSuppressReason", m.AutomaticShortfallSuppressReason) + populate(objectMap, "commitment", m.Commitment) + populate(objectMap, "displayName", m.DisplayName) + populateTime[datetime.RFC3339](objectMap, "endAt", m.EndAt) + populate(objectMap, "milestones", m.Milestones) + populate(objectMap, "primaryBillingAccountResourceId", m.PrimaryBillingAccountResourceID) + populate(objectMap, "primaryResourceId", m.PrimaryResourceID) + populate(objectMap, "status", m.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MaccPatchRequestProperties. +func (m *MaccPatchRequestProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "allowContributors": + err = unpopulate(val, "AllowContributors", &m.AllowContributors) + delete(rawMsg, key) + case "automaticShortfall": + err = unpopulate(val, "AutomaticShortfall", &m.AutomaticShortfall) + delete(rawMsg, key) + case "automaticShortfallSuppressReason": + err = unpopulate(val, "AutomaticShortfallSuppressReason", &m.AutomaticShortfallSuppressReason) + delete(rawMsg, key) + case "commitment": + err = unpopulate(val, "Commitment", &m.Commitment) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &m.DisplayName) + delete(rawMsg, key) + case "endAt": + err = unpopulateTime[datetime.RFC3339](val, "EndAt", &m.EndAt) + delete(rawMsg, key) + case "milestones": + err = unpopulate(val, "Milestones", &m.Milestones) + delete(rawMsg, key) + case "primaryBillingAccountResourceId": + err = unpopulate(val, "PrimaryBillingAccountResourceID", &m.PrimaryBillingAccountResourceID) + delete(rawMsg, key) + case "primaryResourceId": + err = unpopulate(val, "PrimaryResourceID", &m.PrimaryResourceID) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &m.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MaccValidateModel. +func (m MaccValidateModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["benefitType"] = BenefitTypeMACC + populate(objectMap, "properties", m.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MaccValidateModel. +func (m *MaccValidateModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "benefitType": + err = unpopulate(val, "BenefitType", &m.BenefitType) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &m.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedServiceIdentity. +func (m ManagedServiceIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "principalId", m.PrincipalID) + populate(objectMap, "tenantId", m.TenantID) + populate(objectMap, "type", m.Type) + populate(objectMap, "userAssignedIdentities", m.UserAssignedIdentities) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedServiceIdentity. +func (m *ManagedServiceIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "principalId": + err = unpopulate(val, "PrincipalID", &m.PrincipalID) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &m.TenantID) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + case "userAssignedIdentities": + err = unpopulate(val, "UserAssignedIdentities", &m.UserAssignedIdentities) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MarketSetPricesItems. +func (m MarketSetPricesItems) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "currency", m.Currency) + populate(objectMap, "markets", m.Markets) + populate(objectMap, "value", m.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MarketSetPricesItems. +func (m *MarketSetPricesItems) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "currency": + err = unpopulate(val, "Currency", &m.Currency) + delete(rawMsg, key) + case "markets": + err = unpopulate(val, "Markets", &m.Markets) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &m.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Operation. +func (o Operation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionType", o.ActionType) + populate(objectMap, "display", o.Display) + populate(objectMap, "isDataAction", o.IsDataAction) + populate(objectMap, "name", o.Name) + populate(objectMap, "origin", o.Origin) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Operation. +func (o *Operation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionType": + err = unpopulate(val, "ActionType", &o.ActionType) + delete(rawMsg, key) + case "display": + err = unpopulate(val, "Display", &o.Display) + delete(rawMsg, key) + case "isDataAction": + err = unpopulate(val, "IsDataAction", &o.IsDataAction) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "origin": + err = unpopulate(val, "Origin", &o.Origin) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationDisplay. +func (o OperationDisplay) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", o.Description) + populate(objectMap, "operation", o.Operation) + populate(objectMap, "provider", o.Provider) + populate(objectMap, "resource", o.Resource) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationDisplay. +func (o *OperationDisplay) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &o.Description) + delete(rawMsg, key) + case "operation": + err = unpopulate(val, "Operation", &o.Operation) + delete(rawMsg, key) + case "provider": + err = unpopulate(val, "Provider", &o.Provider) + delete(rawMsg, key) + case "resource": + err = unpopulate(val, "Resource", &o.Resource) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationListResult. +func (o *OperationListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &o.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PaymentDetail. +func (p PaymentDetail) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "billingAccount", p.BillingAccount) + populate(objectMap, "billingCurrencyTotal", p.BillingCurrencyTotal) + populateTime[datetime.PlainDate](objectMap, "dueDate", p.DueDate) + populate(objectMap, "extendedStatusInfo", p.ExtendedStatusInfo) + populateTime[datetime.PlainDate](objectMap, "paymentDate", p.PaymentDate) + populate(objectMap, "pricingCurrencyTotal", p.PricingCurrencyTotal) + populate(objectMap, "status", p.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PaymentDetail. +func (p *PaymentDetail) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "billingAccount": + err = unpopulate(val, "BillingAccount", &p.BillingAccount) + delete(rawMsg, key) + case "billingCurrencyTotal": + err = unpopulate(val, "BillingCurrencyTotal", &p.BillingCurrencyTotal) + delete(rawMsg, key) + case "dueDate": + err = unpopulateTime[datetime.PlainDate](val, "DueDate", &p.DueDate) + delete(rawMsg, key) + case "extendedStatusInfo": + err = unpopulate(val, "ExtendedStatusInfo", &p.ExtendedStatusInfo) + delete(rawMsg, key) + case "paymentDate": + err = unpopulateTime[datetime.PlainDate](val, "PaymentDate", &p.PaymentDate) + delete(rawMsg, key) + case "pricingCurrencyTotal": + err = unpopulate(val, "PricingCurrencyTotal", &p.PricingCurrencyTotal) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &p.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Plan. +func (p Plan) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", p.Name) + populate(objectMap, "product", p.Product) + populate(objectMap, "promotionCode", p.PromotionCode) + populate(objectMap, "publisher", p.Publisher) + populate(objectMap, "version", p.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Plan. +func (p *Plan) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "product": + err = unpopulate(val, "Product", &p.Product) + delete(rawMsg, key) + case "promotionCode": + err = unpopulate(val, "PromotionCode", &p.PromotionCode) + delete(rawMsg, key) + case "publisher": + err = unpopulate(val, "Publisher", &p.Publisher) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &p.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Price. +func (p Price) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "amount", p.Amount) + populate(objectMap, "currencyCode", p.CurrencyCode) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Price. +func (p *Price) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "amount": + err = unpopulate(val, "Amount", &p.Amount) + delete(rawMsg, key) + case "currencyCode": + err = unpopulate(val, "CurrencyCode", &p.CurrencyCode) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PriceGuaranteeProperties. +func (p PriceGuaranteeProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "priceGuaranteeDate", p.PriceGuaranteeDate) + populate(objectMap, "pricingPolicy", p.PricingPolicy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PriceGuaranteeProperties. +func (p *PriceGuaranteeProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "priceGuaranteeDate": + err = unpopulateTime[datetime.RFC3339](val, "PriceGuaranteeDate", &p.PriceGuaranteeDate) + delete(rawMsg, key) + case "pricingPolicy": + err = unpopulate(val, "PricingPolicy", &p.PricingPolicy) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrimaryConditionalCreditProperties. +func (p PrimaryConditionalCreditProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowContributors", p.AllowContributors) + populate(objectMap, "benefitResourceId", p.BenefitResourceID) + populate(objectMap, "billingAccountResourceId", p.BillingAccountResourceID) + populate(objectMap, "displayName", p.DisplayName) + populateTime[datetime.RFC3339](objectMap, "endAt", p.EndAt) + objectMap["entityType"] = ConditionalCreditEntityTypePrimary + populate(objectMap, "milestones", p.Milestones) + populate(objectMap, "productCode", p.ProductCode) + populate(objectMap, "provisioningState", p.ProvisioningState) + populate(objectMap, "resourceId", p.ResourceID) + populateTime[datetime.RFC3339](objectMap, "startAt", p.StartAt) + populate(objectMap, "status", p.Status) + populate(objectMap, "systemId", p.SystemID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrimaryConditionalCreditProperties. +func (p *PrimaryConditionalCreditProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "allowContributors": + err = unpopulate(val, "AllowContributors", &p.AllowContributors) + delete(rawMsg, key) + case "benefitResourceId": + err = unpopulate(val, "BenefitResourceID", &p.BenefitResourceID) + delete(rawMsg, key) + case "billingAccountResourceId": + err = unpopulate(val, "BillingAccountResourceID", &p.BillingAccountResourceID) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &p.DisplayName) + delete(rawMsg, key) + case "endAt": + err = unpopulateTime[datetime.RFC3339](val, "EndAt", &p.EndAt) + delete(rawMsg, key) + case "entityType": + err = unpopulate(val, "EntityType", &p.EntityType) + delete(rawMsg, key) + case "milestones": + err = unpopulate(val, "Milestones", &p.Milestones) + delete(rawMsg, key) + case "productCode": + err = unpopulate(val, "ProductCode", &p.ProductCode) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &p.ResourceID) + delete(rawMsg, key) + case "startAt": + err = unpopulateTime[datetime.RFC3339](val, "StartAt", &p.StartAt) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &p.Status) + delete(rawMsg, key) + case "systemId": + err = unpopulate(val, "SystemID", &p.SystemID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PurchaseRequest. +func (p PurchaseRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", p.Properties) + populate(objectMap, "sku", p.SKU) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PurchaseRequest. +func (p *PurchaseRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &p.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &p.SKU) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PurchaseRequestProperties. +func (p PurchaseRequestProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "appliedScopeProperties", p.AppliedScopeProperties) + populate(objectMap, "appliedScopeType", p.AppliedScopeType) + populate(objectMap, "billingPlan", p.BillingPlan) + populate(objectMap, "billingScopeId", p.BillingScopeID) + populate(objectMap, "commitment", p.Commitment) + populate(objectMap, "displayName", p.DisplayName) + populateTime[datetime.RFC3339](objectMap, "effectiveDateTime", p.EffectiveDateTime) + populate(objectMap, "renew", p.Renew) + populate(objectMap, "term", p.Term) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PurchaseRequestProperties. +func (p *PurchaseRequestProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "appliedScopeProperties": + err = unpopulate(val, "AppliedScopeProperties", &p.AppliedScopeProperties) + delete(rawMsg, key) + case "appliedScopeType": + err = unpopulate(val, "AppliedScopeType", &p.AppliedScopeType) + delete(rawMsg, key) + case "billingPlan": + err = unpopulate(val, "BillingPlan", &p.BillingPlan) + delete(rawMsg, key) + case "billingScopeId": + err = unpopulate(val, "BillingScopeID", &p.BillingScopeID) + delete(rawMsg, key) + case "commitment": + err = unpopulate(val, "Commitment", &p.Commitment) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &p.DisplayName) + delete(rawMsg, key) + case "effectiveDateTime": + err = unpopulateTime[datetime.RFC3339](val, "EffectiveDateTime", &p.EffectiveDateTime) + delete(rawMsg, key) + case "renew": + err = unpopulate(val, "Renew", &p.Renew) + delete(rawMsg, key) + case "term": + err = unpopulate(val, "Term", &p.Term) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RenewProperties. +func (r RenewProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "purchaseProperties", r.PurchaseProperties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RenewProperties. +func (r *RenewProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "purchaseProperties": + err = unpopulate(val, "PurchaseProperties", &r.PurchaseProperties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ReservationOrderAliasRequest. +func (r ReservationOrderAliasRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", r.ID) + populate(objectMap, "location", r.Location) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "sku", r.SKU) + populate(objectMap, "systemData", r.SystemData) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ReservationOrderAliasRequest. +func (r *ReservationOrderAliasRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &r.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &r.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &r.SKU) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &r.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ReservationOrderAliasRequestProperties. +func (r ReservationOrderAliasRequestProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "appliedScopeProperties", r.AppliedScopeProperties) + populate(objectMap, "appliedScopeType", r.AppliedScopeType) + populate(objectMap, "billingPlan", r.BillingPlan) + populate(objectMap, "billingScopeId", r.BillingScopeID) + populate(objectMap, "displayName", r.DisplayName) + populate(objectMap, "quantity", r.Quantity) + populate(objectMap, "renew", r.Renew) + populate(objectMap, "reservedResourceProperties", r.ReservedResourceProperties) + populate(objectMap, "reservedResourceType", r.ReservedResourceType) + populateTime[datetime.RFC3339](objectMap, "reviewDateTime", r.ReviewDateTime) + populate(objectMap, "term", r.Term) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ReservationOrderAliasRequestProperties. +func (r *ReservationOrderAliasRequestProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "appliedScopeProperties": + err = unpopulate(val, "AppliedScopeProperties", &r.AppliedScopeProperties) + delete(rawMsg, key) + case "appliedScopeType": + err = unpopulate(val, "AppliedScopeType", &r.AppliedScopeType) + delete(rawMsg, key) + case "billingPlan": + err = unpopulate(val, "BillingPlan", &r.BillingPlan) + delete(rawMsg, key) + case "billingScopeId": + err = unpopulate(val, "BillingScopeID", &r.BillingScopeID) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &r.DisplayName) + delete(rawMsg, key) + case "quantity": + err = unpopulate(val, "Quantity", &r.Quantity) + delete(rawMsg, key) + case "renew": + err = unpopulate(val, "Renew", &r.Renew) + delete(rawMsg, key) + case "reservedResourceProperties": + err = unpopulate(val, "ReservedResourceProperties", &r.ReservedResourceProperties) + delete(rawMsg, key) + case "reservedResourceType": + err = unpopulate(val, "ReservedResourceType", &r.ReservedResourceType) + delete(rawMsg, key) + case "reviewDateTime": + err = unpopulateTime[datetime.RFC3339](val, "ReviewDateTime", &r.ReviewDateTime) + delete(rawMsg, key) + case "term": + err = unpopulate(val, "Term", &r.Term) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ReservationOrderAliasRequestPropertiesReservedResourceProperties. +func (r ReservationOrderAliasRequestPropertiesReservedResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "instanceFlexibility", r.InstanceFlexibility) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ReservationOrderAliasRequestPropertiesReservedResourceProperties. +func (r *ReservationOrderAliasRequestPropertiesReservedResourceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "instanceFlexibility": + err = unpopulate(val, "InstanceFlexibility", &r.InstanceFlexibility) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ReservationOrderAliasResponse. +func (r ReservationOrderAliasResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", r.ID) + populate(objectMap, "location", r.Location) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "sku", r.SKU) + populate(objectMap, "systemData", r.SystemData) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ReservationOrderAliasResponse. +func (r *ReservationOrderAliasResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &r.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &r.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &r.SKU) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &r.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ReservationOrderAliasResponseProperties. +func (r ReservationOrderAliasResponseProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "appliedScopeProperties", r.AppliedScopeProperties) + populate(objectMap, "appliedScopeType", r.AppliedScopeType) + populate(objectMap, "billingPlan", r.BillingPlan) + populate(objectMap, "billingScopeId", r.BillingScopeID) + populate(objectMap, "displayName", r.DisplayName) + populate(objectMap, "provisioningState", r.ProvisioningState) + populate(objectMap, "quantity", r.Quantity) + populate(objectMap, "renew", r.Renew) + populate(objectMap, "reservationOrderId", r.ReservationOrderID) + populate(objectMap, "reservedResourceProperties", r.ReservedResourceProperties) + populate(objectMap, "reservedResourceType", r.ReservedResourceType) + populateTime[datetime.RFC3339](objectMap, "reviewDateTime", r.ReviewDateTime) + populate(objectMap, "term", r.Term) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ReservationOrderAliasResponseProperties. +func (r *ReservationOrderAliasResponseProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "appliedScopeProperties": + err = unpopulate(val, "AppliedScopeProperties", &r.AppliedScopeProperties) + delete(rawMsg, key) + case "appliedScopeType": + err = unpopulate(val, "AppliedScopeType", &r.AppliedScopeType) + delete(rawMsg, key) + case "billingPlan": + err = unpopulate(val, "BillingPlan", &r.BillingPlan) + delete(rawMsg, key) + case "billingScopeId": + err = unpopulate(val, "BillingScopeID", &r.BillingScopeID) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &r.DisplayName) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &r.ProvisioningState) + delete(rawMsg, key) + case "quantity": + err = unpopulate(val, "Quantity", &r.Quantity) + delete(rawMsg, key) + case "renew": + err = unpopulate(val, "Renew", &r.Renew) + delete(rawMsg, key) + case "reservationOrderId": + err = unpopulate(val, "ReservationOrderID", &r.ReservationOrderID) + delete(rawMsg, key) + case "reservedResourceProperties": + err = unpopulate(val, "ReservedResourceProperties", &r.ReservedResourceProperties) + delete(rawMsg, key) + case "reservedResourceType": + err = unpopulate(val, "ReservedResourceType", &r.ReservedResourceType) + delete(rawMsg, key) + case "reviewDateTime": + err = unpopulateTime[datetime.RFC3339](val, "ReviewDateTime", &r.ReviewDateTime) + delete(rawMsg, key) + case "term": + err = unpopulate(val, "Term", &r.Term) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ReservationOrderAliasResponsePropertiesReservedResourceProperties. +func (r ReservationOrderAliasResponsePropertiesReservedResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "instanceFlexibility", r.InstanceFlexibility) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ReservationOrderAliasResponsePropertiesReservedResourceProperties. +func (r *ReservationOrderAliasResponsePropertiesReservedResourceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "instanceFlexibility": + err = unpopulate(val, "InstanceFlexibility", &r.InstanceFlexibility) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceSKU. +func (r ResourceSKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", r.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceSKU. +func (r *ResourceSKU) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RoleAssignmentEntity. +func (r RoleAssignmentEntity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RoleAssignmentEntity. +func (r *RoleAssignmentEntity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &r.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RoleAssignmentEntityProperties. +func (r RoleAssignmentEntityProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "principalId", r.PrincipalID) + populate(objectMap, "roleDefinitionId", r.RoleDefinitionID) + populate(objectMap, "scope", r.Scope) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RoleAssignmentEntityProperties. +func (r *RoleAssignmentEntityProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "principalId": + err = unpopulate(val, "PrincipalID", &r.PrincipalID) + delete(rawMsg, key) + case "roleDefinitionId": + err = unpopulate(val, "RoleDefinitionID", &r.RoleDefinitionID) + delete(rawMsg, key) + case "scope": + err = unpopulate(val, "Scope", &r.Scope) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SKU. +func (s SKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "capacity", s.Capacity) + populate(objectMap, "family", s.Family) + populate(objectMap, "name", s.Name) + populate(objectMap, "size", s.Size) + populate(objectMap, "tier", s.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SKU. +func (s *SKU) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "capacity": + err = unpopulate(val, "Capacity", &s.Capacity) + delete(rawMsg, key) + case "family": + err = unpopulate(val, "Family", &s.Family) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "size": + err = unpopulate(val, "Size", &s.Size) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &s.Tier) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SavingsPlanModel. +func (s SavingsPlanModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "sku", s.SKU) + populate(objectMap, "systemData", s.SystemData) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SavingsPlanModel. +func (s *SavingsPlanModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &s.SKU) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &s.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SavingsPlanModelList. +func (s SavingsPlanModelList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SavingsPlanModelList. +func (s *SavingsPlanModelList) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &s.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SavingsPlanModelListResult. +func (s SavingsPlanModelListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "additionalProperties", s.AdditionalProperties) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SavingsPlanModelListResult. +func (s *SavingsPlanModelListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "additionalProperties": + err = unpopulate(val, "AdditionalProperties", &s.AdditionalProperties) + delete(rawMsg, key) + case "nextLink": + err = unpopulate(val, "NextLink", &s.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SavingsPlanModelProperties. +func (s SavingsPlanModelProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "appliedScopeProperties", s.AppliedScopeProperties) + populate(objectMap, "appliedScopeType", s.AppliedScopeType) + populateTime[datetime.RFC3339](objectMap, "benefitStartTime", s.BenefitStartTime) + populate(objectMap, "billingAccountId", s.BillingAccountID) + populate(objectMap, "billingPlan", s.BillingPlan) + populate(objectMap, "billingProfileId", s.BillingProfileID) + populate(objectMap, "billingScopeId", s.BillingScopeID) + populate(objectMap, "commitment", s.Commitment) + populate(objectMap, "customerId", s.CustomerID) + populate(objectMap, "displayName", s.DisplayName) + populate(objectMap, "displayProvisioningState", s.DisplayProvisioningState) + populateTime[datetime.RFC3339](objectMap, "effectiveDateTime", s.EffectiveDateTime) + populateTime[datetime.RFC3339](objectMap, "expiryDateTime", s.ExpiryDateTime) + populate(objectMap, "extendedStatusInfo", s.ExtendedStatusInfo) + populate(objectMap, "provisioningState", s.ProvisioningState) + populateTime[datetime.RFC3339](objectMap, "purchaseDateTime", s.PurchaseDateTime) + populate(objectMap, "renew", s.Renew) + populate(objectMap, "renewDestination", s.RenewDestination) + populate(objectMap, "renewProperties", s.RenewProperties) + populate(objectMap, "renewSource", s.RenewSource) + populate(objectMap, "term", s.Term) + populate(objectMap, "userFriendlyAppliedScopeType", s.UserFriendlyAppliedScopeType) + populate(objectMap, "utilization", s.Utilization) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SavingsPlanModelProperties. +func (s *SavingsPlanModelProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "appliedScopeProperties": + err = unpopulate(val, "AppliedScopeProperties", &s.AppliedScopeProperties) + delete(rawMsg, key) + case "appliedScopeType": + err = unpopulate(val, "AppliedScopeType", &s.AppliedScopeType) + delete(rawMsg, key) + case "benefitStartTime": + err = unpopulateTime[datetime.RFC3339](val, "BenefitStartTime", &s.BenefitStartTime) + delete(rawMsg, key) + case "billingAccountId": + err = unpopulate(val, "BillingAccountID", &s.BillingAccountID) + delete(rawMsg, key) + case "billingPlan": + err = unpopulate(val, "BillingPlan", &s.BillingPlan) + delete(rawMsg, key) + case "billingProfileId": + err = unpopulate(val, "BillingProfileID", &s.BillingProfileID) + delete(rawMsg, key) + case "billingScopeId": + err = unpopulate(val, "BillingScopeID", &s.BillingScopeID) + delete(rawMsg, key) + case "commitment": + err = unpopulate(val, "Commitment", &s.Commitment) + delete(rawMsg, key) + case "customerId": + err = unpopulate(val, "CustomerID", &s.CustomerID) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &s.DisplayName) + delete(rawMsg, key) + case "displayProvisioningState": + err = unpopulate(val, "DisplayProvisioningState", &s.DisplayProvisioningState) + delete(rawMsg, key) + case "effectiveDateTime": + err = unpopulateTime[datetime.RFC3339](val, "EffectiveDateTime", &s.EffectiveDateTime) + delete(rawMsg, key) + case "expiryDateTime": + err = unpopulateTime[datetime.RFC3339](val, "ExpiryDateTime", &s.ExpiryDateTime) + delete(rawMsg, key) + case "extendedStatusInfo": + err = unpopulate(val, "ExtendedStatusInfo", &s.ExtendedStatusInfo) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + case "purchaseDateTime": + err = unpopulateTime[datetime.RFC3339](val, "PurchaseDateTime", &s.PurchaseDateTime) + delete(rawMsg, key) + case "renew": + err = unpopulate(val, "Renew", &s.Renew) + delete(rawMsg, key) + case "renewDestination": + err = unpopulate(val, "RenewDestination", &s.RenewDestination) + delete(rawMsg, key) + case "renewProperties": + err = unpopulate(val, "RenewProperties", &s.RenewProperties) + delete(rawMsg, key) + case "renewSource": + err = unpopulate(val, "RenewSource", &s.RenewSource) + delete(rawMsg, key) + case "term": + err = unpopulate(val, "Term", &s.Term) + delete(rawMsg, key) + case "userFriendlyAppliedScopeType": + err = unpopulate(val, "UserFriendlyAppliedScopeType", &s.UserFriendlyAppliedScopeType) + delete(rawMsg, key) + case "utilization": + err = unpopulate(val, "Utilization", &s.Utilization) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SavingsPlanOrderAliasModel. +func (s SavingsPlanOrderAliasModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + populate(objectMap, "kind", s.Kind) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "sku", s.SKU) + populate(objectMap, "systemData", s.SystemData) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SavingsPlanOrderAliasModel. +func (s *SavingsPlanOrderAliasModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &s.Kind) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &s.SKU) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &s.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SavingsPlanOrderAliasProperties. +func (s SavingsPlanOrderAliasProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "appliedScopeProperties", s.AppliedScopeProperties) + populate(objectMap, "appliedScopeType", s.AppliedScopeType) + populate(objectMap, "billingPlan", s.BillingPlan) + populate(objectMap, "billingScopeId", s.BillingScopeID) + populate(objectMap, "commitment", s.Commitment) + populate(objectMap, "displayName", s.DisplayName) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "renew", s.Renew) + populate(objectMap, "savingsPlanOrderId", s.SavingsPlanOrderID) + populate(objectMap, "term", s.Term) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SavingsPlanOrderAliasProperties. +func (s *SavingsPlanOrderAliasProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "appliedScopeProperties": + err = unpopulate(val, "AppliedScopeProperties", &s.AppliedScopeProperties) + delete(rawMsg, key) + case "appliedScopeType": + err = unpopulate(val, "AppliedScopeType", &s.AppliedScopeType) + delete(rawMsg, key) + case "billingPlan": + err = unpopulate(val, "BillingPlan", &s.BillingPlan) + delete(rawMsg, key) + case "billingScopeId": + err = unpopulate(val, "BillingScopeID", &s.BillingScopeID) + delete(rawMsg, key) + case "commitment": + err = unpopulate(val, "Commitment", &s.Commitment) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &s.DisplayName) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + case "renew": + err = unpopulate(val, "Renew", &s.Renew) + delete(rawMsg, key) + case "savingsPlanOrderId": + err = unpopulate(val, "SavingsPlanOrderID", &s.SavingsPlanOrderID) + delete(rawMsg, key) + case "term": + err = unpopulate(val, "Term", &s.Term) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SavingsPlanOrderModel. +func (s SavingsPlanOrderModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "sku", s.SKU) + populate(objectMap, "systemData", s.SystemData) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SavingsPlanOrderModel. +func (s *SavingsPlanOrderModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &s.SKU) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &s.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SavingsPlanOrderModelList. +func (s SavingsPlanOrderModelList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SavingsPlanOrderModelList. +func (s *SavingsPlanOrderModelList) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &s.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SavingsPlanOrderModelProperties. +func (s SavingsPlanOrderModelProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "benefitStartTime", s.BenefitStartTime) + populate(objectMap, "billingAccountId", s.BillingAccountID) + populate(objectMap, "billingPlan", s.BillingPlan) + populate(objectMap, "billingProfileId", s.BillingProfileID) + populate(objectMap, "billingScopeId", s.BillingScopeID) + populate(objectMap, "customerId", s.CustomerID) + populate(objectMap, "displayName", s.DisplayName) + populateTime[datetime.RFC3339](objectMap, "expiryDateTime", s.ExpiryDateTime) + populate(objectMap, "extendedStatusInfo", s.ExtendedStatusInfo) + populate(objectMap, "planInformation", s.PlanInformation) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "savingsPlans", s.SavingsPlans) + populate(objectMap, "term", s.Term) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SavingsPlanOrderModelProperties. +func (s *SavingsPlanOrderModelProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "benefitStartTime": + err = unpopulateTime[datetime.RFC3339](val, "BenefitStartTime", &s.BenefitStartTime) + delete(rawMsg, key) + case "billingAccountId": + err = unpopulate(val, "BillingAccountID", &s.BillingAccountID) + delete(rawMsg, key) + case "billingPlan": + err = unpopulate(val, "BillingPlan", &s.BillingPlan) + delete(rawMsg, key) + case "billingProfileId": + err = unpopulate(val, "BillingProfileID", &s.BillingProfileID) + delete(rawMsg, key) + case "billingScopeId": + err = unpopulate(val, "BillingScopeID", &s.BillingScopeID) + delete(rawMsg, key) + case "customerId": + err = unpopulate(val, "CustomerID", &s.CustomerID) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &s.DisplayName) + delete(rawMsg, key) + case "expiryDateTime": + err = unpopulateTime[datetime.RFC3339](val, "ExpiryDateTime", &s.ExpiryDateTime) + delete(rawMsg, key) + case "extendedStatusInfo": + err = unpopulate(val, "ExtendedStatusInfo", &s.ExtendedStatusInfo) + delete(rawMsg, key) + case "planInformation": + err = unpopulate(val, "PlanInformation", &s.PlanInformation) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + case "savingsPlans": + err = unpopulate(val, "SavingsPlans", &s.SavingsPlans) + delete(rawMsg, key) + case "term": + err = unpopulate(val, "Term", &s.Term) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SavingsPlanSummary. +func (s SavingsPlanSummary) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", s.Name) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SavingsPlanSummary. +func (s *SavingsPlanSummary) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SavingsPlanSummaryCount. +func (s SavingsPlanSummaryCount) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "cancelledCount", s.CancelledCount) + populate(objectMap, "expiredCount", s.ExpiredCount) + populate(objectMap, "expiringCount", s.ExpiringCount) + populate(objectMap, "failedCount", s.FailedCount) + populate(objectMap, "noBenefitCount", s.NoBenefitCount) + populate(objectMap, "pendingCount", s.PendingCount) + populate(objectMap, "processingCount", s.ProcessingCount) + populate(objectMap, "succeededCount", s.SucceededCount) + populate(objectMap, "warningCount", s.WarningCount) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SavingsPlanSummaryCount. +func (s *SavingsPlanSummaryCount) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "cancelledCount": + err = unpopulate(val, "CancelledCount", &s.CancelledCount) + delete(rawMsg, key) + case "expiredCount": + err = unpopulate(val, "ExpiredCount", &s.ExpiredCount) + delete(rawMsg, key) + case "expiringCount": + err = unpopulate(val, "ExpiringCount", &s.ExpiringCount) + delete(rawMsg, key) + case "failedCount": + err = unpopulate(val, "FailedCount", &s.FailedCount) + delete(rawMsg, key) + case "noBenefitCount": + err = unpopulate(val, "NoBenefitCount", &s.NoBenefitCount) + delete(rawMsg, key) + case "pendingCount": + err = unpopulate(val, "PendingCount", &s.PendingCount) + delete(rawMsg, key) + case "processingCount": + err = unpopulate(val, "ProcessingCount", &s.ProcessingCount) + delete(rawMsg, key) + case "succeededCount": + err = unpopulate(val, "SucceededCount", &s.SucceededCount) + delete(rawMsg, key) + case "warningCount": + err = unpopulate(val, "WarningCount", &s.WarningCount) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SavingsPlanUpdateRequest. +func (s SavingsPlanUpdateRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", s.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SavingsPlanUpdateRequest. +func (s *SavingsPlanUpdateRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SavingsPlanUpdateRequestProperties. +func (s SavingsPlanUpdateRequestProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "appliedScopeProperties", s.AppliedScopeProperties) + populate(objectMap, "appliedScopeType", s.AppliedScopeType) + populate(objectMap, "displayName", s.DisplayName) + populate(objectMap, "renew", s.Renew) + populate(objectMap, "renewProperties", s.RenewProperties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SavingsPlanUpdateRequestProperties. +func (s *SavingsPlanUpdateRequestProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "appliedScopeProperties": + err = unpopulate(val, "AppliedScopeProperties", &s.AppliedScopeProperties) + delete(rawMsg, key) + case "appliedScopeType": + err = unpopulate(val, "AppliedScopeType", &s.AppliedScopeType) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &s.DisplayName) + delete(rawMsg, key) + case "renew": + err = unpopulate(val, "Renew", &s.Renew) + delete(rawMsg, key) + case "renewProperties": + err = unpopulate(val, "RenewProperties", &s.RenewProperties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SavingsPlanUpdateValidateRequest. +func (s SavingsPlanUpdateValidateRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "benefits", s.Benefits) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SavingsPlanUpdateValidateRequest. +func (s *SavingsPlanUpdateValidateRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "benefits": + err = unpopulate(val, "Benefits", &s.Benefits) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SavingsPlanValidResponseProperty. +func (s SavingsPlanValidResponseProperty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "reason", s.Reason) + populate(objectMap, "reasonCode", s.ReasonCode) + populate(objectMap, "valid", s.Valid) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SavingsPlanValidResponseProperty. +func (s *SavingsPlanValidResponseProperty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "reason": + err = unpopulate(val, "Reason", &s.Reason) + delete(rawMsg, key) + case "reasonCode": + err = unpopulate(val, "ReasonCode", &s.ReasonCode) + delete(rawMsg, key) + case "valid": + err = unpopulate(val, "Valid", &s.Valid) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SavingsPlanValidateModel. +func (s SavingsPlanValidateModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["benefitType"] = BenefitTypeSavingsPlan + populate(objectMap, "id", s.ID) + populate(objectMap, "kind", s.Kind) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "sku", s.SKU) + populate(objectMap, "systemData", s.SystemData) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SavingsPlanValidateModel. +func (s *SavingsPlanValidateModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "benefitType": + err = unpopulate(val, "BenefitType", &s.BenefitType) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &s.Kind) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &s.SKU) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &s.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SavingsPlanValidateResponse. +func (s SavingsPlanValidateResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "benefits", s.Benefits) + populate(objectMap, "nextLink", s.NextLink) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SavingsPlanValidateResponse. +func (s *SavingsPlanValidateResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "benefits": + err = unpopulate(val, "Benefits", &s.Benefits) + delete(rawMsg, key) + case "nextLink": + err = unpopulate(val, "NextLink", &s.NextLink) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SellerResourceListRequest. +func (s SellerResourceListRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", s.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SellerResourceListRequest. +func (s *SellerResourceListRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SellerResourceListRequestProperties. +func (s SellerResourceListRequestProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "billingAccountResourceId", s.BillingAccountResourceID) + populate(objectMap, "contributors", s.Contributors) + populate(objectMap, "$filter", s.Filter) + populate(objectMap, "milestones", s.Milestones) + populate(objectMap, "primaryResourceId", s.PrimaryResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SellerResourceListRequestProperties. +func (s *SellerResourceListRequestProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "billingAccountResourceId": + err = unpopulate(val, "BillingAccountResourceID", &s.BillingAccountResourceID) + delete(rawMsg, key) + case "contributors": + err = unpopulate(val, "Contributors", &s.Contributors) + delete(rawMsg, key) + case "$filter": + err = unpopulate(val, "Filter", &s.Filter) + delete(rawMsg, key) + case "milestones": + err = unpopulate(val, "Milestones", &s.Milestones) + delete(rawMsg, key) + case "primaryResourceId": + err = unpopulate(val, "PrimaryResourceID", &s.PrimaryResourceID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ServiceManagedIdentity. +func (s ServiceManagedIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "principalId", s.PrincipalID) + populate(objectMap, "tenantId", s.TenantID) + populate(objectMap, "type", s.Type) + populate(objectMap, "userAssignedIdentities", s.UserAssignedIdentities) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceManagedIdentity. +func (s *ServiceManagedIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "principalId": + err = unpopulate(val, "PrincipalID", &s.PrincipalID) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &s.TenantID) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + case "userAssignedIdentities": + err = unpopulate(val, "UserAssignedIdentities", &s.UserAssignedIdentities) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Shortfall. +func (s Shortfall) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "balanceVersion", s.BalanceVersion) + populate(objectMap, "charge", s.Charge) + populateTime[datetime.RFC3339](objectMap, "endAt", s.EndAt) + populate(objectMap, "productCode", s.ProductCode) + populate(objectMap, "resourceId", s.ResourceID) + populateTime[datetime.RFC3339](objectMap, "startAt", s.StartAt) + populate(objectMap, "systemId", s.SystemID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Shortfall. +func (s *Shortfall) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "balanceVersion": + err = unpopulate(val, "BalanceVersion", &s.BalanceVersion) + delete(rawMsg, key) + case "charge": + err = unpopulate(val, "Charge", &s.Charge) + delete(rawMsg, key) + case "endAt": + err = unpopulateTime[datetime.RFC3339](val, "EndAt", &s.EndAt) + delete(rawMsg, key) + case "productCode": + err = unpopulate(val, "ProductCode", &s.ProductCode) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &s.ResourceID) + delete(rawMsg, key) + case "startAt": + err = unpopulateTime[datetime.RFC3339](val, "StartAt", &s.StartAt) + delete(rawMsg, key) + case "systemId": + err = unpopulate(val, "SystemID", &s.SystemID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateTime[datetime.RFC3339](objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateTime[datetime.RFC3339](val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateTime[datetime.RFC3339](val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserAssignedIdentity. +func (u UserAssignedIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clientId", u.ClientID) + populate(objectMap, "principalId", u.PrincipalID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserAssignedIdentity. +func (u *UserAssignedIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "clientId": + err = unpopulate(val, "ClientID", &u.ClientID) + delete(rawMsg, key) + case "principalId": + err = unpopulate(val, "PrincipalID", &u.PrincipalID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Utilization. +func (u Utilization) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "aggregates", u.Aggregates) + populate(objectMap, "trend", u.Trend) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Utilization. +func (u *Utilization) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "aggregates": + err = unpopulate(val, "Aggregates", &u.Aggregates) + delete(rawMsg, key) + case "trend": + err = unpopulate(val, "Trend", &u.Trend) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UtilizationAggregates. +func (u UtilizationAggregates) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "grain", u.Grain) + populate(objectMap, "grainUnit", u.GrainUnit) + populate(objectMap, "value", u.Value) + populate(objectMap, "valueUnit", u.ValueUnit) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UtilizationAggregates. +func (u *UtilizationAggregates) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "grain": + err = unpopulate(val, "Grain", &u.Grain) + delete(rawMsg, key) + case "grainUnit": + err = unpopulate(val, "GrainUnit", &u.GrainUnit) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &u.Value) + delete(rawMsg, key) + case "valueUnit": + err = unpopulate(val, "ValueUnit", &u.ValueUnit) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/local/armbillingbenefits/zz_operations_client.go b/test/local/armbillingbenefits/zz_operations_client.go new file mode 100644 index 000000000000..a025a7072d3a --- /dev/null +++ b/test/local/armbillingbenefits/zz_operations_client.go @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armbillingbenefits + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +// +// Generated from API version 2025-12-01-preview +type OperationsClient struct { + internal *arm.Client +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*OperationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OperationsClient{ + internal: cl, + } + return client, nil +} + +// NewListPager - List the operations for the provider +// - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ + More: func(page OperationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OperationsClientListResponse) (OperationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OperationsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return OperationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, _ *OperationsClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.BillingBenefits/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsClientListResponse, error) { + result := OperationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armbillingbenefits/zz_options.go b/test/local/armbillingbenefits/zz_options.go new file mode 100644 index 000000000000..5daaa7eaa5ba --- /dev/null +++ b/test/local/armbillingbenefits/zz_options.go @@ -0,0 +1,401 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armbillingbenefits + +// ApplicableMaccsClientListOptions contains the optional parameters for the ApplicableMaccsClient.NewListPager method. +type ApplicableMaccsClientListOptions struct { + // placeholder for future optional parameters +} + +// ConditionalCreditContributorsClientGetFromPrimaryOptions contains the optional parameters for the ConditionalCreditContributorsClient.GetFromPrimary +// method. +type ConditionalCreditContributorsClientGetFromPrimaryOptions struct { + // placeholder for future optional parameters +} + +// ConditionalCreditContributorsClientListFromApplicableConditionalCreditOptions contains the optional parameters for the +// ConditionalCreditContributorsClient.NewListFromApplicableConditionalCreditPager method. +type ConditionalCreditContributorsClientListFromApplicableConditionalCreditOptions struct { + // placeholder for future optional parameters +} + +// ConditionalCreditContributorsClientListFromPrimaryOptions contains the optional parameters for the ConditionalCreditContributorsClient.NewListFromPrimaryPager +// method. +type ConditionalCreditContributorsClientListFromPrimaryOptions struct { + // placeholder for future optional parameters +} + +// ConditionalCreditsClientBeginCancelOptions contains the optional parameters for the ConditionalCreditsClient.BeginCancel +// method. +type ConditionalCreditsClientBeginCancelOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ConditionalCreditsClientBeginCreateOrUpdateOptions contains the optional parameters for the ConditionalCreditsClient.BeginCreateOrUpdate +// method. +type ConditionalCreditsClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ConditionalCreditsClientBeginDeleteOptions contains the optional parameters for the ConditionalCreditsClient.BeginDelete +// method. +type ConditionalCreditsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ConditionalCreditsClientBeginUpdateOptions contains the optional parameters for the ConditionalCreditsClient.BeginUpdate +// method. +type ConditionalCreditsClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ConditionalCreditsClientGetOptions contains the optional parameters for the ConditionalCreditsClient.Get method. +type ConditionalCreditsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ConditionalCreditsClientListByResourceGroupOptions contains the optional parameters for the ConditionalCreditsClient.NewListByResourceGroupPager +// method. +type ConditionalCreditsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// ConditionalCreditsClientListBySubscriptionOptions contains the optional parameters for the ConditionalCreditsClient.NewListBySubscriptionPager +// method. +type ConditionalCreditsClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// ConditionalCreditsClientScopeListOptions contains the optional parameters for the ConditionalCreditsClient.NewScopeListPager +// method. +type ConditionalCreditsClientScopeListOptions struct { + // placeholder for future optional parameters +} + +// ContributorsClientGetFromPrimaryOptions contains the optional parameters for the ContributorsClient.GetFromPrimary method. +type ContributorsClientGetFromPrimaryOptions struct { + // placeholder for future optional parameters +} + +// ContributorsClientListFromApplicableMaccOptions contains the optional parameters for the ContributorsClient.NewListFromApplicableMaccPager +// method. +type ContributorsClientListFromApplicableMaccOptions struct { + // placeholder for future optional parameters +} + +// ContributorsClientListFromPrimaryOptions contains the optional parameters for the ContributorsClient.NewListFromPrimaryPager +// method. +type ContributorsClientListFromPrimaryOptions struct { + // placeholder for future optional parameters +} + +// CreditsClientBeginCancelOptions contains the optional parameters for the CreditsClient.BeginCancel method. +type CreditsClientBeginCancelOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CreditsClientBeginCreateOptions contains the optional parameters for the CreditsClient.BeginCreate method. +type CreditsClientBeginCreateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CreditsClientBeginDeleteOptions contains the optional parameters for the CreditsClient.BeginDelete method. +type CreditsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CreditsClientBeginUpdateOptions contains the optional parameters for the CreditsClient.BeginUpdate method. +type CreditsClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CreditsClientGetOptions contains the optional parameters for the CreditsClient.Get method. +type CreditsClientGetOptions struct { + // placeholder for future optional parameters +} + +// CreditsClientListApplicableOptions contains the optional parameters for the CreditsClient.NewListApplicablePager method. +type CreditsClientListApplicableOptions struct { + // placeholder for future optional parameters +} + +// CreditsClientListByResourceGroupOptions contains the optional parameters for the CreditsClient.NewListByResourceGroupPager +// method. +type CreditsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// CreditsClientListBySubscriptionOptions contains the optional parameters for the CreditsClient.NewListBySubscriptionPager +// method. +type CreditsClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// DiscountClientBeginUpdateOptions contains the optional parameters for the DiscountClient.BeginUpdate method. +type DiscountClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// DiscountClientGetOptions contains the optional parameters for the DiscountClient.Get method. +type DiscountClientGetOptions struct { + // placeholder for future optional parameters +} + +// DiscountsClientBeginCancelOptions contains the optional parameters for the DiscountsClient.BeginCancel method. +type DiscountsClientBeginCancelOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// DiscountsClientBeginCreateOptions contains the optional parameters for the DiscountsClient.BeginCreate method. +type DiscountsClientBeginCreateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// DiscountsClientBeginDeleteOptions contains the optional parameters for the DiscountsClient.BeginDelete method. +type DiscountsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// DiscountsClientResourceGroupListOptions contains the optional parameters for the DiscountsClient.NewResourceGroupListPager +// method. +type DiscountsClientResourceGroupListOptions struct { + // placeholder for future optional parameters +} + +// DiscountsClientScopeListOptions contains the optional parameters for the DiscountsClient.NewScopeListPager method. +type DiscountsClientScopeListOptions struct { + // placeholder for future optional parameters +} + +// DiscountsClientSubscriptionListOptions contains the optional parameters for the DiscountsClient.NewSubscriptionListPager +// method. +type DiscountsClientSubscriptionListOptions struct { + // placeholder for future optional parameters +} + +// FreeServicesClientBeginCreateOptions contains the optional parameters for the FreeServicesClient.BeginCreate method. +type FreeServicesClientBeginCreateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// FreeServicesClientBeginDeleteOptions contains the optional parameters for the FreeServicesClient.BeginDelete method. +type FreeServicesClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// FreeServicesClientBeginUpdateOptions contains the optional parameters for the FreeServicesClient.BeginUpdate method. +type FreeServicesClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// FreeServicesClientGetOptions contains the optional parameters for the FreeServicesClient.Get method. +type FreeServicesClientGetOptions struct { + // placeholder for future optional parameters +} + +// FreeServicesClientListByResourceGroupOptions contains the optional parameters for the FreeServicesClient.NewListByResourceGroupPager +// method. +type FreeServicesClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// FreeServicesClientListBySubscriptionOptions contains the optional parameters for the FreeServicesClient.NewListBySubscriptionPager +// method. +type FreeServicesClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// MaccsClientBeginCancelOptions contains the optional parameters for the MaccsClient.BeginCancel method. +type MaccsClientBeginCancelOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// MaccsClientBeginChargeShortfallOptions contains the optional parameters for the MaccsClient.BeginChargeShortfall method. +type MaccsClientBeginChargeShortfallOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// MaccsClientBeginCreateOptions contains the optional parameters for the MaccsClient.BeginCreate method. +type MaccsClientBeginCreateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// MaccsClientBeginDeleteOptions contains the optional parameters for the MaccsClient.BeginDelete method. +type MaccsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// MaccsClientBeginUpdateOptions contains the optional parameters for the MaccsClient.BeginUpdate method. +type MaccsClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// MaccsClientBeginWriteOffOptions contains the optional parameters for the MaccsClient.BeginWriteOff method. +type MaccsClientBeginWriteOffOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// MaccsClientGetOptions contains the optional parameters for the MaccsClient.Get method. +type MaccsClientGetOptions struct { + // placeholder for future optional parameters +} + +// MaccsClientListByResourceGroupOptions contains the optional parameters for the MaccsClient.NewListByResourceGroupPager +// method. +type MaccsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// MaccsClientListBySubscriptionOptions contains the optional parameters for the MaccsClient.NewListBySubscriptionPager method. +type MaccsClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} + +// RPClientValidateOptions contains the optional parameters for the RPClient.Validate method. +type RPClientValidateOptions struct { + // placeholder for future optional parameters +} + +// ReservationOrderAliasClientBeginCreateOptions contains the optional parameters for the ReservationOrderAliasClient.BeginCreate +// method. +type ReservationOrderAliasClientBeginCreateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ReservationOrderAliasClientGetOptions contains the optional parameters for the ReservationOrderAliasClient.Get method. +type ReservationOrderAliasClientGetOptions struct { + // placeholder for future optional parameters +} + +// SavingsPlanClientBeginUpdateOptions contains the optional parameters for the SavingsPlanClient.BeginUpdate method. +type SavingsPlanClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// SavingsPlanClientGetOptions contains the optional parameters for the SavingsPlanClient.Get method. +type SavingsPlanClientGetOptions struct { + // May be used to expand the detail information of some properties. + Expand *string +} + +// SavingsPlanClientListAllOptions contains the optional parameters for the SavingsPlanClient.NewListAllPager method. +type SavingsPlanClientListAllOptions struct { + // May be used to filter by reservation properties. The filter supports 'eq', 'or', and 'and'. It does not currently support + // 'ne', 'gt', 'le', 'ge', or 'not'. Reservation properties include sku/name, properties/{appliedScopeType, archived, displayName, + // displayProvisioningState, effectiveDateTime, expiryDate, provisioningState, quantity, renew, reservedResourceType, term, + // userFriendlyAppliedScopeType, userFriendlyRenewState} + Filter *string + + // May be used to sort order by reservation properties. + Orderby *string + + // To indicate whether to refresh the roll up counts of the savings plans group by provisioning states + RefreshSummary *string + + // The selected provisioning state + SelectedState *string + + // The number of savings plans to skip from the list before returning results + Skiptoken *float32 + + // To number of savings plans to return + Take *float32 +} + +// SavingsPlanClientListOptions contains the optional parameters for the SavingsPlanClient.NewListPager method. +type SavingsPlanClientListOptions struct { + // placeholder for future optional parameters +} + +// SavingsPlanClientValidateUpdateOptions contains the optional parameters for the SavingsPlanClient.ValidateUpdate method. +type SavingsPlanClientValidateUpdateOptions struct { + // placeholder for future optional parameters +} + +// SavingsPlanOrderAliasClientBeginCreateOptions contains the optional parameters for the SavingsPlanOrderAliasClient.BeginCreate +// method. +type SavingsPlanOrderAliasClientBeginCreateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// SavingsPlanOrderAliasClientGetOptions contains the optional parameters for the SavingsPlanOrderAliasClient.Get method. +type SavingsPlanOrderAliasClientGetOptions struct { + // placeholder for future optional parameters +} + +// SavingsPlanOrderClientElevateOptions contains the optional parameters for the SavingsPlanOrderClient.Elevate method. +type SavingsPlanOrderClientElevateOptions struct { + // placeholder for future optional parameters +} + +// SavingsPlanOrderClientGetOptions contains the optional parameters for the SavingsPlanOrderClient.Get method. +type SavingsPlanOrderClientGetOptions struct { + // May be used to expand the detail information of some properties. + Expand *string +} + +// SavingsPlanOrderClientListOptions contains the optional parameters for the SavingsPlanOrderClient.NewListPager method. +type SavingsPlanOrderClientListOptions struct { + // placeholder for future optional parameters +} + +// SellerResourceClientListOptions contains the optional parameters for the SellerResourceClient.List method. +type SellerResourceClientListOptions struct { + // placeholder for future optional parameters +} + +// SourcesClientCreateOptions contains the optional parameters for the SourcesClient.Create method. +type SourcesClientCreateOptions struct { + // placeholder for future optional parameters +} + +// SourcesClientDeleteOptions contains the optional parameters for the SourcesClient.Delete method. +type SourcesClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// SourcesClientGetOptions contains the optional parameters for the SourcesClient.Get method. +type SourcesClientGetOptions struct { + // placeholder for future optional parameters +} + +// SourcesClientListByCreditOptions contains the optional parameters for the SourcesClient.NewListByCreditPager method. +type SourcesClientListByCreditOptions struct { + // placeholder for future optional parameters +} + +// SourcesClientUpdateOptions contains the optional parameters for the SourcesClient.Update method. +type SourcesClientUpdateOptions struct { + // placeholder for future optional parameters +} diff --git a/test/local/armbillingbenefits/zz_polymorphic_helpers.go b/test/local/armbillingbenefits/zz_polymorphic_helpers.go new file mode 100644 index 000000000000..1dc8342c6e5e --- /dev/null +++ b/test/local/armbillingbenefits/zz_polymorphic_helpers.go @@ -0,0 +1,128 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armbillingbenefits + +import "encoding/json" + +func unmarshalBenefitValidateModelClassification(rawMsg json.RawMessage) (BenefitValidateModelClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b BenefitValidateModelClassification + switch m["benefitType"] { + case string(BenefitTypeConditionalCredits): + b = &ConditionalCreditsValidateModel{} + case string(BenefitTypeCredits): + b = &CreditsValidateModel{} + case string(BenefitTypeMACC): + b = &MaccValidateModel{} + case string(BenefitTypeSavingsPlan): + b = &SavingsPlanValidateModel{} + default: + b = &BenefitValidateModel{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} + +func unmarshalBenefitValidateModelClassificationArray(rawMsg json.RawMessage) ([]BenefitValidateModelClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]BenefitValidateModelClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalBenefitValidateModelClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalConditionalCreditPropertiesClassification(rawMsg json.RawMessage) (ConditionalCreditPropertiesClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b ConditionalCreditPropertiesClassification + switch m["entityType"] { + case string(ConditionalCreditEntityTypeContributor): + b = &ContributorConditionalCreditProperties{} + case string(ConditionalCreditEntityTypePrimary): + b = &PrimaryConditionalCreditProperties{} + default: + b = &ConditionalCreditProperties{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} + +func unmarshalDiscountPropertiesClassification(rawMsg json.RawMessage) (DiscountPropertiesClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b DiscountPropertiesClassification + switch m["entityType"] { + case string(DiscountEntityTypeAffiliate): + b = &EntityTypeAffiliateDiscount{} + case string(DiscountEntityTypePrimary): + b = &EntityTypePrimaryDiscount{} + default: + b = &DiscountProperties{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} + +func unmarshalDiscountTypePropertiesClassification(rawMsg json.RawMessage) (DiscountTypePropertiesClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b DiscountTypePropertiesClassification + switch m["discountType"] { + case string(DiscountTypeEnumCustomPrice): + b = &DiscountTypeCustomPrice{} + case string(DiscountTypeEnumCustomPriceMultiCurrency): + b = &DiscountTypeCustomPriceMultiCurrency{} + case string(DiscountTypeEnumProduct): + b = &DiscountTypeProduct{} + case string(DiscountTypeEnumProductFamily): + b = &DiscountTypeProductFamily{} + case string(DiscountTypeEnumSKU): + b = &DiscountTypeProductSKU{} + default: + b = &DiscountTypeProperties{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} diff --git a/test/local/armbillingbenefits/zz_reservationorderalias_client.go b/test/local/armbillingbenefits/zz_reservationorderalias_client.go new file mode 100644 index 000000000000..dc9623a6f5e1 --- /dev/null +++ b/test/local/armbillingbenefits/zz_reservationorderalias_client.go @@ -0,0 +1,161 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armbillingbenefits + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ReservationOrderAliasClient contains the methods for the ReservationOrderAlias group. +// Don't use this type directly, use NewReservationOrderAliasClient() instead. +// +// Generated from API version 2025-12-01-preview +type ReservationOrderAliasClient struct { + internal *arm.Client +} + +// NewReservationOrderAliasClient creates a new instance of ReservationOrderAliasClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewReservationOrderAliasClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*ReservationOrderAliasClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ReservationOrderAliasClient{ + internal: cl, + } + return client, nil +} + +// BeginCreate - Create a reservation order alias. +// If the operation fails it returns an *azcore.ResponseError type. +// - reservationOrderAliasName - Name of the reservation order alias +// - body - Request body for creating a reservation order alias +// - options - ReservationOrderAliasClientBeginCreateOptions contains the optional parameters for the ReservationOrderAliasClient.BeginCreate +// method. +func (client *ReservationOrderAliasClient) BeginCreate(ctx context.Context, reservationOrderAliasName string, body ReservationOrderAliasRequest, options *ReservationOrderAliasClientBeginCreateOptions) (*runtime.Poller[ReservationOrderAliasClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, reservationOrderAliasName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ReservationOrderAliasClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ReservationOrderAliasClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Create a reservation order alias. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ReservationOrderAliasClient) create(ctx context.Context, reservationOrderAliasName string, body ReservationOrderAliasRequest, options *ReservationOrderAliasClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "ReservationOrderAliasClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, reservationOrderAliasName, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *ReservationOrderAliasClient) createCreateRequest(ctx context.Context, reservationOrderAliasName string, body ReservationOrderAliasRequest, _ *ReservationOrderAliasClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.BillingBenefits/reservationOrderAliases/{reservationOrderAliasName}" + if reservationOrderAliasName == "" { + return nil, errors.New("parameter reservationOrderAliasName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{reservationOrderAliasName}", url.PathEscape(reservationOrderAliasName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// Get - Get a reservation order alias. +// If the operation fails it returns an *azcore.ResponseError type. +// - reservationOrderAliasName - Name of the reservation order alias +// - options - ReservationOrderAliasClientGetOptions contains the optional parameters for the ReservationOrderAliasClient.Get +// method. +func (client *ReservationOrderAliasClient) Get(ctx context.Context, reservationOrderAliasName string, options *ReservationOrderAliasClientGetOptions) (ReservationOrderAliasClientGetResponse, error) { + var err error + const operationName = "ReservationOrderAliasClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, reservationOrderAliasName, options) + if err != nil { + return ReservationOrderAliasClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ReservationOrderAliasClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ReservationOrderAliasClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ReservationOrderAliasClient) getCreateRequest(ctx context.Context, reservationOrderAliasName string, _ *ReservationOrderAliasClientGetOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.BillingBenefits/reservationOrderAliases/{reservationOrderAliasName}" + if reservationOrderAliasName == "" { + return nil, errors.New("parameter reservationOrderAliasName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{reservationOrderAliasName}", url.PathEscape(reservationOrderAliasName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ReservationOrderAliasClient) getHandleResponse(resp *http.Response) (ReservationOrderAliasClientGetResponse, error) { + result := ReservationOrderAliasClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ReservationOrderAliasResponse); err != nil { + return ReservationOrderAliasClientGetResponse{}, err + } + return result, nil +} diff --git a/test/local/armbillingbenefits/zz_responses.go b/test/local/armbillingbenefits/zz_responses.go new file mode 100644 index 000000000000..4a546fcd6d69 --- /dev/null +++ b/test/local/armbillingbenefits/zz_responses.go @@ -0,0 +1,393 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armbillingbenefits + +// ApplicableMaccsClientListResponse contains the response from method ApplicableMaccsClient.NewListPager. +type ApplicableMaccsClientListResponse struct { + // Applicable MACC list + ApplicableMaccList +} + +// ConditionalCreditContributorsClientGetFromPrimaryResponse contains the response from method ConditionalCreditContributorsClient.GetFromPrimary. +type ConditionalCreditContributorsClientGetFromPrimaryResponse struct { + // Conditional credit contributor + ConditionalCreditContributor +} + +// ConditionalCreditContributorsClientListFromApplicableConditionalCreditResponse contains the response from method ConditionalCreditContributorsClient.NewListFromApplicableConditionalCreditPager. +type ConditionalCreditContributorsClientListFromApplicableConditionalCreditResponse struct { + // Conditional credit contributor list + ConditionalCreditContributorList +} + +// ConditionalCreditContributorsClientListFromPrimaryResponse contains the response from method ConditionalCreditContributorsClient.NewListFromPrimaryPager. +type ConditionalCreditContributorsClientListFromPrimaryResponse struct { + // Conditional credit contributor list + ConditionalCreditContributorList +} + +// ConditionalCreditsClientCancelResponse contains the response from method ConditionalCreditsClient.BeginCancel. +type ConditionalCreditsClientCancelResponse struct { + // Resource definition for Conditional Credits. + ConditionalCredit +} + +// ConditionalCreditsClientCreateOrUpdateResponse contains the response from method ConditionalCreditsClient.BeginCreateOrUpdate. +type ConditionalCreditsClientCreateOrUpdateResponse struct { + // Resource definition for Conditional Credits. + ConditionalCredit +} + +// ConditionalCreditsClientDeleteResponse contains the response from method ConditionalCreditsClient.BeginDelete. +type ConditionalCreditsClientDeleteResponse struct { + // placeholder for future response values +} + +// ConditionalCreditsClientGetResponse contains the response from method ConditionalCreditsClient.Get. +type ConditionalCreditsClientGetResponse struct { + // Resource definition for Conditional Credits. + ConditionalCredit +} + +// ConditionalCreditsClientListByResourceGroupResponse contains the response from method ConditionalCreditsClient.NewListByResourceGroupPager. +type ConditionalCreditsClientListByResourceGroupResponse struct { + // List of applicable conditional credits + ConditionalCreditList +} + +// ConditionalCreditsClientListBySubscriptionResponse contains the response from method ConditionalCreditsClient.NewListBySubscriptionPager. +type ConditionalCreditsClientListBySubscriptionResponse struct { + // List of applicable conditional credits + ConditionalCreditList +} + +// ConditionalCreditsClientScopeListResponse contains the response from method ConditionalCreditsClient.NewScopeListPager. +type ConditionalCreditsClientScopeListResponse struct { + // List of applicable conditional credits + ConditionalCreditList +} + +// ConditionalCreditsClientUpdateResponse contains the response from method ConditionalCreditsClient.BeginUpdate. +type ConditionalCreditsClientUpdateResponse struct { + // Resource definition for Conditional Credits. + ConditionalCredit +} + +// ContributorsClientGetFromPrimaryResponse contains the response from method ContributorsClient.GetFromPrimary. +type ContributorsClientGetFromPrimaryResponse struct { + // MACC contributor + Contributor +} + +// ContributorsClientListFromApplicableMaccResponse contains the response from method ContributorsClient.NewListFromApplicableMaccPager. +type ContributorsClientListFromApplicableMaccResponse struct { + // Contributor list + ContributorList +} + +// ContributorsClientListFromPrimaryResponse contains the response from method ContributorsClient.NewListFromPrimaryPager. +type ContributorsClientListFromPrimaryResponse struct { + // Contributor list + ContributorList +} + +// CreditsClientCancelResponse contains the response from method CreditsClient.BeginCancel. +type CreditsClientCancelResponse struct { + // Credit resource definition + Credit +} + +// CreditsClientCreateResponse contains the response from method CreditsClient.BeginCreate. +type CreditsClientCreateResponse struct { + // Credit resource definition + Credit +} + +// CreditsClientDeleteResponse contains the response from method CreditsClient.BeginDelete. +type CreditsClientDeleteResponse struct { + // placeholder for future response values +} + +// CreditsClientGetResponse contains the response from method CreditsClient.Get. +type CreditsClientGetResponse struct { + // Credit resource definition + Credit +} + +// CreditsClientListApplicableResponse contains the response from method CreditsClient.NewListApplicablePager. +type CreditsClientListApplicableResponse struct { + // List of credits + CreditsList +} + +// CreditsClientListByResourceGroupResponse contains the response from method CreditsClient.NewListByResourceGroupPager. +type CreditsClientListByResourceGroupResponse struct { + // List of credits + CreditsList +} + +// CreditsClientListBySubscriptionResponse contains the response from method CreditsClient.NewListBySubscriptionPager. +type CreditsClientListBySubscriptionResponse struct { + // List of credits + CreditsList +} + +// CreditsClientUpdateResponse contains the response from method CreditsClient.BeginUpdate. +type CreditsClientUpdateResponse struct { + // Credit resource definition + Credit +} + +// DiscountClientGetResponse contains the response from method DiscountClient.Get. +type DiscountClientGetResponse struct { + // Resource definition for Discounts. + Discount +} + +// DiscountClientUpdateResponse contains the response from method DiscountClient.BeginUpdate. +type DiscountClientUpdateResponse struct { + // Resource definition for Discounts. + Discount +} + +// DiscountsClientCancelResponse contains the response from method DiscountsClient.BeginCancel. +type DiscountsClientCancelResponse struct { + // Resource definition for Discounts. + Discount +} + +// DiscountsClientCreateResponse contains the response from method DiscountsClient.BeginCreate. +type DiscountsClientCreateResponse struct { + // Resource definition for Discounts. + Discount +} + +// DiscountsClientDeleteResponse contains the response from method DiscountsClient.BeginDelete. +type DiscountsClientDeleteResponse struct { + // placeholder for future response values +} + +// DiscountsClientResourceGroupListResponse contains the response from method DiscountsClient.NewResourceGroupListPager. +type DiscountsClientResourceGroupListResponse struct { + // Discount list + DiscountList +} + +// DiscountsClientScopeListResponse contains the response from method DiscountsClient.NewScopeListPager. +type DiscountsClientScopeListResponse struct { + // Discount list + DiscountList +} + +// DiscountsClientSubscriptionListResponse contains the response from method DiscountsClient.NewSubscriptionListPager. +type DiscountsClientSubscriptionListResponse struct { + // Discount list + DiscountList +} + +// FreeServicesClientCreateResponse contains the response from method FreeServicesClient.BeginCreate. +type FreeServicesClientCreateResponse struct { + // Free Services resource definition + FreeServices +} + +// FreeServicesClientDeleteResponse contains the response from method FreeServicesClient.BeginDelete. +type FreeServicesClientDeleteResponse struct { + // placeholder for future response values +} + +// FreeServicesClientGetResponse contains the response from method FreeServicesClient.Get. +type FreeServicesClientGetResponse struct { + // Free Services resource definition + FreeServices +} + +// FreeServicesClientListByResourceGroupResponse contains the response from method FreeServicesClient.NewListByResourceGroupPager. +type FreeServicesClientListByResourceGroupResponse struct { + // This operation lists the free services that are available under the specified subscription. + FreeServicesList +} + +// FreeServicesClientListBySubscriptionResponse contains the response from method FreeServicesClient.NewListBySubscriptionPager. +type FreeServicesClientListBySubscriptionResponse struct { + // This operation lists the free services that are available under the specified subscription. + FreeServicesList +} + +// FreeServicesClientUpdateResponse contains the response from method FreeServicesClient.BeginUpdate. +type FreeServicesClientUpdateResponse struct { + // Free Services resource definition + FreeServices +} + +// MaccsClientCancelResponse contains the response from method MaccsClient.BeginCancel. +type MaccsClientCancelResponse struct { + // Microsoft Azure Consumption Commitment. + Macc +} + +// MaccsClientChargeShortfallResponse contains the response from method MaccsClient.BeginChargeShortfall. +type MaccsClientChargeShortfallResponse struct { + // Microsoft Azure Consumption Commitment. + Macc +} + +// MaccsClientCreateResponse contains the response from method MaccsClient.BeginCreate. +type MaccsClientCreateResponse struct { + // Microsoft Azure Consumption Commitment. + Macc +} + +// MaccsClientDeleteResponse contains the response from method MaccsClient.BeginDelete. +type MaccsClientDeleteResponse struct { + // placeholder for future response values +} + +// MaccsClientGetResponse contains the response from method MaccsClient.Get. +type MaccsClientGetResponse struct { + // Microsoft Azure Consumption Commitment. + Macc +} + +// MaccsClientListByResourceGroupResponse contains the response from method MaccsClient.NewListByResourceGroupPager. +type MaccsClientListByResourceGroupResponse struct { + // MACC list + MaccList +} + +// MaccsClientListBySubscriptionResponse contains the response from method MaccsClient.NewListBySubscriptionPager. +type MaccsClientListBySubscriptionResponse struct { + // MACC list + MaccList +} + +// MaccsClientUpdateResponse contains the response from method MaccsClient.BeginUpdate. +type MaccsClientUpdateResponse struct { + // Microsoft Azure Consumption Commitment. + Macc +} + +// MaccsClientWriteOffResponse contains the response from method MaccsClient.BeginWriteOff. +type MaccsClientWriteOffResponse struct { + // Microsoft Azure Consumption Commitment. + Macc +} + +// OperationsClientListResponse contains the response from method OperationsClient.NewListPager. +type OperationsClientListResponse struct { + // A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. + OperationListResult +} + +// RPClientValidateResponse contains the response from method RPClient.Validate. +type RPClientValidateResponse struct { + // Benefit validate response. + BenefitValidateResponse +} + +// ReservationOrderAliasClientCreateResponse contains the response from method ReservationOrderAliasClient.BeginCreate. +type ReservationOrderAliasClientCreateResponse struct { + // Reservation order alias + ReservationOrderAliasResponse +} + +// ReservationOrderAliasClientGetResponse contains the response from method ReservationOrderAliasClient.Get. +type ReservationOrderAliasClientGetResponse struct { + // Reservation order alias + ReservationOrderAliasResponse +} + +// SavingsPlanClientGetResponse contains the response from method SavingsPlanClient.Get. +type SavingsPlanClientGetResponse struct { + // Savings plan + SavingsPlanModel +} + +// SavingsPlanClientListAllResponse contains the response from method SavingsPlanClient.NewListAllPager. +type SavingsPlanClientListAllResponse struct { + // Represents the result of listing savings plan models + SavingsPlanModelListResult +} + +// SavingsPlanClientListResponse contains the response from method SavingsPlanClient.NewListPager. +type SavingsPlanClientListResponse struct { + // Paged collection of SavingsPlanModel items + SavingsPlanModelList +} + +// SavingsPlanClientUpdateResponse contains the response from method SavingsPlanClient.BeginUpdate. +type SavingsPlanClientUpdateResponse struct { + // Savings plan + SavingsPlanModel +} + +// SavingsPlanClientValidateUpdateResponse contains the response from method SavingsPlanClient.ValidateUpdate. +type SavingsPlanClientValidateUpdateResponse struct { + SavingsPlanValidateResponse +} + +// SavingsPlanOrderAliasClientCreateResponse contains the response from method SavingsPlanOrderAliasClient.BeginCreate. +type SavingsPlanOrderAliasClientCreateResponse struct { + // Savings plan order alias + SavingsPlanOrderAliasModel +} + +// SavingsPlanOrderAliasClientGetResponse contains the response from method SavingsPlanOrderAliasClient.Get. +type SavingsPlanOrderAliasClientGetResponse struct { + // Savings plan order alias + SavingsPlanOrderAliasModel +} + +// SavingsPlanOrderClientElevateResponse contains the response from method SavingsPlanOrderClient.Elevate. +type SavingsPlanOrderClientElevateResponse struct { + // Role assignment entity + RoleAssignmentEntity +} + +// SavingsPlanOrderClientGetResponse contains the response from method SavingsPlanOrderClient.Get. +type SavingsPlanOrderClientGetResponse struct { + // Savings plan order + SavingsPlanOrderModel +} + +// SavingsPlanOrderClientListResponse contains the response from method SavingsPlanOrderClient.NewListPager. +type SavingsPlanOrderClientListResponse struct { + // Paged collection of SavingsPlanOrderModel items + SavingsPlanOrderModelList +} + +// SellerResourceClientListResponse contains the response from method SellerResourceClient.List. +type SellerResourceClientListResponse struct { + MaccArray []*Macc +} + +// SourcesClientCreateResponse contains the response from method SourcesClient.Create. +type SourcesClientCreateResponse struct { + // Credit source resource definition + CreditSource +} + +// SourcesClientDeleteResponse contains the response from method SourcesClient.Delete. +type SourcesClientDeleteResponse struct { + // placeholder for future response values +} + +// SourcesClientGetResponse contains the response from method SourcesClient.Get. +type SourcesClientGetResponse struct { + // Credit source resource definition + CreditSource +} + +// SourcesClientListByCreditResponse contains the response from method SourcesClient.NewListByCreditPager. +type SourcesClientListByCreditResponse struct { + // List of credit sources + CreditSourcesList +} + +// SourcesClientUpdateResponse contains the response from method SourcesClient.Update. +type SourcesClientUpdateResponse struct { + // Credit source resource definition + CreditSource +} diff --git a/test/local/armbillingbenefits/zz_rp_client.go b/test/local/armbillingbenefits/zz_rp_client.go new file mode 100644 index 000000000000..2ad65419d656 --- /dev/null +++ b/test/local/armbillingbenefits/zz_rp_client.go @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armbillingbenefits + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// RPClient contains the methods for the RP group. +// Don't use this type directly, use NewRPClient() instead. +// +// Generated from API version 2025-12-01-preview +type RPClient struct { + internal *arm.Client +} + +// NewRPClient creates a new instance of RPClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewRPClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*RPClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &RPClient{ + internal: cl, + } + return client, nil +} + +// Validate - Validate savings plan purchase. +// If the operation fails it returns an *azcore.ResponseError type. +// - body - The request body +// - options - RPClientValidateOptions contains the optional parameters for the RPClient.Validate method. +func (client *RPClient) Validate(ctx context.Context, body BenefitValidateRequest, options *RPClientValidateOptions) (RPClientValidateResponse, error) { + var err error + const operationName = "RPClient.Validate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.validateCreateRequest(ctx, body, options) + if err != nil { + return RPClientValidateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RPClientValidateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RPClientValidateResponse{}, err + } + resp, err := client.validateHandleResponse(httpResp) + return resp, err +} + +// validateCreateRequest creates the Validate request. +func (client *RPClient) validateCreateRequest(ctx context.Context, body BenefitValidateRequest, _ *RPClientValidateOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.BillingBenefits/validate" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// validateHandleResponse handles the Validate response. +func (client *RPClient) validateHandleResponse(resp *http.Response) (RPClientValidateResponse, error) { + result := RPClientValidateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BenefitValidateResponse); err != nil { + return RPClientValidateResponse{}, err + } + return result, nil +} diff --git a/test/local/armbillingbenefits/zz_savingsplan_client.go b/test/local/armbillingbenefits/zz_savingsplan_client.go new file mode 100644 index 000000000000..0801defd8a27 --- /dev/null +++ b/test/local/armbillingbenefits/zz_savingsplan_client.go @@ -0,0 +1,356 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armbillingbenefits + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" +) + +// SavingsPlanClient contains the methods for the SavingsPlan group. +// Don't use this type directly, use NewSavingsPlanClient() instead. +// +// Generated from API version 2025-12-01-preview +type SavingsPlanClient struct { + internal *arm.Client +} + +// NewSavingsPlanClient creates a new instance of SavingsPlanClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewSavingsPlanClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*SavingsPlanClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SavingsPlanClient{ + internal: cl, + } + return client, nil +} + +// Get - Get savings plan. +// If the operation fails it returns an *azcore.ResponseError type. +// - savingsPlanOrderID - Order ID of the savings plan +// - savingsPlanID - ID of the savings plan +// - options - SavingsPlanClientGetOptions contains the optional parameters for the SavingsPlanClient.Get method. +func (client *SavingsPlanClient) Get(ctx context.Context, savingsPlanOrderID string, savingsPlanID string, options *SavingsPlanClientGetOptions) (SavingsPlanClientGetResponse, error) { + var err error + const operationName = "SavingsPlanClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, savingsPlanOrderID, savingsPlanID, options) + if err != nil { + return SavingsPlanClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SavingsPlanClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SavingsPlanClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *SavingsPlanClient) getCreateRequest(ctx context.Context, savingsPlanOrderID string, savingsPlanID string, options *SavingsPlanClientGetOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans/{savingsPlanId}" + if savingsPlanOrderID == "" { + return nil, errors.New("parameter savingsPlanOrderID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{savingsPlanOrderId}", url.PathEscape(savingsPlanOrderID)) + if savingsPlanID == "" { + return nil, errors.New("parameter savingsPlanID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{savingsPlanId}", url.PathEscape(savingsPlanID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *SavingsPlanClient) getHandleResponse(resp *http.Response) (SavingsPlanClientGetResponse, error) { + result := SavingsPlanClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SavingsPlanModel); err != nil { + return SavingsPlanClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List savings plans in an order. +// - savingsPlanOrderID - Order ID of the savings plan +// - options - SavingsPlanClientListOptions contains the optional parameters for the SavingsPlanClient.NewListPager method. +func (client *SavingsPlanClient) NewListPager(savingsPlanOrderID string, options *SavingsPlanClientListOptions) *runtime.Pager[SavingsPlanClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[SavingsPlanClientListResponse]{ + More: func(page SavingsPlanClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SavingsPlanClientListResponse) (SavingsPlanClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SavingsPlanClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, savingsPlanOrderID, options) + }, nil) + if err != nil { + return SavingsPlanClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *SavingsPlanClient) listCreateRequest(ctx context.Context, savingsPlanOrderID string, _ *SavingsPlanClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans" + if savingsPlanOrderID == "" { + return nil, errors.New("parameter savingsPlanOrderID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{savingsPlanOrderId}", url.PathEscape(savingsPlanOrderID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *SavingsPlanClient) listHandleResponse(resp *http.Response) (SavingsPlanClientListResponse, error) { + result := SavingsPlanClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SavingsPlanModelList); err != nil { + return SavingsPlanClientListResponse{}, err + } + return result, nil +} + +// NewListAllPager - List savings plans. +// - options - SavingsPlanClientListAllOptions contains the optional parameters for the SavingsPlanClient.NewListAllPager method. +func (client *SavingsPlanClient) NewListAllPager(options *SavingsPlanClientListAllOptions) *runtime.Pager[SavingsPlanClientListAllResponse] { + return runtime.NewPager(runtime.PagingHandler[SavingsPlanClientListAllResponse]{ + More: func(page SavingsPlanClientListAllResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SavingsPlanClientListAllResponse) (SavingsPlanClientListAllResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SavingsPlanClient.NewListAllPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listAllCreateRequest(ctx, options) + }, nil) + if err != nil { + return SavingsPlanClientListAllResponse{}, err + } + return client.listAllHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAllCreateRequest creates the ListAll request. +func (client *SavingsPlanClient) listAllCreateRequest(ctx context.Context, options *SavingsPlanClientListAllOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.BillingBenefits/savingsPlans" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.Orderby != nil { + reqQP.Set("$orderby", *options.Orderby) + } + if options != nil && options.Skiptoken != nil { + reqQP.Set("$skiptoken", strconv.FormatFloat(float64(*options.Skiptoken), 'f', -1, 32)) + } + reqQP.Set("api-version", version20251201Preview) + if options != nil && options.RefreshSummary != nil { + reqQP.Set("refreshSummary", *options.RefreshSummary) + } + if options != nil && options.SelectedState != nil { + reqQP.Set("selectedState", *options.SelectedState) + } + if options != nil && options.Take != nil { + reqQP.Set("take", strconv.FormatFloat(float64(*options.Take), 'f', -1, 32)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAllHandleResponse handles the ListAll response. +func (client *SavingsPlanClient) listAllHandleResponse(resp *http.Response) (SavingsPlanClientListAllResponse, error) { + result := SavingsPlanClientListAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SavingsPlanModelListResult); err != nil { + return SavingsPlanClientListAllResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update savings plan. +// If the operation fails it returns an *azcore.ResponseError type. +// - savingsPlanOrderID - Order ID of the savings plan +// - savingsPlanID - ID of the savings plan +// - body - Request body for patching a savings plan order alias +// - options - SavingsPlanClientBeginUpdateOptions contains the optional parameters for the SavingsPlanClient.BeginUpdate method. +func (client *SavingsPlanClient) BeginUpdate(ctx context.Context, savingsPlanOrderID string, savingsPlanID string, body SavingsPlanUpdateRequest, options *SavingsPlanClientBeginUpdateOptions) (*runtime.Poller[SavingsPlanClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, savingsPlanOrderID, savingsPlanID, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SavingsPlanClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SavingsPlanClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update savings plan. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *SavingsPlanClient) update(ctx context.Context, savingsPlanOrderID string, savingsPlanID string, body SavingsPlanUpdateRequest, options *SavingsPlanClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "SavingsPlanClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, savingsPlanOrderID, savingsPlanID, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *SavingsPlanClient) updateCreateRequest(ctx context.Context, savingsPlanOrderID string, savingsPlanID string, body SavingsPlanUpdateRequest, _ *SavingsPlanClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans/{savingsPlanId}" + if savingsPlanOrderID == "" { + return nil, errors.New("parameter savingsPlanOrderID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{savingsPlanOrderId}", url.PathEscape(savingsPlanOrderID)) + if savingsPlanID == "" { + return nil, errors.New("parameter savingsPlanID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{savingsPlanId}", url.PathEscape(savingsPlanID)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// ValidateUpdate - Validate savings plan patch. +// If the operation fails it returns an *azcore.ResponseError type. +// - savingsPlanOrderID - Order ID of the savings plan +// - savingsPlanID - ID of the savings plan +// - body - Request body for validating a savings plan patch request +// - options - SavingsPlanClientValidateUpdateOptions contains the optional parameters for the SavingsPlanClient.ValidateUpdate +// method. +func (client *SavingsPlanClient) ValidateUpdate(ctx context.Context, savingsPlanOrderID string, savingsPlanID string, body SavingsPlanUpdateValidateRequest, options *SavingsPlanClientValidateUpdateOptions) (SavingsPlanClientValidateUpdateResponse, error) { + var err error + const operationName = "SavingsPlanClient.ValidateUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.validateUpdateCreateRequest(ctx, savingsPlanOrderID, savingsPlanID, body, options) + if err != nil { + return SavingsPlanClientValidateUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SavingsPlanClientValidateUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SavingsPlanClientValidateUpdateResponse{}, err + } + resp, err := client.validateUpdateHandleResponse(httpResp) + return resp, err +} + +// validateUpdateCreateRequest creates the ValidateUpdate request. +func (client *SavingsPlanClient) validateUpdateCreateRequest(ctx context.Context, savingsPlanOrderID string, savingsPlanID string, body SavingsPlanUpdateValidateRequest, _ *SavingsPlanClientValidateUpdateOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/savingsPlans/{savingsPlanId}/validate" + if savingsPlanOrderID == "" { + return nil, errors.New("parameter savingsPlanOrderID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{savingsPlanOrderId}", url.PathEscape(savingsPlanOrderID)) + if savingsPlanID == "" { + return nil, errors.New("parameter savingsPlanID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{savingsPlanId}", url.PathEscape(savingsPlanID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// validateUpdateHandleResponse handles the ValidateUpdate response. +func (client *SavingsPlanClient) validateUpdateHandleResponse(resp *http.Response) (SavingsPlanClientValidateUpdateResponse, error) { + result := SavingsPlanClientValidateUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SavingsPlanValidateResponse); err != nil { + return SavingsPlanClientValidateUpdateResponse{}, err + } + return result, nil +} diff --git a/test/local/armbillingbenefits/zz_savingsplanorder_client.go b/test/local/armbillingbenefits/zz_savingsplanorder_client.go new file mode 100644 index 000000000000..1b6f17fd8960 --- /dev/null +++ b/test/local/armbillingbenefits/zz_savingsplanorder_client.go @@ -0,0 +1,198 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armbillingbenefits + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// SavingsPlanOrderClient contains the methods for the SavingsPlanOrder group. +// Don't use this type directly, use NewSavingsPlanOrderClient() instead. +// +// Generated from API version 2025-12-01-preview +type SavingsPlanOrderClient struct { + internal *arm.Client +} + +// NewSavingsPlanOrderClient creates a new instance of SavingsPlanOrderClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewSavingsPlanOrderClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*SavingsPlanOrderClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SavingsPlanOrderClient{ + internal: cl, + } + return client, nil +} + +// Elevate - Elevate as owner on savings plan order based on billing permissions. +// If the operation fails it returns an *azcore.ResponseError type. +// - savingsPlanOrderID - Order ID of the savings plan +// - options - SavingsPlanOrderClientElevateOptions contains the optional parameters for the SavingsPlanOrderClient.Elevate +// method. +func (client *SavingsPlanOrderClient) Elevate(ctx context.Context, savingsPlanOrderID string, options *SavingsPlanOrderClientElevateOptions) (SavingsPlanOrderClientElevateResponse, error) { + var err error + const operationName = "SavingsPlanOrderClient.Elevate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.elevateCreateRequest(ctx, savingsPlanOrderID, options) + if err != nil { + return SavingsPlanOrderClientElevateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SavingsPlanOrderClientElevateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SavingsPlanOrderClientElevateResponse{}, err + } + resp, err := client.elevateHandleResponse(httpResp) + return resp, err +} + +// elevateCreateRequest creates the Elevate request. +func (client *SavingsPlanOrderClient) elevateCreateRequest(ctx context.Context, savingsPlanOrderID string, _ *SavingsPlanOrderClientElevateOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}/elevate" + if savingsPlanOrderID == "" { + return nil, errors.New("parameter savingsPlanOrderID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{savingsPlanOrderId}", url.PathEscape(savingsPlanOrderID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// elevateHandleResponse handles the Elevate response. +func (client *SavingsPlanOrderClient) elevateHandleResponse(resp *http.Response) (SavingsPlanOrderClientElevateResponse, error) { + result := SavingsPlanOrderClientElevateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RoleAssignmentEntity); err != nil { + return SavingsPlanOrderClientElevateResponse{}, err + } + return result, nil +} + +// Get - Get a savings plan order. +// If the operation fails it returns an *azcore.ResponseError type. +// - savingsPlanOrderID - Order ID of the savings plan +// - options - SavingsPlanOrderClientGetOptions contains the optional parameters for the SavingsPlanOrderClient.Get method. +func (client *SavingsPlanOrderClient) Get(ctx context.Context, savingsPlanOrderID string, options *SavingsPlanOrderClientGetOptions) (SavingsPlanOrderClientGetResponse, error) { + var err error + const operationName = "SavingsPlanOrderClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, savingsPlanOrderID, options) + if err != nil { + return SavingsPlanOrderClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SavingsPlanOrderClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SavingsPlanOrderClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *SavingsPlanOrderClient) getCreateRequest(ctx context.Context, savingsPlanOrderID string, options *SavingsPlanOrderClientGetOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.BillingBenefits/savingsPlanOrders/{savingsPlanOrderId}" + if savingsPlanOrderID == "" { + return nil, errors.New("parameter savingsPlanOrderID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{savingsPlanOrderId}", url.PathEscape(savingsPlanOrderID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *SavingsPlanOrderClient) getHandleResponse(resp *http.Response) (SavingsPlanOrderClientGetResponse, error) { + result := SavingsPlanOrderClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SavingsPlanOrderModel); err != nil { + return SavingsPlanOrderClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List all Savings plan orders. +// - options - SavingsPlanOrderClientListOptions contains the optional parameters for the SavingsPlanOrderClient.NewListPager +// method. +func (client *SavingsPlanOrderClient) NewListPager(options *SavingsPlanOrderClientListOptions) *runtime.Pager[SavingsPlanOrderClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[SavingsPlanOrderClientListResponse]{ + More: func(page SavingsPlanOrderClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SavingsPlanOrderClientListResponse) (SavingsPlanOrderClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SavingsPlanOrderClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return SavingsPlanOrderClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *SavingsPlanOrderClient) listCreateRequest(ctx context.Context, _ *SavingsPlanOrderClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.BillingBenefits/savingsPlanOrders" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *SavingsPlanOrderClient) listHandleResponse(resp *http.Response) (SavingsPlanOrderClientListResponse, error) { + result := SavingsPlanOrderClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SavingsPlanOrderModelList); err != nil { + return SavingsPlanOrderClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armbillingbenefits/zz_savingsplanorderalias_client.go b/test/local/armbillingbenefits/zz_savingsplanorderalias_client.go new file mode 100644 index 000000000000..371c0ed11646 --- /dev/null +++ b/test/local/armbillingbenefits/zz_savingsplanorderalias_client.go @@ -0,0 +1,161 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armbillingbenefits + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// SavingsPlanOrderAliasClient contains the methods for the SavingsPlanOrderAlias group. +// Don't use this type directly, use NewSavingsPlanOrderAliasClient() instead. +// +// Generated from API version 2025-12-01-preview +type SavingsPlanOrderAliasClient struct { + internal *arm.Client +} + +// NewSavingsPlanOrderAliasClient creates a new instance of SavingsPlanOrderAliasClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewSavingsPlanOrderAliasClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*SavingsPlanOrderAliasClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SavingsPlanOrderAliasClient{ + internal: cl, + } + return client, nil +} + +// BeginCreate - Create a savings plan. Learn more about permissions needed at https://go.microsoft.com/fwlink/?linkid=2215851 +// If the operation fails it returns an *azcore.ResponseError type. +// - savingsPlanOrderAliasName - Name of the savings plan order alias +// - body - Request body for creating a savings plan order alias +// - options - SavingsPlanOrderAliasClientBeginCreateOptions contains the optional parameters for the SavingsPlanOrderAliasClient.BeginCreate +// method. +func (client *SavingsPlanOrderAliasClient) BeginCreate(ctx context.Context, savingsPlanOrderAliasName string, body SavingsPlanOrderAliasModel, options *SavingsPlanOrderAliasClientBeginCreateOptions) (*runtime.Poller[SavingsPlanOrderAliasClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, savingsPlanOrderAliasName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SavingsPlanOrderAliasClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SavingsPlanOrderAliasClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Create a savings plan. Learn more about permissions needed at https://go.microsoft.com/fwlink/?linkid=2215851 +// If the operation fails it returns an *azcore.ResponseError type. +func (client *SavingsPlanOrderAliasClient) create(ctx context.Context, savingsPlanOrderAliasName string, body SavingsPlanOrderAliasModel, options *SavingsPlanOrderAliasClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "SavingsPlanOrderAliasClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, savingsPlanOrderAliasName, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *SavingsPlanOrderAliasClient) createCreateRequest(ctx context.Context, savingsPlanOrderAliasName string, body SavingsPlanOrderAliasModel, _ *SavingsPlanOrderAliasClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.BillingBenefits/savingsPlanOrderAliases/{savingsPlanOrderAliasName}" + if savingsPlanOrderAliasName == "" { + return nil, errors.New("parameter savingsPlanOrderAliasName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{savingsPlanOrderAliasName}", url.PathEscape(savingsPlanOrderAliasName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// Get - Get a savings plan. +// If the operation fails it returns an *azcore.ResponseError type. +// - savingsPlanOrderAliasName - Name of the savings plan order alias +// - options - SavingsPlanOrderAliasClientGetOptions contains the optional parameters for the SavingsPlanOrderAliasClient.Get +// method. +func (client *SavingsPlanOrderAliasClient) Get(ctx context.Context, savingsPlanOrderAliasName string, options *SavingsPlanOrderAliasClientGetOptions) (SavingsPlanOrderAliasClientGetResponse, error) { + var err error + const operationName = "SavingsPlanOrderAliasClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, savingsPlanOrderAliasName, options) + if err != nil { + return SavingsPlanOrderAliasClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SavingsPlanOrderAliasClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SavingsPlanOrderAliasClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *SavingsPlanOrderAliasClient) getCreateRequest(ctx context.Context, savingsPlanOrderAliasName string, _ *SavingsPlanOrderAliasClientGetOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.BillingBenefits/savingsPlanOrderAliases/{savingsPlanOrderAliasName}" + if savingsPlanOrderAliasName == "" { + return nil, errors.New("parameter savingsPlanOrderAliasName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{savingsPlanOrderAliasName}", url.PathEscape(savingsPlanOrderAliasName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *SavingsPlanOrderAliasClient) getHandleResponse(resp *http.Response) (SavingsPlanOrderAliasClientGetResponse, error) { + result := SavingsPlanOrderAliasClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SavingsPlanOrderAliasModel); err != nil { + return SavingsPlanOrderAliasClientGetResponse{}, err + } + return result, nil +} diff --git a/test/local/armbillingbenefits/zz_sellerresource_client.go b/test/local/armbillingbenefits/zz_sellerresource_client.go new file mode 100644 index 000000000000..a0528577f316 --- /dev/null +++ b/test/local/armbillingbenefits/zz_sellerresource_client.go @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armbillingbenefits + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// SellerResourceClient contains the methods for the SellerResource group. +// Don't use this type directly, use NewSellerResourceClient() instead. +// +// Generated from API version 2025-12-01-preview +type SellerResourceClient struct { + internal *arm.Client +} + +// NewSellerResourceClient creates a new instance of SellerResourceClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewSellerResourceClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*SellerResourceClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SellerResourceClient{ + internal: cl, + } + return client, nil +} + +// List - List maccs by billing account +// If the operation fails it returns an *azcore.ResponseError type. +// - body - The request body +// - options - SellerResourceClientListOptions contains the optional parameters for the SellerResourceClient.List method. +func (client *SellerResourceClient) List(ctx context.Context, body SellerResourceListRequest, options *SellerResourceClientListOptions) (SellerResourceClientListResponse, error) { + var err error + const operationName = "SellerResourceClient.List" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listCreateRequest(ctx, body, options) + if err != nil { + return SellerResourceClientListResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SellerResourceClientListResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SellerResourceClientListResponse{}, err + } + resp, err := client.listHandleResponse(httpResp) + return resp, err +} + +// listCreateRequest creates the List request. +func (client *SellerResourceClient) listCreateRequest(ctx context.Context, body SellerResourceListRequest, _ *SellerResourceClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.BillingBenefits/listSellerResources" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// listHandleResponse handles the List response. +func (client *SellerResourceClient) listHandleResponse(resp *http.Response) (SellerResourceClientListResponse, error) { + result := SellerResourceClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.MaccArray); err != nil { + return SellerResourceClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armbillingbenefits/zz_sources_client.go b/test/local/armbillingbenefits/zz_sources_client.go new file mode 100644 index 000000000000..16c2265b00b1 --- /dev/null +++ b/test/local/armbillingbenefits/zz_sources_client.go @@ -0,0 +1,372 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armbillingbenefits + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// SourcesClient contains the methods for the Sources group. +// Don't use this type directly, use NewSourcesClient() instead. +// +// Generated from API version 2025-12-01-preview +type SourcesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewSourcesClient creates a new instance of SourcesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewSourcesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SourcesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SourcesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Create - Create a credit source. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - creditName - Name of the credit +// - sourceName - Name of the credit source +// - body - Credit source create request +// - options - SourcesClientCreateOptions contains the optional parameters for the SourcesClient.Create method. +func (client *SourcesClient) Create(ctx context.Context, resourceGroupName string, creditName string, sourceName string, body CreditSource, options *SourcesClientCreateOptions) (SourcesClientCreateResponse, error) { + var err error + const operationName = "SourcesClient.Create" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, creditName, sourceName, body, options) + if err != nil { + return SourcesClientCreateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SourcesClientCreateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return SourcesClientCreateResponse{}, err + } + resp, err := client.createHandleResponse(httpResp) + return resp, err +} + +// createCreateRequest creates the Create request. +func (client *SourcesClient) createCreateRequest(ctx context.Context, resourceGroupName string, creditName string, sourceName string, body CreditSource, _ *SourcesClientCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/credits/{creditName}/sources/{sourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if creditName == "" { + return nil, errors.New("parameter creditName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{creditName}", url.PathEscape(creditName)) + if sourceName == "" { + return nil, errors.New("parameter sourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{sourceName}", url.PathEscape(sourceName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// createHandleResponse handles the Create response. +func (client *SourcesClient) createHandleResponse(resp *http.Response) (SourcesClientCreateResponse, error) { + result := SourcesClientCreateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CreditSource); err != nil { + return SourcesClientCreateResponse{}, err + } + return result, nil +} + +// Delete - Delete a credit source. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - creditName - Name of the credit +// - sourceName - Name of the credit source +// - options - SourcesClientDeleteOptions contains the optional parameters for the SourcesClient.Delete method. +func (client *SourcesClient) Delete(ctx context.Context, resourceGroupName string, creditName string, sourceName string, options *SourcesClientDeleteOptions) (SourcesClientDeleteResponse, error) { + var err error + const operationName = "SourcesClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, creditName, sourceName, options) + if err != nil { + return SourcesClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SourcesClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return SourcesClientDeleteResponse{}, err + } + return SourcesClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *SourcesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, creditName string, sourceName string, _ *SourcesClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/credits/{creditName}/sources/{sourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if creditName == "" { + return nil, errors.New("parameter creditName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{creditName}", url.PathEscape(creditName)) + if sourceName == "" { + return nil, errors.New("parameter sourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{sourceName}", url.PathEscape(sourceName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a credit source. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - creditName - Name of the credit +// - sourceName - Name of the credit source +// - options - SourcesClientGetOptions contains the optional parameters for the SourcesClient.Get method. +func (client *SourcesClient) Get(ctx context.Context, resourceGroupName string, creditName string, sourceName string, options *SourcesClientGetOptions) (SourcesClientGetResponse, error) { + var err error + const operationName = "SourcesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, creditName, sourceName, options) + if err != nil { + return SourcesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SourcesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SourcesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *SourcesClient) getCreateRequest(ctx context.Context, resourceGroupName string, creditName string, sourceName string, _ *SourcesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/credits/{creditName}/sources/{sourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if creditName == "" { + return nil, errors.New("parameter creditName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{creditName}", url.PathEscape(creditName)) + if sourceName == "" { + return nil, errors.New("parameter sourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{sourceName}", url.PathEscape(sourceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *SourcesClient) getHandleResponse(resp *http.Response) (SourcesClientGetResponse, error) { + result := SourcesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CreditSource); err != nil { + return SourcesClientGetResponse{}, err + } + return result, nil +} + +// NewListByCreditPager - List credit sources for a credit under a resource group from primary service admin. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - creditName - Name of the credit +// - options - SourcesClientListByCreditOptions contains the optional parameters for the SourcesClient.NewListByCreditPager +// method. +func (client *SourcesClient) NewListByCreditPager(resourceGroupName string, creditName string, options *SourcesClientListByCreditOptions) *runtime.Pager[SourcesClientListByCreditResponse] { + return runtime.NewPager(runtime.PagingHandler[SourcesClientListByCreditResponse]{ + More: func(page SourcesClientListByCreditResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SourcesClientListByCreditResponse) (SourcesClientListByCreditResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SourcesClient.NewListByCreditPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByCreditCreateRequest(ctx, resourceGroupName, creditName, options) + }, nil) + if err != nil { + return SourcesClientListByCreditResponse{}, err + } + return client.listByCreditHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByCreditCreateRequest creates the ListByCredit request. +func (client *SourcesClient) listByCreditCreateRequest(ctx context.Context, resourceGroupName string, creditName string, _ *SourcesClientListByCreditOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/credits/{creditName}/sources" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if creditName == "" { + return nil, errors.New("parameter creditName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{creditName}", url.PathEscape(creditName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByCreditHandleResponse handles the ListByCredit response. +func (client *SourcesClient) listByCreditHandleResponse(resp *http.Response) (SourcesClientListByCreditResponse, error) { + result := SourcesClientListByCreditResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CreditSourcesList); err != nil { + return SourcesClientListByCreditResponse{}, err + } + return result, nil +} + +// Update - Update a credit source. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - creditName - Name of the credit +// - sourceName - Name of the credit source +// - body - Credit source patch request +// - options - SourcesClientUpdateOptions contains the optional parameters for the SourcesClient.Update method. +func (client *SourcesClient) Update(ctx context.Context, resourceGroupName string, creditName string, sourceName string, body CreditSourcePatchRequest, options *SourcesClientUpdateOptions) (SourcesClientUpdateResponse, error) { + var err error + const operationName = "SourcesClient.Update" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, creditName, sourceName, body, options) + if err != nil { + return SourcesClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SourcesClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SourcesClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *SourcesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, creditName string, sourceName string, body CreditSourcePatchRequest, _ *SourcesClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.BillingBenefits/credits/{creditName}/sources/{sourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if creditName == "" { + return nil, errors.New("parameter creditName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{creditName}", url.PathEscape(creditName)) + if sourceName == "" { + return nil, errors.New("parameter sourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{sourceName}", url.PathEscape(sourceName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *SourcesClient) updateHandleResponse(resp *http.Response) (SourcesClientUpdateResponse, error) { + result := SourcesClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CreditSource); err != nil { + return SourcesClientUpdateResponse{}, err + } + return result, nil +} diff --git a/test/local/armbillingbenefits/zz_version.go b/test/local/armbillingbenefits/zz_version.go new file mode 100644 index 000000000000..568db2d5ad84 --- /dev/null +++ b/test/local/armbillingbenefits/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package armbillingbenefits + +const ( + moduleName = "armbillingbenefits" + moduleVersion = "v0.1.0" +) diff --git a/test/local/armcodesigning/LICENSE.txt b/test/local/armcodesigning/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/local/armcodesigning/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/local/armcodesigning/fake/zz_accounts_server.go b/test/local/armcodesigning/fake/zz_accounts_server.go new file mode 100644 index 000000000000..e2deb5ef1a22 --- /dev/null +++ b/test/local/armcodesigning/fake/zz_accounts_server.go @@ -0,0 +1,405 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcodesigning" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// AccountsServer is a fake server for instances of the armcodesigning.AccountsClient type. +type AccountsServer struct { + // CheckNameAvailability is the fake for method AccountsClient.CheckNameAvailability + // HTTP status codes to indicate success: http.StatusOK + CheckNameAvailability func(ctx context.Context, body armcodesigning.CheckNameAvailability, options *armcodesigning.AccountsClientCheckNameAvailabilityOptions) (resp azfake.Responder[armcodesigning.AccountsClientCheckNameAvailabilityResponse], errResp azfake.ErrorResponder) + + // BeginCreate is the fake for method AccountsClient.BeginCreate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreate func(ctx context.Context, resourceGroupName string, accountName string, resource armcodesigning.Account, options *armcodesigning.AccountsClientBeginCreateOptions) (resp azfake.PollerResponder[armcodesigning.AccountsClientCreateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method AccountsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, accountName string, options *armcodesigning.AccountsClientBeginDeleteOptions) (resp azfake.PollerResponder[armcodesigning.AccountsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method AccountsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, accountName string, options *armcodesigning.AccountsClientGetOptions) (resp azfake.Responder[armcodesigning.AccountsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method AccountsClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armcodesigning.AccountsClientListByResourceGroupOptions) (resp azfake.PagerResponder[armcodesigning.AccountsClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method AccountsClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armcodesigning.AccountsClientListBySubscriptionOptions) (resp azfake.PagerResponder[armcodesigning.AccountsClientListBySubscriptionResponse]) + + // BeginUpdate is the fake for method AccountsClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, accountName string, properties armcodesigning.AccountPatch, options *armcodesigning.AccountsClientBeginUpdateOptions) (resp azfake.PollerResponder[armcodesigning.AccountsClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewAccountsServerTransport creates a new instance of AccountsServerTransport with the provided implementation. +// The returned AccountsServerTransport instance is connected to an instance of armcodesigning.AccountsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAccountsServerTransport(srv *AccountsServer) *AccountsServerTransport { + return &AccountsServerTransport{ + srv: srv, + beginCreate: newTracker[azfake.PollerResponder[armcodesigning.AccountsClientCreateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armcodesigning.AccountsClientDeleteResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armcodesigning.AccountsClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armcodesigning.AccountsClientListBySubscriptionResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armcodesigning.AccountsClientUpdateResponse]](), + } +} + +// AccountsServerTransport connects instances of armcodesigning.AccountsClient to instances of AccountsServer. +// Don't use this type directly, use NewAccountsServerTransport instead. +type AccountsServerTransport struct { + srv *AccountsServer + beginCreate *tracker[azfake.PollerResponder[armcodesigning.AccountsClientCreateResponse]] + beginDelete *tracker[azfake.PollerResponder[armcodesigning.AccountsClientDeleteResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armcodesigning.AccountsClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armcodesigning.AccountsClientListBySubscriptionResponse]] + beginUpdate *tracker[azfake.PollerResponder[armcodesigning.AccountsClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for AccountsServerTransport. +func (a *AccountsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *AccountsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if accountsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = accountsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "AccountsClient.CheckNameAvailability": + res.resp, res.err = a.dispatchCheckNameAvailability(req) + case "AccountsClient.BeginCreate": + res.resp, res.err = a.dispatchBeginCreate(req) + case "AccountsClient.BeginDelete": + res.resp, res.err = a.dispatchBeginDelete(req) + case "AccountsClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "AccountsClient.NewListByResourceGroupPager": + res.resp, res.err = a.dispatchNewListByResourceGroupPager(req) + case "AccountsClient.NewListBySubscriptionPager": + res.resp, res.err = a.dispatchNewListBySubscriptionPager(req) + case "AccountsClient.BeginUpdate": + res.resp, res.err = a.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *AccountsServerTransport) dispatchCheckNameAvailability(req *http.Request) (*http.Response, error) { + if a.srv.CheckNameAvailability == nil { + return nil, &nonRetriableError{errors.New("fake for method CheckNameAvailability not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CodeSigning/checkNameAvailability` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcodesigning.CheckNameAvailability](req) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.CheckNameAvailability(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CheckNameAvailabilityResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AccountsServerTransport) dispatchBeginCreate(req *http.Request) (*http.Response, error) { + if a.srv.BeginCreate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreate not implemented")} + } + beginCreate := a.beginCreate.get(req) + if beginCreate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CodeSigning/codeSigningAccounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcodesigning.Account](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginCreate(req.Context(), resourceGroupNameParam, accountNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreate = &respr + a.beginCreate.add(req, beginCreate) + } + + resp, err := server.PollerResponderNext(beginCreate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + a.beginCreate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreate) { + a.beginCreate.remove(req) + } + + return resp, nil +} + +func (a *AccountsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if a.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := a.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CodeSigning/codeSigningAccounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginDelete(req.Context(), resourceGroupNameParam, accountNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + a.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + a.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + a.beginDelete.remove(req) + } + + return resp, nil +} + +func (a *AccountsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CodeSigning/codeSigningAccounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Get(req.Context(), resourceGroupNameParam, accountNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Account, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AccountsServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if a.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := a.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CodeSigning/codeSigningAccounts` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := a.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + a.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armcodesigning.AccountsClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + a.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (a *AccountsServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if a.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := a.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CodeSigning/codeSigningAccounts` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := a.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + a.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armcodesigning.AccountsClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + a.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (a *AccountsServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if a.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := a.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CodeSigning/codeSigningAccounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcodesigning.AccountPatch](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginUpdate(req.Context(), resourceGroupNameParam, accountNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + a.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + a.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + a.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to AccountsServerTransport +var accountsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcodesigning/fake/zz_certificateprofiles_server.go b/test/local/armcodesigning/fake/zz_certificateprofiles_server.go new file mode 100644 index 000000000000..82a7cef60476 --- /dev/null +++ b/test/local/armcodesigning/fake/zz_certificateprofiles_server.go @@ -0,0 +1,336 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcodesigning" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// CertificateProfilesServer is a fake server for instances of the armcodesigning.CertificateProfilesClient type. +type CertificateProfilesServer struct { + // BeginCreate is the fake for method CertificateProfilesClient.BeginCreate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreate func(ctx context.Context, resourceGroupName string, accountName string, profileName string, resource armcodesigning.CertificateProfile, options *armcodesigning.CertificateProfilesClientBeginCreateOptions) (resp azfake.PollerResponder[armcodesigning.CertificateProfilesClientCreateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method CertificateProfilesClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, accountName string, profileName string, options *armcodesigning.CertificateProfilesClientBeginDeleteOptions) (resp azfake.PollerResponder[armcodesigning.CertificateProfilesClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method CertificateProfilesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, accountName string, profileName string, options *armcodesigning.CertificateProfilesClientGetOptions) (resp azfake.Responder[armcodesigning.CertificateProfilesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByCodeSigningAccountPager is the fake for method CertificateProfilesClient.NewListByCodeSigningAccountPager + // HTTP status codes to indicate success: http.StatusOK + NewListByCodeSigningAccountPager func(resourceGroupName string, accountName string, options *armcodesigning.CertificateProfilesClientListByCodeSigningAccountOptions) (resp azfake.PagerResponder[armcodesigning.CertificateProfilesClientListByCodeSigningAccountResponse]) + + // RevokeCertificates is the fake for method CertificateProfilesClient.RevokeCertificates + // HTTP status codes to indicate success: http.StatusNoContent + RevokeCertificates func(ctx context.Context, resourceGroupName string, accountName string, profileName string, body armcodesigning.RevokeCertificateList, options *armcodesigning.CertificateProfilesClientRevokeCertificatesOptions) (resp azfake.Responder[armcodesigning.CertificateProfilesClientRevokeCertificatesResponse], errResp azfake.ErrorResponder) +} + +// NewCertificateProfilesServerTransport creates a new instance of CertificateProfilesServerTransport with the provided implementation. +// The returned CertificateProfilesServerTransport instance is connected to an instance of armcodesigning.CertificateProfilesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewCertificateProfilesServerTransport(srv *CertificateProfilesServer) *CertificateProfilesServerTransport { + return &CertificateProfilesServerTransport{ + srv: srv, + beginCreate: newTracker[azfake.PollerResponder[armcodesigning.CertificateProfilesClientCreateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armcodesigning.CertificateProfilesClientDeleteResponse]](), + newListByCodeSigningAccountPager: newTracker[azfake.PagerResponder[armcodesigning.CertificateProfilesClientListByCodeSigningAccountResponse]](), + } +} + +// CertificateProfilesServerTransport connects instances of armcodesigning.CertificateProfilesClient to instances of CertificateProfilesServer. +// Don't use this type directly, use NewCertificateProfilesServerTransport instead. +type CertificateProfilesServerTransport struct { + srv *CertificateProfilesServer + beginCreate *tracker[azfake.PollerResponder[armcodesigning.CertificateProfilesClientCreateResponse]] + beginDelete *tracker[azfake.PollerResponder[armcodesigning.CertificateProfilesClientDeleteResponse]] + newListByCodeSigningAccountPager *tracker[azfake.PagerResponder[armcodesigning.CertificateProfilesClientListByCodeSigningAccountResponse]] +} + +// Do implements the policy.Transporter interface for CertificateProfilesServerTransport. +func (c *CertificateProfilesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *CertificateProfilesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if certificateProfilesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = certificateProfilesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "CertificateProfilesClient.BeginCreate": + res.resp, res.err = c.dispatchBeginCreate(req) + case "CertificateProfilesClient.BeginDelete": + res.resp, res.err = c.dispatchBeginDelete(req) + case "CertificateProfilesClient.Get": + res.resp, res.err = c.dispatchGet(req) + case "CertificateProfilesClient.NewListByCodeSigningAccountPager": + res.resp, res.err = c.dispatchNewListByCodeSigningAccountPager(req) + case "CertificateProfilesClient.RevokeCertificates": + res.resp, res.err = c.dispatchRevokeCertificates(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *CertificateProfilesServerTransport) dispatchBeginCreate(req *http.Request) (*http.Response, error) { + if c.srv.BeginCreate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreate not implemented")} + } + beginCreate := c.beginCreate.get(req) + if beginCreate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CodeSigning/codeSigningAccounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/certificateProfiles/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcodesigning.CertificateProfile](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + profileNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("profileName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginCreate(req.Context(), resourceGroupNameParam, accountNameParam, profileNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreate = &respr + c.beginCreate.add(req, beginCreate) + } + + resp, err := server.PollerResponderNext(beginCreate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + c.beginCreate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreate) { + c.beginCreate.remove(req) + } + + return resp, nil +} + +func (c *CertificateProfilesServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if c.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := c.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CodeSigning/codeSigningAccounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/certificateProfiles/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + profileNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("profileName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginDelete(req.Context(), resourceGroupNameParam, accountNameParam, profileNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + c.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + c.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + c.beginDelete.remove(req) + } + + return resp, nil +} + +func (c *CertificateProfilesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if c.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CodeSigning/codeSigningAccounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/certificateProfiles/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + profileNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("profileName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.Get(req.Context(), resourceGroupNameParam, accountNameParam, profileNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CertificateProfile, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *CertificateProfilesServerTransport) dispatchNewListByCodeSigningAccountPager(req *http.Request) (*http.Response, error) { + if c.srv.NewListByCodeSigningAccountPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByCodeSigningAccountPager not implemented")} + } + newListByCodeSigningAccountPager := c.newListByCodeSigningAccountPager.get(req) + if newListByCodeSigningAccountPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CodeSigning/codeSigningAccounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/certificateProfiles` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + resp := c.srv.NewListByCodeSigningAccountPager(resourceGroupNameParam, accountNameParam, nil) + newListByCodeSigningAccountPager = &resp + c.newListByCodeSigningAccountPager.add(req, newListByCodeSigningAccountPager) + server.PagerResponderInjectNextLinks(newListByCodeSigningAccountPager, req, func(page *armcodesigning.CertificateProfilesClientListByCodeSigningAccountResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByCodeSigningAccountPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + c.newListByCodeSigningAccountPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByCodeSigningAccountPager) { + c.newListByCodeSigningAccountPager.remove(req) + } + return resp, nil +} + +func (c *CertificateProfilesServerTransport) dispatchRevokeCertificates(req *http.Request) (*http.Response, error) { + if c.srv.RevokeCertificates == nil { + return nil, &nonRetriableError{errors.New("fake for method RevokeCertificates not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CodeSigning/codeSigningAccounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/certificateProfiles/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/revokeCertificates` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcodesigning.RevokeCertificateList](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + profileNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("profileName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.RevokeCertificates(req.Context(), resourceGroupNameParam, accountNameParam, profileNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to CertificateProfilesServerTransport +var certificateProfilesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcodesigning/fake/zz_internal.go b/test/local/armcodesigning/fake/zz_internal.go new file mode 100644 index 000000000000..590b4d743e97 --- /dev/null +++ b/test/local/armcodesigning/fake/zz_internal.go @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/local/armcodesigning/fake/zz_operations_server.go b/test/local/armcodesigning/fake/zz_operations_server.go new file mode 100644 index 000000000000..8fe5cbda2a80 --- /dev/null +++ b/test/local/armcodesigning/fake/zz_operations_server.go @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcodesigning" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "slices" +) + +// OperationsServer is a fake server for instances of the armcodesigning.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armcodesigning.OperationsClientListOptions) (resp azfake.PagerResponder[armcodesigning.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of armcodesigning.OperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOperationsServerTransport(srv *OperationsServer) *OperationsServerTransport { + return &OperationsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armcodesigning.OperationsClientListResponse]](), + } +} + +// OperationsServerTransport connects instances of armcodesigning.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[armcodesigning.OperationsClientListResponse]] +} + +// Do implements the policy.Transporter interface for OperationsServerTransport. +func (o *OperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if operationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = operationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OperationsClient.NewListPager": + res.resp, res.err = o.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OperationsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := o.newListPager.get(req) + if newListPager == nil { + resp := o.srv.NewListPager(nil) + newListPager = &resp + o.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcodesigning.OperationsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + o.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + o.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OperationsServerTransport +var operationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcodesigning/fake/zz_server_factory.go b/test/local/armcodesigning/fake/zz_server_factory.go new file mode 100644 index 000000000000..e022a09ba6bb --- /dev/null +++ b/test/local/armcodesigning/fake/zz_server_factory.go @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armcodesigning.ClientFactory type. +type ServerFactory struct { + // AccountsServer contains the fakes for client AccountsClient + AccountsServer AccountsServer + + // CertificateProfilesServer contains the fakes for client CertificateProfilesClient + CertificateProfilesServer CertificateProfilesServer + + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armcodesigning.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of armcodesigning.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trAccountsServer *AccountsServerTransport + trCertificateProfilesServer *CertificateProfilesServerTransport + trOperationsServer *OperationsServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "AccountsClient": + initServer(&s.trMu, &s.trAccountsServer, func() *AccountsServerTransport { return NewAccountsServerTransport(&s.srv.AccountsServer) }) + resp, err = s.trAccountsServer.Do(req) + case "CertificateProfilesClient": + initServer(&s.trMu, &s.trCertificateProfilesServer, func() *CertificateProfilesServerTransport { + return NewCertificateProfilesServerTransport(&s.srv.CertificateProfilesServer) + }) + resp, err = s.trCertificateProfilesServer.Do(req) + case "OperationsClient": + initServer(&s.trMu, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + resp, err = s.trOperationsServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} diff --git a/test/local/armcodesigning/go.mod b/test/local/armcodesigning/go.mod new file mode 100644 index 000000000000..8014c5e2173e --- /dev/null +++ b/test/local/armcodesigning/go.mod @@ -0,0 +1,11 @@ +module armcodesigning + +go 1.25.0 + +require github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect +) diff --git a/test/local/armcodesigning/go.sum b/test/local/armcodesigning/go.sum new file mode 100644 index 000000000000..3fdb64caf441 --- /dev/null +++ b/test/local/armcodesigning/go.sum @@ -0,0 +1,16 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/local/armcodesigning/testdata/_metadata.json b/test/local/armcodesigning/testdata/_metadata.json new file mode 100644 index 000000000000..49467f856f24 --- /dev/null +++ b/test/local/armcodesigning/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Microsoft.CodeSigning": "2026-05-15-preview" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/local/armcodesigning/zz_accounts_client.go b/test/local/armcodesigning/zz_accounts_client.go new file mode 100644 index 000000000000..7c6feb4f7a94 --- /dev/null +++ b/test/local/armcodesigning/zz_accounts_client.go @@ -0,0 +1,496 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcodesigning + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// AccountsClient contains the methods for the Accounts group. +// Don't use this type directly, use NewAccountsClient() instead. +// +// Generated from API version 2026-05-15-preview +type AccountsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAccountsClient creates a new instance of AccountsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewAccountsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AccountsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AccountsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CheckNameAvailability - Checks if the artifact signing account name is valid and is not already in use. +// If the operation fails it returns an *azcore.ResponseError type. +// - body - The CheckAvailability request +// - options - AccountsClientCheckNameAvailabilityOptions contains the optional parameters for the AccountsClient.CheckNameAvailability +// method. +func (client *AccountsClient) CheckNameAvailability(ctx context.Context, body CheckNameAvailability, options *AccountsClientCheckNameAvailabilityOptions) (AccountsClientCheckNameAvailabilityResponse, error) { + var err error + const operationName = "AccountsClient.CheckNameAvailability" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.checkNameAvailabilityCreateRequest(ctx, body, options) + if err != nil { + return AccountsClientCheckNameAvailabilityResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AccountsClientCheckNameAvailabilityResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AccountsClientCheckNameAvailabilityResponse{}, err + } + resp, err := client.checkNameAvailabilityHandleResponse(httpResp) + return resp, err +} + +// checkNameAvailabilityCreateRequest creates the CheckNameAvailability request. +func (client *AccountsClient) checkNameAvailabilityCreateRequest(ctx context.Context, body CheckNameAvailability, _ *AccountsClientCheckNameAvailabilityOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CodeSigning/checkNameAvailability" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260515Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// checkNameAvailabilityHandleResponse handles the CheckNameAvailability response. +func (client *AccountsClient) checkNameAvailabilityHandleResponse(resp *http.Response) (AccountsClientCheckNameAvailabilityResponse, error) { + result := AccountsClientCheckNameAvailabilityResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CheckNameAvailabilityResult); err != nil { + return AccountsClientCheckNameAvailabilityResponse{}, err + } + return result, nil +} + +// BeginCreate - Create an artifact Signing Account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - Artifact Signing account name. +// - resource - Parameters to create the artifact signing account +// - options - AccountsClientBeginCreateOptions contains the optional parameters for the AccountsClient.BeginCreate method. +func (client *AccountsClient) BeginCreate(ctx context.Context, resourceGroupName string, accountName string, resource Account, options *AccountsClientBeginCreateOptions) (*runtime.Poller[AccountsClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, resourceGroupName, accountName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AccountsClientCreateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AccountsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Create an artifact Signing Account. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *AccountsClient) create(ctx context.Context, resourceGroupName string, accountName string, resource Account, options *AccountsClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "AccountsClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, accountName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *AccountsClient) createCreateRequest(ctx context.Context, resourceGroupName string, accountName string, resource Account, _ *AccountsClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260515Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete an artifact signing account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - Artifact Signing account name. +// - options - AccountsClientBeginDeleteOptions contains the optional parameters for the AccountsClient.BeginDelete method. +func (client *AccountsClient) BeginDelete(ctx context.Context, resourceGroupName string, accountName string, options *AccountsClientBeginDeleteOptions) (*runtime.Poller[AccountsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, accountName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AccountsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AccountsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete an artifact signing account. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *AccountsClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, options *AccountsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "AccountsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *AccountsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, _ *AccountsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260515Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get an artifact Signing Account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - Artifact Signing account name. +// - options - AccountsClientGetOptions contains the optional parameters for the AccountsClient.Get method. +func (client *AccountsClient) Get(ctx context.Context, resourceGroupName string, accountName string, options *AccountsClientGetOptions) (AccountsClientGetResponse, error) { + var err error + const operationName = "AccountsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return AccountsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AccountsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AccountsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *AccountsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, _ *AccountsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260515Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *AccountsClient) getHandleResponse(resp *http.Response) (AccountsClientGetResponse, error) { + result := AccountsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Account); err != nil { + return AccountsClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Lists artifact signing accounts within a resource group. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - AccountsClientListByResourceGroupOptions contains the optional parameters for the AccountsClient.NewListByResourceGroupPager +// method. +func (client *AccountsClient) NewListByResourceGroupPager(resourceGroupName string, options *AccountsClientListByResourceGroupOptions) *runtime.Pager[AccountsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[AccountsClientListByResourceGroupResponse]{ + More: func(page AccountsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AccountsClientListByResourceGroupResponse) (AccountsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AccountsClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return AccountsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *AccountsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *AccountsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260515Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *AccountsClient) listByResourceGroupHandleResponse(resp *http.Response) (AccountsClientListByResourceGroupResponse, error) { + result := AccountsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AccountListResult); err != nil { + return AccountsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - Lists artifact signing accounts within a subscription. +// - options - AccountsClientListBySubscriptionOptions contains the optional parameters for the AccountsClient.NewListBySubscriptionPager +// method. +func (client *AccountsClient) NewListBySubscriptionPager(options *AccountsClientListBySubscriptionOptions) *runtime.Pager[AccountsClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[AccountsClientListBySubscriptionResponse]{ + More: func(page AccountsClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AccountsClientListBySubscriptionResponse) (AccountsClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AccountsClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return AccountsClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *AccountsClient) listBySubscriptionCreateRequest(ctx context.Context, _ *AccountsClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CodeSigning/codeSigningAccounts" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260515Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *AccountsClient) listBySubscriptionHandleResponse(resp *http.Response) (AccountsClientListBySubscriptionResponse, error) { + result := AccountsClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AccountListResult); err != nil { + return AccountsClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update an artifact signing account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - Artifact Signing account name. +// - properties - Parameters supplied to update the artifact signing account +// - options - AccountsClientBeginUpdateOptions contains the optional parameters for the AccountsClient.BeginUpdate method. +func (client *AccountsClient) BeginUpdate(ctx context.Context, resourceGroupName string, accountName string, properties AccountPatch, options *AccountsClientBeginUpdateOptions) (*runtime.Poller[AccountsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, accountName, properties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AccountsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AccountsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update an artifact signing account. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *AccountsClient) update(ctx context.Context, resourceGroupName string, accountName string, properties AccountPatch, options *AccountsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "AccountsClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, accountName, properties, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *AccountsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, properties AccountPatch, _ *AccountsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260515Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armcodesigning/zz_certificateprofiles_client.go b/test/local/armcodesigning/zz_certificateprofiles_client.go new file mode 100644 index 000000000000..6b708510a980 --- /dev/null +++ b/test/local/armcodesigning/zz_certificateprofiles_client.go @@ -0,0 +1,393 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcodesigning + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// CertificateProfilesClient contains the methods for the CertificateProfiles group. +// Don't use this type directly, use NewCertificateProfilesClient() instead. +// +// Generated from API version 2026-05-15-preview +type CertificateProfilesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewCertificateProfilesClient creates a new instance of CertificateProfilesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewCertificateProfilesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CertificateProfilesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CertificateProfilesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreate - Create a certificate profile. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - Artifact Signing account name. +// - profileName - Certificate profile name. +// - resource - Parameters to create the certificate profile +// - options - CertificateProfilesClientBeginCreateOptions contains the optional parameters for the CertificateProfilesClient.BeginCreate +// method. +func (client *CertificateProfilesClient) BeginCreate(ctx context.Context, resourceGroupName string, accountName string, profileName string, resource CertificateProfile, options *CertificateProfilesClientBeginCreateOptions) (*runtime.Poller[CertificateProfilesClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, resourceGroupName, accountName, profileName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CertificateProfilesClientCreateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CertificateProfilesClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Create a certificate profile. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CertificateProfilesClient) create(ctx context.Context, resourceGroupName string, accountName string, profileName string, resource CertificateProfile, options *CertificateProfilesClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "CertificateProfilesClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, accountName, profileName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *CertificateProfilesClient) createCreateRequest(ctx context.Context, resourceGroupName string, accountName string, profileName string, resource CertificateProfile, _ *CertificateProfilesClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if profileName == "" { + return nil, errors.New("parameter profileName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{profileName}", url.PathEscape(profileName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260515Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a certificate profile. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - Artifact Signing account name. +// - profileName - Certificate profile name. +// - options - CertificateProfilesClientBeginDeleteOptions contains the optional parameters for the CertificateProfilesClient.BeginDelete +// method. +func (client *CertificateProfilesClient) BeginDelete(ctx context.Context, resourceGroupName string, accountName string, profileName string, options *CertificateProfilesClientBeginDeleteOptions) (*runtime.Poller[CertificateProfilesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, accountName, profileName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CertificateProfilesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CertificateProfilesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a certificate profile. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CertificateProfilesClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, profileName string, options *CertificateProfilesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "CertificateProfilesClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, profileName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *CertificateProfilesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, profileName string, _ *CertificateProfilesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if profileName == "" { + return nil, errors.New("parameter profileName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{profileName}", url.PathEscape(profileName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260515Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get details of a certificate profile. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - Artifact Signing account name. +// - profileName - Certificate profile name. +// - options - CertificateProfilesClientGetOptions contains the optional parameters for the CertificateProfilesClient.Get method. +func (client *CertificateProfilesClient) Get(ctx context.Context, resourceGroupName string, accountName string, profileName string, options *CertificateProfilesClientGetOptions) (CertificateProfilesClientGetResponse, error) { + var err error + const operationName = "CertificateProfilesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, profileName, options) + if err != nil { + return CertificateProfilesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CertificateProfilesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CertificateProfilesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *CertificateProfilesClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, profileName string, _ *CertificateProfilesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if profileName == "" { + return nil, errors.New("parameter profileName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{profileName}", url.PathEscape(profileName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260515Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *CertificateProfilesClient) getHandleResponse(resp *http.Response) (CertificateProfilesClientGetResponse, error) { + result := CertificateProfilesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CertificateProfile); err != nil { + return CertificateProfilesClientGetResponse{}, err + } + return result, nil +} + +// NewListByCodeSigningAccountPager - List certificate profiles under an artifact signing account. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - Artifact Signing account name. +// - options - CertificateProfilesClientListByCodeSigningAccountOptions contains the optional parameters for the CertificateProfilesClient.NewListByCodeSigningAccountPager +// method. +func (client *CertificateProfilesClient) NewListByCodeSigningAccountPager(resourceGroupName string, accountName string, options *CertificateProfilesClientListByCodeSigningAccountOptions) *runtime.Pager[CertificateProfilesClientListByCodeSigningAccountResponse] { + return runtime.NewPager(runtime.PagingHandler[CertificateProfilesClientListByCodeSigningAccountResponse]{ + More: func(page CertificateProfilesClientListByCodeSigningAccountResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CertificateProfilesClientListByCodeSigningAccountResponse) (CertificateProfilesClientListByCodeSigningAccountResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CertificateProfilesClient.NewListByCodeSigningAccountPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByCodeSigningAccountCreateRequest(ctx, resourceGroupName, accountName, options) + }, nil) + if err != nil { + return CertificateProfilesClientListByCodeSigningAccountResponse{}, err + } + return client.listByCodeSigningAccountHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByCodeSigningAccountCreateRequest creates the ListByCodeSigningAccount request. +func (client *CertificateProfilesClient) listByCodeSigningAccountCreateRequest(ctx context.Context, resourceGroupName string, accountName string, _ *CertificateProfilesClientListByCodeSigningAccountOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260515Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByCodeSigningAccountHandleResponse handles the ListByCodeSigningAccount response. +func (client *CertificateProfilesClient) listByCodeSigningAccountHandleResponse(resp *http.Response) (CertificateProfilesClientListByCodeSigningAccountResponse, error) { + result := CertificateProfilesClientListByCodeSigningAccountResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CertificateProfileListResult); err != nil { + return CertificateProfilesClientListByCodeSigningAccountResponse{}, err + } + return result, nil +} + +// RevokeCertificates - Revokes certificates under a certificate profile. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - Artifact Signing account name. +// - profileName - Certificate profile name. +// - body - Parameters to revoke the certificates in the certificate profile +// - options - CertificateProfilesClientRevokeCertificatesOptions contains the optional parameters for the CertificateProfilesClient.RevokeCertificates +// method. +func (client *CertificateProfilesClient) RevokeCertificates(ctx context.Context, resourceGroupName string, accountName string, profileName string, body RevokeCertificateList, options *CertificateProfilesClientRevokeCertificatesOptions) (CertificateProfilesClientRevokeCertificatesResponse, error) { + var err error + const operationName = "CertificateProfilesClient.RevokeCertificates" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.revokeCertificatesCreateRequest(ctx, resourceGroupName, accountName, profileName, body, options) + if err != nil { + return CertificateProfilesClientRevokeCertificatesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CertificateProfilesClientRevokeCertificatesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return CertificateProfilesClientRevokeCertificatesResponse{}, err + } + return CertificateProfilesClientRevokeCertificatesResponse{}, nil +} + +// revokeCertificatesCreateRequest creates the RevokeCertificates request. +func (client *CertificateProfilesClient) revokeCertificatesCreateRequest(ctx context.Context, resourceGroupName string, accountName string, profileName string, body RevokeCertificateList, _ *CertificateProfilesClientRevokeCertificatesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}/revokeCertificates" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if profileName == "" { + return nil, errors.New("parameter profileName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{profileName}", url.PathEscape(profileName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260515Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armcodesigning/zz_client_factory.go b/test/local/armcodesigning/zz_client_factory.go new file mode 100644 index 000000000000..c1562cd16ae4 --- /dev/null +++ b/test/local/armcodesigning/zz_client_factory.go @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcodesigning + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + subscriptionID string + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, + internal: internal, + }, nil +} + +// NewAccountsClient creates a new instance of AccountsClient. +func (c *ClientFactory) NewAccountsClient() *AccountsClient { + return &AccountsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewCertificateProfilesClient creates a new instance of CertificateProfilesClient. +func (c *ClientFactory) NewCertificateProfilesClient() *CertificateProfilesClient { + return &CertificateProfilesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: c.internal, + } +} diff --git a/test/local/armcodesigning/zz_constants.go b/test/local/armcodesigning/zz_constants.go new file mode 100644 index 000000000000..9ff39de8830e --- /dev/null +++ b/test/local/armcodesigning/zz_constants.go @@ -0,0 +1,227 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcodesigning + +const ( + version20260515Preview string = "2026-05-15-preview" +) + +// ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +type ActionType string + +const ( + // ActionTypeInternal - Actions are for internal-only APIs. + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// CertificateProfileStatus - Status of the certificate profiles. +type CertificateProfileStatus string + +const ( + // CertificateProfileStatusActive - The certificate profile is active. + CertificateProfileStatusActive CertificateProfileStatus = "Active" + // CertificateProfileStatusDisabled - The certificate profile is disabled. + CertificateProfileStatusDisabled CertificateProfileStatus = "Disabled" + // CertificateProfileStatusSuspended - The certificate profile is suspended. + CertificateProfileStatusSuspended CertificateProfileStatus = "Suspended" +) + +// PossibleCertificateProfileStatusValues returns the possible values for the CertificateProfileStatus const type. +func PossibleCertificateProfileStatusValues() []CertificateProfileStatus { + return []CertificateProfileStatus{ + CertificateProfileStatusActive, + CertificateProfileStatusDisabled, + CertificateProfileStatusSuspended, + } +} + +// CertificateStatus - Status of the certificate +type CertificateStatus string + +const ( + // CertificateStatusActive - The certificate is active. + CertificateStatusActive CertificateStatus = "Active" + // CertificateStatusExpired - The certificate is expired. + CertificateStatusExpired CertificateStatus = "Expired" + // CertificateStatusRevoked - The certificate is revoked. + CertificateStatusRevoked CertificateStatus = "Revoked" +) + +// PossibleCertificateStatusValues returns the possible values for the CertificateStatus const type. +func PossibleCertificateStatusValues() []CertificateStatus { + return []CertificateStatus{ + CertificateStatusActive, + CertificateStatusExpired, + CertificateStatusRevoked, + } +} + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// NameUnavailabilityReason - The reason that an artifact signing account name could not be used. The Reason element is only +// returned if nameAvailable is false. +type NameUnavailabilityReason string + +const ( + // NameUnavailabilityReasonAccountNameInvalid - Account name is invalid + NameUnavailabilityReasonAccountNameInvalid NameUnavailabilityReason = "AccountNameInvalid" + // NameUnavailabilityReasonAlreadyExists - Account name already exists + NameUnavailabilityReasonAlreadyExists NameUnavailabilityReason = "AlreadyExists" +) + +// PossibleNameUnavailabilityReasonValues returns the possible values for the NameUnavailabilityReason const type. +func PossibleNameUnavailabilityReasonValues() []NameUnavailabilityReason { + return []NameUnavailabilityReason{ + NameUnavailabilityReasonAccountNameInvalid, + NameUnavailabilityReasonAlreadyExists, + } +} + +// Origin - The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default +// value is "user,system" +type Origin string + +const ( + // OriginSystem - Indicates the operation is initiated by a system. + OriginSystem Origin = "system" + // OriginUser - Indicates the operation is initiated by a user. + OriginUser Origin = "user" + // OriginUserSystem - Indicates the operation is initiated by a user or system. + OriginUserSystem Origin = "user,system" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginSystem, + OriginUser, + OriginUserSystem, + } +} + +// ProfileType - Type of the certificate +type ProfileType string + +const ( + // ProfileTypePrivateTrust - Used for signing files which are distributed internally within organization or group boundary. + ProfileTypePrivateTrust ProfileType = "PrivateTrust" + // ProfileTypePrivateTrustCIPolicy - Used for signing CI policy files. + ProfileTypePrivateTrustCIPolicy ProfileType = "PrivateTrustCIPolicy" + // ProfileTypePublicTrust - Used for signing files which are distributed publicly. + ProfileTypePublicTrust ProfileType = "PublicTrust" + // ProfileTypePublicTrustTest - Used for signing files for testing purpose. + ProfileTypePublicTrustTest ProfileType = "PublicTrustTest" + // ProfileTypeVBSEnclave - Used for signing files which are run in secure vbs enclave. + ProfileTypeVBSEnclave ProfileType = "VBSEnclave" +) + +// PossibleProfileTypeValues returns the possible values for the ProfileType const type. +func PossibleProfileTypeValues() []ProfileType { + return []ProfileType{ + ProfileTypePrivateTrust, + ProfileTypePrivateTrustCIPolicy, + ProfileTypePublicTrust, + ProfileTypePublicTrustTest, + ProfileTypeVBSEnclave, + } +} + +// ProvisioningState - The status of the current operation. +type ProvisioningState string + +const ( + // ProvisioningStateAccepted - Resource creation started. + ProvisioningStateAccepted ProvisioningState = "Accepted" + // ProvisioningStateCanceled - Resource creation was canceled. + ProvisioningStateCanceled ProvisioningState = "Canceled" + // ProvisioningStateDeleting - Deletion in progress. + ProvisioningStateDeleting ProvisioningState = "Deleting" + // ProvisioningStateFailed - Resource creation failed. + ProvisioningStateFailed ProvisioningState = "Failed" + // ProvisioningStateSucceeded - Resource has been created. + ProvisioningStateSucceeded ProvisioningState = "Succeeded" + // ProvisioningStateUpdating - Updating in progress. + ProvisioningStateUpdating ProvisioningState = "Updating" +) + +// PossibleProvisioningStateValues returns the possible values for the ProvisioningState const type. +func PossibleProvisioningStateValues() []ProvisioningState { + return []ProvisioningState{ + ProvisioningStateAccepted, + ProvisioningStateCanceled, + ProvisioningStateDeleting, + ProvisioningStateFailed, + ProvisioningStateSucceeded, + ProvisioningStateUpdating, + } +} + +// RevocationStatus - Revocation status of the certificate. +type RevocationStatus string + +const ( + // RevocationStatusFailed - Certificate revocation failed. + RevocationStatusFailed RevocationStatus = "Failed" + // RevocationStatusInProgress - Certificate revocation is in progress. + RevocationStatusInProgress RevocationStatus = "InProgress" + // RevocationStatusSucceeded - Certificate revocation succeeded. + RevocationStatusSucceeded RevocationStatus = "Succeeded" +) + +// PossibleRevocationStatusValues returns the possible values for the RevocationStatus const type. +func PossibleRevocationStatusValues() []RevocationStatus { + return []RevocationStatus{ + RevocationStatusFailed, + RevocationStatusInProgress, + RevocationStatusSucceeded, + } +} + +// SKUName - Name of the sku. +type SKUName string + +const ( + // SKUNameBasic - Basic sku. + SKUNameBasic SKUName = "Basic" + // SKUNamePremium - Premium sku. + SKUNamePremium SKUName = "Premium" +) + +// PossibleSKUNameValues returns the possible values for the SKUName const type. +func PossibleSKUNameValues() []SKUName { + return []SKUName{ + SKUNameBasic, + SKUNamePremium, + } +} diff --git a/test/local/armcodesigning/zz_models.go b/test/local/armcodesigning/zz_models.go new file mode 100644 index 000000000000..b13cb48fea02 --- /dev/null +++ b/test/local/armcodesigning/zz_models.go @@ -0,0 +1,309 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcodesigning + +import "time" + +// Account - Artifact signing account resource. +type Account struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *AccountProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// AccountListResult - The response of a CodeSigningAccount list operation. +type AccountListResult struct { + // REQUIRED; The CodeSigningAccount items on this page + Value []*Account + + // The link to the next page of items + NextLink *string +} + +// AccountPatch - Parameters for creating or updating an artifact signing account. +type AccountPatch struct { + // Properties of the artifact signing account. + Properties *AccountPatchProperties + + // Resource tags. + Tags map[string]*string +} + +// AccountPatchProperties - Properties of the artifact signing account. +type AccountPatchProperties struct { + // SKU of the artifact signing account. + SKU *AccountSKUPatch +} + +// AccountProperties - Properties of the artifact signing account. +type AccountProperties struct { + // SKU of the artifact signing account. + SKU *AccountSKU + + // READ-ONLY; The URI of the artifact signing account which is used during signing files. + AccountURI *string + + // READ-ONLY; Status of the current operation on artifact signing account. + ProvisioningState *ProvisioningState +} + +// AccountSKU - SKU of the artifact signing account. +type AccountSKU struct { + // REQUIRED; Name of the SKU. + Name *SKUName +} + +// AccountSKUPatch - SKU of the artifact signing account. +type AccountSKUPatch struct { + // Name of the SKU. + Name *SKUName +} + +// Certificate - Properties of the certificate. +type Certificate struct { + // Certificate created date. + CreatedDate *string + + // Enhanced key usage of the certificate. + EnhancedKeyUsage *string + + // Certificate expiry date. + ExpiryDate *string + + // Revocations history of a certificate. + Revocation *Revocation + + // Serial number of the certificate. + SerialNumber *string + + // Status of the certificate. + Status *CertificateStatus + + // Subject name of the certificate. + SubjectName *string + + // Thumbprint of the certificate. + Thumbprint *string +} + +// CertificateProfile - Certificate profile resource. +type CertificateProfile struct { + // The resource-specific properties for this resource. + Properties *CertificateProfileProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// CertificateProfileListResult - The response of a CertificateProfile list operation. +type CertificateProfileListResult struct { + // REQUIRED; The CertificateProfile items on this page + Value []*CertificateProfile + + // The link to the next page of items + NextLink *string +} + +// CertificateProfileProperties - Properties of the certificate profile. +type CertificateProfileProperties struct { + // REQUIRED; Identity validation id used for the certificate subject name. + IdentityValidationID *string + + // REQUIRED; Profile type of the certificate. + ProfileType *ProfileType + + // Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types + IncludeCity *bool + + // Whether to include C in the certificate subject name. Applicable only for private trust, private trust ci profile types + IncludeCountry *bool + + // Whether to include PC in the certificate subject name. + IncludePostalCode *bool + + // Whether to include S in the certificate subject name. Applicable only for private trust, private trust ci profile types + IncludeState *bool + + // Whether to include STREET in the certificate subject name. + IncludeStreetAddress *bool + + // Indicates whether the resource is intended for a specific usage scenario. + ProgramType *string + + // READ-ONLY; List of renewed certificates. + Certificates []*Certificate + + // READ-ONLY; Status of the current operation on certificate profile. + ProvisioningState *ProvisioningState + + // READ-ONLY; Status of the certificate profile. + Status *CertificateProfileStatus +} + +// CheckNameAvailability - The parameters used to check the availability of the artifact signing account name. +type CheckNameAvailability struct { + // REQUIRED; Artifact signing account name. + Name *string + + // REQUIRED; The type of the resource, "Microsoft.CodeSigning/codeSigningAccounts". + Type *string +} + +// CheckNameAvailabilityResult - The CheckNameAvailability operation response. +type CheckNameAvailabilityResult struct { + // READ-ONLY; An error message explaining the Reason value in more detail. + Message *string + + // READ-ONLY; A boolean value that indicates whether the name is available for you to use. If true, the name is available. + // If false, the name has already been taken or is invalid and cannot be used. + NameAvailable *bool + + // READ-ONLY; The reason that an artifact signing account name could not be used. The Reason element is only returned if nameAvailable + // is false. + Reason *NameUnavailabilityReason +} + +// Operation - REST API Operation +// +// Details of a REST API operation, returned from the Resource Provider Operations API +type Operation struct { + // Localized display information for this particular operation. + Display *OperationDisplay + + // READ-ONLY; Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + ActionType *ActionType + + // READ-ONLY; Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure + // Resource Manager/control-plane operations. + IsDataAction *bool + + // READ-ONLY; The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + // "Microsoft.Compute/virtualMachines/capture/action" + Name *string + + // READ-ONLY; The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default + // value is "user,system" + Origin *Origin +} + +// OperationDisplay - Localized display information for an operation. +type OperationDisplay struct { + // READ-ONLY; The short, localized friendly description of the operation; suitable for tool tips and detailed views. + Description *string + + // READ-ONLY; The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual + // Machine", "Restart Virtual Machine". + Operation *string + + // READ-ONLY; The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft + // Compute". + Provider *string + + // READ-ONLY; The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job + // Schedule Collections". + Resource *string +} + +// OperationListResult - A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to +// get the next set of results. +type OperationListResult struct { + // REQUIRED; The Operation items on this page + Value []*Operation + + // The link to the next page of items + NextLink *string +} + +// Revocation details of the certificate. +type Revocation struct { + // The timestamp when the revocation is effective. + EffectiveAt *time.Time + + // Reason for the revocation failure. + FailureReason *string + + // Reason for revocation. + Reason *string + + // Remarks for the revocation. + Remarks *string + + // The timestamp when the revocation is requested. + RequestedAt *time.Time + + // Status of the revocation. + Status *RevocationStatus +} + +// RevokeCertificate - Defines the certificate revocation properties. +type RevokeCertificate struct { + // REQUIRED; The timestamp when the revocation is effective. + EffectiveAt *time.Time + + // REQUIRED; Reason for the revocation. + Reason *string + + // REQUIRED; Serial number of the certificate. + SerialNumber *string + + // REQUIRED; Thumbprint of the certificate. + Thumbprint *string + + // Remarks for the revocation. + Remarks *string +} + +// RevokeCertificateList - Defines the list of certificates for revocation in certificate profile. +type RevokeCertificateList struct { + // REQUIRED; List of certificates to be revoked in a certificate profile. + RevokeCertificates []*RevokeCertificate +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time + + // The identity that created the resource. + CreatedBy *string + + // The type of identity that created the resource. + CreatedByType *CreatedByType + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time + + // The identity that last modified the resource. + LastModifiedBy *string + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType +} diff --git a/test/local/armcodesigning/zz_models_serde.go b/test/local/armcodesigning/zz_models_serde.go new file mode 100644 index 000000000000..0a2f9bb83ed8 --- /dev/null +++ b/test/local/armcodesigning/zz_models_serde.go @@ -0,0 +1,830 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcodesigning + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type Account. +func (a Account) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "location", a.Location) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "tags", a.Tags) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Account. +func (a *Account) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &a.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &a.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &a.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountListResult. +func (a AccountListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountListResult. +func (a *AccountListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &a.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountPatch. +func (a AccountPatch) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "tags", a.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountPatch. +func (a *AccountPatch) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &a.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountPatchProperties. +func (a AccountPatchProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "sku", a.SKU) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountPatchProperties. +func (a *AccountPatchProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "sku": + err = unpopulate(val, "SKU", &a.SKU) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountProperties. +func (a AccountProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "accountUri", a.AccountURI) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "sku", a.SKU) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountProperties. +func (a *AccountProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "accountUri": + err = unpopulate(val, "AccountURI", &a.AccountURI) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &a.SKU) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountSKU. +func (a AccountSKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", a.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountSKU. +func (a *AccountSKU) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountSKUPatch. +func (a AccountSKUPatch) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", a.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountSKUPatch. +func (a *AccountSKUPatch) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Certificate. +func (c Certificate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "createdDate", c.CreatedDate) + populate(objectMap, "enhancedKeyUsage", c.EnhancedKeyUsage) + populate(objectMap, "expiryDate", c.ExpiryDate) + populate(objectMap, "revocation", c.Revocation) + populate(objectMap, "serialNumber", c.SerialNumber) + populate(objectMap, "status", c.Status) + populate(objectMap, "subjectName", c.SubjectName) + populate(objectMap, "thumbprint", c.Thumbprint) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Certificate. +func (c *Certificate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdDate": + err = unpopulate(val, "CreatedDate", &c.CreatedDate) + delete(rawMsg, key) + case "enhancedKeyUsage": + err = unpopulate(val, "EnhancedKeyUsage", &c.EnhancedKeyUsage) + delete(rawMsg, key) + case "expiryDate": + err = unpopulate(val, "ExpiryDate", &c.ExpiryDate) + delete(rawMsg, key) + case "revocation": + err = unpopulate(val, "Revocation", &c.Revocation) + delete(rawMsg, key) + case "serialNumber": + err = unpopulate(val, "SerialNumber", &c.SerialNumber) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &c.Status) + delete(rawMsg, key) + case "subjectName": + err = unpopulate(val, "SubjectName", &c.SubjectName) + delete(rawMsg, key) + case "thumbprint": + err = unpopulate(val, "Thumbprint", &c.Thumbprint) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CertificateProfile. +func (c CertificateProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", c.ID) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "systemData", c.SystemData) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CertificateProfile. +func (c *CertificateProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &c.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CertificateProfileListResult. +func (c CertificateProfileListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", c.NextLink) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CertificateProfileListResult. +func (c *CertificateProfileListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &c.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &c.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CertificateProfileProperties. +func (c CertificateProfileProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "certificates", c.Certificates) + populate(objectMap, "identityValidationId", c.IdentityValidationID) + populate(objectMap, "includeCity", c.IncludeCity) + populate(objectMap, "includeCountry", c.IncludeCountry) + populate(objectMap, "includePostalCode", c.IncludePostalCode) + populate(objectMap, "includeState", c.IncludeState) + populate(objectMap, "includeStreetAddress", c.IncludeStreetAddress) + populate(objectMap, "profileType", c.ProfileType) + populate(objectMap, "programType", c.ProgramType) + populate(objectMap, "provisioningState", c.ProvisioningState) + populate(objectMap, "status", c.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CertificateProfileProperties. +func (c *CertificateProfileProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "certificates": + err = unpopulate(val, "Certificates", &c.Certificates) + delete(rawMsg, key) + case "identityValidationId": + err = unpopulate(val, "IdentityValidationID", &c.IdentityValidationID) + delete(rawMsg, key) + case "includeCity": + err = unpopulate(val, "IncludeCity", &c.IncludeCity) + delete(rawMsg, key) + case "includeCountry": + err = unpopulate(val, "IncludeCountry", &c.IncludeCountry) + delete(rawMsg, key) + case "includePostalCode": + err = unpopulate(val, "IncludePostalCode", &c.IncludePostalCode) + delete(rawMsg, key) + case "includeState": + err = unpopulate(val, "IncludeState", &c.IncludeState) + delete(rawMsg, key) + case "includeStreetAddress": + err = unpopulate(val, "IncludeStreetAddress", &c.IncludeStreetAddress) + delete(rawMsg, key) + case "profileType": + err = unpopulate(val, "ProfileType", &c.ProfileType) + delete(rawMsg, key) + case "programType": + err = unpopulate(val, "ProgramType", &c.ProgramType) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &c.ProvisioningState) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &c.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CheckNameAvailability. +func (c CheckNameAvailability) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", c.Name) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CheckNameAvailability. +func (c *CheckNameAvailability) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CheckNameAvailabilityResult. +func (c CheckNameAvailabilityResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "message", c.Message) + populate(objectMap, "nameAvailable", c.NameAvailable) + populate(objectMap, "reason", c.Reason) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CheckNameAvailabilityResult. +func (c *CheckNameAvailabilityResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "message": + err = unpopulate(val, "Message", &c.Message) + delete(rawMsg, key) + case "nameAvailable": + err = unpopulate(val, "NameAvailable", &c.NameAvailable) + delete(rawMsg, key) + case "reason": + err = unpopulate(val, "Reason", &c.Reason) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Operation. +func (o Operation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionType", o.ActionType) + populate(objectMap, "display", o.Display) + populate(objectMap, "isDataAction", o.IsDataAction) + populate(objectMap, "name", o.Name) + populate(objectMap, "origin", o.Origin) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Operation. +func (o *Operation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionType": + err = unpopulate(val, "ActionType", &o.ActionType) + delete(rawMsg, key) + case "display": + err = unpopulate(val, "Display", &o.Display) + delete(rawMsg, key) + case "isDataAction": + err = unpopulate(val, "IsDataAction", &o.IsDataAction) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "origin": + err = unpopulate(val, "Origin", &o.Origin) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationDisplay. +func (o OperationDisplay) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", o.Description) + populate(objectMap, "operation", o.Operation) + populate(objectMap, "provider", o.Provider) + populate(objectMap, "resource", o.Resource) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationDisplay. +func (o *OperationDisplay) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &o.Description) + delete(rawMsg, key) + case "operation": + err = unpopulate(val, "Operation", &o.Operation) + delete(rawMsg, key) + case "provider": + err = unpopulate(val, "Provider", &o.Provider) + delete(rawMsg, key) + case "resource": + err = unpopulate(val, "Resource", &o.Resource) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationListResult. +func (o *OperationListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &o.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Revocation. +func (r Revocation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "effectiveAt", r.EffectiveAt) + populate(objectMap, "failureReason", r.FailureReason) + populate(objectMap, "reason", r.Reason) + populate(objectMap, "remarks", r.Remarks) + populateTime[datetime.RFC3339](objectMap, "requestedAt", r.RequestedAt) + populate(objectMap, "status", r.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Revocation. +func (r *Revocation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "effectiveAt": + err = unpopulateTime[datetime.RFC3339](val, "EffectiveAt", &r.EffectiveAt) + delete(rawMsg, key) + case "failureReason": + err = unpopulate(val, "FailureReason", &r.FailureReason) + delete(rawMsg, key) + case "reason": + err = unpopulate(val, "Reason", &r.Reason) + delete(rawMsg, key) + case "remarks": + err = unpopulate(val, "Remarks", &r.Remarks) + delete(rawMsg, key) + case "requestedAt": + err = unpopulateTime[datetime.RFC3339](val, "RequestedAt", &r.RequestedAt) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &r.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RevokeCertificate. +func (r RevokeCertificate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "effectiveAt", r.EffectiveAt) + populate(objectMap, "reason", r.Reason) + populate(objectMap, "remarks", r.Remarks) + populate(objectMap, "serialNumber", r.SerialNumber) + populate(objectMap, "thumbprint", r.Thumbprint) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RevokeCertificate. +func (r *RevokeCertificate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "effectiveAt": + err = unpopulateTime[datetime.RFC3339](val, "EffectiveAt", &r.EffectiveAt) + delete(rawMsg, key) + case "reason": + err = unpopulate(val, "Reason", &r.Reason) + delete(rawMsg, key) + case "remarks": + err = unpopulate(val, "Remarks", &r.Remarks) + delete(rawMsg, key) + case "serialNumber": + err = unpopulate(val, "SerialNumber", &r.SerialNumber) + delete(rawMsg, key) + case "thumbprint": + err = unpopulate(val, "Thumbprint", &r.Thumbprint) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RevokeCertificateList. +func (r RevokeCertificateList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "revokeCertificates", r.RevokeCertificates) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RevokeCertificateList. +func (r *RevokeCertificateList) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "revokeCertificates": + err = unpopulate(val, "RevokeCertificates", &r.RevokeCertificates) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateTime[datetime.RFC3339](objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateTime[datetime.RFC3339](val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateTime[datetime.RFC3339](val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/local/armcodesigning/zz_operations_client.go b/test/local/armcodesigning/zz_operations_client.go new file mode 100644 index 000000000000..4e92e8977fde --- /dev/null +++ b/test/local/armcodesigning/zz_operations_client.go @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcodesigning + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +// +// Generated from API version 2026-05-15-preview +type OperationsClient struct { + internal *arm.Client +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*OperationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OperationsClient{ + internal: cl, + } + return client, nil +} + +// NewListPager - List the operations for the provider +// - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ + More: func(page OperationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OperationsClientListResponse) (OperationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OperationsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return OperationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, _ *OperationsClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.CodeSigning/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260515Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsClientListResponse, error) { + result := OperationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armcodesigning/zz_options.go b/test/local/armcodesigning/zz_options.go new file mode 100644 index 000000000000..a94797e554db --- /dev/null +++ b/test/local/armcodesigning/zz_options.go @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcodesigning + +// AccountsClientBeginCreateOptions contains the optional parameters for the AccountsClient.BeginCreate method. +type AccountsClientBeginCreateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// AccountsClientBeginDeleteOptions contains the optional parameters for the AccountsClient.BeginDelete method. +type AccountsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// AccountsClientBeginUpdateOptions contains the optional parameters for the AccountsClient.BeginUpdate method. +type AccountsClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// AccountsClientCheckNameAvailabilityOptions contains the optional parameters for the AccountsClient.CheckNameAvailability +// method. +type AccountsClientCheckNameAvailabilityOptions struct { + // placeholder for future optional parameters +} + +// AccountsClientGetOptions contains the optional parameters for the AccountsClient.Get method. +type AccountsClientGetOptions struct { + // placeholder for future optional parameters +} + +// AccountsClientListByResourceGroupOptions contains the optional parameters for the AccountsClient.NewListByResourceGroupPager +// method. +type AccountsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// AccountsClientListBySubscriptionOptions contains the optional parameters for the AccountsClient.NewListBySubscriptionPager +// method. +type AccountsClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// CertificateProfilesClientBeginCreateOptions contains the optional parameters for the CertificateProfilesClient.BeginCreate +// method. +type CertificateProfilesClientBeginCreateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CertificateProfilesClientBeginDeleteOptions contains the optional parameters for the CertificateProfilesClient.BeginDelete +// method. +type CertificateProfilesClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CertificateProfilesClientGetOptions contains the optional parameters for the CertificateProfilesClient.Get method. +type CertificateProfilesClientGetOptions struct { + // placeholder for future optional parameters +} + +// CertificateProfilesClientListByCodeSigningAccountOptions contains the optional parameters for the CertificateProfilesClient.NewListByCodeSigningAccountPager +// method. +type CertificateProfilesClientListByCodeSigningAccountOptions struct { + // placeholder for future optional parameters +} + +// CertificateProfilesClientRevokeCertificatesOptions contains the optional parameters for the CertificateProfilesClient.RevokeCertificates +// method. +type CertificateProfilesClientRevokeCertificatesOptions struct { + // placeholder for future optional parameters +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} diff --git a/test/local/armcodesigning/zz_responses.go b/test/local/armcodesigning/zz_responses.go new file mode 100644 index 000000000000..24623b681c9c --- /dev/null +++ b/test/local/armcodesigning/zz_responses.go @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcodesigning + +// AccountsClientCheckNameAvailabilityResponse contains the response from method AccountsClient.CheckNameAvailability. +type AccountsClientCheckNameAvailabilityResponse struct { + // The CheckNameAvailability operation response. + CheckNameAvailabilityResult +} + +// AccountsClientCreateResponse contains the response from method AccountsClient.BeginCreate. +type AccountsClientCreateResponse struct { + // Artifact signing account resource. + Account +} + +// AccountsClientDeleteResponse contains the response from method AccountsClient.BeginDelete. +type AccountsClientDeleteResponse struct { + // placeholder for future response values +} + +// AccountsClientGetResponse contains the response from method AccountsClient.Get. +type AccountsClientGetResponse struct { + // Artifact signing account resource. + Account +} + +// AccountsClientListByResourceGroupResponse contains the response from method AccountsClient.NewListByResourceGroupPager. +type AccountsClientListByResourceGroupResponse struct { + // The response of a CodeSigningAccount list operation. + AccountListResult +} + +// AccountsClientListBySubscriptionResponse contains the response from method AccountsClient.NewListBySubscriptionPager. +type AccountsClientListBySubscriptionResponse struct { + // The response of a CodeSigningAccount list operation. + AccountListResult +} + +// AccountsClientUpdateResponse contains the response from method AccountsClient.BeginUpdate. +type AccountsClientUpdateResponse struct { + // Artifact signing account resource. + Account +} + +// CertificateProfilesClientCreateResponse contains the response from method CertificateProfilesClient.BeginCreate. +type CertificateProfilesClientCreateResponse struct { + // Certificate profile resource. + CertificateProfile +} + +// CertificateProfilesClientDeleteResponse contains the response from method CertificateProfilesClient.BeginDelete. +type CertificateProfilesClientDeleteResponse struct { + // placeholder for future response values +} + +// CertificateProfilesClientGetResponse contains the response from method CertificateProfilesClient.Get. +type CertificateProfilesClientGetResponse struct { + // Certificate profile resource. + CertificateProfile +} + +// CertificateProfilesClientListByCodeSigningAccountResponse contains the response from method CertificateProfilesClient.NewListByCodeSigningAccountPager. +type CertificateProfilesClientListByCodeSigningAccountResponse struct { + // The response of a CertificateProfile list operation. + CertificateProfileListResult +} + +// CertificateProfilesClientRevokeCertificatesResponse contains the response from method CertificateProfilesClient.RevokeCertificates. +type CertificateProfilesClientRevokeCertificatesResponse struct { + // placeholder for future response values +} + +// OperationsClientListResponse contains the response from method OperationsClient.NewListPager. +type OperationsClientListResponse struct { + // A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. + OperationListResult +} diff --git a/test/local/armcodesigning/zz_version.go b/test/local/armcodesigning/zz_version.go new file mode 100644 index 000000000000..8c25d8ecf9aa --- /dev/null +++ b/test/local/armcodesigning/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package armcodesigning + +const ( + moduleName = "armcodesigning" + moduleVersion = "v0.1.0" +) diff --git a/test/local/armcognitiveservices/LICENSE.txt b/test/local/armcognitiveservices/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/local/armcognitiveservices/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/local/armcognitiveservices/fake/zz_accountcapabilityhosts_server.go b/test/local/armcognitiveservices/fake/zz_accountcapabilityhosts_server.go new file mode 100644 index 000000000000..33bb4b077826 --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_accountcapabilityhosts_server.go @@ -0,0 +1,289 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// AccountCapabilityHostsServer is a fake server for instances of the armcognitiveservices.AccountCapabilityHostsClient type. +type AccountCapabilityHostsServer struct { + // BeginCreateOrUpdate is the fake for method AccountCapabilityHostsClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, accountName string, capabilityHostName string, capabilityHost armcognitiveservices.CapabilityHost, options *armcognitiveservices.AccountCapabilityHostsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armcognitiveservices.AccountCapabilityHostsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method AccountCapabilityHostsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, accountName string, capabilityHostName string, options *armcognitiveservices.AccountCapabilityHostsClientBeginDeleteOptions) (resp azfake.PollerResponder[armcognitiveservices.AccountCapabilityHostsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method AccountCapabilityHostsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, accountName string, capabilityHostName string, options *armcognitiveservices.AccountCapabilityHostsClientGetOptions) (resp azfake.Responder[armcognitiveservices.AccountCapabilityHostsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method AccountCapabilityHostsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, accountName string, options *armcognitiveservices.AccountCapabilityHostsClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.AccountCapabilityHostsClientListResponse]) +} + +// NewAccountCapabilityHostsServerTransport creates a new instance of AccountCapabilityHostsServerTransport with the provided implementation. +// The returned AccountCapabilityHostsServerTransport instance is connected to an instance of armcognitiveservices.AccountCapabilityHostsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAccountCapabilityHostsServerTransport(srv *AccountCapabilityHostsServer) *AccountCapabilityHostsServerTransport { + return &AccountCapabilityHostsServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armcognitiveservices.AccountCapabilityHostsClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armcognitiveservices.AccountCapabilityHostsClientDeleteResponse]](), + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.AccountCapabilityHostsClientListResponse]](), + } +} + +// AccountCapabilityHostsServerTransport connects instances of armcognitiveservices.AccountCapabilityHostsClient to instances of AccountCapabilityHostsServer. +// Don't use this type directly, use NewAccountCapabilityHostsServerTransport instead. +type AccountCapabilityHostsServerTransport struct { + srv *AccountCapabilityHostsServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armcognitiveservices.AccountCapabilityHostsClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armcognitiveservices.AccountCapabilityHostsClientDeleteResponse]] + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.AccountCapabilityHostsClientListResponse]] +} + +// Do implements the policy.Transporter interface for AccountCapabilityHostsServerTransport. +func (a *AccountCapabilityHostsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *AccountCapabilityHostsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if accountCapabilityHostsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = accountCapabilityHostsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "AccountCapabilityHostsClient.BeginCreateOrUpdate": + res.resp, res.err = a.dispatchBeginCreateOrUpdate(req) + case "AccountCapabilityHostsClient.BeginDelete": + res.resp, res.err = a.dispatchBeginDelete(req) + case "AccountCapabilityHostsClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "AccountCapabilityHostsClient.NewListPager": + res.resp, res.err = a.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *AccountCapabilityHostsServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if a.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := a.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/capabilityHosts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.CapabilityHost](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + capabilityHostNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("capabilityHostName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, accountNameParam, capabilityHostNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + a.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + a.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + a.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (a *AccountCapabilityHostsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if a.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := a.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/capabilityHosts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + capabilityHostNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("capabilityHostName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginDelete(req.Context(), resourceGroupNameParam, accountNameParam, capabilityHostNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + a.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + a.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + a.beginDelete.remove(req) + } + + return resp, nil +} + +func (a *AccountCapabilityHostsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/capabilityHosts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + capabilityHostNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("capabilityHostName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Get(req.Context(), resourceGroupNameParam, accountNameParam, capabilityHostNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CapabilityHost, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AccountCapabilityHostsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if a.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := a.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/capabilityHosts` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + resp := a.srv.NewListPager(resourceGroupNameParam, accountNameParam, nil) + newListPager = &resp + a.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.AccountCapabilityHostsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + a.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to AccountCapabilityHostsServerTransport +var accountCapabilityHostsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_accountconnections_server.go b/test/local/armcognitiveservices/fake/zz_accountconnections_server.go new file mode 100644 index 000000000000..e607239e1b42 --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_accountconnections_server.go @@ -0,0 +1,326 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" + "strconv" +) + +// AccountConnectionsServer is a fake server for instances of the armcognitiveservices.AccountConnectionsClient type. +type AccountConnectionsServer struct { + // Create is the fake for method AccountConnectionsClient.Create + // HTTP status codes to indicate success: http.StatusOK + Create func(ctx context.Context, resourceGroupName string, accountName string, connectionName string, connection armcognitiveservices.ConnectionPropertiesV2BasicResource, options *armcognitiveservices.AccountConnectionsClientCreateOptions) (resp azfake.Responder[armcognitiveservices.AccountConnectionsClientCreateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method AccountConnectionsClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceGroupName string, accountName string, connectionName string, options *armcognitiveservices.AccountConnectionsClientDeleteOptions) (resp azfake.Responder[armcognitiveservices.AccountConnectionsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method AccountConnectionsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, accountName string, connectionName string, options *armcognitiveservices.AccountConnectionsClientGetOptions) (resp azfake.Responder[armcognitiveservices.AccountConnectionsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method AccountConnectionsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, accountName string, options *armcognitiveservices.AccountConnectionsClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.AccountConnectionsClientListResponse]) + + // Update is the fake for method AccountConnectionsClient.Update + // HTTP status codes to indicate success: http.StatusOK + Update func(ctx context.Context, resourceGroupName string, accountName string, connectionName string, connection armcognitiveservices.ConnectionUpdateContent, options *armcognitiveservices.AccountConnectionsClientUpdateOptions) (resp azfake.Responder[armcognitiveservices.AccountConnectionsClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewAccountConnectionsServerTransport creates a new instance of AccountConnectionsServerTransport with the provided implementation. +// The returned AccountConnectionsServerTransport instance is connected to an instance of armcognitiveservices.AccountConnectionsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAccountConnectionsServerTransport(srv *AccountConnectionsServer) *AccountConnectionsServerTransport { + return &AccountConnectionsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.AccountConnectionsClientListResponse]](), + } +} + +// AccountConnectionsServerTransport connects instances of armcognitiveservices.AccountConnectionsClient to instances of AccountConnectionsServer. +// Don't use this type directly, use NewAccountConnectionsServerTransport instead. +type AccountConnectionsServerTransport struct { + srv *AccountConnectionsServer + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.AccountConnectionsClientListResponse]] +} + +// Do implements the policy.Transporter interface for AccountConnectionsServerTransport. +func (a *AccountConnectionsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *AccountConnectionsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if accountConnectionsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = accountConnectionsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "AccountConnectionsClient.Create": + res.resp, res.err = a.dispatchCreate(req) + case "AccountConnectionsClient.Delete": + res.resp, res.err = a.dispatchDelete(req) + case "AccountConnectionsClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "AccountConnectionsClient.NewListPager": + res.resp, res.err = a.dispatchNewListPager(req) + case "AccountConnectionsClient.Update": + res.resp, res.err = a.dispatchUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *AccountConnectionsServerTransport) dispatchCreate(req *http.Request) (*http.Response, error) { + if a.srv.Create == nil { + return nil, &nonRetriableError{errors.New("fake for method Create not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/connections/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.ConnectionPropertiesV2BasicResource](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + connectionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("connectionName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Create(req.Context(), resourceGroupNameParam, accountNameParam, connectionNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ConnectionPropertiesV2BasicResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AccountConnectionsServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if a.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/connections/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + connectionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("connectionName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Delete(req.Context(), resourceGroupNameParam, accountNameParam, connectionNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AccountConnectionsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/connections/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + connectionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("connectionName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Get(req.Context(), resourceGroupNameParam, accountNameParam, connectionNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ConnectionPropertiesV2BasicResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AccountConnectionsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if a.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := a.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/connections` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + targetParam := getOptional(qp.Get("target")) + categoryParam := getOptional(qp.Get("category")) + includeAllParam, err := parseOptional(qp.Get("includeAll"), strconv.ParseBool) + if err != nil { + return nil, err + } + var options *armcognitiveservices.AccountConnectionsClientListOptions + if targetParam != nil || categoryParam != nil || includeAllParam != nil { + options = &armcognitiveservices.AccountConnectionsClientListOptions{ + Target: targetParam, + Category: categoryParam, + IncludeAll: includeAllParam, + } + } + resp := a.srv.NewListPager(resourceGroupNameParam, accountNameParam, options) + newListPager = &resp + a.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.AccountConnectionsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + a.newListPager.remove(req) + } + return resp, nil +} + +func (a *AccountConnectionsServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) { + if a.srv.Update == nil { + return nil, &nonRetriableError{errors.New("fake for method Update not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/connections/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.ConnectionUpdateContent](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + connectionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("connectionName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Update(req.Context(), resourceGroupNameParam, accountNameParam, connectionNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ConnectionPropertiesV2BasicResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to AccountConnectionsServerTransport +var accountConnectionsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_accounts_server.go b/test/local/armcognitiveservices/fake/zz_accounts_server.go new file mode 100644 index 000000000000..9cfb6690155d --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_accounts_server.go @@ -0,0 +1,587 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// AccountsServer is a fake server for instances of the armcognitiveservices.AccountsClient type. +type AccountsServer struct { + // BeginCreate is the fake for method AccountsClient.BeginCreate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated, http.StatusAccepted + BeginCreate func(ctx context.Context, resourceGroupName string, accountName string, account armcognitiveservices.Account, options *armcognitiveservices.AccountsClientBeginCreateOptions) (resp azfake.PollerResponder[armcognitiveservices.AccountsClientCreateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method AccountsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, accountName string, options *armcognitiveservices.AccountsClientBeginDeleteOptions) (resp azfake.PollerResponder[armcognitiveservices.AccountsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method AccountsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, accountName string, options *armcognitiveservices.AccountsClientGetOptions) (resp azfake.Responder[armcognitiveservices.AccountsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method AccountsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armcognitiveservices.AccountsClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.AccountsClientListResponse]) + + // NewListByResourceGroupPager is the fake for method AccountsClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armcognitiveservices.AccountsClientListByResourceGroupOptions) (resp azfake.PagerResponder[armcognitiveservices.AccountsClientListByResourceGroupResponse]) + + // ListKeys is the fake for method AccountsClient.ListKeys + // HTTP status codes to indicate success: http.StatusOK + ListKeys func(ctx context.Context, resourceGroupName string, accountName string, options *armcognitiveservices.AccountsClientListKeysOptions) (resp azfake.Responder[armcognitiveservices.AccountsClientListKeysResponse], errResp azfake.ErrorResponder) + + // NewListModelsPager is the fake for method AccountsClient.NewListModelsPager + // HTTP status codes to indicate success: http.StatusOK + NewListModelsPager func(resourceGroupName string, accountName string, options *armcognitiveservices.AccountsClientListModelsOptions) (resp azfake.PagerResponder[armcognitiveservices.AccountsClientListModelsResponse]) + + // ListSKUs is the fake for method AccountsClient.ListSKUs + // HTTP status codes to indicate success: http.StatusOK + ListSKUs func(ctx context.Context, resourceGroupName string, accountName string, options *armcognitiveservices.AccountsClientListSKUsOptions) (resp azfake.Responder[armcognitiveservices.AccountsClientListSKUsResponse], errResp azfake.ErrorResponder) + + // ListUsages is the fake for method AccountsClient.ListUsages + // HTTP status codes to indicate success: http.StatusOK + ListUsages func(ctx context.Context, resourceGroupName string, accountName string, options *armcognitiveservices.AccountsClientListUsagesOptions) (resp azfake.Responder[armcognitiveservices.AccountsClientListUsagesResponse], errResp azfake.ErrorResponder) + + // RegenerateKey is the fake for method AccountsClient.RegenerateKey + // HTTP status codes to indicate success: http.StatusOK + RegenerateKey func(ctx context.Context, resourceGroupName string, accountName string, parameters armcognitiveservices.RegenerateKeyParameters, options *armcognitiveservices.AccountsClientRegenerateKeyOptions) (resp azfake.Responder[armcognitiveservices.AccountsClientRegenerateKeyResponse], errResp azfake.ErrorResponder) + + // BeginUpdate is the fake for method AccountsClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, accountName string, account armcognitiveservices.Account, options *armcognitiveservices.AccountsClientBeginUpdateOptions) (resp azfake.PollerResponder[armcognitiveservices.AccountsClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewAccountsServerTransport creates a new instance of AccountsServerTransport with the provided implementation. +// The returned AccountsServerTransport instance is connected to an instance of armcognitiveservices.AccountsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAccountsServerTransport(srv *AccountsServer) *AccountsServerTransport { + return &AccountsServerTransport{ + srv: srv, + beginCreate: newTracker[azfake.PollerResponder[armcognitiveservices.AccountsClientCreateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armcognitiveservices.AccountsClientDeleteResponse]](), + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.AccountsClientListResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armcognitiveservices.AccountsClientListByResourceGroupResponse]](), + newListModelsPager: newTracker[azfake.PagerResponder[armcognitiveservices.AccountsClientListModelsResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armcognitiveservices.AccountsClientUpdateResponse]](), + } +} + +// AccountsServerTransport connects instances of armcognitiveservices.AccountsClient to instances of AccountsServer. +// Don't use this type directly, use NewAccountsServerTransport instead. +type AccountsServerTransport struct { + srv *AccountsServer + beginCreate *tracker[azfake.PollerResponder[armcognitiveservices.AccountsClientCreateResponse]] + beginDelete *tracker[azfake.PollerResponder[armcognitiveservices.AccountsClientDeleteResponse]] + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.AccountsClientListResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armcognitiveservices.AccountsClientListByResourceGroupResponse]] + newListModelsPager *tracker[azfake.PagerResponder[armcognitiveservices.AccountsClientListModelsResponse]] + beginUpdate *tracker[azfake.PollerResponder[armcognitiveservices.AccountsClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for AccountsServerTransport. +func (a *AccountsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *AccountsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if accountsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = accountsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "AccountsClient.BeginCreate": + res.resp, res.err = a.dispatchBeginCreate(req) + case "AccountsClient.BeginDelete": + res.resp, res.err = a.dispatchBeginDelete(req) + case "AccountsClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "AccountsClient.NewListPager": + res.resp, res.err = a.dispatchNewListPager(req) + case "AccountsClient.NewListByResourceGroupPager": + res.resp, res.err = a.dispatchNewListByResourceGroupPager(req) + case "AccountsClient.ListKeys": + res.resp, res.err = a.dispatchListKeys(req) + case "AccountsClient.NewListModelsPager": + res.resp, res.err = a.dispatchNewListModelsPager(req) + case "AccountsClient.ListSKUs": + res.resp, res.err = a.dispatchListSKUs(req) + case "AccountsClient.ListUsages": + res.resp, res.err = a.dispatchListUsages(req) + case "AccountsClient.RegenerateKey": + res.resp, res.err = a.dispatchRegenerateKey(req) + case "AccountsClient.BeginUpdate": + res.resp, res.err = a.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *AccountsServerTransport) dispatchBeginCreate(req *http.Request) (*http.Response, error) { + if a.srv.BeginCreate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreate not implemented")} + } + beginCreate := a.beginCreate.get(req) + if beginCreate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.Account](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginCreate(req.Context(), resourceGroupNameParam, accountNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreate = &respr + a.beginCreate.add(req, beginCreate) + } + + resp, err := server.PollerResponderNext(beginCreate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated, http.StatusAccepted}, resp.StatusCode) { + a.beginCreate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreate) { + a.beginCreate.remove(req) + } + + return resp, nil +} + +func (a *AccountsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if a.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := a.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginDelete(req.Context(), resourceGroupNameParam, accountNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + a.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + a.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + a.beginDelete.remove(req) + } + + return resp, nil +} + +func (a *AccountsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Get(req.Context(), resourceGroupNameParam, accountNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Account, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AccountsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if a.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := a.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := a.srv.NewListPager(nil) + newListPager = &resp + a.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.AccountsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + a.newListPager.remove(req) + } + return resp, nil +} + +func (a *AccountsServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if a.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := a.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := a.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + a.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armcognitiveservices.AccountsClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + a.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (a *AccountsServerTransport) dispatchListKeys(req *http.Request) (*http.Response, error) { + if a.srv.ListKeys == nil { + return nil, &nonRetriableError{errors.New("fake for method ListKeys not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/listKeys` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.ListKeys(req.Context(), resourceGroupNameParam, accountNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).APIKeys, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AccountsServerTransport) dispatchNewListModelsPager(req *http.Request) (*http.Response, error) { + if a.srv.NewListModelsPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListModelsPager not implemented")} + } + newListModelsPager := a.newListModelsPager.get(req) + if newListModelsPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/models` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + resp := a.srv.NewListModelsPager(resourceGroupNameParam, accountNameParam, nil) + newListModelsPager = &resp + a.newListModelsPager.add(req, newListModelsPager) + server.PagerResponderInjectNextLinks(newListModelsPager, req, func(page *armcognitiveservices.AccountsClientListModelsResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListModelsPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListModelsPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListModelsPager) { + a.newListModelsPager.remove(req) + } + return resp, nil +} + +func (a *AccountsServerTransport) dispatchListSKUs(req *http.Request) (*http.Response, error) { + if a.srv.ListSKUs == nil { + return nil, &nonRetriableError{errors.New("fake for method ListSKUs not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/skus` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.ListSKUs(req.Context(), resourceGroupNameParam, accountNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).AccountSKUListResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AccountsServerTransport) dispatchListUsages(req *http.Request) (*http.Response, error) { + if a.srv.ListUsages == nil { + return nil, &nonRetriableError{errors.New("fake for method ListUsages not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/usages` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + filterParam := getOptional(qp.Get("$filter")) + var options *armcognitiveservices.AccountsClientListUsagesOptions + if filterParam != nil { + options = &armcognitiveservices.AccountsClientListUsagesOptions{ + Filter: filterParam, + } + } + respr, errRespr := a.srv.ListUsages(req.Context(), resourceGroupNameParam, accountNameParam, options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).UsageListResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AccountsServerTransport) dispatchRegenerateKey(req *http.Request) (*http.Response, error) { + if a.srv.RegenerateKey == nil { + return nil, &nonRetriableError{errors.New("fake for method RegenerateKey not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/regenerateKey` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.RegenerateKeyParameters](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.RegenerateKey(req.Context(), resourceGroupNameParam, accountNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).APIKeys, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AccountsServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if a.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := a.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.Account](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginUpdate(req.Context(), resourceGroupNameParam, accountNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + a.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + a.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + a.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to AccountsServerTransport +var accountsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_agentapplications_server.go b/test/local/armcognitiveservices/fake/zz_agentapplications_server.go new file mode 100644 index 000000000000..891b3cbdeda3 --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_agentapplications_server.go @@ -0,0 +1,487 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" + "strconv" +) + +// AgentApplicationsServer is a fake server for instances of the armcognitiveservices.AgentApplicationsClient type. +type AgentApplicationsServer struct { + // BeginCreateOrUpdate is the fake for method AgentApplicationsClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, accountName string, projectName string, name string, body armcognitiveservices.AgentApplication, options *armcognitiveservices.AgentApplicationsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armcognitiveservices.AgentApplicationsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method AgentApplicationsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, accountName string, projectName string, name string, options *armcognitiveservices.AgentApplicationsClientBeginDeleteOptions) (resp azfake.PollerResponder[armcognitiveservices.AgentApplicationsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Disable is the fake for method AgentApplicationsClient.Disable + // HTTP status codes to indicate success: http.StatusOK + Disable func(ctx context.Context, resourceGroupName string, accountName string, projectName string, name string, options *armcognitiveservices.AgentApplicationsClientDisableOptions) (resp azfake.Responder[armcognitiveservices.AgentApplicationsClientDisableResponse], errResp azfake.ErrorResponder) + + // Enable is the fake for method AgentApplicationsClient.Enable + // HTTP status codes to indicate success: http.StatusOK + Enable func(ctx context.Context, resourceGroupName string, accountName string, projectName string, name string, options *armcognitiveservices.AgentApplicationsClientEnableOptions) (resp azfake.Responder[armcognitiveservices.AgentApplicationsClientEnableResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method AgentApplicationsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, accountName string, projectName string, name string, options *armcognitiveservices.AgentApplicationsClientGetOptions) (resp azfake.Responder[armcognitiveservices.AgentApplicationsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method AgentApplicationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, accountName string, projectName string, options *armcognitiveservices.AgentApplicationsClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.AgentApplicationsClientListResponse]) + + // ListAgents is the fake for method AgentApplicationsClient.ListAgents + // HTTP status codes to indicate success: http.StatusOK + ListAgents func(ctx context.Context, resourceGroupName string, accountName string, projectName string, name string, options *armcognitiveservices.AgentApplicationsClientListAgentsOptions) (resp azfake.Responder[armcognitiveservices.AgentApplicationsClientListAgentsResponse], errResp azfake.ErrorResponder) +} + +// NewAgentApplicationsServerTransport creates a new instance of AgentApplicationsServerTransport with the provided implementation. +// The returned AgentApplicationsServerTransport instance is connected to an instance of armcognitiveservices.AgentApplicationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAgentApplicationsServerTransport(srv *AgentApplicationsServer) *AgentApplicationsServerTransport { + return &AgentApplicationsServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armcognitiveservices.AgentApplicationsClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armcognitiveservices.AgentApplicationsClientDeleteResponse]](), + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.AgentApplicationsClientListResponse]](), + } +} + +// AgentApplicationsServerTransport connects instances of armcognitiveservices.AgentApplicationsClient to instances of AgentApplicationsServer. +// Don't use this type directly, use NewAgentApplicationsServerTransport instead. +type AgentApplicationsServerTransport struct { + srv *AgentApplicationsServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armcognitiveservices.AgentApplicationsClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armcognitiveservices.AgentApplicationsClientDeleteResponse]] + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.AgentApplicationsClientListResponse]] +} + +// Do implements the policy.Transporter interface for AgentApplicationsServerTransport. +func (a *AgentApplicationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *AgentApplicationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if agentApplicationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = agentApplicationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "AgentApplicationsClient.BeginCreateOrUpdate": + res.resp, res.err = a.dispatchBeginCreateOrUpdate(req) + case "AgentApplicationsClient.BeginDelete": + res.resp, res.err = a.dispatchBeginDelete(req) + case "AgentApplicationsClient.Disable": + res.resp, res.err = a.dispatchDisable(req) + case "AgentApplicationsClient.Enable": + res.resp, res.err = a.dispatchEnable(req) + case "AgentApplicationsClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "AgentApplicationsClient.NewListPager": + res.resp, res.err = a.dispatchNewListPager(req) + case "AgentApplicationsClient.ListAgents": + res.resp, res.err = a.dispatchListAgents(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *AgentApplicationsServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if a.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := a.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/applications/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.AgentApplication](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")]) + if err != nil { + return nil, err + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("name")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, accountNameParam, projectNameParam, nameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + a.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + a.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + a.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (a *AgentApplicationsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if a.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := a.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/applications/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")]) + if err != nil { + return nil, err + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("name")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginDelete(req.Context(), resourceGroupNameParam, accountNameParam, projectNameParam, nameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + a.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + a.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + a.beginDelete.remove(req) + } + + return resp, nil +} + +func (a *AgentApplicationsServerTransport) dispatchDisable(req *http.Request) (*http.Response, error) { + if a.srv.Disable == nil { + return nil, &nonRetriableError{errors.New("fake for method Disable not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/applications/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/disable` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")]) + if err != nil { + return nil, err + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("name")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Disable(req.Context(), resourceGroupNameParam, accountNameParam, projectNameParam, nameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AgentApplicationsServerTransport) dispatchEnable(req *http.Request) (*http.Response, error) { + if a.srv.Enable == nil { + return nil, &nonRetriableError{errors.New("fake for method Enable not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/applications/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/enable` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")]) + if err != nil { + return nil, err + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("name")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Enable(req.Context(), resourceGroupNameParam, accountNameParam, projectNameParam, nameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AgentApplicationsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/applications/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")]) + if err != nil { + return nil, err + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("name")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Get(req.Context(), resourceGroupNameParam, accountNameParam, projectNameParam, nameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).AgentApplication, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AgentApplicationsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if a.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := a.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/applications` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")]) + if err != nil { + return nil, err + } + countParam, err := parseOptional(qp.Get("count"), func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + skipParam, err := parseOptional(qp.Get("$skip"), func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + skipTokenParam := getOptional(qp.Get("$skipToken")) + searchTextParam := getOptional(qp.Get("searchText")) + orderByParam := getOptional(qp.Get("orderBy")) + orderByAscParam, err := parseOptional(qp.Get("orderByAsc"), strconv.ParseBool) + if err != nil { + return nil, err + } + var options *armcognitiveservices.AgentApplicationsClientListOptions + if countParam != nil || skipParam != nil || skipTokenParam != nil || len(qp["names"]) > 0 || searchTextParam != nil || orderByParam != nil || orderByAscParam != nil { + options = &armcognitiveservices.AgentApplicationsClientListOptions{ + Count: countParam, + Skip: skipParam, + SkipToken: skipTokenParam, + Names: qp["names"], + SearchText: searchTextParam, + OrderBy: orderByParam, + OrderByAsc: orderByAscParam, + } + } + resp := a.srv.NewListPager(resourceGroupNameParam, accountNameParam, projectNameParam, options) + newListPager = &resp + a.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.AgentApplicationsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + a.newListPager.remove(req) + } + return resp, nil +} + +func (a *AgentApplicationsServerTransport) dispatchListAgents(req *http.Request) (*http.Response, error) { + if a.srv.ListAgents == nil { + return nil, &nonRetriableError{errors.New("fake for method ListAgents not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/applications/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/listAgents` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")]) + if err != nil { + return nil, err + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("name")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.ListAgents(req.Context(), resourceGroupNameParam, accountNameParam, projectNameParam, nameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).AgentReferenceResourceArmPaginatedResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to AgentApplicationsServerTransport +var agentApplicationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_agentdeployments_server.go b/test/local/armcognitiveservices/fake/zz_agentdeployments_server.go new file mode 100644 index 000000000000..c2daa29fc8d6 --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_agentdeployments_server.go @@ -0,0 +1,451 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" + "strconv" +) + +// AgentDeploymentsServer is a fake server for instances of the armcognitiveservices.AgentDeploymentsClient type. +type AgentDeploymentsServer struct { + // BeginCreateOrUpdate is the fake for method AgentDeploymentsClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, accountName string, projectName string, appName string, deploymentName string, body armcognitiveservices.AgentDeployment, options *armcognitiveservices.AgentDeploymentsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armcognitiveservices.AgentDeploymentsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method AgentDeploymentsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, accountName string, projectName string, appName string, deploymentName string, options *armcognitiveservices.AgentDeploymentsClientBeginDeleteOptions) (resp azfake.PollerResponder[armcognitiveservices.AgentDeploymentsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method AgentDeploymentsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, accountName string, projectName string, appName string, deploymentName string, options *armcognitiveservices.AgentDeploymentsClientGetOptions) (resp azfake.Responder[armcognitiveservices.AgentDeploymentsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method AgentDeploymentsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, accountName string, projectName string, appName string, options *armcognitiveservices.AgentDeploymentsClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.AgentDeploymentsClientListResponse]) + + // Start is the fake for method AgentDeploymentsClient.Start + // HTTP status codes to indicate success: http.StatusOK + Start func(ctx context.Context, resourceGroupName string, accountName string, projectName string, appName string, deploymentName string, options *armcognitiveservices.AgentDeploymentsClientStartOptions) (resp azfake.Responder[armcognitiveservices.AgentDeploymentsClientStartResponse], errResp azfake.ErrorResponder) + + // Stop is the fake for method AgentDeploymentsClient.Stop + // HTTP status codes to indicate success: http.StatusOK + Stop func(ctx context.Context, resourceGroupName string, accountName string, projectName string, appName string, deploymentName string, options *armcognitiveservices.AgentDeploymentsClientStopOptions) (resp azfake.Responder[armcognitiveservices.AgentDeploymentsClientStopResponse], errResp azfake.ErrorResponder) +} + +// NewAgentDeploymentsServerTransport creates a new instance of AgentDeploymentsServerTransport with the provided implementation. +// The returned AgentDeploymentsServerTransport instance is connected to an instance of armcognitiveservices.AgentDeploymentsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAgentDeploymentsServerTransport(srv *AgentDeploymentsServer) *AgentDeploymentsServerTransport { + return &AgentDeploymentsServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armcognitiveservices.AgentDeploymentsClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armcognitiveservices.AgentDeploymentsClientDeleteResponse]](), + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.AgentDeploymentsClientListResponse]](), + } +} + +// AgentDeploymentsServerTransport connects instances of armcognitiveservices.AgentDeploymentsClient to instances of AgentDeploymentsServer. +// Don't use this type directly, use NewAgentDeploymentsServerTransport instead. +type AgentDeploymentsServerTransport struct { + srv *AgentDeploymentsServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armcognitiveservices.AgentDeploymentsClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armcognitiveservices.AgentDeploymentsClientDeleteResponse]] + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.AgentDeploymentsClientListResponse]] +} + +// Do implements the policy.Transporter interface for AgentDeploymentsServerTransport. +func (a *AgentDeploymentsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *AgentDeploymentsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if agentDeploymentsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = agentDeploymentsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "AgentDeploymentsClient.BeginCreateOrUpdate": + res.resp, res.err = a.dispatchBeginCreateOrUpdate(req) + case "AgentDeploymentsClient.BeginDelete": + res.resp, res.err = a.dispatchBeginDelete(req) + case "AgentDeploymentsClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "AgentDeploymentsClient.NewListPager": + res.resp, res.err = a.dispatchNewListPager(req) + case "AgentDeploymentsClient.Start": + res.resp, res.err = a.dispatchStart(req) + case "AgentDeploymentsClient.Stop": + res.resp, res.err = a.dispatchStop(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *AgentDeploymentsServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if a.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := a.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/applications/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/agentDeployments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 7 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.AgentDeployment](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")]) + if err != nil { + return nil, err + } + appNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("appName")]) + if err != nil { + return nil, err + } + deploymentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("deploymentName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, accountNameParam, projectNameParam, appNameParam, deploymentNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + a.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + a.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + a.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (a *AgentDeploymentsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if a.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := a.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/applications/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/agentDeployments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 7 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")]) + if err != nil { + return nil, err + } + appNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("appName")]) + if err != nil { + return nil, err + } + deploymentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("deploymentName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginDelete(req.Context(), resourceGroupNameParam, accountNameParam, projectNameParam, appNameParam, deploymentNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + a.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + a.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + a.beginDelete.remove(req) + } + + return resp, nil +} + +func (a *AgentDeploymentsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/applications/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/agentDeployments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 7 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")]) + if err != nil { + return nil, err + } + appNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("appName")]) + if err != nil { + return nil, err + } + deploymentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("deploymentName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Get(req.Context(), resourceGroupNameParam, accountNameParam, projectNameParam, appNameParam, deploymentNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).AgentDeployment, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AgentDeploymentsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if a.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := a.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/applications/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/agentDeployments` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")]) + if err != nil { + return nil, err + } + appNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("appName")]) + if err != nil { + return nil, err + } + countParam, err := parseOptional(qp.Get("count"), func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + skipTokenParam := getOptional(qp.Get("$skipToken")) + orderByParam := getOptional(qp.Get("orderBy")) + orderByAscParam, err := parseOptional(qp.Get("orderByAsc"), strconv.ParseBool) + if err != nil { + return nil, err + } + var options *armcognitiveservices.AgentDeploymentsClientListOptions + if countParam != nil || skipTokenParam != nil || len(qp["names"]) > 0 || orderByParam != nil || orderByAscParam != nil { + options = &armcognitiveservices.AgentDeploymentsClientListOptions{ + Count: countParam, + SkipToken: skipTokenParam, + Names: qp["names"], + OrderBy: orderByParam, + OrderByAsc: orderByAscParam, + } + } + resp := a.srv.NewListPager(resourceGroupNameParam, accountNameParam, projectNameParam, appNameParam, options) + newListPager = &resp + a.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.AgentDeploymentsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + a.newListPager.remove(req) + } + return resp, nil +} + +func (a *AgentDeploymentsServerTransport) dispatchStart(req *http.Request) (*http.Response, error) { + if a.srv.Start == nil { + return nil, &nonRetriableError{errors.New("fake for method Start not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/applications/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/agentDeployments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/start` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 7 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")]) + if err != nil { + return nil, err + } + appNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("appName")]) + if err != nil { + return nil, err + } + deploymentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("deploymentName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Start(req.Context(), resourceGroupNameParam, accountNameParam, projectNameParam, appNameParam, deploymentNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AgentDeploymentsServerTransport) dispatchStop(req *http.Request) (*http.Response, error) { + if a.srv.Stop == nil { + return nil, &nonRetriableError{errors.New("fake for method Stop not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/applications/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/agentDeployments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/stop` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 7 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")]) + if err != nil { + return nil, err + } + appNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("appName")]) + if err != nil { + return nil, err + } + deploymentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("deploymentName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Stop(req.Context(), resourceGroupNameParam, accountNameParam, projectNameParam, appNameParam, deploymentNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to AgentDeploymentsServerTransport +var agentDeploymentsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_commitmentplans_server.go b/test/local/armcognitiveservices/fake/zz_commitmentplans_server.go new file mode 100644 index 000000000000..9ddc8bb0fad3 --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_commitmentplans_server.go @@ -0,0 +1,773 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// CommitmentPlansServer is a fake server for instances of the armcognitiveservices.CommitmentPlansClient type. +type CommitmentPlansServer struct { + // CreateOrUpdate is the fake for method CommitmentPlansClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, accountName string, commitmentPlanName string, commitmentPlan armcognitiveservices.CommitmentPlan, options *armcognitiveservices.CommitmentPlansClientCreateOrUpdateOptions) (resp azfake.Responder[armcognitiveservices.CommitmentPlansClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginCreateOrUpdateAssociation is the fake for method CommitmentPlansClient.BeginCreateOrUpdateAssociation + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdateAssociation func(ctx context.Context, resourceGroupName string, commitmentPlanName string, commitmentPlanAssociationName string, association armcognitiveservices.CommitmentPlanAccountAssociation, options *armcognitiveservices.CommitmentPlansClientBeginCreateOrUpdateAssociationOptions) (resp azfake.PollerResponder[armcognitiveservices.CommitmentPlansClientCreateOrUpdateAssociationResponse], errResp azfake.ErrorResponder) + + // BeginCreateOrUpdatePlan is the fake for method CommitmentPlansClient.BeginCreateOrUpdatePlan + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdatePlan func(ctx context.Context, resourceGroupName string, commitmentPlanName string, commitmentPlan armcognitiveservices.CommitmentPlan, options *armcognitiveservices.CommitmentPlansClientBeginCreateOrUpdatePlanOptions) (resp azfake.PollerResponder[armcognitiveservices.CommitmentPlansClientCreateOrUpdatePlanResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method CommitmentPlansClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, accountName string, commitmentPlanName string, options *armcognitiveservices.CommitmentPlansClientBeginDeleteOptions) (resp azfake.PollerResponder[armcognitiveservices.CommitmentPlansClientDeleteResponse], errResp azfake.ErrorResponder) + + // BeginDeleteAssociation is the fake for method CommitmentPlansClient.BeginDeleteAssociation + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDeleteAssociation func(ctx context.Context, resourceGroupName string, commitmentPlanName string, commitmentPlanAssociationName string, options *armcognitiveservices.CommitmentPlansClientBeginDeleteAssociationOptions) (resp azfake.PollerResponder[armcognitiveservices.CommitmentPlansClientDeleteAssociationResponse], errResp azfake.ErrorResponder) + + // BeginDeletePlan is the fake for method CommitmentPlansClient.BeginDeletePlan + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDeletePlan func(ctx context.Context, resourceGroupName string, commitmentPlanName string, options *armcognitiveservices.CommitmentPlansClientBeginDeletePlanOptions) (resp azfake.PollerResponder[armcognitiveservices.CommitmentPlansClientDeletePlanResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method CommitmentPlansClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, accountName string, commitmentPlanName string, options *armcognitiveservices.CommitmentPlansClientGetOptions) (resp azfake.Responder[armcognitiveservices.CommitmentPlansClientGetResponse], errResp azfake.ErrorResponder) + + // GetAssociation is the fake for method CommitmentPlansClient.GetAssociation + // HTTP status codes to indicate success: http.StatusOK + GetAssociation func(ctx context.Context, resourceGroupName string, commitmentPlanName string, commitmentPlanAssociationName string, options *armcognitiveservices.CommitmentPlansClientGetAssociationOptions) (resp azfake.Responder[armcognitiveservices.CommitmentPlansClientGetAssociationResponse], errResp azfake.ErrorResponder) + + // GetPlan is the fake for method CommitmentPlansClient.GetPlan + // HTTP status codes to indicate success: http.StatusOK + GetPlan func(ctx context.Context, resourceGroupName string, commitmentPlanName string, options *armcognitiveservices.CommitmentPlansClientGetPlanOptions) (resp azfake.Responder[armcognitiveservices.CommitmentPlansClientGetPlanResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method CommitmentPlansClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, accountName string, options *armcognitiveservices.CommitmentPlansClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.CommitmentPlansClientListResponse]) + + // NewListAssociationsPager is the fake for method CommitmentPlansClient.NewListAssociationsPager + // HTTP status codes to indicate success: http.StatusOK + NewListAssociationsPager func(resourceGroupName string, commitmentPlanName string, options *armcognitiveservices.CommitmentPlansClientListAssociationsOptions) (resp azfake.PagerResponder[armcognitiveservices.CommitmentPlansClientListAssociationsResponse]) + + // NewListPlansByResourceGroupPager is the fake for method CommitmentPlansClient.NewListPlansByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListPlansByResourceGroupPager func(resourceGroupName string, options *armcognitiveservices.CommitmentPlansClientListPlansByResourceGroupOptions) (resp azfake.PagerResponder[armcognitiveservices.CommitmentPlansClientListPlansByResourceGroupResponse]) + + // NewListPlansBySubscriptionPager is the fake for method CommitmentPlansClient.NewListPlansBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListPlansBySubscriptionPager func(options *armcognitiveservices.CommitmentPlansClientListPlansBySubscriptionOptions) (resp azfake.PagerResponder[armcognitiveservices.CommitmentPlansClientListPlansBySubscriptionResponse]) + + // BeginUpdatePlan is the fake for method CommitmentPlansClient.BeginUpdatePlan + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdatePlan func(ctx context.Context, resourceGroupName string, commitmentPlanName string, commitmentPlan armcognitiveservices.PatchResourceTagsAndSKU, options *armcognitiveservices.CommitmentPlansClientBeginUpdatePlanOptions) (resp azfake.PollerResponder[armcognitiveservices.CommitmentPlansClientUpdatePlanResponse], errResp azfake.ErrorResponder) +} + +// NewCommitmentPlansServerTransport creates a new instance of CommitmentPlansServerTransport with the provided implementation. +// The returned CommitmentPlansServerTransport instance is connected to an instance of armcognitiveservices.CommitmentPlansClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewCommitmentPlansServerTransport(srv *CommitmentPlansServer) *CommitmentPlansServerTransport { + return &CommitmentPlansServerTransport{ + srv: srv, + beginCreateOrUpdateAssociation: newTracker[azfake.PollerResponder[armcognitiveservices.CommitmentPlansClientCreateOrUpdateAssociationResponse]](), + beginCreateOrUpdatePlan: newTracker[azfake.PollerResponder[armcognitiveservices.CommitmentPlansClientCreateOrUpdatePlanResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armcognitiveservices.CommitmentPlansClientDeleteResponse]](), + beginDeleteAssociation: newTracker[azfake.PollerResponder[armcognitiveservices.CommitmentPlansClientDeleteAssociationResponse]](), + beginDeletePlan: newTracker[azfake.PollerResponder[armcognitiveservices.CommitmentPlansClientDeletePlanResponse]](), + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.CommitmentPlansClientListResponse]](), + newListAssociationsPager: newTracker[azfake.PagerResponder[armcognitiveservices.CommitmentPlansClientListAssociationsResponse]](), + newListPlansByResourceGroupPager: newTracker[azfake.PagerResponder[armcognitiveservices.CommitmentPlansClientListPlansByResourceGroupResponse]](), + newListPlansBySubscriptionPager: newTracker[azfake.PagerResponder[armcognitiveservices.CommitmentPlansClientListPlansBySubscriptionResponse]](), + beginUpdatePlan: newTracker[azfake.PollerResponder[armcognitiveservices.CommitmentPlansClientUpdatePlanResponse]](), + } +} + +// CommitmentPlansServerTransport connects instances of armcognitiveservices.CommitmentPlansClient to instances of CommitmentPlansServer. +// Don't use this type directly, use NewCommitmentPlansServerTransport instead. +type CommitmentPlansServerTransport struct { + srv *CommitmentPlansServer + beginCreateOrUpdateAssociation *tracker[azfake.PollerResponder[armcognitiveservices.CommitmentPlansClientCreateOrUpdateAssociationResponse]] + beginCreateOrUpdatePlan *tracker[azfake.PollerResponder[armcognitiveservices.CommitmentPlansClientCreateOrUpdatePlanResponse]] + beginDelete *tracker[azfake.PollerResponder[armcognitiveservices.CommitmentPlansClientDeleteResponse]] + beginDeleteAssociation *tracker[azfake.PollerResponder[armcognitiveservices.CommitmentPlansClientDeleteAssociationResponse]] + beginDeletePlan *tracker[azfake.PollerResponder[armcognitiveservices.CommitmentPlansClientDeletePlanResponse]] + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.CommitmentPlansClientListResponse]] + newListAssociationsPager *tracker[azfake.PagerResponder[armcognitiveservices.CommitmentPlansClientListAssociationsResponse]] + newListPlansByResourceGroupPager *tracker[azfake.PagerResponder[armcognitiveservices.CommitmentPlansClientListPlansByResourceGroupResponse]] + newListPlansBySubscriptionPager *tracker[azfake.PagerResponder[armcognitiveservices.CommitmentPlansClientListPlansBySubscriptionResponse]] + beginUpdatePlan *tracker[azfake.PollerResponder[armcognitiveservices.CommitmentPlansClientUpdatePlanResponse]] +} + +// Do implements the policy.Transporter interface for CommitmentPlansServerTransport. +func (c *CommitmentPlansServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *CommitmentPlansServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if commitmentPlansServerTransportInterceptor != nil { + res.resp, res.err, intercepted = commitmentPlansServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "CommitmentPlansClient.CreateOrUpdate": + res.resp, res.err = c.dispatchCreateOrUpdate(req) + case "CommitmentPlansClient.BeginCreateOrUpdateAssociation": + res.resp, res.err = c.dispatchBeginCreateOrUpdateAssociation(req) + case "CommitmentPlansClient.BeginCreateOrUpdatePlan": + res.resp, res.err = c.dispatchBeginCreateOrUpdatePlan(req) + case "CommitmentPlansClient.BeginDelete": + res.resp, res.err = c.dispatchBeginDelete(req) + case "CommitmentPlansClient.BeginDeleteAssociation": + res.resp, res.err = c.dispatchBeginDeleteAssociation(req) + case "CommitmentPlansClient.BeginDeletePlan": + res.resp, res.err = c.dispatchBeginDeletePlan(req) + case "CommitmentPlansClient.Get": + res.resp, res.err = c.dispatchGet(req) + case "CommitmentPlansClient.GetAssociation": + res.resp, res.err = c.dispatchGetAssociation(req) + case "CommitmentPlansClient.GetPlan": + res.resp, res.err = c.dispatchGetPlan(req) + case "CommitmentPlansClient.NewListPager": + res.resp, res.err = c.dispatchNewListPager(req) + case "CommitmentPlansClient.NewListAssociationsPager": + res.resp, res.err = c.dispatchNewListAssociationsPager(req) + case "CommitmentPlansClient.NewListPlansByResourceGroupPager": + res.resp, res.err = c.dispatchNewListPlansByResourceGroupPager(req) + case "CommitmentPlansClient.NewListPlansBySubscriptionPager": + res.resp, res.err = c.dispatchNewListPlansBySubscriptionPager(req) + case "CommitmentPlansClient.BeginUpdatePlan": + res.resp, res.err = c.dispatchBeginUpdatePlan(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *CommitmentPlansServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if c.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/commitmentPlans/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.CommitmentPlan](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + commitmentPlanNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("commitmentPlanName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, accountNameParam, commitmentPlanNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CommitmentPlan, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *CommitmentPlansServerTransport) dispatchBeginCreateOrUpdateAssociation(req *http.Request) (*http.Response, error) { + if c.srv.BeginCreateOrUpdateAssociation == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdateAssociation not implemented")} + } + beginCreateOrUpdateAssociation := c.beginCreateOrUpdateAssociation.get(req) + if beginCreateOrUpdateAssociation == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/commitmentPlans/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/accountAssociations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.CommitmentPlanAccountAssociation](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + commitmentPlanNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("commitmentPlanName")]) + if err != nil { + return nil, err + } + commitmentPlanAssociationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("commitmentPlanAssociationName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginCreateOrUpdateAssociation(req.Context(), resourceGroupNameParam, commitmentPlanNameParam, commitmentPlanAssociationNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdateAssociation = &respr + c.beginCreateOrUpdateAssociation.add(req, beginCreateOrUpdateAssociation) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdateAssociation, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + c.beginCreateOrUpdateAssociation.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdateAssociation) { + c.beginCreateOrUpdateAssociation.remove(req) + } + + return resp, nil +} + +func (c *CommitmentPlansServerTransport) dispatchBeginCreateOrUpdatePlan(req *http.Request) (*http.Response, error) { + if c.srv.BeginCreateOrUpdatePlan == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdatePlan not implemented")} + } + beginCreateOrUpdatePlan := c.beginCreateOrUpdatePlan.get(req) + if beginCreateOrUpdatePlan == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/commitmentPlans/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.CommitmentPlan](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + commitmentPlanNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("commitmentPlanName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginCreateOrUpdatePlan(req.Context(), resourceGroupNameParam, commitmentPlanNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdatePlan = &respr + c.beginCreateOrUpdatePlan.add(req, beginCreateOrUpdatePlan) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdatePlan, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + c.beginCreateOrUpdatePlan.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdatePlan) { + c.beginCreateOrUpdatePlan.remove(req) + } + + return resp, nil +} + +func (c *CommitmentPlansServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if c.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := c.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/commitmentPlans/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + commitmentPlanNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("commitmentPlanName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginDelete(req.Context(), resourceGroupNameParam, accountNameParam, commitmentPlanNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + c.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + c.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + c.beginDelete.remove(req) + } + + return resp, nil +} + +func (c *CommitmentPlansServerTransport) dispatchBeginDeleteAssociation(req *http.Request) (*http.Response, error) { + if c.srv.BeginDeleteAssociation == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDeleteAssociation not implemented")} + } + beginDeleteAssociation := c.beginDeleteAssociation.get(req) + if beginDeleteAssociation == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/commitmentPlans/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/accountAssociations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + commitmentPlanNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("commitmentPlanName")]) + if err != nil { + return nil, err + } + commitmentPlanAssociationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("commitmentPlanAssociationName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginDeleteAssociation(req.Context(), resourceGroupNameParam, commitmentPlanNameParam, commitmentPlanAssociationNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDeleteAssociation = &respr + c.beginDeleteAssociation.add(req, beginDeleteAssociation) + } + + resp, err := server.PollerResponderNext(beginDeleteAssociation, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + c.beginDeleteAssociation.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDeleteAssociation) { + c.beginDeleteAssociation.remove(req) + } + + return resp, nil +} + +func (c *CommitmentPlansServerTransport) dispatchBeginDeletePlan(req *http.Request) (*http.Response, error) { + if c.srv.BeginDeletePlan == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDeletePlan not implemented")} + } + beginDeletePlan := c.beginDeletePlan.get(req) + if beginDeletePlan == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/commitmentPlans/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + commitmentPlanNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("commitmentPlanName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginDeletePlan(req.Context(), resourceGroupNameParam, commitmentPlanNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDeletePlan = &respr + c.beginDeletePlan.add(req, beginDeletePlan) + } + + resp, err := server.PollerResponderNext(beginDeletePlan, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + c.beginDeletePlan.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDeletePlan) { + c.beginDeletePlan.remove(req) + } + + return resp, nil +} + +func (c *CommitmentPlansServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if c.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/commitmentPlans/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + commitmentPlanNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("commitmentPlanName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.Get(req.Context(), resourceGroupNameParam, accountNameParam, commitmentPlanNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CommitmentPlan, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *CommitmentPlansServerTransport) dispatchGetAssociation(req *http.Request) (*http.Response, error) { + if c.srv.GetAssociation == nil { + return nil, &nonRetriableError{errors.New("fake for method GetAssociation not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/commitmentPlans/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/accountAssociations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + commitmentPlanNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("commitmentPlanName")]) + if err != nil { + return nil, err + } + commitmentPlanAssociationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("commitmentPlanAssociationName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.GetAssociation(req.Context(), resourceGroupNameParam, commitmentPlanNameParam, commitmentPlanAssociationNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CommitmentPlanAccountAssociation, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *CommitmentPlansServerTransport) dispatchGetPlan(req *http.Request) (*http.Response, error) { + if c.srv.GetPlan == nil { + return nil, &nonRetriableError{errors.New("fake for method GetPlan not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/commitmentPlans/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + commitmentPlanNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("commitmentPlanName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.GetPlan(req.Context(), resourceGroupNameParam, commitmentPlanNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CommitmentPlan, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *CommitmentPlansServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if c.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := c.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/commitmentPlans` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + resp := c.srv.NewListPager(resourceGroupNameParam, accountNameParam, nil) + newListPager = &resp + c.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.CommitmentPlansClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + c.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + c.newListPager.remove(req) + } + return resp, nil +} + +func (c *CommitmentPlansServerTransport) dispatchNewListAssociationsPager(req *http.Request) (*http.Response, error) { + if c.srv.NewListAssociationsPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListAssociationsPager not implemented")} + } + newListAssociationsPager := c.newListAssociationsPager.get(req) + if newListAssociationsPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/commitmentPlans/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/accountAssociations` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + commitmentPlanNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("commitmentPlanName")]) + if err != nil { + return nil, err + } + resp := c.srv.NewListAssociationsPager(resourceGroupNameParam, commitmentPlanNameParam, nil) + newListAssociationsPager = &resp + c.newListAssociationsPager.add(req, newListAssociationsPager) + server.PagerResponderInjectNextLinks(newListAssociationsPager, req, func(page *armcognitiveservices.CommitmentPlansClientListAssociationsResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListAssociationsPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + c.newListAssociationsPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListAssociationsPager) { + c.newListAssociationsPager.remove(req) + } + return resp, nil +} + +func (c *CommitmentPlansServerTransport) dispatchNewListPlansByResourceGroupPager(req *http.Request) (*http.Response, error) { + if c.srv.NewListPlansByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPlansByResourceGroupPager not implemented")} + } + newListPlansByResourceGroupPager := c.newListPlansByResourceGroupPager.get(req) + if newListPlansByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/commitmentPlans` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := c.srv.NewListPlansByResourceGroupPager(resourceGroupNameParam, nil) + newListPlansByResourceGroupPager = &resp + c.newListPlansByResourceGroupPager.add(req, newListPlansByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListPlansByResourceGroupPager, req, func(page *armcognitiveservices.CommitmentPlansClientListPlansByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPlansByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + c.newListPlansByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPlansByResourceGroupPager) { + c.newListPlansByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (c *CommitmentPlansServerTransport) dispatchNewListPlansBySubscriptionPager(req *http.Request) (*http.Response, error) { + if c.srv.NewListPlansBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPlansBySubscriptionPager not implemented")} + } + newListPlansBySubscriptionPager := c.newListPlansBySubscriptionPager.get(req) + if newListPlansBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/commitmentPlans` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := c.srv.NewListPlansBySubscriptionPager(nil) + newListPlansBySubscriptionPager = &resp + c.newListPlansBySubscriptionPager.add(req, newListPlansBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListPlansBySubscriptionPager, req, func(page *armcognitiveservices.CommitmentPlansClientListPlansBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPlansBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + c.newListPlansBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPlansBySubscriptionPager) { + c.newListPlansBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (c *CommitmentPlansServerTransport) dispatchBeginUpdatePlan(req *http.Request) (*http.Response, error) { + if c.srv.BeginUpdatePlan == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdatePlan not implemented")} + } + beginUpdatePlan := c.beginUpdatePlan.get(req) + if beginUpdatePlan == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/commitmentPlans/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.PatchResourceTagsAndSKU](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + commitmentPlanNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("commitmentPlanName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginUpdatePlan(req.Context(), resourceGroupNameParam, commitmentPlanNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdatePlan = &respr + c.beginUpdatePlan.add(req, beginUpdatePlan) + } + + resp, err := server.PollerResponderNext(beginUpdatePlan, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + c.beginUpdatePlan.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdatePlan) { + c.beginUpdatePlan.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to CommitmentPlansServerTransport +var commitmentPlansServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_commitmenttiers_server.go b/test/local/armcognitiveservices/fake/zz_commitmenttiers_server.go new file mode 100644 index 000000000000..4bba428d6234 --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_commitmenttiers_server.go @@ -0,0 +1,125 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// CommitmentTiersServer is a fake server for instances of the armcognitiveservices.CommitmentTiersClient type. +type CommitmentTiersServer struct { + // NewListPager is the fake for method CommitmentTiersClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(location string, options *armcognitiveservices.CommitmentTiersClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.CommitmentTiersClientListResponse]) +} + +// NewCommitmentTiersServerTransport creates a new instance of CommitmentTiersServerTransport with the provided implementation. +// The returned CommitmentTiersServerTransport instance is connected to an instance of armcognitiveservices.CommitmentTiersClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewCommitmentTiersServerTransport(srv *CommitmentTiersServer) *CommitmentTiersServerTransport { + return &CommitmentTiersServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.CommitmentTiersClientListResponse]](), + } +} + +// CommitmentTiersServerTransport connects instances of armcognitiveservices.CommitmentTiersClient to instances of CommitmentTiersServer. +// Don't use this type directly, use NewCommitmentTiersServerTransport instead. +type CommitmentTiersServerTransport struct { + srv *CommitmentTiersServer + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.CommitmentTiersClientListResponse]] +} + +// Do implements the policy.Transporter interface for CommitmentTiersServerTransport. +func (c *CommitmentTiersServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *CommitmentTiersServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if commitmentTiersServerTransportInterceptor != nil { + res.resp, res.err, intercepted = commitmentTiersServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "CommitmentTiersClient.NewListPager": + res.resp, res.err = c.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *CommitmentTiersServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if c.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := c.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/commitmentTiers` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + resp := c.srv.NewListPager(locationParam, nil) + newListPager = &resp + c.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.CommitmentTiersClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + c.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + c.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to CommitmentTiersServerTransport +var commitmentTiersServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_defenderforaisettings_server.go b/test/local/armcognitiveservices/fake/zz_defenderforaisettings_server.go new file mode 100644 index 000000000000..62f5ece96868 --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_defenderforaisettings_server.go @@ -0,0 +1,267 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// DefenderForAISettingsServer is a fake server for instances of the armcognitiveservices.DefenderForAISettingsClient type. +type DefenderForAISettingsServer struct { + // CreateOrUpdate is the fake for method DefenderForAISettingsClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, accountName string, defenderForAISettingName string, defenderForAISettings armcognitiveservices.DefenderForAISetting, options *armcognitiveservices.DefenderForAISettingsClientCreateOrUpdateOptions) (resp azfake.Responder[armcognitiveservices.DefenderForAISettingsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method DefenderForAISettingsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, accountName string, defenderForAISettingName string, options *armcognitiveservices.DefenderForAISettingsClientGetOptions) (resp azfake.Responder[armcognitiveservices.DefenderForAISettingsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method DefenderForAISettingsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, accountName string, options *armcognitiveservices.DefenderForAISettingsClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.DefenderForAISettingsClientListResponse]) + + // Update is the fake for method DefenderForAISettingsClient.Update + // HTTP status codes to indicate success: http.StatusOK + Update func(ctx context.Context, resourceGroupName string, accountName string, defenderForAISettingName string, defenderForAISettings armcognitiveservices.DefenderForAISetting, options *armcognitiveservices.DefenderForAISettingsClientUpdateOptions) (resp azfake.Responder[armcognitiveservices.DefenderForAISettingsClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewDefenderForAISettingsServerTransport creates a new instance of DefenderForAISettingsServerTransport with the provided implementation. +// The returned DefenderForAISettingsServerTransport instance is connected to an instance of armcognitiveservices.DefenderForAISettingsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDefenderForAISettingsServerTransport(srv *DefenderForAISettingsServer) *DefenderForAISettingsServerTransport { + return &DefenderForAISettingsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.DefenderForAISettingsClientListResponse]](), + } +} + +// DefenderForAISettingsServerTransport connects instances of armcognitiveservices.DefenderForAISettingsClient to instances of DefenderForAISettingsServer. +// Don't use this type directly, use NewDefenderForAISettingsServerTransport instead. +type DefenderForAISettingsServerTransport struct { + srv *DefenderForAISettingsServer + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.DefenderForAISettingsClientListResponse]] +} + +// Do implements the policy.Transporter interface for DefenderForAISettingsServerTransport. +func (d *DefenderForAISettingsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DefenderForAISettingsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if defenderForAiSettingsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = defenderForAiSettingsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DefenderForAISettingsClient.CreateOrUpdate": + res.resp, res.err = d.dispatchCreateOrUpdate(req) + case "DefenderForAISettingsClient.Get": + res.resp, res.err = d.dispatchGet(req) + case "DefenderForAISettingsClient.NewListPager": + res.resp, res.err = d.dispatchNewListPager(req) + case "DefenderForAISettingsClient.Update": + res.resp, res.err = d.dispatchUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DefenderForAISettingsServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if d.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/defenderForAISettings/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.DefenderForAISetting](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + defenderForAISettingNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("defenderForAISettingName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, accountNameParam, defenderForAISettingNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DefenderForAISetting, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DefenderForAISettingsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/defenderForAISettings/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + defenderForAISettingNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("defenderForAISettingName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Get(req.Context(), resourceGroupNameParam, accountNameParam, defenderForAISettingNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DefenderForAISetting, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DefenderForAISettingsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if d.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := d.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/defenderForAISettings` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + resp := d.srv.NewListPager(resourceGroupNameParam, accountNameParam, nil) + newListPager = &resp + d.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.DefenderForAISettingsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + d.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + d.newListPager.remove(req) + } + return resp, nil +} + +func (d *DefenderForAISettingsServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) { + if d.srv.Update == nil { + return nil, &nonRetriableError{errors.New("fake for method Update not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/defenderForAISettings/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.DefenderForAISetting](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + defenderForAISettingNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("defenderForAISettingName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Update(req.Context(), resourceGroupNameParam, accountNameParam, defenderForAISettingNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DefenderForAISetting, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DefenderForAISettingsServerTransport +var defenderForAiSettingsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_deletedaccounts_server.go b/test/local/armcognitiveservices/fake/zz_deletedaccounts_server.go new file mode 100644 index 000000000000..bb9b63d7d5c2 --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_deletedaccounts_server.go @@ -0,0 +1,221 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// DeletedAccountsServer is a fake server for instances of the armcognitiveservices.DeletedAccountsClient type. +type DeletedAccountsServer struct { + // Get is the fake for method DeletedAccountsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, location string, resourceGroupName string, accountName string, options *armcognitiveservices.DeletedAccountsClientGetOptions) (resp azfake.Responder[armcognitiveservices.DeletedAccountsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method DeletedAccountsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armcognitiveservices.DeletedAccountsClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.DeletedAccountsClientListResponse]) + + // BeginPurge is the fake for method DeletedAccountsClient.BeginPurge + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginPurge func(ctx context.Context, location string, resourceGroupName string, accountName string, options *armcognitiveservices.DeletedAccountsClientBeginPurgeOptions) (resp azfake.PollerResponder[armcognitiveservices.DeletedAccountsClientPurgeResponse], errResp azfake.ErrorResponder) +} + +// NewDeletedAccountsServerTransport creates a new instance of DeletedAccountsServerTransport with the provided implementation. +// The returned DeletedAccountsServerTransport instance is connected to an instance of armcognitiveservices.DeletedAccountsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDeletedAccountsServerTransport(srv *DeletedAccountsServer) *DeletedAccountsServerTransport { + return &DeletedAccountsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.DeletedAccountsClientListResponse]](), + beginPurge: newTracker[azfake.PollerResponder[armcognitiveservices.DeletedAccountsClientPurgeResponse]](), + } +} + +// DeletedAccountsServerTransport connects instances of armcognitiveservices.DeletedAccountsClient to instances of DeletedAccountsServer. +// Don't use this type directly, use NewDeletedAccountsServerTransport instead. +type DeletedAccountsServerTransport struct { + srv *DeletedAccountsServer + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.DeletedAccountsClientListResponse]] + beginPurge *tracker[azfake.PollerResponder[armcognitiveservices.DeletedAccountsClientPurgeResponse]] +} + +// Do implements the policy.Transporter interface for DeletedAccountsServerTransport. +func (d *DeletedAccountsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DeletedAccountsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if deletedAccountsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = deletedAccountsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DeletedAccountsClient.Get": + res.resp, res.err = d.dispatchGet(req) + case "DeletedAccountsClient.NewListPager": + res.resp, res.err = d.dispatchNewListPager(req) + case "DeletedAccountsClient.BeginPurge": + res.resp, res.err = d.dispatchBeginPurge(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DeletedAccountsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/deletedAccounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Get(req.Context(), locationParam, resourceGroupNameParam, accountNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Account, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DeletedAccountsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if d.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := d.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/deletedAccounts` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := d.srv.NewListPager(nil) + newListPager = &resp + d.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.DeletedAccountsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + d.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + d.newListPager.remove(req) + } + return resp, nil +} + +func (d *DeletedAccountsServerTransport) dispatchBeginPurge(req *http.Request) (*http.Response, error) { + if d.srv.BeginPurge == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginPurge not implemented")} + } + beginPurge := d.beginPurge.get(req) + if beginPurge == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/deletedAccounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.BeginPurge(req.Context(), locationParam, resourceGroupNameParam, accountNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginPurge = &respr + d.beginPurge.add(req, beginPurge) + } + + resp, err := server.PollerResponderNext(beginPurge, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + d.beginPurge.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginPurge) { + d.beginPurge.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to DeletedAccountsServerTransport +var deletedAccountsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_deployments_server.go b/test/local/armcognitiveservices/fake/zz_deployments_server.go new file mode 100644 index 000000000000..c1e32fef5bc0 --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_deployments_server.go @@ -0,0 +1,488 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// DeploymentsServer is a fake server for instances of the armcognitiveservices.DeploymentsClient type. +type DeploymentsServer struct { + // BeginCreateOrUpdate is the fake for method DeploymentsClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, deployment armcognitiveservices.Deployment, options *armcognitiveservices.DeploymentsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armcognitiveservices.DeploymentsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method DeploymentsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, options *armcognitiveservices.DeploymentsClientBeginDeleteOptions) (resp azfake.PollerResponder[armcognitiveservices.DeploymentsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method DeploymentsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, options *armcognitiveservices.DeploymentsClientGetOptions) (resp azfake.Responder[armcognitiveservices.DeploymentsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method DeploymentsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, accountName string, options *armcognitiveservices.DeploymentsClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.DeploymentsClientListResponse]) + + // NewListSKUsPager is the fake for method DeploymentsClient.NewListSKUsPager + // HTTP status codes to indicate success: http.StatusOK + NewListSKUsPager func(resourceGroupName string, accountName string, deploymentName string, options *armcognitiveservices.DeploymentsClientListSKUsOptions) (resp azfake.PagerResponder[armcognitiveservices.DeploymentsClientListSKUsResponse]) + + // Pause is the fake for method DeploymentsClient.Pause + // HTTP status codes to indicate success: http.StatusOK + Pause func(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, options *armcognitiveservices.DeploymentsClientPauseOptions) (resp azfake.Responder[armcognitiveservices.DeploymentsClientPauseResponse], errResp azfake.ErrorResponder) + + // Resume is the fake for method DeploymentsClient.Resume + // HTTP status codes to indicate success: http.StatusOK + Resume func(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, options *armcognitiveservices.DeploymentsClientResumeOptions) (resp azfake.Responder[armcognitiveservices.DeploymentsClientResumeResponse], errResp azfake.ErrorResponder) + + // BeginUpdate is the fake for method DeploymentsClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, deployment armcognitiveservices.PatchResourceTagsAndSKU, options *armcognitiveservices.DeploymentsClientBeginUpdateOptions) (resp azfake.PollerResponder[armcognitiveservices.DeploymentsClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewDeploymentsServerTransport creates a new instance of DeploymentsServerTransport with the provided implementation. +// The returned DeploymentsServerTransport instance is connected to an instance of armcognitiveservices.DeploymentsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDeploymentsServerTransport(srv *DeploymentsServer) *DeploymentsServerTransport { + return &DeploymentsServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armcognitiveservices.DeploymentsClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armcognitiveservices.DeploymentsClientDeleteResponse]](), + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.DeploymentsClientListResponse]](), + newListSKUsPager: newTracker[azfake.PagerResponder[armcognitiveservices.DeploymentsClientListSKUsResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armcognitiveservices.DeploymentsClientUpdateResponse]](), + } +} + +// DeploymentsServerTransport connects instances of armcognitiveservices.DeploymentsClient to instances of DeploymentsServer. +// Don't use this type directly, use NewDeploymentsServerTransport instead. +type DeploymentsServerTransport struct { + srv *DeploymentsServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armcognitiveservices.DeploymentsClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armcognitiveservices.DeploymentsClientDeleteResponse]] + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.DeploymentsClientListResponse]] + newListSKUsPager *tracker[azfake.PagerResponder[armcognitiveservices.DeploymentsClientListSKUsResponse]] + beginUpdate *tracker[azfake.PollerResponder[armcognitiveservices.DeploymentsClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for DeploymentsServerTransport. +func (d *DeploymentsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DeploymentsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if deploymentsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = deploymentsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DeploymentsClient.BeginCreateOrUpdate": + res.resp, res.err = d.dispatchBeginCreateOrUpdate(req) + case "DeploymentsClient.BeginDelete": + res.resp, res.err = d.dispatchBeginDelete(req) + case "DeploymentsClient.Get": + res.resp, res.err = d.dispatchGet(req) + case "DeploymentsClient.NewListPager": + res.resp, res.err = d.dispatchNewListPager(req) + case "DeploymentsClient.NewListSKUsPager": + res.resp, res.err = d.dispatchNewListSKUsPager(req) + case "DeploymentsClient.Pause": + res.resp, res.err = d.dispatchPause(req) + case "DeploymentsClient.Resume": + res.resp, res.err = d.dispatchResume(req) + case "DeploymentsClient.BeginUpdate": + res.resp, res.err = d.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DeploymentsServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if d.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := d.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/deployments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.Deployment](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + deploymentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("deploymentName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, accountNameParam, deploymentNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + d.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + d.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + d.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (d *DeploymentsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if d.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := d.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/deployments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + deploymentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("deploymentName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.BeginDelete(req.Context(), resourceGroupNameParam, accountNameParam, deploymentNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + d.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + d.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + d.beginDelete.remove(req) + } + + return resp, nil +} + +func (d *DeploymentsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/deployments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + deploymentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("deploymentName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Get(req.Context(), resourceGroupNameParam, accountNameParam, deploymentNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Deployment, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DeploymentsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if d.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := d.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/deployments` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + resp := d.srv.NewListPager(resourceGroupNameParam, accountNameParam, nil) + newListPager = &resp + d.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.DeploymentsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + d.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + d.newListPager.remove(req) + } + return resp, nil +} + +func (d *DeploymentsServerTransport) dispatchNewListSKUsPager(req *http.Request) (*http.Response, error) { + if d.srv.NewListSKUsPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListSKUsPager not implemented")} + } + newListSKUsPager := d.newListSKUsPager.get(req) + if newListSKUsPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/deployments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/skus` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + deploymentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("deploymentName")]) + if err != nil { + return nil, err + } + resp := d.srv.NewListSKUsPager(resourceGroupNameParam, accountNameParam, deploymentNameParam, nil) + newListSKUsPager = &resp + d.newListSKUsPager.add(req, newListSKUsPager) + server.PagerResponderInjectNextLinks(newListSKUsPager, req, func(page *armcognitiveservices.DeploymentsClientListSKUsResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListSKUsPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + d.newListSKUsPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListSKUsPager) { + d.newListSKUsPager.remove(req) + } + return resp, nil +} + +func (d *DeploymentsServerTransport) dispatchPause(req *http.Request) (*http.Response, error) { + if d.srv.Pause == nil { + return nil, &nonRetriableError{errors.New("fake for method Pause not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/deployments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/pause` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + deploymentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("deploymentName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Pause(req.Context(), resourceGroupNameParam, accountNameParam, deploymentNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Deployment, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DeploymentsServerTransport) dispatchResume(req *http.Request) (*http.Response, error) { + if d.srv.Resume == nil { + return nil, &nonRetriableError{errors.New("fake for method Resume not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/deployments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resume` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + deploymentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("deploymentName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Resume(req.Context(), resourceGroupNameParam, accountNameParam, deploymentNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Deployment, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DeploymentsServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if d.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := d.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/deployments/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.PatchResourceTagsAndSKU](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + deploymentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("deploymentName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.BeginUpdate(req.Context(), resourceGroupNameParam, accountNameParam, deploymentNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + d.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + d.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + d.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to DeploymentsServerTransport +var deploymentsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_encryptionscopes_server.go b/test/local/armcognitiveservices/fake/zz_encryptionscopes_server.go new file mode 100644 index 000000000000..eea174836f26 --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_encryptionscopes_server.go @@ -0,0 +1,276 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// EncryptionScopesServer is a fake server for instances of the armcognitiveservices.EncryptionScopesClient type. +type EncryptionScopesServer struct { + // CreateOrUpdate is the fake for method EncryptionScopesClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, accountName string, encryptionScopeName string, encryptionScope armcognitiveservices.EncryptionScope, options *armcognitiveservices.EncryptionScopesClientCreateOrUpdateOptions) (resp azfake.Responder[armcognitiveservices.EncryptionScopesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method EncryptionScopesClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, accountName string, encryptionScopeName string, options *armcognitiveservices.EncryptionScopesClientBeginDeleteOptions) (resp azfake.PollerResponder[armcognitiveservices.EncryptionScopesClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method EncryptionScopesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, accountName string, encryptionScopeName string, options *armcognitiveservices.EncryptionScopesClientGetOptions) (resp azfake.Responder[armcognitiveservices.EncryptionScopesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method EncryptionScopesClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, accountName string, options *armcognitiveservices.EncryptionScopesClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.EncryptionScopesClientListResponse]) +} + +// NewEncryptionScopesServerTransport creates a new instance of EncryptionScopesServerTransport with the provided implementation. +// The returned EncryptionScopesServerTransport instance is connected to an instance of armcognitiveservices.EncryptionScopesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewEncryptionScopesServerTransport(srv *EncryptionScopesServer) *EncryptionScopesServerTransport { + return &EncryptionScopesServerTransport{ + srv: srv, + beginDelete: newTracker[azfake.PollerResponder[armcognitiveservices.EncryptionScopesClientDeleteResponse]](), + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.EncryptionScopesClientListResponse]](), + } +} + +// EncryptionScopesServerTransport connects instances of armcognitiveservices.EncryptionScopesClient to instances of EncryptionScopesServer. +// Don't use this type directly, use NewEncryptionScopesServerTransport instead. +type EncryptionScopesServerTransport struct { + srv *EncryptionScopesServer + beginDelete *tracker[azfake.PollerResponder[armcognitiveservices.EncryptionScopesClientDeleteResponse]] + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.EncryptionScopesClientListResponse]] +} + +// Do implements the policy.Transporter interface for EncryptionScopesServerTransport. +func (e *EncryptionScopesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return e.dispatchToMethodFake(req, method) +} + +func (e *EncryptionScopesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if encryptionScopesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = encryptionScopesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "EncryptionScopesClient.CreateOrUpdate": + res.resp, res.err = e.dispatchCreateOrUpdate(req) + case "EncryptionScopesClient.BeginDelete": + res.resp, res.err = e.dispatchBeginDelete(req) + case "EncryptionScopesClient.Get": + res.resp, res.err = e.dispatchGet(req) + case "EncryptionScopesClient.NewListPager": + res.resp, res.err = e.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (e *EncryptionScopesServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if e.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/encryptionScopes/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.EncryptionScope](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + encryptionScopeNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("encryptionScopeName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, accountNameParam, encryptionScopeNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).EncryptionScope, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *EncryptionScopesServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if e.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := e.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/encryptionScopes/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + encryptionScopeNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("encryptionScopeName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.BeginDelete(req.Context(), resourceGroupNameParam, accountNameParam, encryptionScopeNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + e.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + e.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + e.beginDelete.remove(req) + } + + return resp, nil +} + +func (e *EncryptionScopesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if e.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/encryptionScopes/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + encryptionScopeNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("encryptionScopeName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.Get(req.Context(), resourceGroupNameParam, accountNameParam, encryptionScopeNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).EncryptionScope, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *EncryptionScopesServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if e.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := e.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/encryptionScopes` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + resp := e.srv.NewListPager(resourceGroupNameParam, accountNameParam, nil) + newListPager = &resp + e.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.EncryptionScopesClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + e.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + e.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to EncryptionScopesServerTransport +var encryptionScopesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_internal.go b/test/local/armcognitiveservices/fake/zz_internal.go new file mode 100644 index 000000000000..504fffe54caa --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_internal.go @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "reflect" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getOptional[T any](v T) *T { + if reflect.ValueOf(v).IsZero() { + return nil + } + return &v +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func parseOptional[T any](v string, parse func(v string) (T, error)) (*T, error) { + if v == "" { + return nil, nil + } + t, err := parse(v) + if err != nil { + return nil, err + } + return &t, nil +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/local/armcognitiveservices/fake/zz_locationbasedmodelcapacities_server.go b/test/local/armcognitiveservices/fake/zz_locationbasedmodelcapacities_server.go new file mode 100644 index 000000000000..455e815bb723 --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_locationbasedmodelcapacities_server.go @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// LocationBasedModelCapacitiesServer is a fake server for instances of the armcognitiveservices.LocationBasedModelCapacitiesClient type. +type LocationBasedModelCapacitiesServer struct { + // NewListPager is the fake for method LocationBasedModelCapacitiesClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(location string, modelFormat string, modelName string, modelVersion string, options *armcognitiveservices.LocationBasedModelCapacitiesClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.LocationBasedModelCapacitiesClientListResponse]) +} + +// NewLocationBasedModelCapacitiesServerTransport creates a new instance of LocationBasedModelCapacitiesServerTransport with the provided implementation. +// The returned LocationBasedModelCapacitiesServerTransport instance is connected to an instance of armcognitiveservices.LocationBasedModelCapacitiesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewLocationBasedModelCapacitiesServerTransport(srv *LocationBasedModelCapacitiesServer) *LocationBasedModelCapacitiesServerTransport { + return &LocationBasedModelCapacitiesServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.LocationBasedModelCapacitiesClientListResponse]](), + } +} + +// LocationBasedModelCapacitiesServerTransport connects instances of armcognitiveservices.LocationBasedModelCapacitiesClient to instances of LocationBasedModelCapacitiesServer. +// Don't use this type directly, use NewLocationBasedModelCapacitiesServerTransport instead. +type LocationBasedModelCapacitiesServerTransport struct { + srv *LocationBasedModelCapacitiesServer + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.LocationBasedModelCapacitiesClientListResponse]] +} + +// Do implements the policy.Transporter interface for LocationBasedModelCapacitiesServerTransport. +func (l *LocationBasedModelCapacitiesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return l.dispatchToMethodFake(req, method) +} + +func (l *LocationBasedModelCapacitiesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if locationBasedModelCapacitiesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = locationBasedModelCapacitiesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "LocationBasedModelCapacitiesClient.NewListPager": + res.resp, res.err = l.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (l *LocationBasedModelCapacitiesServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if l.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := l.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/modelCapacities` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + resp := l.srv.NewListPager(locationParam, qp.Get("modelFormat"), qp.Get("modelName"), qp.Get("modelVersion"), nil) + newListPager = &resp + l.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.LocationBasedModelCapacitiesClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + l.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + l.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to LocationBasedModelCapacitiesServerTransport +var locationBasedModelCapacitiesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_managednetworkprovisions_server.go b/test/local/armcognitiveservices/fake/zz_managednetworkprovisions_server.go new file mode 100644 index 000000000000..662320d4563a --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_managednetworkprovisions_server.go @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "reflect" + "regexp" + "slices" +) + +// ManagedNetworkProvisionsServer is a fake server for instances of the armcognitiveservices.ManagedNetworkProvisionsClient type. +type ManagedNetworkProvisionsServer struct { + // BeginProvisionManagedNetwork is the fake for method ManagedNetworkProvisionsClient.BeginProvisionManagedNetwork + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginProvisionManagedNetwork func(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, options *armcognitiveservices.ManagedNetworkProvisionsClientBeginProvisionManagedNetworkOptions) (resp azfake.PollerResponder[armcognitiveservices.ManagedNetworkProvisionsClientProvisionManagedNetworkResponse], errResp azfake.ErrorResponder) +} + +// NewManagedNetworkProvisionsServerTransport creates a new instance of ManagedNetworkProvisionsServerTransport with the provided implementation. +// The returned ManagedNetworkProvisionsServerTransport instance is connected to an instance of armcognitiveservices.ManagedNetworkProvisionsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewManagedNetworkProvisionsServerTransport(srv *ManagedNetworkProvisionsServer) *ManagedNetworkProvisionsServerTransport { + return &ManagedNetworkProvisionsServerTransport{ + srv: srv, + beginProvisionManagedNetwork: newTracker[azfake.PollerResponder[armcognitiveservices.ManagedNetworkProvisionsClientProvisionManagedNetworkResponse]](), + } +} + +// ManagedNetworkProvisionsServerTransport connects instances of armcognitiveservices.ManagedNetworkProvisionsClient to instances of ManagedNetworkProvisionsServer. +// Don't use this type directly, use NewManagedNetworkProvisionsServerTransport instead. +type ManagedNetworkProvisionsServerTransport struct { + srv *ManagedNetworkProvisionsServer + beginProvisionManagedNetwork *tracker[azfake.PollerResponder[armcognitiveservices.ManagedNetworkProvisionsClientProvisionManagedNetworkResponse]] +} + +// Do implements the policy.Transporter interface for ManagedNetworkProvisionsServerTransport. +func (m *ManagedNetworkProvisionsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToMethodFake(req, method) +} + +func (m *ManagedNetworkProvisionsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if managedNetworkProvisionsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = managedNetworkProvisionsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ManagedNetworkProvisionsClient.BeginProvisionManagedNetwork": + res.resp, res.err = m.dispatchBeginProvisionManagedNetwork(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *ManagedNetworkProvisionsServerTransport) dispatchBeginProvisionManagedNetwork(req *http.Request) (*http.Response, error) { + if m.srv.BeginProvisionManagedNetwork == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginProvisionManagedNetwork not implemented")} + } + beginProvisionManagedNetwork := m.beginProvisionManagedNetwork.get(req) + if beginProvisionManagedNetwork == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/managedNetworks/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/provision` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.ManagedNetworkProvisionOptions](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + managedNetworkNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managedNetworkName")]) + if err != nil { + return nil, err + } + var options *armcognitiveservices.ManagedNetworkProvisionsClientBeginProvisionManagedNetworkOptions + if !reflect.ValueOf(body).IsZero() { + options = &armcognitiveservices.ManagedNetworkProvisionsClientBeginProvisionManagedNetworkOptions{ + Body: &body, + } + } + respr, errRespr := m.srv.BeginProvisionManagedNetwork(req.Context(), resourceGroupNameParam, accountNameParam, managedNetworkNameParam, options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginProvisionManagedNetwork = &respr + m.beginProvisionManagedNetwork.add(req, beginProvisionManagedNetwork) + } + + resp, err := server.PollerResponderNext(beginProvisionManagedNetwork, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + m.beginProvisionManagedNetwork.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginProvisionManagedNetwork) { + m.beginProvisionManagedNetwork.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to ManagedNetworkProvisionsServerTransport +var managedNetworkProvisionsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_managednetworksettings_server.go b/test/local/armcognitiveservices/fake/zz_managednetworksettings_server.go new file mode 100644 index 000000000000..f596f29df446 --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_managednetworksettings_server.go @@ -0,0 +1,349 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// ManagedNetworkSettingsServer is a fake server for instances of the armcognitiveservices.ManagedNetworkSettingsClient type. +type ManagedNetworkSettingsServer struct { + // BeginDelete is the fake for method ManagedNetworkSettingsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, options *armcognitiveservices.ManagedNetworkSettingsClientBeginDeleteOptions) (resp azfake.PollerResponder[armcognitiveservices.ManagedNetworkSettingsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method ManagedNetworkSettingsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, options *armcognitiveservices.ManagedNetworkSettingsClientGetOptions) (resp azfake.Responder[armcognitiveservices.ManagedNetworkSettingsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method ManagedNetworkSettingsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, accountName string, options *armcognitiveservices.ManagedNetworkSettingsClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.ManagedNetworkSettingsClientListResponse]) + + // BeginPatch is the fake for method ManagedNetworkSettingsClient.BeginPatch + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginPatch func(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, body armcognitiveservices.ManagedNetworkSettingsPropertiesBasicResource, options *armcognitiveservices.ManagedNetworkSettingsClientBeginPatchOptions) (resp azfake.PollerResponder[armcognitiveservices.ManagedNetworkSettingsClientPatchResponse], errResp azfake.ErrorResponder) + + // BeginPut is the fake for method ManagedNetworkSettingsClient.BeginPut + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginPut func(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, body armcognitiveservices.ManagedNetworkSettingsPropertiesBasicResource, options *armcognitiveservices.ManagedNetworkSettingsClientBeginPutOptions) (resp azfake.PollerResponder[armcognitiveservices.ManagedNetworkSettingsClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewManagedNetworkSettingsServerTransport creates a new instance of ManagedNetworkSettingsServerTransport with the provided implementation. +// The returned ManagedNetworkSettingsServerTransport instance is connected to an instance of armcognitiveservices.ManagedNetworkSettingsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewManagedNetworkSettingsServerTransport(srv *ManagedNetworkSettingsServer) *ManagedNetworkSettingsServerTransport { + return &ManagedNetworkSettingsServerTransport{ + srv: srv, + beginDelete: newTracker[azfake.PollerResponder[armcognitiveservices.ManagedNetworkSettingsClientDeleteResponse]](), + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.ManagedNetworkSettingsClientListResponse]](), + beginPatch: newTracker[azfake.PollerResponder[armcognitiveservices.ManagedNetworkSettingsClientPatchResponse]](), + beginPut: newTracker[azfake.PollerResponder[armcognitiveservices.ManagedNetworkSettingsClientPutResponse]](), + } +} + +// ManagedNetworkSettingsServerTransport connects instances of armcognitiveservices.ManagedNetworkSettingsClient to instances of ManagedNetworkSettingsServer. +// Don't use this type directly, use NewManagedNetworkSettingsServerTransport instead. +type ManagedNetworkSettingsServerTransport struct { + srv *ManagedNetworkSettingsServer + beginDelete *tracker[azfake.PollerResponder[armcognitiveservices.ManagedNetworkSettingsClientDeleteResponse]] + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.ManagedNetworkSettingsClientListResponse]] + beginPatch *tracker[azfake.PollerResponder[armcognitiveservices.ManagedNetworkSettingsClientPatchResponse]] + beginPut *tracker[azfake.PollerResponder[armcognitiveservices.ManagedNetworkSettingsClientPutResponse]] +} + +// Do implements the policy.Transporter interface for ManagedNetworkSettingsServerTransport. +func (m *ManagedNetworkSettingsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToMethodFake(req, method) +} + +func (m *ManagedNetworkSettingsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if managedNetworkSettingsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = managedNetworkSettingsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ManagedNetworkSettingsClient.BeginDelete": + res.resp, res.err = m.dispatchBeginDelete(req) + case "ManagedNetworkSettingsClient.Get": + res.resp, res.err = m.dispatchGet(req) + case "ManagedNetworkSettingsClient.NewListPager": + res.resp, res.err = m.dispatchNewListPager(req) + case "ManagedNetworkSettingsClient.BeginPatch": + res.resp, res.err = m.dispatchBeginPatch(req) + case "ManagedNetworkSettingsClient.BeginPut": + res.resp, res.err = m.dispatchBeginPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *ManagedNetworkSettingsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if m.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := m.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/managedNetworks/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + managedNetworkNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managedNetworkName")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.BeginDelete(req.Context(), resourceGroupNameParam, accountNameParam, managedNetworkNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + m.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + m.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + m.beginDelete.remove(req) + } + + return resp, nil +} + +func (m *ManagedNetworkSettingsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if m.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/managedNetworks/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + managedNetworkNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managedNetworkName")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.Get(req.Context(), resourceGroupNameParam, accountNameParam, managedNetworkNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ManagedNetworkSettingsPropertiesBasicResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *ManagedNetworkSettingsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if m.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := m.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/managedNetworks` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + resp := m.srv.NewListPager(resourceGroupNameParam, accountNameParam, nil) + newListPager = &resp + m.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.ManagedNetworkSettingsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + m.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + m.newListPager.remove(req) + } + return resp, nil +} + +func (m *ManagedNetworkSettingsServerTransport) dispatchBeginPatch(req *http.Request) (*http.Response, error) { + if m.srv.BeginPatch == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginPatch not implemented")} + } + beginPatch := m.beginPatch.get(req) + if beginPatch == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/managedNetworks/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.ManagedNetworkSettingsPropertiesBasicResource](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + managedNetworkNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managedNetworkName")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.BeginPatch(req.Context(), resourceGroupNameParam, accountNameParam, managedNetworkNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginPatch = &respr + m.beginPatch.add(req, beginPatch) + } + + resp, err := server.PollerResponderNext(beginPatch, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + m.beginPatch.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginPatch) { + m.beginPatch.remove(req) + } + + return resp, nil +} + +func (m *ManagedNetworkSettingsServerTransport) dispatchBeginPut(req *http.Request) (*http.Response, error) { + if m.srv.BeginPut == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginPut not implemented")} + } + beginPut := m.beginPut.get(req) + if beginPut == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/managedNetworks/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.ManagedNetworkSettingsPropertiesBasicResource](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + managedNetworkNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managedNetworkName")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.BeginPut(req.Context(), resourceGroupNameParam, accountNameParam, managedNetworkNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginPut = &respr + m.beginPut.add(req, beginPut) + } + + resp, err := server.PollerResponderNext(beginPut, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + m.beginPut.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginPut) { + m.beginPut.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to ManagedNetworkSettingsServerTransport +var managedNetworkSettingsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_management_server.go b/test/local/armcognitiveservices/fake/zz_management_server.go new file mode 100644 index 000000000000..d7052bff26bb --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_management_server.go @@ -0,0 +1,187 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// ManagementServer is a fake server for instances of the armcognitiveservices.ManagementClient type. +type ManagementServer struct { + // CalculateModelCapacity is the fake for method ManagementClient.CalculateModelCapacity + // HTTP status codes to indicate success: http.StatusOK + CalculateModelCapacity func(ctx context.Context, parameters armcognitiveservices.CalculateModelCapacityParameter, options *armcognitiveservices.ManagementClientCalculateModelCapacityOptions) (resp azfake.Responder[armcognitiveservices.ManagementClientCalculateModelCapacityResponse], errResp azfake.ErrorResponder) + + // CheckDomainAvailability is the fake for method ManagementClient.CheckDomainAvailability + // HTTP status codes to indicate success: http.StatusOK + CheckDomainAvailability func(ctx context.Context, parameters armcognitiveservices.CheckDomainAvailabilityParameter, options *armcognitiveservices.ManagementClientCheckDomainAvailabilityOptions) (resp azfake.Responder[armcognitiveservices.ManagementClientCheckDomainAvailabilityResponse], errResp azfake.ErrorResponder) + + // CheckSKUAvailability is the fake for method ManagementClient.CheckSKUAvailability + // HTTP status codes to indicate success: http.StatusOK + CheckSKUAvailability func(ctx context.Context, location string, parameters armcognitiveservices.CheckSKUAvailabilityParameter, options *armcognitiveservices.ManagementClientCheckSKUAvailabilityOptions) (resp azfake.Responder[armcognitiveservices.ManagementClientCheckSKUAvailabilityResponse], errResp azfake.ErrorResponder) +} + +// NewManagementServerTransport creates a new instance of ManagementServerTransport with the provided implementation. +// The returned ManagementServerTransport instance is connected to an instance of armcognitiveservices.ManagementClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewManagementServerTransport(srv *ManagementServer) *ManagementServerTransport { + return &ManagementServerTransport{srv: srv} +} + +// ManagementServerTransport connects instances of armcognitiveservices.ManagementClient to instances of ManagementServer. +// Don't use this type directly, use NewManagementServerTransport instead. +type ManagementServerTransport struct { + srv *ManagementServer +} + +// Do implements the policy.Transporter interface for ManagementServerTransport. +func (m *ManagementServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToMethodFake(req, method) +} + +func (m *ManagementServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if managementServerTransportInterceptor != nil { + res.resp, res.err, intercepted = managementServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ManagementClient.CalculateModelCapacity": + res.resp, res.err = m.dispatchCalculateModelCapacity(req) + case "ManagementClient.CheckDomainAvailability": + res.resp, res.err = m.dispatchCheckDomainAvailability(req) + case "ManagementClient.CheckSKUAvailability": + res.resp, res.err = m.dispatchCheckSKUAvailability(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *ManagementServerTransport) dispatchCalculateModelCapacity(req *http.Request) (*http.Response, error) { + if m.srv.CalculateModelCapacity == nil { + return nil, &nonRetriableError{errors.New("fake for method CalculateModelCapacity not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/calculateModelCapacity` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.CalculateModelCapacityParameter](req) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.CalculateModelCapacity(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CalculateModelCapacityResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *ManagementServerTransport) dispatchCheckDomainAvailability(req *http.Request) (*http.Response, error) { + if m.srv.CheckDomainAvailability == nil { + return nil, &nonRetriableError{errors.New("fake for method CheckDomainAvailability not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/checkDomainAvailability` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.CheckDomainAvailabilityParameter](req) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.CheckDomainAvailability(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DomainAvailability, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *ManagementServerTransport) dispatchCheckSKUAvailability(req *http.Request) (*http.Response, error) { + if m.srv.CheckSKUAvailability == nil { + return nil, &nonRetriableError{errors.New("fake for method CheckSKUAvailability not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/checkSkuAvailability` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.CheckSKUAvailabilityParameter](req) + if err != nil { + return nil, err + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.CheckSKUAvailability(req.Context(), locationParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).SKUAvailabilityListResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ManagementServerTransport +var managementServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_modelcapacities_server.go b/test/local/armcognitiveservices/fake/zz_modelcapacities_server.go new file mode 100644 index 000000000000..6b791d12723d --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_modelcapacities_server.go @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "regexp" + "slices" +) + +// ModelCapacitiesServer is a fake server for instances of the armcognitiveservices.ModelCapacitiesClient type. +type ModelCapacitiesServer struct { + // NewListPager is the fake for method ModelCapacitiesClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(modelFormat string, modelName string, modelVersion string, options *armcognitiveservices.ModelCapacitiesClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.ModelCapacitiesClientListResponse]) +} + +// NewModelCapacitiesServerTransport creates a new instance of ModelCapacitiesServerTransport with the provided implementation. +// The returned ModelCapacitiesServerTransport instance is connected to an instance of armcognitiveservices.ModelCapacitiesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewModelCapacitiesServerTransport(srv *ModelCapacitiesServer) *ModelCapacitiesServerTransport { + return &ModelCapacitiesServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.ModelCapacitiesClientListResponse]](), + } +} + +// ModelCapacitiesServerTransport connects instances of armcognitiveservices.ModelCapacitiesClient to instances of ModelCapacitiesServer. +// Don't use this type directly, use NewModelCapacitiesServerTransport instead. +type ModelCapacitiesServerTransport struct { + srv *ModelCapacitiesServer + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.ModelCapacitiesClientListResponse]] +} + +// Do implements the policy.Transporter interface for ModelCapacitiesServerTransport. +func (m *ModelCapacitiesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToMethodFake(req, method) +} + +func (m *ModelCapacitiesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if modelCapacitiesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = modelCapacitiesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ModelCapacitiesClient.NewListPager": + res.resp, res.err = m.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *ModelCapacitiesServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if m.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := m.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/modelCapacities` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + resp := m.srv.NewListPager(qp.Get("modelFormat"), qp.Get("modelName"), qp.Get("modelVersion"), nil) + newListPager = &resp + m.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.ModelCapacitiesClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + m.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + m.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ModelCapacitiesServerTransport +var modelCapacitiesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_models_server.go b/test/local/armcognitiveservices/fake/zz_models_server.go new file mode 100644 index 000000000000..e1ec06ecc9cd --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_models_server.go @@ -0,0 +1,125 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// ModelsServer is a fake server for instances of the armcognitiveservices.ModelsClient type. +type ModelsServer struct { + // NewListPager is the fake for method ModelsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(location string, options *armcognitiveservices.ModelsClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.ModelsClientListResponse]) +} + +// NewModelsServerTransport creates a new instance of ModelsServerTransport with the provided implementation. +// The returned ModelsServerTransport instance is connected to an instance of armcognitiveservices.ModelsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewModelsServerTransport(srv *ModelsServer) *ModelsServerTransport { + return &ModelsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.ModelsClientListResponse]](), + } +} + +// ModelsServerTransport connects instances of armcognitiveservices.ModelsClient to instances of ModelsServer. +// Don't use this type directly, use NewModelsServerTransport instead. +type ModelsServerTransport struct { + srv *ModelsServer + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.ModelsClientListResponse]] +} + +// Do implements the policy.Transporter interface for ModelsServerTransport. +func (m *ModelsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToMethodFake(req, method) +} + +func (m *ModelsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if modelsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = modelsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ModelsClient.NewListPager": + res.resp, res.err = m.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *ModelsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if m.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := m.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/models` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + resp := m.srv.NewListPager(locationParam, nil) + newListPager = &resp + m.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.ModelsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + m.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + m.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ModelsServerTransport +var modelsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_networksecurityperimeterconfigurations_server.go b/test/local/armcognitiveservices/fake/zz_networksecurityperimeterconfigurations_server.go new file mode 100644 index 000000000000..d5f2eee1c456 --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_networksecurityperimeterconfigurations_server.go @@ -0,0 +1,229 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// NetworkSecurityPerimeterConfigurationsServer is a fake server for instances of the armcognitiveservices.NetworkSecurityPerimeterConfigurationsClient type. +type NetworkSecurityPerimeterConfigurationsServer struct { + // Get is the fake for method NetworkSecurityPerimeterConfigurationsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, accountName string, nspConfigurationName string, options *armcognitiveservices.NetworkSecurityPerimeterConfigurationsClientGetOptions) (resp azfake.Responder[armcognitiveservices.NetworkSecurityPerimeterConfigurationsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method NetworkSecurityPerimeterConfigurationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, accountName string, options *armcognitiveservices.NetworkSecurityPerimeterConfigurationsClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.NetworkSecurityPerimeterConfigurationsClientListResponse]) + + // BeginReconcile is the fake for method NetworkSecurityPerimeterConfigurationsClient.BeginReconcile + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginReconcile func(ctx context.Context, resourceGroupName string, accountName string, nspConfigurationName string, options *armcognitiveservices.NetworkSecurityPerimeterConfigurationsClientBeginReconcileOptions) (resp azfake.PollerResponder[armcognitiveservices.NetworkSecurityPerimeterConfigurationsClientReconcileResponse], errResp azfake.ErrorResponder) +} + +// NewNetworkSecurityPerimeterConfigurationsServerTransport creates a new instance of NetworkSecurityPerimeterConfigurationsServerTransport with the provided implementation. +// The returned NetworkSecurityPerimeterConfigurationsServerTransport instance is connected to an instance of armcognitiveservices.NetworkSecurityPerimeterConfigurationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewNetworkSecurityPerimeterConfigurationsServerTransport(srv *NetworkSecurityPerimeterConfigurationsServer) *NetworkSecurityPerimeterConfigurationsServerTransport { + return &NetworkSecurityPerimeterConfigurationsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.NetworkSecurityPerimeterConfigurationsClientListResponse]](), + beginReconcile: newTracker[azfake.PollerResponder[armcognitiveservices.NetworkSecurityPerimeterConfigurationsClientReconcileResponse]](), + } +} + +// NetworkSecurityPerimeterConfigurationsServerTransport connects instances of armcognitiveservices.NetworkSecurityPerimeterConfigurationsClient to instances of NetworkSecurityPerimeterConfigurationsServer. +// Don't use this type directly, use NewNetworkSecurityPerimeterConfigurationsServerTransport instead. +type NetworkSecurityPerimeterConfigurationsServerTransport struct { + srv *NetworkSecurityPerimeterConfigurationsServer + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.NetworkSecurityPerimeterConfigurationsClientListResponse]] + beginReconcile *tracker[azfake.PollerResponder[armcognitiveservices.NetworkSecurityPerimeterConfigurationsClientReconcileResponse]] +} + +// Do implements the policy.Transporter interface for NetworkSecurityPerimeterConfigurationsServerTransport. +func (n *NetworkSecurityPerimeterConfigurationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return n.dispatchToMethodFake(req, method) +} + +func (n *NetworkSecurityPerimeterConfigurationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if networkSecurityPerimeterConfigurationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = networkSecurityPerimeterConfigurationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "NetworkSecurityPerimeterConfigurationsClient.Get": + res.resp, res.err = n.dispatchGet(req) + case "NetworkSecurityPerimeterConfigurationsClient.NewListPager": + res.resp, res.err = n.dispatchNewListPager(req) + case "NetworkSecurityPerimeterConfigurationsClient.BeginReconcile": + res.resp, res.err = n.dispatchBeginReconcile(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (n *NetworkSecurityPerimeterConfigurationsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if n.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/networkSecurityPerimeterConfigurations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + nspConfigurationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("nspConfigurationName")]) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.Get(req.Context(), resourceGroupNameParam, accountNameParam, nspConfigurationNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).NetworkSecurityPerimeterConfiguration, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NetworkSecurityPerimeterConfigurationsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if n.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := n.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/networkSecurityPerimeterConfigurations` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + resp := n.srv.NewListPager(resourceGroupNameParam, accountNameParam, nil) + newListPager = &resp + n.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.NetworkSecurityPerimeterConfigurationsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + n.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + n.newListPager.remove(req) + } + return resp, nil +} + +func (n *NetworkSecurityPerimeterConfigurationsServerTransport) dispatchBeginReconcile(req *http.Request) (*http.Response, error) { + if n.srv.BeginReconcile == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginReconcile not implemented")} + } + beginReconcile := n.beginReconcile.get(req) + if beginReconcile == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/networkSecurityPerimeterConfigurations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/reconcile` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + nspConfigurationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("nspConfigurationName")]) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.BeginReconcile(req.Context(), resourceGroupNameParam, accountNameParam, nspConfigurationNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginReconcile = &respr + n.beginReconcile.add(req, beginReconcile) + } + + resp, err := server.PollerResponderNext(beginReconcile, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + n.beginReconcile.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginReconcile) { + n.beginReconcile.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to NetworkSecurityPerimeterConfigurationsServerTransport +var networkSecurityPerimeterConfigurationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_operations_server.go b/test/local/armcognitiveservices/fake/zz_operations_server.go new file mode 100644 index 000000000000..7b1ac6769afc --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_operations_server.go @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "slices" +) + +// OperationsServer is a fake server for instances of the armcognitiveservices.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armcognitiveservices.OperationsClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of armcognitiveservices.OperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOperationsServerTransport(srv *OperationsServer) *OperationsServerTransport { + return &OperationsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.OperationsClientListResponse]](), + } +} + +// OperationsServerTransport connects instances of armcognitiveservices.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.OperationsClientListResponse]] +} + +// Do implements the policy.Transporter interface for OperationsServerTransport. +func (o *OperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if operationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = operationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OperationsClient.NewListPager": + res.resp, res.err = o.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OperationsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := o.newListPager.get(req) + if newListPager == nil { + resp := o.srv.NewListPager(nil) + newListPager = &resp + o.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.OperationsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + o.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + o.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OperationsServerTransport +var operationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_outboundrule_server.go b/test/local/armcognitiveservices/fake/zz_outboundrule_server.go new file mode 100644 index 000000000000..908a234d8407 --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_outboundrule_server.go @@ -0,0 +1,305 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// OutboundRuleServer is a fake server for instances of the armcognitiveservices.OutboundRuleClient type. +type OutboundRuleServer struct { + // BeginCreateOrUpdate is the fake for method OutboundRuleClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, ruleName string, body armcognitiveservices.OutboundRuleBasicResource, options *armcognitiveservices.OutboundRuleClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armcognitiveservices.OutboundRuleClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method OutboundRuleClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, ruleName string, options *armcognitiveservices.OutboundRuleClientBeginDeleteOptions) (resp azfake.PollerResponder[armcognitiveservices.OutboundRuleClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method OutboundRuleClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, ruleName string, options *armcognitiveservices.OutboundRuleClientGetOptions) (resp azfake.Responder[armcognitiveservices.OutboundRuleClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method OutboundRuleClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, accountName string, managedNetworkName string, options *armcognitiveservices.OutboundRuleClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.OutboundRuleClientListResponse]) +} + +// NewOutboundRuleServerTransport creates a new instance of OutboundRuleServerTransport with the provided implementation. +// The returned OutboundRuleServerTransport instance is connected to an instance of armcognitiveservices.OutboundRuleClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOutboundRuleServerTransport(srv *OutboundRuleServer) *OutboundRuleServerTransport { + return &OutboundRuleServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armcognitiveservices.OutboundRuleClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armcognitiveservices.OutboundRuleClientDeleteResponse]](), + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.OutboundRuleClientListResponse]](), + } +} + +// OutboundRuleServerTransport connects instances of armcognitiveservices.OutboundRuleClient to instances of OutboundRuleServer. +// Don't use this type directly, use NewOutboundRuleServerTransport instead. +type OutboundRuleServerTransport struct { + srv *OutboundRuleServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armcognitiveservices.OutboundRuleClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armcognitiveservices.OutboundRuleClientDeleteResponse]] + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.OutboundRuleClientListResponse]] +} + +// Do implements the policy.Transporter interface for OutboundRuleServerTransport. +func (o *OutboundRuleServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OutboundRuleServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if outboundRuleServerTransportInterceptor != nil { + res.resp, res.err, intercepted = outboundRuleServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OutboundRuleClient.BeginCreateOrUpdate": + res.resp, res.err = o.dispatchBeginCreateOrUpdate(req) + case "OutboundRuleClient.BeginDelete": + res.resp, res.err = o.dispatchBeginDelete(req) + case "OutboundRuleClient.Get": + res.resp, res.err = o.dispatchGet(req) + case "OutboundRuleClient.NewListPager": + res.resp, res.err = o.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OutboundRuleServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if o.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := o.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/managedNetworks/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/outboundRules/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.OutboundRuleBasicResource](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + managedNetworkNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managedNetworkName")]) + if err != nil { + return nil, err + } + ruleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("ruleName")]) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, accountNameParam, managedNetworkNameParam, ruleNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + o.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + o.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + o.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (o *OutboundRuleServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if o.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := o.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/managedNetworks/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/outboundRules/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + managedNetworkNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managedNetworkName")]) + if err != nil { + return nil, err + } + ruleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("ruleName")]) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.BeginDelete(req.Context(), resourceGroupNameParam, accountNameParam, managedNetworkNameParam, ruleNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + o.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + o.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + o.beginDelete.remove(req) + } + + return resp, nil +} + +func (o *OutboundRuleServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if o.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/managedNetworks/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/outboundRules/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + managedNetworkNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managedNetworkName")]) + if err != nil { + return nil, err + } + ruleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("ruleName")]) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.Get(req.Context(), resourceGroupNameParam, accountNameParam, managedNetworkNameParam, ruleNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).OutboundRuleBasicResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OutboundRuleServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := o.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/managedNetworks/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/outboundRules` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + managedNetworkNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managedNetworkName")]) + if err != nil { + return nil, err + } + resp := o.srv.NewListPager(resourceGroupNameParam, accountNameParam, managedNetworkNameParam, nil) + newListPager = &resp + o.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.OutboundRuleClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + o.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + o.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OutboundRuleServerTransport +var outboundRuleServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_outboundrules_server.go b/test/local/armcognitiveservices/fake/zz_outboundrules_server.go new file mode 100644 index 000000000000..56b39734285c --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_outboundrules_server.go @@ -0,0 +1,140 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// OutboundRulesServer is a fake server for instances of the armcognitiveservices.OutboundRulesClient type. +type OutboundRulesServer struct { + // BeginPost is the fake for method OutboundRulesClient.BeginPost + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginPost func(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, body armcognitiveservices.ManagedNetworkSettingsBasicResource, options *armcognitiveservices.OutboundRulesClientBeginPostOptions) (resp azfake.PollerResponder[azfake.PagerResponder[armcognitiveservices.OutboundRulesClientPostResponse]], errResp azfake.ErrorResponder) +} + +// NewOutboundRulesServerTransport creates a new instance of OutboundRulesServerTransport with the provided implementation. +// The returned OutboundRulesServerTransport instance is connected to an instance of armcognitiveservices.OutboundRulesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOutboundRulesServerTransport(srv *OutboundRulesServer) *OutboundRulesServerTransport { + return &OutboundRulesServerTransport{ + srv: srv, + beginPost: newTracker[azfake.PollerResponder[azfake.PagerResponder[armcognitiveservices.OutboundRulesClientPostResponse]]](), + } +} + +// OutboundRulesServerTransport connects instances of armcognitiveservices.OutboundRulesClient to instances of OutboundRulesServer. +// Don't use this type directly, use NewOutboundRulesServerTransport instead. +type OutboundRulesServerTransport struct { + srv *OutboundRulesServer + beginPost *tracker[azfake.PollerResponder[azfake.PagerResponder[armcognitiveservices.OutboundRulesClientPostResponse]]] +} + +// Do implements the policy.Transporter interface for OutboundRulesServerTransport. +func (o *OutboundRulesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OutboundRulesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if outboundRulesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = outboundRulesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OutboundRulesClient.BeginPost": + res.resp, res.err = o.dispatchBeginPost(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OutboundRulesServerTransport) dispatchBeginPost(req *http.Request) (*http.Response, error) { + if o.srv.BeginPost == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginPost not implemented")} + } + beginPost := o.beginPost.get(req) + if beginPost == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/managedNetworks/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/batchOutboundRules` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.ManagedNetworkSettingsBasicResource](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + managedNetworkNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("managedNetworkName")]) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.BeginPost(req.Context(), resourceGroupNameParam, accountNameParam, managedNetworkNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginPost = &respr + o.beginPost.add(req, beginPost) + } + + resp, err := server.PollerResponderNext(beginPost, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + o.beginPost.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginPost) { + o.beginPost.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to OutboundRulesServerTransport +var outboundRulesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_privateendpointconnections_server.go b/test/local/armcognitiveservices/fake/zz_privateendpointconnections_server.go new file mode 100644 index 000000000000..563a7d8847ac --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_privateendpointconnections_server.go @@ -0,0 +1,278 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// PrivateEndpointConnectionsServer is a fake server for instances of the armcognitiveservices.PrivateEndpointConnectionsClient type. +type PrivateEndpointConnectionsServer struct { + // BeginCreateOrUpdate is the fake for method PrivateEndpointConnectionsClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string, properties armcognitiveservices.PrivateEndpointConnection, options *armcognitiveservices.PrivateEndpointConnectionsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armcognitiveservices.PrivateEndpointConnectionsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method PrivateEndpointConnectionsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string, options *armcognitiveservices.PrivateEndpointConnectionsClientBeginDeleteOptions) (resp azfake.PollerResponder[armcognitiveservices.PrivateEndpointConnectionsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method PrivateEndpointConnectionsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string, options *armcognitiveservices.PrivateEndpointConnectionsClientGetOptions) (resp azfake.Responder[armcognitiveservices.PrivateEndpointConnectionsClientGetResponse], errResp azfake.ErrorResponder) + + // List is the fake for method PrivateEndpointConnectionsClient.List + // HTTP status codes to indicate success: http.StatusOK + List func(ctx context.Context, resourceGroupName string, accountName string, options *armcognitiveservices.PrivateEndpointConnectionsClientListOptions) (resp azfake.Responder[armcognitiveservices.PrivateEndpointConnectionsClientListResponse], errResp azfake.ErrorResponder) +} + +// NewPrivateEndpointConnectionsServerTransport creates a new instance of PrivateEndpointConnectionsServerTransport with the provided implementation. +// The returned PrivateEndpointConnectionsServerTransport instance is connected to an instance of armcognitiveservices.PrivateEndpointConnectionsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewPrivateEndpointConnectionsServerTransport(srv *PrivateEndpointConnectionsServer) *PrivateEndpointConnectionsServerTransport { + return &PrivateEndpointConnectionsServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armcognitiveservices.PrivateEndpointConnectionsClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armcognitiveservices.PrivateEndpointConnectionsClientDeleteResponse]](), + } +} + +// PrivateEndpointConnectionsServerTransport connects instances of armcognitiveservices.PrivateEndpointConnectionsClient to instances of PrivateEndpointConnectionsServer. +// Don't use this type directly, use NewPrivateEndpointConnectionsServerTransport instead. +type PrivateEndpointConnectionsServerTransport struct { + srv *PrivateEndpointConnectionsServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armcognitiveservices.PrivateEndpointConnectionsClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armcognitiveservices.PrivateEndpointConnectionsClientDeleteResponse]] +} + +// Do implements the policy.Transporter interface for PrivateEndpointConnectionsServerTransport. +func (p *PrivateEndpointConnectionsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return p.dispatchToMethodFake(req, method) +} + +func (p *PrivateEndpointConnectionsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if privateEndpointConnectionsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = privateEndpointConnectionsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "PrivateEndpointConnectionsClient.BeginCreateOrUpdate": + res.resp, res.err = p.dispatchBeginCreateOrUpdate(req) + case "PrivateEndpointConnectionsClient.BeginDelete": + res.resp, res.err = p.dispatchBeginDelete(req) + case "PrivateEndpointConnectionsClient.Get": + res.resp, res.err = p.dispatchGet(req) + case "PrivateEndpointConnectionsClient.List": + res.resp, res.err = p.dispatchList(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (p *PrivateEndpointConnectionsServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if p.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := p.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/privateEndpointConnections/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.PrivateEndpointConnection](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + privateEndpointConnectionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("privateEndpointConnectionName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, accountNameParam, privateEndpointConnectionNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + p.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + p.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + p.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (p *PrivateEndpointConnectionsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if p.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := p.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/privateEndpointConnections/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + privateEndpointConnectionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("privateEndpointConnectionName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.BeginDelete(req.Context(), resourceGroupNameParam, accountNameParam, privateEndpointConnectionNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + p.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + p.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + p.beginDelete.remove(req) + } + + return resp, nil +} + +func (p *PrivateEndpointConnectionsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if p.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/privateEndpointConnections/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + privateEndpointConnectionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("privateEndpointConnectionName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.Get(req.Context(), resourceGroupNameParam, accountNameParam, privateEndpointConnectionNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).PrivateEndpointConnection, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (p *PrivateEndpointConnectionsServerTransport) dispatchList(req *http.Request) (*http.Response, error) { + if p.srv.List == nil { + return nil, &nonRetriableError{errors.New("fake for method List not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/privateEndpointConnections` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.List(req.Context(), resourceGroupNameParam, accountNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).PrivateEndpointConnectionListResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to PrivateEndpointConnectionsServerTransport +var privateEndpointConnectionsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_privatelinkresources_server.go b/test/local/armcognitiveservices/fake/zz_privatelinkresources_server.go new file mode 100644 index 000000000000..932f546f0162 --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_privatelinkresources_server.go @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// PrivateLinkResourcesServer is a fake server for instances of the armcognitiveservices.PrivateLinkResourcesClient type. +type PrivateLinkResourcesServer struct { + // List is the fake for method PrivateLinkResourcesClient.List + // HTTP status codes to indicate success: http.StatusOK + List func(ctx context.Context, resourceGroupName string, accountName string, options *armcognitiveservices.PrivateLinkResourcesClientListOptions) (resp azfake.Responder[armcognitiveservices.PrivateLinkResourcesClientListResponse], errResp azfake.ErrorResponder) +} + +// NewPrivateLinkResourcesServerTransport creates a new instance of PrivateLinkResourcesServerTransport with the provided implementation. +// The returned PrivateLinkResourcesServerTransport instance is connected to an instance of armcognitiveservices.PrivateLinkResourcesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewPrivateLinkResourcesServerTransport(srv *PrivateLinkResourcesServer) *PrivateLinkResourcesServerTransport { + return &PrivateLinkResourcesServerTransport{srv: srv} +} + +// PrivateLinkResourcesServerTransport connects instances of armcognitiveservices.PrivateLinkResourcesClient to instances of PrivateLinkResourcesServer. +// Don't use this type directly, use NewPrivateLinkResourcesServerTransport instead. +type PrivateLinkResourcesServerTransport struct { + srv *PrivateLinkResourcesServer +} + +// Do implements the policy.Transporter interface for PrivateLinkResourcesServerTransport. +func (p *PrivateLinkResourcesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return p.dispatchToMethodFake(req, method) +} + +func (p *PrivateLinkResourcesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if privateLinkResourcesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = privateLinkResourcesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "PrivateLinkResourcesClient.List": + res.resp, res.err = p.dispatchList(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (p *PrivateLinkResourcesServerTransport) dispatchList(req *http.Request) (*http.Response, error) { + if p.srv.List == nil { + return nil, &nonRetriableError{errors.New("fake for method List not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/privateLinkResources` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.List(req.Context(), resourceGroupNameParam, accountNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).PrivateLinkResourceListResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to PrivateLinkResourcesServerTransport +var privateLinkResourcesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_projectcapabilityhosts_server.go b/test/local/armcognitiveservices/fake/zz_projectcapabilityhosts_server.go new file mode 100644 index 000000000000..46ed9146cdb4 --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_projectcapabilityhosts_server.go @@ -0,0 +1,305 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// ProjectCapabilityHostsServer is a fake server for instances of the armcognitiveservices.ProjectCapabilityHostsClient type. +type ProjectCapabilityHostsServer struct { + // BeginCreateOrUpdate is the fake for method ProjectCapabilityHostsClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, accountName string, projectName string, capabilityHostName string, capabilityHost armcognitiveservices.ProjectCapabilityHost, options *armcognitiveservices.ProjectCapabilityHostsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armcognitiveservices.ProjectCapabilityHostsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method ProjectCapabilityHostsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, accountName string, projectName string, capabilityHostName string, options *armcognitiveservices.ProjectCapabilityHostsClientBeginDeleteOptions) (resp azfake.PollerResponder[armcognitiveservices.ProjectCapabilityHostsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method ProjectCapabilityHostsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, accountName string, projectName string, capabilityHostName string, options *armcognitiveservices.ProjectCapabilityHostsClientGetOptions) (resp azfake.Responder[armcognitiveservices.ProjectCapabilityHostsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method ProjectCapabilityHostsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, accountName string, projectName string, options *armcognitiveservices.ProjectCapabilityHostsClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.ProjectCapabilityHostsClientListResponse]) +} + +// NewProjectCapabilityHostsServerTransport creates a new instance of ProjectCapabilityHostsServerTransport with the provided implementation. +// The returned ProjectCapabilityHostsServerTransport instance is connected to an instance of armcognitiveservices.ProjectCapabilityHostsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewProjectCapabilityHostsServerTransport(srv *ProjectCapabilityHostsServer) *ProjectCapabilityHostsServerTransport { + return &ProjectCapabilityHostsServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armcognitiveservices.ProjectCapabilityHostsClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armcognitiveservices.ProjectCapabilityHostsClientDeleteResponse]](), + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.ProjectCapabilityHostsClientListResponse]](), + } +} + +// ProjectCapabilityHostsServerTransport connects instances of armcognitiveservices.ProjectCapabilityHostsClient to instances of ProjectCapabilityHostsServer. +// Don't use this type directly, use NewProjectCapabilityHostsServerTransport instead. +type ProjectCapabilityHostsServerTransport struct { + srv *ProjectCapabilityHostsServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armcognitiveservices.ProjectCapabilityHostsClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armcognitiveservices.ProjectCapabilityHostsClientDeleteResponse]] + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.ProjectCapabilityHostsClientListResponse]] +} + +// Do implements the policy.Transporter interface for ProjectCapabilityHostsServerTransport. +func (p *ProjectCapabilityHostsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return p.dispatchToMethodFake(req, method) +} + +func (p *ProjectCapabilityHostsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if projectCapabilityHostsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = projectCapabilityHostsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ProjectCapabilityHostsClient.BeginCreateOrUpdate": + res.resp, res.err = p.dispatchBeginCreateOrUpdate(req) + case "ProjectCapabilityHostsClient.BeginDelete": + res.resp, res.err = p.dispatchBeginDelete(req) + case "ProjectCapabilityHostsClient.Get": + res.resp, res.err = p.dispatchGet(req) + case "ProjectCapabilityHostsClient.NewListPager": + res.resp, res.err = p.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (p *ProjectCapabilityHostsServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if p.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := p.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/capabilityHosts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.ProjectCapabilityHost](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")]) + if err != nil { + return nil, err + } + capabilityHostNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("capabilityHostName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, accountNameParam, projectNameParam, capabilityHostNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + p.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + p.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + p.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (p *ProjectCapabilityHostsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if p.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := p.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/capabilityHosts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")]) + if err != nil { + return nil, err + } + capabilityHostNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("capabilityHostName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.BeginDelete(req.Context(), resourceGroupNameParam, accountNameParam, projectNameParam, capabilityHostNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + p.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + p.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + p.beginDelete.remove(req) + } + + return resp, nil +} + +func (p *ProjectCapabilityHostsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if p.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/capabilityHosts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")]) + if err != nil { + return nil, err + } + capabilityHostNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("capabilityHostName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.Get(req.Context(), resourceGroupNameParam, accountNameParam, projectNameParam, capabilityHostNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ProjectCapabilityHost, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (p *ProjectCapabilityHostsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if p.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := p.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/capabilityHosts` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")]) + if err != nil { + return nil, err + } + resp := p.srv.NewListPager(resourceGroupNameParam, accountNameParam, projectNameParam, nil) + newListPager = &resp + p.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.ProjectCapabilityHostsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + p.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ProjectCapabilityHostsServerTransport +var projectCapabilityHostsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_projectconnections_server.go b/test/local/armcognitiveservices/fake/zz_projectconnections_server.go new file mode 100644 index 000000000000..16a5f2784142 --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_projectconnections_server.go @@ -0,0 +1,346 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" + "strconv" +) + +// ProjectConnectionsServer is a fake server for instances of the armcognitiveservices.ProjectConnectionsClient type. +type ProjectConnectionsServer struct { + // Create is the fake for method ProjectConnectionsClient.Create + // HTTP status codes to indicate success: http.StatusOK + Create func(ctx context.Context, resourceGroupName string, accountName string, projectName string, connectionName string, connection armcognitiveservices.ConnectionPropertiesV2BasicResource, options *armcognitiveservices.ProjectConnectionsClientCreateOptions) (resp azfake.Responder[armcognitiveservices.ProjectConnectionsClientCreateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method ProjectConnectionsClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceGroupName string, accountName string, projectName string, connectionName string, options *armcognitiveservices.ProjectConnectionsClientDeleteOptions) (resp azfake.Responder[armcognitiveservices.ProjectConnectionsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method ProjectConnectionsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, accountName string, projectName string, connectionName string, options *armcognitiveservices.ProjectConnectionsClientGetOptions) (resp azfake.Responder[armcognitiveservices.ProjectConnectionsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method ProjectConnectionsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, accountName string, projectName string, options *armcognitiveservices.ProjectConnectionsClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.ProjectConnectionsClientListResponse]) + + // Update is the fake for method ProjectConnectionsClient.Update + // HTTP status codes to indicate success: http.StatusOK + Update func(ctx context.Context, resourceGroupName string, accountName string, projectName string, connectionName string, connection armcognitiveservices.ConnectionUpdateContent, options *armcognitiveservices.ProjectConnectionsClientUpdateOptions) (resp azfake.Responder[armcognitiveservices.ProjectConnectionsClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewProjectConnectionsServerTransport creates a new instance of ProjectConnectionsServerTransport with the provided implementation. +// The returned ProjectConnectionsServerTransport instance is connected to an instance of armcognitiveservices.ProjectConnectionsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewProjectConnectionsServerTransport(srv *ProjectConnectionsServer) *ProjectConnectionsServerTransport { + return &ProjectConnectionsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.ProjectConnectionsClientListResponse]](), + } +} + +// ProjectConnectionsServerTransport connects instances of armcognitiveservices.ProjectConnectionsClient to instances of ProjectConnectionsServer. +// Don't use this type directly, use NewProjectConnectionsServerTransport instead. +type ProjectConnectionsServerTransport struct { + srv *ProjectConnectionsServer + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.ProjectConnectionsClientListResponse]] +} + +// Do implements the policy.Transporter interface for ProjectConnectionsServerTransport. +func (p *ProjectConnectionsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return p.dispatchToMethodFake(req, method) +} + +func (p *ProjectConnectionsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if projectConnectionsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = projectConnectionsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ProjectConnectionsClient.Create": + res.resp, res.err = p.dispatchCreate(req) + case "ProjectConnectionsClient.Delete": + res.resp, res.err = p.dispatchDelete(req) + case "ProjectConnectionsClient.Get": + res.resp, res.err = p.dispatchGet(req) + case "ProjectConnectionsClient.NewListPager": + res.resp, res.err = p.dispatchNewListPager(req) + case "ProjectConnectionsClient.Update": + res.resp, res.err = p.dispatchUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (p *ProjectConnectionsServerTransport) dispatchCreate(req *http.Request) (*http.Response, error) { + if p.srv.Create == nil { + return nil, &nonRetriableError{errors.New("fake for method Create not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/connections/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.ConnectionPropertiesV2BasicResource](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")]) + if err != nil { + return nil, err + } + connectionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("connectionName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.Create(req.Context(), resourceGroupNameParam, accountNameParam, projectNameParam, connectionNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ConnectionPropertiesV2BasicResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (p *ProjectConnectionsServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if p.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/connections/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")]) + if err != nil { + return nil, err + } + connectionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("connectionName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.Delete(req.Context(), resourceGroupNameParam, accountNameParam, projectNameParam, connectionNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (p *ProjectConnectionsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if p.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/connections/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")]) + if err != nil { + return nil, err + } + connectionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("connectionName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.Get(req.Context(), resourceGroupNameParam, accountNameParam, projectNameParam, connectionNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ConnectionPropertiesV2BasicResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (p *ProjectConnectionsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if p.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := p.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/connections` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")]) + if err != nil { + return nil, err + } + targetParam := getOptional(qp.Get("target")) + categoryParam := getOptional(qp.Get("category")) + includeAllParam, err := parseOptional(qp.Get("includeAll"), strconv.ParseBool) + if err != nil { + return nil, err + } + var options *armcognitiveservices.ProjectConnectionsClientListOptions + if targetParam != nil || categoryParam != nil || includeAllParam != nil { + options = &armcognitiveservices.ProjectConnectionsClientListOptions{ + Target: targetParam, + Category: categoryParam, + IncludeAll: includeAllParam, + } + } + resp := p.srv.NewListPager(resourceGroupNameParam, accountNameParam, projectNameParam, options) + newListPager = &resp + p.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.ProjectConnectionsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + p.newListPager.remove(req) + } + return resp, nil +} + +func (p *ProjectConnectionsServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) { + if p.srv.Update == nil { + return nil, &nonRetriableError{errors.New("fake for method Update not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/connections/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.ConnectionUpdateContent](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")]) + if err != nil { + return nil, err + } + connectionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("connectionName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.Update(req.Context(), resourceGroupNameParam, accountNameParam, projectNameParam, connectionNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ConnectionPropertiesV2BasicResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ProjectConnectionsServerTransport +var projectConnectionsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_projects_server.go b/test/local/armcognitiveservices/fake/zz_projects_server.go new file mode 100644 index 000000000000..c133c525d25c --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_projects_server.go @@ -0,0 +1,349 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// ProjectsServer is a fake server for instances of the armcognitiveservices.ProjectsClient type. +type ProjectsServer struct { + // BeginCreate is the fake for method ProjectsClient.BeginCreate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated, http.StatusAccepted + BeginCreate func(ctx context.Context, resourceGroupName string, accountName string, projectName string, project armcognitiveservices.Project, options *armcognitiveservices.ProjectsClientBeginCreateOptions) (resp azfake.PollerResponder[armcognitiveservices.ProjectsClientCreateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method ProjectsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, accountName string, projectName string, options *armcognitiveservices.ProjectsClientBeginDeleteOptions) (resp azfake.PollerResponder[armcognitiveservices.ProjectsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method ProjectsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, accountName string, projectName string, options *armcognitiveservices.ProjectsClientGetOptions) (resp azfake.Responder[armcognitiveservices.ProjectsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method ProjectsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, accountName string, options *armcognitiveservices.ProjectsClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.ProjectsClientListResponse]) + + // BeginUpdate is the fake for method ProjectsClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, accountName string, projectName string, project armcognitiveservices.Project, options *armcognitiveservices.ProjectsClientBeginUpdateOptions) (resp azfake.PollerResponder[armcognitiveservices.ProjectsClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewProjectsServerTransport creates a new instance of ProjectsServerTransport with the provided implementation. +// The returned ProjectsServerTransport instance is connected to an instance of armcognitiveservices.ProjectsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewProjectsServerTransport(srv *ProjectsServer) *ProjectsServerTransport { + return &ProjectsServerTransport{ + srv: srv, + beginCreate: newTracker[azfake.PollerResponder[armcognitiveservices.ProjectsClientCreateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armcognitiveservices.ProjectsClientDeleteResponse]](), + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.ProjectsClientListResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armcognitiveservices.ProjectsClientUpdateResponse]](), + } +} + +// ProjectsServerTransport connects instances of armcognitiveservices.ProjectsClient to instances of ProjectsServer. +// Don't use this type directly, use NewProjectsServerTransport instead. +type ProjectsServerTransport struct { + srv *ProjectsServer + beginCreate *tracker[azfake.PollerResponder[armcognitiveservices.ProjectsClientCreateResponse]] + beginDelete *tracker[azfake.PollerResponder[armcognitiveservices.ProjectsClientDeleteResponse]] + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.ProjectsClientListResponse]] + beginUpdate *tracker[azfake.PollerResponder[armcognitiveservices.ProjectsClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for ProjectsServerTransport. +func (p *ProjectsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return p.dispatchToMethodFake(req, method) +} + +func (p *ProjectsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if projectsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = projectsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ProjectsClient.BeginCreate": + res.resp, res.err = p.dispatchBeginCreate(req) + case "ProjectsClient.BeginDelete": + res.resp, res.err = p.dispatchBeginDelete(req) + case "ProjectsClient.Get": + res.resp, res.err = p.dispatchGet(req) + case "ProjectsClient.NewListPager": + res.resp, res.err = p.dispatchNewListPager(req) + case "ProjectsClient.BeginUpdate": + res.resp, res.err = p.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (p *ProjectsServerTransport) dispatchBeginCreate(req *http.Request) (*http.Response, error) { + if p.srv.BeginCreate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreate not implemented")} + } + beginCreate := p.beginCreate.get(req) + if beginCreate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.Project](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.BeginCreate(req.Context(), resourceGroupNameParam, accountNameParam, projectNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreate = &respr + p.beginCreate.add(req, beginCreate) + } + + resp, err := server.PollerResponderNext(beginCreate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated, http.StatusAccepted}, resp.StatusCode) { + p.beginCreate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreate) { + p.beginCreate.remove(req) + } + + return resp, nil +} + +func (p *ProjectsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if p.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := p.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.BeginDelete(req.Context(), resourceGroupNameParam, accountNameParam, projectNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + p.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + p.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + p.beginDelete.remove(req) + } + + return resp, nil +} + +func (p *ProjectsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if p.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.Get(req.Context(), resourceGroupNameParam, accountNameParam, projectNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Project, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (p *ProjectsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if p.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := p.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + resp := p.srv.NewListPager(resourceGroupNameParam, accountNameParam, nil) + newListPager = &resp + p.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.ProjectsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + p.newListPager.remove(req) + } + return resp, nil +} + +func (p *ProjectsServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if p.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := p.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/projects/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.Project](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + projectNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("projectName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.BeginUpdate(req.Context(), resourceGroupNameParam, accountNameParam, projectNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + p.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + p.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + p.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to ProjectsServerTransport +var projectsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_quotatiers_server.go b/test/local/armcognitiveservices/fake/zz_quotatiers_server.go new file mode 100644 index 000000000000..fd87f545e9e9 --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_quotatiers_server.go @@ -0,0 +1,235 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// QuotaTiersServer is a fake server for instances of the armcognitiveservices.QuotaTiersClient type. +type QuotaTiersServer struct { + // CreateOrUpdate is the fake for method QuotaTiersClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, defaultParam string, tier armcognitiveservices.QuotaTier, options *armcognitiveservices.QuotaTiersClientCreateOrUpdateOptions) (resp azfake.Responder[armcognitiveservices.QuotaTiersClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method QuotaTiersClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, defaultParam string, options *armcognitiveservices.QuotaTiersClientGetOptions) (resp azfake.Responder[armcognitiveservices.QuotaTiersClientGetResponse], errResp azfake.ErrorResponder) + + // NewListBySubscriptionPager is the fake for method QuotaTiersClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armcognitiveservices.QuotaTiersClientListBySubscriptionOptions) (resp azfake.PagerResponder[armcognitiveservices.QuotaTiersClientListBySubscriptionResponse]) + + // Update is the fake for method QuotaTiersClient.Update + // HTTP status codes to indicate success: http.StatusOK + Update func(ctx context.Context, defaultParam string, tier armcognitiveservices.QuotaTier, options *armcognitiveservices.QuotaTiersClientUpdateOptions) (resp azfake.Responder[armcognitiveservices.QuotaTiersClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewQuotaTiersServerTransport creates a new instance of QuotaTiersServerTransport with the provided implementation. +// The returned QuotaTiersServerTransport instance is connected to an instance of armcognitiveservices.QuotaTiersClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewQuotaTiersServerTransport(srv *QuotaTiersServer) *QuotaTiersServerTransport { + return &QuotaTiersServerTransport{ + srv: srv, + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armcognitiveservices.QuotaTiersClientListBySubscriptionResponse]](), + } +} + +// QuotaTiersServerTransport connects instances of armcognitiveservices.QuotaTiersClient to instances of QuotaTiersServer. +// Don't use this type directly, use NewQuotaTiersServerTransport instead. +type QuotaTiersServerTransport struct { + srv *QuotaTiersServer + newListBySubscriptionPager *tracker[azfake.PagerResponder[armcognitiveservices.QuotaTiersClientListBySubscriptionResponse]] +} + +// Do implements the policy.Transporter interface for QuotaTiersServerTransport. +func (q *QuotaTiersServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return q.dispatchToMethodFake(req, method) +} + +func (q *QuotaTiersServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if quotaTiersServerTransportInterceptor != nil { + res.resp, res.err, intercepted = quotaTiersServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "QuotaTiersClient.CreateOrUpdate": + res.resp, res.err = q.dispatchCreateOrUpdate(req) + case "QuotaTiersClient.Get": + res.resp, res.err = q.dispatchGet(req) + case "QuotaTiersClient.NewListBySubscriptionPager": + res.resp, res.err = q.dispatchNewListBySubscriptionPager(req) + case "QuotaTiersClient.Update": + res.resp, res.err = q.dispatchUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (q *QuotaTiersServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if q.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/quotaTiers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.QuotaTier](req) + if err != nil { + return nil, err + } + defaultParamParam, err := url.PathUnescape(matches[regex.SubexpIndex("default")]) + if err != nil { + return nil, err + } + respr, errRespr := q.srv.CreateOrUpdate(req.Context(), defaultParamParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).QuotaTier, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (q *QuotaTiersServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if q.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/quotaTiers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + defaultParamParam, err := url.PathUnescape(matches[regex.SubexpIndex("default")]) + if err != nil { + return nil, err + } + respr, errRespr := q.srv.Get(req.Context(), defaultParamParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).QuotaTier, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (q *QuotaTiersServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if q.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := q.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/quotaTiers` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := q.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + q.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armcognitiveservices.QuotaTiersClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + q.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + q.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (q *QuotaTiersServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) { + if q.srv.Update == nil { + return nil, &nonRetriableError{errors.New("fake for method Update not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/quotaTiers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.QuotaTier](req) + if err != nil { + return nil, err + } + defaultParamParam, err := url.PathUnescape(matches[regex.SubexpIndex("default")]) + if err != nil { + return nil, err + } + respr, errRespr := q.srv.Update(req.Context(), defaultParamParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).QuotaTier, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to QuotaTiersServerTransport +var quotaTiersServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_raiblocklistitems_server.go b/test/local/armcognitiveservices/fake/zz_raiblocklistitems_server.go new file mode 100644 index 000000000000..f75b4d34e10e --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_raiblocklistitems_server.go @@ -0,0 +1,386 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// RaiBlocklistItemsServer is a fake server for instances of the armcognitiveservices.RaiBlocklistItemsClient type. +type RaiBlocklistItemsServer struct { + // BatchAdd is the fake for method RaiBlocklistItemsClient.BatchAdd + // HTTP status codes to indicate success: http.StatusOK + BatchAdd func(ctx context.Context, resourceGroupName string, accountName string, raiBlocklistName string, raiBlocklistItems []*armcognitiveservices.RaiBlocklistItemBulkRequest, options *armcognitiveservices.RaiBlocklistItemsClientBatchAddOptions) (resp azfake.Responder[armcognitiveservices.RaiBlocklistItemsClientBatchAddResponse], errResp azfake.ErrorResponder) + + // BatchDelete is the fake for method RaiBlocklistItemsClient.BatchDelete + // HTTP status codes to indicate success: http.StatusNoContent + BatchDelete func(ctx context.Context, resourceGroupName string, accountName string, raiBlocklistName string, raiBlocklistItemsNames []*string, options *armcognitiveservices.RaiBlocklistItemsClientBatchDeleteOptions) (resp azfake.Responder[armcognitiveservices.RaiBlocklistItemsClientBatchDeleteResponse], errResp azfake.ErrorResponder) + + // CreateOrUpdate is the fake for method RaiBlocklistItemsClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, accountName string, raiBlocklistName string, raiBlocklistItemName string, raiBlocklistItem armcognitiveservices.RaiBlocklistItem, options *armcognitiveservices.RaiBlocklistItemsClientCreateOrUpdateOptions) (resp azfake.Responder[armcognitiveservices.RaiBlocklistItemsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method RaiBlocklistItemsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, accountName string, raiBlocklistName string, raiBlocklistItemName string, options *armcognitiveservices.RaiBlocklistItemsClientBeginDeleteOptions) (resp azfake.PollerResponder[armcognitiveservices.RaiBlocklistItemsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method RaiBlocklistItemsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, accountName string, raiBlocklistName string, raiBlocklistItemName string, options *armcognitiveservices.RaiBlocklistItemsClientGetOptions) (resp azfake.Responder[armcognitiveservices.RaiBlocklistItemsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method RaiBlocklistItemsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, accountName string, raiBlocklistName string, options *armcognitiveservices.RaiBlocklistItemsClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.RaiBlocklistItemsClientListResponse]) +} + +// NewRaiBlocklistItemsServerTransport creates a new instance of RaiBlocklistItemsServerTransport with the provided implementation. +// The returned RaiBlocklistItemsServerTransport instance is connected to an instance of armcognitiveservices.RaiBlocklistItemsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewRaiBlocklistItemsServerTransport(srv *RaiBlocklistItemsServer) *RaiBlocklistItemsServerTransport { + return &RaiBlocklistItemsServerTransport{ + srv: srv, + beginDelete: newTracker[azfake.PollerResponder[armcognitiveservices.RaiBlocklistItemsClientDeleteResponse]](), + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.RaiBlocklistItemsClientListResponse]](), + } +} + +// RaiBlocklistItemsServerTransport connects instances of armcognitiveservices.RaiBlocklistItemsClient to instances of RaiBlocklistItemsServer. +// Don't use this type directly, use NewRaiBlocklistItemsServerTransport instead. +type RaiBlocklistItemsServerTransport struct { + srv *RaiBlocklistItemsServer + beginDelete *tracker[azfake.PollerResponder[armcognitiveservices.RaiBlocklistItemsClientDeleteResponse]] + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.RaiBlocklistItemsClientListResponse]] +} + +// Do implements the policy.Transporter interface for RaiBlocklistItemsServerTransport. +func (r *RaiBlocklistItemsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return r.dispatchToMethodFake(req, method) +} + +func (r *RaiBlocklistItemsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if raiBlocklistItemsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = raiBlocklistItemsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "RaiBlocklistItemsClient.BatchAdd": + res.resp, res.err = r.dispatchBatchAdd(req) + case "RaiBlocklistItemsClient.BatchDelete": + res.resp, res.err = r.dispatchBatchDelete(req) + case "RaiBlocklistItemsClient.CreateOrUpdate": + res.resp, res.err = r.dispatchCreateOrUpdate(req) + case "RaiBlocklistItemsClient.BeginDelete": + res.resp, res.err = r.dispatchBeginDelete(req) + case "RaiBlocklistItemsClient.Get": + res.resp, res.err = r.dispatchGet(req) + case "RaiBlocklistItemsClient.NewListPager": + res.resp, res.err = r.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (r *RaiBlocklistItemsServerTransport) dispatchBatchAdd(req *http.Request) (*http.Response, error) { + if r.srv.BatchAdd == nil { + return nil, &nonRetriableError{errors.New("fake for method BatchAdd not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raiBlocklists/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/addRaiBlocklistItems` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[[]*armcognitiveservices.RaiBlocklistItemBulkRequest](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + raiBlocklistNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("raiBlocklistName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.BatchAdd(req.Context(), resourceGroupNameParam, accountNameParam, raiBlocklistNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RaiBlocklist, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (r *RaiBlocklistItemsServerTransport) dispatchBatchDelete(req *http.Request) (*http.Response, error) { + if r.srv.BatchDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BatchDelete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raiBlocklists/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/deleteRaiBlocklistItems` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[[]*string](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + raiBlocklistNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("raiBlocklistName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.BatchDelete(req.Context(), resourceGroupNameParam, accountNameParam, raiBlocklistNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (r *RaiBlocklistItemsServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if r.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raiBlocklists/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raiBlocklistItems/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.RaiBlocklistItem](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + raiBlocklistNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("raiBlocklistName")]) + if err != nil { + return nil, err + } + raiBlocklistItemNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("raiBlocklistItemName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, accountNameParam, raiBlocklistNameParam, raiBlocklistItemNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RaiBlocklistItem, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (r *RaiBlocklistItemsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if r.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := r.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raiBlocklists/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raiBlocklistItems/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + raiBlocklistNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("raiBlocklistName")]) + if err != nil { + return nil, err + } + raiBlocklistItemNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("raiBlocklistItemName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.BeginDelete(req.Context(), resourceGroupNameParam, accountNameParam, raiBlocklistNameParam, raiBlocklistItemNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + r.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + r.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + r.beginDelete.remove(req) + } + + return resp, nil +} + +func (r *RaiBlocklistItemsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if r.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raiBlocklists/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raiBlocklistItems/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 6 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + raiBlocklistNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("raiBlocklistName")]) + if err != nil { + return nil, err + } + raiBlocklistItemNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("raiBlocklistItemName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.Get(req.Context(), resourceGroupNameParam, accountNameParam, raiBlocklistNameParam, raiBlocklistItemNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RaiBlocklistItem, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (r *RaiBlocklistItemsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if r.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := r.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raiBlocklists/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raiBlocklistItems` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + raiBlocklistNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("raiBlocklistName")]) + if err != nil { + return nil, err + } + resp := r.srv.NewListPager(resourceGroupNameParam, accountNameParam, raiBlocklistNameParam, nil) + newListPager = &resp + r.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.RaiBlocklistItemsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + r.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + r.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to RaiBlocklistItemsServerTransport +var raiBlocklistItemsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_raiblocklists_server.go b/test/local/armcognitiveservices/fake/zz_raiblocklists_server.go new file mode 100644 index 000000000000..2906af009bcf --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_raiblocklists_server.go @@ -0,0 +1,276 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// RaiBlocklistsServer is a fake server for instances of the armcognitiveservices.RaiBlocklistsClient type. +type RaiBlocklistsServer struct { + // CreateOrUpdate is the fake for method RaiBlocklistsClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, accountName string, raiBlocklistName string, raiBlocklist armcognitiveservices.RaiBlocklist, options *armcognitiveservices.RaiBlocklistsClientCreateOrUpdateOptions) (resp azfake.Responder[armcognitiveservices.RaiBlocklistsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method RaiBlocklistsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, accountName string, raiBlocklistName string, options *armcognitiveservices.RaiBlocklistsClientBeginDeleteOptions) (resp azfake.PollerResponder[armcognitiveservices.RaiBlocklistsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method RaiBlocklistsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, accountName string, raiBlocklistName string, options *armcognitiveservices.RaiBlocklistsClientGetOptions) (resp azfake.Responder[armcognitiveservices.RaiBlocklistsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method RaiBlocklistsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, accountName string, options *armcognitiveservices.RaiBlocklistsClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.RaiBlocklistsClientListResponse]) +} + +// NewRaiBlocklistsServerTransport creates a new instance of RaiBlocklistsServerTransport with the provided implementation. +// The returned RaiBlocklistsServerTransport instance is connected to an instance of armcognitiveservices.RaiBlocklistsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewRaiBlocklistsServerTransport(srv *RaiBlocklistsServer) *RaiBlocklistsServerTransport { + return &RaiBlocklistsServerTransport{ + srv: srv, + beginDelete: newTracker[azfake.PollerResponder[armcognitiveservices.RaiBlocklistsClientDeleteResponse]](), + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.RaiBlocklistsClientListResponse]](), + } +} + +// RaiBlocklistsServerTransport connects instances of armcognitiveservices.RaiBlocklistsClient to instances of RaiBlocklistsServer. +// Don't use this type directly, use NewRaiBlocklistsServerTransport instead. +type RaiBlocklistsServerTransport struct { + srv *RaiBlocklistsServer + beginDelete *tracker[azfake.PollerResponder[armcognitiveservices.RaiBlocklistsClientDeleteResponse]] + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.RaiBlocklistsClientListResponse]] +} + +// Do implements the policy.Transporter interface for RaiBlocklistsServerTransport. +func (r *RaiBlocklistsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return r.dispatchToMethodFake(req, method) +} + +func (r *RaiBlocklistsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if raiBlocklistsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = raiBlocklistsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "RaiBlocklistsClient.CreateOrUpdate": + res.resp, res.err = r.dispatchCreateOrUpdate(req) + case "RaiBlocklistsClient.BeginDelete": + res.resp, res.err = r.dispatchBeginDelete(req) + case "RaiBlocklistsClient.Get": + res.resp, res.err = r.dispatchGet(req) + case "RaiBlocklistsClient.NewListPager": + res.resp, res.err = r.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (r *RaiBlocklistsServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if r.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raiBlocklists/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.RaiBlocklist](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + raiBlocklistNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("raiBlocklistName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, accountNameParam, raiBlocklistNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RaiBlocklist, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (r *RaiBlocklistsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if r.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := r.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raiBlocklists/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + raiBlocklistNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("raiBlocklistName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.BeginDelete(req.Context(), resourceGroupNameParam, accountNameParam, raiBlocklistNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + r.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + r.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + r.beginDelete.remove(req) + } + + return resp, nil +} + +func (r *RaiBlocklistsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if r.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raiBlocklists/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + raiBlocklistNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("raiBlocklistName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.Get(req.Context(), resourceGroupNameParam, accountNameParam, raiBlocklistNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RaiBlocklist, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (r *RaiBlocklistsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if r.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := r.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raiBlocklists` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + resp := r.srv.NewListPager(resourceGroupNameParam, accountNameParam, nil) + newListPager = &resp + r.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.RaiBlocklistsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + r.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + r.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to RaiBlocklistsServerTransport +var raiBlocklistsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_raicontentfilters_server.go b/test/local/armcognitiveservices/fake/zz_raicontentfilters_server.go new file mode 100644 index 000000000000..8bf73133c531 --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_raicontentfilters_server.go @@ -0,0 +1,165 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// RaiContentFiltersServer is a fake server for instances of the armcognitiveservices.RaiContentFiltersClient type. +type RaiContentFiltersServer struct { + // Get is the fake for method RaiContentFiltersClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, location string, filterName string, options *armcognitiveservices.RaiContentFiltersClientGetOptions) (resp azfake.Responder[armcognitiveservices.RaiContentFiltersClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method RaiContentFiltersClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(location string, options *armcognitiveservices.RaiContentFiltersClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.RaiContentFiltersClientListResponse]) +} + +// NewRaiContentFiltersServerTransport creates a new instance of RaiContentFiltersServerTransport with the provided implementation. +// The returned RaiContentFiltersServerTransport instance is connected to an instance of armcognitiveservices.RaiContentFiltersClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewRaiContentFiltersServerTransport(srv *RaiContentFiltersServer) *RaiContentFiltersServerTransport { + return &RaiContentFiltersServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.RaiContentFiltersClientListResponse]](), + } +} + +// RaiContentFiltersServerTransport connects instances of armcognitiveservices.RaiContentFiltersClient to instances of RaiContentFiltersServer. +// Don't use this type directly, use NewRaiContentFiltersServerTransport instead. +type RaiContentFiltersServerTransport struct { + srv *RaiContentFiltersServer + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.RaiContentFiltersClientListResponse]] +} + +// Do implements the policy.Transporter interface for RaiContentFiltersServerTransport. +func (r *RaiContentFiltersServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return r.dispatchToMethodFake(req, method) +} + +func (r *RaiContentFiltersServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if raiContentFiltersServerTransportInterceptor != nil { + res.resp, res.err, intercepted = raiContentFiltersServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "RaiContentFiltersClient.Get": + res.resp, res.err = r.dispatchGet(req) + case "RaiContentFiltersClient.NewListPager": + res.resp, res.err = r.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (r *RaiContentFiltersServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if r.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raiContentFilters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + filterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("filterName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.Get(req.Context(), locationParam, filterNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RaiContentFilter, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (r *RaiContentFiltersServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if r.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := r.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raiContentFilters` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + resp := r.srv.NewListPager(locationParam, nil) + newListPager = &resp + r.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.RaiContentFiltersClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + r.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + r.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to RaiContentFiltersServerTransport +var raiContentFiltersServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_raiexternalsafetyprovider_server.go b/test/local/armcognitiveservices/fake/zz_raiexternalsafetyprovider_server.go new file mode 100644 index 000000000000..83dc46c7f876 --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_raiexternalsafetyprovider_server.go @@ -0,0 +1,202 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// RaiExternalSafetyProviderServer is a fake server for instances of the armcognitiveservices.RaiExternalSafetyProviderClient type. +type RaiExternalSafetyProviderServer struct { + // CreateOrUpdate is the fake for method RaiExternalSafetyProviderClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, safetyProviderName string, safetyProvider armcognitiveservices.RaiExternalSafetyProviderSchema, options *armcognitiveservices.RaiExternalSafetyProviderClientCreateOrUpdateOptions) (resp azfake.Responder[armcognitiveservices.RaiExternalSafetyProviderClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method RaiExternalSafetyProviderClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, safetyProviderName string, options *armcognitiveservices.RaiExternalSafetyProviderClientBeginDeleteOptions) (resp azfake.PollerResponder[armcognitiveservices.RaiExternalSafetyProviderClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method RaiExternalSafetyProviderClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, safetyProviderName string, options *armcognitiveservices.RaiExternalSafetyProviderClientGetOptions) (resp azfake.Responder[armcognitiveservices.RaiExternalSafetyProviderClientGetResponse], errResp azfake.ErrorResponder) +} + +// NewRaiExternalSafetyProviderServerTransport creates a new instance of RaiExternalSafetyProviderServerTransport with the provided implementation. +// The returned RaiExternalSafetyProviderServerTransport instance is connected to an instance of armcognitiveservices.RaiExternalSafetyProviderClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewRaiExternalSafetyProviderServerTransport(srv *RaiExternalSafetyProviderServer) *RaiExternalSafetyProviderServerTransport { + return &RaiExternalSafetyProviderServerTransport{ + srv: srv, + beginDelete: newTracker[azfake.PollerResponder[armcognitiveservices.RaiExternalSafetyProviderClientDeleteResponse]](), + } +} + +// RaiExternalSafetyProviderServerTransport connects instances of armcognitiveservices.RaiExternalSafetyProviderClient to instances of RaiExternalSafetyProviderServer. +// Don't use this type directly, use NewRaiExternalSafetyProviderServerTransport instead. +type RaiExternalSafetyProviderServerTransport struct { + srv *RaiExternalSafetyProviderServer + beginDelete *tracker[azfake.PollerResponder[armcognitiveservices.RaiExternalSafetyProviderClientDeleteResponse]] +} + +// Do implements the policy.Transporter interface for RaiExternalSafetyProviderServerTransport. +func (r *RaiExternalSafetyProviderServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return r.dispatchToMethodFake(req, method) +} + +func (r *RaiExternalSafetyProviderServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if raiExternalSafetyProviderServerTransportInterceptor != nil { + res.resp, res.err, intercepted = raiExternalSafetyProviderServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "RaiExternalSafetyProviderClient.CreateOrUpdate": + res.resp, res.err = r.dispatchCreateOrUpdate(req) + case "RaiExternalSafetyProviderClient.BeginDelete": + res.resp, res.err = r.dispatchBeginDelete(req) + case "RaiExternalSafetyProviderClient.Get": + res.resp, res.err = r.dispatchGet(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (r *RaiExternalSafetyProviderServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if r.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/raiExternalSafetyProviders/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.RaiExternalSafetyProviderSchema](req) + if err != nil { + return nil, err + } + safetyProviderNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("safetyProviderName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.CreateOrUpdate(req.Context(), safetyProviderNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RaiExternalSafetyProviderSchema, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (r *RaiExternalSafetyProviderServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if r.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := r.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/raiExternalSafetyProviders/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + safetyProviderNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("safetyProviderName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.BeginDelete(req.Context(), safetyProviderNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + r.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + r.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + r.beginDelete.remove(req) + } + + return resp, nil +} + +func (r *RaiExternalSafetyProviderServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if r.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/raiExternalSafetyProviders/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + safetyProviderNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("safetyProviderName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.Get(req.Context(), safetyProviderNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RaiExternalSafetyProviderSchema, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to RaiExternalSafetyProviderServerTransport +var raiExternalSafetyProviderServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_raiexternalsafetyproviders_server.go b/test/local/armcognitiveservices/fake/zz_raiexternalsafetyproviders_server.go new file mode 100644 index 000000000000..891fbcfce393 --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_raiexternalsafetyproviders_server.go @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "regexp" + "slices" +) + +// RaiExternalSafetyProvidersServer is a fake server for instances of the armcognitiveservices.RaiExternalSafetyProvidersClient type. +type RaiExternalSafetyProvidersServer struct { + // NewListPager is the fake for method RaiExternalSafetyProvidersClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armcognitiveservices.RaiExternalSafetyProvidersClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.RaiExternalSafetyProvidersClientListResponse]) +} + +// NewRaiExternalSafetyProvidersServerTransport creates a new instance of RaiExternalSafetyProvidersServerTransport with the provided implementation. +// The returned RaiExternalSafetyProvidersServerTransport instance is connected to an instance of armcognitiveservices.RaiExternalSafetyProvidersClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewRaiExternalSafetyProvidersServerTransport(srv *RaiExternalSafetyProvidersServer) *RaiExternalSafetyProvidersServerTransport { + return &RaiExternalSafetyProvidersServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.RaiExternalSafetyProvidersClientListResponse]](), + } +} + +// RaiExternalSafetyProvidersServerTransport connects instances of armcognitiveservices.RaiExternalSafetyProvidersClient to instances of RaiExternalSafetyProvidersServer. +// Don't use this type directly, use NewRaiExternalSafetyProvidersServerTransport instead. +type RaiExternalSafetyProvidersServerTransport struct { + srv *RaiExternalSafetyProvidersServer + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.RaiExternalSafetyProvidersClientListResponse]] +} + +// Do implements the policy.Transporter interface for RaiExternalSafetyProvidersServerTransport. +func (r *RaiExternalSafetyProvidersServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return r.dispatchToMethodFake(req, method) +} + +func (r *RaiExternalSafetyProvidersServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if raiExternalSafetyProvidersServerTransportInterceptor != nil { + res.resp, res.err, intercepted = raiExternalSafetyProvidersServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "RaiExternalSafetyProvidersClient.NewListPager": + res.resp, res.err = r.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (r *RaiExternalSafetyProvidersServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if r.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := r.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/raiExternalSafetyProviders` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := r.srv.NewListPager(nil) + newListPager = &resp + r.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.RaiExternalSafetyProvidersClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + r.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + r.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to RaiExternalSafetyProvidersServerTransport +var raiExternalSafetyProvidersServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_raipolicies_server.go b/test/local/armcognitiveservices/fake/zz_raipolicies_server.go new file mode 100644 index 000000000000..e863be94c949 --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_raipolicies_server.go @@ -0,0 +1,276 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// RaiPoliciesServer is a fake server for instances of the armcognitiveservices.RaiPoliciesClient type. +type RaiPoliciesServer struct { + // CreateOrUpdate is the fake for method RaiPoliciesClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, accountName string, raiPolicyName string, raiPolicy armcognitiveservices.RaiPolicy, options *armcognitiveservices.RaiPoliciesClientCreateOrUpdateOptions) (resp azfake.Responder[armcognitiveservices.RaiPoliciesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method RaiPoliciesClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, accountName string, raiPolicyName string, options *armcognitiveservices.RaiPoliciesClientBeginDeleteOptions) (resp azfake.PollerResponder[armcognitiveservices.RaiPoliciesClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method RaiPoliciesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, accountName string, raiPolicyName string, options *armcognitiveservices.RaiPoliciesClientGetOptions) (resp azfake.Responder[armcognitiveservices.RaiPoliciesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method RaiPoliciesClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, accountName string, options *armcognitiveservices.RaiPoliciesClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.RaiPoliciesClientListResponse]) +} + +// NewRaiPoliciesServerTransport creates a new instance of RaiPoliciesServerTransport with the provided implementation. +// The returned RaiPoliciesServerTransport instance is connected to an instance of armcognitiveservices.RaiPoliciesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewRaiPoliciesServerTransport(srv *RaiPoliciesServer) *RaiPoliciesServerTransport { + return &RaiPoliciesServerTransport{ + srv: srv, + beginDelete: newTracker[azfake.PollerResponder[armcognitiveservices.RaiPoliciesClientDeleteResponse]](), + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.RaiPoliciesClientListResponse]](), + } +} + +// RaiPoliciesServerTransport connects instances of armcognitiveservices.RaiPoliciesClient to instances of RaiPoliciesServer. +// Don't use this type directly, use NewRaiPoliciesServerTransport instead. +type RaiPoliciesServerTransport struct { + srv *RaiPoliciesServer + beginDelete *tracker[azfake.PollerResponder[armcognitiveservices.RaiPoliciesClientDeleteResponse]] + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.RaiPoliciesClientListResponse]] +} + +// Do implements the policy.Transporter interface for RaiPoliciesServerTransport. +func (r *RaiPoliciesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return r.dispatchToMethodFake(req, method) +} + +func (r *RaiPoliciesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if raiPoliciesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = raiPoliciesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "RaiPoliciesClient.CreateOrUpdate": + res.resp, res.err = r.dispatchCreateOrUpdate(req) + case "RaiPoliciesClient.BeginDelete": + res.resp, res.err = r.dispatchBeginDelete(req) + case "RaiPoliciesClient.Get": + res.resp, res.err = r.dispatchGet(req) + case "RaiPoliciesClient.NewListPager": + res.resp, res.err = r.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (r *RaiPoliciesServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if r.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raiPolicies/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.RaiPolicy](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + raiPolicyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("raiPolicyName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, accountNameParam, raiPolicyNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RaiPolicy, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (r *RaiPoliciesServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if r.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := r.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raiPolicies/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + raiPolicyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("raiPolicyName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.BeginDelete(req.Context(), resourceGroupNameParam, accountNameParam, raiPolicyNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + r.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + r.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + r.beginDelete.remove(req) + } + + return resp, nil +} + +func (r *RaiPoliciesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if r.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raiPolicies/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + raiPolicyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("raiPolicyName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.Get(req.Context(), resourceGroupNameParam, accountNameParam, raiPolicyNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RaiPolicy, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (r *RaiPoliciesServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if r.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := r.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raiPolicies` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + resp := r.srv.NewListPager(resourceGroupNameParam, accountNameParam, nil) + newListPager = &resp + r.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.RaiPoliciesClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + r.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + r.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to RaiPoliciesServerTransport +var raiPoliciesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_raitoollabels_server.go b/test/local/armcognitiveservices/fake/zz_raitoollabels_server.go new file mode 100644 index 000000000000..22b8ac50b66c --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_raitoollabels_server.go @@ -0,0 +1,276 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// RaiToolLabelsServer is a fake server for instances of the armcognitiveservices.RaiToolLabelsClient type. +type RaiToolLabelsServer struct { + // CreateOrUpdate is the fake for method RaiToolLabelsClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, accountName string, raiToolConnectionName string, raiToolLabel armcognitiveservices.RaiToolLabel, options *armcognitiveservices.RaiToolLabelsClientCreateOrUpdateOptions) (resp azfake.Responder[armcognitiveservices.RaiToolLabelsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method RaiToolLabelsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, accountName string, raiToolConnectionName string, options *armcognitiveservices.RaiToolLabelsClientBeginDeleteOptions) (resp azfake.PollerResponder[armcognitiveservices.RaiToolLabelsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method RaiToolLabelsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, accountName string, raiToolConnectionName string, options *armcognitiveservices.RaiToolLabelsClientGetOptions) (resp azfake.Responder[armcognitiveservices.RaiToolLabelsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method RaiToolLabelsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, accountName string, options *armcognitiveservices.RaiToolLabelsClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.RaiToolLabelsClientListResponse]) +} + +// NewRaiToolLabelsServerTransport creates a new instance of RaiToolLabelsServerTransport with the provided implementation. +// The returned RaiToolLabelsServerTransport instance is connected to an instance of armcognitiveservices.RaiToolLabelsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewRaiToolLabelsServerTransport(srv *RaiToolLabelsServer) *RaiToolLabelsServerTransport { + return &RaiToolLabelsServerTransport{ + srv: srv, + beginDelete: newTracker[azfake.PollerResponder[armcognitiveservices.RaiToolLabelsClientDeleteResponse]](), + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.RaiToolLabelsClientListResponse]](), + } +} + +// RaiToolLabelsServerTransport connects instances of armcognitiveservices.RaiToolLabelsClient to instances of RaiToolLabelsServer. +// Don't use this type directly, use NewRaiToolLabelsServerTransport instead. +type RaiToolLabelsServerTransport struct { + srv *RaiToolLabelsServer + beginDelete *tracker[azfake.PollerResponder[armcognitiveservices.RaiToolLabelsClientDeleteResponse]] + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.RaiToolLabelsClientListResponse]] +} + +// Do implements the policy.Transporter interface for RaiToolLabelsServerTransport. +func (r *RaiToolLabelsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return r.dispatchToMethodFake(req, method) +} + +func (r *RaiToolLabelsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if raiToolLabelsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = raiToolLabelsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "RaiToolLabelsClient.CreateOrUpdate": + res.resp, res.err = r.dispatchCreateOrUpdate(req) + case "RaiToolLabelsClient.BeginDelete": + res.resp, res.err = r.dispatchBeginDelete(req) + case "RaiToolLabelsClient.Get": + res.resp, res.err = r.dispatchGet(req) + case "RaiToolLabelsClient.NewListPager": + res.resp, res.err = r.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (r *RaiToolLabelsServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if r.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raiToolLabels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.RaiToolLabel](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + raiToolConnectionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("raiToolConnectionName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, accountNameParam, raiToolConnectionNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RaiToolLabel, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (r *RaiToolLabelsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if r.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := r.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raiToolLabels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + raiToolConnectionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("raiToolConnectionName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.BeginDelete(req.Context(), resourceGroupNameParam, accountNameParam, raiToolConnectionNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + r.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + r.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + r.beginDelete.remove(req) + } + + return resp, nil +} + +func (r *RaiToolLabelsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if r.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raiToolLabels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + raiToolConnectionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("raiToolConnectionName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.Get(req.Context(), resourceGroupNameParam, accountNameParam, raiToolConnectionNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RaiToolLabel, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (r *RaiToolLabelsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if r.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := r.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raiToolLabels` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + resp := r.srv.NewListPager(resourceGroupNameParam, accountNameParam, nil) + newListPager = &resp + r.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.RaiToolLabelsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + r.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + r.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to RaiToolLabelsServerTransport +var raiToolLabelsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_raitopics_server.go b/test/local/armcognitiveservices/fake/zz_raitopics_server.go new file mode 100644 index 000000000000..f216b5f89f36 --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_raitopics_server.go @@ -0,0 +1,276 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// RaiTopicsServer is a fake server for instances of the armcognitiveservices.RaiTopicsClient type. +type RaiTopicsServer struct { + // CreateOrUpdate is the fake for method RaiTopicsClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, accountName string, raiTopicName string, raiTopic armcognitiveservices.RaiTopic, options *armcognitiveservices.RaiTopicsClientCreateOrUpdateOptions) (resp azfake.Responder[armcognitiveservices.RaiTopicsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method RaiTopicsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, accountName string, raiTopicName string, options *armcognitiveservices.RaiTopicsClientBeginDeleteOptions) (resp azfake.PollerResponder[armcognitiveservices.RaiTopicsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method RaiTopicsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, accountName string, raiTopicName string, options *armcognitiveservices.RaiTopicsClientGetOptions) (resp azfake.Responder[armcognitiveservices.RaiTopicsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method RaiTopicsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceGroupName string, accountName string, options *armcognitiveservices.RaiTopicsClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.RaiTopicsClientListResponse]) +} + +// NewRaiTopicsServerTransport creates a new instance of RaiTopicsServerTransport with the provided implementation. +// The returned RaiTopicsServerTransport instance is connected to an instance of armcognitiveservices.RaiTopicsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewRaiTopicsServerTransport(srv *RaiTopicsServer) *RaiTopicsServerTransport { + return &RaiTopicsServerTransport{ + srv: srv, + beginDelete: newTracker[azfake.PollerResponder[armcognitiveservices.RaiTopicsClientDeleteResponse]](), + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.RaiTopicsClientListResponse]](), + } +} + +// RaiTopicsServerTransport connects instances of armcognitiveservices.RaiTopicsClient to instances of RaiTopicsServer. +// Don't use this type directly, use NewRaiTopicsServerTransport instead. +type RaiTopicsServerTransport struct { + srv *RaiTopicsServer + beginDelete *tracker[azfake.PollerResponder[armcognitiveservices.RaiTopicsClientDeleteResponse]] + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.RaiTopicsClientListResponse]] +} + +// Do implements the policy.Transporter interface for RaiTopicsServerTransport. +func (r *RaiTopicsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return r.dispatchToMethodFake(req, method) +} + +func (r *RaiTopicsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if raiTopicsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = raiTopicsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "RaiTopicsClient.CreateOrUpdate": + res.resp, res.err = r.dispatchCreateOrUpdate(req) + case "RaiTopicsClient.BeginDelete": + res.resp, res.err = r.dispatchBeginDelete(req) + case "RaiTopicsClient.Get": + res.resp, res.err = r.dispatchGet(req) + case "RaiTopicsClient.NewListPager": + res.resp, res.err = r.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (r *RaiTopicsServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if r.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raitopics/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.RaiTopic](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + raiTopicNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("raiTopicName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, accountNameParam, raiTopicNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RaiTopic, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (r *RaiTopicsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if r.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := r.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raitopics/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + raiTopicNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("raiTopicName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.BeginDelete(req.Context(), resourceGroupNameParam, accountNameParam, raiTopicNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + r.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + r.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + r.beginDelete.remove(req) + } + + return resp, nil +} + +func (r *RaiTopicsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if r.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raitopics/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + raiTopicNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("raiTopicName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.Get(req.Context(), resourceGroupNameParam, accountNameParam, raiTopicNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RaiTopic, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (r *RaiTopicsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if r.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := r.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/raitopics` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + resp := r.srv.NewListPager(resourceGroupNameParam, accountNameParam, nil) + newListPager = &resp + r.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.RaiTopicsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + r.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + r.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to RaiTopicsServerTransport +var raiTopicsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_resourceskus_server.go b/test/local/armcognitiveservices/fake/zz_resourceskus_server.go new file mode 100644 index 000000000000..a674f5eb4674 --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_resourceskus_server.go @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "regexp" + "slices" +) + +// ResourceSKUsServer is a fake server for instances of the armcognitiveservices.ResourceSKUsClient type. +type ResourceSKUsServer struct { + // NewListPager is the fake for method ResourceSKUsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armcognitiveservices.ResourceSKUsClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.ResourceSKUsClientListResponse]) +} + +// NewResourceSKUsServerTransport creates a new instance of ResourceSKUsServerTransport with the provided implementation. +// The returned ResourceSKUsServerTransport instance is connected to an instance of armcognitiveservices.ResourceSKUsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewResourceSKUsServerTransport(srv *ResourceSKUsServer) *ResourceSKUsServerTransport { + return &ResourceSKUsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.ResourceSKUsClientListResponse]](), + } +} + +// ResourceSKUsServerTransport connects instances of armcognitiveservices.ResourceSKUsClient to instances of ResourceSKUsServer. +// Don't use this type directly, use NewResourceSKUsServerTransport instead. +type ResourceSKUsServerTransport struct { + srv *ResourceSKUsServer + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.ResourceSKUsClientListResponse]] +} + +// Do implements the policy.Transporter interface for ResourceSKUsServerTransport. +func (r *ResourceSKUsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return r.dispatchToMethodFake(req, method) +} + +func (r *ResourceSKUsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if resourceSkUsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = resourceSkUsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ResourceSKUsClient.NewListPager": + res.resp, res.err = r.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (r *ResourceSKUsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if r.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := r.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/skus` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := r.srv.NewListPager(nil) + newListPager = &resp + r.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.ResourceSKUsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + r.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + r.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ResourceSKUsServerTransport +var resourceSkUsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_server_factory.go b/test/local/armcognitiveservices/fake/zz_server_factory.go new file mode 100644 index 000000000000..8ea69a4b728a --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_server_factory.go @@ -0,0 +1,384 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armcognitiveservices.ClientFactory type. +type ServerFactory struct { + // AccountCapabilityHostsServer contains the fakes for client AccountCapabilityHostsClient + AccountCapabilityHostsServer AccountCapabilityHostsServer + + // AccountConnectionsServer contains the fakes for client AccountConnectionsClient + AccountConnectionsServer AccountConnectionsServer + + // AccountsServer contains the fakes for client AccountsClient + AccountsServer AccountsServer + + // AgentApplicationsServer contains the fakes for client AgentApplicationsClient + AgentApplicationsServer AgentApplicationsServer + + // AgentDeploymentsServer contains the fakes for client AgentDeploymentsClient + AgentDeploymentsServer AgentDeploymentsServer + + // CommitmentPlansServer contains the fakes for client CommitmentPlansClient + CommitmentPlansServer CommitmentPlansServer + + // CommitmentTiersServer contains the fakes for client CommitmentTiersClient + CommitmentTiersServer CommitmentTiersServer + + // DefenderForAISettingsServer contains the fakes for client DefenderForAISettingsClient + DefenderForAISettingsServer DefenderForAISettingsServer + + // DeletedAccountsServer contains the fakes for client DeletedAccountsClient + DeletedAccountsServer DeletedAccountsServer + + // DeploymentsServer contains the fakes for client DeploymentsClient + DeploymentsServer DeploymentsServer + + // EncryptionScopesServer contains the fakes for client EncryptionScopesClient + EncryptionScopesServer EncryptionScopesServer + + // LocationBasedModelCapacitiesServer contains the fakes for client LocationBasedModelCapacitiesClient + LocationBasedModelCapacitiesServer LocationBasedModelCapacitiesServer + + // ManagedNetworkProvisionsServer contains the fakes for client ManagedNetworkProvisionsClient + ManagedNetworkProvisionsServer ManagedNetworkProvisionsServer + + // ManagedNetworkSettingsServer contains the fakes for client ManagedNetworkSettingsClient + ManagedNetworkSettingsServer ManagedNetworkSettingsServer + + // ManagementServer contains the fakes for client ManagementClient + ManagementServer ManagementServer + + // ModelCapacitiesServer contains the fakes for client ModelCapacitiesClient + ModelCapacitiesServer ModelCapacitiesServer + + // ModelsServer contains the fakes for client ModelsClient + ModelsServer ModelsServer + + // NetworkSecurityPerimeterConfigurationsServer contains the fakes for client NetworkSecurityPerimeterConfigurationsClient + NetworkSecurityPerimeterConfigurationsServer NetworkSecurityPerimeterConfigurationsServer + + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer + + // OutboundRuleServer contains the fakes for client OutboundRuleClient + OutboundRuleServer OutboundRuleServer + + // OutboundRulesServer contains the fakes for client OutboundRulesClient + OutboundRulesServer OutboundRulesServer + + // PrivateEndpointConnectionsServer contains the fakes for client PrivateEndpointConnectionsClient + PrivateEndpointConnectionsServer PrivateEndpointConnectionsServer + + // PrivateLinkResourcesServer contains the fakes for client PrivateLinkResourcesClient + PrivateLinkResourcesServer PrivateLinkResourcesServer + + // ProjectCapabilityHostsServer contains the fakes for client ProjectCapabilityHostsClient + ProjectCapabilityHostsServer ProjectCapabilityHostsServer + + // ProjectConnectionsServer contains the fakes for client ProjectConnectionsClient + ProjectConnectionsServer ProjectConnectionsServer + + // ProjectsServer contains the fakes for client ProjectsClient + ProjectsServer ProjectsServer + + // QuotaTiersServer contains the fakes for client QuotaTiersClient + QuotaTiersServer QuotaTiersServer + + // RaiBlocklistItemsServer contains the fakes for client RaiBlocklistItemsClient + RaiBlocklistItemsServer RaiBlocklistItemsServer + + // RaiBlocklistsServer contains the fakes for client RaiBlocklistsClient + RaiBlocklistsServer RaiBlocklistsServer + + // RaiContentFiltersServer contains the fakes for client RaiContentFiltersClient + RaiContentFiltersServer RaiContentFiltersServer + + // RaiExternalSafetyProviderServer contains the fakes for client RaiExternalSafetyProviderClient + RaiExternalSafetyProviderServer RaiExternalSafetyProviderServer + + // RaiExternalSafetyProvidersServer contains the fakes for client RaiExternalSafetyProvidersClient + RaiExternalSafetyProvidersServer RaiExternalSafetyProvidersServer + + // RaiPoliciesServer contains the fakes for client RaiPoliciesClient + RaiPoliciesServer RaiPoliciesServer + + // RaiToolLabelsServer contains the fakes for client RaiToolLabelsClient + RaiToolLabelsServer RaiToolLabelsServer + + // RaiTopicsServer contains the fakes for client RaiTopicsClient + RaiTopicsServer RaiTopicsServer + + // ResourceSKUsServer contains the fakes for client ResourceSKUsClient + ResourceSKUsServer ResourceSKUsServer + + // SubscriptionRaiPolicyServer contains the fakes for client SubscriptionRaiPolicyClient + SubscriptionRaiPolicyServer SubscriptionRaiPolicyServer + + // TestRaiExternalSafetyProviderServer contains the fakes for client TestRaiExternalSafetyProviderClient + TestRaiExternalSafetyProviderServer TestRaiExternalSafetyProviderServer + + // UsagesServer contains the fakes for client UsagesClient + UsagesServer UsagesServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armcognitiveservices.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of armcognitiveservices.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trAccountCapabilityHostsServer *AccountCapabilityHostsServerTransport + trAccountConnectionsServer *AccountConnectionsServerTransport + trAccountsServer *AccountsServerTransport + trAgentApplicationsServer *AgentApplicationsServerTransport + trAgentDeploymentsServer *AgentDeploymentsServerTransport + trCommitmentPlansServer *CommitmentPlansServerTransport + trCommitmentTiersServer *CommitmentTiersServerTransport + trDefenderForAISettingsServer *DefenderForAISettingsServerTransport + trDeletedAccountsServer *DeletedAccountsServerTransport + trDeploymentsServer *DeploymentsServerTransport + trEncryptionScopesServer *EncryptionScopesServerTransport + trLocationBasedModelCapacitiesServer *LocationBasedModelCapacitiesServerTransport + trManagedNetworkProvisionsServer *ManagedNetworkProvisionsServerTransport + trManagedNetworkSettingsServer *ManagedNetworkSettingsServerTransport + trManagementServer *ManagementServerTransport + trModelCapacitiesServer *ModelCapacitiesServerTransport + trModelsServer *ModelsServerTransport + trNetworkSecurityPerimeterConfigurationsServer *NetworkSecurityPerimeterConfigurationsServerTransport + trOperationsServer *OperationsServerTransport + trOutboundRuleServer *OutboundRuleServerTransport + trOutboundRulesServer *OutboundRulesServerTransport + trPrivateEndpointConnectionsServer *PrivateEndpointConnectionsServerTransport + trPrivateLinkResourcesServer *PrivateLinkResourcesServerTransport + trProjectCapabilityHostsServer *ProjectCapabilityHostsServerTransport + trProjectConnectionsServer *ProjectConnectionsServerTransport + trProjectsServer *ProjectsServerTransport + trQuotaTiersServer *QuotaTiersServerTransport + trRaiBlocklistItemsServer *RaiBlocklistItemsServerTransport + trRaiBlocklistsServer *RaiBlocklistsServerTransport + trRaiContentFiltersServer *RaiContentFiltersServerTransport + trRaiExternalSafetyProviderServer *RaiExternalSafetyProviderServerTransport + trRaiExternalSafetyProvidersServer *RaiExternalSafetyProvidersServerTransport + trRaiPoliciesServer *RaiPoliciesServerTransport + trRaiToolLabelsServer *RaiToolLabelsServerTransport + trRaiTopicsServer *RaiTopicsServerTransport + trResourceSKUsServer *ResourceSKUsServerTransport + trSubscriptionRaiPolicyServer *SubscriptionRaiPolicyServerTransport + trTestRaiExternalSafetyProviderServer *TestRaiExternalSafetyProviderServerTransport + trUsagesServer *UsagesServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "AccountCapabilityHostsClient": + initServer(&s.trMu, &s.trAccountCapabilityHostsServer, func() *AccountCapabilityHostsServerTransport { + return NewAccountCapabilityHostsServerTransport(&s.srv.AccountCapabilityHostsServer) + }) + resp, err = s.trAccountCapabilityHostsServer.Do(req) + case "AccountConnectionsClient": + initServer(&s.trMu, &s.trAccountConnectionsServer, func() *AccountConnectionsServerTransport { + return NewAccountConnectionsServerTransport(&s.srv.AccountConnectionsServer) + }) + resp, err = s.trAccountConnectionsServer.Do(req) + case "AccountsClient": + initServer(&s.trMu, &s.trAccountsServer, func() *AccountsServerTransport { return NewAccountsServerTransport(&s.srv.AccountsServer) }) + resp, err = s.trAccountsServer.Do(req) + case "AgentApplicationsClient": + initServer(&s.trMu, &s.trAgentApplicationsServer, func() *AgentApplicationsServerTransport { + return NewAgentApplicationsServerTransport(&s.srv.AgentApplicationsServer) + }) + resp, err = s.trAgentApplicationsServer.Do(req) + case "AgentDeploymentsClient": + initServer(&s.trMu, &s.trAgentDeploymentsServer, func() *AgentDeploymentsServerTransport { + return NewAgentDeploymentsServerTransport(&s.srv.AgentDeploymentsServer) + }) + resp, err = s.trAgentDeploymentsServer.Do(req) + case "CommitmentPlansClient": + initServer(&s.trMu, &s.trCommitmentPlansServer, func() *CommitmentPlansServerTransport { + return NewCommitmentPlansServerTransport(&s.srv.CommitmentPlansServer) + }) + resp, err = s.trCommitmentPlansServer.Do(req) + case "CommitmentTiersClient": + initServer(&s.trMu, &s.trCommitmentTiersServer, func() *CommitmentTiersServerTransport { + return NewCommitmentTiersServerTransport(&s.srv.CommitmentTiersServer) + }) + resp, err = s.trCommitmentTiersServer.Do(req) + case "DefenderForAISettingsClient": + initServer(&s.trMu, &s.trDefenderForAISettingsServer, func() *DefenderForAISettingsServerTransport { + return NewDefenderForAISettingsServerTransport(&s.srv.DefenderForAISettingsServer) + }) + resp, err = s.trDefenderForAISettingsServer.Do(req) + case "DeletedAccountsClient": + initServer(&s.trMu, &s.trDeletedAccountsServer, func() *DeletedAccountsServerTransport { + return NewDeletedAccountsServerTransport(&s.srv.DeletedAccountsServer) + }) + resp, err = s.trDeletedAccountsServer.Do(req) + case "DeploymentsClient": + initServer(&s.trMu, &s.trDeploymentsServer, func() *DeploymentsServerTransport { return NewDeploymentsServerTransport(&s.srv.DeploymentsServer) }) + resp, err = s.trDeploymentsServer.Do(req) + case "EncryptionScopesClient": + initServer(&s.trMu, &s.trEncryptionScopesServer, func() *EncryptionScopesServerTransport { + return NewEncryptionScopesServerTransport(&s.srv.EncryptionScopesServer) + }) + resp, err = s.trEncryptionScopesServer.Do(req) + case "LocationBasedModelCapacitiesClient": + initServer(&s.trMu, &s.trLocationBasedModelCapacitiesServer, func() *LocationBasedModelCapacitiesServerTransport { + return NewLocationBasedModelCapacitiesServerTransport(&s.srv.LocationBasedModelCapacitiesServer) + }) + resp, err = s.trLocationBasedModelCapacitiesServer.Do(req) + case "ManagedNetworkProvisionsClient": + initServer(&s.trMu, &s.trManagedNetworkProvisionsServer, func() *ManagedNetworkProvisionsServerTransport { + return NewManagedNetworkProvisionsServerTransport(&s.srv.ManagedNetworkProvisionsServer) + }) + resp, err = s.trManagedNetworkProvisionsServer.Do(req) + case "ManagedNetworkSettingsClient": + initServer(&s.trMu, &s.trManagedNetworkSettingsServer, func() *ManagedNetworkSettingsServerTransport { + return NewManagedNetworkSettingsServerTransport(&s.srv.ManagedNetworkSettingsServer) + }) + resp, err = s.trManagedNetworkSettingsServer.Do(req) + case "ManagementClient": + initServer(&s.trMu, &s.trManagementServer, func() *ManagementServerTransport { return NewManagementServerTransport(&s.srv.ManagementServer) }) + resp, err = s.trManagementServer.Do(req) + case "ModelCapacitiesClient": + initServer(&s.trMu, &s.trModelCapacitiesServer, func() *ModelCapacitiesServerTransport { + return NewModelCapacitiesServerTransport(&s.srv.ModelCapacitiesServer) + }) + resp, err = s.trModelCapacitiesServer.Do(req) + case "ModelsClient": + initServer(&s.trMu, &s.trModelsServer, func() *ModelsServerTransport { return NewModelsServerTransport(&s.srv.ModelsServer) }) + resp, err = s.trModelsServer.Do(req) + case "NetworkSecurityPerimeterConfigurationsClient": + initServer(&s.trMu, &s.trNetworkSecurityPerimeterConfigurationsServer, func() *NetworkSecurityPerimeterConfigurationsServerTransport { + return NewNetworkSecurityPerimeterConfigurationsServerTransport(&s.srv.NetworkSecurityPerimeterConfigurationsServer) + }) + resp, err = s.trNetworkSecurityPerimeterConfigurationsServer.Do(req) + case "OperationsClient": + initServer(&s.trMu, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + resp, err = s.trOperationsServer.Do(req) + case "OutboundRuleClient": + initServer(&s.trMu, &s.trOutboundRuleServer, func() *OutboundRuleServerTransport { return NewOutboundRuleServerTransport(&s.srv.OutboundRuleServer) }) + resp, err = s.trOutboundRuleServer.Do(req) + case "OutboundRulesClient": + initServer(&s.trMu, &s.trOutboundRulesServer, func() *OutboundRulesServerTransport { + return NewOutboundRulesServerTransport(&s.srv.OutboundRulesServer) + }) + resp, err = s.trOutboundRulesServer.Do(req) + case "PrivateEndpointConnectionsClient": + initServer(&s.trMu, &s.trPrivateEndpointConnectionsServer, func() *PrivateEndpointConnectionsServerTransport { + return NewPrivateEndpointConnectionsServerTransport(&s.srv.PrivateEndpointConnectionsServer) + }) + resp, err = s.trPrivateEndpointConnectionsServer.Do(req) + case "PrivateLinkResourcesClient": + initServer(&s.trMu, &s.trPrivateLinkResourcesServer, func() *PrivateLinkResourcesServerTransport { + return NewPrivateLinkResourcesServerTransport(&s.srv.PrivateLinkResourcesServer) + }) + resp, err = s.trPrivateLinkResourcesServer.Do(req) + case "ProjectCapabilityHostsClient": + initServer(&s.trMu, &s.trProjectCapabilityHostsServer, func() *ProjectCapabilityHostsServerTransport { + return NewProjectCapabilityHostsServerTransport(&s.srv.ProjectCapabilityHostsServer) + }) + resp, err = s.trProjectCapabilityHostsServer.Do(req) + case "ProjectConnectionsClient": + initServer(&s.trMu, &s.trProjectConnectionsServer, func() *ProjectConnectionsServerTransport { + return NewProjectConnectionsServerTransport(&s.srv.ProjectConnectionsServer) + }) + resp, err = s.trProjectConnectionsServer.Do(req) + case "ProjectsClient": + initServer(&s.trMu, &s.trProjectsServer, func() *ProjectsServerTransport { return NewProjectsServerTransport(&s.srv.ProjectsServer) }) + resp, err = s.trProjectsServer.Do(req) + case "QuotaTiersClient": + initServer(&s.trMu, &s.trQuotaTiersServer, func() *QuotaTiersServerTransport { return NewQuotaTiersServerTransport(&s.srv.QuotaTiersServer) }) + resp, err = s.trQuotaTiersServer.Do(req) + case "RaiBlocklistItemsClient": + initServer(&s.trMu, &s.trRaiBlocklistItemsServer, func() *RaiBlocklistItemsServerTransport { + return NewRaiBlocklistItemsServerTransport(&s.srv.RaiBlocklistItemsServer) + }) + resp, err = s.trRaiBlocklistItemsServer.Do(req) + case "RaiBlocklistsClient": + initServer(&s.trMu, &s.trRaiBlocklistsServer, func() *RaiBlocklistsServerTransport { + return NewRaiBlocklistsServerTransport(&s.srv.RaiBlocklistsServer) + }) + resp, err = s.trRaiBlocklistsServer.Do(req) + case "RaiContentFiltersClient": + initServer(&s.trMu, &s.trRaiContentFiltersServer, func() *RaiContentFiltersServerTransport { + return NewRaiContentFiltersServerTransport(&s.srv.RaiContentFiltersServer) + }) + resp, err = s.trRaiContentFiltersServer.Do(req) + case "RaiExternalSafetyProviderClient": + initServer(&s.trMu, &s.trRaiExternalSafetyProviderServer, func() *RaiExternalSafetyProviderServerTransport { + return NewRaiExternalSafetyProviderServerTransport(&s.srv.RaiExternalSafetyProviderServer) + }) + resp, err = s.trRaiExternalSafetyProviderServer.Do(req) + case "RaiExternalSafetyProvidersClient": + initServer(&s.trMu, &s.trRaiExternalSafetyProvidersServer, func() *RaiExternalSafetyProvidersServerTransport { + return NewRaiExternalSafetyProvidersServerTransport(&s.srv.RaiExternalSafetyProvidersServer) + }) + resp, err = s.trRaiExternalSafetyProvidersServer.Do(req) + case "RaiPoliciesClient": + initServer(&s.trMu, &s.trRaiPoliciesServer, func() *RaiPoliciesServerTransport { return NewRaiPoliciesServerTransport(&s.srv.RaiPoliciesServer) }) + resp, err = s.trRaiPoliciesServer.Do(req) + case "RaiToolLabelsClient": + initServer(&s.trMu, &s.trRaiToolLabelsServer, func() *RaiToolLabelsServerTransport { + return NewRaiToolLabelsServerTransport(&s.srv.RaiToolLabelsServer) + }) + resp, err = s.trRaiToolLabelsServer.Do(req) + case "RaiTopicsClient": + initServer(&s.trMu, &s.trRaiTopicsServer, func() *RaiTopicsServerTransport { return NewRaiTopicsServerTransport(&s.srv.RaiTopicsServer) }) + resp, err = s.trRaiTopicsServer.Do(req) + case "ResourceSKUsClient": + initServer(&s.trMu, &s.trResourceSKUsServer, func() *ResourceSKUsServerTransport { return NewResourceSKUsServerTransport(&s.srv.ResourceSKUsServer) }) + resp, err = s.trResourceSKUsServer.Do(req) + case "SubscriptionRaiPolicyClient": + initServer(&s.trMu, &s.trSubscriptionRaiPolicyServer, func() *SubscriptionRaiPolicyServerTransport { + return NewSubscriptionRaiPolicyServerTransport(&s.srv.SubscriptionRaiPolicyServer) + }) + resp, err = s.trSubscriptionRaiPolicyServer.Do(req) + case "TestRaiExternalSafetyProviderClient": + initServer(&s.trMu, &s.trTestRaiExternalSafetyProviderServer, func() *TestRaiExternalSafetyProviderServerTransport { + return NewTestRaiExternalSafetyProviderServerTransport(&s.srv.TestRaiExternalSafetyProviderServer) + }) + resp, err = s.trTestRaiExternalSafetyProviderServer.Do(req) + case "UsagesClient": + initServer(&s.trMu, &s.trUsagesServer, func() *UsagesServerTransport { return NewUsagesServerTransport(&s.srv.UsagesServer) }) + resp, err = s.trUsagesServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} diff --git a/test/local/armcognitiveservices/fake/zz_subscriptionraipolicy_server.go b/test/local/armcognitiveservices/fake/zz_subscriptionraipolicy_server.go new file mode 100644 index 000000000000..1e6a21a50b88 --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_subscriptionraipolicy_server.go @@ -0,0 +1,202 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// SubscriptionRaiPolicyServer is a fake server for instances of the armcognitiveservices.SubscriptionRaiPolicyClient type. +type SubscriptionRaiPolicyServer struct { + // CreateOrUpdate is the fake for method SubscriptionRaiPolicyClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, raiPolicyName string, raiPolicy armcognitiveservices.RaiPolicy, options *armcognitiveservices.SubscriptionRaiPolicyClientCreateOrUpdateOptions) (resp azfake.Responder[armcognitiveservices.SubscriptionRaiPolicyClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method SubscriptionRaiPolicyClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, raiPolicyName string, options *armcognitiveservices.SubscriptionRaiPolicyClientBeginDeleteOptions) (resp azfake.PollerResponder[armcognitiveservices.SubscriptionRaiPolicyClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method SubscriptionRaiPolicyClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, raiPolicyName string, options *armcognitiveservices.SubscriptionRaiPolicyClientGetOptions) (resp azfake.Responder[armcognitiveservices.SubscriptionRaiPolicyClientGetResponse], errResp azfake.ErrorResponder) +} + +// NewSubscriptionRaiPolicyServerTransport creates a new instance of SubscriptionRaiPolicyServerTransport with the provided implementation. +// The returned SubscriptionRaiPolicyServerTransport instance is connected to an instance of armcognitiveservices.SubscriptionRaiPolicyClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSubscriptionRaiPolicyServerTransport(srv *SubscriptionRaiPolicyServer) *SubscriptionRaiPolicyServerTransport { + return &SubscriptionRaiPolicyServerTransport{ + srv: srv, + beginDelete: newTracker[azfake.PollerResponder[armcognitiveservices.SubscriptionRaiPolicyClientDeleteResponse]](), + } +} + +// SubscriptionRaiPolicyServerTransport connects instances of armcognitiveservices.SubscriptionRaiPolicyClient to instances of SubscriptionRaiPolicyServer. +// Don't use this type directly, use NewSubscriptionRaiPolicyServerTransport instead. +type SubscriptionRaiPolicyServerTransport struct { + srv *SubscriptionRaiPolicyServer + beginDelete *tracker[azfake.PollerResponder[armcognitiveservices.SubscriptionRaiPolicyClientDeleteResponse]] +} + +// Do implements the policy.Transporter interface for SubscriptionRaiPolicyServerTransport. +func (s *SubscriptionRaiPolicyServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *SubscriptionRaiPolicyServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if subscriptionRaiPolicyServerTransportInterceptor != nil { + res.resp, res.err, intercepted = subscriptionRaiPolicyServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SubscriptionRaiPolicyClient.CreateOrUpdate": + res.resp, res.err = s.dispatchCreateOrUpdate(req) + case "SubscriptionRaiPolicyClient.BeginDelete": + res.resp, res.err = s.dispatchBeginDelete(req) + case "SubscriptionRaiPolicyClient.Get": + res.resp, res.err = s.dispatchGet(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *SubscriptionRaiPolicyServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if s.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/raiPolicy/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.RaiPolicy](req) + if err != nil { + return nil, err + } + raiPolicyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("raiPolicyName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.CreateOrUpdate(req.Context(), raiPolicyNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RaiPolicy, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SubscriptionRaiPolicyServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if s.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := s.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/raiPolicy/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + raiPolicyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("raiPolicyName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.BeginDelete(req.Context(), raiPolicyNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + s.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + s.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + s.beginDelete.remove(req) + } + + return resp, nil +} + +func (s *SubscriptionRaiPolicyServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if s.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/raiPolicy/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + raiPolicyNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("raiPolicyName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Get(req.Context(), raiPolicyNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RaiPolicy, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SubscriptionRaiPolicyServerTransport +var subscriptionRaiPolicyServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_testraiexternalsafetyprovider_server.go b/test/local/armcognitiveservices/fake/zz_testraiexternalsafetyprovider_server.go new file mode 100644 index 000000000000..004e7aece652 --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_testraiexternalsafetyprovider_server.go @@ -0,0 +1,125 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// TestRaiExternalSafetyProviderServer is a fake server for instances of the armcognitiveservices.TestRaiExternalSafetyProviderClient type. +type TestRaiExternalSafetyProviderServer struct { + // CreateOrUpdate is the fake for method TestRaiExternalSafetyProviderClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, accountName string, safetyProviderName string, safetyProvider armcognitiveservices.RaiExternalSafetyProviderSchema, options *armcognitiveservices.TestRaiExternalSafetyProviderClientCreateOrUpdateOptions) (resp azfake.Responder[armcognitiveservices.TestRaiExternalSafetyProviderClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewTestRaiExternalSafetyProviderServerTransport creates a new instance of TestRaiExternalSafetyProviderServerTransport with the provided implementation. +// The returned TestRaiExternalSafetyProviderServerTransport instance is connected to an instance of armcognitiveservices.TestRaiExternalSafetyProviderClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewTestRaiExternalSafetyProviderServerTransport(srv *TestRaiExternalSafetyProviderServer) *TestRaiExternalSafetyProviderServerTransport { + return &TestRaiExternalSafetyProviderServerTransport{srv: srv} +} + +// TestRaiExternalSafetyProviderServerTransport connects instances of armcognitiveservices.TestRaiExternalSafetyProviderClient to instances of TestRaiExternalSafetyProviderServer. +// Don't use this type directly, use NewTestRaiExternalSafetyProviderServerTransport instead. +type TestRaiExternalSafetyProviderServerTransport struct { + srv *TestRaiExternalSafetyProviderServer +} + +// Do implements the policy.Transporter interface for TestRaiExternalSafetyProviderServerTransport. +func (t *TestRaiExternalSafetyProviderServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return t.dispatchToMethodFake(req, method) +} + +func (t *TestRaiExternalSafetyProviderServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if testRaiExternalSafetyProviderServerTransportInterceptor != nil { + res.resp, res.err, intercepted = testRaiExternalSafetyProviderServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "TestRaiExternalSafetyProviderClient.CreateOrUpdate": + res.resp, res.err = t.dispatchCreateOrUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (t *TestRaiExternalSafetyProviderServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if t.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/accounts/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/testRaiExternalSafetyProvider/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcognitiveservices.RaiExternalSafetyProviderSchema](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + accountNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("accountName")]) + if err != nil { + return nil, err + } + safetyProviderNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("safetyProviderName")]) + if err != nil { + return nil, err + } + respr, errRespr := t.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, accountNameParam, safetyProviderNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RaiExternalSafetyProviderSchema, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to TestRaiExternalSafetyProviderServerTransport +var testRaiExternalSafetyProviderServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/fake/zz_usages_server.go b/test/local/armcognitiveservices/fake/zz_usages_server.go new file mode 100644 index 000000000000..1ebbb65cfb1c --- /dev/null +++ b/test/local/armcognitiveservices/fake/zz_usages_server.go @@ -0,0 +1,133 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcognitiveservices" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// UsagesServer is a fake server for instances of the armcognitiveservices.UsagesClient type. +type UsagesServer struct { + // NewListPager is the fake for method UsagesClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(location string, options *armcognitiveservices.UsagesClientListOptions) (resp azfake.PagerResponder[armcognitiveservices.UsagesClientListResponse]) +} + +// NewUsagesServerTransport creates a new instance of UsagesServerTransport with the provided implementation. +// The returned UsagesServerTransport instance is connected to an instance of armcognitiveservices.UsagesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewUsagesServerTransport(srv *UsagesServer) *UsagesServerTransport { + return &UsagesServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armcognitiveservices.UsagesClientListResponse]](), + } +} + +// UsagesServerTransport connects instances of armcognitiveservices.UsagesClient to instances of UsagesServer. +// Don't use this type directly, use NewUsagesServerTransport instead. +type UsagesServerTransport struct { + srv *UsagesServer + newListPager *tracker[azfake.PagerResponder[armcognitiveservices.UsagesClientListResponse]] +} + +// Do implements the policy.Transporter interface for UsagesServerTransport. +func (u *UsagesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return u.dispatchToMethodFake(req, method) +} + +func (u *UsagesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if usagesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = usagesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "UsagesClient.NewListPager": + res.resp, res.err = u.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (u *UsagesServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if u.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := u.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.CognitiveServices/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/usages` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + filterParam := getOptional(qp.Get("$filter")) + var options *armcognitiveservices.UsagesClientListOptions + if filterParam != nil { + options = &armcognitiveservices.UsagesClientListOptions{ + Filter: filterParam, + } + } + resp := u.srv.NewListPager(locationParam, options) + newListPager = &resp + u.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcognitiveservices.UsagesClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + u.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + u.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to UsagesServerTransport +var usagesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcognitiveservices/go.mod b/test/local/armcognitiveservices/go.mod new file mode 100644 index 000000000000..4a55cb5f2e6e --- /dev/null +++ b/test/local/armcognitiveservices/go.mod @@ -0,0 +1,11 @@ +module armcognitiveservices + +go 1.25.0 + +require github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect +) diff --git a/test/local/armcognitiveservices/go.sum b/test/local/armcognitiveservices/go.sum new file mode 100644 index 000000000000..3fdb64caf441 --- /dev/null +++ b/test/local/armcognitiveservices/go.sum @@ -0,0 +1,16 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/local/armcognitiveservices/testdata/_metadata.json b/test/local/armcognitiveservices/testdata/_metadata.json new file mode 100644 index 000000000000..e7d670f91ccb --- /dev/null +++ b/test/local/armcognitiveservices/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Microsoft.CognitiveServices": "2026-05-01" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/local/armcognitiveservices/zz_accountcapabilityhosts_client.go b/test/local/armcognitiveservices/zz_accountcapabilityhosts_client.go new file mode 100644 index 000000000000..121aea62f6c4 --- /dev/null +++ b/test/local/armcognitiveservices/zz_accountcapabilityhosts_client.go @@ -0,0 +1,344 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// AccountCapabilityHostsClient contains the methods for the AccountCapabilityHosts group. +// Don't use this type directly, use NewAccountCapabilityHostsClient() instead. +// +// Generated from API version 2026-05-01 +type AccountCapabilityHostsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAccountCapabilityHostsClient creates a new instance of AccountCapabilityHostsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewAccountCapabilityHostsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AccountCapabilityHostsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AccountCapabilityHostsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create or update account capabilityHost. +// +// Create or update account capabilityHost. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - capabilityHostName - The name of the capability host associated with the Cognitive Services Resource +// - capabilityHost - CapabilityHost definition. +// - options - AccountCapabilityHostsClientBeginCreateOrUpdateOptions contains the optional parameters for the AccountCapabilityHostsClient.BeginCreateOrUpdate +// method. +func (client *AccountCapabilityHostsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, capabilityHostName string, capabilityHost CapabilityHost, options *AccountCapabilityHostsClientBeginCreateOrUpdateOptions) (*runtime.Poller[AccountCapabilityHostsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, accountName, capabilityHostName, capabilityHost, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AccountCapabilityHostsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaOriginalURI, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AccountCapabilityHostsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create or update account capabilityHost. +// +// Create or update account capabilityHost. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *AccountCapabilityHostsClient) createOrUpdate(ctx context.Context, resourceGroupName string, accountName string, capabilityHostName string, capabilityHost CapabilityHost, options *AccountCapabilityHostsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "AccountCapabilityHostsClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, capabilityHostName, capabilityHost, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *AccountCapabilityHostsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, capabilityHostName string, capabilityHost CapabilityHost, _ *AccountCapabilityHostsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/capabilityHosts/{capabilityHostName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if capabilityHostName == "" { + return nil, errors.New("parameter capabilityHostName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{capabilityHostName}", url.PathEscape(capabilityHostName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, capabilityHost); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete account capabilityHost. +// +// Delete account capabilityHost. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - capabilityHostName - The name of the capability host associated with the Cognitive Services Resource +// - options - AccountCapabilityHostsClientBeginDeleteOptions contains the optional parameters for the AccountCapabilityHostsClient.BeginDelete +// method. +func (client *AccountCapabilityHostsClient) BeginDelete(ctx context.Context, resourceGroupName string, accountName string, capabilityHostName string, options *AccountCapabilityHostsClientBeginDeleteOptions) (*runtime.Poller[AccountCapabilityHostsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, accountName, capabilityHostName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AccountCapabilityHostsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AccountCapabilityHostsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete account capabilityHost. +// +// Delete account capabilityHost. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *AccountCapabilityHostsClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, capabilityHostName string, options *AccountCapabilityHostsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "AccountCapabilityHostsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, capabilityHostName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *AccountCapabilityHostsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, capabilityHostName string, _ *AccountCapabilityHostsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/capabilityHosts/{capabilityHostName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if capabilityHostName == "" { + return nil, errors.New("parameter capabilityHostName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{capabilityHostName}", url.PathEscape(capabilityHostName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get account capabilityHost. +// +// Get account capabilityHost. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - capabilityHostName - The name of the capability host associated with the Cognitive Services Resource +// - options - AccountCapabilityHostsClientGetOptions contains the optional parameters for the AccountCapabilityHostsClient.Get +// method. +func (client *AccountCapabilityHostsClient) Get(ctx context.Context, resourceGroupName string, accountName string, capabilityHostName string, options *AccountCapabilityHostsClientGetOptions) (AccountCapabilityHostsClientGetResponse, error) { + var err error + const operationName = "AccountCapabilityHostsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, capabilityHostName, options) + if err != nil { + return AccountCapabilityHostsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AccountCapabilityHostsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AccountCapabilityHostsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *AccountCapabilityHostsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, capabilityHostName string, _ *AccountCapabilityHostsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/capabilityHosts/{capabilityHostName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if capabilityHostName == "" { + return nil, errors.New("parameter capabilityHostName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{capabilityHostName}", url.PathEscape(capabilityHostName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *AccountCapabilityHostsClient) getHandleResponse(resp *http.Response) (AccountCapabilityHostsClientGetResponse, error) { + result := AccountCapabilityHostsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CapabilityHost); err != nil { + return AccountCapabilityHostsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List capabilityHost. +// +// List capabilityHost. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - options - AccountCapabilityHostsClientListOptions contains the optional parameters for the AccountCapabilityHostsClient.NewListPager +// method. +func (client *AccountCapabilityHostsClient) NewListPager(resourceGroupName string, accountName string, options *AccountCapabilityHostsClientListOptions) *runtime.Pager[AccountCapabilityHostsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[AccountCapabilityHostsClientListResponse]{ + More: func(page AccountCapabilityHostsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AccountCapabilityHostsClientListResponse) (AccountCapabilityHostsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AccountCapabilityHostsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, options) + }, nil) + if err != nil { + return AccountCapabilityHostsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *AccountCapabilityHostsClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, _ *AccountCapabilityHostsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/capabilityHosts" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *AccountCapabilityHostsClient) listHandleResponse(resp *http.Response) (AccountCapabilityHostsClientListResponse, error) { + result := AccountCapabilityHostsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CapabilityHostResourceArmPaginatedResult); err != nil { + return AccountCapabilityHostsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_accountconnections_client.go b/test/local/armcognitiveservices/zz_accountconnections_client.go new file mode 100644 index 000000000000..27c67bd3a3f3 --- /dev/null +++ b/test/local/armcognitiveservices/zz_accountconnections_client.go @@ -0,0 +1,395 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" +) + +// AccountConnectionsClient contains the methods for the AccountConnections group. +// Don't use this type directly, use NewAccountConnectionsClient() instead. +// +// Generated from API version 2026-05-01 +type AccountConnectionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAccountConnectionsClient creates a new instance of AccountConnectionsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewAccountConnectionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AccountConnectionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AccountConnectionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Create - Create or update Cognitive Services account connection under the specified account. +// +// Create or update Cognitive Services account connection under the specified account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - connectionName - Friendly name of the connection +// - connection - The object for creating or updating a new account connection +// - options - AccountConnectionsClientCreateOptions contains the optional parameters for the AccountConnectionsClient.Create +// method. +func (client *AccountConnectionsClient) Create(ctx context.Context, resourceGroupName string, accountName string, connectionName string, connection ConnectionPropertiesV2BasicResource, options *AccountConnectionsClientCreateOptions) (AccountConnectionsClientCreateResponse, error) { + var err error + const operationName = "AccountConnectionsClient.Create" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, accountName, connectionName, connection, options) + if err != nil { + return AccountConnectionsClientCreateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AccountConnectionsClientCreateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AccountConnectionsClientCreateResponse{}, err + } + resp, err := client.createHandleResponse(httpResp) + return resp, err +} + +// createCreateRequest creates the Create request. +func (client *AccountConnectionsClient) createCreateRequest(ctx context.Context, resourceGroupName string, accountName string, connectionName string, connection ConnectionPropertiesV2BasicResource, _ *AccountConnectionsClientCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/connections/{connectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, connection); err != nil { + return nil, err + } + return req, nil +} + +// createHandleResponse handles the Create response. +func (client *AccountConnectionsClient) createHandleResponse(resp *http.Response) (AccountConnectionsClientCreateResponse, error) { + result := AccountConnectionsClientCreateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ConnectionPropertiesV2BasicResource); err != nil { + return AccountConnectionsClientCreateResponse{}, err + } + return result, nil +} + +// Delete - Delete Cognitive Services account connection by name. +// +// Delete Cognitive Services account connection by name. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - connectionName - Friendly name of the connection +// - options - AccountConnectionsClientDeleteOptions contains the optional parameters for the AccountConnectionsClient.Delete +// method. +func (client *AccountConnectionsClient) Delete(ctx context.Context, resourceGroupName string, accountName string, connectionName string, options *AccountConnectionsClientDeleteOptions) (AccountConnectionsClientDeleteResponse, error) { + var err error + const operationName = "AccountConnectionsClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, connectionName, options) + if err != nil { + return AccountConnectionsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AccountConnectionsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return AccountConnectionsClientDeleteResponse{}, err + } + return AccountConnectionsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *AccountConnectionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, connectionName string, _ *AccountConnectionsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/connections/{connectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Lists Cognitive Services account connection by name. +// +// Lists Cognitive Services account connection by name. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - connectionName - Friendly name of the connection +// - options - AccountConnectionsClientGetOptions contains the optional parameters for the AccountConnectionsClient.Get method. +func (client *AccountConnectionsClient) Get(ctx context.Context, resourceGroupName string, accountName string, connectionName string, options *AccountConnectionsClientGetOptions) (AccountConnectionsClientGetResponse, error) { + var err error + const operationName = "AccountConnectionsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, connectionName, options) + if err != nil { + return AccountConnectionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AccountConnectionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AccountConnectionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *AccountConnectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, connectionName string, _ *AccountConnectionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/connections/{connectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *AccountConnectionsClient) getHandleResponse(resp *http.Response) (AccountConnectionsClientGetResponse, error) { + result := AccountConnectionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ConnectionPropertiesV2BasicResource); err != nil { + return AccountConnectionsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all the available Cognitive Services account connections under the specified account. +// +// Lists all the available Cognitive Services account connections under the specified account. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - options - AccountConnectionsClientListOptions contains the optional parameters for the AccountConnectionsClient.NewListPager +// method. +func (client *AccountConnectionsClient) NewListPager(resourceGroupName string, accountName string, options *AccountConnectionsClientListOptions) *runtime.Pager[AccountConnectionsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[AccountConnectionsClientListResponse]{ + More: func(page AccountConnectionsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AccountConnectionsClientListResponse) (AccountConnectionsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AccountConnectionsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, options) + }, nil) + if err != nil { + return AccountConnectionsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *AccountConnectionsClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *AccountConnectionsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/connections" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + if options != nil && options.Category != nil { + reqQP.Set("category", *options.Category) + } + if options != nil && options.IncludeAll != nil { + reqQP.Set("includeAll", strconv.FormatBool(*options.IncludeAll)) + } + if options != nil && options.Target != nil { + reqQP.Set("target", *options.Target) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *AccountConnectionsClient) listHandleResponse(resp *http.Response) (AccountConnectionsClientListResponse, error) { + result := AccountConnectionsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ConnectionPropertiesV2BasicResourceArmPaginatedResult); err != nil { + return AccountConnectionsClientListResponse{}, err + } + return result, nil +} + +// Update - Update Cognitive Services account connection under the specified account. +// +// Update Cognitive Services account connection under the specified account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - connectionName - Friendly name of the connection +// - connection - Parameters for account connection update. +// - options - AccountConnectionsClientUpdateOptions contains the optional parameters for the AccountConnectionsClient.Update +// method. +func (client *AccountConnectionsClient) Update(ctx context.Context, resourceGroupName string, accountName string, connectionName string, connection ConnectionUpdateContent, options *AccountConnectionsClientUpdateOptions) (AccountConnectionsClientUpdateResponse, error) { + var err error + const operationName = "AccountConnectionsClient.Update" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, accountName, connectionName, connection, options) + if err != nil { + return AccountConnectionsClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AccountConnectionsClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AccountConnectionsClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *AccountConnectionsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, connectionName string, connection ConnectionUpdateContent, _ *AccountConnectionsClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/connections/{connectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, connection); err != nil { + return nil, err + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *AccountConnectionsClient) updateHandleResponse(resp *http.Response) (AccountConnectionsClientUpdateResponse, error) { + result := AccountConnectionsClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ConnectionPropertiesV2BasicResource); err != nil { + return AccountConnectionsClientUpdateResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_accounts_client.go b/test/local/armcognitiveservices/zz_accounts_client.go new file mode 100644 index 000000000000..c975565ee960 --- /dev/null +++ b/test/local/armcognitiveservices/zz_accounts_client.go @@ -0,0 +1,756 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// AccountsClient contains the methods for the Accounts group. +// Don't use this type directly, use NewAccountsClient() instead. +// +// Generated from API version 2026-05-01 +type AccountsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAccountsClient creates a new instance of AccountsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewAccountsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AccountsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AccountsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreate - Create Cognitive Services Account. Accounts is a resource group wide resource type. It holds the keys for +// developer to access intelligent APIs. It's also the resource type for billing. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - account - The parameters to provide for the created account. +// - options - AccountsClientBeginCreateOptions contains the optional parameters for the AccountsClient.BeginCreate method. +func (client *AccountsClient) BeginCreate(ctx context.Context, resourceGroupName string, accountName string, account Account, options *AccountsClientBeginCreateOptions) (*runtime.Poller[AccountsClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, resourceGroupName, accountName, account, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AccountsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AccountsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Create Cognitive Services Account. Accounts is a resource group wide resource type. It holds the keys for developer +// to access intelligent APIs. It's also the resource type for billing. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *AccountsClient) create(ctx context.Context, resourceGroupName string, accountName string, account Account, options *AccountsClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "AccountsClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, accountName, account, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *AccountsClient) createCreateRequest(ctx context.Context, resourceGroupName string, accountName string, account Account, _ *AccountsClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, account); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a Cognitive Services account from the resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - options - AccountsClientBeginDeleteOptions contains the optional parameters for the AccountsClient.BeginDelete method. +func (client *AccountsClient) BeginDelete(ctx context.Context, resourceGroupName string, accountName string, options *AccountsClientBeginDeleteOptions) (*runtime.Poller[AccountsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, accountName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AccountsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AccountsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a Cognitive Services account from the resource group. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *AccountsClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, options *AccountsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "AccountsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *AccountsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, _ *AccountsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Returns a Cognitive Services account specified by the parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - options - AccountsClientGetOptions contains the optional parameters for the AccountsClient.Get method. +func (client *AccountsClient) Get(ctx context.Context, resourceGroupName string, accountName string, options *AccountsClientGetOptions) (AccountsClientGetResponse, error) { + var err error + const operationName = "AccountsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return AccountsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AccountsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AccountsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *AccountsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, _ *AccountsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *AccountsClient) getHandleResponse(resp *http.Response) (AccountsClientGetResponse, error) { + result := AccountsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Account); err != nil { + return AccountsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Returns all the resources of a particular type belonging to a subscription. +// - options - AccountsClientListOptions contains the optional parameters for the AccountsClient.NewListPager method. +func (client *AccountsClient) NewListPager(options *AccountsClientListOptions) *runtime.Pager[AccountsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[AccountsClientListResponse]{ + More: func(page AccountsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AccountsClientListResponse) (AccountsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AccountsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return AccountsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *AccountsClient) listCreateRequest(ctx context.Context, _ *AccountsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/accounts" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *AccountsClient) listHandleResponse(resp *http.Response) (AccountsClientListResponse, error) { + result := AccountsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AccountListResult); err != nil { + return AccountsClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Returns all the resources of a particular type belonging to a resource group +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - AccountsClientListByResourceGroupOptions contains the optional parameters for the AccountsClient.NewListByResourceGroupPager +// method. +func (client *AccountsClient) NewListByResourceGroupPager(resourceGroupName string, options *AccountsClientListByResourceGroupOptions) *runtime.Pager[AccountsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[AccountsClientListByResourceGroupResponse]{ + More: func(page AccountsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AccountsClientListByResourceGroupResponse) (AccountsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AccountsClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return AccountsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *AccountsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *AccountsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *AccountsClient) listByResourceGroupHandleResponse(resp *http.Response) (AccountsClientListByResourceGroupResponse, error) { + result := AccountsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AccountListResult); err != nil { + return AccountsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// ListKeys - Lists the account keys for the specified Cognitive Services account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - options - AccountsClientListKeysOptions contains the optional parameters for the AccountsClient.ListKeys method. +func (client *AccountsClient) ListKeys(ctx context.Context, resourceGroupName string, accountName string, options *AccountsClientListKeysOptions) (AccountsClientListKeysResponse, error) { + var err error + const operationName = "AccountsClient.ListKeys" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listKeysCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return AccountsClientListKeysResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AccountsClientListKeysResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AccountsClientListKeysResponse{}, err + } + resp, err := client.listKeysHandleResponse(httpResp) + return resp, err +} + +// listKeysCreateRequest creates the ListKeys request. +func (client *AccountsClient) listKeysCreateRequest(ctx context.Context, resourceGroupName string, accountName string, _ *AccountsClientListKeysOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/listKeys" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listKeysHandleResponse handles the ListKeys response. +func (client *AccountsClient) listKeysHandleResponse(resp *http.Response) (AccountsClientListKeysResponse, error) { + result := AccountsClientListKeysResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.APIKeys); err != nil { + return AccountsClientListKeysResponse{}, err + } + return result, nil +} + +// NewListModelsPager - List available Models for the requested Cognitive Services account +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - options - AccountsClientListModelsOptions contains the optional parameters for the AccountsClient.NewListModelsPager method. +func (client *AccountsClient) NewListModelsPager(resourceGroupName string, accountName string, options *AccountsClientListModelsOptions) *runtime.Pager[AccountsClientListModelsResponse] { + return runtime.NewPager(runtime.PagingHandler[AccountsClientListModelsResponse]{ + More: func(page AccountsClientListModelsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AccountsClientListModelsResponse) (AccountsClientListModelsResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AccountsClient.NewListModelsPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listModelsCreateRequest(ctx, resourceGroupName, accountName, options) + }, nil) + if err != nil { + return AccountsClientListModelsResponse{}, err + } + return client.listModelsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listModelsCreateRequest creates the ListModels request. +func (client *AccountsClient) listModelsCreateRequest(ctx context.Context, resourceGroupName string, accountName string, _ *AccountsClientListModelsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/models" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listModelsHandleResponse handles the ListModels response. +func (client *AccountsClient) listModelsHandleResponse(resp *http.Response) (AccountsClientListModelsResponse, error) { + result := AccountsClientListModelsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AccountModelListResult); err != nil { + return AccountsClientListModelsResponse{}, err + } + return result, nil +} + +// ListSKUs - List available SKUs for the requested Cognitive Services account +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - options - AccountsClientListSKUsOptions contains the optional parameters for the AccountsClient.ListSKUs method. +func (client *AccountsClient) ListSKUs(ctx context.Context, resourceGroupName string, accountName string, options *AccountsClientListSKUsOptions) (AccountsClientListSKUsResponse, error) { + var err error + const operationName = "AccountsClient.ListSKUs" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listSKUsCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return AccountsClientListSKUsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AccountsClientListSKUsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AccountsClientListSKUsResponse{}, err + } + resp, err := client.listSKUsHandleResponse(httpResp) + return resp, err +} + +// listSKUsCreateRequest creates the ListSKUs request. +func (client *AccountsClient) listSKUsCreateRequest(ctx context.Context, resourceGroupName string, accountName string, _ *AccountsClientListSKUsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/skus" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listSKUsHandleResponse handles the ListSKUs response. +func (client *AccountsClient) listSKUsHandleResponse(resp *http.Response) (AccountsClientListSKUsResponse, error) { + result := AccountsClientListSKUsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AccountSKUListResult); err != nil { + return AccountsClientListSKUsResponse{}, err + } + return result, nil +} + +// ListUsages - Get usages for the requested Cognitive Services account +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - options - AccountsClientListUsagesOptions contains the optional parameters for the AccountsClient.ListUsages method. +func (client *AccountsClient) ListUsages(ctx context.Context, resourceGroupName string, accountName string, options *AccountsClientListUsagesOptions) (AccountsClientListUsagesResponse, error) { + var err error + const operationName = "AccountsClient.ListUsages" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listUsagesCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return AccountsClientListUsagesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AccountsClientListUsagesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AccountsClientListUsagesResponse{}, err + } + resp, err := client.listUsagesHandleResponse(httpResp) + return resp, err +} + +// listUsagesCreateRequest creates the ListUsages request. +func (client *AccountsClient) listUsagesCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *AccountsClientListUsagesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/usages" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listUsagesHandleResponse handles the ListUsages response. +func (client *AccountsClient) listUsagesHandleResponse(resp *http.Response) (AccountsClientListUsagesResponse, error) { + result := AccountsClientListUsagesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.UsageListResult); err != nil { + return AccountsClientListUsagesResponse{}, err + } + return result, nil +} + +// RegenerateKey - Regenerates the specified account key for the specified Cognitive Services account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - parameters - regenerate key parameters. +// - options - AccountsClientRegenerateKeyOptions contains the optional parameters for the AccountsClient.RegenerateKey method. +func (client *AccountsClient) RegenerateKey(ctx context.Context, resourceGroupName string, accountName string, parameters RegenerateKeyParameters, options *AccountsClientRegenerateKeyOptions) (AccountsClientRegenerateKeyResponse, error) { + var err error + const operationName = "AccountsClient.RegenerateKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.regenerateKeyCreateRequest(ctx, resourceGroupName, accountName, parameters, options) + if err != nil { + return AccountsClientRegenerateKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AccountsClientRegenerateKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AccountsClientRegenerateKeyResponse{}, err + } + resp, err := client.regenerateKeyHandleResponse(httpResp) + return resp, err +} + +// regenerateKeyCreateRequest creates the RegenerateKey request. +func (client *AccountsClient) regenerateKeyCreateRequest(ctx context.Context, resourceGroupName string, accountName string, parameters RegenerateKeyParameters, _ *AccountsClientRegenerateKeyOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/regenerateKey" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// regenerateKeyHandleResponse handles the RegenerateKey response. +func (client *AccountsClient) regenerateKeyHandleResponse(resp *http.Response) (AccountsClientRegenerateKeyResponse, error) { + result := AccountsClientRegenerateKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.APIKeys); err != nil { + return AccountsClientRegenerateKeyResponse{}, err + } + return result, nil +} + +// BeginUpdate - Updates a Cognitive Services account +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - account - The parameters to provide for the created account. +// - options - AccountsClientBeginUpdateOptions contains the optional parameters for the AccountsClient.BeginUpdate method. +func (client *AccountsClient) BeginUpdate(ctx context.Context, resourceGroupName string, accountName string, account Account, options *AccountsClientBeginUpdateOptions) (*runtime.Poller[AccountsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, accountName, account, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AccountsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AccountsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Updates a Cognitive Services account +// If the operation fails it returns an *azcore.ResponseError type. +func (client *AccountsClient) update(ctx context.Context, resourceGroupName string, accountName string, account Account, options *AccountsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "AccountsClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, accountName, account, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *AccountsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, account Account, _ *AccountsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, account); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armcognitiveservices/zz_agentapplications_client.go b/test/local/armcognitiveservices/zz_agentapplications_client.go new file mode 100644 index 000000000000..04ebb889fbf6 --- /dev/null +++ b/test/local/armcognitiveservices/zz_agentapplications_client.go @@ -0,0 +1,589 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" +) + +// AgentApplicationsClient contains the methods for the AgentApplications group. +// Don't use this type directly, use NewAgentApplicationsClient() instead. +// +// Generated from API version 2026-05-01 +type AgentApplicationsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAgentApplicationsClient creates a new instance of AgentApplicationsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewAgentApplicationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AgentApplicationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AgentApplicationsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates an Agent Application (asynchronous). +// +// Creates or updates an Agent Application (asynchronous). +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - projectName - The name of Cognitive Services account's project. +// - name - Name for the Agent Application. +// - body - Agent Application definition object. +// - options - AgentApplicationsClientBeginCreateOrUpdateOptions contains the optional parameters for the AgentApplicationsClient.BeginCreateOrUpdate +// method. +func (client *AgentApplicationsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, projectName string, name string, body AgentApplication, options *AgentApplicationsClientBeginCreateOrUpdateOptions) (*runtime.Poller[AgentApplicationsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, accountName, projectName, name, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AgentApplicationsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AgentApplicationsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates an Agent Application (asynchronous). +// +// Creates or updates an Agent Application (asynchronous). +// If the operation fails it returns an *azcore.ResponseError type. +func (client *AgentApplicationsClient) createOrUpdate(ctx context.Context, resourceGroupName string, accountName string, projectName string, name string, body AgentApplication, options *AgentApplicationsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "AgentApplicationsClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, projectName, name, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *AgentApplicationsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, projectName string, name string, body AgentApplication, _ *AgentApplicationsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/projects/{projectName}/applications/{name}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if projectName == "" { + return nil, errors.New("parameter projectName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{projectName}", url.PathEscape(projectName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete Agent Application. +// +// Delete Agent Application. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - projectName - The name of Cognitive Services account's project. +// - name - Name for the Agent Application. +// - options - AgentApplicationsClientBeginDeleteOptions contains the optional parameters for the AgentApplicationsClient.BeginDelete +// method. +func (client *AgentApplicationsClient) BeginDelete(ctx context.Context, resourceGroupName string, accountName string, projectName string, name string, options *AgentApplicationsClientBeginDeleteOptions) (*runtime.Poller[AgentApplicationsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, accountName, projectName, name, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AgentApplicationsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AgentApplicationsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete Agent Application. +// +// Delete Agent Application. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *AgentApplicationsClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, projectName string, name string, options *AgentApplicationsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "AgentApplicationsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, projectName, name, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *AgentApplicationsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, projectName string, name string, _ *AgentApplicationsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/projects/{projectName}/applications/{name}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if projectName == "" { + return nil, errors.New("parameter projectName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{projectName}", url.PathEscape(projectName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Disable - Disables an Agent Application. +// +// Disables an Agent Application. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - projectName - The name of Cognitive Services account's project. +// - name - Name for the Agent Application. +// - options - AgentApplicationsClientDisableOptions contains the optional parameters for the AgentApplicationsClient.Disable +// method. +func (client *AgentApplicationsClient) Disable(ctx context.Context, resourceGroupName string, accountName string, projectName string, name string, options *AgentApplicationsClientDisableOptions) (AgentApplicationsClientDisableResponse, error) { + var err error + const operationName = "AgentApplicationsClient.Disable" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.disableCreateRequest(ctx, resourceGroupName, accountName, projectName, name, options) + if err != nil { + return AgentApplicationsClientDisableResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AgentApplicationsClientDisableResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AgentApplicationsClientDisableResponse{}, err + } + return AgentApplicationsClientDisableResponse{}, nil +} + +// disableCreateRequest creates the Disable request. +func (client *AgentApplicationsClient) disableCreateRequest(ctx context.Context, resourceGroupName string, accountName string, projectName string, name string, _ *AgentApplicationsClientDisableOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/projects/{projectName}/applications/{name}/disable" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if projectName == "" { + return nil, errors.New("parameter projectName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{projectName}", url.PathEscape(projectName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Enable - Enables an Agent Application. +// +// Enables an Agent Application. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - projectName - The name of Cognitive Services account's project. +// - name - Name for the Agent Application. +// - options - AgentApplicationsClientEnableOptions contains the optional parameters for the AgentApplicationsClient.Enable +// method. +func (client *AgentApplicationsClient) Enable(ctx context.Context, resourceGroupName string, accountName string, projectName string, name string, options *AgentApplicationsClientEnableOptions) (AgentApplicationsClientEnableResponse, error) { + var err error + const operationName = "AgentApplicationsClient.Enable" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.enableCreateRequest(ctx, resourceGroupName, accountName, projectName, name, options) + if err != nil { + return AgentApplicationsClientEnableResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AgentApplicationsClientEnableResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AgentApplicationsClientEnableResponse{}, err + } + return AgentApplicationsClientEnableResponse{}, nil +} + +// enableCreateRequest creates the Enable request. +func (client *AgentApplicationsClient) enableCreateRequest(ctx context.Context, resourceGroupName string, accountName string, projectName string, name string, _ *AgentApplicationsClientEnableOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/projects/{projectName}/applications/{name}/enable" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if projectName == "" { + return nil, errors.New("parameter projectName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{projectName}", url.PathEscape(projectName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Gets an Agent Application by name. +// +// Gets an Agent Application by name. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - projectName - The name of Cognitive Services account's project. +// - name - Name for the Agent Application. +// - options - AgentApplicationsClientGetOptions contains the optional parameters for the AgentApplicationsClient.Get method. +func (client *AgentApplicationsClient) Get(ctx context.Context, resourceGroupName string, accountName string, projectName string, name string, options *AgentApplicationsClientGetOptions) (AgentApplicationsClientGetResponse, error) { + var err error + const operationName = "AgentApplicationsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, projectName, name, options) + if err != nil { + return AgentApplicationsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AgentApplicationsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AgentApplicationsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *AgentApplicationsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, projectName string, name string, _ *AgentApplicationsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/projects/{projectName}/applications/{name}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if projectName == "" { + return nil, errors.New("parameter projectName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{projectName}", url.PathEscape(projectName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *AgentApplicationsClient) getHandleResponse(resp *http.Response) (AgentApplicationsClientGetResponse, error) { + result := AgentApplicationsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AgentApplication); err != nil { + return AgentApplicationsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists Agent Applications in the project. +// +// Lists Agent Applications in the project. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - projectName - The name of Cognitive Services account's project. +// - options - AgentApplicationsClientListOptions contains the optional parameters for the AgentApplicationsClient.NewListPager +// method. +func (client *AgentApplicationsClient) NewListPager(resourceGroupName string, accountName string, projectName string, options *AgentApplicationsClientListOptions) *runtime.Pager[AgentApplicationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[AgentApplicationsClientListResponse]{ + More: func(page AgentApplicationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AgentApplicationsClientListResponse) (AgentApplicationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AgentApplicationsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, projectName, options) + }, nil) + if err != nil { + return AgentApplicationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *AgentApplicationsClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, projectName string, options *AgentApplicationsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/projects/{projectName}/applications" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if projectName == "" { + return nil, errors.New("parameter projectName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{projectName}", url.PathEscape(projectName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Skip != nil { + reqQP.Set("$skip", strconv.FormatInt(int64(*options.Skip), 10)) + } + if options != nil && options.SkipToken != nil { + reqQP.Set("$skipToken", *options.SkipToken) + } + reqQP.Set("api-version", version20260501) + if options != nil && options.Count != nil { + reqQP.Set("count", strconv.FormatInt(int64(*options.Count), 10)) + } + if options != nil && options.Names != nil { + for _, qv := range options.Names { + reqQP.Add("names", qv) + } + } + if options != nil && options.OrderBy != nil { + reqQP.Set("orderBy", *options.OrderBy) + } + if options != nil && options.OrderByAsc != nil { + reqQP.Set("orderByAsc", strconv.FormatBool(*options.OrderByAsc)) + } + if options != nil && options.SearchText != nil { + reqQP.Set("searchText", *options.SearchText) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *AgentApplicationsClient) listHandleResponse(resp *http.Response) (AgentApplicationsClientListResponse, error) { + result := AgentApplicationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AgentApplicationResourceArmPaginatedResult); err != nil { + return AgentApplicationsClientListResponse{}, err + } + return result, nil +} + +// ListAgents - Lists agents for an Agent Application. +// +// Lists agents for an Agent Application. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - projectName - The name of Cognitive Services account's project. +// - name - Name for the Agent Application. +// - options - AgentApplicationsClientListAgentsOptions contains the optional parameters for the AgentApplicationsClient.ListAgents +// method. +func (client *AgentApplicationsClient) ListAgents(ctx context.Context, resourceGroupName string, accountName string, projectName string, name string, options *AgentApplicationsClientListAgentsOptions) (AgentApplicationsClientListAgentsResponse, error) { + var err error + const operationName = "AgentApplicationsClient.ListAgents" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listAgentsCreateRequest(ctx, resourceGroupName, accountName, projectName, name, options) + if err != nil { + return AgentApplicationsClientListAgentsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AgentApplicationsClientListAgentsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AgentApplicationsClientListAgentsResponse{}, err + } + resp, err := client.listAgentsHandleResponse(httpResp) + return resp, err +} + +// listAgentsCreateRequest creates the ListAgents request. +func (client *AgentApplicationsClient) listAgentsCreateRequest(ctx context.Context, resourceGroupName string, accountName string, projectName string, name string, _ *AgentApplicationsClientListAgentsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/projects/{projectName}/applications/{name}/listAgents" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if projectName == "" { + return nil, errors.New("parameter projectName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{projectName}", url.PathEscape(projectName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAgentsHandleResponse handles the ListAgents response. +func (client *AgentApplicationsClient) listAgentsHandleResponse(resp *http.Response) (AgentApplicationsClientListAgentsResponse, error) { + result := AgentApplicationsClientListAgentsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AgentReferenceResourceArmPaginatedResult); err != nil { + return AgentApplicationsClientListAgentsResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_agentdeployments_client.go b/test/local/armcognitiveservices/zz_agentdeployments_client.go new file mode 100644 index 000000000000..4681992a425a --- /dev/null +++ b/test/local/armcognitiveservices/zz_agentdeployments_client.go @@ -0,0 +1,536 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" +) + +// AgentDeploymentsClient contains the methods for the AgentDeployments group. +// Don't use this type directly, use NewAgentDeploymentsClient() instead. +// +// Generated from API version 2026-05-01 +type AgentDeploymentsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAgentDeploymentsClient creates a new instance of AgentDeploymentsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewAgentDeploymentsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AgentDeploymentsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AgentDeploymentsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates or updates an Agent Deployment (asynchronous). +// +// Creates or updates an Agent Deployment (asynchronous). +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - projectName - The name of Cognitive Services account's project. +// - appName - The name of the application associated with the Cognitive Services Account +// - deploymentName - The name of the deployment associated with the Cognitive Services Account +// - body - Agent Deployment definition object. +// - options - AgentDeploymentsClientBeginCreateOrUpdateOptions contains the optional parameters for the AgentDeploymentsClient.BeginCreateOrUpdate +// method. +func (client *AgentDeploymentsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, projectName string, appName string, deploymentName string, body AgentDeployment, options *AgentDeploymentsClientBeginCreateOrUpdateOptions) (*runtime.Poller[AgentDeploymentsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, accountName, projectName, appName, deploymentName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AgentDeploymentsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AgentDeploymentsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates or updates an Agent Deployment (asynchronous). +// +// Creates or updates an Agent Deployment (asynchronous). +// If the operation fails it returns an *azcore.ResponseError type. +func (client *AgentDeploymentsClient) createOrUpdate(ctx context.Context, resourceGroupName string, accountName string, projectName string, appName string, deploymentName string, body AgentDeployment, options *AgentDeploymentsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "AgentDeploymentsClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, projectName, appName, deploymentName, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *AgentDeploymentsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, projectName string, appName string, deploymentName string, body AgentDeployment, _ *AgentDeploymentsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/projects/{projectName}/applications/{appName}/agentDeployments/{deploymentName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if projectName == "" { + return nil, errors.New("parameter projectName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{projectName}", url.PathEscape(projectName)) + if appName == "" { + return nil, errors.New("parameter appName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{appName}", url.PathEscape(appName)) + if deploymentName == "" { + return nil, errors.New("parameter deploymentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{deploymentName}", url.PathEscape(deploymentName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete Agent Deployment. +// +// Delete Agent Deployment. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - projectName - The name of Cognitive Services account's project. +// - appName - The name of the application associated with the Cognitive Services Account +// - deploymentName - The name of the deployment associated with the Cognitive Services Account +// - options - AgentDeploymentsClientBeginDeleteOptions contains the optional parameters for the AgentDeploymentsClient.BeginDelete +// method. +func (client *AgentDeploymentsClient) BeginDelete(ctx context.Context, resourceGroupName string, accountName string, projectName string, appName string, deploymentName string, options *AgentDeploymentsClientBeginDeleteOptions) (*runtime.Poller[AgentDeploymentsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, accountName, projectName, appName, deploymentName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AgentDeploymentsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AgentDeploymentsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete Agent Deployment. +// +// Delete Agent Deployment. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *AgentDeploymentsClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, projectName string, appName string, deploymentName string, options *AgentDeploymentsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "AgentDeploymentsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, projectName, appName, deploymentName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *AgentDeploymentsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, projectName string, appName string, deploymentName string, _ *AgentDeploymentsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/projects/{projectName}/applications/{appName}/agentDeployments/{deploymentName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if projectName == "" { + return nil, errors.New("parameter projectName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{projectName}", url.PathEscape(projectName)) + if appName == "" { + return nil, errors.New("parameter appName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{appName}", url.PathEscape(appName)) + if deploymentName == "" { + return nil, errors.New("parameter deploymentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{deploymentName}", url.PathEscape(deploymentName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Gets an Agent Deployment by name. +// +// Gets an Agent Deployment by name. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - projectName - The name of Cognitive Services account's project. +// - appName - The name of the application associated with the Cognitive Services Account +// - deploymentName - The name of the deployment associated with the Cognitive Services Account +// - options - AgentDeploymentsClientGetOptions contains the optional parameters for the AgentDeploymentsClient.Get method. +func (client *AgentDeploymentsClient) Get(ctx context.Context, resourceGroupName string, accountName string, projectName string, appName string, deploymentName string, options *AgentDeploymentsClientGetOptions) (AgentDeploymentsClientGetResponse, error) { + var err error + const operationName = "AgentDeploymentsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, projectName, appName, deploymentName, options) + if err != nil { + return AgentDeploymentsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AgentDeploymentsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AgentDeploymentsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *AgentDeploymentsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, projectName string, appName string, deploymentName string, _ *AgentDeploymentsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/projects/{projectName}/applications/{appName}/agentDeployments/{deploymentName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if projectName == "" { + return nil, errors.New("parameter projectName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{projectName}", url.PathEscape(projectName)) + if appName == "" { + return nil, errors.New("parameter appName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{appName}", url.PathEscape(appName)) + if deploymentName == "" { + return nil, errors.New("parameter deploymentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{deploymentName}", url.PathEscape(deploymentName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *AgentDeploymentsClient) getHandleResponse(resp *http.Response) (AgentDeploymentsClientGetResponse, error) { + result := AgentDeploymentsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AgentDeployment); err != nil { + return AgentDeploymentsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists Agent Deployments in the application. +// +// Lists Agent Deployments in the application. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - projectName - The name of Cognitive Services account's project. +// - appName - The name of the application associated with the Cognitive Services Account +// - options - AgentDeploymentsClientListOptions contains the optional parameters for the AgentDeploymentsClient.NewListPager +// method. +func (client *AgentDeploymentsClient) NewListPager(resourceGroupName string, accountName string, projectName string, appName string, options *AgentDeploymentsClientListOptions) *runtime.Pager[AgentDeploymentsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[AgentDeploymentsClientListResponse]{ + More: func(page AgentDeploymentsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AgentDeploymentsClientListResponse) (AgentDeploymentsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AgentDeploymentsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, projectName, appName, options) + }, nil) + if err != nil { + return AgentDeploymentsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *AgentDeploymentsClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, projectName string, appName string, options *AgentDeploymentsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/projects/{projectName}/applications/{appName}/agentDeployments" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if projectName == "" { + return nil, errors.New("parameter projectName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{projectName}", url.PathEscape(projectName)) + if appName == "" { + return nil, errors.New("parameter appName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{appName}", url.PathEscape(appName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.SkipToken != nil { + reqQP.Set("$skipToken", *options.SkipToken) + } + reqQP.Set("api-version", version20260501) + if options != nil && options.Count != nil { + reqQP.Set("count", strconv.FormatInt(int64(*options.Count), 10)) + } + if options != nil && options.Names != nil { + for _, qv := range options.Names { + reqQP.Add("names", qv) + } + } + if options != nil && options.OrderBy != nil { + reqQP.Set("orderBy", *options.OrderBy) + } + if options != nil && options.OrderByAsc != nil { + reqQP.Set("orderByAsc", strconv.FormatBool(*options.OrderByAsc)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *AgentDeploymentsClient) listHandleResponse(resp *http.Response) (AgentDeploymentsClientListResponse, error) { + result := AgentDeploymentsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AgentDeploymentResourceArmPaginatedResult); err != nil { + return AgentDeploymentsClientListResponse{}, err + } + return result, nil +} + +// Start - Starts an Agent Deployment. +// +// Starts an Agent Deployment. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - projectName - The name of Cognitive Services account's project. +// - appName - The name of the application associated with the Cognitive Services Account +// - deploymentName - The name of the deployment associated with the Cognitive Services Account +// - options - AgentDeploymentsClientStartOptions contains the optional parameters for the AgentDeploymentsClient.Start method. +func (client *AgentDeploymentsClient) Start(ctx context.Context, resourceGroupName string, accountName string, projectName string, appName string, deploymentName string, options *AgentDeploymentsClientStartOptions) (AgentDeploymentsClientStartResponse, error) { + var err error + const operationName = "AgentDeploymentsClient.Start" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.startCreateRequest(ctx, resourceGroupName, accountName, projectName, appName, deploymentName, options) + if err != nil { + return AgentDeploymentsClientStartResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AgentDeploymentsClientStartResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AgentDeploymentsClientStartResponse{}, err + } + return AgentDeploymentsClientStartResponse{}, nil +} + +// startCreateRequest creates the Start request. +func (client *AgentDeploymentsClient) startCreateRequest(ctx context.Context, resourceGroupName string, accountName string, projectName string, appName string, deploymentName string, _ *AgentDeploymentsClientStartOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/projects/{projectName}/applications/{appName}/agentDeployments/{deploymentName}/start" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if projectName == "" { + return nil, errors.New("parameter projectName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{projectName}", url.PathEscape(projectName)) + if appName == "" { + return nil, errors.New("parameter appName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{appName}", url.PathEscape(appName)) + if deploymentName == "" { + return nil, errors.New("parameter deploymentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{deploymentName}", url.PathEscape(deploymentName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Stop - Stops an Agent Deployment. +// +// Stops an Agent Deployment. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - projectName - The name of Cognitive Services account's project. +// - appName - The name of the application associated with the Cognitive Services Account +// - deploymentName - The name of the deployment associated with the Cognitive Services Account +// - options - AgentDeploymentsClientStopOptions contains the optional parameters for the AgentDeploymentsClient.Stop method. +func (client *AgentDeploymentsClient) Stop(ctx context.Context, resourceGroupName string, accountName string, projectName string, appName string, deploymentName string, options *AgentDeploymentsClientStopOptions) (AgentDeploymentsClientStopResponse, error) { + var err error + const operationName = "AgentDeploymentsClient.Stop" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.stopCreateRequest(ctx, resourceGroupName, accountName, projectName, appName, deploymentName, options) + if err != nil { + return AgentDeploymentsClientStopResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AgentDeploymentsClientStopResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AgentDeploymentsClientStopResponse{}, err + } + return AgentDeploymentsClientStopResponse{}, nil +} + +// stopCreateRequest creates the Stop request. +func (client *AgentDeploymentsClient) stopCreateRequest(ctx context.Context, resourceGroupName string, accountName string, projectName string, appName string, deploymentName string, _ *AgentDeploymentsClientStopOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/projects/{projectName}/applications/{appName}/agentDeployments/{deploymentName}/stop" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if projectName == "" { + return nil, errors.New("parameter projectName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{projectName}", url.PathEscape(projectName)) + if appName == "" { + return nil, errors.New("parameter appName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{appName}", url.PathEscape(appName)) + if deploymentName == "" { + return nil, errors.New("parameter deploymentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{deploymentName}", url.PathEscape(deploymentName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/local/armcognitiveservices/zz_client_factory.go b/test/local/armcognitiveservices/zz_client_factory.go new file mode 100644 index 000000000000..e144ad61e910 --- /dev/null +++ b/test/local/armcognitiveservices/zz_client_factory.go @@ -0,0 +1,344 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + subscriptionID string + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, + internal: internal, + }, nil +} + +// NewAccountCapabilityHostsClient creates a new instance of AccountCapabilityHostsClient. +func (c *ClientFactory) NewAccountCapabilityHostsClient() *AccountCapabilityHostsClient { + return &AccountCapabilityHostsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewAccountConnectionsClient creates a new instance of AccountConnectionsClient. +func (c *ClientFactory) NewAccountConnectionsClient() *AccountConnectionsClient { + return &AccountConnectionsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewAccountsClient creates a new instance of AccountsClient. +func (c *ClientFactory) NewAccountsClient() *AccountsClient { + return &AccountsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewAgentApplicationsClient creates a new instance of AgentApplicationsClient. +func (c *ClientFactory) NewAgentApplicationsClient() *AgentApplicationsClient { + return &AgentApplicationsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewAgentDeploymentsClient creates a new instance of AgentDeploymentsClient. +func (c *ClientFactory) NewAgentDeploymentsClient() *AgentDeploymentsClient { + return &AgentDeploymentsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewCommitmentPlansClient creates a new instance of CommitmentPlansClient. +func (c *ClientFactory) NewCommitmentPlansClient() *CommitmentPlansClient { + return &CommitmentPlansClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewCommitmentTiersClient creates a new instance of CommitmentTiersClient. +func (c *ClientFactory) NewCommitmentTiersClient() *CommitmentTiersClient { + return &CommitmentTiersClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewDefenderForAISettingsClient creates a new instance of DefenderForAISettingsClient. +func (c *ClientFactory) NewDefenderForAISettingsClient() *DefenderForAISettingsClient { + return &DefenderForAISettingsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewDeletedAccountsClient creates a new instance of DeletedAccountsClient. +func (c *ClientFactory) NewDeletedAccountsClient() *DeletedAccountsClient { + return &DeletedAccountsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewDeploymentsClient creates a new instance of DeploymentsClient. +func (c *ClientFactory) NewDeploymentsClient() *DeploymentsClient { + return &DeploymentsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewEncryptionScopesClient creates a new instance of EncryptionScopesClient. +func (c *ClientFactory) NewEncryptionScopesClient() *EncryptionScopesClient { + return &EncryptionScopesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewLocationBasedModelCapacitiesClient creates a new instance of LocationBasedModelCapacitiesClient. +func (c *ClientFactory) NewLocationBasedModelCapacitiesClient() *LocationBasedModelCapacitiesClient { + return &LocationBasedModelCapacitiesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewManagedNetworkProvisionsClient creates a new instance of ManagedNetworkProvisionsClient. +func (c *ClientFactory) NewManagedNetworkProvisionsClient() *ManagedNetworkProvisionsClient { + return &ManagedNetworkProvisionsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewManagedNetworkSettingsClient creates a new instance of ManagedNetworkSettingsClient. +func (c *ClientFactory) NewManagedNetworkSettingsClient() *ManagedNetworkSettingsClient { + return &ManagedNetworkSettingsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewManagementClient creates a new instance of ManagementClient. +func (c *ClientFactory) NewManagementClient() *ManagementClient { + return &ManagementClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewModelCapacitiesClient creates a new instance of ModelCapacitiesClient. +func (c *ClientFactory) NewModelCapacitiesClient() *ModelCapacitiesClient { + return &ModelCapacitiesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewModelsClient creates a new instance of ModelsClient. +func (c *ClientFactory) NewModelsClient() *ModelsClient { + return &ModelsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewNetworkSecurityPerimeterConfigurationsClient creates a new instance of NetworkSecurityPerimeterConfigurationsClient. +func (c *ClientFactory) NewNetworkSecurityPerimeterConfigurationsClient() *NetworkSecurityPerimeterConfigurationsClient { + return &NetworkSecurityPerimeterConfigurationsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: c.internal, + } +} + +// NewOutboundRuleClient creates a new instance of OutboundRuleClient. +func (c *ClientFactory) NewOutboundRuleClient() *OutboundRuleClient { + return &OutboundRuleClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewOutboundRulesClient creates a new instance of OutboundRulesClient. +func (c *ClientFactory) NewOutboundRulesClient() *OutboundRulesClient { + return &OutboundRulesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewPrivateEndpointConnectionsClient creates a new instance of PrivateEndpointConnectionsClient. +func (c *ClientFactory) NewPrivateEndpointConnectionsClient() *PrivateEndpointConnectionsClient { + return &PrivateEndpointConnectionsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewPrivateLinkResourcesClient creates a new instance of PrivateLinkResourcesClient. +func (c *ClientFactory) NewPrivateLinkResourcesClient() *PrivateLinkResourcesClient { + return &PrivateLinkResourcesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewProjectCapabilityHostsClient creates a new instance of ProjectCapabilityHostsClient. +func (c *ClientFactory) NewProjectCapabilityHostsClient() *ProjectCapabilityHostsClient { + return &ProjectCapabilityHostsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewProjectConnectionsClient creates a new instance of ProjectConnectionsClient. +func (c *ClientFactory) NewProjectConnectionsClient() *ProjectConnectionsClient { + return &ProjectConnectionsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewProjectsClient creates a new instance of ProjectsClient. +func (c *ClientFactory) NewProjectsClient() *ProjectsClient { + return &ProjectsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewQuotaTiersClient creates a new instance of QuotaTiersClient. +func (c *ClientFactory) NewQuotaTiersClient() *QuotaTiersClient { + return &QuotaTiersClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewRaiBlocklistItemsClient creates a new instance of RaiBlocklistItemsClient. +func (c *ClientFactory) NewRaiBlocklistItemsClient() *RaiBlocklistItemsClient { + return &RaiBlocklistItemsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewRaiBlocklistsClient creates a new instance of RaiBlocklistsClient. +func (c *ClientFactory) NewRaiBlocklistsClient() *RaiBlocklistsClient { + return &RaiBlocklistsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewRaiContentFiltersClient creates a new instance of RaiContentFiltersClient. +func (c *ClientFactory) NewRaiContentFiltersClient() *RaiContentFiltersClient { + return &RaiContentFiltersClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewRaiExternalSafetyProviderClient creates a new instance of RaiExternalSafetyProviderClient. +func (c *ClientFactory) NewRaiExternalSafetyProviderClient() *RaiExternalSafetyProviderClient { + return &RaiExternalSafetyProviderClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewRaiExternalSafetyProvidersClient creates a new instance of RaiExternalSafetyProvidersClient. +func (c *ClientFactory) NewRaiExternalSafetyProvidersClient() *RaiExternalSafetyProvidersClient { + return &RaiExternalSafetyProvidersClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewRaiPoliciesClient creates a new instance of RaiPoliciesClient. +func (c *ClientFactory) NewRaiPoliciesClient() *RaiPoliciesClient { + return &RaiPoliciesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewRaiToolLabelsClient creates a new instance of RaiToolLabelsClient. +func (c *ClientFactory) NewRaiToolLabelsClient() *RaiToolLabelsClient { + return &RaiToolLabelsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewRaiTopicsClient creates a new instance of RaiTopicsClient. +func (c *ClientFactory) NewRaiTopicsClient() *RaiTopicsClient { + return &RaiTopicsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewResourceSKUsClient creates a new instance of ResourceSKUsClient. +func (c *ClientFactory) NewResourceSKUsClient() *ResourceSKUsClient { + return &ResourceSKUsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewSubscriptionRaiPolicyClient creates a new instance of SubscriptionRaiPolicyClient. +func (c *ClientFactory) NewSubscriptionRaiPolicyClient() *SubscriptionRaiPolicyClient { + return &SubscriptionRaiPolicyClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewTestRaiExternalSafetyProviderClient creates a new instance of TestRaiExternalSafetyProviderClient. +func (c *ClientFactory) NewTestRaiExternalSafetyProviderClient() *TestRaiExternalSafetyProviderClient { + return &TestRaiExternalSafetyProviderClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewUsagesClient creates a new instance of UsagesClient. +func (c *ClientFactory) NewUsagesClient() *UsagesClient { + return &UsagesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} diff --git a/test/local/armcognitiveservices/zz_commitmentplans_client.go b/test/local/armcognitiveservices/zz_commitmentplans_client.go new file mode 100644 index 000000000000..587b29fa494d --- /dev/null +++ b/test/local/armcognitiveservices/zz_commitmentplans_client.go @@ -0,0 +1,1008 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// CommitmentPlansClient contains the methods for the CommitmentPlans group. +// Don't use this type directly, use NewCommitmentPlansClient() instead. +// +// Generated from API version 2026-05-01 +type CommitmentPlansClient struct { + internal *arm.Client + subscriptionID string +} + +// NewCommitmentPlansClient creates a new instance of CommitmentPlansClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewCommitmentPlansClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CommitmentPlansClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CommitmentPlansClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Update the state of specified commitmentPlans associated with the Cognitive Services account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - commitmentPlanName - The name of the commitmentPlan associated with the Cognitive Services Account +// - commitmentPlan - The commitmentPlan properties. +// - options - CommitmentPlansClientCreateOrUpdateOptions contains the optional parameters for the CommitmentPlansClient.CreateOrUpdate +// method. +func (client *CommitmentPlansClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, commitmentPlanName string, commitmentPlan CommitmentPlan, options *CommitmentPlansClientCreateOrUpdateOptions) (CommitmentPlansClientCreateOrUpdateResponse, error) { + var err error + const operationName = "CommitmentPlansClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, commitmentPlanName, commitmentPlan, options) + if err != nil { + return CommitmentPlansClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CommitmentPlansClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return CommitmentPlansClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *CommitmentPlansClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, commitmentPlanName string, commitmentPlan CommitmentPlan, _ *CommitmentPlansClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/commitmentPlans/{commitmentPlanName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if commitmentPlanName == "" { + return nil, errors.New("parameter commitmentPlanName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{commitmentPlanName}", url.PathEscape(commitmentPlanName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, commitmentPlan); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *CommitmentPlansClient) createOrUpdateHandleResponse(resp *http.Response) (CommitmentPlansClientCreateOrUpdateResponse, error) { + result := CommitmentPlansClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CommitmentPlan); err != nil { + return CommitmentPlansClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// BeginCreateOrUpdateAssociation - Create or update the association of the Cognitive Services commitment plan. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - commitmentPlanName - The name of the commitmentPlan associated with the Cognitive Services Account +// - commitmentPlanAssociationName - The name of the commitment plan association with the Cognitive Services Account +// - association - The commitmentPlan properties. +// - options - CommitmentPlansClientBeginCreateOrUpdateAssociationOptions contains the optional parameters for the CommitmentPlansClient.BeginCreateOrUpdateAssociation +// method. +func (client *CommitmentPlansClient) BeginCreateOrUpdateAssociation(ctx context.Context, resourceGroupName string, commitmentPlanName string, commitmentPlanAssociationName string, association CommitmentPlanAccountAssociation, options *CommitmentPlansClientBeginCreateOrUpdateAssociationOptions) (*runtime.Poller[CommitmentPlansClientCreateOrUpdateAssociationResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdateAssociation(ctx, resourceGroupName, commitmentPlanName, commitmentPlanAssociationName, association, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CommitmentPlansClientCreateOrUpdateAssociationResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CommitmentPlansClientCreateOrUpdateAssociationResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdateAssociation - Create or update the association of the Cognitive Services commitment plan. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CommitmentPlansClient) createOrUpdateAssociation(ctx context.Context, resourceGroupName string, commitmentPlanName string, commitmentPlanAssociationName string, association CommitmentPlanAccountAssociation, options *CommitmentPlansClientBeginCreateOrUpdateAssociationOptions) (*http.Response, error) { + var err error + const operationName = "CommitmentPlansClient.BeginCreateOrUpdateAssociation" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateAssociationCreateRequest(ctx, resourceGroupName, commitmentPlanName, commitmentPlanAssociationName, association, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateAssociationCreateRequest creates the CreateOrUpdateAssociation request. +func (client *CommitmentPlansClient) createOrUpdateAssociationCreateRequest(ctx context.Context, resourceGroupName string, commitmentPlanName string, commitmentPlanAssociationName string, association CommitmentPlanAccountAssociation, _ *CommitmentPlansClientBeginCreateOrUpdateAssociationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}/accountAssociations/{commitmentPlanAssociationName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if commitmentPlanName == "" { + return nil, errors.New("parameter commitmentPlanName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{commitmentPlanName}", url.PathEscape(commitmentPlanName)) + if commitmentPlanAssociationName == "" { + return nil, errors.New("parameter commitmentPlanAssociationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{commitmentPlanAssociationName}", url.PathEscape(commitmentPlanAssociationName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, association); err != nil { + return nil, err + } + return req, nil +} + +// BeginCreateOrUpdatePlan - Create Cognitive Services commitment plan. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - commitmentPlanName - The name of the commitmentPlan associated with the Cognitive Services Account +// - commitmentPlan - The parameters to provide for the created commitment plan. +// - options - CommitmentPlansClientBeginCreateOrUpdatePlanOptions contains the optional parameters for the CommitmentPlansClient.BeginCreateOrUpdatePlan +// method. +func (client *CommitmentPlansClient) BeginCreateOrUpdatePlan(ctx context.Context, resourceGroupName string, commitmentPlanName string, commitmentPlan CommitmentPlan, options *CommitmentPlansClientBeginCreateOrUpdatePlanOptions) (*runtime.Poller[CommitmentPlansClientCreateOrUpdatePlanResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdatePlan(ctx, resourceGroupName, commitmentPlanName, commitmentPlan, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CommitmentPlansClientCreateOrUpdatePlanResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CommitmentPlansClientCreateOrUpdatePlanResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdatePlan - Create Cognitive Services commitment plan. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CommitmentPlansClient) createOrUpdatePlan(ctx context.Context, resourceGroupName string, commitmentPlanName string, commitmentPlan CommitmentPlan, options *CommitmentPlansClientBeginCreateOrUpdatePlanOptions) (*http.Response, error) { + var err error + const operationName = "CommitmentPlansClient.BeginCreateOrUpdatePlan" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdatePlanCreateRequest(ctx, resourceGroupName, commitmentPlanName, commitmentPlan, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdatePlanCreateRequest creates the CreateOrUpdatePlan request. +func (client *CommitmentPlansClient) createOrUpdatePlanCreateRequest(ctx context.Context, resourceGroupName string, commitmentPlanName string, commitmentPlan CommitmentPlan, _ *CommitmentPlansClientBeginCreateOrUpdatePlanOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if commitmentPlanName == "" { + return nil, errors.New("parameter commitmentPlanName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{commitmentPlanName}", url.PathEscape(commitmentPlanName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, commitmentPlan); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes the specified commitmentPlan associated with the Cognitive Services account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - commitmentPlanName - The name of the commitmentPlan associated with the Cognitive Services Account +// - options - CommitmentPlansClientBeginDeleteOptions contains the optional parameters for the CommitmentPlansClient.BeginDelete +// method. +func (client *CommitmentPlansClient) BeginDelete(ctx context.Context, resourceGroupName string, accountName string, commitmentPlanName string, options *CommitmentPlansClientBeginDeleteOptions) (*runtime.Poller[CommitmentPlansClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, accountName, commitmentPlanName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CommitmentPlansClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CommitmentPlansClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified commitmentPlan associated with the Cognitive Services account. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CommitmentPlansClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, commitmentPlanName string, options *CommitmentPlansClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "CommitmentPlansClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, commitmentPlanName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *CommitmentPlansClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, commitmentPlanName string, _ *CommitmentPlansClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/commitmentPlans/{commitmentPlanName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if commitmentPlanName == "" { + return nil, errors.New("parameter commitmentPlanName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{commitmentPlanName}", url.PathEscape(commitmentPlanName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// BeginDeleteAssociation - Deletes the association of the Cognitive Services commitment plan. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - commitmentPlanName - The name of the commitmentPlan associated with the Cognitive Services Account +// - commitmentPlanAssociationName - The name of the commitment plan association with the Cognitive Services Account +// - options - CommitmentPlansClientBeginDeleteAssociationOptions contains the optional parameters for the CommitmentPlansClient.BeginDeleteAssociation +// method. +func (client *CommitmentPlansClient) BeginDeleteAssociation(ctx context.Context, resourceGroupName string, commitmentPlanName string, commitmentPlanAssociationName string, options *CommitmentPlansClientBeginDeleteAssociationOptions) (*runtime.Poller[CommitmentPlansClientDeleteAssociationResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteAssociation(ctx, resourceGroupName, commitmentPlanName, commitmentPlanAssociationName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CommitmentPlansClientDeleteAssociationResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CommitmentPlansClientDeleteAssociationResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// DeleteAssociation - Deletes the association of the Cognitive Services commitment plan. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CommitmentPlansClient) deleteAssociation(ctx context.Context, resourceGroupName string, commitmentPlanName string, commitmentPlanAssociationName string, options *CommitmentPlansClientBeginDeleteAssociationOptions) (*http.Response, error) { + var err error + const operationName = "CommitmentPlansClient.BeginDeleteAssociation" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteAssociationCreateRequest(ctx, resourceGroupName, commitmentPlanName, commitmentPlanAssociationName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteAssociationCreateRequest creates the DeleteAssociation request. +func (client *CommitmentPlansClient) deleteAssociationCreateRequest(ctx context.Context, resourceGroupName string, commitmentPlanName string, commitmentPlanAssociationName string, _ *CommitmentPlansClientBeginDeleteAssociationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}/accountAssociations/{commitmentPlanAssociationName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if commitmentPlanName == "" { + return nil, errors.New("parameter commitmentPlanName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{commitmentPlanName}", url.PathEscape(commitmentPlanName)) + if commitmentPlanAssociationName == "" { + return nil, errors.New("parameter commitmentPlanAssociationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{commitmentPlanAssociationName}", url.PathEscape(commitmentPlanAssociationName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// BeginDeletePlan - Deletes a Cognitive Services commitment plan from the resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - commitmentPlanName - The name of the commitmentPlan associated with the Cognitive Services Account +// - options - CommitmentPlansClientBeginDeletePlanOptions contains the optional parameters for the CommitmentPlansClient.BeginDeletePlan +// method. +func (client *CommitmentPlansClient) BeginDeletePlan(ctx context.Context, resourceGroupName string, commitmentPlanName string, options *CommitmentPlansClientBeginDeletePlanOptions) (*runtime.Poller[CommitmentPlansClientDeletePlanResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deletePlan(ctx, resourceGroupName, commitmentPlanName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CommitmentPlansClientDeletePlanResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CommitmentPlansClientDeletePlanResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// DeletePlan - Deletes a Cognitive Services commitment plan from the resource group. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CommitmentPlansClient) deletePlan(ctx context.Context, resourceGroupName string, commitmentPlanName string, options *CommitmentPlansClientBeginDeletePlanOptions) (*http.Response, error) { + var err error + const operationName = "CommitmentPlansClient.BeginDeletePlan" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deletePlanCreateRequest(ctx, resourceGroupName, commitmentPlanName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deletePlanCreateRequest creates the DeletePlan request. +func (client *CommitmentPlansClient) deletePlanCreateRequest(ctx context.Context, resourceGroupName string, commitmentPlanName string, _ *CommitmentPlansClientBeginDeletePlanOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if commitmentPlanName == "" { + return nil, errors.New("parameter commitmentPlanName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{commitmentPlanName}", url.PathEscape(commitmentPlanName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Gets the specified commitmentPlans associated with the Cognitive Services account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - commitmentPlanName - The name of the commitmentPlan associated with the Cognitive Services Account +// - options - CommitmentPlansClientGetOptions contains the optional parameters for the CommitmentPlansClient.Get method. +func (client *CommitmentPlansClient) Get(ctx context.Context, resourceGroupName string, accountName string, commitmentPlanName string, options *CommitmentPlansClientGetOptions) (CommitmentPlansClientGetResponse, error) { + var err error + const operationName = "CommitmentPlansClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, commitmentPlanName, options) + if err != nil { + return CommitmentPlansClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CommitmentPlansClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CommitmentPlansClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *CommitmentPlansClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, commitmentPlanName string, _ *CommitmentPlansClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/commitmentPlans/{commitmentPlanName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if commitmentPlanName == "" { + return nil, errors.New("parameter commitmentPlanName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{commitmentPlanName}", url.PathEscape(commitmentPlanName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *CommitmentPlansClient) getHandleResponse(resp *http.Response) (CommitmentPlansClientGetResponse, error) { + result := CommitmentPlansClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CommitmentPlan); err != nil { + return CommitmentPlansClientGetResponse{}, err + } + return result, nil +} + +// GetAssociation - Gets the association of the Cognitive Services commitment plan. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - commitmentPlanName - The name of the commitmentPlan associated with the Cognitive Services Account +// - commitmentPlanAssociationName - The name of the commitment plan association with the Cognitive Services Account +// - options - CommitmentPlansClientGetAssociationOptions contains the optional parameters for the CommitmentPlansClient.GetAssociation +// method. +func (client *CommitmentPlansClient) GetAssociation(ctx context.Context, resourceGroupName string, commitmentPlanName string, commitmentPlanAssociationName string, options *CommitmentPlansClientGetAssociationOptions) (CommitmentPlansClientGetAssociationResponse, error) { + var err error + const operationName = "CommitmentPlansClient.GetAssociation" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getAssociationCreateRequest(ctx, resourceGroupName, commitmentPlanName, commitmentPlanAssociationName, options) + if err != nil { + return CommitmentPlansClientGetAssociationResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CommitmentPlansClientGetAssociationResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CommitmentPlansClientGetAssociationResponse{}, err + } + resp, err := client.getAssociationHandleResponse(httpResp) + return resp, err +} + +// getAssociationCreateRequest creates the GetAssociation request. +func (client *CommitmentPlansClient) getAssociationCreateRequest(ctx context.Context, resourceGroupName string, commitmentPlanName string, commitmentPlanAssociationName string, _ *CommitmentPlansClientGetAssociationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}/accountAssociations/{commitmentPlanAssociationName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if commitmentPlanName == "" { + return nil, errors.New("parameter commitmentPlanName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{commitmentPlanName}", url.PathEscape(commitmentPlanName)) + if commitmentPlanAssociationName == "" { + return nil, errors.New("parameter commitmentPlanAssociationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{commitmentPlanAssociationName}", url.PathEscape(commitmentPlanAssociationName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getAssociationHandleResponse handles the GetAssociation response. +func (client *CommitmentPlansClient) getAssociationHandleResponse(resp *http.Response) (CommitmentPlansClientGetAssociationResponse, error) { + result := CommitmentPlansClientGetAssociationResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CommitmentPlanAccountAssociation); err != nil { + return CommitmentPlansClientGetAssociationResponse{}, err + } + return result, nil +} + +// GetPlan - Returns a Cognitive Services commitment plan specified by the parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - commitmentPlanName - The name of the commitmentPlan associated with the Cognitive Services Account +// - options - CommitmentPlansClientGetPlanOptions contains the optional parameters for the CommitmentPlansClient.GetPlan method. +func (client *CommitmentPlansClient) GetPlan(ctx context.Context, resourceGroupName string, commitmentPlanName string, options *CommitmentPlansClientGetPlanOptions) (CommitmentPlansClientGetPlanResponse, error) { + var err error + const operationName = "CommitmentPlansClient.GetPlan" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getPlanCreateRequest(ctx, resourceGroupName, commitmentPlanName, options) + if err != nil { + return CommitmentPlansClientGetPlanResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CommitmentPlansClientGetPlanResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CommitmentPlansClientGetPlanResponse{}, err + } + resp, err := client.getPlanHandleResponse(httpResp) + return resp, err +} + +// getPlanCreateRequest creates the GetPlan request. +func (client *CommitmentPlansClient) getPlanCreateRequest(ctx context.Context, resourceGroupName string, commitmentPlanName string, _ *CommitmentPlansClientGetPlanOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if commitmentPlanName == "" { + return nil, errors.New("parameter commitmentPlanName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{commitmentPlanName}", url.PathEscape(commitmentPlanName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getPlanHandleResponse handles the GetPlan response. +func (client *CommitmentPlansClient) getPlanHandleResponse(resp *http.Response) (CommitmentPlansClientGetPlanResponse, error) { + result := CommitmentPlansClientGetPlanResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CommitmentPlan); err != nil { + return CommitmentPlansClientGetPlanResponse{}, err + } + return result, nil +} + +// NewListPager - Gets the commitmentPlans associated with the Cognitive Services account. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - options - CommitmentPlansClientListOptions contains the optional parameters for the CommitmentPlansClient.NewListPager +// method. +func (client *CommitmentPlansClient) NewListPager(resourceGroupName string, accountName string, options *CommitmentPlansClientListOptions) *runtime.Pager[CommitmentPlansClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[CommitmentPlansClientListResponse]{ + More: func(page CommitmentPlansClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CommitmentPlansClientListResponse) (CommitmentPlansClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CommitmentPlansClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, options) + }, nil) + if err != nil { + return CommitmentPlansClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *CommitmentPlansClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, _ *CommitmentPlansClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/commitmentPlans" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *CommitmentPlansClient) listHandleResponse(resp *http.Response) (CommitmentPlansClientListResponse, error) { + result := CommitmentPlansClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CommitmentPlanListResult); err != nil { + return CommitmentPlansClientListResponse{}, err + } + return result, nil +} + +// NewListAssociationsPager - Gets the associations of the Cognitive Services commitment plan. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - commitmentPlanName - The name of the commitmentPlan associated with the Cognitive Services Account +// - options - CommitmentPlansClientListAssociationsOptions contains the optional parameters for the CommitmentPlansClient.NewListAssociationsPager +// method. +func (client *CommitmentPlansClient) NewListAssociationsPager(resourceGroupName string, commitmentPlanName string, options *CommitmentPlansClientListAssociationsOptions) *runtime.Pager[CommitmentPlansClientListAssociationsResponse] { + return runtime.NewPager(runtime.PagingHandler[CommitmentPlansClientListAssociationsResponse]{ + More: func(page CommitmentPlansClientListAssociationsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CommitmentPlansClientListAssociationsResponse) (CommitmentPlansClientListAssociationsResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CommitmentPlansClient.NewListAssociationsPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listAssociationsCreateRequest(ctx, resourceGroupName, commitmentPlanName, options) + }, nil) + if err != nil { + return CommitmentPlansClientListAssociationsResponse{}, err + } + return client.listAssociationsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAssociationsCreateRequest creates the ListAssociations request. +func (client *CommitmentPlansClient) listAssociationsCreateRequest(ctx context.Context, resourceGroupName string, commitmentPlanName string, _ *CommitmentPlansClientListAssociationsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}/accountAssociations" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if commitmentPlanName == "" { + return nil, errors.New("parameter commitmentPlanName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{commitmentPlanName}", url.PathEscape(commitmentPlanName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAssociationsHandleResponse handles the ListAssociations response. +func (client *CommitmentPlansClient) listAssociationsHandleResponse(resp *http.Response) (CommitmentPlansClientListAssociationsResponse, error) { + result := CommitmentPlansClientListAssociationsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CommitmentPlanAccountAssociationListResult); err != nil { + return CommitmentPlansClientListAssociationsResponse{}, err + } + return result, nil +} + +// NewListPlansByResourceGroupPager - Returns all the resources of a particular type belonging to a resource group +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - CommitmentPlansClientListPlansByResourceGroupOptions contains the optional parameters for the CommitmentPlansClient.NewListPlansByResourceGroupPager +// method. +func (client *CommitmentPlansClient) NewListPlansByResourceGroupPager(resourceGroupName string, options *CommitmentPlansClientListPlansByResourceGroupOptions) *runtime.Pager[CommitmentPlansClientListPlansByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[CommitmentPlansClientListPlansByResourceGroupResponse]{ + More: func(page CommitmentPlansClientListPlansByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CommitmentPlansClientListPlansByResourceGroupResponse) (CommitmentPlansClientListPlansByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CommitmentPlansClient.NewListPlansByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listPlansByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return CommitmentPlansClientListPlansByResourceGroupResponse{}, err + } + return client.listPlansByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listPlansByResourceGroupCreateRequest creates the ListPlansByResourceGroup request. +func (client *CommitmentPlansClient) listPlansByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *CommitmentPlansClientListPlansByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listPlansByResourceGroupHandleResponse handles the ListPlansByResourceGroup response. +func (client *CommitmentPlansClient) listPlansByResourceGroupHandleResponse(resp *http.Response) (CommitmentPlansClientListPlansByResourceGroupResponse, error) { + result := CommitmentPlansClientListPlansByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CommitmentPlanListResult); err != nil { + return CommitmentPlansClientListPlansByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListPlansBySubscriptionPager - Returns all the resources of a particular type belonging to a subscription. +// - options - CommitmentPlansClientListPlansBySubscriptionOptions contains the optional parameters for the CommitmentPlansClient.NewListPlansBySubscriptionPager +// method. +func (client *CommitmentPlansClient) NewListPlansBySubscriptionPager(options *CommitmentPlansClientListPlansBySubscriptionOptions) *runtime.Pager[CommitmentPlansClientListPlansBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[CommitmentPlansClientListPlansBySubscriptionResponse]{ + More: func(page CommitmentPlansClientListPlansBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CommitmentPlansClientListPlansBySubscriptionResponse) (CommitmentPlansClientListPlansBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CommitmentPlansClient.NewListPlansBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listPlansBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return CommitmentPlansClientListPlansBySubscriptionResponse{}, err + } + return client.listPlansBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listPlansBySubscriptionCreateRequest creates the ListPlansBySubscription request. +func (client *CommitmentPlansClient) listPlansBySubscriptionCreateRequest(ctx context.Context, _ *CommitmentPlansClientListPlansBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/commitmentPlans" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listPlansBySubscriptionHandleResponse handles the ListPlansBySubscription response. +func (client *CommitmentPlansClient) listPlansBySubscriptionHandleResponse(resp *http.Response) (CommitmentPlansClientListPlansBySubscriptionResponse, error) { + result := CommitmentPlansClientListPlansBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CommitmentPlanListResult); err != nil { + return CommitmentPlansClientListPlansBySubscriptionResponse{}, err + } + return result, nil +} + +// BeginUpdatePlan - Create Cognitive Services commitment plan. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - commitmentPlanName - The name of the commitmentPlan associated with the Cognitive Services Account +// - commitmentPlan - The parameters to provide for the created commitment plan. +// - options - CommitmentPlansClientBeginUpdatePlanOptions contains the optional parameters for the CommitmentPlansClient.BeginUpdatePlan +// method. +func (client *CommitmentPlansClient) BeginUpdatePlan(ctx context.Context, resourceGroupName string, commitmentPlanName string, commitmentPlan PatchResourceTagsAndSKU, options *CommitmentPlansClientBeginUpdatePlanOptions) (*runtime.Poller[CommitmentPlansClientUpdatePlanResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.updatePlan(ctx, resourceGroupName, commitmentPlanName, commitmentPlan, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CommitmentPlansClientUpdatePlanResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CommitmentPlansClientUpdatePlanResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// UpdatePlan - Create Cognitive Services commitment plan. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CommitmentPlansClient) updatePlan(ctx context.Context, resourceGroupName string, commitmentPlanName string, commitmentPlan PatchResourceTagsAndSKU, options *CommitmentPlansClientBeginUpdatePlanOptions) (*http.Response, error) { + var err error + const operationName = "CommitmentPlansClient.BeginUpdatePlan" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updatePlanCreateRequest(ctx, resourceGroupName, commitmentPlanName, commitmentPlan, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updatePlanCreateRequest creates the UpdatePlan request. +func (client *CommitmentPlansClient) updatePlanCreateRequest(ctx context.Context, resourceGroupName string, commitmentPlanName string, commitmentPlan PatchResourceTagsAndSKU, _ *CommitmentPlansClientBeginUpdatePlanOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/commitmentPlans/{commitmentPlanName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if commitmentPlanName == "" { + return nil, errors.New("parameter commitmentPlanName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{commitmentPlanName}", url.PathEscape(commitmentPlanName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, commitmentPlan); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armcognitiveservices/zz_commitmenttiers_client.go b/test/local/armcognitiveservices/zz_commitmenttiers_client.go new file mode 100644 index 000000000000..ae04e33e8a9e --- /dev/null +++ b/test/local/armcognitiveservices/zz_commitmenttiers_client.go @@ -0,0 +1,100 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// CommitmentTiersClient contains the methods for the CommitmentTiers group. +// Don't use this type directly, use NewCommitmentTiersClient() instead. +// +// Generated from API version 2026-05-01 +type CommitmentTiersClient struct { + internal *arm.Client + subscriptionID string +} + +// NewCommitmentTiersClient creates a new instance of CommitmentTiersClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewCommitmentTiersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CommitmentTiersClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CommitmentTiersClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListPager - List Commitment Tiers. +// - location - The location name. +// - options - CommitmentTiersClientListOptions contains the optional parameters for the CommitmentTiersClient.NewListPager +// method. +func (client *CommitmentTiersClient) NewListPager(location string, options *CommitmentTiersClientListOptions) *runtime.Pager[CommitmentTiersClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[CommitmentTiersClientListResponse]{ + More: func(page CommitmentTiersClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CommitmentTiersClientListResponse) (CommitmentTiersClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CommitmentTiersClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, location, options) + }, nil) + if err != nil { + return CommitmentTiersClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *CommitmentTiersClient) listCreateRequest(ctx context.Context, location string, _ *CommitmentTiersClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/commitmentTiers" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *CommitmentTiersClient) listHandleResponse(resp *http.Response) (CommitmentTiersClientListResponse, error) { + result := CommitmentTiersClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CommitmentTierListResult); err != nil { + return CommitmentTiersClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_constants.go b/test/local/armcognitiveservices/zz_constants.go new file mode 100644 index 000000000000..a0be15dc11de --- /dev/null +++ b/test/local/armcognitiveservices/zz_constants.go @@ -0,0 +1,1646 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +const ( + version20260501 string = "2026-05-01" +) + +// AbusePenaltyAction - The action of AbusePenalty. +type AbusePenaltyAction string + +const ( + AbusePenaltyActionBlock AbusePenaltyAction = "Block" + AbusePenaltyActionThrottle AbusePenaltyAction = "Throttle" +) + +// PossibleAbusePenaltyActionValues returns the possible values for the AbusePenaltyAction const type. +func PossibleAbusePenaltyActionValues() []AbusePenaltyAction { + return []AbusePenaltyAction{ + AbusePenaltyActionBlock, + AbusePenaltyActionThrottle, + } +} + +// ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +type ActionType string + +const ( + // ActionTypeInternal - Actions are for internal-only APIs. + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// AgentDeploymentProvisioningState - Provisioning state of an agentic deployment, as an Azure resource. +type AgentDeploymentProvisioningState string + +const ( + // AgentDeploymentProvisioningStateCanceled - The deployment was canceled. + AgentDeploymentProvisioningStateCanceled AgentDeploymentProvisioningState = "Canceled" + // AgentDeploymentProvisioningStateCreating - The deployment is being created. + AgentDeploymentProvisioningStateCreating AgentDeploymentProvisioningState = "Creating" + // AgentDeploymentProvisioningStateDeleting - The deployment is being deleted. + AgentDeploymentProvisioningStateDeleting AgentDeploymentProvisioningState = "Deleting" + // AgentDeploymentProvisioningStateFailed - The deployment failed. + AgentDeploymentProvisioningStateFailed AgentDeploymentProvisioningState = "Failed" + // AgentDeploymentProvisioningStateSucceeded - The deployment was successfully completed. + AgentDeploymentProvisioningStateSucceeded AgentDeploymentProvisioningState = "Succeeded" + // AgentDeploymentProvisioningStateUpdating - The deployment is being updated. + AgentDeploymentProvisioningStateUpdating AgentDeploymentProvisioningState = "Updating" +) + +// PossibleAgentDeploymentProvisioningStateValues returns the possible values for the AgentDeploymentProvisioningState const type. +func PossibleAgentDeploymentProvisioningStateValues() []AgentDeploymentProvisioningState { + return []AgentDeploymentProvisioningState{ + AgentDeploymentProvisioningStateCanceled, + AgentDeploymentProvisioningStateCreating, + AgentDeploymentProvisioningStateDeleting, + AgentDeploymentProvisioningStateFailed, + AgentDeploymentProvisioningStateSucceeded, + AgentDeploymentProvisioningStateUpdating, + } +} + +// AgentDeploymentState - Current operational state of the agentic functionality represented by this deployment. +type AgentDeploymentState string + +const ( + // AgentDeploymentStateDeleted - The deployment was deleted. + AgentDeploymentStateDeleted AgentDeploymentState = "Deleted" + // AgentDeploymentStateDeleting - The deployment is being deleted. + AgentDeploymentStateDeleting AgentDeploymentState = "Deleting" + // AgentDeploymentStateFailed - The deployment failed. + AgentDeploymentStateFailed AgentDeploymentState = "Failed" + // AgentDeploymentStateRunning - The deployment started/is operational. + AgentDeploymentStateRunning AgentDeploymentState = "Running" + // AgentDeploymentStateStarting - The deployment is starting. + AgentDeploymentStateStarting AgentDeploymentState = "Starting" + // AgentDeploymentStateStopped - The deployment was stopped. + AgentDeploymentStateStopped AgentDeploymentState = "Stopped" + // AgentDeploymentStateStopping - The deployment is being stopped. + AgentDeploymentStateStopping AgentDeploymentState = "Stopping" + // AgentDeploymentStateUpdating - The deployment is being updated. + AgentDeploymentStateUpdating AgentDeploymentState = "Updating" +) + +// PossibleAgentDeploymentStateValues returns the possible values for the AgentDeploymentState const type. +func PossibleAgentDeploymentStateValues() []AgentDeploymentState { + return []AgentDeploymentState{ + AgentDeploymentStateDeleted, + AgentDeploymentStateDeleting, + AgentDeploymentStateFailed, + AgentDeploymentStateRunning, + AgentDeploymentStateStarting, + AgentDeploymentStateStopped, + AgentDeploymentStateStopping, + AgentDeploymentStateUpdating, + } +} + +// AgentDeploymentType - Specifies the type of deployment for an agent, indicating how the underlying compute and network +// infrastructure is managed. +type AgentDeploymentType string + +const ( + // AgentDeploymentTypeCustom - The underlying infra is provisioned by the deployer (BYO) + AgentDeploymentTypeCustom AgentDeploymentType = "Custom" + // AgentDeploymentTypeHosted - The underlying infra is owned by the platform + AgentDeploymentTypeHosted AgentDeploymentType = "Hosted" + // AgentDeploymentTypeManaged - The underlying infra is managed by the platform in the deployer's subscription + AgentDeploymentTypeManaged AgentDeploymentType = "Managed" +) + +// PossibleAgentDeploymentTypeValues returns the possible values for the AgentDeploymentType const type. +func PossibleAgentDeploymentTypeValues() []AgentDeploymentType { + return []AgentDeploymentType{ + AgentDeploymentTypeCustom, + AgentDeploymentTypeHosted, + AgentDeploymentTypeManaged, + } +} + +// AgentProtocol - Protocol used by the agent/exposed by a deployment. +type AgentProtocol string + +const ( + // AgentProtocolA2A - Agent2Agent standard + AgentProtocolA2A AgentProtocol = "A2A" + // AgentProtocolAgent - Agent protocol (aka Active) + AgentProtocolAgent AgentProtocol = "Agent" + // AgentProtocolResponses - OpenAI-compatible + AgentProtocolResponses AgentProtocol = "Responses" +) + +// PossibleAgentProtocolValues returns the possible values for the AgentProtocol const type. +func PossibleAgentProtocolValues() []AgentProtocol { + return []AgentProtocol{ + AgentProtocolA2A, + AgentProtocolAgent, + AgentProtocolResponses, + } +} + +// AgenticApplicationProvisioningState - Provisioning state of an agentic application. +type AgenticApplicationProvisioningState string + +const ( + // AgenticApplicationProvisioningStateCanceled - The application provisioning was canceled. + AgenticApplicationProvisioningStateCanceled AgenticApplicationProvisioningState = "Canceled" + // AgenticApplicationProvisioningStateCreating - The application is being created. + AgenticApplicationProvisioningStateCreating AgenticApplicationProvisioningState = "Creating" + // AgenticApplicationProvisioningStateDeleting - The application is being deleted. + AgenticApplicationProvisioningStateDeleting AgenticApplicationProvisioningState = "Deleting" + // AgenticApplicationProvisioningStateFailed - The application provisioning failed. + AgenticApplicationProvisioningStateFailed AgenticApplicationProvisioningState = "Failed" + // AgenticApplicationProvisioningStateSucceeded - The application was successfully provisioned. + AgenticApplicationProvisioningStateSucceeded AgenticApplicationProvisioningState = "Succeeded" + // AgenticApplicationProvisioningStateUpdating - The application is being updated. + AgenticApplicationProvisioningStateUpdating AgenticApplicationProvisioningState = "Updating" +) + +// PossibleAgenticApplicationProvisioningStateValues returns the possible values for the AgenticApplicationProvisioningState const type. +func PossibleAgenticApplicationProvisioningStateValues() []AgenticApplicationProvisioningState { + return []AgenticApplicationProvisioningState{ + AgenticApplicationProvisioningStateCanceled, + AgenticApplicationProvisioningStateCreating, + AgenticApplicationProvisioningStateDeleting, + AgenticApplicationProvisioningStateFailed, + AgenticApplicationProvisioningStateSucceeded, + AgenticApplicationProvisioningStateUpdating, + } +} + +// BuiltInAuthorizationScheme - Authorization scheme type. +type BuiltInAuthorizationScheme string + +const ( + // BuiltInAuthorizationSchemeChannels - Channels-specific (AzureBotService) authorization + BuiltInAuthorizationSchemeChannels BuiltInAuthorizationScheme = "Channels" + // BuiltInAuthorizationSchemeCustom - Custom scheme defined by the application author + BuiltInAuthorizationSchemeCustom BuiltInAuthorizationScheme = "Custom" + // BuiltInAuthorizationSchemeDefault - Standard AzureML RBAC + BuiltInAuthorizationSchemeDefault BuiltInAuthorizationScheme = "Default" + // BuiltInAuthorizationSchemeOrganizationScope - Claim-based, requires membership in the tenant + BuiltInAuthorizationSchemeOrganizationScope BuiltInAuthorizationScheme = "OrganizationScope" +) + +// PossibleBuiltInAuthorizationSchemeValues returns the possible values for the BuiltInAuthorizationScheme const type. +func PossibleBuiltInAuthorizationSchemeValues() []BuiltInAuthorizationScheme { + return []BuiltInAuthorizationScheme{ + BuiltInAuthorizationSchemeChannels, + BuiltInAuthorizationSchemeCustom, + BuiltInAuthorizationSchemeDefault, + BuiltInAuthorizationSchemeOrganizationScope, + } +} + +// ByPassSelection - Setting for trusted services. +type ByPassSelection string + +const ( + ByPassSelectionAzureServices ByPassSelection = "AzureServices" + ByPassSelectionNone ByPassSelection = "None" +) + +// PossibleByPassSelectionValues returns the possible values for the ByPassSelection const type. +func PossibleByPassSelectionValues() []ByPassSelection { + return []ByPassSelection{ + ByPassSelectionAzureServices, + ByPassSelectionNone, + } +} + +type CapabilityHostKind string + +const ( + CapabilityHostKindAgents CapabilityHostKind = "Agents" +) + +// PossibleCapabilityHostKindValues returns the possible values for the CapabilityHostKind const type. +func PossibleCapabilityHostKindValues() []CapabilityHostKind { + return []CapabilityHostKind{ + CapabilityHostKindAgents, + } +} + +// CapabilityHostProvisioningState - Provisioning state of capability host. +type CapabilityHostProvisioningState string + +const ( + CapabilityHostProvisioningStateCanceled CapabilityHostProvisioningState = "Canceled" + CapabilityHostProvisioningStateCreating CapabilityHostProvisioningState = "Creating" + CapabilityHostProvisioningStateDeleting CapabilityHostProvisioningState = "Deleting" + CapabilityHostProvisioningStateFailed CapabilityHostProvisioningState = "Failed" + CapabilityHostProvisioningStateSucceeded CapabilityHostProvisioningState = "Succeeded" + CapabilityHostProvisioningStateUpdating CapabilityHostProvisioningState = "Updating" +) + +// PossibleCapabilityHostProvisioningStateValues returns the possible values for the CapabilityHostProvisioningState const type. +func PossibleCapabilityHostProvisioningStateValues() []CapabilityHostProvisioningState { + return []CapabilityHostProvisioningState{ + CapabilityHostProvisioningStateCanceled, + CapabilityHostProvisioningStateCreating, + CapabilityHostProvisioningStateDeleting, + CapabilityHostProvisioningStateFailed, + CapabilityHostProvisioningStateSucceeded, + CapabilityHostProvisioningStateUpdating, + } +} + +// CommitmentPlanProvisioningState - Gets the status of the resource at the time the operation was called. +type CommitmentPlanProvisioningState string + +const ( + CommitmentPlanProvisioningStateAccepted CommitmentPlanProvisioningState = "Accepted" + CommitmentPlanProvisioningStateCanceled CommitmentPlanProvisioningState = "Canceled" + CommitmentPlanProvisioningStateCreating CommitmentPlanProvisioningState = "Creating" + CommitmentPlanProvisioningStateDeleting CommitmentPlanProvisioningState = "Deleting" + CommitmentPlanProvisioningStateFailed CommitmentPlanProvisioningState = "Failed" + CommitmentPlanProvisioningStateMoving CommitmentPlanProvisioningState = "Moving" + CommitmentPlanProvisioningStateSucceeded CommitmentPlanProvisioningState = "Succeeded" +) + +// PossibleCommitmentPlanProvisioningStateValues returns the possible values for the CommitmentPlanProvisioningState const type. +func PossibleCommitmentPlanProvisioningStateValues() []CommitmentPlanProvisioningState { + return []CommitmentPlanProvisioningState{ + CommitmentPlanProvisioningStateAccepted, + CommitmentPlanProvisioningStateCanceled, + CommitmentPlanProvisioningStateCreating, + CommitmentPlanProvisioningStateDeleting, + CommitmentPlanProvisioningStateFailed, + CommitmentPlanProvisioningStateMoving, + CommitmentPlanProvisioningStateSucceeded, + } +} + +// ConnectionAuthType - Authentication type of the connection target +type ConnectionAuthType string + +const ( + ConnectionAuthTypeAAD ConnectionAuthType = "AAD" + ConnectionAuthTypeAPIKey ConnectionAuthType = "ApiKey" + ConnectionAuthTypeAccessKey ConnectionAuthType = "AccessKey" + ConnectionAuthTypeAccountKey ConnectionAuthType = "AccountKey" + ConnectionAuthTypeAccountManagedIdentity ConnectionAuthType = "AccountManagedIdentity" + ConnectionAuthTypeAgentUserImpersonation ConnectionAuthType = "AgentUserImpersonation" + ConnectionAuthTypeAgenticIdentityToken ConnectionAuthType = "AgenticIdentityToken" + ConnectionAuthTypeAgenticUser ConnectionAuthType = "AgenticUser" + ConnectionAuthTypeCustomKeys ConnectionAuthType = "CustomKeys" + ConnectionAuthTypeDelegatedSAS ConnectionAuthType = "DelegatedSAS" + ConnectionAuthTypeManagedIdentity ConnectionAuthType = "ManagedIdentity" + ConnectionAuthTypeNone ConnectionAuthType = "None" + ConnectionAuthTypeOAuth2 ConnectionAuthType = "OAuth2" + ConnectionAuthTypePAT ConnectionAuthType = "PAT" + ConnectionAuthTypeProjectManagedIdentity ConnectionAuthType = "ProjectManagedIdentity" + ConnectionAuthTypeSAS ConnectionAuthType = "SAS" + ConnectionAuthTypeServicePrincipal ConnectionAuthType = "ServicePrincipal" + ConnectionAuthTypeUserEntraToken ConnectionAuthType = "UserEntraToken" + ConnectionAuthTypeUsernamePassword ConnectionAuthType = "UsernamePassword" +) + +// PossibleConnectionAuthTypeValues returns the possible values for the ConnectionAuthType const type. +func PossibleConnectionAuthTypeValues() []ConnectionAuthType { + return []ConnectionAuthType{ + ConnectionAuthTypeAAD, + ConnectionAuthTypeAPIKey, + ConnectionAuthTypeAccessKey, + ConnectionAuthTypeAccountKey, + ConnectionAuthTypeAccountManagedIdentity, + ConnectionAuthTypeAgentUserImpersonation, + ConnectionAuthTypeAgenticIdentityToken, + ConnectionAuthTypeAgenticUser, + ConnectionAuthTypeCustomKeys, + ConnectionAuthTypeDelegatedSAS, + ConnectionAuthTypeManagedIdentity, + ConnectionAuthTypeNone, + ConnectionAuthTypeOAuth2, + ConnectionAuthTypePAT, + ConnectionAuthTypeProjectManagedIdentity, + ConnectionAuthTypeSAS, + ConnectionAuthTypeServicePrincipal, + ConnectionAuthTypeUserEntraToken, + ConnectionAuthTypeUsernamePassword, + } +} + +// ConnectionCategory - Category of the connection +type ConnectionCategory string + +const ( + ConnectionCategoryADLSGen2 ConnectionCategory = "ADLSGen2" + ConnectionCategoryAIServices ConnectionCategory = "AIServices" + ConnectionCategoryAPIKey ConnectionCategory = "ApiKey" + ConnectionCategoryAPIManagement ConnectionCategory = "ApiManagement" + ConnectionCategoryAmazonMws ConnectionCategory = "AmazonMws" + ConnectionCategoryAmazonRdsForOracle ConnectionCategory = "AmazonRdsForOracle" + ConnectionCategoryAmazonRdsForSQLServer ConnectionCategory = "AmazonRdsForSqlServer" + ConnectionCategoryAmazonRedshift ConnectionCategory = "AmazonRedshift" + ConnectionCategoryAmazonS3Compatible ConnectionCategory = "AmazonS3Compatible" + ConnectionCategoryAppConfig ConnectionCategory = "AppConfig" + ConnectionCategoryAppInsights ConnectionCategory = "AppInsights" + ConnectionCategoryAzureBlob ConnectionCategory = "AzureBlob" + ConnectionCategoryAzureContainerAppEnvironment ConnectionCategory = "AzureContainerAppEnvironment" + ConnectionCategoryAzureDataExplorer ConnectionCategory = "AzureDataExplorer" + ConnectionCategoryAzureDatabricksDeltaLake ConnectionCategory = "AzureDatabricksDeltaLake" + ConnectionCategoryAzureKeyVault ConnectionCategory = "AzureKeyVault" + ConnectionCategoryAzureMariaDb ConnectionCategory = "AzureMariaDb" + ConnectionCategoryAzureMySQLDb ConnectionCategory = "AzureMySqlDb" + ConnectionCategoryAzureOneLake ConnectionCategory = "AzureOneLake" + ConnectionCategoryAzureOpenAI ConnectionCategory = "AzureOpenAI" + ConnectionCategoryAzurePostgresDb ConnectionCategory = "AzurePostgresDb" + ConnectionCategoryAzureSQLDb ConnectionCategory = "AzureSqlDb" + ConnectionCategoryAzureSQLMi ConnectionCategory = "AzureSqlMi" + ConnectionCategoryAzureStorageAccount ConnectionCategory = "AzureStorageAccount" + ConnectionCategoryAzureSynapseAnalytics ConnectionCategory = "AzureSynapseAnalytics" + ConnectionCategoryAzureTableStorage ConnectionCategory = "AzureTableStorage" + ConnectionCategoryBingLLMSearch ConnectionCategory = "BingLLMSearch" + ConnectionCategoryCassandra ConnectionCategory = "Cassandra" + ConnectionCategoryCognitiveSearch ConnectionCategory = "CognitiveSearch" + ConnectionCategoryCognitiveService ConnectionCategory = "CognitiveService" + ConnectionCategoryConcur ConnectionCategory = "Concur" + ConnectionCategoryContainerRegistry ConnectionCategory = "ContainerRegistry" + ConnectionCategoryCosmosDb ConnectionCategory = "CosmosDb" + ConnectionCategoryCosmosDbMongoDbAPI ConnectionCategory = "CosmosDbMongoDbApi" + ConnectionCategoryCouchbase ConnectionCategory = "Couchbase" + ConnectionCategoryCustomKeys ConnectionCategory = "CustomKeys" + ConnectionCategoryDatabricks ConnectionCategory = "Databricks" + ConnectionCategoryDb2 ConnectionCategory = "Db2" + ConnectionCategoryDrill ConnectionCategory = "Drill" + ConnectionCategoryDynamics ConnectionCategory = "Dynamics" + ConnectionCategoryDynamicsAx ConnectionCategory = "DynamicsAx" + ConnectionCategoryDynamicsCrm ConnectionCategory = "DynamicsCrm" + ConnectionCategoryElasticsearch ConnectionCategory = "Elasticsearch" + ConnectionCategoryEloqua ConnectionCategory = "Eloqua" + ConnectionCategoryFileServer ConnectionCategory = "FileServer" + ConnectionCategoryFtpServer ConnectionCategory = "FtpServer" + ConnectionCategoryGenericContainerRegistry ConnectionCategory = "GenericContainerRegistry" + ConnectionCategoryGenericHTTP ConnectionCategory = "GenericHttp" + ConnectionCategoryGenericRest ConnectionCategory = "GenericRest" + ConnectionCategoryGit ConnectionCategory = "Git" + ConnectionCategoryGoogleAdWords ConnectionCategory = "GoogleAdWords" + ConnectionCategoryGoogleBigQuery ConnectionCategory = "GoogleBigQuery" + ConnectionCategoryGoogleCloudStorage ConnectionCategory = "GoogleCloudStorage" + ConnectionCategoryGreenplum ConnectionCategory = "Greenplum" + ConnectionCategoryGroundingWithBingSearch ConnectionCategory = "GroundingWithBingSearch" + ConnectionCategoryGroundingWithCustomSearch ConnectionCategory = "GroundingWithCustomSearch" + ConnectionCategoryHbase ConnectionCategory = "Hbase" + ConnectionCategoryHdfs ConnectionCategory = "Hdfs" + ConnectionCategoryHive ConnectionCategory = "Hive" + ConnectionCategoryHubspot ConnectionCategory = "Hubspot" + ConnectionCategoryImpala ConnectionCategory = "Impala" + ConnectionCategoryInformix ConnectionCategory = "Informix" + ConnectionCategoryJira ConnectionCategory = "Jira" + ConnectionCategoryMagento ConnectionCategory = "Magento" + ConnectionCategoryManagedOnlineEndpoint ConnectionCategory = "ManagedOnlineEndpoint" + ConnectionCategoryMariaDb ConnectionCategory = "MariaDb" + ConnectionCategoryMarketo ConnectionCategory = "Marketo" + ConnectionCategoryMicrosoftAccess ConnectionCategory = "MicrosoftAccess" + ConnectionCategoryMicrosoftFabric ConnectionCategory = "MicrosoftFabric" + ConnectionCategoryModelGateway ConnectionCategory = "ModelGateway" + ConnectionCategoryMongoDbAtlas ConnectionCategory = "MongoDbAtlas" + ConnectionCategoryMongoDbV2 ConnectionCategory = "MongoDbV2" + ConnectionCategoryMySQL ConnectionCategory = "MySql" + ConnectionCategoryNetezza ConnectionCategory = "Netezza" + ConnectionCategoryODataRest ConnectionCategory = "ODataRest" + ConnectionCategoryOdbc ConnectionCategory = "Odbc" + ConnectionCategoryOffice365 ConnectionCategory = "Office365" + ConnectionCategoryOpenAI ConnectionCategory = "OpenAI" + ConnectionCategoryOracle ConnectionCategory = "Oracle" + ConnectionCategoryOracleCloudStorage ConnectionCategory = "OracleCloudStorage" + ConnectionCategoryOracleServiceCloud ConnectionCategory = "OracleServiceCloud" + ConnectionCategoryPayPal ConnectionCategory = "PayPal" + ConnectionCategoryPhoenix ConnectionCategory = "Phoenix" + ConnectionCategoryPinecone ConnectionCategory = "Pinecone" + ConnectionCategoryPostgreSQL ConnectionCategory = "PostgreSql" + ConnectionCategoryPowerPlatformEnvironment ConnectionCategory = "PowerPlatformEnvironment" + ConnectionCategoryPresto ConnectionCategory = "Presto" + ConnectionCategoryPythonFeed ConnectionCategory = "PythonFeed" + ConnectionCategoryQuickBooks ConnectionCategory = "QuickBooks" + ConnectionCategoryRedis ConnectionCategory = "Redis" + ConnectionCategoryRemoteA2A ConnectionCategory = "RemoteA2A" + ConnectionCategoryRemoteTool ConnectionCategory = "RemoteTool" + ConnectionCategoryResponsys ConnectionCategory = "Responsys" + ConnectionCategoryS3 ConnectionCategory = "S3" + ConnectionCategorySQLServer ConnectionCategory = "SqlServer" + ConnectionCategorySalesforce ConnectionCategory = "Salesforce" + ConnectionCategorySalesforceMarketingCloud ConnectionCategory = "SalesforceMarketingCloud" + ConnectionCategorySalesforceServiceCloud ConnectionCategory = "SalesforceServiceCloud" + ConnectionCategorySapBw ConnectionCategory = "SapBw" + ConnectionCategorySapCloudForCustomer ConnectionCategory = "SapCloudForCustomer" + ConnectionCategorySapEcc ConnectionCategory = "SapEcc" + ConnectionCategorySapHana ConnectionCategory = "SapHana" + ConnectionCategorySapOpenHub ConnectionCategory = "SapOpenHub" + ConnectionCategorySapTable ConnectionCategory = "SapTable" + ConnectionCategorySerp ConnectionCategory = "Serp" + ConnectionCategoryServerless ConnectionCategory = "Serverless" + ConnectionCategoryServiceNow ConnectionCategory = "ServiceNow" + ConnectionCategorySftp ConnectionCategory = "Sftp" + ConnectionCategorySharePointOnlineList ConnectionCategory = "SharePointOnlineList" + ConnectionCategorySharepoint ConnectionCategory = "Sharepoint" + ConnectionCategoryShopify ConnectionCategory = "Shopify" + ConnectionCategorySnowflake ConnectionCategory = "Snowflake" + ConnectionCategorySpark ConnectionCategory = "Spark" + ConnectionCategorySquare ConnectionCategory = "Square" + ConnectionCategorySybase ConnectionCategory = "Sybase" + ConnectionCategoryTeradata ConnectionCategory = "Teradata" + ConnectionCategoryVertica ConnectionCategory = "Vertica" + ConnectionCategoryWebTable ConnectionCategory = "WebTable" + ConnectionCategoryXero ConnectionCategory = "Xero" + ConnectionCategoryZoho ConnectionCategory = "Zoho" +) + +// PossibleConnectionCategoryValues returns the possible values for the ConnectionCategory const type. +func PossibleConnectionCategoryValues() []ConnectionCategory { + return []ConnectionCategory{ + ConnectionCategoryADLSGen2, + ConnectionCategoryAIServices, + ConnectionCategoryAPIKey, + ConnectionCategoryAPIManagement, + ConnectionCategoryAmazonMws, + ConnectionCategoryAmazonRdsForOracle, + ConnectionCategoryAmazonRdsForSQLServer, + ConnectionCategoryAmazonRedshift, + ConnectionCategoryAmazonS3Compatible, + ConnectionCategoryAppConfig, + ConnectionCategoryAppInsights, + ConnectionCategoryAzureBlob, + ConnectionCategoryAzureContainerAppEnvironment, + ConnectionCategoryAzureDataExplorer, + ConnectionCategoryAzureDatabricksDeltaLake, + ConnectionCategoryAzureKeyVault, + ConnectionCategoryAzureMariaDb, + ConnectionCategoryAzureMySQLDb, + ConnectionCategoryAzureOneLake, + ConnectionCategoryAzureOpenAI, + ConnectionCategoryAzurePostgresDb, + ConnectionCategoryAzureSQLDb, + ConnectionCategoryAzureSQLMi, + ConnectionCategoryAzureStorageAccount, + ConnectionCategoryAzureSynapseAnalytics, + ConnectionCategoryAzureTableStorage, + ConnectionCategoryBingLLMSearch, + ConnectionCategoryCassandra, + ConnectionCategoryCognitiveSearch, + ConnectionCategoryCognitiveService, + ConnectionCategoryConcur, + ConnectionCategoryContainerRegistry, + ConnectionCategoryCosmosDb, + ConnectionCategoryCosmosDbMongoDbAPI, + ConnectionCategoryCouchbase, + ConnectionCategoryCustomKeys, + ConnectionCategoryDatabricks, + ConnectionCategoryDb2, + ConnectionCategoryDrill, + ConnectionCategoryDynamics, + ConnectionCategoryDynamicsAx, + ConnectionCategoryDynamicsCrm, + ConnectionCategoryElasticsearch, + ConnectionCategoryEloqua, + ConnectionCategoryFileServer, + ConnectionCategoryFtpServer, + ConnectionCategoryGenericContainerRegistry, + ConnectionCategoryGenericHTTP, + ConnectionCategoryGenericRest, + ConnectionCategoryGit, + ConnectionCategoryGoogleAdWords, + ConnectionCategoryGoogleBigQuery, + ConnectionCategoryGoogleCloudStorage, + ConnectionCategoryGreenplum, + ConnectionCategoryGroundingWithBingSearch, + ConnectionCategoryGroundingWithCustomSearch, + ConnectionCategoryHbase, + ConnectionCategoryHdfs, + ConnectionCategoryHive, + ConnectionCategoryHubspot, + ConnectionCategoryImpala, + ConnectionCategoryInformix, + ConnectionCategoryJira, + ConnectionCategoryMagento, + ConnectionCategoryManagedOnlineEndpoint, + ConnectionCategoryMariaDb, + ConnectionCategoryMarketo, + ConnectionCategoryMicrosoftAccess, + ConnectionCategoryMicrosoftFabric, + ConnectionCategoryModelGateway, + ConnectionCategoryMongoDbAtlas, + ConnectionCategoryMongoDbV2, + ConnectionCategoryMySQL, + ConnectionCategoryNetezza, + ConnectionCategoryODataRest, + ConnectionCategoryOdbc, + ConnectionCategoryOffice365, + ConnectionCategoryOpenAI, + ConnectionCategoryOracle, + ConnectionCategoryOracleCloudStorage, + ConnectionCategoryOracleServiceCloud, + ConnectionCategoryPayPal, + ConnectionCategoryPhoenix, + ConnectionCategoryPinecone, + ConnectionCategoryPostgreSQL, + ConnectionCategoryPowerPlatformEnvironment, + ConnectionCategoryPresto, + ConnectionCategoryPythonFeed, + ConnectionCategoryQuickBooks, + ConnectionCategoryRedis, + ConnectionCategoryRemoteA2A, + ConnectionCategoryRemoteTool, + ConnectionCategoryResponsys, + ConnectionCategoryS3, + ConnectionCategorySQLServer, + ConnectionCategorySalesforce, + ConnectionCategorySalesforceMarketingCloud, + ConnectionCategorySalesforceServiceCloud, + ConnectionCategorySapBw, + ConnectionCategorySapCloudForCustomer, + ConnectionCategorySapEcc, + ConnectionCategorySapHana, + ConnectionCategorySapOpenHub, + ConnectionCategorySapTable, + ConnectionCategorySerp, + ConnectionCategoryServerless, + ConnectionCategoryServiceNow, + ConnectionCategorySftp, + ConnectionCategorySharePointOnlineList, + ConnectionCategorySharepoint, + ConnectionCategoryShopify, + ConnectionCategorySnowflake, + ConnectionCategorySpark, + ConnectionCategorySquare, + ConnectionCategorySybase, + ConnectionCategoryTeradata, + ConnectionCategoryVertica, + ConnectionCategoryWebTable, + ConnectionCategoryXero, + ConnectionCategoryZoho, + } +} + +// ConnectionGroup - Group based on connection category +type ConnectionGroup string + +const ( + ConnectionGroupAzure ConnectionGroup = "Azure" + ConnectionGroupAzureAI ConnectionGroup = "AzureAI" + ConnectionGroupDatabase ConnectionGroup = "Database" + ConnectionGroupFile ConnectionGroup = "File" + ConnectionGroupGenericProtocol ConnectionGroup = "GenericProtocol" + ConnectionGroupNoSQL ConnectionGroup = "NoSQL" + ConnectionGroupServicesAndApps ConnectionGroup = "ServicesAndApps" +) + +// PossibleConnectionGroupValues returns the possible values for the ConnectionGroup const type. +func PossibleConnectionGroupValues() []ConnectionGroup { + return []ConnectionGroup{ + ConnectionGroupAzure, + ConnectionGroupAzureAI, + ConnectionGroupDatabase, + ConnectionGroupFile, + ConnectionGroupGenericProtocol, + ConnectionGroupNoSQL, + ConnectionGroupServicesAndApps, + } +} + +// ContentLevel - Level at which content is filtered. +type ContentLevel string + +const ( + ContentLevelHigh ContentLevel = "High" + ContentLevelLow ContentLevel = "Low" + ContentLevelMedium ContentLevel = "Medium" +) + +// PossibleContentLevelValues returns the possible values for the ContentLevel const type. +func PossibleContentLevelValues() []ContentLevel { + return []ContentLevel{ + ContentLevelHigh, + ContentLevelLow, + ContentLevelMedium, + } +} + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// DefenderForAISettingState - Defender for AI state on the AI resource. +type DefenderForAISettingState string + +const ( + DefenderForAISettingStateDisabled DefenderForAISettingState = "Disabled" + DefenderForAISettingStateEnabled DefenderForAISettingState = "Enabled" +) + +// PossibleDefenderForAISettingStateValues returns the possible values for the DefenderForAISettingState const type. +func PossibleDefenderForAISettingStateValues() []DefenderForAISettingState { + return []DefenderForAISettingState{ + DefenderForAISettingStateDisabled, + DefenderForAISettingStateEnabled, + } +} + +// DeploymentModelVersionUpgradeOption - Deployment model version upgrade option. +type DeploymentModelVersionUpgradeOption string + +const ( + DeploymentModelVersionUpgradeOptionNoAutoUpgrade DeploymentModelVersionUpgradeOption = "NoAutoUpgrade" + DeploymentModelVersionUpgradeOptionOnceCurrentVersionExpired DeploymentModelVersionUpgradeOption = "OnceCurrentVersionExpired" + DeploymentModelVersionUpgradeOptionOnceNewDefaultVersionAvailable DeploymentModelVersionUpgradeOption = "OnceNewDefaultVersionAvailable" +) + +// PossibleDeploymentModelVersionUpgradeOptionValues returns the possible values for the DeploymentModelVersionUpgradeOption const type. +func PossibleDeploymentModelVersionUpgradeOptionValues() []DeploymentModelVersionUpgradeOption { + return []DeploymentModelVersionUpgradeOption{ + DeploymentModelVersionUpgradeOptionNoAutoUpgrade, + DeploymentModelVersionUpgradeOptionOnceCurrentVersionExpired, + DeploymentModelVersionUpgradeOptionOnceNewDefaultVersionAvailable, + } +} + +// DeploymentProvisioningState - Gets the status of the resource at the time the operation was called. +type DeploymentProvisioningState string + +const ( + DeploymentProvisioningStateAccepted DeploymentProvisioningState = "Accepted" + DeploymentProvisioningStateCanceled DeploymentProvisioningState = "Canceled" + DeploymentProvisioningStateCreating DeploymentProvisioningState = "Creating" + DeploymentProvisioningStateDeleting DeploymentProvisioningState = "Deleting" + DeploymentProvisioningStateDisabled DeploymentProvisioningState = "Disabled" + DeploymentProvisioningStateFailed DeploymentProvisioningState = "Failed" + DeploymentProvisioningStateMoving DeploymentProvisioningState = "Moving" + DeploymentProvisioningStateSucceeded DeploymentProvisioningState = "Succeeded" +) + +// PossibleDeploymentProvisioningStateValues returns the possible values for the DeploymentProvisioningState const type. +func PossibleDeploymentProvisioningStateValues() []DeploymentProvisioningState { + return []DeploymentProvisioningState{ + DeploymentProvisioningStateAccepted, + DeploymentProvisioningStateCanceled, + DeploymentProvisioningStateCreating, + DeploymentProvisioningStateDeleting, + DeploymentProvisioningStateDisabled, + DeploymentProvisioningStateFailed, + DeploymentProvisioningStateMoving, + DeploymentProvisioningStateSucceeded, + } +} + +// DeploymentScaleType - Deployment scale type. +type DeploymentScaleType string + +const ( + DeploymentScaleTypeManual DeploymentScaleType = "Manual" + DeploymentScaleTypeStandard DeploymentScaleType = "Standard" +) + +// PossibleDeploymentScaleTypeValues returns the possible values for the DeploymentScaleType const type. +func PossibleDeploymentScaleTypeValues() []DeploymentScaleType { + return []DeploymentScaleType{ + DeploymentScaleTypeManual, + DeploymentScaleTypeStandard, + } +} + +// DeploymentState - The state of the deployment. Controls whether the deployment is accepting inference requests. Use 'Running' +// for active deployments that process requests, or 'Paused' to temporarily stop inference while preserving the deployment +// configuration. +type DeploymentState string + +const ( + // DeploymentStatePaused - The deployment is paused and not accepting inference requests. + DeploymentStatePaused DeploymentState = "Paused" + // DeploymentStateRunning - The deployment is running and accepting inference requests. + DeploymentStateRunning DeploymentState = "Running" +) + +// PossibleDeploymentStateValues returns the possible values for the DeploymentState const type. +func PossibleDeploymentStateValues() []DeploymentState { + return []DeploymentState{ + DeploymentStatePaused, + DeploymentStateRunning, + } +} + +// DeprecationStatus - Indicates whether the deprecation date is a confirmed planned end-of-life date or an estimated deprecation +// date. When 'Planned', the deprecation date represents a confirmed and communicated model end-of-life date. When 'Tentative', +// the deprecation date is an estimated timeline that may be subject to change. +type DeprecationStatus string + +const ( + DeprecationStatusPlanned DeprecationStatus = "Planned" + DeprecationStatusTentative DeprecationStatus = "Tentative" +) + +// PossibleDeprecationStatusValues returns the possible values for the DeprecationStatus const type. +func PossibleDeprecationStatusValues() []DeprecationStatus { + return []DeprecationStatus{ + DeprecationStatusPlanned, + DeprecationStatusTentative, + } +} + +// EncryptionScopeProvisioningState - Gets the status of the resource at the time the operation was called. +type EncryptionScopeProvisioningState string + +const ( + EncryptionScopeProvisioningStateAccepted EncryptionScopeProvisioningState = "Accepted" + EncryptionScopeProvisioningStateCanceled EncryptionScopeProvisioningState = "Canceled" + EncryptionScopeProvisioningStateCreating EncryptionScopeProvisioningState = "Creating" + EncryptionScopeProvisioningStateDeleting EncryptionScopeProvisioningState = "Deleting" + EncryptionScopeProvisioningStateFailed EncryptionScopeProvisioningState = "Failed" + EncryptionScopeProvisioningStateMoving EncryptionScopeProvisioningState = "Moving" + EncryptionScopeProvisioningStateSucceeded EncryptionScopeProvisioningState = "Succeeded" +) + +// PossibleEncryptionScopeProvisioningStateValues returns the possible values for the EncryptionScopeProvisioningState const type. +func PossibleEncryptionScopeProvisioningStateValues() []EncryptionScopeProvisioningState { + return []EncryptionScopeProvisioningState{ + EncryptionScopeProvisioningStateAccepted, + EncryptionScopeProvisioningStateCanceled, + EncryptionScopeProvisioningStateCreating, + EncryptionScopeProvisioningStateDeleting, + EncryptionScopeProvisioningStateFailed, + EncryptionScopeProvisioningStateMoving, + EncryptionScopeProvisioningStateSucceeded, + } +} + +// EncryptionScopeState - The encryptionScope state. +type EncryptionScopeState string + +const ( + EncryptionScopeStateDisabled EncryptionScopeState = "Disabled" + EncryptionScopeStateEnabled EncryptionScopeState = "Enabled" +) + +// PossibleEncryptionScopeStateValues returns the possible values for the EncryptionScopeState const type. +func PossibleEncryptionScopeStateValues() []EncryptionScopeState { + return []EncryptionScopeState{ + EncryptionScopeStateDisabled, + EncryptionScopeStateEnabled, + } +} + +// FirewallSKU - Firewall Sku used for FQDN Rules +type FirewallSKU string + +const ( + FirewallSKUBasic FirewallSKU = "Basic" + FirewallSKUStandard FirewallSKU = "Standard" +) + +// PossibleFirewallSKUValues returns the possible values for the FirewallSKU const type. +func PossibleFirewallSKUValues() []FirewallSKU { + return []FirewallSKU{ + FirewallSKUBasic, + FirewallSKUStandard, + } +} + +// HostingModel - Account hosting model. +type HostingModel string + +const ( + HostingModelConnectedContainer HostingModel = "ConnectedContainer" + HostingModelDisconnectedContainer HostingModel = "DisconnectedContainer" + HostingModelProvisionedWeb HostingModel = "ProvisionedWeb" + HostingModelWeb HostingModel = "Web" +) + +// PossibleHostingModelValues returns the possible values for the HostingModel const type. +func PossibleHostingModelValues() []HostingModel { + return []HostingModel{ + HostingModelConnectedContainer, + HostingModelDisconnectedContainer, + HostingModelProvisionedWeb, + HostingModelWeb, + } +} + +// IdentityKind - Specifies the kind of Entra identity described by this object. +type IdentityKind string + +const ( + // IdentityKindAgentBlueprint - Represents a class identity, used for agentic applications. + IdentityKindAgentBlueprint IdentityKind = "AgentBlueprint" + // IdentityKindAgentInstance - Represents an instance identity. + IdentityKindAgentInstance IdentityKind = "AgentInstance" + // IdentityKindAgenticUser - Represents an agentic instance identity with user-like traits. + IdentityKindAgenticUser IdentityKind = "AgenticUser" + // IdentityKindManaged - Represents a classic managed identity. + IdentityKindManaged IdentityKind = "Managed" + // IdentityKindNone - No identity. + IdentityKindNone IdentityKind = "None" +) + +// PossibleIdentityKindValues returns the possible values for the IdentityKind const type. +func PossibleIdentityKindValues() []IdentityKind { + return []IdentityKind{ + IdentityKindAgentBlueprint, + IdentityKindAgentInstance, + IdentityKindAgenticUser, + IdentityKindManaged, + IdentityKindNone, + } +} + +// IdentityManagementType - Enumeration of identity types, from the perspective of management. +type IdentityManagementType string + +const ( + // IdentityManagementTypeNone - No identity. + IdentityManagementTypeNone IdentityManagementType = "None" + // IdentityManagementTypeSystem - Platform-managed identity. + IdentityManagementTypeSystem IdentityManagementType = "System" + // IdentityManagementTypeUser - User-managed identity. + IdentityManagementTypeUser IdentityManagementType = "User" +) + +// PossibleIdentityManagementTypeValues returns the possible values for the IdentityManagementType const type. +func PossibleIdentityManagementTypeValues() []IdentityManagementType { + return []IdentityManagementType{ + IdentityManagementTypeNone, + IdentityManagementTypeSystem, + IdentityManagementTypeUser, + } +} + +// IdentityProvisioningState - Represents the provisioning state of an identity resource. +type IdentityProvisioningState string + +const ( + // IdentityProvisioningStateCanceled - Identity provisioning has been canceled. + IdentityProvisioningStateCanceled IdentityProvisioningState = "Canceled" + // IdentityProvisioningStateCreating - Identity is being created. + IdentityProvisioningStateCreating IdentityProvisioningState = "Creating" + // IdentityProvisioningStateDeleting - Identity is being deleted. + IdentityProvisioningStateDeleting IdentityProvisioningState = "Deleting" + // IdentityProvisioningStateFailed - Identity provisioning has failed. + IdentityProvisioningStateFailed IdentityProvisioningState = "Failed" + // IdentityProvisioningStateSucceeded - Identity has been successfully provisioned. + IdentityProvisioningStateSucceeded IdentityProvisioningState = "Succeeded" + // IdentityProvisioningStateUpdating - Identity is being updated. + IdentityProvisioningStateUpdating IdentityProvisioningState = "Updating" +) + +// PossibleIdentityProvisioningStateValues returns the possible values for the IdentityProvisioningState const type. +func PossibleIdentityProvisioningStateValues() []IdentityProvisioningState { + return []IdentityProvisioningState{ + IdentityProvisioningStateCanceled, + IdentityProvisioningStateCreating, + IdentityProvisioningStateDeleting, + IdentityProvisioningStateFailed, + IdentityProvisioningStateSucceeded, + IdentityProvisioningStateUpdating, + } +} + +// IsolationMode - Isolation mode for the managed network of a cognitive services account. +type IsolationMode string + +const ( + IsolationModeAllowInternetOutbound IsolationMode = "AllowInternetOutbound" + IsolationModeAllowOnlyApprovedOutbound IsolationMode = "AllowOnlyApprovedOutbound" + IsolationModeDisabled IsolationMode = "Disabled" +) + +// PossibleIsolationModeValues returns the possible values for the IsolationMode const type. +func PossibleIsolationModeValues() []IsolationMode { + return []IsolationMode{ + IsolationModeAllowInternetOutbound, + IsolationModeAllowOnlyApprovedOutbound, + IsolationModeDisabled, + } +} + +// KeyName - key name to generate (Key1|Key2) +type KeyName string + +const ( + KeyNameKey1 KeyName = "Key1" + KeyNameKey2 KeyName = "Key2" +) + +// PossibleKeyNameValues returns the possible values for the KeyName const type. +func PossibleKeyNameValues() []KeyName { + return []KeyName{ + KeyNameKey1, + KeyNameKey2, + } +} + +// KeySource - Enumerates the possible value of keySource for Encryption +type KeySource string + +const ( + KeySourceMicrosoftCognitiveServices KeySource = "Microsoft.CognitiveServices" + KeySourceMicrosoftKeyVault KeySource = "Microsoft.KeyVault" +) + +// PossibleKeySourceValues returns the possible values for the KeySource const type. +func PossibleKeySourceValues() []KeySource { + return []KeySource{ + KeySourceMicrosoftCognitiveServices, + KeySourceMicrosoftKeyVault, + } +} + +// ManagedNetworkKind - The Kind of the managed network. Users can switch from V1 to V2 for granular access controls, but +// cannot switch back to V1 once V2 is enabled. +type ManagedNetworkKind string + +const ( + ManagedNetworkKindV1 ManagedNetworkKind = "V1" + ManagedNetworkKindV2 ManagedNetworkKind = "V2" +) + +// PossibleManagedNetworkKindValues returns the possible values for the ManagedNetworkKind const type. +func PossibleManagedNetworkKindValues() []ManagedNetworkKind { + return []ManagedNetworkKind{ + ManagedNetworkKindV1, + ManagedNetworkKindV2, + } +} + +type ManagedNetworkProvisioningState string + +const ( + ManagedNetworkProvisioningStateDeferred ManagedNetworkProvisioningState = "Deferred" + ManagedNetworkProvisioningStateDeleted ManagedNetworkProvisioningState = "Deleted" + ManagedNetworkProvisioningStateDeleting ManagedNetworkProvisioningState = "Deleting" + ManagedNetworkProvisioningStateFailed ManagedNetworkProvisioningState = "Failed" + ManagedNetworkProvisioningStateSucceeded ManagedNetworkProvisioningState = "Succeeded" + ManagedNetworkProvisioningStateUpdating ManagedNetworkProvisioningState = "Updating" +) + +// PossibleManagedNetworkProvisioningStateValues returns the possible values for the ManagedNetworkProvisioningState const type. +func PossibleManagedNetworkProvisioningStateValues() []ManagedNetworkProvisioningState { + return []ManagedNetworkProvisioningState{ + ManagedNetworkProvisioningStateDeferred, + ManagedNetworkProvisioningStateDeleted, + ManagedNetworkProvisioningStateDeleting, + ManagedNetworkProvisioningStateFailed, + ManagedNetworkProvisioningStateSucceeded, + ManagedNetworkProvisioningStateUpdating, + } +} + +// ManagedNetworkStatus - Status for the managed network of a cognitive services account. +type ManagedNetworkStatus string + +const ( + ManagedNetworkStatusActive ManagedNetworkStatus = "Active" + ManagedNetworkStatusInactive ManagedNetworkStatus = "Inactive" +) + +// PossibleManagedNetworkStatusValues returns the possible values for the ManagedNetworkStatus const type. +func PossibleManagedNetworkStatusValues() []ManagedNetworkStatus { + return []ManagedNetworkStatus{ + ManagedNetworkStatusActive, + ManagedNetworkStatusInactive, + } +} + +type ManagedPERequirement string + +const ( + ManagedPERequirementNotApplicable ManagedPERequirement = "NotApplicable" + ManagedPERequirementNotRequired ManagedPERequirement = "NotRequired" + ManagedPERequirementRequired ManagedPERequirement = "Required" +) + +// PossibleManagedPERequirementValues returns the possible values for the ManagedPERequirement const type. +func PossibleManagedPERequirementValues() []ManagedPERequirement { + return []ManagedPERequirement{ + ManagedPERequirementNotApplicable, + ManagedPERequirementNotRequired, + ManagedPERequirementRequired, + } +} + +type ManagedPEStatus string + +const ( + ManagedPEStatusActive ManagedPEStatus = "Active" + ManagedPEStatusInactive ManagedPEStatus = "Inactive" + ManagedPEStatusNotApplicable ManagedPEStatus = "NotApplicable" +) + +// PossibleManagedPEStatusValues returns the possible values for the ManagedPEStatus const type. +func PossibleManagedPEStatusValues() []ManagedPEStatus { + return []ManagedPEStatus{ + ManagedPEStatusActive, + ManagedPEStatusInactive, + ManagedPEStatusNotApplicable, + } +} + +// ModelLifecycleStatus - Model lifecycle status. +type ModelLifecycleStatus string + +const ( + // ModelLifecycleStatusDeprecated - Model has been deprecated, also known as retired, and is no longer supported. Inference + // calls to deployments of models in this lifecycle state will return 410 errors. + ModelLifecycleStatusDeprecated ModelLifecycleStatus = "Deprecated" + // ModelLifecycleStatusDeprecating - Model is being deprecated and will be removed in the future. Only customers with existing + // deployments can create new deployments with this model. + ModelLifecycleStatusDeprecating ModelLifecycleStatus = "Deprecating" + // ModelLifecycleStatusGenerallyAvailable - Model is generally available for production use. + ModelLifecycleStatusGenerallyAvailable ModelLifecycleStatus = "GenerallyAvailable" + // ModelLifecycleStatusLegacy - Model is a legacy version that is no longer recommended for use. Customers should migrate + // to newer models. Check replacementConfig for upgrade information. + ModelLifecycleStatusLegacy ModelLifecycleStatus = "Legacy" + // ModelLifecycleStatusPreview - Model is in preview and may be subject to changes. + ModelLifecycleStatusPreview ModelLifecycleStatus = "Preview" + // ModelLifecycleStatusStable - Legacy state. Replaced with GenerallyAvailable going forward. + ModelLifecycleStatusStable ModelLifecycleStatus = "Stable" +) + +// PossibleModelLifecycleStatusValues returns the possible values for the ModelLifecycleStatus const type. +func PossibleModelLifecycleStatusValues() []ModelLifecycleStatus { + return []ModelLifecycleStatus{ + ModelLifecycleStatusDeprecated, + ModelLifecycleStatusDeprecating, + ModelLifecycleStatusGenerallyAvailable, + ModelLifecycleStatusLegacy, + ModelLifecycleStatusPreview, + ModelLifecycleStatusStable, + } +} + +// NetworkRuleAction - The default action when no rule from ipRules and from virtualNetworkRules match. This is only used +// after the bypass property has been evaluated. +type NetworkRuleAction string + +const ( + NetworkRuleActionAllow NetworkRuleAction = "Allow" + NetworkRuleActionDeny NetworkRuleAction = "Deny" +) + +// PossibleNetworkRuleActionValues returns the possible values for the NetworkRuleAction const type. +func PossibleNetworkRuleActionValues() []NetworkRuleAction { + return []NetworkRuleAction{ + NetworkRuleActionAllow, + NetworkRuleActionDeny, + } +} + +// NspAccessRuleDirection - Direction of Access Rule +type NspAccessRuleDirection string + +const ( + NspAccessRuleDirectionInbound NspAccessRuleDirection = "Inbound" + NspAccessRuleDirectionOutbound NspAccessRuleDirection = "Outbound" +) + +// PossibleNspAccessRuleDirectionValues returns the possible values for the NspAccessRuleDirection const type. +func PossibleNspAccessRuleDirectionValues() []NspAccessRuleDirection { + return []NspAccessRuleDirection{ + NspAccessRuleDirectionInbound, + NspAccessRuleDirectionOutbound, + } +} + +// Origin - The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default +// value is "user,system" +type Origin string + +const ( + // OriginSystem - Indicates the operation is initiated by a system. + OriginSystem Origin = "system" + // OriginUser - Indicates the operation is initiated by a user. + OriginUser Origin = "user" + // OriginUserSystem - Indicates the operation is initiated by a user or system. + OriginUserSystem Origin = "user,system" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginSystem, + OriginUser, + OriginUserSystem, + } +} + +// PrivateEndpointConnectionProvisioningState - The current provisioning state. +type PrivateEndpointConnectionProvisioningState string + +const ( + // PrivateEndpointConnectionProvisioningStateCreating - Connection is being created + PrivateEndpointConnectionProvisioningStateCreating PrivateEndpointConnectionProvisioningState = "Creating" + // PrivateEndpointConnectionProvisioningStateDeleting - Connection is being deleted + PrivateEndpointConnectionProvisioningStateDeleting PrivateEndpointConnectionProvisioningState = "Deleting" + // PrivateEndpointConnectionProvisioningStateFailed - Connection provisioning has failed + PrivateEndpointConnectionProvisioningStateFailed PrivateEndpointConnectionProvisioningState = "Failed" + // PrivateEndpointConnectionProvisioningStateSucceeded - Connection has been provisioned + PrivateEndpointConnectionProvisioningStateSucceeded PrivateEndpointConnectionProvisioningState = "Succeeded" +) + +// PossiblePrivateEndpointConnectionProvisioningStateValues returns the possible values for the PrivateEndpointConnectionProvisioningState const type. +func PossiblePrivateEndpointConnectionProvisioningStateValues() []PrivateEndpointConnectionProvisioningState { + return []PrivateEndpointConnectionProvisioningState{ + PrivateEndpointConnectionProvisioningStateCreating, + PrivateEndpointConnectionProvisioningStateDeleting, + PrivateEndpointConnectionProvisioningStateFailed, + PrivateEndpointConnectionProvisioningStateSucceeded, + } +} + +// PrivateEndpointServiceConnectionStatus - The private endpoint connection status. +type PrivateEndpointServiceConnectionStatus string + +const ( + // PrivateEndpointServiceConnectionStatusApproved - Connection approved + PrivateEndpointServiceConnectionStatusApproved PrivateEndpointServiceConnectionStatus = "Approved" + // PrivateEndpointServiceConnectionStatusPending - Connection waiting for approval or rejection + PrivateEndpointServiceConnectionStatusPending PrivateEndpointServiceConnectionStatus = "Pending" + // PrivateEndpointServiceConnectionStatusRejected - Connection Rejected + PrivateEndpointServiceConnectionStatusRejected PrivateEndpointServiceConnectionStatus = "Rejected" +) + +// PossiblePrivateEndpointServiceConnectionStatusValues returns the possible values for the PrivateEndpointServiceConnectionStatus const type. +func PossiblePrivateEndpointServiceConnectionStatusValues() []PrivateEndpointServiceConnectionStatus { + return []PrivateEndpointServiceConnectionStatus{ + PrivateEndpointServiceConnectionStatusApproved, + PrivateEndpointServiceConnectionStatusPending, + PrivateEndpointServiceConnectionStatusRejected, + } +} + +// ProvisioningState - Gets the status of the cognitive services account at the time the operation was called. +type ProvisioningState string + +const ( + ProvisioningStateAccepted ProvisioningState = "Accepted" + ProvisioningStateCanceled ProvisioningState = "Canceled" + ProvisioningStateCreating ProvisioningState = "Creating" + ProvisioningStateDeleting ProvisioningState = "Deleting" + ProvisioningStateFailed ProvisioningState = "Failed" + ProvisioningStateMoving ProvisioningState = "Moving" + ProvisioningStateResolvingDNS ProvisioningState = "ResolvingDNS" + ProvisioningStateSucceeded ProvisioningState = "Succeeded" +) + +// PossibleProvisioningStateValues returns the possible values for the ProvisioningState const type. +func PossibleProvisioningStateValues() []ProvisioningState { + return []ProvisioningState{ + ProvisioningStateAccepted, + ProvisioningStateCanceled, + ProvisioningStateCreating, + ProvisioningStateDeleting, + ProvisioningStateFailed, + ProvisioningStateMoving, + ProvisioningStateResolvingDNS, + ProvisioningStateSucceeded, + } +} + +// PublicNetworkAccess - Whether or not public endpoint access is allowed for this account. +type PublicNetworkAccess string + +const ( + PublicNetworkAccessDisabled PublicNetworkAccess = "Disabled" + PublicNetworkAccessEnabled PublicNetworkAccess = "Enabled" +) + +// PossiblePublicNetworkAccessValues returns the possible values for the PublicNetworkAccess const type. +func PossiblePublicNetworkAccessValues() []PublicNetworkAccess { + return []PublicNetworkAccess{ + PublicNetworkAccessDisabled, + PublicNetworkAccessEnabled, + } +} + +// QuotaUsageStatus - Cognitive Services account quota usage status. +type QuotaUsageStatus string + +const ( + QuotaUsageStatusBlocked QuotaUsageStatus = "Blocked" + QuotaUsageStatusInOverage QuotaUsageStatus = "InOverage" + QuotaUsageStatusIncluded QuotaUsageStatus = "Included" + QuotaUsageStatusUnknown QuotaUsageStatus = "Unknown" +) + +// PossibleQuotaUsageStatusValues returns the possible values for the QuotaUsageStatus const type. +func PossibleQuotaUsageStatusValues() []QuotaUsageStatus { + return []QuotaUsageStatus{ + QuotaUsageStatusBlocked, + QuotaUsageStatusInOverage, + QuotaUsageStatusIncluded, + QuotaUsageStatusUnknown, + } +} + +// RaiActionType - The action types to apply to the content filters +type RaiActionType string + +const ( + RaiActionTypeANNOTATING RaiActionType = "ANNOTATING" + RaiActionTypeBLOCKING RaiActionType = "BLOCKING" + RaiActionTypeHITL RaiActionType = "HITL" + RaiActionTypeNone RaiActionType = "None" + RaiActionTypeRETRY RaiActionType = "RETRY" +) + +// PossibleRaiActionTypeValues returns the possible values for the RaiActionType const type. +func PossibleRaiActionTypeValues() []RaiActionType { + return []RaiActionType{ + RaiActionTypeANNOTATING, + RaiActionTypeBLOCKING, + RaiActionTypeHITL, + RaiActionTypeNone, + RaiActionTypeRETRY, + } +} + +// RaiPolicyContentSource - Content source to apply the Content Filters. +type RaiPolicyContentSource string + +const ( + RaiPolicyContentSourceCompletion RaiPolicyContentSource = "Completion" + RaiPolicyContentSourcePostRun RaiPolicyContentSource = "PostRun" + RaiPolicyContentSourcePostToolCall RaiPolicyContentSource = "PostToolCall" + RaiPolicyContentSourcePreRun RaiPolicyContentSource = "PreRun" + RaiPolicyContentSourcePreToolCall RaiPolicyContentSource = "PreToolCall" + RaiPolicyContentSourcePrompt RaiPolicyContentSource = "Prompt" +) + +// PossibleRaiPolicyContentSourceValues returns the possible values for the RaiPolicyContentSource const type. +func PossibleRaiPolicyContentSourceValues() []RaiPolicyContentSource { + return []RaiPolicyContentSource{ + RaiPolicyContentSourceCompletion, + RaiPolicyContentSourcePostRun, + RaiPolicyContentSourcePostToolCall, + RaiPolicyContentSourcePreRun, + RaiPolicyContentSourcePreToolCall, + RaiPolicyContentSourcePrompt, + } +} + +// RaiPolicyMode - Rai policy mode. The enum value mapping is as below: Default = 0, Deferred=1, Blocking=2, Asynchronous_filter +// =3. Please use 'Asynchronous_filter' after 2025-06-01. It is the same as 'Deferred' in previous version. +type RaiPolicyMode string + +const ( + RaiPolicyModeAsynchronousFilter RaiPolicyMode = "Asynchronous_filter" + RaiPolicyModeBlocking RaiPolicyMode = "Blocking" + RaiPolicyModeDefault RaiPolicyMode = "Default" + RaiPolicyModeDeferred RaiPolicyMode = "Deferred" +) + +// PossibleRaiPolicyModeValues returns the possible values for the RaiPolicyMode const type. +func PossibleRaiPolicyModeValues() []RaiPolicyMode { + return []RaiPolicyMode{ + RaiPolicyModeAsynchronousFilter, + RaiPolicyModeBlocking, + RaiPolicyModeDefault, + RaiPolicyModeDeferred, + } +} + +// RaiPolicyType - Content Filters policy type. +type RaiPolicyType string + +const ( + RaiPolicyTypeSystemManaged RaiPolicyType = "SystemManaged" + RaiPolicyTypeUserManaged RaiPolicyType = "UserManaged" +) + +// PossibleRaiPolicyTypeValues returns the possible values for the RaiPolicyType const type. +func PossibleRaiPolicyTypeValues() []RaiPolicyType { + return []RaiPolicyType{ + RaiPolicyTypeSystemManaged, + RaiPolicyTypeUserManaged, + } +} + +// ResourceIdentityType - The identity type. +type ResourceIdentityType string + +const ( + ResourceIdentityTypeNone ResourceIdentityType = "None" + ResourceIdentityTypeSystemAssigned ResourceIdentityType = "SystemAssigned" + ResourceIdentityTypeSystemAssignedUserAssigned ResourceIdentityType = "SystemAssigned, UserAssigned" + ResourceIdentityTypeUserAssigned ResourceIdentityType = "UserAssigned" +) + +// PossibleResourceIdentityTypeValues returns the possible values for the ResourceIdentityType const type. +func PossibleResourceIdentityTypeValues() []ResourceIdentityType { + return []ResourceIdentityType{ + ResourceIdentityTypeNone, + ResourceIdentityTypeSystemAssigned, + ResourceIdentityTypeSystemAssignedUserAssigned, + ResourceIdentityTypeUserAssigned, + } +} + +// ResourceSKURestrictionsReasonCode - The reason for restriction. +type ResourceSKURestrictionsReasonCode string + +const ( + ResourceSKURestrictionsReasonCodeNotAvailableForSubscription ResourceSKURestrictionsReasonCode = "NotAvailableForSubscription" + ResourceSKURestrictionsReasonCodeQuotaID ResourceSKURestrictionsReasonCode = "QuotaId" +) + +// PossibleResourceSKURestrictionsReasonCodeValues returns the possible values for the ResourceSKURestrictionsReasonCode const type. +func PossibleResourceSKURestrictionsReasonCodeValues() []ResourceSKURestrictionsReasonCode { + return []ResourceSKURestrictionsReasonCode{ + ResourceSKURestrictionsReasonCodeNotAvailableForSubscription, + ResourceSKURestrictionsReasonCodeQuotaID, + } +} + +// ResourceSKURestrictionsType - The type of restrictions. +type ResourceSKURestrictionsType string + +const ( + ResourceSKURestrictionsTypeLocation ResourceSKURestrictionsType = "Location" + ResourceSKURestrictionsTypeZone ResourceSKURestrictionsType = "Zone" +) + +// PossibleResourceSKURestrictionsTypeValues returns the possible values for the ResourceSKURestrictionsType const type. +func PossibleResourceSKURestrictionsTypeValues() []ResourceSKURestrictionsType { + return []ResourceSKURestrictionsType{ + ResourceSKURestrictionsTypeLocation, + ResourceSKURestrictionsTypeZone, + } +} + +// RoutingMethods - Multiregion routing methods. +type RoutingMethods string + +const ( + RoutingMethodsPerformance RoutingMethods = "Performance" + RoutingMethodsPriority RoutingMethods = "Priority" + RoutingMethodsWeighted RoutingMethods = "Weighted" +) + +// PossibleRoutingMethodsValues returns the possible values for the RoutingMethods const type. +func PossibleRoutingMethodsValues() []RoutingMethods { + return []RoutingMethods{ + RoutingMethodsPerformance, + RoutingMethodsPriority, + RoutingMethodsWeighted, + } +} + +// RoutingMode - The model-router routing mode that determines how requests are distributed across models. +type RoutingMode string + +const ( + // RoutingModeBalanced - Balance cost and quality when routing requests across models. + RoutingModeBalanced RoutingMode = "balanced" + // RoutingModeCost - Route requests to minimize cost while meeting performance requirements. + RoutingModeCost RoutingMode = "cost" + // RoutingModeQuality - Route requests to maximize quality regardless of cost. + RoutingModeQuality RoutingMode = "quality" +) + +// PossibleRoutingModeValues returns the possible values for the RoutingMode const type. +func PossibleRoutingModeValues() []RoutingMode { + return []RoutingMode{ + RoutingModeBalanced, + RoutingModeCost, + RoutingModeQuality, + } +} + +// RuleAction - The action enum for a managed network outbound rule. +type RuleAction string + +const ( + RuleActionAllow RuleAction = "Allow" + RuleActionDeny RuleAction = "Deny" +) + +// PossibleRuleActionValues returns the possible values for the RuleAction const type. +func PossibleRuleActionValues() []RuleAction { + return []RuleAction{ + RuleActionAllow, + RuleActionDeny, + } +} + +// RuleCategory - Category of a managed network Outbound Rule of a cognitive services account. +type RuleCategory string + +const ( + RuleCategoryDependency RuleCategory = "Dependency" + RuleCategoryRecommended RuleCategory = "Recommended" + RuleCategoryRequired RuleCategory = "Required" + RuleCategoryUserDefined RuleCategory = "UserDefined" +) + +// PossibleRuleCategoryValues returns the possible values for the RuleCategory const type. +func PossibleRuleCategoryValues() []RuleCategory { + return []RuleCategory{ + RuleCategoryDependency, + RuleCategoryRecommended, + RuleCategoryRequired, + RuleCategoryUserDefined, + } +} + +// RuleStatus - Type of a managed network Outbound Rule of a cognitive services account. +type RuleStatus string + +const ( + RuleStatusActive RuleStatus = "Active" + RuleStatusDeleting RuleStatus = "Deleting" + RuleStatusFailed RuleStatus = "Failed" + RuleStatusInactive RuleStatus = "Inactive" + RuleStatusProvisioning RuleStatus = "Provisioning" +) + +// PossibleRuleStatusValues returns the possible values for the RuleStatus const type. +func PossibleRuleStatusValues() []RuleStatus { + return []RuleStatus{ + RuleStatusActive, + RuleStatusDeleting, + RuleStatusFailed, + RuleStatusInactive, + RuleStatusProvisioning, + } +} + +// RuleType - Type of a managed network Outbound Rule of a cognitive services account. +type RuleType string + +const ( + RuleTypeFQDN RuleType = "FQDN" + RuleTypePrivateEndpoint RuleType = "PrivateEndpoint" + RuleTypeServiceTag RuleType = "ServiceTag" +) + +// PossibleRuleTypeValues returns the possible values for the RuleType const type. +func PossibleRuleTypeValues() []RuleType { + return []RuleType{ + RuleTypeFQDN, + RuleTypePrivateEndpoint, + RuleTypeServiceTag, + } +} + +// SKUTier - This field is required to be implemented by the Resource Provider if the service has more than one tier, but +// is not required on a PUT. +type SKUTier string + +const ( + SKUTierBasic SKUTier = "Basic" + SKUTierEnterprise SKUTier = "Enterprise" + SKUTierFree SKUTier = "Free" + SKUTierPremium SKUTier = "Premium" + SKUTierStandard SKUTier = "Standard" +) + +// PossibleSKUTierValues returns the possible values for the SKUTier const type. +func PossibleSKUTierValues() []SKUTier { + return []SKUTier{ + SKUTierBasic, + SKUTierEnterprise, + SKUTierFree, + SKUTierPremium, + SKUTierStandard, + } +} + +// ScenarioType - Specifies what features in AI Foundry network injection applies to. Currently only supports 'agent' for +// agent scenarios. 'none' means no network injection. +type ScenarioType string + +const ( + ScenarioTypeAgent ScenarioType = "agent" + ScenarioTypeNone ScenarioType = "none" +) + +// PossibleScenarioTypeValues returns the possible values for the ScenarioType const type. +func PossibleScenarioTypeValues() []ScenarioType { + return []ScenarioType{ + ScenarioTypeAgent, + ScenarioTypeNone, + } +} + +// ServiceTier - The service tier for the deployment. Determines the pricing and performance level for request processing. +// Use 'Default' for standard pricing or 'Priority' for higher-priority processing with premium pricing. Note: Pause operations +// are only supported on Standard, DataZoneStandard, and GlobalStandard SKUs. +type ServiceTier string + +const ( + // ServiceTierDefault - Default service tier meaning the request will be processed with the standard pricing and performance + // for the selected model. + ServiceTierDefault ServiceTier = "Default" + // ServiceTierPriority - Priority service tier meaning the request will be processed with higher pricing and performance for + // the selected model. + ServiceTierPriority ServiceTier = "Priority" +) + +// PossibleServiceTierValues returns the possible values for the ServiceTier const type. +func PossibleServiceTierValues() []ServiceTier { + return []ServiceTier{ + ServiceTierDefault, + ServiceTierPriority, + } +} + +// TierUpgradePolicy - Gets the tier upgrade policy for the subscription. +type TierUpgradePolicy string + +const ( + TierUpgradePolicyNoAutoUpgrade TierUpgradePolicy = "NoAutoUpgrade" + TierUpgradePolicyOnceUpgradeIsAvailable TierUpgradePolicy = "OnceUpgradeIsAvailable" +) + +// PossibleTierUpgradePolicyValues returns the possible values for the TierUpgradePolicy const type. +func PossibleTierUpgradePolicyValues() []TierUpgradePolicy { + return []TierUpgradePolicy{ + TierUpgradePolicyNoAutoUpgrade, + TierUpgradePolicyOnceUpgradeIsAvailable, + } +} + +// TrafficRoutingProtocol - Traffic routing protocol, used to distribute an application's inbound traffic to its deployments. +type TrafficRoutingProtocol string + +const ( + // TrafficRoutingProtocolFixedRatio - Percentage based routing + TrafficRoutingProtocolFixedRatio TrafficRoutingProtocol = "FixedRatio" +) + +// PossibleTrafficRoutingProtocolValues returns the possible values for the TrafficRoutingProtocol const type. +func PossibleTrafficRoutingProtocolValues() []TrafficRoutingProtocol { + return []TrafficRoutingProtocol{ + TrafficRoutingProtocolFixedRatio, + } +} + +// UnitType - The unit of the metric. +type UnitType string + +const ( + UnitTypeBytes UnitType = "Bytes" + UnitTypeBytesPerSecond UnitType = "BytesPerSecond" + UnitTypeCount UnitType = "Count" + UnitTypeCountPerSecond UnitType = "CountPerSecond" + UnitTypeMilliseconds UnitType = "Milliseconds" + UnitTypePercent UnitType = "Percent" + UnitTypeSeconds UnitType = "Seconds" +) + +// PossibleUnitTypeValues returns the possible values for the UnitType const type. +func PossibleUnitTypeValues() []UnitType { + return []UnitType{ + UnitTypeBytes, + UnitTypeBytesPerSecond, + UnitTypeCount, + UnitTypeCountPerSecond, + UnitTypeMilliseconds, + UnitTypePercent, + UnitTypeSeconds, + } +} + +// UpgradeAvailabilityStatus - Specifies whether an upgrade to the next quota tier is available. +type UpgradeAvailabilityStatus string + +const ( + UpgradeAvailabilityStatusAvailable UpgradeAvailabilityStatus = "Available" + UpgradeAvailabilityStatusNotAvailable UpgradeAvailabilityStatus = "NotAvailable" +) + +// PossibleUpgradeAvailabilityStatusValues returns the possible values for the UpgradeAvailabilityStatus const type. +func PossibleUpgradeAvailabilityStatusValues() []UpgradeAvailabilityStatus { + return []UpgradeAvailabilityStatus{ + UpgradeAvailabilityStatusAvailable, + UpgradeAvailabilityStatusNotAvailable, + } +} diff --git a/test/local/armcognitiveservices/zz_defenderforaisettings_client.go b/test/local/armcognitiveservices/zz_defenderforaisettings_client.go new file mode 100644 index 000000000000..1bbf39a39883 --- /dev/null +++ b/test/local/armcognitiveservices/zz_defenderforaisettings_client.go @@ -0,0 +1,319 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// DefenderForAISettingsClient contains the methods for the DefenderForAISettings group. +// Don't use this type directly, use NewDefenderForAISettingsClient() instead. +// +// Generated from API version 2026-05-01 +type DefenderForAISettingsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDefenderForAISettingsClient creates a new instance of DefenderForAISettingsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewDefenderForAISettingsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DefenderForAISettingsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DefenderForAISettingsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Creates or Updates the specified Defender for AI setting. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - defenderForAISettingName - The name of the defender for AI setting. +// - defenderForAISettings - Properties describing the Defender for AI setting. +// - options - DefenderForAISettingsClientCreateOrUpdateOptions contains the optional parameters for the DefenderForAISettingsClient.CreateOrUpdate +// method. +func (client *DefenderForAISettingsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, defenderForAISettingName string, defenderForAISettings DefenderForAISetting, options *DefenderForAISettingsClientCreateOrUpdateOptions) (DefenderForAISettingsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "DefenderForAISettingsClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, defenderForAISettingName, defenderForAISettings, options) + if err != nil { + return DefenderForAISettingsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DefenderForAISettingsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return DefenderForAISettingsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *DefenderForAISettingsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, defenderForAISettingName string, defenderForAISettings DefenderForAISetting, _ *DefenderForAISettingsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/defenderForAISettings/{defenderForAISettingName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if defenderForAISettingName == "" { + return nil, errors.New("parameter defenderForAISettingName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{defenderForAISettingName}", url.PathEscape(defenderForAISettingName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, defenderForAISettings); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *DefenderForAISettingsClient) createOrUpdateHandleResponse(resp *http.Response) (DefenderForAISettingsClientCreateOrUpdateResponse, error) { + result := DefenderForAISettingsClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DefenderForAISetting); err != nil { + return DefenderForAISettingsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Get - Gets the specified Defender for AI setting by name. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - defenderForAISettingName - The name of the defender for AI setting. +// - options - DefenderForAISettingsClientGetOptions contains the optional parameters for the DefenderForAISettingsClient.Get +// method. +func (client *DefenderForAISettingsClient) Get(ctx context.Context, resourceGroupName string, accountName string, defenderForAISettingName string, options *DefenderForAISettingsClientGetOptions) (DefenderForAISettingsClientGetResponse, error) { + var err error + const operationName = "DefenderForAISettingsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, defenderForAISettingName, options) + if err != nil { + return DefenderForAISettingsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DefenderForAISettingsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DefenderForAISettingsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DefenderForAISettingsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, defenderForAISettingName string, _ *DefenderForAISettingsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/defenderForAISettings/{defenderForAISettingName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if defenderForAISettingName == "" { + return nil, errors.New("parameter defenderForAISettingName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{defenderForAISettingName}", url.PathEscape(defenderForAISettingName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DefenderForAISettingsClient) getHandleResponse(resp *http.Response) (DefenderForAISettingsClientGetResponse, error) { + result := DefenderForAISettingsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DefenderForAISetting); err != nil { + return DefenderForAISettingsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists the Defender for AI settings. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - options - DefenderForAISettingsClientListOptions contains the optional parameters for the DefenderForAISettingsClient.NewListPager +// method. +func (client *DefenderForAISettingsClient) NewListPager(resourceGroupName string, accountName string, options *DefenderForAISettingsClientListOptions) *runtime.Pager[DefenderForAISettingsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[DefenderForAISettingsClientListResponse]{ + More: func(page DefenderForAISettingsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DefenderForAISettingsClientListResponse) (DefenderForAISettingsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DefenderForAISettingsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, options) + }, nil) + if err != nil { + return DefenderForAISettingsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *DefenderForAISettingsClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, _ *DefenderForAISettingsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/defenderForAISettings" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *DefenderForAISettingsClient) listHandleResponse(resp *http.Response) (DefenderForAISettingsClientListResponse, error) { + result := DefenderForAISettingsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DefenderForAISettingResult); err != nil { + return DefenderForAISettingsClientListResponse{}, err + } + return result, nil +} + +// Update - Updates the specified Defender for AI setting. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - defenderForAISettingName - The name of the defender for AI setting. +// - defenderForAISettings - Properties describing the Defender for AI setting. +// - options - DefenderForAISettingsClientUpdateOptions contains the optional parameters for the DefenderForAISettingsClient.Update +// method. +func (client *DefenderForAISettingsClient) Update(ctx context.Context, resourceGroupName string, accountName string, defenderForAISettingName string, defenderForAISettings DefenderForAISetting, options *DefenderForAISettingsClientUpdateOptions) (DefenderForAISettingsClientUpdateResponse, error) { + var err error + const operationName = "DefenderForAISettingsClient.Update" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, accountName, defenderForAISettingName, defenderForAISettings, options) + if err != nil { + return DefenderForAISettingsClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DefenderForAISettingsClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DefenderForAISettingsClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *DefenderForAISettingsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, defenderForAISettingName string, defenderForAISettings DefenderForAISetting, _ *DefenderForAISettingsClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/defenderForAISettings/{defenderForAISettingName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if defenderForAISettingName == "" { + return nil, errors.New("parameter defenderForAISettingName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{defenderForAISettingName}", url.PathEscape(defenderForAISettingName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, defenderForAISettings); err != nil { + return nil, err + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *DefenderForAISettingsClient) updateHandleResponse(resp *http.Response) (DefenderForAISettingsClientUpdateResponse, error) { + result := DefenderForAISettingsClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DefenderForAISetting); err != nil { + return DefenderForAISettingsClientUpdateResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_deletedaccounts_client.go b/test/local/armcognitiveservices/zz_deletedaccounts_client.go new file mode 100644 index 000000000000..693211309b1a --- /dev/null +++ b/test/local/armcognitiveservices/zz_deletedaccounts_client.go @@ -0,0 +1,238 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// DeletedAccountsClient contains the methods for the DeletedAccounts group. +// Don't use this type directly, use NewDeletedAccountsClient() instead. +// +// Generated from API version 2026-05-01 +type DeletedAccountsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDeletedAccountsClient creates a new instance of DeletedAccountsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewDeletedAccountsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DeletedAccountsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DeletedAccountsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Returns a Cognitive Services account specified by the parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// - location - The location name. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - options - DeletedAccountsClientGetOptions contains the optional parameters for the DeletedAccountsClient.Get method. +func (client *DeletedAccountsClient) Get(ctx context.Context, location string, resourceGroupName string, accountName string, options *DeletedAccountsClientGetOptions) (DeletedAccountsClientGetResponse, error) { + var err error + const operationName = "DeletedAccountsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, location, resourceGroupName, accountName, options) + if err != nil { + return DeletedAccountsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DeletedAccountsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DeletedAccountsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DeletedAccountsClient) getCreateRequest(ctx context.Context, location string, resourceGroupName string, accountName string, _ *DeletedAccountsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/resourceGroups/{resourceGroupName}/deletedAccounts/{accountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DeletedAccountsClient) getHandleResponse(resp *http.Response) (DeletedAccountsClientGetResponse, error) { + result := DeletedAccountsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Account); err != nil { + return DeletedAccountsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Returns all the resources of a particular type belonging to a subscription. +// - options - DeletedAccountsClientListOptions contains the optional parameters for the DeletedAccountsClient.NewListPager +// method. +func (client *DeletedAccountsClient) NewListPager(options *DeletedAccountsClientListOptions) *runtime.Pager[DeletedAccountsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[DeletedAccountsClientListResponse]{ + More: func(page DeletedAccountsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DeletedAccountsClientListResponse) (DeletedAccountsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DeletedAccountsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return DeletedAccountsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *DeletedAccountsClient) listCreateRequest(ctx context.Context, _ *DeletedAccountsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/deletedAccounts" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *DeletedAccountsClient) listHandleResponse(resp *http.Response) (DeletedAccountsClientListResponse, error) { + result := DeletedAccountsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AccountListResult); err != nil { + return DeletedAccountsClientListResponse{}, err + } + return result, nil +} + +// BeginPurge - Deletes a Cognitive Services account from the resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// - location - The location name. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - options - DeletedAccountsClientBeginPurgeOptions contains the optional parameters for the DeletedAccountsClient.BeginPurge +// method. +func (client *DeletedAccountsClient) BeginPurge(ctx context.Context, location string, resourceGroupName string, accountName string, options *DeletedAccountsClientBeginPurgeOptions) (*runtime.Poller[DeletedAccountsClientPurgeResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.purge(ctx, location, resourceGroupName, accountName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DeletedAccountsClientPurgeResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DeletedAccountsClientPurgeResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Purge - Deletes a Cognitive Services account from the resource group. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *DeletedAccountsClient) purge(ctx context.Context, location string, resourceGroupName string, accountName string, options *DeletedAccountsClientBeginPurgeOptions) (*http.Response, error) { + var err error + const operationName = "DeletedAccountsClient.BeginPurge" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.purgeCreateRequest(ctx, location, resourceGroupName, accountName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// purgeCreateRequest creates the Purge request. +func (client *DeletedAccountsClient) purgeCreateRequest(ctx context.Context, location string, resourceGroupName string, accountName string, _ *DeletedAccountsClientBeginPurgeOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/resourceGroups/{resourceGroupName}/deletedAccounts/{accountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/local/armcognitiveservices/zz_deployments_client.go b/test/local/armcognitiveservices/zz_deployments_client.go new file mode 100644 index 000000000000..142554d23c39 --- /dev/null +++ b/test/local/armcognitiveservices/zz_deployments_client.go @@ -0,0 +1,618 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// DeploymentsClient contains the methods for the Deployments group. +// Don't use this type directly, use NewDeploymentsClient() instead. +// +// Generated from API version 2026-05-01 +type DeploymentsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDeploymentsClient creates a new instance of DeploymentsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewDeploymentsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DeploymentsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DeploymentsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Update the state of specified deployments associated with the Cognitive Services account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - deploymentName - The name of the deployment associated with the Cognitive Services Account +// - deployment - The deployment properties. +// - options - DeploymentsClientBeginCreateOrUpdateOptions contains the optional parameters for the DeploymentsClient.BeginCreateOrUpdate +// method. +func (client *DeploymentsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, deployment Deployment, options *DeploymentsClientBeginCreateOrUpdateOptions) (*runtime.Poller[DeploymentsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, accountName, deploymentName, deployment, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DeploymentsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DeploymentsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Update the state of specified deployments associated with the Cognitive Services account. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *DeploymentsClient) createOrUpdate(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, deployment Deployment, options *DeploymentsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "DeploymentsClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, deploymentName, deployment, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *DeploymentsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, deployment Deployment, _ *DeploymentsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/deployments/{deploymentName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if deploymentName == "" { + return nil, errors.New("parameter deploymentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{deploymentName}", url.PathEscape(deploymentName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, deployment); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes the specified deployment associated with the Cognitive Services account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - deploymentName - The name of the deployment associated with the Cognitive Services Account +// - options - DeploymentsClientBeginDeleteOptions contains the optional parameters for the DeploymentsClient.BeginDelete method. +func (client *DeploymentsClient) BeginDelete(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, options *DeploymentsClientBeginDeleteOptions) (*runtime.Poller[DeploymentsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, accountName, deploymentName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DeploymentsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DeploymentsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified deployment associated with the Cognitive Services account. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *DeploymentsClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, options *DeploymentsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "DeploymentsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, deploymentName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *DeploymentsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, _ *DeploymentsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/deployments/{deploymentName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if deploymentName == "" { + return nil, errors.New("parameter deploymentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{deploymentName}", url.PathEscape(deploymentName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Gets the specified deployments associated with the Cognitive Services account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - deploymentName - The name of the deployment associated with the Cognitive Services Account +// - options - DeploymentsClientGetOptions contains the optional parameters for the DeploymentsClient.Get method. +func (client *DeploymentsClient) Get(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, options *DeploymentsClientGetOptions) (DeploymentsClientGetResponse, error) { + var err error + const operationName = "DeploymentsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, deploymentName, options) + if err != nil { + return DeploymentsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DeploymentsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DeploymentsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DeploymentsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, _ *DeploymentsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/deployments/{deploymentName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if deploymentName == "" { + return nil, errors.New("parameter deploymentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{deploymentName}", url.PathEscape(deploymentName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DeploymentsClient) getHandleResponse(resp *http.Response) (DeploymentsClientGetResponse, error) { + result := DeploymentsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Deployment); err != nil { + return DeploymentsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets the deployments associated with the Cognitive Services account. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - options - DeploymentsClientListOptions contains the optional parameters for the DeploymentsClient.NewListPager method. +func (client *DeploymentsClient) NewListPager(resourceGroupName string, accountName string, options *DeploymentsClientListOptions) *runtime.Pager[DeploymentsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[DeploymentsClientListResponse]{ + More: func(page DeploymentsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DeploymentsClientListResponse) (DeploymentsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DeploymentsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, options) + }, nil) + if err != nil { + return DeploymentsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *DeploymentsClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, _ *DeploymentsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/deployments" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *DeploymentsClient) listHandleResponse(resp *http.Response) (DeploymentsClientListResponse, error) { + result := DeploymentsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DeploymentListResult); err != nil { + return DeploymentsClientListResponse{}, err + } + return result, nil +} + +// NewListSKUsPager - Lists the specified deployments skus associated with the Cognitive Services account. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - deploymentName - The name of the deployment associated with the Cognitive Services Account +// - options - DeploymentsClientListSKUsOptions contains the optional parameters for the DeploymentsClient.NewListSKUsPager +// method. +func (client *DeploymentsClient) NewListSKUsPager(resourceGroupName string, accountName string, deploymentName string, options *DeploymentsClientListSKUsOptions) *runtime.Pager[DeploymentsClientListSKUsResponse] { + return runtime.NewPager(runtime.PagingHandler[DeploymentsClientListSKUsResponse]{ + More: func(page DeploymentsClientListSKUsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DeploymentsClientListSKUsResponse) (DeploymentsClientListSKUsResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DeploymentsClient.NewListSKUsPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listSKUsCreateRequest(ctx, resourceGroupName, accountName, deploymentName, options) + }, nil) + if err != nil { + return DeploymentsClientListSKUsResponse{}, err + } + return client.listSKUsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listSKUsCreateRequest creates the ListSKUs request. +func (client *DeploymentsClient) listSKUsCreateRequest(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, _ *DeploymentsClientListSKUsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/deployments/{deploymentName}/skus" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if deploymentName == "" { + return nil, errors.New("parameter deploymentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{deploymentName}", url.PathEscape(deploymentName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listSKUsHandleResponse handles the ListSKUs response. +func (client *DeploymentsClient) listSKUsHandleResponse(resp *http.Response) (DeploymentsClientListSKUsResponse, error) { + result := DeploymentsClientListSKUsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DeploymentSKUListResult); err != nil { + return DeploymentsClientListSKUsResponse{}, err + } + return result, nil +} + +// Pause - Pause a deployment +// +// Pauses inferencing on a deployment by setting the deploymentState to 'Paused' (see #/definitions/DeploymentProperties/properties/deploymentState). +// Only Standard, DataZoneStandard, and GlobalStandard SKUs support this operation. Inference requests to the paused deployment +// endpoint will receive HTTP 423 (Locked). This operation is idempotent. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - deploymentName - The name of the deployment associated with the Cognitive Services Account +// - options - DeploymentsClientPauseOptions contains the optional parameters for the DeploymentsClient.Pause method. +func (client *DeploymentsClient) Pause(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, options *DeploymentsClientPauseOptions) (DeploymentsClientPauseResponse, error) { + var err error + const operationName = "DeploymentsClient.Pause" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.pauseCreateRequest(ctx, resourceGroupName, accountName, deploymentName, options) + if err != nil { + return DeploymentsClientPauseResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DeploymentsClientPauseResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DeploymentsClientPauseResponse{}, err + } + resp, err := client.pauseHandleResponse(httpResp) + return resp, err +} + +// pauseCreateRequest creates the Pause request. +func (client *DeploymentsClient) pauseCreateRequest(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, _ *DeploymentsClientPauseOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/deployments/{deploymentName}/pause" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if deploymentName == "" { + return nil, errors.New("parameter deploymentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{deploymentName}", url.PathEscape(deploymentName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// pauseHandleResponse handles the Pause response. +func (client *DeploymentsClient) pauseHandleResponse(resp *http.Response) (DeploymentsClientPauseResponse, error) { + result := DeploymentsClientPauseResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Deployment); err != nil { + return DeploymentsClientPauseResponse{}, err + } + return result, nil +} + +// Resume - Resume a deployment +// +// Resumes inferencing on a previously paused deployment by setting the deploymentState to 'Running' (see #/definitions/DeploymentProperties/properties/deploymentState). +// This operation is idempotent and can be safely called on already running deployments. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - deploymentName - The name of the deployment associated with the Cognitive Services Account +// - options - DeploymentsClientResumeOptions contains the optional parameters for the DeploymentsClient.Resume method. +func (client *DeploymentsClient) Resume(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, options *DeploymentsClientResumeOptions) (DeploymentsClientResumeResponse, error) { + var err error + const operationName = "DeploymentsClient.Resume" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.resumeCreateRequest(ctx, resourceGroupName, accountName, deploymentName, options) + if err != nil { + return DeploymentsClientResumeResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DeploymentsClientResumeResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DeploymentsClientResumeResponse{}, err + } + resp, err := client.resumeHandleResponse(httpResp) + return resp, err +} + +// resumeCreateRequest creates the Resume request. +func (client *DeploymentsClient) resumeCreateRequest(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, _ *DeploymentsClientResumeOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/deployments/{deploymentName}/resume" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if deploymentName == "" { + return nil, errors.New("parameter deploymentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{deploymentName}", url.PathEscape(deploymentName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// resumeHandleResponse handles the Resume response. +func (client *DeploymentsClient) resumeHandleResponse(resp *http.Response) (DeploymentsClientResumeResponse, error) { + result := DeploymentsClientResumeResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Deployment); err != nil { + return DeploymentsClientResumeResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update specified deployments associated with the Cognitive Services account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - deploymentName - The name of the deployment associated with the Cognitive Services Account +// - deployment - The deployment properties. +// - options - DeploymentsClientBeginUpdateOptions contains the optional parameters for the DeploymentsClient.BeginUpdate method. +func (client *DeploymentsClient) BeginUpdate(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, deployment PatchResourceTagsAndSKU, options *DeploymentsClientBeginUpdateOptions) (*runtime.Poller[DeploymentsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, accountName, deploymentName, deployment, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DeploymentsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DeploymentsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update specified deployments associated with the Cognitive Services account. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *DeploymentsClient) update(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, deployment PatchResourceTagsAndSKU, options *DeploymentsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "DeploymentsClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, accountName, deploymentName, deployment, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *DeploymentsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, deploymentName string, deployment PatchResourceTagsAndSKU, _ *DeploymentsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/deployments/{deploymentName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if deploymentName == "" { + return nil, errors.New("parameter deploymentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{deploymentName}", url.PathEscape(deploymentName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, deployment); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armcognitiveservices/zz_encryptionscopes_client.go b/test/local/armcognitiveservices/zz_encryptionscopes_client.go new file mode 100644 index 000000000000..e23b2ce00dba --- /dev/null +++ b/test/local/armcognitiveservices/zz_encryptionscopes_client.go @@ -0,0 +1,321 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// EncryptionScopesClient contains the methods for the EncryptionScopes group. +// Don't use this type directly, use NewEncryptionScopesClient() instead. +// +// Generated from API version 2026-05-01 +type EncryptionScopesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewEncryptionScopesClient creates a new instance of EncryptionScopesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewEncryptionScopesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*EncryptionScopesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &EncryptionScopesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Update the state of specified encryptionScope associated with the Cognitive Services account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - encryptionScopeName - The name of the encryptionScope associated with the Cognitive Services Account +// - encryptionScope - The encryptionScope properties. +// - options - EncryptionScopesClientCreateOrUpdateOptions contains the optional parameters for the EncryptionScopesClient.CreateOrUpdate +// method. +func (client *EncryptionScopesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, encryptionScopeName string, encryptionScope EncryptionScope, options *EncryptionScopesClientCreateOrUpdateOptions) (EncryptionScopesClientCreateOrUpdateResponse, error) { + var err error + const operationName = "EncryptionScopesClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, encryptionScopeName, encryptionScope, options) + if err != nil { + return EncryptionScopesClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EncryptionScopesClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return EncryptionScopesClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *EncryptionScopesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, encryptionScopeName string, encryptionScope EncryptionScope, _ *EncryptionScopesClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/encryptionScopes/{encryptionScopeName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if encryptionScopeName == "" { + return nil, errors.New("parameter encryptionScopeName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{encryptionScopeName}", url.PathEscape(encryptionScopeName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, encryptionScope); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *EncryptionScopesClient) createOrUpdateHandleResponse(resp *http.Response) (EncryptionScopesClientCreateOrUpdateResponse, error) { + result := EncryptionScopesClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.EncryptionScope); err != nil { + return EncryptionScopesClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// BeginDelete - Deletes the specified encryptionScope associated with the Cognitive Services account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - encryptionScopeName - The name of the encryptionScope associated with the Cognitive Services Account +// - options - EncryptionScopesClientBeginDeleteOptions contains the optional parameters for the EncryptionScopesClient.BeginDelete +// method. +func (client *EncryptionScopesClient) BeginDelete(ctx context.Context, resourceGroupName string, accountName string, encryptionScopeName string, options *EncryptionScopesClientBeginDeleteOptions) (*runtime.Poller[EncryptionScopesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, accountName, encryptionScopeName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[EncryptionScopesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[EncryptionScopesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified encryptionScope associated with the Cognitive Services account. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *EncryptionScopesClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, encryptionScopeName string, options *EncryptionScopesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "EncryptionScopesClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, encryptionScopeName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *EncryptionScopesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, encryptionScopeName string, _ *EncryptionScopesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/encryptionScopes/{encryptionScopeName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if encryptionScopeName == "" { + return nil, errors.New("parameter encryptionScopeName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{encryptionScopeName}", url.PathEscape(encryptionScopeName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Gets the specified EncryptionScope associated with the Cognitive Services account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - encryptionScopeName - The name of the encryptionScope associated with the Cognitive Services Account +// - options - EncryptionScopesClientGetOptions contains the optional parameters for the EncryptionScopesClient.Get method. +func (client *EncryptionScopesClient) Get(ctx context.Context, resourceGroupName string, accountName string, encryptionScopeName string, options *EncryptionScopesClientGetOptions) (EncryptionScopesClientGetResponse, error) { + var err error + const operationName = "EncryptionScopesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, encryptionScopeName, options) + if err != nil { + return EncryptionScopesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EncryptionScopesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return EncryptionScopesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *EncryptionScopesClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, encryptionScopeName string, _ *EncryptionScopesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/encryptionScopes/{encryptionScopeName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if encryptionScopeName == "" { + return nil, errors.New("parameter encryptionScopeName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{encryptionScopeName}", url.PathEscape(encryptionScopeName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *EncryptionScopesClient) getHandleResponse(resp *http.Response) (EncryptionScopesClientGetResponse, error) { + result := EncryptionScopesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.EncryptionScope); err != nil { + return EncryptionScopesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets the content filters associated with the Azure OpenAI account. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - options - EncryptionScopesClientListOptions contains the optional parameters for the EncryptionScopesClient.NewListPager +// method. +func (client *EncryptionScopesClient) NewListPager(resourceGroupName string, accountName string, options *EncryptionScopesClientListOptions) *runtime.Pager[EncryptionScopesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[EncryptionScopesClientListResponse]{ + More: func(page EncryptionScopesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *EncryptionScopesClientListResponse) (EncryptionScopesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "EncryptionScopesClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, options) + }, nil) + if err != nil { + return EncryptionScopesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *EncryptionScopesClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, _ *EncryptionScopesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/encryptionScopes" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *EncryptionScopesClient) listHandleResponse(resp *http.Response) (EncryptionScopesClientListResponse, error) { + result := EncryptionScopesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.EncryptionScopeListResult); err != nil { + return EncryptionScopesClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_interfaces.go b/test/local/armcognitiveservices/zz_interfaces.go new file mode 100644 index 000000000000..b4b8632d044a --- /dev/null +++ b/test/local/armcognitiveservices/zz_interfaces.go @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +// AgentDeploymentPropertiesClassification provides polymorphic access to related types. +// Call the interface's GetAgentDeploymentProperties() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *AgentDeploymentProperties, *HostedAgentDeployment, *ManagedAgentDeployment +type AgentDeploymentPropertiesClassification interface { + // GetAgentDeploymentProperties returns the AgentDeploymentProperties content of the underlying type. + GetAgentDeploymentProperties() *AgentDeploymentProperties +} + +// ApplicationAuthorizationPolicyClassification provides polymorphic access to related types. +// Call the interface's GetApplicationAuthorizationPolicy() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *ApplicationAuthorizationPolicy, *ChannelsBuiltInAuthorizationPolicy, *OrganizationSharedBuiltInAuthorizationPolicy, +// - *RoleBasedBuiltInAuthorizationPolicy +type ApplicationAuthorizationPolicyClassification interface { + // GetApplicationAuthorizationPolicy returns the ApplicationAuthorizationPolicy content of the underlying type. + GetApplicationAuthorizationPolicy() *ApplicationAuthorizationPolicy +} + +// ConnectionPropertiesV2Classification provides polymorphic access to related types. +// Call the interface's GetConnectionPropertiesV2() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *AADAuthTypeConnectionProperties, *APIKeyAuthConnectionProperties, *AccessKeyAuthTypeConnectionProperties, *AccountKeyAuthTypeConnectionProperties, +// - *ConnectionPropertiesV2, *CustomKeysConnectionProperties, *ManagedIdentityAuthTypeConnectionProperties, *NoneAuthTypeConnectionProperties, +// - *OAuth2AuthTypeConnectionProperties, *PATAuthTypeConnectionProperties, *SASAuthTypeConnectionProperties, *ServicePrincipalAuthTypeConnectionProperties, +// - *UsernamePasswordAuthTypeConnectionProperties +type ConnectionPropertiesV2Classification interface { + // GetConnectionPropertiesV2 returns the ConnectionPropertiesV2 content of the underlying type. + GetConnectionPropertiesV2() *ConnectionPropertiesV2 +} + +// OutboundRuleClassification provides polymorphic access to related types. +// Call the interface's GetOutboundRule() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *FqdnOutboundRule, *OutboundRule, *PrivateEndpointOutboundRule, *ServiceTagOutboundRule +type OutboundRuleClassification interface { + // GetOutboundRule returns the OutboundRule content of the underlying type. + GetOutboundRule() *OutboundRule +} diff --git a/test/local/armcognitiveservices/zz_locationbasedmodelcapacities_client.go b/test/local/armcognitiveservices/zz_locationbasedmodelcapacities_client.go new file mode 100644 index 000000000000..f7a0299dcabe --- /dev/null +++ b/test/local/armcognitiveservices/zz_locationbasedmodelcapacities_client.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// LocationBasedModelCapacitiesClient contains the methods for the LocationBasedModelCapacities group. +// Don't use this type directly, use NewLocationBasedModelCapacitiesClient() instead. +// +// Generated from API version 2026-05-01 +type LocationBasedModelCapacitiesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewLocationBasedModelCapacitiesClient creates a new instance of LocationBasedModelCapacitiesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewLocationBasedModelCapacitiesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*LocationBasedModelCapacitiesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &LocationBasedModelCapacitiesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListPager - List Location Based ModelCapacities. +// - location - The location name. +// - modelFormat - The format of the Model +// - modelName - The name of the Model +// - modelVersion - The version of the Model +// - options - LocationBasedModelCapacitiesClientListOptions contains the optional parameters for the LocationBasedModelCapacitiesClient.NewListPager +// method. +func (client *LocationBasedModelCapacitiesClient) NewListPager(location string, modelFormat string, modelName string, modelVersion string, options *LocationBasedModelCapacitiesClientListOptions) *runtime.Pager[LocationBasedModelCapacitiesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[LocationBasedModelCapacitiesClientListResponse]{ + More: func(page LocationBasedModelCapacitiesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *LocationBasedModelCapacitiesClientListResponse) (LocationBasedModelCapacitiesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "LocationBasedModelCapacitiesClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, location, modelFormat, modelName, modelVersion, options) + }, nil) + if err != nil { + return LocationBasedModelCapacitiesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *LocationBasedModelCapacitiesClient) listCreateRequest(ctx context.Context, location string, modelFormat string, modelName string, modelVersion string, _ *LocationBasedModelCapacitiesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/modelCapacities" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + reqQP.Set("modelFormat", modelFormat) + reqQP.Set("modelName", modelName) + reqQP.Set("modelVersion", modelVersion) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *LocationBasedModelCapacitiesClient) listHandleResponse(resp *http.Response) (LocationBasedModelCapacitiesClientListResponse, error) { + result := LocationBasedModelCapacitiesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ModelCapacityListResult); err != nil { + return LocationBasedModelCapacitiesClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_managednetworkprovisions_client.go b/test/local/armcognitiveservices/zz_managednetworkprovisions_client.go new file mode 100644 index 000000000000..b07f11a4651b --- /dev/null +++ b/test/local/armcognitiveservices/zz_managednetworkprovisions_client.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ManagedNetworkProvisionsClient contains the methods for the ManagedNetworkProvisions group. +// Don't use this type directly, use NewManagedNetworkProvisionsClient() instead. +// +// Generated from API version 2026-05-01 +type ManagedNetworkProvisionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewManagedNetworkProvisionsClient creates a new instance of ManagedNetworkProvisionsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewManagedNetworkProvisionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ManagedNetworkProvisionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ManagedNetworkProvisionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginProvisionManagedNetwork - Provisions the managed network of a cognitive services account. +// +// Provisions the managed network of a cognitive services account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - managedNetworkName - Name of the managedNetwork associated with the cognitive services account. Only 'default' is supported. +// - options - ManagedNetworkProvisionsClientBeginProvisionManagedNetworkOptions contains the optional parameters for the ManagedNetworkProvisionsClient.BeginProvisionManagedNetwork +// method. +func (client *ManagedNetworkProvisionsClient) BeginProvisionManagedNetwork(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, options *ManagedNetworkProvisionsClientBeginProvisionManagedNetworkOptions) (*runtime.Poller[ManagedNetworkProvisionsClientProvisionManagedNetworkResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.provisionManagedNetwork(ctx, resourceGroupName, accountName, managedNetworkName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ManagedNetworkProvisionsClientProvisionManagedNetworkResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ManagedNetworkProvisionsClientProvisionManagedNetworkResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ProvisionManagedNetwork - Provisions the managed network of a cognitive services account. +// +// Provisions the managed network of a cognitive services account. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ManagedNetworkProvisionsClient) provisionManagedNetwork(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, options *ManagedNetworkProvisionsClientBeginProvisionManagedNetworkOptions) (*http.Response, error) { + var err error + const operationName = "ManagedNetworkProvisionsClient.BeginProvisionManagedNetwork" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.provisionManagedNetworkCreateRequest(ctx, resourceGroupName, accountName, managedNetworkName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// provisionManagedNetworkCreateRequest creates the ProvisionManagedNetwork request. +func (client *ManagedNetworkProvisionsClient) provisionManagedNetworkCreateRequest(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, options *ManagedNetworkProvisionsClientBeginProvisionManagedNetworkOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/managedNetworks/{managedNetworkName}/provision" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if managedNetworkName == "" { + return nil, errors.New("parameter managedNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{managedNetworkName}", url.PathEscape(managedNetworkName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.Body != nil { + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, *options.Body); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} diff --git a/test/local/armcognitiveservices/zz_managednetworksettings_client.go b/test/local/armcognitiveservices/zz_managednetworksettings_client.go new file mode 100644 index 000000000000..62b6923da6d0 --- /dev/null +++ b/test/local/armcognitiveservices/zz_managednetworksettings_client.go @@ -0,0 +1,429 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ManagedNetworkSettingsClient contains the methods for the ManagedNetworkSettings group. +// Don't use this type directly, use NewManagedNetworkSettingsClient() instead. +// +// Generated from API version 2026-05-01 +type ManagedNetworkSettingsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewManagedNetworkSettingsClient creates a new instance of ManagedNetworkSettingsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewManagedNetworkSettingsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ManagedNetworkSettingsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ManagedNetworkSettingsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginDelete - Delete API for managed network settings of a cognitive services account. +// +// Delete API for managed network settings of a cognitive services account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - managedNetworkName - Name of the managedNetwork associated with the cognitive services account. Only 'default' is supported. +// - options - ManagedNetworkSettingsClientBeginDeleteOptions contains the optional parameters for the ManagedNetworkSettingsClient.BeginDelete +// method. +func (client *ManagedNetworkSettingsClient) BeginDelete(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, options *ManagedNetworkSettingsClientBeginDeleteOptions) (*runtime.Poller[ManagedNetworkSettingsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, accountName, managedNetworkName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ManagedNetworkSettingsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ManagedNetworkSettingsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete API for managed network settings of a cognitive services account. +// +// Delete API for managed network settings of a cognitive services account. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ManagedNetworkSettingsClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, options *ManagedNetworkSettingsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ManagedNetworkSettingsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, managedNetworkName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ManagedNetworkSettingsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, _ *ManagedNetworkSettingsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/managedNetworks/{managedNetworkName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if managedNetworkName == "" { + return nil, errors.New("parameter managedNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{managedNetworkName}", url.PathEscape(managedNetworkName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get API for managed network settings of a cognitive services account. +// +// Get API for managed network settings of a cognitive services account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - managedNetworkName - Name of the managedNetwork associated with the cognitive services account. Only 'default' is supported. +// - options - ManagedNetworkSettingsClientGetOptions contains the optional parameters for the ManagedNetworkSettingsClient.Get +// method. +func (client *ManagedNetworkSettingsClient) Get(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, options *ManagedNetworkSettingsClientGetOptions) (ManagedNetworkSettingsClientGetResponse, error) { + var err error + const operationName = "ManagedNetworkSettingsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, managedNetworkName, options) + if err != nil { + return ManagedNetworkSettingsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagedNetworkSettingsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ManagedNetworkSettingsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ManagedNetworkSettingsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, _ *ManagedNetworkSettingsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/managedNetworks/{managedNetworkName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if managedNetworkName == "" { + return nil, errors.New("parameter managedNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{managedNetworkName}", url.PathEscape(managedNetworkName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ManagedNetworkSettingsClient) getHandleResponse(resp *http.Response) (ManagedNetworkSettingsClientGetResponse, error) { + result := ManagedNetworkSettingsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagedNetworkSettingsPropertiesBasicResource); err != nil { + return ManagedNetworkSettingsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List API for managed network settings of a cognitive services account. +// +// List API for managed network settings of a cognitive services account. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - options - ManagedNetworkSettingsClientListOptions contains the optional parameters for the ManagedNetworkSettingsClient.NewListPager +// method. +func (client *ManagedNetworkSettingsClient) NewListPager(resourceGroupName string, accountName string, options *ManagedNetworkSettingsClientListOptions) *runtime.Pager[ManagedNetworkSettingsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ManagedNetworkSettingsClientListResponse]{ + More: func(page ManagedNetworkSettingsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ManagedNetworkSettingsClientListResponse) (ManagedNetworkSettingsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ManagedNetworkSettingsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, options) + }, nil) + if err != nil { + return ManagedNetworkSettingsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ManagedNetworkSettingsClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, _ *ManagedNetworkSettingsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/managedNetworks" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ManagedNetworkSettingsClient) listHandleResponse(resp *http.Response) (ManagedNetworkSettingsClientListResponse, error) { + result := ManagedNetworkSettingsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagedNetworkListResult); err != nil { + return ManagedNetworkSettingsClientListResponse{}, err + } + return result, nil +} + +// BeginPatch - Patch API for managed network settings of a cognitive services account. +// +// Patch API for managed network settings of a cognitive services account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - managedNetworkName - Name of the managedNetwork associated with the cognitive services account. Only 'default' is supported. +// - body - The Managed Network Settings object of the account. +// - options - ManagedNetworkSettingsClientBeginPatchOptions contains the optional parameters for the ManagedNetworkSettingsClient.BeginPatch +// method. +func (client *ManagedNetworkSettingsClient) BeginPatch(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, body ManagedNetworkSettingsPropertiesBasicResource, options *ManagedNetworkSettingsClientBeginPatchOptions) (*runtime.Poller[ManagedNetworkSettingsClientPatchResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.patch(ctx, resourceGroupName, accountName, managedNetworkName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ManagedNetworkSettingsClientPatchResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ManagedNetworkSettingsClientPatchResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Patch - Patch API for managed network settings of a cognitive services account. +// +// Patch API for managed network settings of a cognitive services account. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ManagedNetworkSettingsClient) patch(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, body ManagedNetworkSettingsPropertiesBasicResource, options *ManagedNetworkSettingsClientBeginPatchOptions) (*http.Response, error) { + var err error + const operationName = "ManagedNetworkSettingsClient.BeginPatch" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.patchCreateRequest(ctx, resourceGroupName, accountName, managedNetworkName, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// patchCreateRequest creates the Patch request. +func (client *ManagedNetworkSettingsClient) patchCreateRequest(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, body ManagedNetworkSettingsPropertiesBasicResource, _ *ManagedNetworkSettingsClientBeginPatchOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/managedNetworks/{managedNetworkName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if managedNetworkName == "" { + return nil, errors.New("parameter managedNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{managedNetworkName}", url.PathEscape(managedNetworkName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// BeginPut - PUT API for managed network settings of a cognitive services account. +// +// PUT API for managed network settings of a cognitive services account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - managedNetworkName - Name of the managedNetwork associated with the cognitive services account. Only 'default' is supported. +// - body - The Managed Network Settings object of the account. +// - options - ManagedNetworkSettingsClientBeginPutOptions contains the optional parameters for the ManagedNetworkSettingsClient.BeginPut +// method. +func (client *ManagedNetworkSettingsClient) BeginPut(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, body ManagedNetworkSettingsPropertiesBasicResource, options *ManagedNetworkSettingsClientBeginPutOptions) (*runtime.Poller[ManagedNetworkSettingsClientPutResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.put(ctx, resourceGroupName, accountName, managedNetworkName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ManagedNetworkSettingsClientPutResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ManagedNetworkSettingsClientPutResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Put - PUT API for managed network settings of a cognitive services account. +// +// PUT API for managed network settings of a cognitive services account. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ManagedNetworkSettingsClient) put(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, body ManagedNetworkSettingsPropertiesBasicResource, options *ManagedNetworkSettingsClientBeginPutOptions) (*http.Response, error) { + var err error + const operationName = "ManagedNetworkSettingsClient.BeginPut" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, resourceGroupName, accountName, managedNetworkName, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// putCreateRequest creates the Put request. +func (client *ManagedNetworkSettingsClient) putCreateRequest(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, body ManagedNetworkSettingsPropertiesBasicResource, _ *ManagedNetworkSettingsClientBeginPutOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/managedNetworks/{managedNetworkName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if managedNetworkName == "" { + return nil, errors.New("parameter managedNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{managedNetworkName}", url.PathEscape(managedNetworkName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armcognitiveservices/zz_management_client.go b/test/local/armcognitiveservices/zz_management_client.go new file mode 100644 index 000000000000..e23f64fe18d8 --- /dev/null +++ b/test/local/armcognitiveservices/zz_management_client.go @@ -0,0 +1,221 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ManagementClient contains the methods for the Management group. +// Don't use this type directly, use NewManagementClient() instead. +// +// Generated from API version 2026-05-01 +type ManagementClient struct { + internal *arm.Client + subscriptionID string +} + +// NewManagementClient creates a new instance of ManagementClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewManagementClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ManagementClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ManagementClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CalculateModelCapacity - Model capacity calculator. +// If the operation fails it returns an *azcore.ResponseError type. +// - parameters - The request body +// - options - ManagementClientCalculateModelCapacityOptions contains the optional parameters for the ManagementClient.CalculateModelCapacity +// method. +func (client *ManagementClient) CalculateModelCapacity(ctx context.Context, parameters CalculateModelCapacityParameter, options *ManagementClientCalculateModelCapacityOptions) (ManagementClientCalculateModelCapacityResponse, error) { + var err error + const operationName = "ManagementClient.CalculateModelCapacity" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.calculateModelCapacityCreateRequest(ctx, parameters, options) + if err != nil { + return ManagementClientCalculateModelCapacityResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagementClientCalculateModelCapacityResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ManagementClientCalculateModelCapacityResponse{}, err + } + resp, err := client.calculateModelCapacityHandleResponse(httpResp) + return resp, err +} + +// calculateModelCapacityCreateRequest creates the CalculateModelCapacity request. +func (client *ManagementClient) calculateModelCapacityCreateRequest(ctx context.Context, parameters CalculateModelCapacityParameter, _ *ManagementClientCalculateModelCapacityOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/calculateModelCapacity" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// calculateModelCapacityHandleResponse handles the CalculateModelCapacity response. +func (client *ManagementClient) calculateModelCapacityHandleResponse(resp *http.Response) (ManagementClientCalculateModelCapacityResponse, error) { + result := ManagementClientCalculateModelCapacityResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CalculateModelCapacityResult); err != nil { + return ManagementClientCalculateModelCapacityResponse{}, err + } + return result, nil +} + +// CheckDomainAvailability - Check whether a domain is available. +// If the operation fails it returns an *azcore.ResponseError type. +// - parameters - The request body +// - options - ManagementClientCheckDomainAvailabilityOptions contains the optional parameters for the ManagementClient.CheckDomainAvailability +// method. +func (client *ManagementClient) CheckDomainAvailability(ctx context.Context, parameters CheckDomainAvailabilityParameter, options *ManagementClientCheckDomainAvailabilityOptions) (ManagementClientCheckDomainAvailabilityResponse, error) { + var err error + const operationName = "ManagementClient.CheckDomainAvailability" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.checkDomainAvailabilityCreateRequest(ctx, parameters, options) + if err != nil { + return ManagementClientCheckDomainAvailabilityResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagementClientCheckDomainAvailabilityResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ManagementClientCheckDomainAvailabilityResponse{}, err + } + resp, err := client.checkDomainAvailabilityHandleResponse(httpResp) + return resp, err +} + +// checkDomainAvailabilityCreateRequest creates the CheckDomainAvailability request. +func (client *ManagementClient) checkDomainAvailabilityCreateRequest(ctx context.Context, parameters CheckDomainAvailabilityParameter, _ *ManagementClientCheckDomainAvailabilityOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/checkDomainAvailability" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// checkDomainAvailabilityHandleResponse handles the CheckDomainAvailability response. +func (client *ManagementClient) checkDomainAvailabilityHandleResponse(resp *http.Response) (ManagementClientCheckDomainAvailabilityResponse, error) { + result := ManagementClientCheckDomainAvailabilityResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DomainAvailability); err != nil { + return ManagementClientCheckDomainAvailabilityResponse{}, err + } + return result, nil +} + +// CheckSKUAvailability - Check available SKUs. +// If the operation fails it returns an *azcore.ResponseError type. +// - location - The location name. +// - parameters - The request body +// - options - ManagementClientCheckSKUAvailabilityOptions contains the optional parameters for the ManagementClient.CheckSKUAvailability +// method. +func (client *ManagementClient) CheckSKUAvailability(ctx context.Context, location string, parameters CheckSKUAvailabilityParameter, options *ManagementClientCheckSKUAvailabilityOptions) (ManagementClientCheckSKUAvailabilityResponse, error) { + var err error + const operationName = "ManagementClient.CheckSKUAvailability" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.checkSKUAvailabilityCreateRequest(ctx, location, parameters, options) + if err != nil { + return ManagementClientCheckSKUAvailabilityResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ManagementClientCheckSKUAvailabilityResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ManagementClientCheckSKUAvailabilityResponse{}, err + } + resp, err := client.checkSKUAvailabilityHandleResponse(httpResp) + return resp, err +} + +// checkSKUAvailabilityCreateRequest creates the CheckSKUAvailability request. +func (client *ManagementClient) checkSKUAvailabilityCreateRequest(ctx context.Context, location string, parameters CheckSKUAvailabilityParameter, _ *ManagementClientCheckSKUAvailabilityOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/checkSkuAvailability" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// checkSKUAvailabilityHandleResponse handles the CheckSKUAvailability response. +func (client *ManagementClient) checkSKUAvailabilityHandleResponse(resp *http.Response) (ManagementClientCheckSKUAvailabilityResponse, error) { + result := ManagementClientCheckSKUAvailabilityResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SKUAvailabilityListResult); err != nil { + return ManagementClientCheckSKUAvailabilityResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_modelcapacities_client.go b/test/local/armcognitiveservices/zz_modelcapacities_client.go new file mode 100644 index 000000000000..a22f94b8b03a --- /dev/null +++ b/test/local/armcognitiveservices/zz_modelcapacities_client.go @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ModelCapacitiesClient contains the methods for the ModelCapacities group. +// Don't use this type directly, use NewModelCapacitiesClient() instead. +// +// Generated from API version 2026-05-01 +type ModelCapacitiesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewModelCapacitiesClient creates a new instance of ModelCapacitiesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewModelCapacitiesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ModelCapacitiesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ModelCapacitiesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListPager - List ModelCapacities. +// - modelFormat - The format of the Model +// - modelName - The name of the Model +// - modelVersion - The version of the Model +// - options - ModelCapacitiesClientListOptions contains the optional parameters for the ModelCapacitiesClient.NewListPager +// method. +func (client *ModelCapacitiesClient) NewListPager(modelFormat string, modelName string, modelVersion string, options *ModelCapacitiesClientListOptions) *runtime.Pager[ModelCapacitiesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ModelCapacitiesClientListResponse]{ + More: func(page ModelCapacitiesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ModelCapacitiesClientListResponse) (ModelCapacitiesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ModelCapacitiesClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, modelFormat, modelName, modelVersion, options) + }, nil) + if err != nil { + return ModelCapacitiesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ModelCapacitiesClient) listCreateRequest(ctx context.Context, modelFormat string, modelName string, modelVersion string, _ *ModelCapacitiesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/modelCapacities" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + reqQP.Set("modelFormat", modelFormat) + reqQP.Set("modelName", modelName) + reqQP.Set("modelVersion", modelVersion) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ModelCapacitiesClient) listHandleResponse(resp *http.Response) (ModelCapacitiesClientListResponse, error) { + result := ModelCapacitiesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ModelCapacityListResult); err != nil { + return ModelCapacitiesClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_models.go b/test/local/armcognitiveservices/zz_models.go new file mode 100644 index 000000000000..3a62f5f5e897 --- /dev/null +++ b/test/local/armcognitiveservices/zz_models.go @@ -0,0 +1,3778 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import "time" + +// AADAuthTypeConnectionProperties - This connection type covers the AAD auth for any applicable Azure service +type AADAuthTypeConnectionProperties struct { + // CONSTANT; Authentication type of the connection target + // Field has constant value ConnectionAuthTypeAAD, any specified value is ignored. + AuthType *ConnectionAuthType + + // Category of the connection + Category *ConnectionCategory + + // Provides the error message if the connection fails + Error *string + ExpiryTime *time.Time + IsSharedToAll *bool + + // Store user metadata for this connection + Metadata map[string]*string + + // Specifies how private endpoints are used with this connection: 'Required', 'NotRequired', or 'NotApplicable'. + PeRequirement *ManagedPERequirement + + // Specifies the status of private endpoints for this connection: 'Inactive', 'Active', or 'NotApplicable'. + PeStatus *ManagedPEStatus + SharedUserList []*string + + // The connection URL to be used. + Target *string + UseWorkspaceManagedIdentity *bool + + // READ-ONLY + CreatedByWorkspaceArmID *string + + // READ-ONLY; Group based on connection category + Group *ConnectionGroup +} + +// GetConnectionPropertiesV2 implements the ConnectionPropertiesV2Classification interface for type AADAuthTypeConnectionProperties. +func (a *AADAuthTypeConnectionProperties) GetConnectionPropertiesV2() *ConnectionPropertiesV2 { + return &ConnectionPropertiesV2{ + AuthType: a.AuthType, + Category: a.Category, + CreatedByWorkspaceArmID: a.CreatedByWorkspaceArmID, + Error: a.Error, + ExpiryTime: a.ExpiryTime, + Group: a.Group, + IsSharedToAll: a.IsSharedToAll, + Metadata: a.Metadata, + PeRequirement: a.PeRequirement, + PeStatus: a.PeStatus, + SharedUserList: a.SharedUserList, + Target: a.Target, + UseWorkspaceManagedIdentity: a.UseWorkspaceManagedIdentity, + } +} + +// APIKeyAuthConnectionProperties - This connection type covers the generic ApiKey auth connection categories, for examples: +// AzureOpenAI: +// Category:= AzureOpenAI +// AuthType:= ApiKey (as type discriminator) +// Credentials:= {ApiKey} as .ApiKey +// Target:= {ApiBase} +// CognitiveService: +// Category:= CognitiveService +// AuthType:= ApiKey (as type discriminator) +// Credentials:= {SubscriptionKey} as ApiKey +// Target:= ServiceRegion={serviceRegion} +// CognitiveSearch: +// Category:= CognitiveSearch +// AuthType:= ApiKey (as type discriminator) +// Credentials:= {Key} as ApiKey +// Target:= {Endpoint} +// Use Metadata property bag for ApiType, ApiVersion, Kind and other metadata fields +type APIKeyAuthConnectionProperties struct { + // CONSTANT; Authentication type of the connection target + // Field has constant value ConnectionAuthTypeAPIKey, any specified value is ignored. + AuthType *ConnectionAuthType + + // Category of the connection + Category *ConnectionCategory + + // Api key object for connection credential. + Credentials *ConnectionAPIKey + + // Provides the error message if the connection fails + Error *string + ExpiryTime *time.Time + IsSharedToAll *bool + + // Store user metadata for this connection + Metadata map[string]*string + + // Specifies how private endpoints are used with this connection: 'Required', 'NotRequired', or 'NotApplicable'. + PeRequirement *ManagedPERequirement + + // Specifies the status of private endpoints for this connection: 'Inactive', 'Active', or 'NotApplicable'. + PeStatus *ManagedPEStatus + SharedUserList []*string + + // The connection URL to be used. + Target *string + UseWorkspaceManagedIdentity *bool + + // READ-ONLY + CreatedByWorkspaceArmID *string + + // READ-ONLY; Group based on connection category + Group *ConnectionGroup +} + +// GetConnectionPropertiesV2 implements the ConnectionPropertiesV2Classification interface for type APIKeyAuthConnectionProperties. +func (a *APIKeyAuthConnectionProperties) GetConnectionPropertiesV2() *ConnectionPropertiesV2 { + return &ConnectionPropertiesV2{ + AuthType: a.AuthType, + Category: a.Category, + CreatedByWorkspaceArmID: a.CreatedByWorkspaceArmID, + Error: a.Error, + ExpiryTime: a.ExpiryTime, + Group: a.Group, + IsSharedToAll: a.IsSharedToAll, + Metadata: a.Metadata, + PeRequirement: a.PeRequirement, + PeStatus: a.PeStatus, + SharedUserList: a.SharedUserList, + Target: a.Target, + UseWorkspaceManagedIdentity: a.UseWorkspaceManagedIdentity, + } +} + +// APIKeys - The access keys for the cognitive services account. +type APIKeys struct { + // Gets the value of key 1. + Key1 *string + + // Gets the value of key 2. + Key2 *string +} + +// APIProperties - The api properties for special APIs. +type APIProperties struct { + // (Metrics Advisor Only) The Azure AD Client Id (Application Id). + AADClientID *string + + // (Metrics Advisor Only) The Azure AD Tenant Id. + AADTenantID *string + AdditionalProperties map[string]any + + // (Personalization Only) The flag to enable statistics of Bing Search. + EventHubConnectionString *string + + // (QnAMaker Only) The Azure Search endpoint id of QnAMaker. + QnaAzureSearchEndpointID *string + + // (QnAMaker Only) The Azure Search endpoint key of QnAMaker. + QnaAzureSearchEndpointKey *string + + // (QnAMaker Only) The runtime endpoint of QnAMaker. + QnaRuntimeEndpoint *string + + // (Bing Search Only) The flag to enable statistics of Bing Search. + StatisticsEnabled *bool + + // (Personalization Only) The storage account connection string. + StorageAccountConnectionString *string + + // (Metrics Advisor Only) The super user of Metrics Advisor. + SuperUser *string + + // (Metrics Advisor Only) The website name of Metrics Advisor. + WebsiteName *string +} + +// AbusePenalty - The abuse penalty. +type AbusePenalty struct { + // The action of AbusePenalty. + Action *AbusePenaltyAction + + // The datetime of expiration of the AbusePenalty. + Expiration *time.Time + + // The percentage of rate limit. + RateLimitPercentage *float32 +} + +type AccessKeyAuthTypeConnectionProperties struct { + // CONSTANT; Authentication type of the connection target + // Field has constant value ConnectionAuthTypeAccessKey, any specified value is ignored. + AuthType *ConnectionAuthType + + // Category of the connection + Category *ConnectionCategory + Credentials *ConnectionAccessKey + + // Provides the error message if the connection fails + Error *string + ExpiryTime *time.Time + IsSharedToAll *bool + + // Store user metadata for this connection + Metadata map[string]*string + + // Specifies how private endpoints are used with this connection: 'Required', 'NotRequired', or 'NotApplicable'. + PeRequirement *ManagedPERequirement + + // Specifies the status of private endpoints for this connection: 'Inactive', 'Active', or 'NotApplicable'. + PeStatus *ManagedPEStatus + SharedUserList []*string + + // The connection URL to be used. + Target *string + UseWorkspaceManagedIdentity *bool + + // READ-ONLY + CreatedByWorkspaceArmID *string + + // READ-ONLY; Group based on connection category + Group *ConnectionGroup +} + +// GetConnectionPropertiesV2 implements the ConnectionPropertiesV2Classification interface for type AccessKeyAuthTypeConnectionProperties. +func (a *AccessKeyAuthTypeConnectionProperties) GetConnectionPropertiesV2() *ConnectionPropertiesV2 { + return &ConnectionPropertiesV2{ + AuthType: a.AuthType, + Category: a.Category, + CreatedByWorkspaceArmID: a.CreatedByWorkspaceArmID, + Error: a.Error, + ExpiryTime: a.ExpiryTime, + Group: a.Group, + IsSharedToAll: a.IsSharedToAll, + Metadata: a.Metadata, + PeRequirement: a.PeRequirement, + PeStatus: a.PeStatus, + SharedUserList: a.SharedUserList, + Target: a.Target, + UseWorkspaceManagedIdentity: a.UseWorkspaceManagedIdentity, + } +} + +// Account - Cognitive Services account is an Azure resource representing the provisioned account, it's type, location and +// SKU. +type Account struct { + // Identity for the resource. + Identity *Identity + + // The kind (type) of cognitive service account. + Kind *string + + // The geo-location where the resource lives + Location *string + + // Properties of Cognitive Services account. + Properties *AccountProperties + + // The resource model definition representing SKU + SKU *SKU + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Resource Etag. + Etag *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// AccountKeyAuthTypeConnectionProperties - This connection type covers the account key connection for Azure storage +type AccountKeyAuthTypeConnectionProperties struct { + // CONSTANT; Authentication type of the connection target + // Field has constant value ConnectionAuthTypeAccountKey, any specified value is ignored. + AuthType *ConnectionAuthType + + // Category of the connection + Category *ConnectionCategory + + // Account key object for connection credential. + Credentials *ConnectionAccountKey + + // Provides the error message if the connection fails + Error *string + ExpiryTime *time.Time + IsSharedToAll *bool + + // Store user metadata for this connection + Metadata map[string]*string + + // Specifies how private endpoints are used with this connection: 'Required', 'NotRequired', or 'NotApplicable'. + PeRequirement *ManagedPERequirement + + // Specifies the status of private endpoints for this connection: 'Inactive', 'Active', or 'NotApplicable'. + PeStatus *ManagedPEStatus + SharedUserList []*string + + // The connection URL to be used. + Target *string + UseWorkspaceManagedIdentity *bool + + // READ-ONLY + CreatedByWorkspaceArmID *string + + // READ-ONLY; Group based on connection category + Group *ConnectionGroup +} + +// GetConnectionPropertiesV2 implements the ConnectionPropertiesV2Classification interface for type AccountKeyAuthTypeConnectionProperties. +func (a *AccountKeyAuthTypeConnectionProperties) GetConnectionPropertiesV2() *ConnectionPropertiesV2 { + return &ConnectionPropertiesV2{ + AuthType: a.AuthType, + Category: a.Category, + CreatedByWorkspaceArmID: a.CreatedByWorkspaceArmID, + Error: a.Error, + ExpiryTime: a.ExpiryTime, + Group: a.Group, + IsSharedToAll: a.IsSharedToAll, + Metadata: a.Metadata, + PeRequirement: a.PeRequirement, + PeStatus: a.PeStatus, + SharedUserList: a.SharedUserList, + Target: a.Target, + UseWorkspaceManagedIdentity: a.UseWorkspaceManagedIdentity, + } +} + +// AccountListResult - The list of cognitive services accounts operation response. +type AccountListResult struct { + // The link used to get the next page of accounts. + NextLink *string + + // READ-ONLY; Gets the list of Cognitive Services accounts and their properties. + Value []*Account +} + +// AccountModel - Cognitive Services account Model. +type AccountModel struct { + // Properties of Cognitive Services account deployment model. + BaseModel *DeploymentModel + + // The capabilities. + Capabilities map[string]*string + + // Cognitive Services account ModelDeprecationInfo. + Deprecation *ModelDeprecationInfo + + // The capabilities for finetune models. + FinetuneCapabilities map[string]*string + + // Deployment model format. + Format *string + + // If the model is default version. + IsDefaultVersion *bool + + // Model lifecycle status. + LifecycleStatus *ModelLifecycleStatus + + // The max capacity. + MaxCapacity *int32 + + // Asset identifier for the model in the model catalog. + ModelCatalogAssetID *string + + // Deployment model name. + Name *string + + // Deployment model publisher. + Publisher *string + + // Configuration for model replacement. + ReplacementConfig *ReplacementConfig + + // The list of Model Sku. + SKUs []*ModelSKU + + // Optional. Deployment model source ARM resource ID. + Source *string + + // Optional. Source of the model, another Microsoft.CognitiveServices accounts ARM resource ID. + SourceAccount *string + + // Optional. Deployment model version. If version is not specified, a default version will be assigned. The default version + // is different for different models and might change when there is new version available for a model. Default version for + // a model could be found from list models API. + Version *string + + // READ-ONLY; The call rate limit Cognitive Services account. + CallRateLimit *CallRateLimit + + // READ-ONLY; Metadata pertaining to creation and last modification of the resource. + SystemData *SystemData +} + +// AccountModelListResult - The list of cognitive services accounts operation response. +type AccountModelListResult struct { + // The link used to get the next page of Model. + NextLink *string + + // Gets the list of Cognitive Services accounts Model and their properties. + Value []*AccountModel +} + +// AccountProperties - Properties of Cognitive Services account. +type AccountProperties struct { + // The api properties for special APIs. + APIProperties *APIProperties + + // Specifies whether this resource support project management as child resources, used as containers for access management, + // data isolation and cost in AI Foundry. + AllowProjectManagement *bool + AllowedFqdnList []*string + + // The user owned AML account properties. + AmlWorkspace *UserOwnedAmlWorkspace + + // Specifies the projects, by project name, that are associated with this resource. + AssociatedProjects []*string + + // Optional subdomain name used for token-based authentication. + CustomSubDomainName *string + + // Specifies the project, by project name, that is targeted when data plane endpoints are called without a project parameter. + DefaultProject *string + DisableLocalAuth *bool + + // The flag to enable dynamic throttling. + DynamicThrottlingEnabled *bool + + // The encryption properties for this resource. + Encryption *Encryption + + // The multiregion settings of Cognitive Services account. + Locations *MultiRegionSettings + + // Resource migration token. + MigrationToken *string + + // A collection of rules governing the accessibility from specific network locations. + NetworkACLs *NetworkRuleSet + NetworkInjections []*NetworkInjection + + // Whether or not public endpoint access is allowed for this account. + PublicNetworkAccess *PublicNetworkAccess + + // Cognitive Services Rai Monitor Config. + RaiMonitorConfig *RaiMonitorConfig + Restore *bool + RestrictOutboundNetworkAccess *bool + + // The flag to disable stored completions. + StoredCompletionsDisabled *bool + + // The storage accounts for this resource. + UserOwnedStorage []*UserOwnedStorage + + // READ-ONLY; The abuse penalty. + AbusePenalty *AbusePenalty + + // READ-ONLY; The call rate limit Cognitive Services account. + CallRateLimit *CallRateLimit + + // READ-ONLY; Gets the capabilities of the cognitive services account. Each item indicates the capability of a specific feature. + // The values are read-only and for reference only. + Capabilities []*SKUCapability + + // READ-ONLY; The commitment plan associations of Cognitive Services account. + CommitmentPlanAssociations []*CommitmentPlanAssociation + + // READ-ONLY; Gets the date of cognitive services account creation. + DateCreated *string + + // READ-ONLY; The deletion date, only available for deleted account. + DeletionDate *string + + // READ-ONLY; Endpoint of the created account. + Endpoint *string + + // READ-ONLY; Dictionary of + Endpoints map[string]*string + + // READ-ONLY; The internal identifier (deprecated, do not use this property). + InternalID *string + + // READ-ONLY; If the resource is migrated from an existing key. + IsMigrated *bool + + // READ-ONLY; The private endpoint connection associated with the Cognitive Services account. + PrivateEndpointConnections []*PrivateEndpointConnection + + // READ-ONLY; Gets the status of the cognitive services account at the time the operation was called. + ProvisioningState *ProvisioningState + + // READ-ONLY + QuotaLimit *QuotaLimit + + // READ-ONLY; Sku change info of account. + SKUChangeInfo *SKUChangeInfo + + // READ-ONLY; The scheduled purge date, only available for deleted account. + ScheduledPurgeDate *string +} + +// AccountSKU - Cognitive Services resource type and SKU. +type AccountSKU struct { + // Resource Namespace and Type + ResourceType *string + + // The SKU of Cognitive Services account. + SKU *SKU +} + +// AccountSKUListResult - The list of cognitive services accounts operation response. +type AccountSKUListResult struct { + // Gets the list of Cognitive Services accounts and their properties. + Value []*AccountSKU +} + +// AgentApplication - Agent Application resource +type AgentApplication struct { + // REQUIRED; [Required] Additional attributes of the entity. + Properties *AgenticApplicationProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// AgentApplicationResourceArmPaginatedResult - A paginated list of Agent Application entities. +type AgentApplicationResourceArmPaginatedResult struct { + // The link to the next page of Agent Application objects. If null, there are no additional pages. + NextLink *string + + // An array of objects of type Agent Application. + Value []*AgentApplication +} + +// AgentDeployment - Agent Deployment resource +type AgentDeployment struct { + // REQUIRED; [Required] Additional attributes of the entity. + Properties AgentDeploymentPropertiesClassification + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// AgentDeploymentProperties - Type representing an agent deployment as a management construct. +type AgentDeploymentProperties struct { + // REQUIRED; Gets or sets the type of deployment for the agent. + DeploymentType *AgentDeploymentType + + // Returns a flat list of agent:version deployed in this deployment. + Agents []*VersionedAgentReference + + // Gets or sets the unique identifier of the deployment. + DeploymentID *string + + // The asset description text. + Description *string + + // Gets or sets the display name of the deployment. + DisplayName *string + + // Gets or sets the supported protocol types and versions exposed by this deployment. + Protocols []*AgentProtocolVersion + + // Gets or sets the current operational state of the deployment (and, intrinsically, of the comprising agents). + State *AgentDeploymentState + + // Tag dictionary. Tags can be added, removed, and updated. + Tags map[string]*string + + // READ-ONLY; Gets or sets the provisioning state of the agent deployment. + ProvisioningState *AgentDeploymentProvisioningState +} + +// GetAgentDeploymentProperties implements the AgentDeploymentPropertiesClassification interface for type AgentDeploymentProperties. +func (a *AgentDeploymentProperties) GetAgentDeploymentProperties() *AgentDeploymentProperties { + return a +} + +// AgentDeploymentResourceArmPaginatedResult - A paginated list of Agent Deployment entities. +type AgentDeploymentResourceArmPaginatedResult struct { + // The link to the next page of Agent Deployment objects. If null, there are no additional pages. + NextLink *string + + // An array of objects of type Agent Deployment. + Value []*AgentDeployment +} + +// AgentProtocolVersion - Type modeling the protocol and version used by an agent/exposed by a deployment. +type AgentProtocolVersion struct { + // The protocol used by the agent/exposed by a deployment. + Protocol *AgentProtocol + + // The version of the protocol. + Version *string +} + +// AgentReference - Agent Reference resource +type AgentReference struct { + // REQUIRED; [Required] Additional attributes of the entity. + Properties *AgentReferenceProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// AgentReferenceProperties - Type modeling a reference to a version of an agent definition. +type AgentReferenceProperties struct { + // Gets the agent's unique identifier within the organization (subscription). + AgentID *string + + // Gets the agent's name (unique within the project/app). + AgentName *string +} + +// AgentReferenceResourceArmPaginatedResult - A paginated list of Agent Reference entities. +type AgentReferenceResourceArmPaginatedResult struct { + // The link to the next page of Agent Reference objects. If null, there are no additional pages. + NextLink *string + + // An array of objects of type Agent Reference. + Value []*AgentReference +} + +// AgenticApplicationProperties - Resource type representing an agentic application as a management construct. +type AgenticApplicationProperties struct { + // The EntraId Agentic Blueprint of the application. + AgentIdentityBlueprint *AssignedIdentity + + // The list of agent definitions comprising this application, returned as references to the objects under the parent project; + // use this to obtain a flat list of all agent-version pairs represented by this application. + Agents []*AgentReferenceProperties + + // Gets or sets the authorization policy associated with this agentic application instance. + AuthorizationPolicy ApplicationAuthorizationPolicyClassification + + // The application's dedicated invocation endpoint. + BaseURL *string + + // The (default) agent instance identity of the application. + DefaultInstanceIdentity *AssignedIdentity + + // The asset description text. + Description *string + + // The display name of the application. + DisplayName *string + + // Tag dictionary. Tags can be added, removed, and updated. + Tags map[string]*string + + // Gets or sets the traffic routing policy for the application's deployments. + TrafficRoutingPolicy *ApplicationTrafficRoutingPolicy + + // READ-ONLY; Enabledstate of the application. + IsEnabled *bool + + // READ-ONLY; Provisioning state of the application. + ProvisioningState *AgenticApplicationProvisioningState +} + +// ApplicationAuthorizationPolicy - Represents a policy for authorizing applications based on specified authentication and +// authorization schemes. +type ApplicationAuthorizationPolicy struct { + // REQUIRED; Authorization scheme type. + Type *BuiltInAuthorizationScheme +} + +// GetApplicationAuthorizationPolicy implements the ApplicationAuthorizationPolicyClassification interface for type ApplicationAuthorizationPolicy. +func (a *ApplicationAuthorizationPolicy) GetApplicationAuthorizationPolicy() *ApplicationAuthorizationPolicy { + return a +} + +// ApplicationTrafficRoutingPolicy - Type representing an application traffic policy as a property of an agentic application. +type ApplicationTrafficRoutingPolicy struct { + // Methodology used to route traffic to the application's deployments. + Protocol *TrafficRoutingProtocol + + // Gets or sets the collection of traffic routing rules. + Rules []*TrafficRoutingRule +} + +// AssignedIdentity - Type representing an identity assignment +type AssignedIdentity struct { + // REQUIRED; The client ID of the identity. + ClientID *string + + // REQUIRED; Specifies the kind of Entra identity described by this object. + Kind *IdentityKind + + // REQUIRED; The principal ID of the identity. + PrincipalID *string + + // REQUIRED; The tenant ID of the identity. + TenantID *string + + // REQUIRED; Enumeration of identity types, from the perspective of management. + Type *IdentityManagementType + + // The subject of this identity assignment. + Subject *string + + // READ-ONLY; Represents the provisioning state of an identity resource. + ProvisioningState *IdentityProvisioningState +} + +type BillingMeterInfo struct { + MeterID *string + Name *string + Unit *string +} + +// CalculateModelCapacityParameter - Calculate Model Capacity parameter. +type CalculateModelCapacityParameter struct { + // Properties of Cognitive Services account deployment model. + Model *DeploymentModel + + // The name of SKU. + SKUName *string + + // List of Model Capacity Calculator Workload. + Workloads []*ModelCapacityCalculatorWorkload +} + +// CalculateModelCapacityResult - Calculate Model Capacity result. +type CalculateModelCapacityResult struct { + // Model Estimated Capacity. + EstimatedCapacity *CalculateModelCapacityResultEstimatedCapacity + + // Properties of Cognitive Services account deployment model. + Model *DeploymentModel + SKUName *string +} + +// CalculateModelCapacityResultEstimatedCapacity - Model Estimated Capacity. +type CalculateModelCapacityResultEstimatedCapacity struct { + DeployableValue *int32 + Value *int32 +} + +// CallRateLimit - The call rate limit Cognitive Services account. +type CallRateLimit struct { + // The count value of Call Rate Limit. + Count *float32 + + // The renewal period in seconds of Call Rate Limit. + RenewalPeriod *float32 + Rules []*ThrottlingRule +} + +// CapabilityHost - Azure Resource Manager resource envelope. +type CapabilityHost struct { + // REQUIRED; [Required] Additional attributes of the entity. + Properties *CapabilityHostProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +type CapabilityHostProperties struct { + // List of AI services connections. + AiServicesConnections []*string + + // Kind of this capability host. + CapabilityHostKind *CapabilityHostKind + + // Customer subnet info to help set up this capability host. + CustomerSubnet *string + + // The asset description text. + Description *string + + // Whether public hosting environment is enabled for the capability host + EnablePublicHostingEnvironment *bool + + // List of connection names from those available in the account or project to be used as a storage resource. + StorageConnections []*string + + // Tag dictionary. Tags can be added, removed, and updated. + Tags map[string]*string + + // List of connection names from those available in the account or project to be used for Thread storage. + ThreadStorageConnections []*string + + // List of connection names from those available in the account or project to be used for vector database (e.g. CosmosDB). + VectorStoreConnections []*string + + // READ-ONLY; Provisioning state for the CapabilityHost. + ProvisioningState *CapabilityHostProvisioningState +} + +// CapabilityHostResourceArmPaginatedResult - A paginated list of Capability Host entities. +type CapabilityHostResourceArmPaginatedResult struct { + // The link to the next page of Capability Host objects. If null, there are no additional pages. + NextLink *string + + // An array of objects of type Capability Host. + Value []*CapabilityHost +} + +// CapacityConfig - The capacity configuration. +type CapacityConfig struct { + // The array of allowed values for capacity. + AllowedValues []*int32 + + // The default capacity. + Default *int32 + + // The maximum capacity. + Maximum *int32 + + // The minimum capacity. + Minimum *int32 + + // The minimal incremental between allowed values for capacity. + Step *int32 +} + +// ChannelsBuiltInAuthorizationPolicy - Represents a built-in authorization policy specific to Azure Bot Service/Channels +// authentication. +type ChannelsBuiltInAuthorizationPolicy struct { + // CONSTANT; Authorization scheme type. + // Field has constant value BuiltInAuthorizationSchemeChannels, any specified value is ignored. + Type *BuiltInAuthorizationScheme +} + +// GetApplicationAuthorizationPolicy implements the ApplicationAuthorizationPolicyClassification interface for type ChannelsBuiltInAuthorizationPolicy. +func (c *ChannelsBuiltInAuthorizationPolicy) GetApplicationAuthorizationPolicy() *ApplicationAuthorizationPolicy { + return &ApplicationAuthorizationPolicy{ + Type: c.Type, + } +} + +// CheckDomainAvailabilityParameter - Check Domain availability parameter. +type CheckDomainAvailabilityParameter struct { + // REQUIRED; The subdomain name to use. + SubdomainName *string + + // REQUIRED; The Type of the resource. + Type *string + + // The kind (type) of cognitive service account. + Kind *string +} + +// CheckSKUAvailabilityParameter - Check SKU availability parameter. +type CheckSKUAvailabilityParameter struct { + // REQUIRED; The kind (type) of cognitive service account. + Kind *string + + // REQUIRED; The SKU of the resource. + SKUs []*string + + // REQUIRED; The Type of the resource. + Type *string +} + +// CommitmentCost - Cognitive Services account commitment cost. +type CommitmentCost struct { + // Commitment meter Id. + CommitmentMeterID *string + + // Overage meter Id. + OverageMeterID *string +} + +// CommitmentPeriod - Cognitive Services account commitment period. +type CommitmentPeriod struct { + // Commitment period commitment count. + Count *int32 + + // Commitment period commitment tier. + Tier *string + + // READ-ONLY; Commitment period end date. + EndDate *string + + // READ-ONLY; Cognitive Services account commitment quota. + Quota *CommitmentQuota + + // READ-ONLY; Commitment period start date. + StartDate *string +} + +// CommitmentPlan - Cognitive Services account commitment plan. +type CommitmentPlan struct { + // The kind (type) of cognitive service account. + Kind *string + + // The geo-location where the resource lives + Location *string + + // Properties of Cognitive Services account commitment plan. + Properties *CommitmentPlanProperties + + // The resource model definition representing SKU + SKU *SKU + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Resource Etag. + Etag *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// CommitmentPlanAccountAssociation - The commitment plan association. +type CommitmentPlanAccountAssociation struct { + // Properties of Cognitive Services account commitment plan association. + Properties *CommitmentPlanAccountAssociationProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Resource Etag. + Etag *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// CommitmentPlanAccountAssociationListResult - The list of cognitive services Commitment Plan Account Association operation +// response. +type CommitmentPlanAccountAssociationListResult struct { + // The link used to get the next page of Commitment Plan Account Association. + NextLink *string + + // READ-ONLY; Gets the list of Cognitive Services Commitment Plan Account Association and their properties. + Value []*CommitmentPlanAccountAssociation +} + +// CommitmentPlanAccountAssociationProperties - The commitment plan account association properties. +type CommitmentPlanAccountAssociationProperties struct { + // The Azure resource id of the account. + AccountID *string +} + +// CommitmentPlanAssociation - The commitment plan association. +type CommitmentPlanAssociation struct { + // The Azure resource id of the commitment plan. + CommitmentPlanID *string + + // The location of of the commitment plan. + CommitmentPlanLocation *string +} + +// CommitmentPlanListResult - The list of cognitive services accounts operation response. +type CommitmentPlanListResult struct { + // The link used to get the next page of CommitmentPlan. + NextLink *string + + // READ-ONLY; Gets the list of Cognitive Services accounts CommitmentPlan and their properties. + Value []*CommitmentPlan +} + +// CommitmentPlanProperties - Properties of Cognitive Services account commitment plan. +type CommitmentPlanProperties struct { + // AutoRenew commitment plan. + AutoRenew *bool + + // Commitment plan guid. + CommitmentPlanGUID *string + + // Cognitive Services account commitment period. + Current *CommitmentPeriod + + // Account hosting model. + HostingModel *HostingModel + + // Cognitive Services account commitment period. + Next *CommitmentPeriod + + // Commitment plan type. + PlanType *string + + // READ-ONLY; Cognitive Services account commitment period. + Last *CommitmentPeriod + + // READ-ONLY; The list of ProvisioningIssue. + ProvisioningIssues []*string + + // READ-ONLY; Gets the status of the resource at the time the operation was called. + ProvisioningState *CommitmentPlanProvisioningState +} + +// CommitmentQuota - Cognitive Services account commitment quota. +type CommitmentQuota struct { + // Commitment quota quantity. + Quantity *int64 + + // Commitment quota unit. + Unit *string +} + +// CommitmentTier - Cognitive Services account commitment tier. +type CommitmentTier struct { + // Cognitive Services account commitment cost. + Cost *CommitmentCost + + // Account hosting model. + HostingModel *HostingModel + + // The kind (type) of cognitive service account. + Kind *string + + // Commitment period commitment max count. + MaxCount *int32 + + // Commitment plan type. + PlanType *string + + // Cognitive Services account commitment quota. + Quota *CommitmentQuota + + // The name of the SKU. Ex - P3. It is typically a letter+number code + SKUName *string + + // Commitment period commitment tier. + Tier *string +} + +// CommitmentTierListResult - The list of cognitive services accounts operation response. +type CommitmentTierListResult struct { + // The link used to get the next page of CommitmentTier. + NextLink *string + + // READ-ONLY; Gets the list of Cognitive Services accounts CommitmentTier and their properties. + Value []*CommitmentTier +} + +// ConnectionAPIKey - Api key object for connection credential. +type ConnectionAPIKey struct { + Key *string +} + +type ConnectionAccessKey struct { + AccessKeyID *string + SecretAccessKey *string +} + +// ConnectionAccountKey - Account key object for connection credential. +type ConnectionAccountKey struct { + Key *string +} + +type ConnectionManagedIdentity struct { + ClientID *string + ResourceID *string +} + +// ConnectionOAuth2 - ClientId and ClientSecret are required. Other properties are optional +// depending on each OAuth2 provider's implementation. +type ConnectionOAuth2 struct { + // Required by Concur connection category + AuthURL *string + + // Client id in the format of UUID + ClientID *string + ClientSecret *string + + // Required by GoogleAdWords connection category + DeveloperToken *string + Password *string + + // Required by GoogleBigQuery, GoogleAdWords, Hubspot, QuickBooks, Square, Xero, Zoho + // where user needs to get RefreshToken offline + RefreshToken *string + + // Required by QuickBooks and Xero connection categories + TenantID *string + + // Concur, ServiceNow auth server AccessToken grant type is 'Password' + // which requires UsernamePassword + Username *string +} + +type ConnectionPersonalAccessToken struct { + Pat *string +} + +// ConnectionPropertiesV2 - Connection property base schema. +type ConnectionPropertiesV2 struct { + // REQUIRED; Authentication type of the connection target + AuthType *ConnectionAuthType + + // Category of the connection + Category *ConnectionCategory + + // Provides the error message if the connection fails + Error *string + ExpiryTime *time.Time + IsSharedToAll *bool + + // Store user metadata for this connection + Metadata map[string]*string + + // Specifies how private endpoints are used with this connection: 'Required', 'NotRequired', or 'NotApplicable'. + PeRequirement *ManagedPERequirement + + // Specifies the status of private endpoints for this connection: 'Inactive', 'Active', or 'NotApplicable'. + PeStatus *ManagedPEStatus + SharedUserList []*string + + // The connection URL to be used. + Target *string + UseWorkspaceManagedIdentity *bool + + // READ-ONLY + CreatedByWorkspaceArmID *string + + // READ-ONLY; Group based on connection category + Group *ConnectionGroup +} + +// GetConnectionPropertiesV2 implements the ConnectionPropertiesV2Classification interface for type ConnectionPropertiesV2. +func (c *ConnectionPropertiesV2) GetConnectionPropertiesV2() *ConnectionPropertiesV2 { return c } + +// ConnectionPropertiesV2BasicResource - Connection base resource schema. +type ConnectionPropertiesV2BasicResource struct { + // REQUIRED; Connection property base schema. + Properties ConnectionPropertiesV2Classification + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +type ConnectionPropertiesV2BasicResourceArmPaginatedResult struct { + NextLink *string + Value []*ConnectionPropertiesV2BasicResource +} + +type ConnectionServicePrincipal struct { + ClientID *string + ClientSecret *string + TenantID *string +} + +type ConnectionSharedAccessSignature struct { + Sas *string +} + +// ConnectionUpdateContent - The properties that the Cognitive services connection will be updated with. +type ConnectionUpdateContent struct { + // The properties that the Cognitive services connection will be updated with. + Properties ConnectionPropertiesV2Classification +} + +type ConnectionUsernamePassword struct { + Password *string + + // Optional, required by connections like SalesForce for extra security in addition to UsernamePassword + SecurityToken *string + Username *string +} + +// CustomBlocklistConfig - Gets or sets the source to which filter applies. +type CustomBlocklistConfig struct { + // If blocking would occur. + Blocking *bool + + // Name of ContentFilter. + BlocklistName *string + + // Content source to apply the Content Filters. + Source *RaiPolicyContentSource +} + +// CustomKeys - Custom Keys credential object +type CustomKeys struct { + // Dictionary of + Keys map[string]*string +} + +// CustomKeysConnectionProperties - Category:= CustomKeys +// AuthType:= CustomKeys (as type discriminator) +// Credentials:= {CustomKeys} as CustomKeys +// Target:= {any value} +// Use Metadata property bag for ApiVersion and other metadata fields +type CustomKeysConnectionProperties struct { + // CONSTANT; Authentication type of the connection target + // Field has constant value ConnectionAuthTypeCustomKeys, any specified value is ignored. + AuthType *ConnectionAuthType + + // Category of the connection + Category *ConnectionCategory + + // Custom Keys credential object + Credentials *CustomKeys + + // Provides the error message if the connection fails + Error *string + ExpiryTime *time.Time + IsSharedToAll *bool + + // Store user metadata for this connection + Metadata map[string]*string + + // Specifies how private endpoints are used with this connection: 'Required', 'NotRequired', or 'NotApplicable'. + PeRequirement *ManagedPERequirement + + // Specifies the status of private endpoints for this connection: 'Inactive', 'Active', or 'NotApplicable'. + PeStatus *ManagedPEStatus + SharedUserList []*string + + // The connection URL to be used. + Target *string + UseWorkspaceManagedIdentity *bool + + // READ-ONLY + CreatedByWorkspaceArmID *string + + // READ-ONLY; Group based on connection category + Group *ConnectionGroup +} + +// GetConnectionPropertiesV2 implements the ConnectionPropertiesV2Classification interface for type CustomKeysConnectionProperties. +func (c *CustomKeysConnectionProperties) GetConnectionPropertiesV2() *ConnectionPropertiesV2 { + return &ConnectionPropertiesV2{ + AuthType: c.AuthType, + Category: c.Category, + CreatedByWorkspaceArmID: c.CreatedByWorkspaceArmID, + Error: c.Error, + ExpiryTime: c.ExpiryTime, + Group: c.Group, + IsSharedToAll: c.IsSharedToAll, + Metadata: c.Metadata, + PeRequirement: c.PeRequirement, + PeStatus: c.PeStatus, + SharedUserList: c.SharedUserList, + Target: c.Target, + UseWorkspaceManagedIdentity: c.UseWorkspaceManagedIdentity, + } +} + +// DefenderForAISetting - The Defender for AI resource. +type DefenderForAISetting struct { + // The Defender for AI resource properties. + Properties *DefenderForAISettingProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Resource Etag. + Etag *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// DefenderForAISettingProperties - The Defender for AI resource properties. +type DefenderForAISettingProperties struct { + // Defender for AI state on the AI resource. + State *DefenderForAISettingState +} + +// DefenderForAISettingResult - The list of cognitive services Defender for AI Settings. +type DefenderForAISettingResult struct { + // The link used to get the next page of Defender for AI Settings. + NextLink *string + + // The list of Defender for AI Settings. + Value []*DefenderForAISetting +} + +// Deployment - Cognitive Services account deployment. +type Deployment struct { + // Properties of Cognitive Services account deployment. + Properties *DeploymentProperties + + // The resource model definition representing SKU + SKU *SKU + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Resource Etag. + Etag *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// DeploymentCapacitySettings - Internal use only. +type DeploymentCapacitySettings struct { + // The designated capacity. + DesignatedCapacity *int32 + + // The priority of this capacity setting. + Priority *int32 +} + +// DeploymentListResult - The list of cognitive services accounts operation response. +type DeploymentListResult struct { + // The link used to get the next page of Deployment. + NextLink *string + + // READ-ONLY; Gets the list of Cognitive Services accounts Deployment and their properties. + Value []*Deployment +} + +// DeploymentModel - Properties of Cognitive Services account deployment model. +type DeploymentModel struct { + // Deployment model format. + Format *string + + // Deployment model name. + Name *string + + // Deployment model publisher. + Publisher *string + + // Optional. Deployment model source ARM resource ID. + Source *string + + // Optional. Source of the model, another Microsoft.CognitiveServices accounts ARM resource ID. + SourceAccount *string + + // Optional. Deployment model version. If version is not specified, a default version will be assigned. The default version + // is different for different models and might change when there is new version available for a model. Default version for + // a model could be found from list models API. + Version *string + + // READ-ONLY; The call rate limit Cognitive Services account. + CallRateLimit *CallRateLimit +} + +// DeploymentProperties - Properties of Cognitive Services account deployment. +type DeploymentProperties struct { + // Internal use only. + CapacitySettings *DeploymentCapacitySettings + + // The current capacity. + CurrentCapacity *int32 + + // The state of the deployment. Controls whether the deployment is accepting inference requests. Use 'Running' for active + // deployments that process requests, or 'Paused' to temporarily stop inference while preserving the deployment configuration. + DeploymentState *DeploymentState + + // Properties of Cognitive Services account deployment model. + Model *DeploymentModel + + // The name of parent deployment. + ParentDeploymentName *string + + // The name of RAI policy. + RaiPolicyName *string + + // Routing configuration for the model-router deployment. This property is only applicable when the deployed model is 'model-router' + // version 2025-11-18 or later. Allows you to select the models subset for routing and the routing mode (balanced, quality, + // cost) for routing across all supported models or the model subset. + Routing *DeploymentRouting + + // Properties of Cognitive Services account deployment model. (Deprecated, please use Deployment.sku instead.) + ScaleSettings *DeploymentScaleSettings + + // The service tier for the deployment. Determines the pricing and performance level for request processing. Use 'Default' + // for standard pricing or 'Priority' for higher-priority processing with premium pricing. Note: Pause operations are only + // supported on Standard, DataZoneStandard, and GlobalStandard SKUs. + ServiceTier *ServiceTier + + // Specifies the deployment name that should serve requests when the request would have otherwise been throttled due to reaching + // current deployment throughput limit. + SpilloverDeploymentName *string + + // Deployment model version upgrade option. + VersionUpgradeOption *DeploymentModelVersionUpgradeOption + + // READ-ONLY; The call rate limit Cognitive Services account. + CallRateLimit *CallRateLimit + + // READ-ONLY; The capabilities. + Capabilities map[string]*string + + // READ-ONLY; If the dynamic throttling is enabled. + DynamicThrottlingEnabled *bool + + // READ-ONLY; Gets the status of the resource at the time the operation was called. + ProvisioningState *DeploymentProvisioningState + + // READ-ONLY + RateLimits []*ThrottlingRule +} + +// DeploymentRouting - Routing configuration for the model-router deployment. Specifies how requests are routed across multiple +// models. +type DeploymentRouting struct { + // The model-router routing mode that determines how requests are distributed across models. + Mode *RoutingMode + + // Optional. The list of model-router supported models that the model router can use to route requests across. If not specified, + // the model router will route to all available models specified in the model-router version. + Models []*DeploymentModel +} + +// DeploymentSKUListResult - The list of cognitive services accounts operation response. +type DeploymentSKUListResult struct { + // The link used to get the next page of deployment skus. + NextLink *string + + // READ-ONLY; Gets the list of Cognitive Services accounts deployment skus. + Value []*SKUResource +} + +// DeploymentScaleSettings - Properties of Cognitive Services account deployment model. (Deprecated, please use Deployment.sku +// instead.) +type DeploymentScaleSettings struct { + // Deployment capacity. + Capacity *int32 + + // Deployment scale type. + ScaleType *DeploymentScaleType + + // READ-ONLY; Deployment active capacity. This value might be different from `capacity` if customer recently updated `capacity`. + ActiveCapacity *int32 +} + +// DomainAvailability - Domain availability. +type DomainAvailability struct { + // Indicates the given SKU is available or not. + IsSubdomainAvailable *bool + + // The kind (type) of cognitive service account. + Kind *string + + // Reason why the SKU is not available. + Reason *string + + // The subdomain name to use. + SubdomainName *string + + // The Type of the resource. + Type *string +} + +// Encryption - Properties to configure Encryption +type Encryption struct { + // Enumerates the possible value of keySource for Encryption + KeySource *KeySource + + // Properties of KeyVault + KeyVaultProperties *KeyVaultProperties +} + +// EncryptionScope - Cognitive Services EncryptionScope +type EncryptionScope struct { + // Properties of Cognitive Services EncryptionScope. + Properties *EncryptionScopeProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Resource Etag. + Etag *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// EncryptionScopeListResult - The list of cognitive services EncryptionScopes. +type EncryptionScopeListResult struct { + // The link used to get the next page of EncryptionScope. + NextLink *string + + // The list of EncryptionScope. + Value []*EncryptionScope +} + +// EncryptionScopeProperties - Properties to EncryptionScope +type EncryptionScopeProperties struct { + // Enumerates the possible value of keySource for Encryption + KeySource *KeySource + + // Properties of KeyVault + KeyVaultProperties *KeyVaultProperties + + // The encryptionScope state. + State *EncryptionScopeState + + // READ-ONLY; Gets the status of the resource at the time the operation was called. + ProvisioningState *EncryptionScopeProvisioningState +} + +// FqdnOutboundRule - FQDN Outbound Rule for the managed network of a cognitive services account. +type FqdnOutboundRule struct { + // CONSTANT; Type of a managed network Outbound Rule of a cognitive services account. + // Field has constant value RuleTypeFQDN, any specified value is ignored. + Type *RuleType + + // Category of a managed network Outbound Rule of a cognitive services account. + Category *RuleCategory + Destination *string + + // Type of a managed network Outbound Rule of a cognitive services account. + Status *RuleStatus + + // READ-ONLY; Error information about an outbound rule of a cognitive services account if RuleStatus is failed. + ErrorInformation *string + + // READ-ONLY + ParentRuleNames []*string +} + +// GetOutboundRule implements the OutboundRuleClassification interface for type FqdnOutboundRule. +func (f *FqdnOutboundRule) GetOutboundRule() *OutboundRule { + return &OutboundRule{ + Category: f.Category, + ErrorInformation: f.ErrorInformation, + ParentRuleNames: f.ParentRuleNames, + Status: f.Status, + Type: f.Type, + } +} + +// HostedAgentDeployment - Represents a hosted agent deployment where the underlying infrastructure is owned by the platform. +type HostedAgentDeployment struct { + // CONSTANT; Gets or sets the type of deployment for the agent. + // Field has constant value AgentDeploymentTypeHosted, any specified value is ignored. + DeploymentType *AgentDeploymentType + + // Returns a flat list of agent:version deployed in this deployment. + Agents []*VersionedAgentReference + + // Gets or sets the unique identifier of the deployment. + DeploymentID *string + + // The asset description text. + Description *string + + // Gets or sets the display name of the deployment. + DisplayName *string + + // Gets or sets the maximum number of replicas for this hosted deployment. + MaxReplicas *int32 + + // Gets or sets the minimum number of replicas for this hosted deployment. + MinReplicas *int32 + + // Gets or sets the supported protocol types and versions exposed by this deployment. + Protocols []*AgentProtocolVersion + + // Gets or sets the current operational state of the deployment (and, intrinsically, of the comprising agents). + State *AgentDeploymentState + + // Tag dictionary. Tags can be added, removed, and updated. + Tags map[string]*string + + // READ-ONLY; Gets or sets the provisioning state of the agent deployment. + ProvisioningState *AgentDeploymentProvisioningState +} + +// GetAgentDeploymentProperties implements the AgentDeploymentPropertiesClassification interface for type HostedAgentDeployment. +func (h *HostedAgentDeployment) GetAgentDeploymentProperties() *AgentDeploymentProperties { + return &AgentDeploymentProperties{ + Agents: h.Agents, + DeploymentID: h.DeploymentID, + DeploymentType: h.DeploymentType, + Description: h.Description, + DisplayName: h.DisplayName, + Protocols: h.Protocols, + ProvisioningState: h.ProvisioningState, + State: h.State, + Tags: h.Tags, + } +} + +// IPRule - A rule governing the accessibility from a specific ip address or ip range. +type IPRule struct { + // REQUIRED; An IPv4 address range in CIDR notation, such as '124.56.78.91' (simple IP address) or '124.56.78.0/24' (all addresses + // that start with 124.56.78). + Value *string +} + +// Identity for the resource. +type Identity struct { + // The identity type. + Type *ResourceIdentityType + + // The list of user assigned identities associated with the resource. The user identity dictionary key references will be + // ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName} + UserAssignedIdentities map[string]*UserAssignedIdentity + + // READ-ONLY; The principal ID of resource identity. + PrincipalID *string + + // READ-ONLY; The tenant ID of resource. + TenantID *string +} + +// KeyVaultProperties - Properties to configure keyVault Properties +type KeyVaultProperties struct { + IdentityClientID *string + + // Name of the Key from KeyVault + KeyName *string + + // Uri of KeyVault + KeyVaultURI *string + + // Version of the Key from KeyVault + KeyVersion *string +} + +// ManagedAgentDeployment - Represents a managed agent deployment where the underlying infrastructure is managed by the platform +// in the deployer's subscription. +type ManagedAgentDeployment struct { + // CONSTANT; Gets or sets the type of deployment for the agent. + // Field has constant value AgentDeploymentTypeManaged, any specified value is ignored. + DeploymentType *AgentDeploymentType + + // Returns a flat list of agent:version deployed in this deployment. + Agents []*VersionedAgentReference + + // Gets or sets the unique identifier of the deployment. + DeploymentID *string + + // The asset description text. + Description *string + + // Gets or sets the display name of the deployment. + DisplayName *string + + // Gets or sets the supported protocol types and versions exposed by this deployment. + Protocols []*AgentProtocolVersion + + // Gets or sets the current operational state of the deployment (and, intrinsically, of the comprising agents). + State *AgentDeploymentState + + // Tag dictionary. Tags can be added, removed, and updated. + Tags map[string]*string + + // READ-ONLY; Gets or sets the provisioning state of the agent deployment. + ProvisioningState *AgentDeploymentProvisioningState +} + +// GetAgentDeploymentProperties implements the AgentDeploymentPropertiesClassification interface for type ManagedAgentDeployment. +func (m *ManagedAgentDeployment) GetAgentDeploymentProperties() *AgentDeploymentProperties { + return &AgentDeploymentProperties{ + Agents: m.Agents, + DeploymentID: m.DeploymentID, + DeploymentType: m.DeploymentType, + Description: m.Description, + DisplayName: m.DisplayName, + Protocols: m.Protocols, + ProvisioningState: m.ProvisioningState, + State: m.State, + Tags: m.Tags, + } +} + +type ManagedIdentityAuthTypeConnectionProperties struct { + // CONSTANT; Authentication type of the connection target + // Field has constant value ConnectionAuthTypeManagedIdentity, any specified value is ignored. + AuthType *ConnectionAuthType + + // Category of the connection + Category *ConnectionCategory + Credentials *ConnectionManagedIdentity + + // Provides the error message if the connection fails + Error *string + ExpiryTime *time.Time + IsSharedToAll *bool + + // Store user metadata for this connection + Metadata map[string]*string + + // Specifies how private endpoints are used with this connection: 'Required', 'NotRequired', or 'NotApplicable'. + PeRequirement *ManagedPERequirement + + // Specifies the status of private endpoints for this connection: 'Inactive', 'Active', or 'NotApplicable'. + PeStatus *ManagedPEStatus + SharedUserList []*string + + // The connection URL to be used. + Target *string + UseWorkspaceManagedIdentity *bool + + // READ-ONLY + CreatedByWorkspaceArmID *string + + // READ-ONLY; Group based on connection category + Group *ConnectionGroup +} + +// GetConnectionPropertiesV2 implements the ConnectionPropertiesV2Classification interface for type ManagedIdentityAuthTypeConnectionProperties. +func (m *ManagedIdentityAuthTypeConnectionProperties) GetConnectionPropertiesV2() *ConnectionPropertiesV2 { + return &ConnectionPropertiesV2{ + AuthType: m.AuthType, + Category: m.Category, + CreatedByWorkspaceArmID: m.CreatedByWorkspaceArmID, + Error: m.Error, + ExpiryTime: m.ExpiryTime, + Group: m.Group, + IsSharedToAll: m.IsSharedToAll, + Metadata: m.Metadata, + PeRequirement: m.PeRequirement, + PeStatus: m.PeStatus, + SharedUserList: m.SharedUserList, + Target: m.Target, + UseWorkspaceManagedIdentity: m.UseWorkspaceManagedIdentity, + } +} + +// ManagedNetworkListResult - List of managed networks of a cognitive services account. +type ManagedNetworkListResult struct { + // The link to the next page constructed using the continuationToken. If null, there are no additional pages. + NextLink *string + + // The list of managed network settings of an account. Since this list may be incomplete, the nextLink field should be used + // to request the next list of cognitive services accounts. + Value []*ManagedNetworkSettingsPropertiesBasicResource +} + +// ManagedNetworkProvisionOptions - Managed Network Provisioning options for managed network of a cognitive services account. +type ManagedNetworkProvisionOptions struct { +} + +// ManagedNetworkProvisionStatus - Status of the Provisioning for the managed network of a cognitive services account. +type ManagedNetworkProvisionStatus struct { + // Status for the managed network of a cognitive services account. + Status *ManagedNetworkStatus +} + +// ManagedNetworkSettings - Managed Network settings for a cognitive services account. +type ManagedNetworkSettings struct { + // Firewall Sku used for FQDN Rules + FirewallSKU *FirewallSKU + + // Isolation mode for the managed network of a cognitive services account. + IsolationMode *IsolationMode + + // The Kind of the managed network. Users can switch from V1 to V2 for granular access controls, but cannot switch back to + // V1 once V2 is enabled. + ManagedNetworkKind *ManagedNetworkKind + + // Dictionary of + OutboundRules map[string]OutboundRuleClassification + + // Status of the Provisioning for the managed network of a cognitive services account. + Status *ManagedNetworkProvisionStatus + + // READ-ONLY; Public IP address assigned to the Azure Firewall. + FirewallPublicIPAddress *string + + // READ-ONLY + NetworkID *string + + // READ-ONLY; The provisioning state of the managed network settings. + ProvisioningState *ManagedNetworkProvisioningState +} + +type ManagedNetworkSettingsBasicResource struct { + // Managed Network settings for a cognitive services account. + Properties *ManagedNetworkSettings + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +type ManagedNetworkSettingsEx struct { + // Firewall Sku used for FQDN Rules + FirewallSKU *FirewallSKU + + // Isolation mode for the managed network of a cognitive services account. + IsolationMode *IsolationMode + + // The Kind of the managed network. Users can switch from V1 to V2 for granular access controls, but cannot switch back to + // V1 once V2 is enabled. + ManagedNetworkKind *ManagedNetworkKind + + // Dictionary of + OutboundRules map[string]OutboundRuleClassification + + // Status of the Provisioning for the managed network of a cognitive services account. + Status *ManagedNetworkProvisionStatus + + // READ-ONLY + ChangeableIsolationModes []*IsolationMode + + // READ-ONLY; Public IP address assigned to the Azure Firewall. + FirewallPublicIPAddress *string + + // READ-ONLY + NetworkID *string + + // READ-ONLY; The provisioning state of the managed network settings. + ProvisioningState *ManagedNetworkProvisioningState +} + +// ManagedNetworkSettingsProperties - The properties of the managed network settings of a cognitive services account. +type ManagedNetworkSettingsProperties struct { + // Managed Network settings for a cognitive services account. + ManagedNetwork *ManagedNetworkSettingsEx + + // READ-ONLY; The current deployment state of the managed network resource. The provisioningState is to indicate states for + // resource provisioning. + ProvisioningState *ManagedNetworkProvisioningState +} + +// ManagedNetworkSettingsPropertiesBasicResource - Concrete proxy resource types can be created by aliasing this type using +// a specific property type. +type ManagedNetworkSettingsPropertiesBasicResource struct { + // The properties of the managed network settings of a cognitive services account. + Properties *ManagedNetworkSettingsProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// MetricName - A metric name. +type MetricName struct { + // The friendly name of the metric. + LocalizedValue *string + + // The name of the metric. + Value *string +} + +// Model - Cognitive Services Model. +type Model struct { + // The description of the model. + Description *string + + // The kind (type) of cognitive service account. + Kind *string + + // Cognitive Services account Model. + Model *AccountModel + + // The name of SKU. + SKUName *string +} + +// ModelCapacityCalculatorWorkload - Model Capacity Calculator Workload. +type ModelCapacityCalculatorWorkload struct { + // Dictionary, Model Capacity Calculator Workload Parameters. + RequestParameters *ModelCapacityCalculatorWorkloadRequestParam + + // Request per minute. + RequestPerMinute *int64 +} + +// ModelCapacityCalculatorWorkloadRequestParam - Dictionary, Model Capacity Calculator Workload Parameters. +type ModelCapacityCalculatorWorkloadRequestParam struct { + // Average generated tokens. + AvgGeneratedTokens *int64 + + // Average prompt tokens. + AvgPromptTokens *int64 +} + +// ModelCapacityListResult - The list of cognitive services accounts operation response. +type ModelCapacityListResult struct { + // The link used to get the next page of ModelSkuCapacity. + NextLink *string + + // READ-ONLY; Gets the list of Cognitive Services accounts ModelSkuCapacity. + Value []*ModelCapacityListResultValueItem +} + +type ModelCapacityListResultValueItem struct { + // The location of the Model Sku Capacity. + Location *string + + // Cognitive Services account ModelSkuCapacity. + Properties *ModelSKUCapacityProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ModelDeprecationInfo - Cognitive Services account ModelDeprecationInfo. +type ModelDeprecationInfo struct { + // Indicates whether the deprecation date is a confirmed planned end-of-life date or an estimated deprecation date. When 'Planned', + // the deprecation date represents a confirmed and communicated model end-of-life date. When 'Tentative', the deprecation + // date is an estimated timeline that may be subject to change. + DeprecationStatus *DeprecationStatus + + // The datetime of deprecation of the fineTune Model. + FineTune *string + + // The datetime of deprecation of the inference Model. + Inference *string +} + +// ModelListResult - The list of cognitive services models. +type ModelListResult struct { + // The link used to get the next page of Model. + NextLink *string + + // Gets the list of Cognitive Services accounts Model and their properties. + Value []*Model +} + +// ModelSKU - Describes an available Cognitive Services Model SKU. +type ModelSKU struct { + // The capacity configuration. + Capacity *CapacityConfig + + // The list of billing meter info. + Cost []*BillingMeterInfo + + // The datetime of deprecation of the model SKU. + DeprecationDate *time.Time + + // The name of the model SKU. + Name *string + + // The list of rateLimit. + RateLimits []*CallRateLimit + + // The usage name of the model SKU. + UsageName *string +} + +// ModelSKUCapacityProperties - Cognitive Services account ModelSkuCapacity. +type ModelSKUCapacityProperties struct { + // The available capacity for deployment with this model and sku. + AvailableCapacity *float32 + + // The available capacity for deployment with a fine-tune version of this model and sku. + AvailableFinetuneCapacity *float32 + + // Properties of Cognitive Services account deployment model. + Model *DeploymentModel + SKUName *string +} + +// MultiRegionSettings - The multiregion settings Cognitive Services account. +type MultiRegionSettings struct { + Regions []*RegionSetting + + // Multiregion routing methods. + RoutingMethod *RoutingMethods +} + +// NetworkInjection - Specifies in AI Foundry where virtual network injection occurs to secure scenarios like Agents entirely +// within the user's private network, eliminating public internet exposure while maintaining control over network configurations +// and resources. +type NetworkInjection struct { + // Specifies what features in AI Foundry network injection applies to. Currently only supports 'agent' for agent scenarios. + // 'none' means no network injection. + Scenario *ScenarioType + + // Specify the subnet for which your Agent Client is injected into. + SubnetArmID *string + + // Boolean to enable Microsoft Managed Network for subnet delegation + UseMicrosoftManagedNetwork *bool +} + +// NetworkRuleSet - A set of rules governing the network accessibility. +type NetworkRuleSet struct { + // Setting for trusted services. + Bypass *ByPassSelection + + // The default action when no rule from ipRules and from virtualNetworkRules match. This is only used after the bypass property + // has been evaluated. + DefaultAction *NetworkRuleAction + + // The list of IP address rules. + IPRules []*IPRule + + // The list of virtual network rules. + VirtualNetworkRules []*VirtualNetworkRule +} + +// NetworkSecurityPerimeter - Information about a linked Network Security Perimeter +type NetworkSecurityPerimeter struct { + // Fully qualified identifier of the resource + ID *string + + // Location of the resource + Location *string + + // Guid of the resource + PerimeterGUID *string +} + +// NetworkSecurityPerimeterAccessRule - Network Security Perimeter Access Rule +type NetworkSecurityPerimeterAccessRule struct { + // Network Security Perimeter Access Rule Name + Name *string + + // Properties of Network Security Perimeter Access Rule + Properties *NetworkSecurityPerimeterAccessRuleProperties +} + +// NetworkSecurityPerimeterAccessRuleProperties - The Properties of Network Security Perimeter Rule +type NetworkSecurityPerimeterAccessRuleProperties struct { + // Address prefixes for inbound rules + AddressPrefixes []*string + + // Direction of Access Rule + Direction *NspAccessRuleDirection + + // Fully qualified domain name for outbound rules + FullyQualifiedDomainNames []*string + + // NetworkSecurityPerimeters for inbound rules + NetworkSecurityPerimeters []*NetworkSecurityPerimeter + + // Subscriptions for inbound rules + Subscriptions []*NetworkSecurityPerimeterAccessRulePropertiesSubscriptionsItem +} + +// NetworkSecurityPerimeterAccessRulePropertiesSubscriptionsItem - Subscription for inbound rule +type NetworkSecurityPerimeterAccessRulePropertiesSubscriptionsItem struct { + // Fully qualified identifier of subscription + ID *string +} + +// NetworkSecurityPerimeterConfiguration - NSP Configuration for an Cognitive Services account. +type NetworkSecurityPerimeterConfiguration struct { + // NSP Configuration properties. + Properties *NetworkSecurityPerimeterConfigurationProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// NetworkSecurityPerimeterConfigurationAssociationInfo - Network Security Perimeter Configuration Association Information +type NetworkSecurityPerimeterConfigurationAssociationInfo struct { + // Access Mode of the resource association + AccessMode *string + + // Name of the resource association + Name *string +} + +// NetworkSecurityPerimeterConfigurationList - A list of NSP configurations for an Cognitive Services account. +type NetworkSecurityPerimeterConfigurationList struct { + // Link to retrieve next page of results. + NextLink *string + + // Array of NSP configurations List Result for an Cognitive Services account. + Value []*NetworkSecurityPerimeterConfiguration +} + +// NetworkSecurityPerimeterConfigurationProperties - The properties of an NSP Configuration. +type NetworkSecurityPerimeterConfigurationProperties struct { + // Information about a linked Network Security Perimeter + NetworkSecurityPerimeter *NetworkSecurityPerimeter + + // Network Security Perimeter Profile Information + Profile *NetworkSecurityPerimeterProfileInfo + + // List of Provisioning Issues + ProvisioningIssues []*ProvisioningIssue + + // Network Security Perimeter Configuration Association Information + ResourceAssociation *NetworkSecurityPerimeterConfigurationAssociationInfo + + // READ-ONLY; Provisioning state of NetworkSecurityPerimeter configuration + ProvisioningState *string +} + +// NetworkSecurityPerimeterProfileInfo - Network Security Perimeter Profile Information +type NetworkSecurityPerimeterProfileInfo struct { + AccessRules []*NetworkSecurityPerimeterAccessRule + + // Access rules version of the resource profile + AccessRulesVersion *int64 + + // Current diagnostic settings version + DiagnosticSettingsVersion *int64 + + // List of enabled log categories + EnabledLogCategories []*string + + // Name of the resource profile + Name *string +} + +type NoneAuthTypeConnectionProperties struct { + // CONSTANT; Authentication type of the connection target + // Field has constant value ConnectionAuthTypeNone, any specified value is ignored. + AuthType *ConnectionAuthType + + // Category of the connection + Category *ConnectionCategory + + // Provides the error message if the connection fails + Error *string + ExpiryTime *time.Time + IsSharedToAll *bool + + // Store user metadata for this connection + Metadata map[string]*string + + // Specifies how private endpoints are used with this connection: 'Required', 'NotRequired', or 'NotApplicable'. + PeRequirement *ManagedPERequirement + + // Specifies the status of private endpoints for this connection: 'Inactive', 'Active', or 'NotApplicable'. + PeStatus *ManagedPEStatus + SharedUserList []*string + + // The connection URL to be used. + Target *string + UseWorkspaceManagedIdentity *bool + + // READ-ONLY + CreatedByWorkspaceArmID *string + + // READ-ONLY; Group based on connection category + Group *ConnectionGroup +} + +// GetConnectionPropertiesV2 implements the ConnectionPropertiesV2Classification interface for type NoneAuthTypeConnectionProperties. +func (n *NoneAuthTypeConnectionProperties) GetConnectionPropertiesV2() *ConnectionPropertiesV2 { + return &ConnectionPropertiesV2{ + AuthType: n.AuthType, + Category: n.Category, + CreatedByWorkspaceArmID: n.CreatedByWorkspaceArmID, + Error: n.Error, + ExpiryTime: n.ExpiryTime, + Group: n.Group, + IsSharedToAll: n.IsSharedToAll, + Metadata: n.Metadata, + PeRequirement: n.PeRequirement, + PeStatus: n.PeStatus, + SharedUserList: n.SharedUserList, + Target: n.Target, + UseWorkspaceManagedIdentity: n.UseWorkspaceManagedIdentity, + } +} + +type OAuth2AuthTypeConnectionProperties struct { + // CONSTANT; Authentication type of the connection target + // Field has constant value ConnectionAuthTypeOAuth2, any specified value is ignored. + AuthType *ConnectionAuthType + + // Category of the connection + Category *ConnectionCategory + + // ClientId and ClientSecret are required. Other properties are optional + // depending on each OAuth2 provider's implementation. + Credentials *ConnectionOAuth2 + + // Provides the error message if the connection fails + Error *string + ExpiryTime *time.Time + IsSharedToAll *bool + + // Store user metadata for this connection + Metadata map[string]*string + + // Specifies how private endpoints are used with this connection: 'Required', 'NotRequired', or 'NotApplicable'. + PeRequirement *ManagedPERequirement + + // Specifies the status of private endpoints for this connection: 'Inactive', 'Active', or 'NotApplicable'. + PeStatus *ManagedPEStatus + SharedUserList []*string + + // The connection URL to be used. + Target *string + UseWorkspaceManagedIdentity *bool + + // READ-ONLY + CreatedByWorkspaceArmID *string + + // READ-ONLY; Group based on connection category + Group *ConnectionGroup +} + +// GetConnectionPropertiesV2 implements the ConnectionPropertiesV2Classification interface for type OAuth2AuthTypeConnectionProperties. +func (o *OAuth2AuthTypeConnectionProperties) GetConnectionPropertiesV2() *ConnectionPropertiesV2 { + return &ConnectionPropertiesV2{ + AuthType: o.AuthType, + Category: o.Category, + CreatedByWorkspaceArmID: o.CreatedByWorkspaceArmID, + Error: o.Error, + ExpiryTime: o.ExpiryTime, + Group: o.Group, + IsSharedToAll: o.IsSharedToAll, + Metadata: o.Metadata, + PeRequirement: o.PeRequirement, + PeStatus: o.PeStatus, + SharedUserList: o.SharedUserList, + Target: o.Target, + UseWorkspaceManagedIdentity: o.UseWorkspaceManagedIdentity, + } +} + +// Operation - REST API Operation +// +// Details of a REST API operation, returned from the Resource Provider Operations API +type Operation struct { + // Localized display information for this particular operation. + Display *OperationDisplay + + // READ-ONLY; Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + ActionType *ActionType + + // READ-ONLY; Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure + // Resource Manager/control-plane operations. + IsDataAction *bool + + // READ-ONLY; The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + // "Microsoft.Compute/virtualMachines/capture/action" + Name *string + + // READ-ONLY; The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default + // value is "user,system" + Origin *Origin +} + +// OperationDisplay - Localized display information for an operation. +type OperationDisplay struct { + // READ-ONLY; The short, localized friendly description of the operation; suitable for tool tips and detailed views. + Description *string + + // READ-ONLY; The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual + // Machine", "Restart Virtual Machine". + Operation *string + + // READ-ONLY; The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft + // Compute". + Provider *string + + // READ-ONLY; The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job + // Schedule Collections". + Resource *string +} + +// OperationListResult - A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to +// get the next set of results. +type OperationListResult struct { + // REQUIRED; The Operation items on this page + Value []*Operation + + // The link to the next page of items + NextLink *string +} + +// OrganizationSharedBuiltInAuthorizationPolicy - Built-in authorization policy scoped to organization/tenant. +type OrganizationSharedBuiltInAuthorizationPolicy struct { + // CONSTANT; Authorization scheme type. + // Field has constant value BuiltInAuthorizationSchemeOrganizationScope, any specified value is ignored. + Type *BuiltInAuthorizationScheme +} + +// GetApplicationAuthorizationPolicy implements the ApplicationAuthorizationPolicyClassification interface for type OrganizationSharedBuiltInAuthorizationPolicy. +func (o *OrganizationSharedBuiltInAuthorizationPolicy) GetApplicationAuthorizationPolicy() *ApplicationAuthorizationPolicy { + return &ApplicationAuthorizationPolicy{ + Type: o.Type, + } +} + +// OutboundRule - Outbound Rule for the managed network of a cognitive services account. +type OutboundRule struct { + // REQUIRED; Type of a managed network Outbound Rule of a cognitive services account. + Type *RuleType + + // Category of a managed network Outbound Rule of a cognitive services account. + Category *RuleCategory + + // Type of a managed network Outbound Rule of a cognitive services account. + Status *RuleStatus + + // READ-ONLY; Error information about an outbound rule of a cognitive services account if RuleStatus is failed. + ErrorInformation *string + + // READ-ONLY + ParentRuleNames []*string +} + +// GetOutboundRule implements the OutboundRuleClassification interface for type OutboundRule. +func (o *OutboundRule) GetOutboundRule() *OutboundRule { return o } + +// OutboundRuleBasicResource - Concrete proxy resource types can be created by aliasing this type using a specific property +// type. +type OutboundRuleBasicResource struct { + // REQUIRED; Outbound Rule for the managed network of a cognitive services account. + Properties OutboundRuleClassification + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// OutboundRuleListResult - List of outbound rules for the managed network of a cognitive services account. +type OutboundRuleListResult struct { + // The link to the next page constructed using the continuationToken. If null, there are no additional pages. + NextLink *string + + // The list of cognitive services accounts. Since this list may be incomplete, the nextLink field should be used to request + // the next list of cognitive services accounts. + Value []*OutboundRuleBasicResource +} + +type PATAuthTypeConnectionProperties struct { + // CONSTANT; Authentication type of the connection target + // Field has constant value ConnectionAuthTypePAT, any specified value is ignored. + AuthType *ConnectionAuthType + + // Category of the connection + Category *ConnectionCategory + Credentials *ConnectionPersonalAccessToken + + // Provides the error message if the connection fails + Error *string + ExpiryTime *time.Time + IsSharedToAll *bool + + // Store user metadata for this connection + Metadata map[string]*string + + // Specifies how private endpoints are used with this connection: 'Required', 'NotRequired', or 'NotApplicable'. + PeRequirement *ManagedPERequirement + + // Specifies the status of private endpoints for this connection: 'Inactive', 'Active', or 'NotApplicable'. + PeStatus *ManagedPEStatus + SharedUserList []*string + + // The connection URL to be used. + Target *string + UseWorkspaceManagedIdentity *bool + + // READ-ONLY + CreatedByWorkspaceArmID *string + + // READ-ONLY; Group based on connection category + Group *ConnectionGroup +} + +// GetConnectionPropertiesV2 implements the ConnectionPropertiesV2Classification interface for type PATAuthTypeConnectionProperties. +func (p *PATAuthTypeConnectionProperties) GetConnectionPropertiesV2() *ConnectionPropertiesV2 { + return &ConnectionPropertiesV2{ + AuthType: p.AuthType, + Category: p.Category, + CreatedByWorkspaceArmID: p.CreatedByWorkspaceArmID, + Error: p.Error, + ExpiryTime: p.ExpiryTime, + Group: p.Group, + IsSharedToAll: p.IsSharedToAll, + Metadata: p.Metadata, + PeRequirement: p.PeRequirement, + PeStatus: p.PeStatus, + SharedUserList: p.SharedUserList, + Target: p.Target, + UseWorkspaceManagedIdentity: p.UseWorkspaceManagedIdentity, + } +} + +// PatchResourceTagsAndSKU - The object being used to update tags and sku of a resource, in general used for PATCH operations. +type PatchResourceTagsAndSKU struct { + // The resource model definition representing SKU + SKU *SKU + + // Resource tags. + Tags map[string]*string +} + +// PrivateEndpoint - The private endpoint resource. +type PrivateEndpoint struct { + // READ-ONLY; The resource identifier of the private endpoint + ID *string +} + +// PrivateEndpointConnection - The Private Endpoint Connection resource. +type PrivateEndpointConnection struct { + // The location of the private endpoint connection + Location *string + + // Resource properties. + Properties *PrivateEndpointConnectionProperties + + // READ-ONLY; Resource Etag. + Etag *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// PrivateEndpointConnectionListResult - A list of private endpoint connections +type PrivateEndpointConnectionListResult struct { + // Array of private endpoint connections + Value []*PrivateEndpointConnection +} + +// PrivateEndpointConnectionProperties - Properties of the PrivateEndpointConnectProperties. +type PrivateEndpointConnectionProperties struct { + // REQUIRED; A collection of information about the state of the connection between service consumer and provider. + PrivateLinkServiceConnectionState *PrivateLinkServiceConnectionState + + // The private link resource group ids. + GroupIDs []*string + + // The resource of private end point. + PrivateEndpoint *PrivateEndpoint + + // READ-ONLY; The provisioning state of the private endpoint connection resource. + ProvisioningState *PrivateEndpointConnectionProvisioningState +} + +// PrivateEndpointOutboundRule - Private Endpoint outbound rule for the managed network of a cognitive services account. +type PrivateEndpointOutboundRule struct { + // CONSTANT; Type of a managed network Outbound Rule of a cognitive services account. + // Field has constant value RuleTypePrivateEndpoint, any specified value is ignored. + Type *RuleType + + // Category of a managed network Outbound Rule of a cognitive services account. + Category *RuleCategory + + // Private Endpoint destination. + Destination *PrivateEndpointOutboundRuleDestination + + // List of FQDNs associated with the private endpoint outbound rule. + Fqdns []*string + + // Type of a managed network Outbound Rule of a cognitive services account. + Status *RuleStatus + + // READ-ONLY; Error information about an outbound rule of a cognitive services account if RuleStatus is failed. + ErrorInformation *string + + // READ-ONLY + ParentRuleNames []*string +} + +// GetOutboundRule implements the OutboundRuleClassification interface for type PrivateEndpointOutboundRule. +func (p *PrivateEndpointOutboundRule) GetOutboundRule() *OutboundRule { + return &OutboundRule{ + Category: p.Category, + ErrorInformation: p.ErrorInformation, + ParentRuleNames: p.ParentRuleNames, + Status: p.Status, + Type: p.Type, + } +} + +// PrivateEndpointOutboundRuleDestination - Private Endpoint destination for an outbound rule. +type PrivateEndpointOutboundRuleDestination struct { + // The Azure resource ID of the target private endpoint service. + ServiceResourceID *string + + // The subresource of the target service to connect to. + SubresourceTarget *string +} + +// PrivateLinkResource - A private link resource +type PrivateLinkResource struct { + // Resource properties. + Properties *PrivateLinkResourceProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// PrivateLinkResourceListResult - A list of private link resources +type PrivateLinkResourceListResult struct { + // Array of private link resources + Value []*PrivateLinkResource +} + +// PrivateLinkResourceProperties - Properties of a private link resource. +type PrivateLinkResourceProperties struct { + // The private link resource Private link DNS zone name. + RequiredZoneNames []*string + + // READ-ONLY; The private link resource display name. + DisplayName *string + + // READ-ONLY; The private link resource group id. + GroupID *string + + // READ-ONLY; The private link resource required member names. + RequiredMembers []*string +} + +// PrivateLinkServiceConnectionState - A collection of information about the state of the connection between service consumer +// and provider. +type PrivateLinkServiceConnectionState struct { + // A message indicating if changes on the service provider require any updates on the consumer. + ActionsRequired *string + + // The reason for approval/rejection of the connection. + Description *string + + // Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. + Status *PrivateEndpointServiceConnectionStatus +} + +// Project - Cognitive Services project is an Azure resource representing the provisioned account's project, it's type, location +// and SKU. +type Project struct { + // Identity for the resource. + Identity *Identity + + // The geo-location where the resource lives + Location *string + + // Properties of Cognitive Services project. + Properties *ProjectProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Resource Etag. + Etag *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ProjectCapabilityHost - Azure Resource Manager resource envelope for Project CapabilityHost. +type ProjectCapabilityHost struct { + // REQUIRED; [Required] Additional attributes of the entity. + Properties *ProjectCapabilityHostProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +type ProjectCapabilityHostProperties struct { + // List of AI services connections. + AiServicesConnections []*string + + // List of connection names from those available in the account or project to be used as a storage resource. + StorageConnections []*string + + // List of connection names from those available in the account or project to be used for Thread storage. + ThreadStorageConnections []*string + + // List of connection names from those available in the account or project to be used for vector database (e.g. CosmosDB). + VectorStoreConnections []*string + + // READ-ONLY; Provisioning state for the CapabilityHost. + ProvisioningState *CapabilityHostProvisioningState +} + +// ProjectCapabilityHostResourceArmPaginatedResult - A paginated list of Project Capability Host entities. +type ProjectCapabilityHostResourceArmPaginatedResult struct { + // The link to the next page of Project Capability Host objects. If null, there are no additional pages. + NextLink *string + + // An array of objects of type Project Capability Host. + Value []*ProjectCapabilityHost +} + +// ProjectListResult - The list of cognitive services projects operation response. +type ProjectListResult struct { + // The link used to get the next page of projects. + NextLink *string + + // READ-ONLY; Gets the list of Cognitive Services projects and their properties. + Value []*Project +} + +// ProjectProperties - Properties of Cognitive Services Project'. +type ProjectProperties struct { + // The description of the Cognitive Services Project. + Description *string + + // The display name of the Cognitive Services Project. + DisplayName *string + + // READ-ONLY; The list of endpoint for this Cognitive Services Project. + Endpoints map[string]*string + + // READ-ONLY; Indicates whether the project is the default project for the account. + IsDefault *bool + + // READ-ONLY; Gets the status of the cognitive services project at the time the operation was called. + ProvisioningState *ProvisioningState +} + +type ProvisioningIssue struct { + // Name of the NSP provisioning issue + Name *string + + // Properties of Provisioning Issue + Properties *ProvisioningIssueProperties +} + +// ProvisioningIssueProperties - Properties of Provisioning Issue +type ProvisioningIssueProperties struct { + // Description of the issue + Description *string + + // Type of Issue + IssueType *string + + // Severity of the issue + Severity *string + + // Optional array, suggested access rules + SuggestedAccessRules []*NetworkSecurityPerimeterAccessRule + + // IDs of resources that can be associated to the same perimeter to remediate the issue. + SuggestedResourceIDs []*string +} + +type QuotaLimit struct { + Count *float32 + RenewalPeriod *float32 + Rules []*ThrottlingRule +} + +// QuotaTier - The quota tier information for the subscription +type QuotaTier struct { + // Properties of quota tier resource. + Properties *QuotaTierProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// QuotaTierListResult - The list of Quota Tiers response. +type QuotaTierListResult struct { + // The link used to get the next page of quota tiers. + NextLink *string + + // READ-ONLY; Gets the list of Quota Tiers and their properties. + Value []*QuotaTier +} + +// QuotaTierProperties - Properties of Quota Tier resource'. +type QuotaTierProperties struct { + // Gets the tier upgrade policy for the subscription. + TierUpgradePolicy *TierUpgradePolicy + + // READ-ONLY; The date on which the current tier was assigned to the subscription (UTC). + AssignmentDate *time.Time + + // READ-ONLY; Name of the current quota tier for the subscription. + CurrentTierName *string + + // READ-ONLY; Information about the quota tier upgrade eligibility for the subscription. + TierUpgradeEligibilityInfo *QuotaTierUpgradeEligibilityInfo +} + +// QuotaTierUpgradeEligibilityInfo - Information about the quota tier upgrade eligibility for the subscription. +type QuotaTierUpgradeEligibilityInfo struct { + // Name of the next quota tier for the subscription. + NextTierName *string + + // The date after which the current tier will be upgraded to the next tier if the TierUpgradePolicy is "OnceUpgradeIsAvailable" + // (UTC). + UpgradeApplicableDate *time.Time + + // Specifies whether an upgrade to the next quota tier is available. + UpgradeAvailabilityStatus *UpgradeAvailabilityStatus + + // Reason in case the subscription is not eligible for upgrade to the next tier. + UpgradeUnavailabilityReason *string +} + +// RaiBlockListItemsResult - The list of cognitive services RAI Blocklist Items. +type RaiBlockListItemsResult struct { + // The link used to get the next page of RaiBlocklistItems. + NextLink *string + + // The list of RaiBlocklistItems. + Value []*RaiBlocklistItem +} + +// RaiBlockListResult - The list of cognitive services RAI Blocklists. +type RaiBlockListResult struct { + // The link used to get the next page of RaiBlocklists. + NextLink *string + + // The list of RaiBlocklist. + Value []*RaiBlocklist +} + +// RaiBlocklist - Cognitive Services RaiBlocklist. +type RaiBlocklist struct { + // Properties of Cognitive Services RaiBlocklist. + Properties *RaiBlocklistProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Resource Etag. + Etag *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// RaiBlocklistItem - Cognitive Services RaiBlocklist Item. +type RaiBlocklistItem struct { + // Properties of Cognitive Services RaiBlocklist Item. + Properties *RaiBlocklistItemProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Resource Etag. + Etag *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// RaiBlocklistItemBulkRequest - The Cognitive Services RaiBlocklist Item request body. +type RaiBlocklistItemBulkRequest struct { + Name *string + + // Properties of Cognitive Services RaiBlocklist Item. + Properties *RaiBlocklistItemProperties +} + +// RaiBlocklistItemProperties - RAI Custom Blocklist Item properties. +type RaiBlocklistItemProperties struct { + // If the pattern is a regex pattern. + IsRegex *bool + + // Pattern to match against. + Pattern *string +} + +// RaiBlocklistProperties - RAI Custom Blocklist properties. +type RaiBlocklistProperties struct { + // Description of the block list. + Description *string +} + +// RaiContentFilter - Azure OpenAI Content Filter. +type RaiContentFilter struct { + // Azure OpenAI Content Filter Properties. + Properties *RaiContentFilterProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// RaiContentFilterListResult - The list of Content Filters. +type RaiContentFilterListResult struct { + // The link used to get the next page of Content Filters. + NextLink *string + + // The list of RaiContentFilter. + Value []*RaiContentFilter +} + +// RaiContentFilterProperties - Azure OpenAI Content Filter Properties. +type RaiContentFilterProperties struct { + // If the Content Filter has multi severity levels(Low, Medium, or High). + IsMultiLevelFilter *bool + + // Name of Content Filter. + Name *string + + // Content source to apply the Content Filters. + Source *RaiPolicyContentSource +} + +// RaiExternalSafetyProviderResult - The list of cognitive services RAI External Safety Providers. +type RaiExternalSafetyProviderResult struct { + // The link used to get the next page of Rai External Safety Provider. + NextLink *string + + // The list of RaiExternalSafetyProvider. + Value []*RaiExternalSafetyProviderSchema +} + +// RaiExternalSafetyProviderSchema - Cognitive Services Rai External Safety provider Schema. +type RaiExternalSafetyProviderSchema struct { + // Properties of Cognitive Services Rai External Safety provider. + Properties *RaiExternalSafetyProviderSchemaProperties + + // READ-ONLY; Resource Etag. + Etag *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; Resource tags. + Tags map[string]*string + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// RaiExternalSafetyProviderSchemaProperties - RAI External SafetyProvider schema properties. +type RaiExternalSafetyProviderSchemaProperties struct { + // The Key Vault URI that contains the api key for safety provider urls. + KeyVaultURI *string + + // The managed identity to access the Key Vault. + ManagedIdentity *string + + // Safety provider mode sync/async. + Mode *string + + // The unique identifier of the safety provider. + ProviderID *string + + // Name of the safety provider. + ProviderName *string + + // The name of the secret in Key Vault that contains the api key to access the webhook. + SecretName *string + + // Webhook URL for the safety provider. + URL *string + + // READ-ONLY; Creation time of the safety provider. + CreatedAt *time.Time + + // READ-ONLY; Last modified time of the safety provider. + LastModifiedAt *time.Time +} + +// RaiMonitorConfig - Cognitive Services Rai Monitor Config. +type RaiMonitorConfig struct { + // The storage resource Id. + AdxStorageResourceID *string + + // The identity client Id to access the storage. + IdentityClientID *string +} + +// RaiPolicy - Cognitive Services RaiPolicy. +type RaiPolicy struct { + // Properties of Cognitive Services RaiPolicy. + Properties *RaiPolicyProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Resource Etag. + Etag *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// RaiPolicyContentFilter - Azure OpenAI Content Filter. +type RaiPolicyContentFilter struct { + // The action types to apply to the content filters + Action *RaiActionType + + // If blocking would occur. + Blocking *bool + + // If the ContentFilter is enabled. + Enabled *bool + + // Name of ContentFilter. + Name *string + + // Level at which content is filtered. + SeverityThreshold *ContentLevel + + // Content source to apply the Content Filters. + Source *RaiPolicyContentSource +} + +// RaiPolicyListResult - The list of cognitive services RaiPolicies. +type RaiPolicyListResult struct { + // The link used to get the next page of RaiPolicy. + NextLink *string + + // The list of RaiPolicy. + Value []*RaiPolicy +} + +// RaiPolicyProperties - Azure OpenAI Content Filters properties. +type RaiPolicyProperties struct { + // Name of Rai policy. + BasePolicyName *string + + // The list of Content Filters. + ContentFilters []*RaiPolicyContentFilter + + // The list of custom Blocklist. + CustomBlocklists []*CustomBlocklistConfig + + // Rai policy mode. The enum value mapping is as below: Default = 0, Deferred=1, Blocking=2, Asynchronous_filter =3. Please + // use 'Asynchronous_filter' after 2025-06-01. It is the same as 'Deferred' in previous version. + Mode *RaiPolicyMode + + // The list of Safety Providers. + SafetyProviders []*SafetyProviderConfig + + // READ-ONLY; Content Filters policy type. + Type *RaiPolicyType +} + +// RaiToolLabel - Cognitive Services RAI Tool Label resource. +type RaiToolLabel struct { + // Properties of the RAI Tool Label. + Properties *RaiToolLabelProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Resource Etag. + Etag *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// RaiToolLabelProperties - RAI Tool Label properties. +type RaiToolLabelProperties struct { + // REQUIRED; The unique tool connection name, e.g., 'Web_Search'. + ToolConnectionName *string + + // Account-level tool label definition. + AccountScope *RaiToolLabelPropertiesAccountScope + + // List of project-level tool label definitions. + ProjectScopes []*RaiToolLabelPropertiesProjectScopesItem +} + +// RaiToolLabelPropertiesAccountScope - Account-level tool label definition. +type RaiToolLabelPropertiesAccountScope struct { + // Dictionary of label key-value pairs for the account scope. + LabelValues map[string]*string +} + +type RaiToolLabelPropertiesProjectScopesItem struct { + // REQUIRED; Dictionary of label key-value pairs for the project scope. + LabelValues map[string]*string + + // REQUIRED; Project name to which this scope applies. + Project *string +} + +// RaiToolLabelResult - The list of Cognitive Services RAI Tool Labels. +type RaiToolLabelResult struct { + // The link used to get the next page of RaiToolLabels. + NextLink *string + + // The list of RAI Tool Labels. + Value []*RaiToolLabel +} + +// RaiTopic - Cognitive Services Rai Topic. +type RaiTopic struct { + // Properties of Cognitive Services Rai Topic. + Properties *RaiTopicProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Resource Etag. + Etag *string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// RaiTopicProperties - RAI Custom Topic properties. +type RaiTopicProperties struct { + // Creation time of the custom topic. + CreatedAt *time.Time + + // Description of the custom topic. + Description *string + + // Failed reason if the status is Failed. + FailedReason *string + + // Last modified time of the custom topic. + LastModifiedAt *time.Time + + // Sample blob url for the custom topic. + SampleBlobURL *string + + // Status of the custom topic. + Status *string + + // The unique identifier of the custom topic. + TopicID *string + + // The name of the custom topic. + TopicName *string +} + +// RaiTopicResult - The list of cognitive services RAI Topics. +type RaiTopicResult struct { + // The link used to get the next page of RaiTopics. + NextLink *string + + // The list of RaiTopic. + Value []*RaiTopic +} + +// RegenerateKeyParameters - Regenerate key parameters. +type RegenerateKeyParameters struct { + // REQUIRED; key name to generate (Key1|Key2) + KeyName *KeyName +} + +// RegionSetting - The call rate limit Cognitive Services account. +type RegionSetting struct { + // Maps the region to the regional custom subdomain. + Customsubdomain *string + + // Name of the region. + Name *string + + // A value for priority or weighted routing methods. + Value *float32 +} + +// ReplacementConfig - Configuration for model replacement. +type ReplacementConfig struct { + // The date when automatic upgrade should start. This applies to deployments with the OnceNewDefaultVersionAvailable upgrade + // option. + AutoUpgradeStartDate *time.Time + + // The name of the replacement model. + TargetModelName *string + + // The version of the replacement model. + TargetModelVersion *string + + // The number of days before deprecation date to trigger upgrade. This applies to deployments with the OnceCurrentVersionExpired + // upgrade option. + UpgradeOnExpiryLeadTimeDays *int32 +} + +type RequestMatchPattern struct { + Method *string + Path *string +} + +// ResourceSKU - Describes an available Cognitive Services SKU. +type ResourceSKU struct { + // The Kind of resources that are supported in this SKU. + Kind *string + + // The set of locations that the SKU is available. + Locations []*string + + // The name of SKU. + Name *string + + // The type of resource the SKU applies to. + ResourceType *string + + // The restrictions because of which SKU cannot be used. This is empty if there are no restrictions. + Restrictions []*ResourceSKURestrictions + + // Specifies the tier of Cognitive Services account. + Tier *string +} + +// ResourceSKUListResult - The Get Skus operation response. +type ResourceSKUListResult struct { + // REQUIRED; The ResourceSku items on this page + Value []*ResourceSKU + + // The link to the next page of items + NextLink *string +} + +type ResourceSKURestrictionInfo struct { + // Locations where the SKU is restricted + Locations []*string + + // List of availability zones where the SKU is restricted. + Zones []*string +} + +// ResourceSKURestrictions - Describes restrictions of a SKU. +type ResourceSKURestrictions struct { + // The reason for restriction. + ReasonCode *ResourceSKURestrictionsReasonCode + + // The information about the restriction where the SKU cannot be used. + RestrictionInfo *ResourceSKURestrictionInfo + + // The type of restrictions. + Type *ResourceSKURestrictionsType + + // The value of restrictions. If the restriction type is set to location. This would be different locations where the SKU + // is restricted. + Values []*string +} + +// RoleBasedBuiltInAuthorizationPolicy - Built-in role-based authorization policy. +type RoleBasedBuiltInAuthorizationPolicy struct { + // CONSTANT; Authorization scheme type. + // Field has constant value BuiltInAuthorizationSchemeDefault, any specified value is ignored. + Type *BuiltInAuthorizationScheme +} + +// GetApplicationAuthorizationPolicy implements the ApplicationAuthorizationPolicyClassification interface for type RoleBasedBuiltInAuthorizationPolicy. +func (r *RoleBasedBuiltInAuthorizationPolicy) GetApplicationAuthorizationPolicy() *ApplicationAuthorizationPolicy { + return &ApplicationAuthorizationPolicy{ + Type: r.Type, + } +} + +type SASAuthTypeConnectionProperties struct { + // CONSTANT; Authentication type of the connection target + // Field has constant value ConnectionAuthTypeSAS, any specified value is ignored. + AuthType *ConnectionAuthType + + // Category of the connection + Category *ConnectionCategory + Credentials *ConnectionSharedAccessSignature + + // Provides the error message if the connection fails + Error *string + ExpiryTime *time.Time + IsSharedToAll *bool + + // Store user metadata for this connection + Metadata map[string]*string + + // Specifies how private endpoints are used with this connection: 'Required', 'NotRequired', or 'NotApplicable'. + PeRequirement *ManagedPERequirement + + // Specifies the status of private endpoints for this connection: 'Inactive', 'Active', or 'NotApplicable'. + PeStatus *ManagedPEStatus + SharedUserList []*string + + // The connection URL to be used. + Target *string + UseWorkspaceManagedIdentity *bool + + // READ-ONLY + CreatedByWorkspaceArmID *string + + // READ-ONLY; Group based on connection category + Group *ConnectionGroup +} + +// GetConnectionPropertiesV2 implements the ConnectionPropertiesV2Classification interface for type SASAuthTypeConnectionProperties. +func (s *SASAuthTypeConnectionProperties) GetConnectionPropertiesV2() *ConnectionPropertiesV2 { + return &ConnectionPropertiesV2{ + AuthType: s.AuthType, + Category: s.Category, + CreatedByWorkspaceArmID: s.CreatedByWorkspaceArmID, + Error: s.Error, + ExpiryTime: s.ExpiryTime, + Group: s.Group, + IsSharedToAll: s.IsSharedToAll, + Metadata: s.Metadata, + PeRequirement: s.PeRequirement, + PeStatus: s.PeStatus, + SharedUserList: s.SharedUserList, + Target: s.Target, + UseWorkspaceManagedIdentity: s.UseWorkspaceManagedIdentity, + } +} + +// SKU - The resource model definition representing SKU +type SKU struct { + // REQUIRED; The name of the SKU. Ex - P3. It is typically a letter+number code + Name *string + + // If the SKU supports scale out/in then the capacity integer should be included. If scale out/in is not possible for the + // resource this may be omitted. + Capacity *int32 + + // If the service has different generations of hardware, for the same SKU, then that can be captured here. + Family *string + + // The SKU size. When the name field is the combination of tier and some other value, this would be the standalone code. + Size *string + + // This field is required to be implemented by the Resource Provider if the service has more than one tier, but is not required + // on a PUT. + Tier *SKUTier +} + +// SKUAvailability - SKU availability. +type SKUAvailability struct { + // The kind (type) of cognitive service account. + Kind *string + + // Additional error message. + Message *string + + // Reason why the SKU is not available. + Reason *string + + // Indicates the given SKU is available or not. + SKUAvailable *bool + + // The name of SKU. + SKUName *string + + // The Type of the resource. + Type *string +} + +// SKUAvailabilityListResult - Check SKU availability result list. +type SKUAvailabilityListResult struct { + // Check SKU availability result list. + Value []*SKUAvailability +} + +// SKUCapability - SkuCapability indicates the capability of a certain feature. +type SKUCapability struct { + // The name of the SkuCapability. + Name *string + + // The value of the SkuCapability. + Value *string +} + +// SKUChangeInfo - Sku change info of account. +type SKUChangeInfo struct { + // Gets the count of downgrades. + CountOfDowngrades *float32 + + // Gets the count of upgrades after downgrades. + CountOfUpgradesAfterDowngrades *float32 + + // Gets the last change date. + LastChangeDate *string +} + +// SKUResource - Properties of Cognitive Services account resource sku resource properties. +type SKUResource struct { + // The capacity configuration. + Capacity *CapacityConfig + + // The resource type name. + ResourceType *string + + // The resource model definition representing SKU + SKU *SKU +} + +// SafetyProviderConfig - Gets or sets the source to which safety providers applies. +type SafetyProviderConfig struct { + // If blocking would occur. + Blocking *bool + + // Name of RAI Safety Provider. + SafetyProviderName *string + + // Content source to apply the Content Filters. + Source *RaiPolicyContentSource +} + +type ServicePrincipalAuthTypeConnectionProperties struct { + // CONSTANT; Authentication type of the connection target + // Field has constant value ConnectionAuthTypeServicePrincipal, any specified value is ignored. + AuthType *ConnectionAuthType + + // Category of the connection + Category *ConnectionCategory + Credentials *ConnectionServicePrincipal + + // Provides the error message if the connection fails + Error *string + ExpiryTime *time.Time + IsSharedToAll *bool + + // Store user metadata for this connection + Metadata map[string]*string + + // Specifies how private endpoints are used with this connection: 'Required', 'NotRequired', or 'NotApplicable'. + PeRequirement *ManagedPERequirement + + // Specifies the status of private endpoints for this connection: 'Inactive', 'Active', or 'NotApplicable'. + PeStatus *ManagedPEStatus + SharedUserList []*string + + // The connection URL to be used. + Target *string + UseWorkspaceManagedIdentity *bool + + // READ-ONLY + CreatedByWorkspaceArmID *string + + // READ-ONLY; Group based on connection category + Group *ConnectionGroup +} + +// GetConnectionPropertiesV2 implements the ConnectionPropertiesV2Classification interface for type ServicePrincipalAuthTypeConnectionProperties. +func (s *ServicePrincipalAuthTypeConnectionProperties) GetConnectionPropertiesV2() *ConnectionPropertiesV2 { + return &ConnectionPropertiesV2{ + AuthType: s.AuthType, + Category: s.Category, + CreatedByWorkspaceArmID: s.CreatedByWorkspaceArmID, + Error: s.Error, + ExpiryTime: s.ExpiryTime, + Group: s.Group, + IsSharedToAll: s.IsSharedToAll, + Metadata: s.Metadata, + PeRequirement: s.PeRequirement, + PeStatus: s.PeStatus, + SharedUserList: s.SharedUserList, + Target: s.Target, + UseWorkspaceManagedIdentity: s.UseWorkspaceManagedIdentity, + } +} + +// ServiceTagOutboundRule - Service Tag outbound rule for the managed network of a cognitive services account. +type ServiceTagOutboundRule struct { + // CONSTANT; Type of a managed network Outbound Rule of a cognitive services account. + // Field has constant value RuleTypeServiceTag, any specified value is ignored. + Type *RuleType + + // Category of a managed network Outbound Rule of a cognitive services account. + Category *RuleCategory + + // Service Tag destination. + Destination *ServiceTagOutboundRuleDestination + + // Type of a managed network Outbound Rule of a cognitive services account. + Status *RuleStatus + + // READ-ONLY; Error information about an outbound rule of a cognitive services account if RuleStatus is failed. + ErrorInformation *string + + // READ-ONLY + ParentRuleNames []*string +} + +// GetOutboundRule implements the OutboundRuleClassification interface for type ServiceTagOutboundRule. +func (s *ServiceTagOutboundRule) GetOutboundRule() *OutboundRule { + return &OutboundRule{ + Category: s.Category, + ErrorInformation: s.ErrorInformation, + ParentRuleNames: s.ParentRuleNames, + Status: s.Status, + Type: s.Type, + } +} + +// ServiceTagOutboundRuleDestination - Service Tag destination for an outbound rule. +type ServiceTagOutboundRuleDestination struct { + // The action for the service tag outbound rule. + Action *RuleAction + + // Optional address prefixes. If provided, the serviceTag property will be ignored. + AddressPrefixes []*string + + // Destination port ranges. + PortRanges *string + + // Network protocol used by the service tag rule. + Protocol *string + + // Name of the Azure service tag to target. + ServiceTag *string +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time + + // The identity that created the resource. + CreatedBy *string + + // The type of identity that created the resource. + CreatedByType *CreatedByType + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time + + // The identity that last modified the resource. + LastModifiedBy *string + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType +} + +type ThrottlingRule struct { + Count *float32 + DynamicThrottlingEnabled *bool + Key *string + MatchPatterns []*RequestMatchPattern + MinCount *float32 + RenewalPeriod *float32 +} + +// TrafficRoutingRule - Represents a rule for routing traffic to a specific deployment. +type TrafficRoutingRule struct { + // The unique identifier of the deployment to which traffic is routed by this rule. + DeploymentID *string + + // A user-provided description for this traffic routing rule. + Description *string + + // The identifier of this traffic routing rule. + RuleID *string + + // Gets or sets the percentage of traffic allocated to this instance. + TrafficPercentage *int32 +} + +// Usage - The usage data for a usage request. +type Usage struct { + // Current value for this metric. + CurrentValue *float64 + + // Maximum value for this metric. + Limit *float64 + + // The name information for the metric. + Name *MetricName + + // Next reset time for current quota. + NextResetTime *string + + // The quota period used to summarize the usage values. + QuotaPeriod *string + + // Cognitive Services account quota usage status. + Status *QuotaUsageStatus + + // The unit of the metric. + Unit *UnitType +} + +// UsageListResult - The response to a list usage request. +type UsageListResult struct { + // The link used to get the next page of Usages. + NextLink *string + + // The list of usages for Cognitive Service account. + Value []*Usage +} + +// UserAssignedIdentity - User-assigned managed identity. +type UserAssignedIdentity struct { + // READ-ONLY; Client App Id associated with this identity. + ClientID *string + + // READ-ONLY; Azure Active Directory principal ID associated with this Identity. + PrincipalID *string +} + +// UserOwnedAmlWorkspace - The user owned AML account for Cognitive Services account. +type UserOwnedAmlWorkspace struct { + // Identity Client id of a AML account resource. + IdentityClientID *string + + // Full resource id of a AML account resource. + ResourceID *string +} + +// UserOwnedStorage - The user owned storage for Cognitive Services account. +type UserOwnedStorage struct { + IdentityClientID *string + + // Full resource id of a Microsoft.Storage resource. + ResourceID *string +} + +type UsernamePasswordAuthTypeConnectionProperties struct { + // CONSTANT; Authentication type of the connection target + // Field has constant value ConnectionAuthTypeUsernamePassword, any specified value is ignored. + AuthType *ConnectionAuthType + + // Category of the connection + Category *ConnectionCategory + Credentials *ConnectionUsernamePassword + + // Provides the error message if the connection fails + Error *string + ExpiryTime *time.Time + IsSharedToAll *bool + + // Store user metadata for this connection + Metadata map[string]*string + + // Specifies how private endpoints are used with this connection: 'Required', 'NotRequired', or 'NotApplicable'. + PeRequirement *ManagedPERequirement + + // Specifies the status of private endpoints for this connection: 'Inactive', 'Active', or 'NotApplicable'. + PeStatus *ManagedPEStatus + SharedUserList []*string + + // The connection URL to be used. + Target *string + UseWorkspaceManagedIdentity *bool + + // READ-ONLY + CreatedByWorkspaceArmID *string + + // READ-ONLY; Group based on connection category + Group *ConnectionGroup +} + +// GetConnectionPropertiesV2 implements the ConnectionPropertiesV2Classification interface for type UsernamePasswordAuthTypeConnectionProperties. +func (u *UsernamePasswordAuthTypeConnectionProperties) GetConnectionPropertiesV2() *ConnectionPropertiesV2 { + return &ConnectionPropertiesV2{ + AuthType: u.AuthType, + Category: u.Category, + CreatedByWorkspaceArmID: u.CreatedByWorkspaceArmID, + Error: u.Error, + ExpiryTime: u.ExpiryTime, + Group: u.Group, + IsSharedToAll: u.IsSharedToAll, + Metadata: u.Metadata, + PeRequirement: u.PeRequirement, + PeStatus: u.PeStatus, + SharedUserList: u.SharedUserList, + Target: u.Target, + UseWorkspaceManagedIdentity: u.UseWorkspaceManagedIdentity, + } +} + +// VersionedAgentReference - Type modeling a reference to a version of an agent definition. +type VersionedAgentReference struct { + // Gets the agent's unique identifier within the organization (subscription). + AgentID *string + + // Gets the agent's name (unique within the project/app). + AgentName *string + + // Gets the agent's version (unique for each agent lineage). + AgentVersion *string +} + +// VirtualNetworkRule - A rule governing the accessibility from a specific virtual network. +type VirtualNetworkRule struct { + // REQUIRED; Full resource id of a vnet subnet, such as '/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.Network/virtualNetworks/test-vnet/subnets/subnet1'. + ID *string + + // Ignore missing vnet service endpoint or not. + IgnoreMissingVnetServiceEndpoint *bool + + // Gets the state of virtual network rule. + State *string +} diff --git a/test/local/armcognitiveservices/zz_models_client.go b/test/local/armcognitiveservices/zz_models_client.go new file mode 100644 index 000000000000..86a03350e5b4 --- /dev/null +++ b/test/local/armcognitiveservices/zz_models_client.go @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ModelsClient contains the methods for the Models group. +// Don't use this type directly, use NewModelsClient() instead. +// +// Generated from API version 2026-05-01 +type ModelsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewModelsClient creates a new instance of ModelsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewModelsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ModelsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ModelsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListPager - List Models. +// - location - The location name. +// - options - ModelsClientListOptions contains the optional parameters for the ModelsClient.NewListPager method. +func (client *ModelsClient) NewListPager(location string, options *ModelsClientListOptions) *runtime.Pager[ModelsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ModelsClientListResponse]{ + More: func(page ModelsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ModelsClientListResponse) (ModelsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ModelsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, location, options) + }, nil) + if err != nil { + return ModelsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ModelsClient) listCreateRequest(ctx context.Context, location string, _ *ModelsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/models" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ModelsClient) listHandleResponse(resp *http.Response) (ModelsClientListResponse, error) { + result := ModelsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ModelListResult); err != nil { + return ModelsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_models_serde.go b/test/local/armcognitiveservices/zz_models_serde.go new file mode 100644 index 000000000000..eddb8dd442fe --- /dev/null +++ b/test/local/armcognitiveservices/zz_models_serde.go @@ -0,0 +1,8811 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type AADAuthTypeConnectionProperties. +func (a AADAuthTypeConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["authType"] = ConnectionAuthTypeAAD + populate(objectMap, "category", a.Category) + populate(objectMap, "createdByWorkspaceArmId", a.CreatedByWorkspaceArmID) + populate(objectMap, "error", a.Error) + populateTime[datetime.RFC3339](objectMap, "expiryTime", a.ExpiryTime) + populate(objectMap, "group", a.Group) + populate(objectMap, "isSharedToAll", a.IsSharedToAll) + populate(objectMap, "metadata", a.Metadata) + populate(objectMap, "peRequirement", a.PeRequirement) + populate(objectMap, "peStatus", a.PeStatus) + populate(objectMap, "sharedUserList", a.SharedUserList) + populate(objectMap, "target", a.Target) + populate(objectMap, "useWorkspaceManagedIdentity", a.UseWorkspaceManagedIdentity) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AADAuthTypeConnectionProperties. +func (a *AADAuthTypeConnectionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "authType": + err = unpopulate(val, "AuthType", &a.AuthType) + delete(rawMsg, key) + case "category": + err = unpopulate(val, "Category", &a.Category) + delete(rawMsg, key) + case "createdByWorkspaceArmId": + err = unpopulate(val, "CreatedByWorkspaceArmID", &a.CreatedByWorkspaceArmID) + delete(rawMsg, key) + case "error": + err = unpopulate(val, "Error", &a.Error) + delete(rawMsg, key) + case "expiryTime": + err = unpopulateTime[datetime.RFC3339](val, "ExpiryTime", &a.ExpiryTime) + delete(rawMsg, key) + case "group": + err = unpopulate(val, "Group", &a.Group) + delete(rawMsg, key) + case "isSharedToAll": + err = unpopulate(val, "IsSharedToAll", &a.IsSharedToAll) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &a.Metadata) + delete(rawMsg, key) + case "peRequirement": + err = unpopulate(val, "PeRequirement", &a.PeRequirement) + delete(rawMsg, key) + case "peStatus": + err = unpopulate(val, "PeStatus", &a.PeStatus) + delete(rawMsg, key) + case "sharedUserList": + err = unpopulate(val, "SharedUserList", &a.SharedUserList) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &a.Target) + delete(rawMsg, key) + case "useWorkspaceManagedIdentity": + err = unpopulate(val, "UseWorkspaceManagedIdentity", &a.UseWorkspaceManagedIdentity) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type APIKeyAuthConnectionProperties. +func (a APIKeyAuthConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["authType"] = ConnectionAuthTypeAPIKey + populate(objectMap, "category", a.Category) + populate(objectMap, "createdByWorkspaceArmId", a.CreatedByWorkspaceArmID) + populate(objectMap, "credentials", a.Credentials) + populate(objectMap, "error", a.Error) + populateTime[datetime.RFC3339](objectMap, "expiryTime", a.ExpiryTime) + populate(objectMap, "group", a.Group) + populate(objectMap, "isSharedToAll", a.IsSharedToAll) + populate(objectMap, "metadata", a.Metadata) + populate(objectMap, "peRequirement", a.PeRequirement) + populate(objectMap, "peStatus", a.PeStatus) + populate(objectMap, "sharedUserList", a.SharedUserList) + populate(objectMap, "target", a.Target) + populate(objectMap, "useWorkspaceManagedIdentity", a.UseWorkspaceManagedIdentity) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APIKeyAuthConnectionProperties. +func (a *APIKeyAuthConnectionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "authType": + err = unpopulate(val, "AuthType", &a.AuthType) + delete(rawMsg, key) + case "category": + err = unpopulate(val, "Category", &a.Category) + delete(rawMsg, key) + case "createdByWorkspaceArmId": + err = unpopulate(val, "CreatedByWorkspaceArmID", &a.CreatedByWorkspaceArmID) + delete(rawMsg, key) + case "credentials": + err = unpopulate(val, "Credentials", &a.Credentials) + delete(rawMsg, key) + case "error": + err = unpopulate(val, "Error", &a.Error) + delete(rawMsg, key) + case "expiryTime": + err = unpopulateTime[datetime.RFC3339](val, "ExpiryTime", &a.ExpiryTime) + delete(rawMsg, key) + case "group": + err = unpopulate(val, "Group", &a.Group) + delete(rawMsg, key) + case "isSharedToAll": + err = unpopulate(val, "IsSharedToAll", &a.IsSharedToAll) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &a.Metadata) + delete(rawMsg, key) + case "peRequirement": + err = unpopulate(val, "PeRequirement", &a.PeRequirement) + delete(rawMsg, key) + case "peStatus": + err = unpopulate(val, "PeStatus", &a.PeStatus) + delete(rawMsg, key) + case "sharedUserList": + err = unpopulate(val, "SharedUserList", &a.SharedUserList) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &a.Target) + delete(rawMsg, key) + case "useWorkspaceManagedIdentity": + err = unpopulate(val, "UseWorkspaceManagedIdentity", &a.UseWorkspaceManagedIdentity) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type APIKeys. +func (a APIKeys) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "key1", a.Key1) + populate(objectMap, "key2", a.Key2) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APIKeys. +func (a *APIKeys) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "key1": + err = unpopulate(val, "Key1", &a.Key1) + delete(rawMsg, key) + case "key2": + err = unpopulate(val, "Key2", &a.Key2) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type APIProperties. +func (a APIProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "aadClientId", a.AADClientID) + populate(objectMap, "aadTenantId", a.AADTenantID) + populate(objectMap, "eventHubConnectionString", a.EventHubConnectionString) + populate(objectMap, "qnaAzureSearchEndpointId", a.QnaAzureSearchEndpointID) + populate(objectMap, "qnaAzureSearchEndpointKey", a.QnaAzureSearchEndpointKey) + populate(objectMap, "qnaRuntimeEndpoint", a.QnaRuntimeEndpoint) + populate(objectMap, "statisticsEnabled", a.StatisticsEnabled) + populate(objectMap, "storageAccountConnectionString", a.StorageAccountConnectionString) + populate(objectMap, "superUser", a.SuperUser) + populate(objectMap, "websiteName", a.WebsiteName) + if a.AdditionalProperties != nil { + for key, val := range a.AdditionalProperties { + objectMap[key] = val + } + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APIProperties. +func (a *APIProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "aadClientId": + err = unpopulate(val, "AADClientID", &a.AADClientID) + delete(rawMsg, key) + case "aadTenantId": + err = unpopulate(val, "AADTenantID", &a.AADTenantID) + delete(rawMsg, key) + case "eventHubConnectionString": + err = unpopulate(val, "EventHubConnectionString", &a.EventHubConnectionString) + delete(rawMsg, key) + case "qnaAzureSearchEndpointId": + err = unpopulate(val, "QnaAzureSearchEndpointID", &a.QnaAzureSearchEndpointID) + delete(rawMsg, key) + case "qnaAzureSearchEndpointKey": + err = unpopulate(val, "QnaAzureSearchEndpointKey", &a.QnaAzureSearchEndpointKey) + delete(rawMsg, key) + case "qnaRuntimeEndpoint": + err = unpopulate(val, "QnaRuntimeEndpoint", &a.QnaRuntimeEndpoint) + delete(rawMsg, key) + case "statisticsEnabled": + err = unpopulate(val, "StatisticsEnabled", &a.StatisticsEnabled) + delete(rawMsg, key) + case "storageAccountConnectionString": + err = unpopulate(val, "StorageAccountConnectionString", &a.StorageAccountConnectionString) + delete(rawMsg, key) + case "superUser": + err = unpopulate(val, "SuperUser", &a.SuperUser) + delete(rawMsg, key) + case "websiteName": + err = unpopulate(val, "WebsiteName", &a.WebsiteName) + delete(rawMsg, key) + default: + if a.AdditionalProperties == nil { + a.AdditionalProperties = map[string]any{} + } + if val != nil { + var aux any + err = json.Unmarshal(val, &aux) + a.AdditionalProperties[key] = aux + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AbusePenalty. +func (a AbusePenalty) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "action", a.Action) + populateTime[datetime.RFC3339](objectMap, "expiration", a.Expiration) + populate(objectMap, "rateLimitPercentage", a.RateLimitPercentage) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AbusePenalty. +func (a *AbusePenalty) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "action": + err = unpopulate(val, "Action", &a.Action) + delete(rawMsg, key) + case "expiration": + err = unpopulateTime[datetime.RFC3339](val, "Expiration", &a.Expiration) + delete(rawMsg, key) + case "rateLimitPercentage": + err = unpopulate(val, "RateLimitPercentage", &a.RateLimitPercentage) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccessKeyAuthTypeConnectionProperties. +func (a AccessKeyAuthTypeConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["authType"] = ConnectionAuthTypeAccessKey + populate(objectMap, "category", a.Category) + populate(objectMap, "createdByWorkspaceArmId", a.CreatedByWorkspaceArmID) + populate(objectMap, "credentials", a.Credentials) + populate(objectMap, "error", a.Error) + populateTime[datetime.RFC3339](objectMap, "expiryTime", a.ExpiryTime) + populate(objectMap, "group", a.Group) + populate(objectMap, "isSharedToAll", a.IsSharedToAll) + populate(objectMap, "metadata", a.Metadata) + populate(objectMap, "peRequirement", a.PeRequirement) + populate(objectMap, "peStatus", a.PeStatus) + populate(objectMap, "sharedUserList", a.SharedUserList) + populate(objectMap, "target", a.Target) + populate(objectMap, "useWorkspaceManagedIdentity", a.UseWorkspaceManagedIdentity) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccessKeyAuthTypeConnectionProperties. +func (a *AccessKeyAuthTypeConnectionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "authType": + err = unpopulate(val, "AuthType", &a.AuthType) + delete(rawMsg, key) + case "category": + err = unpopulate(val, "Category", &a.Category) + delete(rawMsg, key) + case "createdByWorkspaceArmId": + err = unpopulate(val, "CreatedByWorkspaceArmID", &a.CreatedByWorkspaceArmID) + delete(rawMsg, key) + case "credentials": + err = unpopulate(val, "Credentials", &a.Credentials) + delete(rawMsg, key) + case "error": + err = unpopulate(val, "Error", &a.Error) + delete(rawMsg, key) + case "expiryTime": + err = unpopulateTime[datetime.RFC3339](val, "ExpiryTime", &a.ExpiryTime) + delete(rawMsg, key) + case "group": + err = unpopulate(val, "Group", &a.Group) + delete(rawMsg, key) + case "isSharedToAll": + err = unpopulate(val, "IsSharedToAll", &a.IsSharedToAll) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &a.Metadata) + delete(rawMsg, key) + case "peRequirement": + err = unpopulate(val, "PeRequirement", &a.PeRequirement) + delete(rawMsg, key) + case "peStatus": + err = unpopulate(val, "PeStatus", &a.PeStatus) + delete(rawMsg, key) + case "sharedUserList": + err = unpopulate(val, "SharedUserList", &a.SharedUserList) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &a.Target) + delete(rawMsg, key) + case "useWorkspaceManagedIdentity": + err = unpopulate(val, "UseWorkspaceManagedIdentity", &a.UseWorkspaceManagedIdentity) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Account. +func (a Account) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", a.Etag) + populate(objectMap, "id", a.ID) + populate(objectMap, "identity", a.Identity) + populate(objectMap, "kind", a.Kind) + populate(objectMap, "location", a.Location) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "sku", a.SKU) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "tags", a.Tags) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Account. +func (a *Account) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &a.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &a.Identity) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &a.Kind) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &a.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &a.SKU) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &a.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &a.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountKeyAuthTypeConnectionProperties. +func (a AccountKeyAuthTypeConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["authType"] = ConnectionAuthTypeAccountKey + populate(objectMap, "category", a.Category) + populate(objectMap, "createdByWorkspaceArmId", a.CreatedByWorkspaceArmID) + populate(objectMap, "credentials", a.Credentials) + populate(objectMap, "error", a.Error) + populateTime[datetime.RFC3339](objectMap, "expiryTime", a.ExpiryTime) + populate(objectMap, "group", a.Group) + populate(objectMap, "isSharedToAll", a.IsSharedToAll) + populate(objectMap, "metadata", a.Metadata) + populate(objectMap, "peRequirement", a.PeRequirement) + populate(objectMap, "peStatus", a.PeStatus) + populate(objectMap, "sharedUserList", a.SharedUserList) + populate(objectMap, "target", a.Target) + populate(objectMap, "useWorkspaceManagedIdentity", a.UseWorkspaceManagedIdentity) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountKeyAuthTypeConnectionProperties. +func (a *AccountKeyAuthTypeConnectionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "authType": + err = unpopulate(val, "AuthType", &a.AuthType) + delete(rawMsg, key) + case "category": + err = unpopulate(val, "Category", &a.Category) + delete(rawMsg, key) + case "createdByWorkspaceArmId": + err = unpopulate(val, "CreatedByWorkspaceArmID", &a.CreatedByWorkspaceArmID) + delete(rawMsg, key) + case "credentials": + err = unpopulate(val, "Credentials", &a.Credentials) + delete(rawMsg, key) + case "error": + err = unpopulate(val, "Error", &a.Error) + delete(rawMsg, key) + case "expiryTime": + err = unpopulateTime[datetime.RFC3339](val, "ExpiryTime", &a.ExpiryTime) + delete(rawMsg, key) + case "group": + err = unpopulate(val, "Group", &a.Group) + delete(rawMsg, key) + case "isSharedToAll": + err = unpopulate(val, "IsSharedToAll", &a.IsSharedToAll) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &a.Metadata) + delete(rawMsg, key) + case "peRequirement": + err = unpopulate(val, "PeRequirement", &a.PeRequirement) + delete(rawMsg, key) + case "peStatus": + err = unpopulate(val, "PeStatus", &a.PeStatus) + delete(rawMsg, key) + case "sharedUserList": + err = unpopulate(val, "SharedUserList", &a.SharedUserList) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &a.Target) + delete(rawMsg, key) + case "useWorkspaceManagedIdentity": + err = unpopulate(val, "UseWorkspaceManagedIdentity", &a.UseWorkspaceManagedIdentity) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountListResult. +func (a AccountListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountListResult. +func (a *AccountListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &a.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountModel. +func (a AccountModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "baseModel", a.BaseModel) + populate(objectMap, "callRateLimit", a.CallRateLimit) + populate(objectMap, "capabilities", a.Capabilities) + populate(objectMap, "deprecation", a.Deprecation) + populate(objectMap, "finetuneCapabilities", a.FinetuneCapabilities) + populate(objectMap, "format", a.Format) + populate(objectMap, "isDefaultVersion", a.IsDefaultVersion) + populate(objectMap, "lifecycleStatus", a.LifecycleStatus) + populate(objectMap, "maxCapacity", a.MaxCapacity) + populate(objectMap, "modelCatalogAssetId", a.ModelCatalogAssetID) + populate(objectMap, "name", a.Name) + populate(objectMap, "publisher", a.Publisher) + populate(objectMap, "replacementConfig", a.ReplacementConfig) + populate(objectMap, "skus", a.SKUs) + populate(objectMap, "source", a.Source) + populate(objectMap, "sourceAccount", a.SourceAccount) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "version", a.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountModel. +func (a *AccountModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "baseModel": + err = unpopulate(val, "BaseModel", &a.BaseModel) + delete(rawMsg, key) + case "callRateLimit": + err = unpopulate(val, "CallRateLimit", &a.CallRateLimit) + delete(rawMsg, key) + case "capabilities": + err = unpopulate(val, "Capabilities", &a.Capabilities) + delete(rawMsg, key) + case "deprecation": + err = unpopulate(val, "Deprecation", &a.Deprecation) + delete(rawMsg, key) + case "finetuneCapabilities": + err = unpopulate(val, "FinetuneCapabilities", &a.FinetuneCapabilities) + delete(rawMsg, key) + case "format": + err = unpopulate(val, "Format", &a.Format) + delete(rawMsg, key) + case "isDefaultVersion": + err = unpopulate(val, "IsDefaultVersion", &a.IsDefaultVersion) + delete(rawMsg, key) + case "lifecycleStatus": + err = unpopulate(val, "LifecycleStatus", &a.LifecycleStatus) + delete(rawMsg, key) + case "maxCapacity": + err = unpopulate(val, "MaxCapacity", &a.MaxCapacity) + delete(rawMsg, key) + case "modelCatalogAssetId": + err = unpopulate(val, "ModelCatalogAssetID", &a.ModelCatalogAssetID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "publisher": + err = unpopulate(val, "Publisher", &a.Publisher) + delete(rawMsg, key) + case "replacementConfig": + err = unpopulate(val, "ReplacementConfig", &a.ReplacementConfig) + delete(rawMsg, key) + case "skus": + err = unpopulate(val, "SKUs", &a.SKUs) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &a.Source) + delete(rawMsg, key) + case "sourceAccount": + err = unpopulate(val, "SourceAccount", &a.SourceAccount) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &a.SystemData) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &a.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountModelListResult. +func (a AccountModelListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountModelListResult. +func (a *AccountModelListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &a.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountProperties. +func (a AccountProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "apiProperties", a.APIProperties) + populate(objectMap, "abusePenalty", a.AbusePenalty) + populate(objectMap, "allowProjectManagement", a.AllowProjectManagement) + populate(objectMap, "allowedFqdnList", a.AllowedFqdnList) + populate(objectMap, "amlWorkspace", a.AmlWorkspace) + populate(objectMap, "associatedProjects", a.AssociatedProjects) + populate(objectMap, "callRateLimit", a.CallRateLimit) + populate(objectMap, "capabilities", a.Capabilities) + populate(objectMap, "commitmentPlanAssociations", a.CommitmentPlanAssociations) + populate(objectMap, "customSubDomainName", a.CustomSubDomainName) + populate(objectMap, "dateCreated", a.DateCreated) + populate(objectMap, "defaultProject", a.DefaultProject) + populate(objectMap, "deletionDate", a.DeletionDate) + populate(objectMap, "disableLocalAuth", a.DisableLocalAuth) + populate(objectMap, "dynamicThrottlingEnabled", a.DynamicThrottlingEnabled) + populate(objectMap, "encryption", a.Encryption) + populate(objectMap, "endpoint", a.Endpoint) + populate(objectMap, "endpoints", a.Endpoints) + populate(objectMap, "internalId", a.InternalID) + populate(objectMap, "isMigrated", a.IsMigrated) + populate(objectMap, "locations", a.Locations) + populate(objectMap, "migrationToken", a.MigrationToken) + populate(objectMap, "networkAcls", a.NetworkACLs) + populate(objectMap, "networkInjections", a.NetworkInjections) + populate(objectMap, "privateEndpointConnections", a.PrivateEndpointConnections) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "publicNetworkAccess", a.PublicNetworkAccess) + populate(objectMap, "quotaLimit", a.QuotaLimit) + populate(objectMap, "raiMonitorConfig", a.RaiMonitorConfig) + populate(objectMap, "restore", a.Restore) + populate(objectMap, "restrictOutboundNetworkAccess", a.RestrictOutboundNetworkAccess) + populate(objectMap, "skuChangeInfo", a.SKUChangeInfo) + populate(objectMap, "scheduledPurgeDate", a.ScheduledPurgeDate) + populate(objectMap, "storedCompletionsDisabled", a.StoredCompletionsDisabled) + populate(objectMap, "userOwnedStorage", a.UserOwnedStorage) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountProperties. +func (a *AccountProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "apiProperties": + err = unpopulate(val, "APIProperties", &a.APIProperties) + delete(rawMsg, key) + case "abusePenalty": + err = unpopulate(val, "AbusePenalty", &a.AbusePenalty) + delete(rawMsg, key) + case "allowProjectManagement": + err = unpopulate(val, "AllowProjectManagement", &a.AllowProjectManagement) + delete(rawMsg, key) + case "allowedFqdnList": + err = unpopulate(val, "AllowedFqdnList", &a.AllowedFqdnList) + delete(rawMsg, key) + case "amlWorkspace": + err = unpopulate(val, "AmlWorkspace", &a.AmlWorkspace) + delete(rawMsg, key) + case "associatedProjects": + err = unpopulate(val, "AssociatedProjects", &a.AssociatedProjects) + delete(rawMsg, key) + case "callRateLimit": + err = unpopulate(val, "CallRateLimit", &a.CallRateLimit) + delete(rawMsg, key) + case "capabilities": + err = unpopulate(val, "Capabilities", &a.Capabilities) + delete(rawMsg, key) + case "commitmentPlanAssociations": + err = unpopulate(val, "CommitmentPlanAssociations", &a.CommitmentPlanAssociations) + delete(rawMsg, key) + case "customSubDomainName": + err = unpopulate(val, "CustomSubDomainName", &a.CustomSubDomainName) + delete(rawMsg, key) + case "dateCreated": + err = unpopulate(val, "DateCreated", &a.DateCreated) + delete(rawMsg, key) + case "defaultProject": + err = unpopulate(val, "DefaultProject", &a.DefaultProject) + delete(rawMsg, key) + case "deletionDate": + err = unpopulate(val, "DeletionDate", &a.DeletionDate) + delete(rawMsg, key) + case "disableLocalAuth": + err = unpopulate(val, "DisableLocalAuth", &a.DisableLocalAuth) + delete(rawMsg, key) + case "dynamicThrottlingEnabled": + err = unpopulate(val, "DynamicThrottlingEnabled", &a.DynamicThrottlingEnabled) + delete(rawMsg, key) + case "encryption": + err = unpopulate(val, "Encryption", &a.Encryption) + delete(rawMsg, key) + case "endpoint": + err = unpopulate(val, "Endpoint", &a.Endpoint) + delete(rawMsg, key) + case "endpoints": + err = unpopulate(val, "Endpoints", &a.Endpoints) + delete(rawMsg, key) + case "internalId": + err = unpopulate(val, "InternalID", &a.InternalID) + delete(rawMsg, key) + case "isMigrated": + err = unpopulate(val, "IsMigrated", &a.IsMigrated) + delete(rawMsg, key) + case "locations": + err = unpopulate(val, "Locations", &a.Locations) + delete(rawMsg, key) + case "migrationToken": + err = unpopulate(val, "MigrationToken", &a.MigrationToken) + delete(rawMsg, key) + case "networkAcls": + err = unpopulate(val, "NetworkACLs", &a.NetworkACLs) + delete(rawMsg, key) + case "networkInjections": + err = unpopulate(val, "NetworkInjections", &a.NetworkInjections) + delete(rawMsg, key) + case "privateEndpointConnections": + err = unpopulate(val, "PrivateEndpointConnections", &a.PrivateEndpointConnections) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "publicNetworkAccess": + err = unpopulate(val, "PublicNetworkAccess", &a.PublicNetworkAccess) + delete(rawMsg, key) + case "quotaLimit": + err = unpopulate(val, "QuotaLimit", &a.QuotaLimit) + delete(rawMsg, key) + case "raiMonitorConfig": + err = unpopulate(val, "RaiMonitorConfig", &a.RaiMonitorConfig) + delete(rawMsg, key) + case "restore": + err = unpopulate(val, "Restore", &a.Restore) + delete(rawMsg, key) + case "restrictOutboundNetworkAccess": + err = unpopulate(val, "RestrictOutboundNetworkAccess", &a.RestrictOutboundNetworkAccess) + delete(rawMsg, key) + case "skuChangeInfo": + err = unpopulate(val, "SKUChangeInfo", &a.SKUChangeInfo) + delete(rawMsg, key) + case "scheduledPurgeDate": + err = unpopulate(val, "ScheduledPurgeDate", &a.ScheduledPurgeDate) + delete(rawMsg, key) + case "storedCompletionsDisabled": + err = unpopulate(val, "StoredCompletionsDisabled", &a.StoredCompletionsDisabled) + delete(rawMsg, key) + case "userOwnedStorage": + err = unpopulate(val, "UserOwnedStorage", &a.UserOwnedStorage) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountSKU. +func (a AccountSKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "resourceType", a.ResourceType) + populate(objectMap, "sku", a.SKU) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountSKU. +func (a *AccountSKU) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "resourceType": + err = unpopulate(val, "ResourceType", &a.ResourceType) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &a.SKU) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AccountSKUListResult. +func (a AccountSKUListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AccountSKUListResult. +func (a *AccountSKUListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AgentApplication. +func (a AgentApplication) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AgentApplication. +func (a *AgentApplication) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &a.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AgentApplicationResourceArmPaginatedResult. +func (a AgentApplicationResourceArmPaginatedResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AgentApplicationResourceArmPaginatedResult. +func (a *AgentApplicationResourceArmPaginatedResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &a.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AgentDeployment. +func (a AgentDeployment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AgentDeployment. +func (a *AgentDeployment) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "properties": + a.Properties, err = unmarshalAgentDeploymentPropertiesClassification(val) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &a.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AgentDeploymentProperties. +func (a AgentDeploymentProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "agents", a.Agents) + populate(objectMap, "deploymentId", a.DeploymentID) + populate(objectMap, "deploymentType", a.DeploymentType) + populate(objectMap, "description", a.Description) + populate(objectMap, "displayName", a.DisplayName) + populate(objectMap, "protocols", a.Protocols) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "state", a.State) + populate(objectMap, "tags", a.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AgentDeploymentProperties. +func (a *AgentDeploymentProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "agents": + err = unpopulate(val, "Agents", &a.Agents) + delete(rawMsg, key) + case "deploymentId": + err = unpopulate(val, "DeploymentID", &a.DeploymentID) + delete(rawMsg, key) + case "deploymentType": + err = unpopulate(val, "DeploymentType", &a.DeploymentType) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &a.Description) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &a.DisplayName) + delete(rawMsg, key) + case "protocols": + err = unpopulate(val, "Protocols", &a.Protocols) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &a.State) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &a.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AgentDeploymentResourceArmPaginatedResult. +func (a AgentDeploymentResourceArmPaginatedResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AgentDeploymentResourceArmPaginatedResult. +func (a *AgentDeploymentResourceArmPaginatedResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &a.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AgentProtocolVersion. +func (a AgentProtocolVersion) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "protocol", a.Protocol) + populate(objectMap, "version", a.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AgentProtocolVersion. +func (a *AgentProtocolVersion) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "protocol": + err = unpopulate(val, "Protocol", &a.Protocol) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &a.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AgentReference. +func (a AgentReference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AgentReference. +func (a *AgentReference) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &a.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AgentReferenceProperties. +func (a AgentReferenceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "agentId", a.AgentID) + populate(objectMap, "agentName", a.AgentName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AgentReferenceProperties. +func (a *AgentReferenceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "agentId": + err = unpopulate(val, "AgentID", &a.AgentID) + delete(rawMsg, key) + case "agentName": + err = unpopulate(val, "AgentName", &a.AgentName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AgentReferenceResourceArmPaginatedResult. +func (a AgentReferenceResourceArmPaginatedResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AgentReferenceResourceArmPaginatedResult. +func (a *AgentReferenceResourceArmPaginatedResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &a.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AgenticApplicationProperties. +func (a AgenticApplicationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "agentIdentityBlueprint", a.AgentIdentityBlueprint) + populate(objectMap, "agents", a.Agents) + populate(objectMap, "authorizationPolicy", a.AuthorizationPolicy) + populate(objectMap, "baseUrl", a.BaseURL) + populate(objectMap, "defaultInstanceIdentity", a.DefaultInstanceIdentity) + populate(objectMap, "description", a.Description) + populate(objectMap, "displayName", a.DisplayName) + populate(objectMap, "isEnabled", a.IsEnabled) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "tags", a.Tags) + populate(objectMap, "trafficRoutingPolicy", a.TrafficRoutingPolicy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AgenticApplicationProperties. +func (a *AgenticApplicationProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "agentIdentityBlueprint": + err = unpopulate(val, "AgentIdentityBlueprint", &a.AgentIdentityBlueprint) + delete(rawMsg, key) + case "agents": + err = unpopulate(val, "Agents", &a.Agents) + delete(rawMsg, key) + case "authorizationPolicy": + a.AuthorizationPolicy, err = unmarshalApplicationAuthorizationPolicyClassification(val) + delete(rawMsg, key) + case "baseUrl": + err = unpopulate(val, "BaseURL", &a.BaseURL) + delete(rawMsg, key) + case "defaultInstanceIdentity": + err = unpopulate(val, "DefaultInstanceIdentity", &a.DefaultInstanceIdentity) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &a.Description) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &a.DisplayName) + delete(rawMsg, key) + case "isEnabled": + err = unpopulate(val, "IsEnabled", &a.IsEnabled) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &a.Tags) + delete(rawMsg, key) + case "trafficRoutingPolicy": + err = unpopulate(val, "TrafficRoutingPolicy", &a.TrafficRoutingPolicy) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ApplicationAuthorizationPolicy. +func (a ApplicationAuthorizationPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationAuthorizationPolicy. +func (a *ApplicationAuthorizationPolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ApplicationTrafficRoutingPolicy. +func (a ApplicationTrafficRoutingPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "protocol", a.Protocol) + populate(objectMap, "rules", a.Rules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationTrafficRoutingPolicy. +func (a *ApplicationTrafficRoutingPolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "protocol": + err = unpopulate(val, "Protocol", &a.Protocol) + delete(rawMsg, key) + case "rules": + err = unpopulate(val, "Rules", &a.Rules) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AssignedIdentity. +func (a AssignedIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clientId", a.ClientID) + populate(objectMap, "kind", a.Kind) + populate(objectMap, "principalId", a.PrincipalID) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "subject", a.Subject) + populate(objectMap, "tenantId", a.TenantID) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AssignedIdentity. +func (a *AssignedIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "clientId": + err = unpopulate(val, "ClientID", &a.ClientID) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &a.Kind) + delete(rawMsg, key) + case "principalId": + err = unpopulate(val, "PrincipalID", &a.PrincipalID) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "subject": + err = unpopulate(val, "Subject", &a.Subject) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &a.TenantID) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BillingMeterInfo. +func (b BillingMeterInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "meterId", b.MeterID) + populate(objectMap, "name", b.Name) + populate(objectMap, "unit", b.Unit) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BillingMeterInfo. +func (b *BillingMeterInfo) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "meterId": + err = unpopulate(val, "MeterID", &b.MeterID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &b.Name) + delete(rawMsg, key) + case "unit": + err = unpopulate(val, "Unit", &b.Unit) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CalculateModelCapacityParameter. +func (c CalculateModelCapacityParameter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "model", c.Model) + populate(objectMap, "skuName", c.SKUName) + populate(objectMap, "workloads", c.Workloads) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CalculateModelCapacityParameter. +func (c *CalculateModelCapacityParameter) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "model": + err = unpopulate(val, "Model", &c.Model) + delete(rawMsg, key) + case "skuName": + err = unpopulate(val, "SKUName", &c.SKUName) + delete(rawMsg, key) + case "workloads": + err = unpopulate(val, "Workloads", &c.Workloads) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CalculateModelCapacityResult. +func (c CalculateModelCapacityResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "estimatedCapacity", c.EstimatedCapacity) + populate(objectMap, "model", c.Model) + populate(objectMap, "skuName", c.SKUName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CalculateModelCapacityResult. +func (c *CalculateModelCapacityResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "estimatedCapacity": + err = unpopulate(val, "EstimatedCapacity", &c.EstimatedCapacity) + delete(rawMsg, key) + case "model": + err = unpopulate(val, "Model", &c.Model) + delete(rawMsg, key) + case "skuName": + err = unpopulate(val, "SKUName", &c.SKUName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CalculateModelCapacityResultEstimatedCapacity. +func (c CalculateModelCapacityResultEstimatedCapacity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "deployableValue", c.DeployableValue) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CalculateModelCapacityResultEstimatedCapacity. +func (c *CalculateModelCapacityResultEstimatedCapacity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "deployableValue": + err = unpopulate(val, "DeployableValue", &c.DeployableValue) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &c.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CallRateLimit. +func (c CallRateLimit) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "count", c.Count) + populate(objectMap, "renewalPeriod", c.RenewalPeriod) + populate(objectMap, "rules", c.Rules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CallRateLimit. +func (c *CallRateLimit) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "count": + err = unpopulate(val, "Count", &c.Count) + delete(rawMsg, key) + case "renewalPeriod": + err = unpopulate(val, "RenewalPeriod", &c.RenewalPeriod) + delete(rawMsg, key) + case "rules": + err = unpopulate(val, "Rules", &c.Rules) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CapabilityHost. +func (c CapabilityHost) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", c.ID) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "systemData", c.SystemData) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CapabilityHost. +func (c *CapabilityHost) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &c.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CapabilityHostProperties. +func (c CapabilityHostProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "aiServicesConnections", c.AiServicesConnections) + populate(objectMap, "capabilityHostKind", c.CapabilityHostKind) + populate(objectMap, "customerSubnet", c.CustomerSubnet) + populate(objectMap, "description", c.Description) + populate(objectMap, "enablePublicHostingEnvironment", c.EnablePublicHostingEnvironment) + populate(objectMap, "provisioningState", c.ProvisioningState) + populate(objectMap, "storageConnections", c.StorageConnections) + populate(objectMap, "tags", c.Tags) + populate(objectMap, "threadStorageConnections", c.ThreadStorageConnections) + populate(objectMap, "vectorStoreConnections", c.VectorStoreConnections) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CapabilityHostProperties. +func (c *CapabilityHostProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "aiServicesConnections": + err = unpopulate(val, "AiServicesConnections", &c.AiServicesConnections) + delete(rawMsg, key) + case "capabilityHostKind": + err = unpopulate(val, "CapabilityHostKind", &c.CapabilityHostKind) + delete(rawMsg, key) + case "customerSubnet": + err = unpopulate(val, "CustomerSubnet", &c.CustomerSubnet) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &c.Description) + delete(rawMsg, key) + case "enablePublicHostingEnvironment": + err = unpopulate(val, "EnablePublicHostingEnvironment", &c.EnablePublicHostingEnvironment) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &c.ProvisioningState) + delete(rawMsg, key) + case "storageConnections": + err = unpopulate(val, "StorageConnections", &c.StorageConnections) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &c.Tags) + delete(rawMsg, key) + case "threadStorageConnections": + err = unpopulate(val, "ThreadStorageConnections", &c.ThreadStorageConnections) + delete(rawMsg, key) + case "vectorStoreConnections": + err = unpopulate(val, "VectorStoreConnections", &c.VectorStoreConnections) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CapabilityHostResourceArmPaginatedResult. +func (c CapabilityHostResourceArmPaginatedResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", c.NextLink) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CapabilityHostResourceArmPaginatedResult. +func (c *CapabilityHostResourceArmPaginatedResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &c.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &c.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CapacityConfig. +func (c CapacityConfig) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowedValues", c.AllowedValues) + populate(objectMap, "default", c.Default) + populate(objectMap, "maximum", c.Maximum) + populate(objectMap, "minimum", c.Minimum) + populate(objectMap, "step", c.Step) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CapacityConfig. +func (c *CapacityConfig) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "allowedValues": + err = unpopulate(val, "AllowedValues", &c.AllowedValues) + delete(rawMsg, key) + case "default": + err = unpopulate(val, "Default", &c.Default) + delete(rawMsg, key) + case "maximum": + err = unpopulate(val, "Maximum", &c.Maximum) + delete(rawMsg, key) + case "minimum": + err = unpopulate(val, "Minimum", &c.Minimum) + delete(rawMsg, key) + case "step": + err = unpopulate(val, "Step", &c.Step) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ChannelsBuiltInAuthorizationPolicy. +func (c ChannelsBuiltInAuthorizationPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["type"] = BuiltInAuthorizationSchemeChannels + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ChannelsBuiltInAuthorizationPolicy. +func (c *ChannelsBuiltInAuthorizationPolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CheckDomainAvailabilityParameter. +func (c CheckDomainAvailabilityParameter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "kind", c.Kind) + populate(objectMap, "subdomainName", c.SubdomainName) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CheckDomainAvailabilityParameter. +func (c *CheckDomainAvailabilityParameter) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &c.Kind) + delete(rawMsg, key) + case "subdomainName": + err = unpopulate(val, "SubdomainName", &c.SubdomainName) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CheckSKUAvailabilityParameter. +func (c CheckSKUAvailabilityParameter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "kind", c.Kind) + populate(objectMap, "skus", c.SKUs) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CheckSKUAvailabilityParameter. +func (c *CheckSKUAvailabilityParameter) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &c.Kind) + delete(rawMsg, key) + case "skus": + err = unpopulate(val, "SKUs", &c.SKUs) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CommitmentCost. +func (c CommitmentCost) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "commitmentMeterId", c.CommitmentMeterID) + populate(objectMap, "overageMeterId", c.OverageMeterID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CommitmentCost. +func (c *CommitmentCost) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "commitmentMeterId": + err = unpopulate(val, "CommitmentMeterID", &c.CommitmentMeterID) + delete(rawMsg, key) + case "overageMeterId": + err = unpopulate(val, "OverageMeterID", &c.OverageMeterID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CommitmentPeriod. +func (c CommitmentPeriod) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "count", c.Count) + populate(objectMap, "endDate", c.EndDate) + populate(objectMap, "quota", c.Quota) + populate(objectMap, "startDate", c.StartDate) + populate(objectMap, "tier", c.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CommitmentPeriod. +func (c *CommitmentPeriod) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "count": + err = unpopulate(val, "Count", &c.Count) + delete(rawMsg, key) + case "endDate": + err = unpopulate(val, "EndDate", &c.EndDate) + delete(rawMsg, key) + case "quota": + err = unpopulate(val, "Quota", &c.Quota) + delete(rawMsg, key) + case "startDate": + err = unpopulate(val, "StartDate", &c.StartDate) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &c.Tier) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CommitmentPlan. +func (c CommitmentPlan) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", c.Etag) + populate(objectMap, "id", c.ID) + populate(objectMap, "kind", c.Kind) + populate(objectMap, "location", c.Location) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "sku", c.SKU) + populate(objectMap, "systemData", c.SystemData) + populate(objectMap, "tags", c.Tags) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CommitmentPlan. +func (c *CommitmentPlan) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &c.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &c.Kind) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &c.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &c.SKU) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &c.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &c.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CommitmentPlanAccountAssociation. +func (c CommitmentPlanAccountAssociation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", c.Etag) + populate(objectMap, "id", c.ID) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "systemData", c.SystemData) + populate(objectMap, "tags", c.Tags) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CommitmentPlanAccountAssociation. +func (c *CommitmentPlanAccountAssociation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &c.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &c.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &c.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CommitmentPlanAccountAssociationListResult. +func (c CommitmentPlanAccountAssociationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", c.NextLink) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CommitmentPlanAccountAssociationListResult. +func (c *CommitmentPlanAccountAssociationListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &c.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &c.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CommitmentPlanAccountAssociationProperties. +func (c CommitmentPlanAccountAssociationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "accountId", c.AccountID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CommitmentPlanAccountAssociationProperties. +func (c *CommitmentPlanAccountAssociationProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "accountId": + err = unpopulate(val, "AccountID", &c.AccountID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CommitmentPlanAssociation. +func (c CommitmentPlanAssociation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "commitmentPlanId", c.CommitmentPlanID) + populate(objectMap, "commitmentPlanLocation", c.CommitmentPlanLocation) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CommitmentPlanAssociation. +func (c *CommitmentPlanAssociation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "commitmentPlanId": + err = unpopulate(val, "CommitmentPlanID", &c.CommitmentPlanID) + delete(rawMsg, key) + case "commitmentPlanLocation": + err = unpopulate(val, "CommitmentPlanLocation", &c.CommitmentPlanLocation) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CommitmentPlanListResult. +func (c CommitmentPlanListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", c.NextLink) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CommitmentPlanListResult. +func (c *CommitmentPlanListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &c.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &c.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CommitmentPlanProperties. +func (c CommitmentPlanProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "autoRenew", c.AutoRenew) + populate(objectMap, "commitmentPlanGuid", c.CommitmentPlanGUID) + populate(objectMap, "current", c.Current) + populate(objectMap, "hostingModel", c.HostingModel) + populate(objectMap, "last", c.Last) + populate(objectMap, "next", c.Next) + populate(objectMap, "planType", c.PlanType) + populate(objectMap, "provisioningIssues", c.ProvisioningIssues) + populate(objectMap, "provisioningState", c.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CommitmentPlanProperties. +func (c *CommitmentPlanProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "autoRenew": + err = unpopulate(val, "AutoRenew", &c.AutoRenew) + delete(rawMsg, key) + case "commitmentPlanGuid": + err = unpopulate(val, "CommitmentPlanGUID", &c.CommitmentPlanGUID) + delete(rawMsg, key) + case "current": + err = unpopulate(val, "Current", &c.Current) + delete(rawMsg, key) + case "hostingModel": + err = unpopulate(val, "HostingModel", &c.HostingModel) + delete(rawMsg, key) + case "last": + err = unpopulate(val, "Last", &c.Last) + delete(rawMsg, key) + case "next": + err = unpopulate(val, "Next", &c.Next) + delete(rawMsg, key) + case "planType": + err = unpopulate(val, "PlanType", &c.PlanType) + delete(rawMsg, key) + case "provisioningIssues": + err = unpopulate(val, "ProvisioningIssues", &c.ProvisioningIssues) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &c.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CommitmentQuota. +func (c CommitmentQuota) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "quantity", c.Quantity) + populate(objectMap, "unit", c.Unit) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CommitmentQuota. +func (c *CommitmentQuota) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "quantity": + err = unpopulate(val, "Quantity", &c.Quantity) + delete(rawMsg, key) + case "unit": + err = unpopulate(val, "Unit", &c.Unit) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CommitmentTier. +func (c CommitmentTier) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "cost", c.Cost) + populate(objectMap, "hostingModel", c.HostingModel) + populate(objectMap, "kind", c.Kind) + populate(objectMap, "maxCount", c.MaxCount) + populate(objectMap, "planType", c.PlanType) + populate(objectMap, "quota", c.Quota) + populate(objectMap, "skuName", c.SKUName) + populate(objectMap, "tier", c.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CommitmentTier. +func (c *CommitmentTier) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "cost": + err = unpopulate(val, "Cost", &c.Cost) + delete(rawMsg, key) + case "hostingModel": + err = unpopulate(val, "HostingModel", &c.HostingModel) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &c.Kind) + delete(rawMsg, key) + case "maxCount": + err = unpopulate(val, "MaxCount", &c.MaxCount) + delete(rawMsg, key) + case "planType": + err = unpopulate(val, "PlanType", &c.PlanType) + delete(rawMsg, key) + case "quota": + err = unpopulate(val, "Quota", &c.Quota) + delete(rawMsg, key) + case "skuName": + err = unpopulate(val, "SKUName", &c.SKUName) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &c.Tier) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CommitmentTierListResult. +func (c CommitmentTierListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", c.NextLink) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CommitmentTierListResult. +func (c *CommitmentTierListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &c.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &c.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConnectionAPIKey. +func (c ConnectionAPIKey) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "key", c.Key) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionAPIKey. +func (c *ConnectionAPIKey) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "key": + err = unpopulate(val, "Key", &c.Key) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConnectionAccessKey. +func (c ConnectionAccessKey) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "accessKeyId", c.AccessKeyID) + populate(objectMap, "secretAccessKey", c.SecretAccessKey) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionAccessKey. +func (c *ConnectionAccessKey) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "accessKeyId": + err = unpopulate(val, "AccessKeyID", &c.AccessKeyID) + delete(rawMsg, key) + case "secretAccessKey": + err = unpopulate(val, "SecretAccessKey", &c.SecretAccessKey) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConnectionAccountKey. +func (c ConnectionAccountKey) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "key", c.Key) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionAccountKey. +func (c *ConnectionAccountKey) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "key": + err = unpopulate(val, "Key", &c.Key) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConnectionManagedIdentity. +func (c ConnectionManagedIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clientId", c.ClientID) + populate(objectMap, "resourceId", c.ResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionManagedIdentity. +func (c *ConnectionManagedIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "clientId": + err = unpopulate(val, "ClientID", &c.ClientID) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &c.ResourceID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConnectionOAuth2. +func (c ConnectionOAuth2) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "authUrl", c.AuthURL) + populate(objectMap, "clientId", c.ClientID) + populate(objectMap, "clientSecret", c.ClientSecret) + populate(objectMap, "developerToken", c.DeveloperToken) + populate(objectMap, "password", c.Password) + populate(objectMap, "refreshToken", c.RefreshToken) + populate(objectMap, "tenantId", c.TenantID) + populate(objectMap, "username", c.Username) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionOAuth2. +func (c *ConnectionOAuth2) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "authUrl": + err = unpopulate(val, "AuthURL", &c.AuthURL) + delete(rawMsg, key) + case "clientId": + err = unpopulate(val, "ClientID", &c.ClientID) + delete(rawMsg, key) + case "clientSecret": + err = unpopulate(val, "ClientSecret", &c.ClientSecret) + delete(rawMsg, key) + case "developerToken": + err = unpopulate(val, "DeveloperToken", &c.DeveloperToken) + delete(rawMsg, key) + case "password": + err = unpopulate(val, "Password", &c.Password) + delete(rawMsg, key) + case "refreshToken": + err = unpopulate(val, "RefreshToken", &c.RefreshToken) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &c.TenantID) + delete(rawMsg, key) + case "username": + err = unpopulate(val, "Username", &c.Username) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConnectionPersonalAccessToken. +func (c ConnectionPersonalAccessToken) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "pat", c.Pat) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionPersonalAccessToken. +func (c *ConnectionPersonalAccessToken) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "pat": + err = unpopulate(val, "Pat", &c.Pat) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConnectionPropertiesV2. +func (c ConnectionPropertiesV2) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "authType", c.AuthType) + populate(objectMap, "category", c.Category) + populate(objectMap, "createdByWorkspaceArmId", c.CreatedByWorkspaceArmID) + populate(objectMap, "error", c.Error) + populateTime[datetime.RFC3339](objectMap, "expiryTime", c.ExpiryTime) + populate(objectMap, "group", c.Group) + populate(objectMap, "isSharedToAll", c.IsSharedToAll) + populate(objectMap, "metadata", c.Metadata) + populate(objectMap, "peRequirement", c.PeRequirement) + populate(objectMap, "peStatus", c.PeStatus) + populate(objectMap, "sharedUserList", c.SharedUserList) + populate(objectMap, "target", c.Target) + populate(objectMap, "useWorkspaceManagedIdentity", c.UseWorkspaceManagedIdentity) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionPropertiesV2. +func (c *ConnectionPropertiesV2) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "authType": + err = unpopulate(val, "AuthType", &c.AuthType) + delete(rawMsg, key) + case "category": + err = unpopulate(val, "Category", &c.Category) + delete(rawMsg, key) + case "createdByWorkspaceArmId": + err = unpopulate(val, "CreatedByWorkspaceArmID", &c.CreatedByWorkspaceArmID) + delete(rawMsg, key) + case "error": + err = unpopulate(val, "Error", &c.Error) + delete(rawMsg, key) + case "expiryTime": + err = unpopulateTime[datetime.RFC3339](val, "ExpiryTime", &c.ExpiryTime) + delete(rawMsg, key) + case "group": + err = unpopulate(val, "Group", &c.Group) + delete(rawMsg, key) + case "isSharedToAll": + err = unpopulate(val, "IsSharedToAll", &c.IsSharedToAll) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &c.Metadata) + delete(rawMsg, key) + case "peRequirement": + err = unpopulate(val, "PeRequirement", &c.PeRequirement) + delete(rawMsg, key) + case "peStatus": + err = unpopulate(val, "PeStatus", &c.PeStatus) + delete(rawMsg, key) + case "sharedUserList": + err = unpopulate(val, "SharedUserList", &c.SharedUserList) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &c.Target) + delete(rawMsg, key) + case "useWorkspaceManagedIdentity": + err = unpopulate(val, "UseWorkspaceManagedIdentity", &c.UseWorkspaceManagedIdentity) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConnectionPropertiesV2BasicResource. +func (c ConnectionPropertiesV2BasicResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", c.ID) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "systemData", c.SystemData) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionPropertiesV2BasicResource. +func (c *ConnectionPropertiesV2BasicResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "properties": + c.Properties, err = unmarshalConnectionPropertiesV2Classification(val) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &c.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConnectionPropertiesV2BasicResourceArmPaginatedResult. +func (c ConnectionPropertiesV2BasicResourceArmPaginatedResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", c.NextLink) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionPropertiesV2BasicResourceArmPaginatedResult. +func (c *ConnectionPropertiesV2BasicResourceArmPaginatedResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &c.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &c.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConnectionServicePrincipal. +func (c ConnectionServicePrincipal) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clientId", c.ClientID) + populate(objectMap, "clientSecret", c.ClientSecret) + populate(objectMap, "tenantId", c.TenantID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionServicePrincipal. +func (c *ConnectionServicePrincipal) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "clientId": + err = unpopulate(val, "ClientID", &c.ClientID) + delete(rawMsg, key) + case "clientSecret": + err = unpopulate(val, "ClientSecret", &c.ClientSecret) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &c.TenantID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConnectionSharedAccessSignature. +func (c ConnectionSharedAccessSignature) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "sas", c.Sas) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionSharedAccessSignature. +func (c *ConnectionSharedAccessSignature) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "sas": + err = unpopulate(val, "Sas", &c.Sas) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConnectionUpdateContent. +func (c ConnectionUpdateContent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", c.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionUpdateContent. +func (c *ConnectionUpdateContent) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + c.Properties, err = unmarshalConnectionPropertiesV2Classification(val) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConnectionUsernamePassword. +func (c ConnectionUsernamePassword) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "password", c.Password) + populate(objectMap, "securityToken", c.SecurityToken) + populate(objectMap, "username", c.Username) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionUsernamePassword. +func (c *ConnectionUsernamePassword) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "password": + err = unpopulate(val, "Password", &c.Password) + delete(rawMsg, key) + case "securityToken": + err = unpopulate(val, "SecurityToken", &c.SecurityToken) + delete(rawMsg, key) + case "username": + err = unpopulate(val, "Username", &c.Username) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CustomBlocklistConfig. +func (c CustomBlocklistConfig) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "blocking", c.Blocking) + populate(objectMap, "blocklistName", c.BlocklistName) + populate(objectMap, "source", c.Source) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CustomBlocklistConfig. +func (c *CustomBlocklistConfig) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "blocking": + err = unpopulate(val, "Blocking", &c.Blocking) + delete(rawMsg, key) + case "blocklistName": + err = unpopulate(val, "BlocklistName", &c.BlocklistName) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &c.Source) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CustomKeys. +func (c CustomKeys) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "keys", c.Keys) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CustomKeys. +func (c *CustomKeys) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "keys": + err = unpopulate(val, "Keys", &c.Keys) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CustomKeysConnectionProperties. +func (c CustomKeysConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["authType"] = ConnectionAuthTypeCustomKeys + populate(objectMap, "category", c.Category) + populate(objectMap, "createdByWorkspaceArmId", c.CreatedByWorkspaceArmID) + populate(objectMap, "credentials", c.Credentials) + populate(objectMap, "error", c.Error) + populateTime[datetime.RFC3339](objectMap, "expiryTime", c.ExpiryTime) + populate(objectMap, "group", c.Group) + populate(objectMap, "isSharedToAll", c.IsSharedToAll) + populate(objectMap, "metadata", c.Metadata) + populate(objectMap, "peRequirement", c.PeRequirement) + populate(objectMap, "peStatus", c.PeStatus) + populate(objectMap, "sharedUserList", c.SharedUserList) + populate(objectMap, "target", c.Target) + populate(objectMap, "useWorkspaceManagedIdentity", c.UseWorkspaceManagedIdentity) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CustomKeysConnectionProperties. +func (c *CustomKeysConnectionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "authType": + err = unpopulate(val, "AuthType", &c.AuthType) + delete(rawMsg, key) + case "category": + err = unpopulate(val, "Category", &c.Category) + delete(rawMsg, key) + case "createdByWorkspaceArmId": + err = unpopulate(val, "CreatedByWorkspaceArmID", &c.CreatedByWorkspaceArmID) + delete(rawMsg, key) + case "credentials": + err = unpopulate(val, "Credentials", &c.Credentials) + delete(rawMsg, key) + case "error": + err = unpopulate(val, "Error", &c.Error) + delete(rawMsg, key) + case "expiryTime": + err = unpopulateTime[datetime.RFC3339](val, "ExpiryTime", &c.ExpiryTime) + delete(rawMsg, key) + case "group": + err = unpopulate(val, "Group", &c.Group) + delete(rawMsg, key) + case "isSharedToAll": + err = unpopulate(val, "IsSharedToAll", &c.IsSharedToAll) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &c.Metadata) + delete(rawMsg, key) + case "peRequirement": + err = unpopulate(val, "PeRequirement", &c.PeRequirement) + delete(rawMsg, key) + case "peStatus": + err = unpopulate(val, "PeStatus", &c.PeStatus) + delete(rawMsg, key) + case "sharedUserList": + err = unpopulate(val, "SharedUserList", &c.SharedUserList) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &c.Target) + delete(rawMsg, key) + case "useWorkspaceManagedIdentity": + err = unpopulate(val, "UseWorkspaceManagedIdentity", &c.UseWorkspaceManagedIdentity) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DefenderForAISetting. +func (d DefenderForAISetting) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", d.Etag) + populate(objectMap, "id", d.ID) + populate(objectMap, "name", d.Name) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "systemData", d.SystemData) + populate(objectMap, "tags", d.Tags) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DefenderForAISetting. +func (d *DefenderForAISetting) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &d.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &d.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &d.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &d.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &d.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DefenderForAISettingProperties. +func (d DefenderForAISettingProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "state", d.State) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DefenderForAISettingProperties. +func (d *DefenderForAISettingProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "state": + err = unpopulate(val, "State", &d.State) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DefenderForAISettingResult. +func (d DefenderForAISettingResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", d.NextLink) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DefenderForAISettingResult. +func (d *DefenderForAISettingResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &d.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &d.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Deployment. +func (d Deployment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", d.Etag) + populate(objectMap, "id", d.ID) + populate(objectMap, "name", d.Name) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "sku", d.SKU) + populate(objectMap, "systemData", d.SystemData) + populate(objectMap, "tags", d.Tags) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Deployment. +func (d *Deployment) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &d.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &d.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &d.SKU) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &d.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &d.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &d.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeploymentCapacitySettings. +func (d DeploymentCapacitySettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "designatedCapacity", d.DesignatedCapacity) + populate(objectMap, "priority", d.Priority) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeploymentCapacitySettings. +func (d *DeploymentCapacitySettings) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "designatedCapacity": + err = unpopulate(val, "DesignatedCapacity", &d.DesignatedCapacity) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, "Priority", &d.Priority) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeploymentListResult. +func (d DeploymentListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", d.NextLink) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeploymentListResult. +func (d *DeploymentListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &d.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &d.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeploymentModel. +func (d DeploymentModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "callRateLimit", d.CallRateLimit) + populate(objectMap, "format", d.Format) + populate(objectMap, "name", d.Name) + populate(objectMap, "publisher", d.Publisher) + populate(objectMap, "source", d.Source) + populate(objectMap, "sourceAccount", d.SourceAccount) + populate(objectMap, "version", d.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeploymentModel. +func (d *DeploymentModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "callRateLimit": + err = unpopulate(val, "CallRateLimit", &d.CallRateLimit) + delete(rawMsg, key) + case "format": + err = unpopulate(val, "Format", &d.Format) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "publisher": + err = unpopulate(val, "Publisher", &d.Publisher) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &d.Source) + delete(rawMsg, key) + case "sourceAccount": + err = unpopulate(val, "SourceAccount", &d.SourceAccount) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &d.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeploymentProperties. +func (d DeploymentProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "callRateLimit", d.CallRateLimit) + populate(objectMap, "capabilities", d.Capabilities) + populate(objectMap, "capacitySettings", d.CapacitySettings) + populate(objectMap, "currentCapacity", d.CurrentCapacity) + populate(objectMap, "deploymentState", d.DeploymentState) + populate(objectMap, "dynamicThrottlingEnabled", d.DynamicThrottlingEnabled) + populate(objectMap, "model", d.Model) + populate(objectMap, "parentDeploymentName", d.ParentDeploymentName) + populate(objectMap, "provisioningState", d.ProvisioningState) + populate(objectMap, "raiPolicyName", d.RaiPolicyName) + populate(objectMap, "rateLimits", d.RateLimits) + populate(objectMap, "routing", d.Routing) + populate(objectMap, "scaleSettings", d.ScaleSettings) + populate(objectMap, "serviceTier", d.ServiceTier) + populate(objectMap, "spilloverDeploymentName", d.SpilloverDeploymentName) + populate(objectMap, "versionUpgradeOption", d.VersionUpgradeOption) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeploymentProperties. +func (d *DeploymentProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "callRateLimit": + err = unpopulate(val, "CallRateLimit", &d.CallRateLimit) + delete(rawMsg, key) + case "capabilities": + err = unpopulate(val, "Capabilities", &d.Capabilities) + delete(rawMsg, key) + case "capacitySettings": + err = unpopulate(val, "CapacitySettings", &d.CapacitySettings) + delete(rawMsg, key) + case "currentCapacity": + err = unpopulate(val, "CurrentCapacity", &d.CurrentCapacity) + delete(rawMsg, key) + case "deploymentState": + err = unpopulate(val, "DeploymentState", &d.DeploymentState) + delete(rawMsg, key) + case "dynamicThrottlingEnabled": + err = unpopulate(val, "DynamicThrottlingEnabled", &d.DynamicThrottlingEnabled) + delete(rawMsg, key) + case "model": + err = unpopulate(val, "Model", &d.Model) + delete(rawMsg, key) + case "parentDeploymentName": + err = unpopulate(val, "ParentDeploymentName", &d.ParentDeploymentName) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &d.ProvisioningState) + delete(rawMsg, key) + case "raiPolicyName": + err = unpopulate(val, "RaiPolicyName", &d.RaiPolicyName) + delete(rawMsg, key) + case "rateLimits": + err = unpopulate(val, "RateLimits", &d.RateLimits) + delete(rawMsg, key) + case "routing": + err = unpopulate(val, "Routing", &d.Routing) + delete(rawMsg, key) + case "scaleSettings": + err = unpopulate(val, "ScaleSettings", &d.ScaleSettings) + delete(rawMsg, key) + case "serviceTier": + err = unpopulate(val, "ServiceTier", &d.ServiceTier) + delete(rawMsg, key) + case "spilloverDeploymentName": + err = unpopulate(val, "SpilloverDeploymentName", &d.SpilloverDeploymentName) + delete(rawMsg, key) + case "versionUpgradeOption": + err = unpopulate(val, "VersionUpgradeOption", &d.VersionUpgradeOption) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeploymentRouting. +func (d DeploymentRouting) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "mode", d.Mode) + populate(objectMap, "models", d.Models) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeploymentRouting. +func (d *DeploymentRouting) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "mode": + err = unpopulate(val, "Mode", &d.Mode) + delete(rawMsg, key) + case "models": + err = unpopulate(val, "Models", &d.Models) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeploymentSKUListResult. +func (d DeploymentSKUListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", d.NextLink) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeploymentSKUListResult. +func (d *DeploymentSKUListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &d.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &d.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeploymentScaleSettings. +func (d DeploymentScaleSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "activeCapacity", d.ActiveCapacity) + populate(objectMap, "capacity", d.Capacity) + populate(objectMap, "scaleType", d.ScaleType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeploymentScaleSettings. +func (d *DeploymentScaleSettings) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "activeCapacity": + err = unpopulate(val, "ActiveCapacity", &d.ActiveCapacity) + delete(rawMsg, key) + case "capacity": + err = unpopulate(val, "Capacity", &d.Capacity) + delete(rawMsg, key) + case "scaleType": + err = unpopulate(val, "ScaleType", &d.ScaleType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DomainAvailability. +func (d DomainAvailability) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "isSubdomainAvailable", d.IsSubdomainAvailable) + populate(objectMap, "kind", d.Kind) + populate(objectMap, "reason", d.Reason) + populate(objectMap, "subdomainName", d.SubdomainName) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DomainAvailability. +func (d *DomainAvailability) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "isSubdomainAvailable": + err = unpopulate(val, "IsSubdomainAvailable", &d.IsSubdomainAvailable) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &d.Kind) + delete(rawMsg, key) + case "reason": + err = unpopulate(val, "Reason", &d.Reason) + delete(rawMsg, key) + case "subdomainName": + err = unpopulate(val, "SubdomainName", &d.SubdomainName) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &d.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Encryption. +func (e Encryption) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "keySource", e.KeySource) + populate(objectMap, "keyVaultProperties", e.KeyVaultProperties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Encryption. +func (e *Encryption) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "keySource": + err = unpopulate(val, "KeySource", &e.KeySource) + delete(rawMsg, key) + case "keyVaultProperties": + err = unpopulate(val, "KeyVaultProperties", &e.KeyVaultProperties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EncryptionScope. +func (e EncryptionScope) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", e.Etag) + populate(objectMap, "id", e.ID) + populate(objectMap, "name", e.Name) + populate(objectMap, "properties", e.Properties) + populate(objectMap, "systemData", e.SystemData) + populate(objectMap, "tags", e.Tags) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EncryptionScope. +func (e *EncryptionScope) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &e.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &e.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &e.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &e.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &e.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &e.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &e.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EncryptionScopeListResult. +func (e EncryptionScopeListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", e.NextLink) + populate(objectMap, "value", e.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EncryptionScopeListResult. +func (e *EncryptionScopeListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &e.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &e.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EncryptionScopeProperties. +func (e EncryptionScopeProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "keySource", e.KeySource) + populate(objectMap, "keyVaultProperties", e.KeyVaultProperties) + populate(objectMap, "provisioningState", e.ProvisioningState) + populate(objectMap, "state", e.State) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EncryptionScopeProperties. +func (e *EncryptionScopeProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "keySource": + err = unpopulate(val, "KeySource", &e.KeySource) + delete(rawMsg, key) + case "keyVaultProperties": + err = unpopulate(val, "KeyVaultProperties", &e.KeyVaultProperties) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &e.ProvisioningState) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &e.State) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FqdnOutboundRule. +func (f FqdnOutboundRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "category", f.Category) + populate(objectMap, "destination", f.Destination) + populate(objectMap, "errorInformation", f.ErrorInformation) + populate(objectMap, "parentRuleNames", f.ParentRuleNames) + populate(objectMap, "status", f.Status) + objectMap["type"] = RuleTypeFQDN + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FqdnOutboundRule. +func (f *FqdnOutboundRule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "category": + err = unpopulate(val, "Category", &f.Category) + delete(rawMsg, key) + case "destination": + err = unpopulate(val, "Destination", &f.Destination) + delete(rawMsg, key) + case "errorInformation": + err = unpopulate(val, "ErrorInformation", &f.ErrorInformation) + delete(rawMsg, key) + case "parentRuleNames": + err = unpopulate(val, "ParentRuleNames", &f.ParentRuleNames) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &f.Status) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &f.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HostedAgentDeployment. +func (h HostedAgentDeployment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "agents", h.Agents) + populate(objectMap, "deploymentId", h.DeploymentID) + objectMap["deploymentType"] = AgentDeploymentTypeHosted + populate(objectMap, "description", h.Description) + populate(objectMap, "displayName", h.DisplayName) + populate(objectMap, "maxReplicas", h.MaxReplicas) + populate(objectMap, "minReplicas", h.MinReplicas) + populate(objectMap, "protocols", h.Protocols) + populate(objectMap, "provisioningState", h.ProvisioningState) + populate(objectMap, "state", h.State) + populate(objectMap, "tags", h.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HostedAgentDeployment. +func (h *HostedAgentDeployment) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "agents": + err = unpopulate(val, "Agents", &h.Agents) + delete(rawMsg, key) + case "deploymentId": + err = unpopulate(val, "DeploymentID", &h.DeploymentID) + delete(rawMsg, key) + case "deploymentType": + err = unpopulate(val, "DeploymentType", &h.DeploymentType) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &h.Description) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &h.DisplayName) + delete(rawMsg, key) + case "maxReplicas": + err = unpopulate(val, "MaxReplicas", &h.MaxReplicas) + delete(rawMsg, key) + case "minReplicas": + err = unpopulate(val, "MinReplicas", &h.MinReplicas) + delete(rawMsg, key) + case "protocols": + err = unpopulate(val, "Protocols", &h.Protocols) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &h.ProvisioningState) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &h.State) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &h.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type IPRule. +func (i IPRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", i.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IPRule. +func (i *IPRule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &i.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Identity. +func (i Identity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "principalId", i.PrincipalID) + populate(objectMap, "tenantId", i.TenantID) + populate(objectMap, "type", i.Type) + populate(objectMap, "userAssignedIdentities", i.UserAssignedIdentities) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Identity. +func (i *Identity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "principalId": + err = unpopulate(val, "PrincipalID", &i.PrincipalID) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &i.TenantID) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &i.Type) + delete(rawMsg, key) + case "userAssignedIdentities": + err = unpopulate(val, "UserAssignedIdentities", &i.UserAssignedIdentities) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyVaultProperties. +func (k KeyVaultProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identityClientId", k.IdentityClientID) + populate(objectMap, "keyName", k.KeyName) + populate(objectMap, "keyVaultUri", k.KeyVaultURI) + populate(objectMap, "keyVersion", k.KeyVersion) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyVaultProperties. +func (k *KeyVaultProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "identityClientId": + err = unpopulate(val, "IdentityClientID", &k.IdentityClientID) + delete(rawMsg, key) + case "keyName": + err = unpopulate(val, "KeyName", &k.KeyName) + delete(rawMsg, key) + case "keyVaultUri": + err = unpopulate(val, "KeyVaultURI", &k.KeyVaultURI) + delete(rawMsg, key) + case "keyVersion": + err = unpopulate(val, "KeyVersion", &k.KeyVersion) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedAgentDeployment. +func (m ManagedAgentDeployment) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "agents", m.Agents) + populate(objectMap, "deploymentId", m.DeploymentID) + objectMap["deploymentType"] = AgentDeploymentTypeManaged + populate(objectMap, "description", m.Description) + populate(objectMap, "displayName", m.DisplayName) + populate(objectMap, "protocols", m.Protocols) + populate(objectMap, "provisioningState", m.ProvisioningState) + populate(objectMap, "state", m.State) + populate(objectMap, "tags", m.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedAgentDeployment. +func (m *ManagedAgentDeployment) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "agents": + err = unpopulate(val, "Agents", &m.Agents) + delete(rawMsg, key) + case "deploymentId": + err = unpopulate(val, "DeploymentID", &m.DeploymentID) + delete(rawMsg, key) + case "deploymentType": + err = unpopulate(val, "DeploymentType", &m.DeploymentType) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &m.Description) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &m.DisplayName) + delete(rawMsg, key) + case "protocols": + err = unpopulate(val, "Protocols", &m.Protocols) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &m.ProvisioningState) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &m.State) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &m.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedIdentityAuthTypeConnectionProperties. +func (m ManagedIdentityAuthTypeConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["authType"] = ConnectionAuthTypeManagedIdentity + populate(objectMap, "category", m.Category) + populate(objectMap, "createdByWorkspaceArmId", m.CreatedByWorkspaceArmID) + populate(objectMap, "credentials", m.Credentials) + populate(objectMap, "error", m.Error) + populateTime[datetime.RFC3339](objectMap, "expiryTime", m.ExpiryTime) + populate(objectMap, "group", m.Group) + populate(objectMap, "isSharedToAll", m.IsSharedToAll) + populate(objectMap, "metadata", m.Metadata) + populate(objectMap, "peRequirement", m.PeRequirement) + populate(objectMap, "peStatus", m.PeStatus) + populate(objectMap, "sharedUserList", m.SharedUserList) + populate(objectMap, "target", m.Target) + populate(objectMap, "useWorkspaceManagedIdentity", m.UseWorkspaceManagedIdentity) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedIdentityAuthTypeConnectionProperties. +func (m *ManagedIdentityAuthTypeConnectionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "authType": + err = unpopulate(val, "AuthType", &m.AuthType) + delete(rawMsg, key) + case "category": + err = unpopulate(val, "Category", &m.Category) + delete(rawMsg, key) + case "createdByWorkspaceArmId": + err = unpopulate(val, "CreatedByWorkspaceArmID", &m.CreatedByWorkspaceArmID) + delete(rawMsg, key) + case "credentials": + err = unpopulate(val, "Credentials", &m.Credentials) + delete(rawMsg, key) + case "error": + err = unpopulate(val, "Error", &m.Error) + delete(rawMsg, key) + case "expiryTime": + err = unpopulateTime[datetime.RFC3339](val, "ExpiryTime", &m.ExpiryTime) + delete(rawMsg, key) + case "group": + err = unpopulate(val, "Group", &m.Group) + delete(rawMsg, key) + case "isSharedToAll": + err = unpopulate(val, "IsSharedToAll", &m.IsSharedToAll) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &m.Metadata) + delete(rawMsg, key) + case "peRequirement": + err = unpopulate(val, "PeRequirement", &m.PeRequirement) + delete(rawMsg, key) + case "peStatus": + err = unpopulate(val, "PeStatus", &m.PeStatus) + delete(rawMsg, key) + case "sharedUserList": + err = unpopulate(val, "SharedUserList", &m.SharedUserList) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &m.Target) + delete(rawMsg, key) + case "useWorkspaceManagedIdentity": + err = unpopulate(val, "UseWorkspaceManagedIdentity", &m.UseWorkspaceManagedIdentity) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedNetworkListResult. +func (m ManagedNetworkListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", m.NextLink) + populate(objectMap, "value", m.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedNetworkListResult. +func (m *ManagedNetworkListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &m.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &m.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedNetworkProvisionStatus. +func (m ManagedNetworkProvisionStatus) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "status", m.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedNetworkProvisionStatus. +func (m *ManagedNetworkProvisionStatus) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "status": + err = unpopulate(val, "Status", &m.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedNetworkSettings. +func (m ManagedNetworkSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "firewallPublicIpAddress", m.FirewallPublicIPAddress) + populate(objectMap, "firewallSku", m.FirewallSKU) + populate(objectMap, "isolationMode", m.IsolationMode) + populate(objectMap, "managedNetworkKind", m.ManagedNetworkKind) + populate(objectMap, "networkId", m.NetworkID) + populate(objectMap, "outboundRules", m.OutboundRules) + populate(objectMap, "provisioningState", m.ProvisioningState) + populate(objectMap, "status", m.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedNetworkSettings. +func (m *ManagedNetworkSettings) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "firewallPublicIpAddress": + err = unpopulate(val, "FirewallPublicIPAddress", &m.FirewallPublicIPAddress) + delete(rawMsg, key) + case "firewallSku": + err = unpopulate(val, "FirewallSKU", &m.FirewallSKU) + delete(rawMsg, key) + case "isolationMode": + err = unpopulate(val, "IsolationMode", &m.IsolationMode) + delete(rawMsg, key) + case "managedNetworkKind": + err = unpopulate(val, "ManagedNetworkKind", &m.ManagedNetworkKind) + delete(rawMsg, key) + case "networkId": + err = unpopulate(val, "NetworkID", &m.NetworkID) + delete(rawMsg, key) + case "outboundRules": + m.OutboundRules, err = unmarshalOutboundRuleClassificationMap(val) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &m.ProvisioningState) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &m.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedNetworkSettingsBasicResource. +func (m ManagedNetworkSettingsBasicResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", m.ID) + populate(objectMap, "name", m.Name) + populate(objectMap, "properties", m.Properties) + populate(objectMap, "systemData", m.SystemData) + populate(objectMap, "type", m.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedNetworkSettingsBasicResource. +func (m *ManagedNetworkSettingsBasicResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &m.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &m.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &m.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &m.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedNetworkSettingsEx. +func (m ManagedNetworkSettingsEx) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "changeableIsolationModes", m.ChangeableIsolationModes) + populate(objectMap, "firewallPublicIpAddress", m.FirewallPublicIPAddress) + populate(objectMap, "firewallSku", m.FirewallSKU) + populate(objectMap, "isolationMode", m.IsolationMode) + populate(objectMap, "managedNetworkKind", m.ManagedNetworkKind) + populate(objectMap, "networkId", m.NetworkID) + populate(objectMap, "outboundRules", m.OutboundRules) + populate(objectMap, "provisioningState", m.ProvisioningState) + populate(objectMap, "status", m.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedNetworkSettingsEx. +func (m *ManagedNetworkSettingsEx) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "changeableIsolationModes": + err = unpopulate(val, "ChangeableIsolationModes", &m.ChangeableIsolationModes) + delete(rawMsg, key) + case "firewallPublicIpAddress": + err = unpopulate(val, "FirewallPublicIPAddress", &m.FirewallPublicIPAddress) + delete(rawMsg, key) + case "firewallSku": + err = unpopulate(val, "FirewallSKU", &m.FirewallSKU) + delete(rawMsg, key) + case "isolationMode": + err = unpopulate(val, "IsolationMode", &m.IsolationMode) + delete(rawMsg, key) + case "managedNetworkKind": + err = unpopulate(val, "ManagedNetworkKind", &m.ManagedNetworkKind) + delete(rawMsg, key) + case "networkId": + err = unpopulate(val, "NetworkID", &m.NetworkID) + delete(rawMsg, key) + case "outboundRules": + m.OutboundRules, err = unmarshalOutboundRuleClassificationMap(val) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &m.ProvisioningState) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &m.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedNetworkSettingsProperties. +func (m ManagedNetworkSettingsProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "managedNetwork", m.ManagedNetwork) + populate(objectMap, "provisioningState", m.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedNetworkSettingsProperties. +func (m *ManagedNetworkSettingsProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "managedNetwork": + err = unpopulate(val, "ManagedNetwork", &m.ManagedNetwork) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &m.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedNetworkSettingsPropertiesBasicResource. +func (m ManagedNetworkSettingsPropertiesBasicResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", m.ID) + populate(objectMap, "name", m.Name) + populate(objectMap, "properties", m.Properties) + populate(objectMap, "systemData", m.SystemData) + populate(objectMap, "type", m.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedNetworkSettingsPropertiesBasicResource. +func (m *ManagedNetworkSettingsPropertiesBasicResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &m.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &m.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &m.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &m.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MetricName. +func (m MetricName) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "localizedValue", m.LocalizedValue) + populate(objectMap, "value", m.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MetricName. +func (m *MetricName) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "localizedValue": + err = unpopulate(val, "LocalizedValue", &m.LocalizedValue) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &m.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Model. +func (m Model) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", m.Description) + populate(objectMap, "kind", m.Kind) + populate(objectMap, "model", m.Model) + populate(objectMap, "skuName", m.SKUName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Model. +func (m *Model) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &m.Description) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &m.Kind) + delete(rawMsg, key) + case "model": + err = unpopulate(val, "Model", &m.Model) + delete(rawMsg, key) + case "skuName": + err = unpopulate(val, "SKUName", &m.SKUName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ModelCapacityCalculatorWorkload. +func (m ModelCapacityCalculatorWorkload) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "requestParameters", m.RequestParameters) + populate(objectMap, "requestPerMinute", m.RequestPerMinute) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ModelCapacityCalculatorWorkload. +func (m *ModelCapacityCalculatorWorkload) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "requestParameters": + err = unpopulate(val, "RequestParameters", &m.RequestParameters) + delete(rawMsg, key) + case "requestPerMinute": + err = unpopulate(val, "RequestPerMinute", &m.RequestPerMinute) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ModelCapacityCalculatorWorkloadRequestParam. +func (m ModelCapacityCalculatorWorkloadRequestParam) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "avgGeneratedTokens", m.AvgGeneratedTokens) + populate(objectMap, "avgPromptTokens", m.AvgPromptTokens) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ModelCapacityCalculatorWorkloadRequestParam. +func (m *ModelCapacityCalculatorWorkloadRequestParam) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "avgGeneratedTokens": + err = unpopulate(val, "AvgGeneratedTokens", &m.AvgGeneratedTokens) + delete(rawMsg, key) + case "avgPromptTokens": + err = unpopulate(val, "AvgPromptTokens", &m.AvgPromptTokens) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ModelCapacityListResult. +func (m ModelCapacityListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", m.NextLink) + populate(objectMap, "value", m.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ModelCapacityListResult. +func (m *ModelCapacityListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &m.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &m.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ModelCapacityListResultValueItem. +func (m ModelCapacityListResultValueItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", m.ID) + populate(objectMap, "location", m.Location) + populate(objectMap, "name", m.Name) + populate(objectMap, "properties", m.Properties) + populate(objectMap, "systemData", m.SystemData) + populate(objectMap, "type", m.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ModelCapacityListResultValueItem. +func (m *ModelCapacityListResultValueItem) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &m.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &m.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &m.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &m.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &m.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ModelDeprecationInfo. +func (m ModelDeprecationInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "deprecationStatus", m.DeprecationStatus) + populate(objectMap, "fineTune", m.FineTune) + populate(objectMap, "inference", m.Inference) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ModelDeprecationInfo. +func (m *ModelDeprecationInfo) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "deprecationStatus": + err = unpopulate(val, "DeprecationStatus", &m.DeprecationStatus) + delete(rawMsg, key) + case "fineTune": + err = unpopulate(val, "FineTune", &m.FineTune) + delete(rawMsg, key) + case "inference": + err = unpopulate(val, "Inference", &m.Inference) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ModelListResult. +func (m ModelListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", m.NextLink) + populate(objectMap, "value", m.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ModelListResult. +func (m *ModelListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &m.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &m.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ModelSKU. +func (m ModelSKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "capacity", m.Capacity) + populate(objectMap, "cost", m.Cost) + populateTime[datetime.RFC3339](objectMap, "deprecationDate", m.DeprecationDate) + populate(objectMap, "name", m.Name) + populate(objectMap, "rateLimits", m.RateLimits) + populate(objectMap, "usageName", m.UsageName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ModelSKU. +func (m *ModelSKU) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "capacity": + err = unpopulate(val, "Capacity", &m.Capacity) + delete(rawMsg, key) + case "cost": + err = unpopulate(val, "Cost", &m.Cost) + delete(rawMsg, key) + case "deprecationDate": + err = unpopulateTime[datetime.RFC3339](val, "DeprecationDate", &m.DeprecationDate) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &m.Name) + delete(rawMsg, key) + case "rateLimits": + err = unpopulate(val, "RateLimits", &m.RateLimits) + delete(rawMsg, key) + case "usageName": + err = unpopulate(val, "UsageName", &m.UsageName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ModelSKUCapacityProperties. +func (m ModelSKUCapacityProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "availableCapacity", m.AvailableCapacity) + populate(objectMap, "availableFinetuneCapacity", m.AvailableFinetuneCapacity) + populate(objectMap, "model", m.Model) + populate(objectMap, "skuName", m.SKUName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ModelSKUCapacityProperties. +func (m *ModelSKUCapacityProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "availableCapacity": + err = unpopulate(val, "AvailableCapacity", &m.AvailableCapacity) + delete(rawMsg, key) + case "availableFinetuneCapacity": + err = unpopulate(val, "AvailableFinetuneCapacity", &m.AvailableFinetuneCapacity) + delete(rawMsg, key) + case "model": + err = unpopulate(val, "Model", &m.Model) + delete(rawMsg, key) + case "skuName": + err = unpopulate(val, "SKUName", &m.SKUName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MultiRegionSettings. +func (m MultiRegionSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "regions", m.Regions) + populate(objectMap, "routingMethod", m.RoutingMethod) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MultiRegionSettings. +func (m *MultiRegionSettings) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "regions": + err = unpopulate(val, "Regions", &m.Regions) + delete(rawMsg, key) + case "routingMethod": + err = unpopulate(val, "RoutingMethod", &m.RoutingMethod) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkInjection. +func (n NetworkInjection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "scenario", n.Scenario) + populate(objectMap, "subnetArmId", n.SubnetArmID) + populate(objectMap, "useMicrosoftManagedNetwork", n.UseMicrosoftManagedNetwork) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkInjection. +func (n *NetworkInjection) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "scenario": + err = unpopulate(val, "Scenario", &n.Scenario) + delete(rawMsg, key) + case "subnetArmId": + err = unpopulate(val, "SubnetArmID", &n.SubnetArmID) + delete(rawMsg, key) + case "useMicrosoftManagedNetwork": + err = unpopulate(val, "UseMicrosoftManagedNetwork", &n.UseMicrosoftManagedNetwork) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkRuleSet. +func (n NetworkRuleSet) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "bypass", n.Bypass) + populate(objectMap, "defaultAction", n.DefaultAction) + populate(objectMap, "ipRules", n.IPRules) + populate(objectMap, "virtualNetworkRules", n.VirtualNetworkRules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkRuleSet. +func (n *NetworkRuleSet) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "bypass": + err = unpopulate(val, "Bypass", &n.Bypass) + delete(rawMsg, key) + case "defaultAction": + err = unpopulate(val, "DefaultAction", &n.DefaultAction) + delete(rawMsg, key) + case "ipRules": + err = unpopulate(val, "IPRules", &n.IPRules) + delete(rawMsg, key) + case "virtualNetworkRules": + err = unpopulate(val, "VirtualNetworkRules", &n.VirtualNetworkRules) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkSecurityPerimeter. +func (n NetworkSecurityPerimeter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", n.ID) + populate(objectMap, "location", n.Location) + populate(objectMap, "perimeterGuid", n.PerimeterGUID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkSecurityPerimeter. +func (n *NetworkSecurityPerimeter) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &n.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &n.Location) + delete(rawMsg, key) + case "perimeterGuid": + err = unpopulate(val, "PerimeterGUID", &n.PerimeterGUID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkSecurityPerimeterAccessRule. +func (n NetworkSecurityPerimeterAccessRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", n.Name) + populate(objectMap, "properties", n.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkSecurityPerimeterAccessRule. +func (n *NetworkSecurityPerimeterAccessRule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &n.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &n.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkSecurityPerimeterAccessRuleProperties. +func (n NetworkSecurityPerimeterAccessRuleProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addressPrefixes", n.AddressPrefixes) + populate(objectMap, "direction", n.Direction) + populate(objectMap, "fullyQualifiedDomainNames", n.FullyQualifiedDomainNames) + populate(objectMap, "networkSecurityPerimeters", n.NetworkSecurityPerimeters) + populate(objectMap, "subscriptions", n.Subscriptions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkSecurityPerimeterAccessRuleProperties. +func (n *NetworkSecurityPerimeterAccessRuleProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "addressPrefixes": + err = unpopulate(val, "AddressPrefixes", &n.AddressPrefixes) + delete(rawMsg, key) + case "direction": + err = unpopulate(val, "Direction", &n.Direction) + delete(rawMsg, key) + case "fullyQualifiedDomainNames": + err = unpopulate(val, "FullyQualifiedDomainNames", &n.FullyQualifiedDomainNames) + delete(rawMsg, key) + case "networkSecurityPerimeters": + err = unpopulate(val, "NetworkSecurityPerimeters", &n.NetworkSecurityPerimeters) + delete(rawMsg, key) + case "subscriptions": + err = unpopulate(val, "Subscriptions", &n.Subscriptions) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkSecurityPerimeterAccessRulePropertiesSubscriptionsItem. +func (n NetworkSecurityPerimeterAccessRulePropertiesSubscriptionsItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", n.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkSecurityPerimeterAccessRulePropertiesSubscriptionsItem. +func (n *NetworkSecurityPerimeterAccessRulePropertiesSubscriptionsItem) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &n.ID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkSecurityPerimeterConfiguration. +func (n NetworkSecurityPerimeterConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", n.ID) + populate(objectMap, "name", n.Name) + populate(objectMap, "properties", n.Properties) + populate(objectMap, "systemData", n.SystemData) + populate(objectMap, "type", n.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkSecurityPerimeterConfiguration. +func (n *NetworkSecurityPerimeterConfiguration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &n.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &n.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &n.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &n.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &n.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkSecurityPerimeterConfigurationAssociationInfo. +func (n NetworkSecurityPerimeterConfigurationAssociationInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "accessMode", n.AccessMode) + populate(objectMap, "name", n.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkSecurityPerimeterConfigurationAssociationInfo. +func (n *NetworkSecurityPerimeterConfigurationAssociationInfo) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "accessMode": + err = unpopulate(val, "AccessMode", &n.AccessMode) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &n.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkSecurityPerimeterConfigurationList. +func (n NetworkSecurityPerimeterConfigurationList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", n.NextLink) + populate(objectMap, "value", n.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkSecurityPerimeterConfigurationList. +func (n *NetworkSecurityPerimeterConfigurationList) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &n.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &n.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkSecurityPerimeterConfigurationProperties. +func (n NetworkSecurityPerimeterConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "networkSecurityPerimeter", n.NetworkSecurityPerimeter) + populate(objectMap, "profile", n.Profile) + populate(objectMap, "provisioningIssues", n.ProvisioningIssues) + populate(objectMap, "provisioningState", n.ProvisioningState) + populate(objectMap, "resourceAssociation", n.ResourceAssociation) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkSecurityPerimeterConfigurationProperties. +func (n *NetworkSecurityPerimeterConfigurationProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "networkSecurityPerimeter": + err = unpopulate(val, "NetworkSecurityPerimeter", &n.NetworkSecurityPerimeter) + delete(rawMsg, key) + case "profile": + err = unpopulate(val, "Profile", &n.Profile) + delete(rawMsg, key) + case "provisioningIssues": + err = unpopulate(val, "ProvisioningIssues", &n.ProvisioningIssues) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &n.ProvisioningState) + delete(rawMsg, key) + case "resourceAssociation": + err = unpopulate(val, "ResourceAssociation", &n.ResourceAssociation) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkSecurityPerimeterProfileInfo. +func (n NetworkSecurityPerimeterProfileInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "accessRules", n.AccessRules) + populate(objectMap, "accessRulesVersion", n.AccessRulesVersion) + populate(objectMap, "diagnosticSettingsVersion", n.DiagnosticSettingsVersion) + populate(objectMap, "enabledLogCategories", n.EnabledLogCategories) + populate(objectMap, "name", n.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkSecurityPerimeterProfileInfo. +func (n *NetworkSecurityPerimeterProfileInfo) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "accessRules": + err = unpopulate(val, "AccessRules", &n.AccessRules) + delete(rawMsg, key) + case "accessRulesVersion": + err = unpopulate(val, "AccessRulesVersion", &n.AccessRulesVersion) + delete(rawMsg, key) + case "diagnosticSettingsVersion": + err = unpopulate(val, "DiagnosticSettingsVersion", &n.DiagnosticSettingsVersion) + delete(rawMsg, key) + case "enabledLogCategories": + err = unpopulate(val, "EnabledLogCategories", &n.EnabledLogCategories) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &n.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NoneAuthTypeConnectionProperties. +func (n NoneAuthTypeConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["authType"] = ConnectionAuthTypeNone + populate(objectMap, "category", n.Category) + populate(objectMap, "createdByWorkspaceArmId", n.CreatedByWorkspaceArmID) + populate(objectMap, "error", n.Error) + populateTime[datetime.RFC3339](objectMap, "expiryTime", n.ExpiryTime) + populate(objectMap, "group", n.Group) + populate(objectMap, "isSharedToAll", n.IsSharedToAll) + populate(objectMap, "metadata", n.Metadata) + populate(objectMap, "peRequirement", n.PeRequirement) + populate(objectMap, "peStatus", n.PeStatus) + populate(objectMap, "sharedUserList", n.SharedUserList) + populate(objectMap, "target", n.Target) + populate(objectMap, "useWorkspaceManagedIdentity", n.UseWorkspaceManagedIdentity) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NoneAuthTypeConnectionProperties. +func (n *NoneAuthTypeConnectionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "authType": + err = unpopulate(val, "AuthType", &n.AuthType) + delete(rawMsg, key) + case "category": + err = unpopulate(val, "Category", &n.Category) + delete(rawMsg, key) + case "createdByWorkspaceArmId": + err = unpopulate(val, "CreatedByWorkspaceArmID", &n.CreatedByWorkspaceArmID) + delete(rawMsg, key) + case "error": + err = unpopulate(val, "Error", &n.Error) + delete(rawMsg, key) + case "expiryTime": + err = unpopulateTime[datetime.RFC3339](val, "ExpiryTime", &n.ExpiryTime) + delete(rawMsg, key) + case "group": + err = unpopulate(val, "Group", &n.Group) + delete(rawMsg, key) + case "isSharedToAll": + err = unpopulate(val, "IsSharedToAll", &n.IsSharedToAll) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &n.Metadata) + delete(rawMsg, key) + case "peRequirement": + err = unpopulate(val, "PeRequirement", &n.PeRequirement) + delete(rawMsg, key) + case "peStatus": + err = unpopulate(val, "PeStatus", &n.PeStatus) + delete(rawMsg, key) + case "sharedUserList": + err = unpopulate(val, "SharedUserList", &n.SharedUserList) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &n.Target) + delete(rawMsg, key) + case "useWorkspaceManagedIdentity": + err = unpopulate(val, "UseWorkspaceManagedIdentity", &n.UseWorkspaceManagedIdentity) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OAuth2AuthTypeConnectionProperties. +func (o OAuth2AuthTypeConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["authType"] = ConnectionAuthTypeOAuth2 + populate(objectMap, "category", o.Category) + populate(objectMap, "createdByWorkspaceArmId", o.CreatedByWorkspaceArmID) + populate(objectMap, "credentials", o.Credentials) + populate(objectMap, "error", o.Error) + populateTime[datetime.RFC3339](objectMap, "expiryTime", o.ExpiryTime) + populate(objectMap, "group", o.Group) + populate(objectMap, "isSharedToAll", o.IsSharedToAll) + populate(objectMap, "metadata", o.Metadata) + populate(objectMap, "peRequirement", o.PeRequirement) + populate(objectMap, "peStatus", o.PeStatus) + populate(objectMap, "sharedUserList", o.SharedUserList) + populate(objectMap, "target", o.Target) + populate(objectMap, "useWorkspaceManagedIdentity", o.UseWorkspaceManagedIdentity) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OAuth2AuthTypeConnectionProperties. +func (o *OAuth2AuthTypeConnectionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "authType": + err = unpopulate(val, "AuthType", &o.AuthType) + delete(rawMsg, key) + case "category": + err = unpopulate(val, "Category", &o.Category) + delete(rawMsg, key) + case "createdByWorkspaceArmId": + err = unpopulate(val, "CreatedByWorkspaceArmID", &o.CreatedByWorkspaceArmID) + delete(rawMsg, key) + case "credentials": + err = unpopulate(val, "Credentials", &o.Credentials) + delete(rawMsg, key) + case "error": + err = unpopulate(val, "Error", &o.Error) + delete(rawMsg, key) + case "expiryTime": + err = unpopulateTime[datetime.RFC3339](val, "ExpiryTime", &o.ExpiryTime) + delete(rawMsg, key) + case "group": + err = unpopulate(val, "Group", &o.Group) + delete(rawMsg, key) + case "isSharedToAll": + err = unpopulate(val, "IsSharedToAll", &o.IsSharedToAll) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &o.Metadata) + delete(rawMsg, key) + case "peRequirement": + err = unpopulate(val, "PeRequirement", &o.PeRequirement) + delete(rawMsg, key) + case "peStatus": + err = unpopulate(val, "PeStatus", &o.PeStatus) + delete(rawMsg, key) + case "sharedUserList": + err = unpopulate(val, "SharedUserList", &o.SharedUserList) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &o.Target) + delete(rawMsg, key) + case "useWorkspaceManagedIdentity": + err = unpopulate(val, "UseWorkspaceManagedIdentity", &o.UseWorkspaceManagedIdentity) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Operation. +func (o Operation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionType", o.ActionType) + populate(objectMap, "display", o.Display) + populate(objectMap, "isDataAction", o.IsDataAction) + populate(objectMap, "name", o.Name) + populate(objectMap, "origin", o.Origin) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Operation. +func (o *Operation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionType": + err = unpopulate(val, "ActionType", &o.ActionType) + delete(rawMsg, key) + case "display": + err = unpopulate(val, "Display", &o.Display) + delete(rawMsg, key) + case "isDataAction": + err = unpopulate(val, "IsDataAction", &o.IsDataAction) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "origin": + err = unpopulate(val, "Origin", &o.Origin) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationDisplay. +func (o OperationDisplay) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", o.Description) + populate(objectMap, "operation", o.Operation) + populate(objectMap, "provider", o.Provider) + populate(objectMap, "resource", o.Resource) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationDisplay. +func (o *OperationDisplay) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &o.Description) + delete(rawMsg, key) + case "operation": + err = unpopulate(val, "Operation", &o.Operation) + delete(rawMsg, key) + case "provider": + err = unpopulate(val, "Provider", &o.Provider) + delete(rawMsg, key) + case "resource": + err = unpopulate(val, "Resource", &o.Resource) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationListResult. +func (o *OperationListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &o.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OrganizationSharedBuiltInAuthorizationPolicy. +func (o OrganizationSharedBuiltInAuthorizationPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["type"] = BuiltInAuthorizationSchemeOrganizationScope + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OrganizationSharedBuiltInAuthorizationPolicy. +func (o *OrganizationSharedBuiltInAuthorizationPolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "type": + err = unpopulate(val, "Type", &o.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OutboundRule. +func (o OutboundRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "category", o.Category) + populate(objectMap, "errorInformation", o.ErrorInformation) + populate(objectMap, "parentRuleNames", o.ParentRuleNames) + populate(objectMap, "status", o.Status) + populate(objectMap, "type", o.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OutboundRule. +func (o *OutboundRule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "category": + err = unpopulate(val, "Category", &o.Category) + delete(rawMsg, key) + case "errorInformation": + err = unpopulate(val, "ErrorInformation", &o.ErrorInformation) + delete(rawMsg, key) + case "parentRuleNames": + err = unpopulate(val, "ParentRuleNames", &o.ParentRuleNames) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &o.Status) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &o.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OutboundRuleBasicResource. +func (o OutboundRuleBasicResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", o.ID) + populate(objectMap, "name", o.Name) + populate(objectMap, "properties", o.Properties) + populate(objectMap, "systemData", o.SystemData) + populate(objectMap, "type", o.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OutboundRuleBasicResource. +func (o *OutboundRuleBasicResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &o.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "properties": + o.Properties, err = unmarshalOutboundRuleClassification(val) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &o.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &o.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OutboundRuleListResult. +func (o OutboundRuleListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OutboundRuleListResult. +func (o *OutboundRuleListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &o.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PATAuthTypeConnectionProperties. +func (p PATAuthTypeConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["authType"] = ConnectionAuthTypePAT + populate(objectMap, "category", p.Category) + populate(objectMap, "createdByWorkspaceArmId", p.CreatedByWorkspaceArmID) + populate(objectMap, "credentials", p.Credentials) + populate(objectMap, "error", p.Error) + populateTime[datetime.RFC3339](objectMap, "expiryTime", p.ExpiryTime) + populate(objectMap, "group", p.Group) + populate(objectMap, "isSharedToAll", p.IsSharedToAll) + populate(objectMap, "metadata", p.Metadata) + populate(objectMap, "peRequirement", p.PeRequirement) + populate(objectMap, "peStatus", p.PeStatus) + populate(objectMap, "sharedUserList", p.SharedUserList) + populate(objectMap, "target", p.Target) + populate(objectMap, "useWorkspaceManagedIdentity", p.UseWorkspaceManagedIdentity) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PATAuthTypeConnectionProperties. +func (p *PATAuthTypeConnectionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "authType": + err = unpopulate(val, "AuthType", &p.AuthType) + delete(rawMsg, key) + case "category": + err = unpopulate(val, "Category", &p.Category) + delete(rawMsg, key) + case "createdByWorkspaceArmId": + err = unpopulate(val, "CreatedByWorkspaceArmID", &p.CreatedByWorkspaceArmID) + delete(rawMsg, key) + case "credentials": + err = unpopulate(val, "Credentials", &p.Credentials) + delete(rawMsg, key) + case "error": + err = unpopulate(val, "Error", &p.Error) + delete(rawMsg, key) + case "expiryTime": + err = unpopulateTime[datetime.RFC3339](val, "ExpiryTime", &p.ExpiryTime) + delete(rawMsg, key) + case "group": + err = unpopulate(val, "Group", &p.Group) + delete(rawMsg, key) + case "isSharedToAll": + err = unpopulate(val, "IsSharedToAll", &p.IsSharedToAll) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &p.Metadata) + delete(rawMsg, key) + case "peRequirement": + err = unpopulate(val, "PeRequirement", &p.PeRequirement) + delete(rawMsg, key) + case "peStatus": + err = unpopulate(val, "PeStatus", &p.PeStatus) + delete(rawMsg, key) + case "sharedUserList": + err = unpopulate(val, "SharedUserList", &p.SharedUserList) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &p.Target) + delete(rawMsg, key) + case "useWorkspaceManagedIdentity": + err = unpopulate(val, "UseWorkspaceManagedIdentity", &p.UseWorkspaceManagedIdentity) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PatchResourceTagsAndSKU. +func (p PatchResourceTagsAndSKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "sku", p.SKU) + populate(objectMap, "tags", p.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PatchResourceTagsAndSKU. +func (p *PatchResourceTagsAndSKU) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "sku": + err = unpopulate(val, "SKU", &p.SKU) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &p.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpoint. +func (p PrivateEndpoint) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", p.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpoint. +func (p *PrivateEndpoint) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnection. +func (p PrivateEndpointConnection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", p.Etag) + populate(objectMap, "id", p.ID) + populate(objectMap, "location", p.Location) + populate(objectMap, "name", p.Name) + populate(objectMap, "properties", p.Properties) + populate(objectMap, "systemData", p.SystemData) + populate(objectMap, "type", p.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpointConnection. +func (p *PrivateEndpointConnection) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &p.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &p.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &p.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &p.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &p.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnectionListResult. +func (p PrivateEndpointConnectionListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpointConnectionListResult. +func (p *PrivateEndpointConnectionListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnectionProperties. +func (p PrivateEndpointConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "groupIds", p.GroupIDs) + populate(objectMap, "privateEndpoint", p.PrivateEndpoint) + populate(objectMap, "privateLinkServiceConnectionState", p.PrivateLinkServiceConnectionState) + populate(objectMap, "provisioningState", p.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpointConnectionProperties. +func (p *PrivateEndpointConnectionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "groupIds": + err = unpopulate(val, "GroupIDs", &p.GroupIDs) + delete(rawMsg, key) + case "privateEndpoint": + err = unpopulate(val, "PrivateEndpoint", &p.PrivateEndpoint) + delete(rawMsg, key) + case "privateLinkServiceConnectionState": + err = unpopulate(val, "PrivateLinkServiceConnectionState", &p.PrivateLinkServiceConnectionState) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointOutboundRule. +func (p PrivateEndpointOutboundRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "category", p.Category) + populate(objectMap, "destination", p.Destination) + populate(objectMap, "errorInformation", p.ErrorInformation) + populate(objectMap, "fqdns", p.Fqdns) + populate(objectMap, "parentRuleNames", p.ParentRuleNames) + populate(objectMap, "status", p.Status) + objectMap["type"] = RuleTypePrivateEndpoint + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpointOutboundRule. +func (p *PrivateEndpointOutboundRule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "category": + err = unpopulate(val, "Category", &p.Category) + delete(rawMsg, key) + case "destination": + err = unpopulate(val, "Destination", &p.Destination) + delete(rawMsg, key) + case "errorInformation": + err = unpopulate(val, "ErrorInformation", &p.ErrorInformation) + delete(rawMsg, key) + case "fqdns": + err = unpopulate(val, "Fqdns", &p.Fqdns) + delete(rawMsg, key) + case "parentRuleNames": + err = unpopulate(val, "ParentRuleNames", &p.ParentRuleNames) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &p.Status) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &p.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointOutboundRuleDestination. +func (p PrivateEndpointOutboundRuleDestination) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "serviceResourceId", p.ServiceResourceID) + populate(objectMap, "subresourceTarget", p.SubresourceTarget) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpointOutboundRuleDestination. +func (p *PrivateEndpointOutboundRuleDestination) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "serviceResourceId": + err = unpopulate(val, "ServiceResourceID", &p.ServiceResourceID) + delete(rawMsg, key) + case "subresourceTarget": + err = unpopulate(val, "SubresourceTarget", &p.SubresourceTarget) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResource. +func (p PrivateLinkResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", p.ID) + populate(objectMap, "name", p.Name) + populate(objectMap, "properties", p.Properties) + populate(objectMap, "systemData", p.SystemData) + populate(objectMap, "type", p.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkResource. +func (p *PrivateLinkResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &p.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &p.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &p.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResourceListResult. +func (p PrivateLinkResourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkResourceListResult. +func (p *PrivateLinkResourceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResourceProperties. +func (p PrivateLinkResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "displayName", p.DisplayName) + populate(objectMap, "groupId", p.GroupID) + populate(objectMap, "requiredMembers", p.RequiredMembers) + populate(objectMap, "requiredZoneNames", p.RequiredZoneNames) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkResourceProperties. +func (p *PrivateLinkResourceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "displayName": + err = unpopulate(val, "DisplayName", &p.DisplayName) + delete(rawMsg, key) + case "groupId": + err = unpopulate(val, "GroupID", &p.GroupID) + delete(rawMsg, key) + case "requiredMembers": + err = unpopulate(val, "RequiredMembers", &p.RequiredMembers) + delete(rawMsg, key) + case "requiredZoneNames": + err = unpopulate(val, "RequiredZoneNames", &p.RequiredZoneNames) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkServiceConnectionState. +func (p PrivateLinkServiceConnectionState) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionsRequired", p.ActionsRequired) + populate(objectMap, "description", p.Description) + populate(objectMap, "status", p.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkServiceConnectionState. +func (p *PrivateLinkServiceConnectionState) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionsRequired": + err = unpopulate(val, "ActionsRequired", &p.ActionsRequired) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &p.Description) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &p.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Project. +func (p Project) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", p.Etag) + populate(objectMap, "id", p.ID) + populate(objectMap, "identity", p.Identity) + populate(objectMap, "location", p.Location) + populate(objectMap, "name", p.Name) + populate(objectMap, "properties", p.Properties) + populate(objectMap, "systemData", p.SystemData) + populate(objectMap, "tags", p.Tags) + populate(objectMap, "type", p.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Project. +func (p *Project) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &p.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &p.Identity) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &p.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &p.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &p.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &p.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &p.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ProjectCapabilityHost. +func (p ProjectCapabilityHost) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", p.ID) + populate(objectMap, "name", p.Name) + populate(objectMap, "properties", p.Properties) + populate(objectMap, "systemData", p.SystemData) + populate(objectMap, "type", p.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ProjectCapabilityHost. +func (p *ProjectCapabilityHost) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &p.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &p.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &p.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ProjectCapabilityHostProperties. +func (p ProjectCapabilityHostProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "aiServicesConnections", p.AiServicesConnections) + populate(objectMap, "provisioningState", p.ProvisioningState) + populate(objectMap, "storageConnections", p.StorageConnections) + populate(objectMap, "threadStorageConnections", p.ThreadStorageConnections) + populate(objectMap, "vectorStoreConnections", p.VectorStoreConnections) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ProjectCapabilityHostProperties. +func (p *ProjectCapabilityHostProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "aiServicesConnections": + err = unpopulate(val, "AiServicesConnections", &p.AiServicesConnections) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + case "storageConnections": + err = unpopulate(val, "StorageConnections", &p.StorageConnections) + delete(rawMsg, key) + case "threadStorageConnections": + err = unpopulate(val, "ThreadStorageConnections", &p.ThreadStorageConnections) + delete(rawMsg, key) + case "vectorStoreConnections": + err = unpopulate(val, "VectorStoreConnections", &p.VectorStoreConnections) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ProjectCapabilityHostResourceArmPaginatedResult. +func (p ProjectCapabilityHostResourceArmPaginatedResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", p.NextLink) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ProjectCapabilityHostResourceArmPaginatedResult. +func (p *ProjectCapabilityHostResourceArmPaginatedResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &p.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ProjectListResult. +func (p ProjectListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", p.NextLink) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ProjectListResult. +func (p *ProjectListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &p.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ProjectProperties. +func (p ProjectProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", p.Description) + populate(objectMap, "displayName", p.DisplayName) + populate(objectMap, "endpoints", p.Endpoints) + populate(objectMap, "isDefault", p.IsDefault) + populate(objectMap, "provisioningState", p.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ProjectProperties. +func (p *ProjectProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &p.Description) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &p.DisplayName) + delete(rawMsg, key) + case "endpoints": + err = unpopulate(val, "Endpoints", &p.Endpoints) + delete(rawMsg, key) + case "isDefault": + err = unpopulate(val, "IsDefault", &p.IsDefault) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ProvisioningIssue. +func (p ProvisioningIssue) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", p.Name) + populate(objectMap, "properties", p.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ProvisioningIssue. +func (p *ProvisioningIssue) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &p.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ProvisioningIssueProperties. +func (p ProvisioningIssueProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", p.Description) + populate(objectMap, "issueType", p.IssueType) + populate(objectMap, "severity", p.Severity) + populate(objectMap, "suggestedAccessRules", p.SuggestedAccessRules) + populate(objectMap, "suggestedResourceIds", p.SuggestedResourceIDs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ProvisioningIssueProperties. +func (p *ProvisioningIssueProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &p.Description) + delete(rawMsg, key) + case "issueType": + err = unpopulate(val, "IssueType", &p.IssueType) + delete(rawMsg, key) + case "severity": + err = unpopulate(val, "Severity", &p.Severity) + delete(rawMsg, key) + case "suggestedAccessRules": + err = unpopulate(val, "SuggestedAccessRules", &p.SuggestedAccessRules) + delete(rawMsg, key) + case "suggestedResourceIds": + err = unpopulate(val, "SuggestedResourceIDs", &p.SuggestedResourceIDs) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type QuotaLimit. +func (q QuotaLimit) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "count", q.Count) + populate(objectMap, "renewalPeriod", q.RenewalPeriod) + populate(objectMap, "rules", q.Rules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type QuotaLimit. +func (q *QuotaLimit) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "count": + err = unpopulate(val, "Count", &q.Count) + delete(rawMsg, key) + case "renewalPeriod": + err = unpopulate(val, "RenewalPeriod", &q.RenewalPeriod) + delete(rawMsg, key) + case "rules": + err = unpopulate(val, "Rules", &q.Rules) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type QuotaTier. +func (q QuotaTier) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", q.ID) + populate(objectMap, "name", q.Name) + populate(objectMap, "properties", q.Properties) + populate(objectMap, "systemData", q.SystemData) + populate(objectMap, "type", q.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type QuotaTier. +func (q *QuotaTier) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &q.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &q.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &q.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &q.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &q.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type QuotaTierListResult. +func (q QuotaTierListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", q.NextLink) + populate(objectMap, "value", q.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type QuotaTierListResult. +func (q *QuotaTierListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &q.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &q.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type QuotaTierProperties. +func (q QuotaTierProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "assignmentDate", q.AssignmentDate) + populate(objectMap, "currentTierName", q.CurrentTierName) + populate(objectMap, "tierUpgradeEligibilityInfo", q.TierUpgradeEligibilityInfo) + populate(objectMap, "tierUpgradePolicy", q.TierUpgradePolicy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type QuotaTierProperties. +func (q *QuotaTierProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "assignmentDate": + err = unpopulateTime[datetime.RFC3339](val, "AssignmentDate", &q.AssignmentDate) + delete(rawMsg, key) + case "currentTierName": + err = unpopulate(val, "CurrentTierName", &q.CurrentTierName) + delete(rawMsg, key) + case "tierUpgradeEligibilityInfo": + err = unpopulate(val, "TierUpgradeEligibilityInfo", &q.TierUpgradeEligibilityInfo) + delete(rawMsg, key) + case "tierUpgradePolicy": + err = unpopulate(val, "TierUpgradePolicy", &q.TierUpgradePolicy) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type QuotaTierUpgradeEligibilityInfo. +func (q QuotaTierUpgradeEligibilityInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextTierName", q.NextTierName) + populateTime[datetime.RFC3339](objectMap, "upgradeApplicableDate", q.UpgradeApplicableDate) + populate(objectMap, "upgradeAvailabilityStatus", q.UpgradeAvailabilityStatus) + populate(objectMap, "upgradeUnavailabilityReason", q.UpgradeUnavailabilityReason) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type QuotaTierUpgradeEligibilityInfo. +func (q *QuotaTierUpgradeEligibilityInfo) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextTierName": + err = unpopulate(val, "NextTierName", &q.NextTierName) + delete(rawMsg, key) + case "upgradeApplicableDate": + err = unpopulateTime[datetime.RFC3339](val, "UpgradeApplicableDate", &q.UpgradeApplicableDate) + delete(rawMsg, key) + case "upgradeAvailabilityStatus": + err = unpopulate(val, "UpgradeAvailabilityStatus", &q.UpgradeAvailabilityStatus) + delete(rawMsg, key) + case "upgradeUnavailabilityReason": + err = unpopulate(val, "UpgradeUnavailabilityReason", &q.UpgradeUnavailabilityReason) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RaiBlockListItemsResult. +func (r RaiBlockListItemsResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", r.NextLink) + populate(objectMap, "value", r.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RaiBlockListItemsResult. +func (r *RaiBlockListItemsResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &r.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &r.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RaiBlockListResult. +func (r RaiBlockListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", r.NextLink) + populate(objectMap, "value", r.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RaiBlockListResult. +func (r *RaiBlockListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &r.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &r.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RaiBlocklist. +func (r RaiBlocklist) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", r.Etag) + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "systemData", r.SystemData) + populate(objectMap, "tags", r.Tags) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RaiBlocklist. +func (r *RaiBlocklist) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &r.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &r.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &r.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &r.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RaiBlocklistItem. +func (r RaiBlocklistItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", r.Etag) + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "systemData", r.SystemData) + populate(objectMap, "tags", r.Tags) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RaiBlocklistItem. +func (r *RaiBlocklistItem) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &r.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &r.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &r.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &r.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RaiBlocklistItemBulkRequest. +func (r RaiBlocklistItemBulkRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RaiBlocklistItemBulkRequest. +func (r *RaiBlocklistItemBulkRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &r.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RaiBlocklistItemProperties. +func (r RaiBlocklistItemProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "isRegex", r.IsRegex) + populate(objectMap, "pattern", r.Pattern) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RaiBlocklistItemProperties. +func (r *RaiBlocklistItemProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "isRegex": + err = unpopulate(val, "IsRegex", &r.IsRegex) + delete(rawMsg, key) + case "pattern": + err = unpopulate(val, "Pattern", &r.Pattern) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RaiBlocklistProperties. +func (r RaiBlocklistProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", r.Description) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RaiBlocklistProperties. +func (r *RaiBlocklistProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &r.Description) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RaiContentFilter. +func (r RaiContentFilter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "systemData", r.SystemData) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RaiContentFilter. +func (r *RaiContentFilter) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &r.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &r.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RaiContentFilterListResult. +func (r RaiContentFilterListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", r.NextLink) + populate(objectMap, "value", r.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RaiContentFilterListResult. +func (r *RaiContentFilterListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &r.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &r.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RaiContentFilterProperties. +func (r RaiContentFilterProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "isMultiLevelFilter", r.IsMultiLevelFilter) + populate(objectMap, "name", r.Name) + populate(objectMap, "source", r.Source) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RaiContentFilterProperties. +func (r *RaiContentFilterProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "isMultiLevelFilter": + err = unpopulate(val, "IsMultiLevelFilter", &r.IsMultiLevelFilter) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &r.Source) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RaiExternalSafetyProviderResult. +func (r RaiExternalSafetyProviderResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", r.NextLink) + populate(objectMap, "value", r.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RaiExternalSafetyProviderResult. +func (r *RaiExternalSafetyProviderResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &r.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &r.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RaiExternalSafetyProviderSchema. +func (r RaiExternalSafetyProviderSchema) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", r.Etag) + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "systemData", r.SystemData) + populate(objectMap, "tags", r.Tags) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RaiExternalSafetyProviderSchema. +func (r *RaiExternalSafetyProviderSchema) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &r.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &r.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &r.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &r.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RaiExternalSafetyProviderSchemaProperties. +func (r RaiExternalSafetyProviderSchemaProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "createdAt", r.CreatedAt) + populate(objectMap, "keyVaultUri", r.KeyVaultURI) + populateTime[datetime.RFC3339](objectMap, "lastModifiedAt", r.LastModifiedAt) + populate(objectMap, "managedIdentity", r.ManagedIdentity) + populate(objectMap, "mode", r.Mode) + populate(objectMap, "providerId", r.ProviderID) + populate(objectMap, "providerName", r.ProviderName) + populate(objectMap, "secretName", r.SecretName) + populate(objectMap, "url", r.URL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RaiExternalSafetyProviderSchemaProperties. +func (r *RaiExternalSafetyProviderSchemaProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateTime[datetime.RFC3339](val, "CreatedAt", &r.CreatedAt) + delete(rawMsg, key) + case "keyVaultUri": + err = unpopulate(val, "KeyVaultURI", &r.KeyVaultURI) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateTime[datetime.RFC3339](val, "LastModifiedAt", &r.LastModifiedAt) + delete(rawMsg, key) + case "managedIdentity": + err = unpopulate(val, "ManagedIdentity", &r.ManagedIdentity) + delete(rawMsg, key) + case "mode": + err = unpopulate(val, "Mode", &r.Mode) + delete(rawMsg, key) + case "providerId": + err = unpopulate(val, "ProviderID", &r.ProviderID) + delete(rawMsg, key) + case "providerName": + err = unpopulate(val, "ProviderName", &r.ProviderName) + delete(rawMsg, key) + case "secretName": + err = unpopulate(val, "SecretName", &r.SecretName) + delete(rawMsg, key) + case "url": + err = unpopulate(val, "URL", &r.URL) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RaiMonitorConfig. +func (r RaiMonitorConfig) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "adxStorageResourceId", r.AdxStorageResourceID) + populate(objectMap, "identityClientId", r.IdentityClientID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RaiMonitorConfig. +func (r *RaiMonitorConfig) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "adxStorageResourceId": + err = unpopulate(val, "AdxStorageResourceID", &r.AdxStorageResourceID) + delete(rawMsg, key) + case "identityClientId": + err = unpopulate(val, "IdentityClientID", &r.IdentityClientID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RaiPolicy. +func (r RaiPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", r.Etag) + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "systemData", r.SystemData) + populate(objectMap, "tags", r.Tags) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RaiPolicy. +func (r *RaiPolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &r.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &r.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &r.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &r.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RaiPolicyContentFilter. +func (r RaiPolicyContentFilter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "action", r.Action) + populate(objectMap, "blocking", r.Blocking) + populate(objectMap, "enabled", r.Enabled) + populate(objectMap, "name", r.Name) + populate(objectMap, "severityThreshold", r.SeverityThreshold) + populate(objectMap, "source", r.Source) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RaiPolicyContentFilter. +func (r *RaiPolicyContentFilter) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "action": + err = unpopulate(val, "Action", &r.Action) + delete(rawMsg, key) + case "blocking": + err = unpopulate(val, "Blocking", &r.Blocking) + delete(rawMsg, key) + case "enabled": + err = unpopulate(val, "Enabled", &r.Enabled) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "severityThreshold": + err = unpopulate(val, "SeverityThreshold", &r.SeverityThreshold) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &r.Source) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RaiPolicyListResult. +func (r RaiPolicyListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", r.NextLink) + populate(objectMap, "value", r.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RaiPolicyListResult. +func (r *RaiPolicyListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &r.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &r.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RaiPolicyProperties. +func (r RaiPolicyProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "basePolicyName", r.BasePolicyName) + populate(objectMap, "contentFilters", r.ContentFilters) + populate(objectMap, "customBlocklists", r.CustomBlocklists) + populate(objectMap, "mode", r.Mode) + populate(objectMap, "safetyProviders", r.SafetyProviders) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RaiPolicyProperties. +func (r *RaiPolicyProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "basePolicyName": + err = unpopulate(val, "BasePolicyName", &r.BasePolicyName) + delete(rawMsg, key) + case "contentFilters": + err = unpopulate(val, "ContentFilters", &r.ContentFilters) + delete(rawMsg, key) + case "customBlocklists": + err = unpopulate(val, "CustomBlocklists", &r.CustomBlocklists) + delete(rawMsg, key) + case "mode": + err = unpopulate(val, "Mode", &r.Mode) + delete(rawMsg, key) + case "safetyProviders": + err = unpopulate(val, "SafetyProviders", &r.SafetyProviders) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RaiToolLabel. +func (r RaiToolLabel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", r.Etag) + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "systemData", r.SystemData) + populate(objectMap, "tags", r.Tags) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RaiToolLabel. +func (r *RaiToolLabel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &r.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &r.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &r.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &r.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RaiToolLabelProperties. +func (r RaiToolLabelProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "accountScope", r.AccountScope) + populate(objectMap, "projectScopes", r.ProjectScopes) + populate(objectMap, "toolConnectionName", r.ToolConnectionName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RaiToolLabelProperties. +func (r *RaiToolLabelProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "accountScope": + err = unpopulate(val, "AccountScope", &r.AccountScope) + delete(rawMsg, key) + case "projectScopes": + err = unpopulate(val, "ProjectScopes", &r.ProjectScopes) + delete(rawMsg, key) + case "toolConnectionName": + err = unpopulate(val, "ToolConnectionName", &r.ToolConnectionName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RaiToolLabelPropertiesAccountScope. +func (r RaiToolLabelPropertiesAccountScope) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "labelValues", r.LabelValues) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RaiToolLabelPropertiesAccountScope. +func (r *RaiToolLabelPropertiesAccountScope) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "labelValues": + err = unpopulate(val, "LabelValues", &r.LabelValues) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RaiToolLabelPropertiesProjectScopesItem. +func (r RaiToolLabelPropertiesProjectScopesItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "labelValues", r.LabelValues) + populate(objectMap, "project", r.Project) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RaiToolLabelPropertiesProjectScopesItem. +func (r *RaiToolLabelPropertiesProjectScopesItem) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "labelValues": + err = unpopulate(val, "LabelValues", &r.LabelValues) + delete(rawMsg, key) + case "project": + err = unpopulate(val, "Project", &r.Project) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RaiToolLabelResult. +func (r RaiToolLabelResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", r.NextLink) + populate(objectMap, "value", r.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RaiToolLabelResult. +func (r *RaiToolLabelResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &r.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &r.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RaiTopic. +func (r RaiTopic) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", r.Etag) + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "systemData", r.SystemData) + populate(objectMap, "tags", r.Tags) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RaiTopic. +func (r *RaiTopic) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &r.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &r.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &r.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &r.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RaiTopicProperties. +func (r RaiTopicProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "createdAt", r.CreatedAt) + populate(objectMap, "description", r.Description) + populate(objectMap, "failedReason", r.FailedReason) + populateTime[datetime.RFC3339](objectMap, "lastModifiedAt", r.LastModifiedAt) + populate(objectMap, "sampleBlobUrl", r.SampleBlobURL) + populate(objectMap, "status", r.Status) + populate(objectMap, "topicId", r.TopicID) + populate(objectMap, "topicName", r.TopicName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RaiTopicProperties. +func (r *RaiTopicProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateTime[datetime.RFC3339](val, "CreatedAt", &r.CreatedAt) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &r.Description) + delete(rawMsg, key) + case "failedReason": + err = unpopulate(val, "FailedReason", &r.FailedReason) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateTime[datetime.RFC3339](val, "LastModifiedAt", &r.LastModifiedAt) + delete(rawMsg, key) + case "sampleBlobUrl": + err = unpopulate(val, "SampleBlobURL", &r.SampleBlobURL) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &r.Status) + delete(rawMsg, key) + case "topicId": + err = unpopulate(val, "TopicID", &r.TopicID) + delete(rawMsg, key) + case "topicName": + err = unpopulate(val, "TopicName", &r.TopicName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RaiTopicResult. +func (r RaiTopicResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", r.NextLink) + populate(objectMap, "value", r.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RaiTopicResult. +func (r *RaiTopicResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &r.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &r.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RegenerateKeyParameters. +func (r RegenerateKeyParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "keyName", r.KeyName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RegenerateKeyParameters. +func (r *RegenerateKeyParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "keyName": + err = unpopulate(val, "KeyName", &r.KeyName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RegionSetting. +func (r RegionSetting) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "customsubdomain", r.Customsubdomain) + populate(objectMap, "name", r.Name) + populate(objectMap, "value", r.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RegionSetting. +func (r *RegionSetting) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "customsubdomain": + err = unpopulate(val, "Customsubdomain", &r.Customsubdomain) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &r.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ReplacementConfig. +func (r ReplacementConfig) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "autoUpgradeStartDate", r.AutoUpgradeStartDate) + populate(objectMap, "targetModelName", r.TargetModelName) + populate(objectMap, "targetModelVersion", r.TargetModelVersion) + populate(objectMap, "upgradeOnExpiryLeadTimeDays", r.UpgradeOnExpiryLeadTimeDays) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ReplacementConfig. +func (r *ReplacementConfig) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "autoUpgradeStartDate": + err = unpopulateTime[datetime.RFC3339](val, "AutoUpgradeStartDate", &r.AutoUpgradeStartDate) + delete(rawMsg, key) + case "targetModelName": + err = unpopulate(val, "TargetModelName", &r.TargetModelName) + delete(rawMsg, key) + case "targetModelVersion": + err = unpopulate(val, "TargetModelVersion", &r.TargetModelVersion) + delete(rawMsg, key) + case "upgradeOnExpiryLeadTimeDays": + err = unpopulate(val, "UpgradeOnExpiryLeadTimeDays", &r.UpgradeOnExpiryLeadTimeDays) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RequestMatchPattern. +func (r RequestMatchPattern) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "method", r.Method) + populate(objectMap, "path", r.Path) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RequestMatchPattern. +func (r *RequestMatchPattern) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "method": + err = unpopulate(val, "Method", &r.Method) + delete(rawMsg, key) + case "path": + err = unpopulate(val, "Path", &r.Path) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceSKU. +func (r ResourceSKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "kind", r.Kind) + populate(objectMap, "locations", r.Locations) + populate(objectMap, "name", r.Name) + populate(objectMap, "resourceType", r.ResourceType) + populate(objectMap, "restrictions", r.Restrictions) + populate(objectMap, "tier", r.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceSKU. +func (r *ResourceSKU) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &r.Kind) + delete(rawMsg, key) + case "locations": + err = unpopulate(val, "Locations", &r.Locations) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "resourceType": + err = unpopulate(val, "ResourceType", &r.ResourceType) + delete(rawMsg, key) + case "restrictions": + err = unpopulate(val, "Restrictions", &r.Restrictions) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &r.Tier) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceSKUListResult. +func (r ResourceSKUListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", r.NextLink) + populate(objectMap, "value", r.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceSKUListResult. +func (r *ResourceSKUListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &r.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &r.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceSKURestrictionInfo. +func (r ResourceSKURestrictionInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "locations", r.Locations) + populate(objectMap, "zones", r.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceSKURestrictionInfo. +func (r *ResourceSKURestrictionInfo) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "locations": + err = unpopulate(val, "Locations", &r.Locations) + delete(rawMsg, key) + case "zones": + err = unpopulate(val, "Zones", &r.Zones) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceSKURestrictions. +func (r ResourceSKURestrictions) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "reasonCode", r.ReasonCode) + populate(objectMap, "restrictionInfo", r.RestrictionInfo) + populate(objectMap, "type", r.Type) + populate(objectMap, "values", r.Values) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceSKURestrictions. +func (r *ResourceSKURestrictions) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "reasonCode": + err = unpopulate(val, "ReasonCode", &r.ReasonCode) + delete(rawMsg, key) + case "restrictionInfo": + err = unpopulate(val, "RestrictionInfo", &r.RestrictionInfo) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + case "values": + err = unpopulate(val, "Values", &r.Values) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RoleBasedBuiltInAuthorizationPolicy. +func (r RoleBasedBuiltInAuthorizationPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["type"] = BuiltInAuthorizationSchemeDefault + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RoleBasedBuiltInAuthorizationPolicy. +func (r *RoleBasedBuiltInAuthorizationPolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SASAuthTypeConnectionProperties. +func (s SASAuthTypeConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["authType"] = ConnectionAuthTypeSAS + populate(objectMap, "category", s.Category) + populate(objectMap, "createdByWorkspaceArmId", s.CreatedByWorkspaceArmID) + populate(objectMap, "credentials", s.Credentials) + populate(objectMap, "error", s.Error) + populateTime[datetime.RFC3339](objectMap, "expiryTime", s.ExpiryTime) + populate(objectMap, "group", s.Group) + populate(objectMap, "isSharedToAll", s.IsSharedToAll) + populate(objectMap, "metadata", s.Metadata) + populate(objectMap, "peRequirement", s.PeRequirement) + populate(objectMap, "peStatus", s.PeStatus) + populate(objectMap, "sharedUserList", s.SharedUserList) + populate(objectMap, "target", s.Target) + populate(objectMap, "useWorkspaceManagedIdentity", s.UseWorkspaceManagedIdentity) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SASAuthTypeConnectionProperties. +func (s *SASAuthTypeConnectionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "authType": + err = unpopulate(val, "AuthType", &s.AuthType) + delete(rawMsg, key) + case "category": + err = unpopulate(val, "Category", &s.Category) + delete(rawMsg, key) + case "createdByWorkspaceArmId": + err = unpopulate(val, "CreatedByWorkspaceArmID", &s.CreatedByWorkspaceArmID) + delete(rawMsg, key) + case "credentials": + err = unpopulate(val, "Credentials", &s.Credentials) + delete(rawMsg, key) + case "error": + err = unpopulate(val, "Error", &s.Error) + delete(rawMsg, key) + case "expiryTime": + err = unpopulateTime[datetime.RFC3339](val, "ExpiryTime", &s.ExpiryTime) + delete(rawMsg, key) + case "group": + err = unpopulate(val, "Group", &s.Group) + delete(rawMsg, key) + case "isSharedToAll": + err = unpopulate(val, "IsSharedToAll", &s.IsSharedToAll) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &s.Metadata) + delete(rawMsg, key) + case "peRequirement": + err = unpopulate(val, "PeRequirement", &s.PeRequirement) + delete(rawMsg, key) + case "peStatus": + err = unpopulate(val, "PeStatus", &s.PeStatus) + delete(rawMsg, key) + case "sharedUserList": + err = unpopulate(val, "SharedUserList", &s.SharedUserList) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &s.Target) + delete(rawMsg, key) + case "useWorkspaceManagedIdentity": + err = unpopulate(val, "UseWorkspaceManagedIdentity", &s.UseWorkspaceManagedIdentity) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SKU. +func (s SKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "capacity", s.Capacity) + populate(objectMap, "family", s.Family) + populate(objectMap, "name", s.Name) + populate(objectMap, "size", s.Size) + populate(objectMap, "tier", s.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SKU. +func (s *SKU) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "capacity": + err = unpopulate(val, "Capacity", &s.Capacity) + delete(rawMsg, key) + case "family": + err = unpopulate(val, "Family", &s.Family) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "size": + err = unpopulate(val, "Size", &s.Size) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &s.Tier) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SKUAvailability. +func (s SKUAvailability) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "kind", s.Kind) + populate(objectMap, "message", s.Message) + populate(objectMap, "reason", s.Reason) + populate(objectMap, "skuAvailable", s.SKUAvailable) + populate(objectMap, "skuName", s.SKUName) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SKUAvailability. +func (s *SKUAvailability) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &s.Kind) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &s.Message) + delete(rawMsg, key) + case "reason": + err = unpopulate(val, "Reason", &s.Reason) + delete(rawMsg, key) + case "skuAvailable": + err = unpopulate(val, "SKUAvailable", &s.SKUAvailable) + delete(rawMsg, key) + case "skuName": + err = unpopulate(val, "SKUName", &s.SKUName) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SKUAvailabilityListResult. +func (s SKUAvailabilityListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SKUAvailabilityListResult. +func (s *SKUAvailabilityListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SKUCapability. +func (s SKUCapability) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", s.Name) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SKUCapability. +func (s *SKUCapability) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SKUChangeInfo. +func (s SKUChangeInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "countOfDowngrades", s.CountOfDowngrades) + populate(objectMap, "countOfUpgradesAfterDowngrades", s.CountOfUpgradesAfterDowngrades) + populate(objectMap, "lastChangeDate", s.LastChangeDate) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SKUChangeInfo. +func (s *SKUChangeInfo) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "countOfDowngrades": + err = unpopulate(val, "CountOfDowngrades", &s.CountOfDowngrades) + delete(rawMsg, key) + case "countOfUpgradesAfterDowngrades": + err = unpopulate(val, "CountOfUpgradesAfterDowngrades", &s.CountOfUpgradesAfterDowngrades) + delete(rawMsg, key) + case "lastChangeDate": + err = unpopulate(val, "LastChangeDate", &s.LastChangeDate) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SKUResource. +func (s SKUResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "capacity", s.Capacity) + populate(objectMap, "resourceType", s.ResourceType) + populate(objectMap, "sku", s.SKU) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SKUResource. +func (s *SKUResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "capacity": + err = unpopulate(val, "Capacity", &s.Capacity) + delete(rawMsg, key) + case "resourceType": + err = unpopulate(val, "ResourceType", &s.ResourceType) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &s.SKU) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SafetyProviderConfig. +func (s SafetyProviderConfig) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "blocking", s.Blocking) + populate(objectMap, "safetyProviderName", s.SafetyProviderName) + populate(objectMap, "source", s.Source) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SafetyProviderConfig. +func (s *SafetyProviderConfig) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "blocking": + err = unpopulate(val, "Blocking", &s.Blocking) + delete(rawMsg, key) + case "safetyProviderName": + err = unpopulate(val, "SafetyProviderName", &s.SafetyProviderName) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &s.Source) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ServicePrincipalAuthTypeConnectionProperties. +func (s ServicePrincipalAuthTypeConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["authType"] = ConnectionAuthTypeServicePrincipal + populate(objectMap, "category", s.Category) + populate(objectMap, "createdByWorkspaceArmId", s.CreatedByWorkspaceArmID) + populate(objectMap, "credentials", s.Credentials) + populate(objectMap, "error", s.Error) + populateTime[datetime.RFC3339](objectMap, "expiryTime", s.ExpiryTime) + populate(objectMap, "group", s.Group) + populate(objectMap, "isSharedToAll", s.IsSharedToAll) + populate(objectMap, "metadata", s.Metadata) + populate(objectMap, "peRequirement", s.PeRequirement) + populate(objectMap, "peStatus", s.PeStatus) + populate(objectMap, "sharedUserList", s.SharedUserList) + populate(objectMap, "target", s.Target) + populate(objectMap, "useWorkspaceManagedIdentity", s.UseWorkspaceManagedIdentity) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServicePrincipalAuthTypeConnectionProperties. +func (s *ServicePrincipalAuthTypeConnectionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "authType": + err = unpopulate(val, "AuthType", &s.AuthType) + delete(rawMsg, key) + case "category": + err = unpopulate(val, "Category", &s.Category) + delete(rawMsg, key) + case "createdByWorkspaceArmId": + err = unpopulate(val, "CreatedByWorkspaceArmID", &s.CreatedByWorkspaceArmID) + delete(rawMsg, key) + case "credentials": + err = unpopulate(val, "Credentials", &s.Credentials) + delete(rawMsg, key) + case "error": + err = unpopulate(val, "Error", &s.Error) + delete(rawMsg, key) + case "expiryTime": + err = unpopulateTime[datetime.RFC3339](val, "ExpiryTime", &s.ExpiryTime) + delete(rawMsg, key) + case "group": + err = unpopulate(val, "Group", &s.Group) + delete(rawMsg, key) + case "isSharedToAll": + err = unpopulate(val, "IsSharedToAll", &s.IsSharedToAll) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &s.Metadata) + delete(rawMsg, key) + case "peRequirement": + err = unpopulate(val, "PeRequirement", &s.PeRequirement) + delete(rawMsg, key) + case "peStatus": + err = unpopulate(val, "PeStatus", &s.PeStatus) + delete(rawMsg, key) + case "sharedUserList": + err = unpopulate(val, "SharedUserList", &s.SharedUserList) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &s.Target) + delete(rawMsg, key) + case "useWorkspaceManagedIdentity": + err = unpopulate(val, "UseWorkspaceManagedIdentity", &s.UseWorkspaceManagedIdentity) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ServiceTagOutboundRule. +func (s ServiceTagOutboundRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "category", s.Category) + populate(objectMap, "destination", s.Destination) + populate(objectMap, "errorInformation", s.ErrorInformation) + populate(objectMap, "parentRuleNames", s.ParentRuleNames) + populate(objectMap, "status", s.Status) + objectMap["type"] = RuleTypeServiceTag + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceTagOutboundRule. +func (s *ServiceTagOutboundRule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "category": + err = unpopulate(val, "Category", &s.Category) + delete(rawMsg, key) + case "destination": + err = unpopulate(val, "Destination", &s.Destination) + delete(rawMsg, key) + case "errorInformation": + err = unpopulate(val, "ErrorInformation", &s.ErrorInformation) + delete(rawMsg, key) + case "parentRuleNames": + err = unpopulate(val, "ParentRuleNames", &s.ParentRuleNames) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &s.Status) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ServiceTagOutboundRuleDestination. +func (s ServiceTagOutboundRuleDestination) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "action", s.Action) + populate(objectMap, "addressPrefixes", s.AddressPrefixes) + populate(objectMap, "portRanges", s.PortRanges) + populate(objectMap, "protocol", s.Protocol) + populate(objectMap, "serviceTag", s.ServiceTag) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceTagOutboundRuleDestination. +func (s *ServiceTagOutboundRuleDestination) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "action": + err = unpopulate(val, "Action", &s.Action) + delete(rawMsg, key) + case "addressPrefixes": + err = unpopulate(val, "AddressPrefixes", &s.AddressPrefixes) + delete(rawMsg, key) + case "portRanges": + err = unpopulate(val, "PortRanges", &s.PortRanges) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &s.Protocol) + delete(rawMsg, key) + case "serviceTag": + err = unpopulate(val, "ServiceTag", &s.ServiceTag) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateTime[datetime.RFC3339](objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateTime[datetime.RFC3339](val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateTime[datetime.RFC3339](val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ThrottlingRule. +func (t ThrottlingRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "count", t.Count) + populate(objectMap, "dynamicThrottlingEnabled", t.DynamicThrottlingEnabled) + populate(objectMap, "key", t.Key) + populate(objectMap, "matchPatterns", t.MatchPatterns) + populate(objectMap, "minCount", t.MinCount) + populate(objectMap, "renewalPeriod", t.RenewalPeriod) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ThrottlingRule. +func (t *ThrottlingRule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "count": + err = unpopulate(val, "Count", &t.Count) + delete(rawMsg, key) + case "dynamicThrottlingEnabled": + err = unpopulate(val, "DynamicThrottlingEnabled", &t.DynamicThrottlingEnabled) + delete(rawMsg, key) + case "key": + err = unpopulate(val, "Key", &t.Key) + delete(rawMsg, key) + case "matchPatterns": + err = unpopulate(val, "MatchPatterns", &t.MatchPatterns) + delete(rawMsg, key) + case "minCount": + err = unpopulate(val, "MinCount", &t.MinCount) + delete(rawMsg, key) + case "renewalPeriod": + err = unpopulate(val, "RenewalPeriod", &t.RenewalPeriod) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TrafficRoutingRule. +func (t TrafficRoutingRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "deploymentId", t.DeploymentID) + populate(objectMap, "description", t.Description) + populate(objectMap, "ruleId", t.RuleID) + populate(objectMap, "trafficPercentage", t.TrafficPercentage) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TrafficRoutingRule. +func (t *TrafficRoutingRule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "deploymentId": + err = unpopulate(val, "DeploymentID", &t.DeploymentID) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &t.Description) + delete(rawMsg, key) + case "ruleId": + err = unpopulate(val, "RuleID", &t.RuleID) + delete(rawMsg, key) + case "trafficPercentage": + err = unpopulate(val, "TrafficPercentage", &t.TrafficPercentage) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Usage. +func (u Usage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "currentValue", u.CurrentValue) + populate(objectMap, "limit", u.Limit) + populate(objectMap, "name", u.Name) + populate(objectMap, "nextResetTime", u.NextResetTime) + populate(objectMap, "quotaPeriod", u.QuotaPeriod) + populate(objectMap, "status", u.Status) + populate(objectMap, "unit", u.Unit) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Usage. +func (u *Usage) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "currentValue": + err = unpopulate(val, "CurrentValue", &u.CurrentValue) + delete(rawMsg, key) + case "limit": + err = unpopulate(val, "Limit", &u.Limit) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &u.Name) + delete(rawMsg, key) + case "nextResetTime": + err = unpopulate(val, "NextResetTime", &u.NextResetTime) + delete(rawMsg, key) + case "quotaPeriod": + err = unpopulate(val, "QuotaPeriod", &u.QuotaPeriod) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &u.Status) + delete(rawMsg, key) + case "unit": + err = unpopulate(val, "Unit", &u.Unit) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UsageListResult. +func (u UsageListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", u.NextLink) + populate(objectMap, "value", u.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UsageListResult. +func (u *UsageListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &u.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &u.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserAssignedIdentity. +func (u UserAssignedIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clientId", u.ClientID) + populate(objectMap, "principalId", u.PrincipalID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserAssignedIdentity. +func (u *UserAssignedIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "clientId": + err = unpopulate(val, "ClientID", &u.ClientID) + delete(rawMsg, key) + case "principalId": + err = unpopulate(val, "PrincipalID", &u.PrincipalID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserOwnedAmlWorkspace. +func (u UserOwnedAmlWorkspace) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identityClientId", u.IdentityClientID) + populate(objectMap, "resourceId", u.ResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserOwnedAmlWorkspace. +func (u *UserOwnedAmlWorkspace) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "identityClientId": + err = unpopulate(val, "IdentityClientID", &u.IdentityClientID) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &u.ResourceID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserOwnedStorage. +func (u UserOwnedStorage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identityClientId", u.IdentityClientID) + populate(objectMap, "resourceId", u.ResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserOwnedStorage. +func (u *UserOwnedStorage) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "identityClientId": + err = unpopulate(val, "IdentityClientID", &u.IdentityClientID) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &u.ResourceID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UsernamePasswordAuthTypeConnectionProperties. +func (u UsernamePasswordAuthTypeConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["authType"] = ConnectionAuthTypeUsernamePassword + populate(objectMap, "category", u.Category) + populate(objectMap, "createdByWorkspaceArmId", u.CreatedByWorkspaceArmID) + populate(objectMap, "credentials", u.Credentials) + populate(objectMap, "error", u.Error) + populateTime[datetime.RFC3339](objectMap, "expiryTime", u.ExpiryTime) + populate(objectMap, "group", u.Group) + populate(objectMap, "isSharedToAll", u.IsSharedToAll) + populate(objectMap, "metadata", u.Metadata) + populate(objectMap, "peRequirement", u.PeRequirement) + populate(objectMap, "peStatus", u.PeStatus) + populate(objectMap, "sharedUserList", u.SharedUserList) + populate(objectMap, "target", u.Target) + populate(objectMap, "useWorkspaceManagedIdentity", u.UseWorkspaceManagedIdentity) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UsernamePasswordAuthTypeConnectionProperties. +func (u *UsernamePasswordAuthTypeConnectionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "authType": + err = unpopulate(val, "AuthType", &u.AuthType) + delete(rawMsg, key) + case "category": + err = unpopulate(val, "Category", &u.Category) + delete(rawMsg, key) + case "createdByWorkspaceArmId": + err = unpopulate(val, "CreatedByWorkspaceArmID", &u.CreatedByWorkspaceArmID) + delete(rawMsg, key) + case "credentials": + err = unpopulate(val, "Credentials", &u.Credentials) + delete(rawMsg, key) + case "error": + err = unpopulate(val, "Error", &u.Error) + delete(rawMsg, key) + case "expiryTime": + err = unpopulateTime[datetime.RFC3339](val, "ExpiryTime", &u.ExpiryTime) + delete(rawMsg, key) + case "group": + err = unpopulate(val, "Group", &u.Group) + delete(rawMsg, key) + case "isSharedToAll": + err = unpopulate(val, "IsSharedToAll", &u.IsSharedToAll) + delete(rawMsg, key) + case "metadata": + err = unpopulate(val, "Metadata", &u.Metadata) + delete(rawMsg, key) + case "peRequirement": + err = unpopulate(val, "PeRequirement", &u.PeRequirement) + delete(rawMsg, key) + case "peStatus": + err = unpopulate(val, "PeStatus", &u.PeStatus) + delete(rawMsg, key) + case "sharedUserList": + err = unpopulate(val, "SharedUserList", &u.SharedUserList) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &u.Target) + delete(rawMsg, key) + case "useWorkspaceManagedIdentity": + err = unpopulate(val, "UseWorkspaceManagedIdentity", &u.UseWorkspaceManagedIdentity) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VersionedAgentReference. +func (v VersionedAgentReference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "agentId", v.AgentID) + populate(objectMap, "agentName", v.AgentName) + populate(objectMap, "agentVersion", v.AgentVersion) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VersionedAgentReference. +func (v *VersionedAgentReference) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "agentId": + err = unpopulate(val, "AgentID", &v.AgentID) + delete(rawMsg, key) + case "agentName": + err = unpopulate(val, "AgentName", &v.AgentName) + delete(rawMsg, key) + case "agentVersion": + err = unpopulate(val, "AgentVersion", &v.AgentVersion) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualNetworkRule. +func (v VirtualNetworkRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", v.ID) + populate(objectMap, "ignoreMissingVnetServiceEndpoint", v.IgnoreMissingVnetServiceEndpoint) + populate(objectMap, "state", v.State) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkRule. +func (v *VirtualNetworkRule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &v.ID) + delete(rawMsg, key) + case "ignoreMissingVnetServiceEndpoint": + err = unpopulate(val, "IgnoreMissingVnetServiceEndpoint", &v.IgnoreMissingVnetServiceEndpoint) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &v.State) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/local/armcognitiveservices/zz_networksecurityperimeterconfigurations_client.go b/test/local/armcognitiveservices/zz_networksecurityperimeterconfigurations_client.go new file mode 100644 index 000000000000..c13d5151f8c5 --- /dev/null +++ b/test/local/armcognitiveservices/zz_networksecurityperimeterconfigurations_client.go @@ -0,0 +1,250 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// NetworkSecurityPerimeterConfigurationsClient contains the methods for the NetworkSecurityPerimeterConfigurations group. +// Don't use this type directly, use NewNetworkSecurityPerimeterConfigurationsClient() instead. +// +// Generated from API version 2026-05-01 +type NetworkSecurityPerimeterConfigurationsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewNetworkSecurityPerimeterConfigurationsClient creates a new instance of NetworkSecurityPerimeterConfigurationsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewNetworkSecurityPerimeterConfigurationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*NetworkSecurityPerimeterConfigurationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &NetworkSecurityPerimeterConfigurationsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Gets the specified NSP configurations for an account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - nspConfigurationName - The name of the NSP Configuration. +// - options - NetworkSecurityPerimeterConfigurationsClientGetOptions contains the optional parameters for the NetworkSecurityPerimeterConfigurationsClient.Get +// method. +func (client *NetworkSecurityPerimeterConfigurationsClient) Get(ctx context.Context, resourceGroupName string, accountName string, nspConfigurationName string, options *NetworkSecurityPerimeterConfigurationsClientGetOptions) (NetworkSecurityPerimeterConfigurationsClientGetResponse, error) { + var err error + const operationName = "NetworkSecurityPerimeterConfigurationsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, nspConfigurationName, options) + if err != nil { + return NetworkSecurityPerimeterConfigurationsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NetworkSecurityPerimeterConfigurationsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NetworkSecurityPerimeterConfigurationsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *NetworkSecurityPerimeterConfigurationsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, nspConfigurationName string, _ *NetworkSecurityPerimeterConfigurationsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/networkSecurityPerimeterConfigurations/{nspConfigurationName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if nspConfigurationName == "" { + return nil, errors.New("parameter nspConfigurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{nspConfigurationName}", url.PathEscape(nspConfigurationName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *NetworkSecurityPerimeterConfigurationsClient) getHandleResponse(resp *http.Response) (NetworkSecurityPerimeterConfigurationsClientGetResponse, error) { + result := NetworkSecurityPerimeterConfigurationsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.NetworkSecurityPerimeterConfiguration); err != nil { + return NetworkSecurityPerimeterConfigurationsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets a list of NSP configurations for an account. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - options - NetworkSecurityPerimeterConfigurationsClientListOptions contains the optional parameters for the NetworkSecurityPerimeterConfigurationsClient.NewListPager +// method. +func (client *NetworkSecurityPerimeterConfigurationsClient) NewListPager(resourceGroupName string, accountName string, options *NetworkSecurityPerimeterConfigurationsClientListOptions) *runtime.Pager[NetworkSecurityPerimeterConfigurationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[NetworkSecurityPerimeterConfigurationsClientListResponse]{ + More: func(page NetworkSecurityPerimeterConfigurationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *NetworkSecurityPerimeterConfigurationsClientListResponse) (NetworkSecurityPerimeterConfigurationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "NetworkSecurityPerimeterConfigurationsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, options) + }, nil) + if err != nil { + return NetworkSecurityPerimeterConfigurationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *NetworkSecurityPerimeterConfigurationsClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, _ *NetworkSecurityPerimeterConfigurationsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/networkSecurityPerimeterConfigurations" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *NetworkSecurityPerimeterConfigurationsClient) listHandleResponse(resp *http.Response) (NetworkSecurityPerimeterConfigurationsClientListResponse, error) { + result := NetworkSecurityPerimeterConfigurationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.NetworkSecurityPerimeterConfigurationList); err != nil { + return NetworkSecurityPerimeterConfigurationsClientListResponse{}, err + } + return result, nil +} + +// BeginReconcile - Reconcile the NSP configuration for an account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - nspConfigurationName - The name of the NSP Configuration. +// - options - NetworkSecurityPerimeterConfigurationsClientBeginReconcileOptions contains the optional parameters for the NetworkSecurityPerimeterConfigurationsClient.BeginReconcile +// method. +func (client *NetworkSecurityPerimeterConfigurationsClient) BeginReconcile(ctx context.Context, resourceGroupName string, accountName string, nspConfigurationName string, options *NetworkSecurityPerimeterConfigurationsClientBeginReconcileOptions) (*runtime.Poller[NetworkSecurityPerimeterConfigurationsClientReconcileResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.reconcile(ctx, resourceGroupName, accountName, nspConfigurationName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[NetworkSecurityPerimeterConfigurationsClientReconcileResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[NetworkSecurityPerimeterConfigurationsClientReconcileResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Reconcile - Reconcile the NSP configuration for an account. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *NetworkSecurityPerimeterConfigurationsClient) reconcile(ctx context.Context, resourceGroupName string, accountName string, nspConfigurationName string, options *NetworkSecurityPerimeterConfigurationsClientBeginReconcileOptions) (*http.Response, error) { + var err error + const operationName = "NetworkSecurityPerimeterConfigurationsClient.BeginReconcile" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.reconcileCreateRequest(ctx, resourceGroupName, accountName, nspConfigurationName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// reconcileCreateRequest creates the Reconcile request. +func (client *NetworkSecurityPerimeterConfigurationsClient) reconcileCreateRequest(ctx context.Context, resourceGroupName string, accountName string, nspConfigurationName string, _ *NetworkSecurityPerimeterConfigurationsClientBeginReconcileOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/networkSecurityPerimeterConfigurations/{nspConfigurationName}/reconcile" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if nspConfigurationName == "" { + return nil, errors.New("parameter nspConfigurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{nspConfigurationName}", url.PathEscape(nspConfigurationName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} diff --git a/test/local/armcognitiveservices/zz_operations_client.go b/test/local/armcognitiveservices/zz_operations_client.go new file mode 100644 index 000000000000..555cfc718b99 --- /dev/null +++ b/test/local/armcognitiveservices/zz_operations_client.go @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +// +// Generated from API version 2026-05-01 +type OperationsClient struct { + internal *arm.Client +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*OperationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OperationsClient{ + internal: cl, + } + return client, nil +} + +// NewListPager - Lists all the available Cognitive Services account operations. +// - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ + More: func(page OperationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OperationsClientListResponse) (OperationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OperationsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return OperationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, _ *OperationsClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.CognitiveServices/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsClientListResponse, error) { + result := OperationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_options.go b/test/local/armcognitiveservices/zz_options.go new file mode 100644 index 000000000000..aa649631c5b2 --- /dev/null +++ b/test/local/armcognitiveservices/zz_options.go @@ -0,0 +1,877 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +// AccountCapabilityHostsClientBeginCreateOrUpdateOptions contains the optional parameters for the AccountCapabilityHostsClient.BeginCreateOrUpdate +// method. +type AccountCapabilityHostsClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// AccountCapabilityHostsClientBeginDeleteOptions contains the optional parameters for the AccountCapabilityHostsClient.BeginDelete +// method. +type AccountCapabilityHostsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// AccountCapabilityHostsClientGetOptions contains the optional parameters for the AccountCapabilityHostsClient.Get method. +type AccountCapabilityHostsClientGetOptions struct { + // placeholder for future optional parameters +} + +// AccountCapabilityHostsClientListOptions contains the optional parameters for the AccountCapabilityHostsClient.NewListPager +// method. +type AccountCapabilityHostsClientListOptions struct { + // placeholder for future optional parameters +} + +// AccountConnectionsClientCreateOptions contains the optional parameters for the AccountConnectionsClient.Create method. +type AccountConnectionsClientCreateOptions struct { + // placeholder for future optional parameters +} + +// AccountConnectionsClientDeleteOptions contains the optional parameters for the AccountConnectionsClient.Delete method. +type AccountConnectionsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// AccountConnectionsClientGetOptions contains the optional parameters for the AccountConnectionsClient.Get method. +type AccountConnectionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// AccountConnectionsClientListOptions contains the optional parameters for the AccountConnectionsClient.NewListPager method. +type AccountConnectionsClientListOptions struct { + // Category of the connection. + Category *string + + // query parameter that indicates if get connection call should return both connections and datastores + IncludeAll *bool + + // Target of the connection. + Target *string +} + +// AccountConnectionsClientUpdateOptions contains the optional parameters for the AccountConnectionsClient.Update method. +type AccountConnectionsClientUpdateOptions struct { + // placeholder for future optional parameters +} + +// AccountsClientBeginCreateOptions contains the optional parameters for the AccountsClient.BeginCreate method. +type AccountsClientBeginCreateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// AccountsClientBeginDeleteOptions contains the optional parameters for the AccountsClient.BeginDelete method. +type AccountsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// AccountsClientBeginUpdateOptions contains the optional parameters for the AccountsClient.BeginUpdate method. +type AccountsClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// AccountsClientGetOptions contains the optional parameters for the AccountsClient.Get method. +type AccountsClientGetOptions struct { + // placeholder for future optional parameters +} + +// AccountsClientListByResourceGroupOptions contains the optional parameters for the AccountsClient.NewListByResourceGroupPager +// method. +type AccountsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// AccountsClientListKeysOptions contains the optional parameters for the AccountsClient.ListKeys method. +type AccountsClientListKeysOptions struct { + // placeholder for future optional parameters +} + +// AccountsClientListModelsOptions contains the optional parameters for the AccountsClient.NewListModelsPager method. +type AccountsClientListModelsOptions struct { + // placeholder for future optional parameters +} + +// AccountsClientListOptions contains the optional parameters for the AccountsClient.NewListPager method. +type AccountsClientListOptions struct { + // placeholder for future optional parameters +} + +// AccountsClientListSKUsOptions contains the optional parameters for the AccountsClient.ListSKUs method. +type AccountsClientListSKUsOptions struct { + // placeholder for future optional parameters +} + +// AccountsClientListUsagesOptions contains the optional parameters for the AccountsClient.ListUsages method. +type AccountsClientListUsagesOptions struct { + // An OData filter expression that describes a subset of usages to return. The supported parameter is name.value (name of + // the metric, can have an or of multiple names). + Filter *string +} + +// AccountsClientRegenerateKeyOptions contains the optional parameters for the AccountsClient.RegenerateKey method. +type AccountsClientRegenerateKeyOptions struct { + // placeholder for future optional parameters +} + +// AgentApplicationsClientBeginCreateOrUpdateOptions contains the optional parameters for the AgentApplicationsClient.BeginCreateOrUpdate +// method. +type AgentApplicationsClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// AgentApplicationsClientBeginDeleteOptions contains the optional parameters for the AgentApplicationsClient.BeginDelete +// method. +type AgentApplicationsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// AgentApplicationsClientDisableOptions contains the optional parameters for the AgentApplicationsClient.Disable method. +type AgentApplicationsClientDisableOptions struct { + // placeholder for future optional parameters +} + +// AgentApplicationsClientEnableOptions contains the optional parameters for the AgentApplicationsClient.Enable method. +type AgentApplicationsClientEnableOptions struct { + // placeholder for future optional parameters +} + +// AgentApplicationsClientGetOptions contains the optional parameters for the AgentApplicationsClient.Get method. +type AgentApplicationsClientGetOptions struct { + // placeholder for future optional parameters +} + +// AgentApplicationsClientListAgentsOptions contains the optional parameters for the AgentApplicationsClient.ListAgents method. +type AgentApplicationsClientListAgentsOptions struct { + // placeholder for future optional parameters +} + +// AgentApplicationsClientListOptions contains the optional parameters for the AgentApplicationsClient.NewListPager method. +type AgentApplicationsClientListOptions struct { + // Number of agent applications to be retrieved in a page of results. + Count *int32 + + // Names of agent applications to retrieve. + Names []string + + // Field to order by. + OrderBy *string + + // Whether to order in ascending order. + OrderByAsc *bool + + // Search text for filtering agent applications. + SearchText *string + + // Number of agent applications to skip. + Skip *int32 + + // Continuation token for pagination. + SkipToken *string +} + +// AgentDeploymentsClientBeginCreateOrUpdateOptions contains the optional parameters for the AgentDeploymentsClient.BeginCreateOrUpdate +// method. +type AgentDeploymentsClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// AgentDeploymentsClientBeginDeleteOptions contains the optional parameters for the AgentDeploymentsClient.BeginDelete method. +type AgentDeploymentsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// AgentDeploymentsClientGetOptions contains the optional parameters for the AgentDeploymentsClient.Get method. +type AgentDeploymentsClientGetOptions struct { + // placeholder for future optional parameters +} + +// AgentDeploymentsClientListOptions contains the optional parameters for the AgentDeploymentsClient.NewListPager method. +type AgentDeploymentsClientListOptions struct { + // Number of agent deployments to be retrieved in a page of results. + Count *int32 + + // Names of agent deployments to retrieve. + Names []string + + // Field to order by. + OrderBy *string + + // Whether to order in ascending order. + OrderByAsc *bool + + // Continuation token for pagination. + SkipToken *string +} + +// AgentDeploymentsClientStartOptions contains the optional parameters for the AgentDeploymentsClient.Start method. +type AgentDeploymentsClientStartOptions struct { + // placeholder for future optional parameters +} + +// AgentDeploymentsClientStopOptions contains the optional parameters for the AgentDeploymentsClient.Stop method. +type AgentDeploymentsClientStopOptions struct { + // placeholder for future optional parameters +} + +// CommitmentPlansClientBeginCreateOrUpdateAssociationOptions contains the optional parameters for the CommitmentPlansClient.BeginCreateOrUpdateAssociation +// method. +type CommitmentPlansClientBeginCreateOrUpdateAssociationOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CommitmentPlansClientBeginCreateOrUpdatePlanOptions contains the optional parameters for the CommitmentPlansClient.BeginCreateOrUpdatePlan +// method. +type CommitmentPlansClientBeginCreateOrUpdatePlanOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CommitmentPlansClientBeginDeleteAssociationOptions contains the optional parameters for the CommitmentPlansClient.BeginDeleteAssociation +// method. +type CommitmentPlansClientBeginDeleteAssociationOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CommitmentPlansClientBeginDeleteOptions contains the optional parameters for the CommitmentPlansClient.BeginDelete method. +type CommitmentPlansClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CommitmentPlansClientBeginDeletePlanOptions contains the optional parameters for the CommitmentPlansClient.BeginDeletePlan +// method. +type CommitmentPlansClientBeginDeletePlanOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CommitmentPlansClientBeginUpdatePlanOptions contains the optional parameters for the CommitmentPlansClient.BeginUpdatePlan +// method. +type CommitmentPlansClientBeginUpdatePlanOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CommitmentPlansClientCreateOrUpdateOptions contains the optional parameters for the CommitmentPlansClient.CreateOrUpdate +// method. +type CommitmentPlansClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// CommitmentPlansClientGetAssociationOptions contains the optional parameters for the CommitmentPlansClient.GetAssociation +// method. +type CommitmentPlansClientGetAssociationOptions struct { + // placeholder for future optional parameters +} + +// CommitmentPlansClientGetOptions contains the optional parameters for the CommitmentPlansClient.Get method. +type CommitmentPlansClientGetOptions struct { + // placeholder for future optional parameters +} + +// CommitmentPlansClientGetPlanOptions contains the optional parameters for the CommitmentPlansClient.GetPlan method. +type CommitmentPlansClientGetPlanOptions struct { + // placeholder for future optional parameters +} + +// CommitmentPlansClientListAssociationsOptions contains the optional parameters for the CommitmentPlansClient.NewListAssociationsPager +// method. +type CommitmentPlansClientListAssociationsOptions struct { + // placeholder for future optional parameters +} + +// CommitmentPlansClientListOptions contains the optional parameters for the CommitmentPlansClient.NewListPager method. +type CommitmentPlansClientListOptions struct { + // placeholder for future optional parameters +} + +// CommitmentPlansClientListPlansByResourceGroupOptions contains the optional parameters for the CommitmentPlansClient.NewListPlansByResourceGroupPager +// method. +type CommitmentPlansClientListPlansByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// CommitmentPlansClientListPlansBySubscriptionOptions contains the optional parameters for the CommitmentPlansClient.NewListPlansBySubscriptionPager +// method. +type CommitmentPlansClientListPlansBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// CommitmentTiersClientListOptions contains the optional parameters for the CommitmentTiersClient.NewListPager method. +type CommitmentTiersClientListOptions struct { + // placeholder for future optional parameters +} + +// DefenderForAISettingsClientCreateOrUpdateOptions contains the optional parameters for the DefenderForAISettingsClient.CreateOrUpdate +// method. +type DefenderForAISettingsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// DefenderForAISettingsClientGetOptions contains the optional parameters for the DefenderForAISettingsClient.Get method. +type DefenderForAISettingsClientGetOptions struct { + // placeholder for future optional parameters +} + +// DefenderForAISettingsClientListOptions contains the optional parameters for the DefenderForAISettingsClient.NewListPager +// method. +type DefenderForAISettingsClientListOptions struct { + // placeholder for future optional parameters +} + +// DefenderForAISettingsClientUpdateOptions contains the optional parameters for the DefenderForAISettingsClient.Update method. +type DefenderForAISettingsClientUpdateOptions struct { + // placeholder for future optional parameters +} + +// DeletedAccountsClientBeginPurgeOptions contains the optional parameters for the DeletedAccountsClient.BeginPurge method. +type DeletedAccountsClientBeginPurgeOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// DeletedAccountsClientGetOptions contains the optional parameters for the DeletedAccountsClient.Get method. +type DeletedAccountsClientGetOptions struct { + // placeholder for future optional parameters +} + +// DeletedAccountsClientListOptions contains the optional parameters for the DeletedAccountsClient.NewListPager method. +type DeletedAccountsClientListOptions struct { + // placeholder for future optional parameters +} + +// DeploymentsClientBeginCreateOrUpdateOptions contains the optional parameters for the DeploymentsClient.BeginCreateOrUpdate +// method. +type DeploymentsClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// DeploymentsClientBeginDeleteOptions contains the optional parameters for the DeploymentsClient.BeginDelete method. +type DeploymentsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// DeploymentsClientBeginUpdateOptions contains the optional parameters for the DeploymentsClient.BeginUpdate method. +type DeploymentsClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// DeploymentsClientGetOptions contains the optional parameters for the DeploymentsClient.Get method. +type DeploymentsClientGetOptions struct { + // placeholder for future optional parameters +} + +// DeploymentsClientListOptions contains the optional parameters for the DeploymentsClient.NewListPager method. +type DeploymentsClientListOptions struct { + // placeholder for future optional parameters +} + +// DeploymentsClientListSKUsOptions contains the optional parameters for the DeploymentsClient.NewListSKUsPager method. +type DeploymentsClientListSKUsOptions struct { + // placeholder for future optional parameters +} + +// DeploymentsClientPauseOptions contains the optional parameters for the DeploymentsClient.Pause method. +type DeploymentsClientPauseOptions struct { + // placeholder for future optional parameters +} + +// DeploymentsClientResumeOptions contains the optional parameters for the DeploymentsClient.Resume method. +type DeploymentsClientResumeOptions struct { + // placeholder for future optional parameters +} + +// EncryptionScopesClientBeginDeleteOptions contains the optional parameters for the EncryptionScopesClient.BeginDelete method. +type EncryptionScopesClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// EncryptionScopesClientCreateOrUpdateOptions contains the optional parameters for the EncryptionScopesClient.CreateOrUpdate +// method. +type EncryptionScopesClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// EncryptionScopesClientGetOptions contains the optional parameters for the EncryptionScopesClient.Get method. +type EncryptionScopesClientGetOptions struct { + // placeholder for future optional parameters +} + +// EncryptionScopesClientListOptions contains the optional parameters for the EncryptionScopesClient.NewListPager method. +type EncryptionScopesClientListOptions struct { + // placeholder for future optional parameters +} + +// LocationBasedModelCapacitiesClientListOptions contains the optional parameters for the LocationBasedModelCapacitiesClient.NewListPager +// method. +type LocationBasedModelCapacitiesClientListOptions struct { + // placeholder for future optional parameters +} + +// ManagedNetworkProvisionsClientBeginProvisionManagedNetworkOptions contains the optional parameters for the ManagedNetworkProvisionsClient.BeginProvisionManagedNetwork +// method. +type ManagedNetworkProvisionsClientBeginProvisionManagedNetworkOptions struct { + // Managed Network Provisioning Options for a cognitive services account. + Body *ManagedNetworkProvisionOptions + + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ManagedNetworkSettingsClientBeginDeleteOptions contains the optional parameters for the ManagedNetworkSettingsClient.BeginDelete +// method. +type ManagedNetworkSettingsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ManagedNetworkSettingsClientBeginPatchOptions contains the optional parameters for the ManagedNetworkSettingsClient.BeginPatch +// method. +type ManagedNetworkSettingsClientBeginPatchOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ManagedNetworkSettingsClientBeginPutOptions contains the optional parameters for the ManagedNetworkSettingsClient.BeginPut +// method. +type ManagedNetworkSettingsClientBeginPutOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ManagedNetworkSettingsClientGetOptions contains the optional parameters for the ManagedNetworkSettingsClient.Get method. +type ManagedNetworkSettingsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ManagedNetworkSettingsClientListOptions contains the optional parameters for the ManagedNetworkSettingsClient.NewListPager +// method. +type ManagedNetworkSettingsClientListOptions struct { + // placeholder for future optional parameters +} + +// ManagementClientCalculateModelCapacityOptions contains the optional parameters for the ManagementClient.CalculateModelCapacity +// method. +type ManagementClientCalculateModelCapacityOptions struct { + // placeholder for future optional parameters +} + +// ManagementClientCheckDomainAvailabilityOptions contains the optional parameters for the ManagementClient.CheckDomainAvailability +// method. +type ManagementClientCheckDomainAvailabilityOptions struct { + // placeholder for future optional parameters +} + +// ManagementClientCheckSKUAvailabilityOptions contains the optional parameters for the ManagementClient.CheckSKUAvailability +// method. +type ManagementClientCheckSKUAvailabilityOptions struct { + // placeholder for future optional parameters +} + +// ModelCapacitiesClientListOptions contains the optional parameters for the ModelCapacitiesClient.NewListPager method. +type ModelCapacitiesClientListOptions struct { + // placeholder for future optional parameters +} + +// ModelsClientListOptions contains the optional parameters for the ModelsClient.NewListPager method. +type ModelsClientListOptions struct { + // placeholder for future optional parameters +} + +// NetworkSecurityPerimeterConfigurationsClientBeginReconcileOptions contains the optional parameters for the NetworkSecurityPerimeterConfigurationsClient.BeginReconcile +// method. +type NetworkSecurityPerimeterConfigurationsClientBeginReconcileOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// NetworkSecurityPerimeterConfigurationsClientGetOptions contains the optional parameters for the NetworkSecurityPerimeterConfigurationsClient.Get +// method. +type NetworkSecurityPerimeterConfigurationsClientGetOptions struct { + // placeholder for future optional parameters +} + +// NetworkSecurityPerimeterConfigurationsClientListOptions contains the optional parameters for the NetworkSecurityPerimeterConfigurationsClient.NewListPager +// method. +type NetworkSecurityPerimeterConfigurationsClientListOptions struct { + // placeholder for future optional parameters +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} + +// OutboundRuleClientBeginCreateOrUpdateOptions contains the optional parameters for the OutboundRuleClient.BeginCreateOrUpdate +// method. +type OutboundRuleClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// OutboundRuleClientBeginDeleteOptions contains the optional parameters for the OutboundRuleClient.BeginDelete method. +type OutboundRuleClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// OutboundRuleClientGetOptions contains the optional parameters for the OutboundRuleClient.Get method. +type OutboundRuleClientGetOptions struct { + // placeholder for future optional parameters +} + +// OutboundRuleClientListOptions contains the optional parameters for the OutboundRuleClient.NewListPager method. +type OutboundRuleClientListOptions struct { + // placeholder for future optional parameters +} + +// OutboundRulesClientBeginPostOptions contains the optional parameters for the OutboundRulesClient.BeginPost method. +type OutboundRulesClientBeginPostOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// PrivateEndpointConnectionsClientBeginCreateOrUpdateOptions contains the optional parameters for the PrivateEndpointConnectionsClient.BeginCreateOrUpdate +// method. +type PrivateEndpointConnectionsClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// PrivateEndpointConnectionsClientBeginDeleteOptions contains the optional parameters for the PrivateEndpointConnectionsClient.BeginDelete +// method. +type PrivateEndpointConnectionsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// PrivateEndpointConnectionsClientGetOptions contains the optional parameters for the PrivateEndpointConnectionsClient.Get +// method. +type PrivateEndpointConnectionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointConnectionsClientListOptions contains the optional parameters for the PrivateEndpointConnectionsClient.List +// method. +type PrivateEndpointConnectionsClientListOptions struct { + // placeholder for future optional parameters +} + +// PrivateLinkResourcesClientListOptions contains the optional parameters for the PrivateLinkResourcesClient.List method. +type PrivateLinkResourcesClientListOptions struct { + // placeholder for future optional parameters +} + +// ProjectCapabilityHostsClientBeginCreateOrUpdateOptions contains the optional parameters for the ProjectCapabilityHostsClient.BeginCreateOrUpdate +// method. +type ProjectCapabilityHostsClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ProjectCapabilityHostsClientBeginDeleteOptions contains the optional parameters for the ProjectCapabilityHostsClient.BeginDelete +// method. +type ProjectCapabilityHostsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ProjectCapabilityHostsClientGetOptions contains the optional parameters for the ProjectCapabilityHostsClient.Get method. +type ProjectCapabilityHostsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ProjectCapabilityHostsClientListOptions contains the optional parameters for the ProjectCapabilityHostsClient.NewListPager +// method. +type ProjectCapabilityHostsClientListOptions struct { + // placeholder for future optional parameters +} + +// ProjectConnectionsClientCreateOptions contains the optional parameters for the ProjectConnectionsClient.Create method. +type ProjectConnectionsClientCreateOptions struct { + // placeholder for future optional parameters +} + +// ProjectConnectionsClientDeleteOptions contains the optional parameters for the ProjectConnectionsClient.Delete method. +type ProjectConnectionsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// ProjectConnectionsClientGetOptions contains the optional parameters for the ProjectConnectionsClient.Get method. +type ProjectConnectionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ProjectConnectionsClientListOptions contains the optional parameters for the ProjectConnectionsClient.NewListPager method. +type ProjectConnectionsClientListOptions struct { + // Category of the connection. + Category *string + + // query parameter that indicates if get connection call should return both connections and datastores + IncludeAll *bool + + // Target of the connection. + Target *string +} + +// ProjectConnectionsClientUpdateOptions contains the optional parameters for the ProjectConnectionsClient.Update method. +type ProjectConnectionsClientUpdateOptions struct { + // placeholder for future optional parameters +} + +// ProjectsClientBeginCreateOptions contains the optional parameters for the ProjectsClient.BeginCreate method. +type ProjectsClientBeginCreateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ProjectsClientBeginDeleteOptions contains the optional parameters for the ProjectsClient.BeginDelete method. +type ProjectsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ProjectsClientBeginUpdateOptions contains the optional parameters for the ProjectsClient.BeginUpdate method. +type ProjectsClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ProjectsClientGetOptions contains the optional parameters for the ProjectsClient.Get method. +type ProjectsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ProjectsClientListOptions contains the optional parameters for the ProjectsClient.NewListPager method. +type ProjectsClientListOptions struct { + // placeholder for future optional parameters +} + +// QuotaTiersClientCreateOrUpdateOptions contains the optional parameters for the QuotaTiersClient.CreateOrUpdate method. +type QuotaTiersClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// QuotaTiersClientGetOptions contains the optional parameters for the QuotaTiersClient.Get method. +type QuotaTiersClientGetOptions struct { + // placeholder for future optional parameters +} + +// QuotaTiersClientListBySubscriptionOptions contains the optional parameters for the QuotaTiersClient.NewListBySubscriptionPager +// method. +type QuotaTiersClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// QuotaTiersClientUpdateOptions contains the optional parameters for the QuotaTiersClient.Update method. +type QuotaTiersClientUpdateOptions struct { + // placeholder for future optional parameters +} + +// RaiBlocklistItemsClientBatchAddOptions contains the optional parameters for the RaiBlocklistItemsClient.BatchAdd method. +type RaiBlocklistItemsClientBatchAddOptions struct { + // placeholder for future optional parameters +} + +// RaiBlocklistItemsClientBatchDeleteOptions contains the optional parameters for the RaiBlocklistItemsClient.BatchDelete +// method. +type RaiBlocklistItemsClientBatchDeleteOptions struct { + // placeholder for future optional parameters +} + +// RaiBlocklistItemsClientBeginDeleteOptions contains the optional parameters for the RaiBlocklistItemsClient.BeginDelete +// method. +type RaiBlocklistItemsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// RaiBlocklistItemsClientCreateOrUpdateOptions contains the optional parameters for the RaiBlocklistItemsClient.CreateOrUpdate +// method. +type RaiBlocklistItemsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// RaiBlocklistItemsClientGetOptions contains the optional parameters for the RaiBlocklistItemsClient.Get method. +type RaiBlocklistItemsClientGetOptions struct { + // placeholder for future optional parameters +} + +// RaiBlocklistItemsClientListOptions contains the optional parameters for the RaiBlocklistItemsClient.NewListPager method. +type RaiBlocklistItemsClientListOptions struct { + // placeholder for future optional parameters +} + +// RaiBlocklistsClientBeginDeleteOptions contains the optional parameters for the RaiBlocklistsClient.BeginDelete method. +type RaiBlocklistsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// RaiBlocklistsClientCreateOrUpdateOptions contains the optional parameters for the RaiBlocklistsClient.CreateOrUpdate method. +type RaiBlocklistsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// RaiBlocklistsClientGetOptions contains the optional parameters for the RaiBlocklistsClient.Get method. +type RaiBlocklistsClientGetOptions struct { + // placeholder for future optional parameters +} + +// RaiBlocklistsClientListOptions contains the optional parameters for the RaiBlocklistsClient.NewListPager method. +type RaiBlocklistsClientListOptions struct { + // placeholder for future optional parameters +} + +// RaiContentFiltersClientGetOptions contains the optional parameters for the RaiContentFiltersClient.Get method. +type RaiContentFiltersClientGetOptions struct { + // placeholder for future optional parameters +} + +// RaiContentFiltersClientListOptions contains the optional parameters for the RaiContentFiltersClient.NewListPager method. +type RaiContentFiltersClientListOptions struct { + // placeholder for future optional parameters +} + +// RaiExternalSafetyProviderClientBeginDeleteOptions contains the optional parameters for the RaiExternalSafetyProviderClient.BeginDelete +// method. +type RaiExternalSafetyProviderClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// RaiExternalSafetyProviderClientCreateOrUpdateOptions contains the optional parameters for the RaiExternalSafetyProviderClient.CreateOrUpdate +// method. +type RaiExternalSafetyProviderClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// RaiExternalSafetyProviderClientGetOptions contains the optional parameters for the RaiExternalSafetyProviderClient.Get +// method. +type RaiExternalSafetyProviderClientGetOptions struct { + // placeholder for future optional parameters +} + +// RaiExternalSafetyProvidersClientListOptions contains the optional parameters for the RaiExternalSafetyProvidersClient.NewListPager +// method. +type RaiExternalSafetyProvidersClientListOptions struct { + // placeholder for future optional parameters +} + +// RaiPoliciesClientBeginDeleteOptions contains the optional parameters for the RaiPoliciesClient.BeginDelete method. +type RaiPoliciesClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// RaiPoliciesClientCreateOrUpdateOptions contains the optional parameters for the RaiPoliciesClient.CreateOrUpdate method. +type RaiPoliciesClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// RaiPoliciesClientGetOptions contains the optional parameters for the RaiPoliciesClient.Get method. +type RaiPoliciesClientGetOptions struct { + // placeholder for future optional parameters +} + +// RaiPoliciesClientListOptions contains the optional parameters for the RaiPoliciesClient.NewListPager method. +type RaiPoliciesClientListOptions struct { + // placeholder for future optional parameters +} + +// RaiToolLabelsClientBeginDeleteOptions contains the optional parameters for the RaiToolLabelsClient.BeginDelete method. +type RaiToolLabelsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// RaiToolLabelsClientCreateOrUpdateOptions contains the optional parameters for the RaiToolLabelsClient.CreateOrUpdate method. +type RaiToolLabelsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// RaiToolLabelsClientGetOptions contains the optional parameters for the RaiToolLabelsClient.Get method. +type RaiToolLabelsClientGetOptions struct { + // placeholder for future optional parameters +} + +// RaiToolLabelsClientListOptions contains the optional parameters for the RaiToolLabelsClient.NewListPager method. +type RaiToolLabelsClientListOptions struct { + // placeholder for future optional parameters +} + +// RaiTopicsClientBeginDeleteOptions contains the optional parameters for the RaiTopicsClient.BeginDelete method. +type RaiTopicsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// RaiTopicsClientCreateOrUpdateOptions contains the optional parameters for the RaiTopicsClient.CreateOrUpdate method. +type RaiTopicsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// RaiTopicsClientGetOptions contains the optional parameters for the RaiTopicsClient.Get method. +type RaiTopicsClientGetOptions struct { + // placeholder for future optional parameters +} + +// RaiTopicsClientListOptions contains the optional parameters for the RaiTopicsClient.NewListPager method. +type RaiTopicsClientListOptions struct { + // placeholder for future optional parameters +} + +// ResourceSKUsClientListOptions contains the optional parameters for the ResourceSKUsClient.NewListPager method. +type ResourceSKUsClientListOptions struct { + // placeholder for future optional parameters +} + +// SubscriptionRaiPolicyClientBeginDeleteOptions contains the optional parameters for the SubscriptionRaiPolicyClient.BeginDelete +// method. +type SubscriptionRaiPolicyClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// SubscriptionRaiPolicyClientCreateOrUpdateOptions contains the optional parameters for the SubscriptionRaiPolicyClient.CreateOrUpdate +// method. +type SubscriptionRaiPolicyClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// SubscriptionRaiPolicyClientGetOptions contains the optional parameters for the SubscriptionRaiPolicyClient.Get method. +type SubscriptionRaiPolicyClientGetOptions struct { + // placeholder for future optional parameters +} + +// TestRaiExternalSafetyProviderClientCreateOrUpdateOptions contains the optional parameters for the TestRaiExternalSafetyProviderClient.CreateOrUpdate +// method. +type TestRaiExternalSafetyProviderClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// UsagesClientListOptions contains the optional parameters for the UsagesClient.NewListPager method. +type UsagesClientListOptions struct { + // An OData filter expression that describes a subset of usages to return. The supported parameter is name.value (name of + // the metric, can have an or of multiple names). + Filter *string +} diff --git a/test/local/armcognitiveservices/zz_outboundrule_client.go b/test/local/armcognitiveservices/zz_outboundrule_client.go new file mode 100644 index 000000000000..cd2ea089ebbf --- /dev/null +++ b/test/local/armcognitiveservices/zz_outboundrule_client.go @@ -0,0 +1,367 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// OutboundRuleClient contains the methods for the OutboundRule group. +// Don't use this type directly, use NewOutboundRuleClient() instead. +// +// Generated from API version 2026-05-01 +type OutboundRuleClient struct { + internal *arm.Client + subscriptionID string +} + +// NewOutboundRuleClient creates a new instance of OutboundRuleClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewOutboundRuleClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*OutboundRuleClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OutboundRuleClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - The PUT API for creating or updating a single outbound rule of the managed network associated with +// the cognitive services account. +// +// The PUT API for creating or updating a single outbound rule of the managed network associated with the cognitive services +// account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - managedNetworkName - Name of the managedNetwork associated with the cognitive services account. Only 'default' is supported. +// - ruleName - Name of the cognitive services account managed network outbound rule +// - options - OutboundRuleClientBeginCreateOrUpdateOptions contains the optional parameters for the OutboundRuleClient.BeginCreateOrUpdate +// method. +func (client *OutboundRuleClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, ruleName string, body OutboundRuleBasicResource, options *OutboundRuleClientBeginCreateOrUpdateOptions) (*runtime.Poller[OutboundRuleClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, accountName, managedNetworkName, ruleName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[OutboundRuleClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[OutboundRuleClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - The PUT API for creating or updating a single outbound rule of the managed network associated with the +// cognitive services account. +// +// The PUT API for creating or updating a single outbound rule of the managed network associated with the cognitive services +// account. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *OutboundRuleClient) createOrUpdate(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, ruleName string, body OutboundRuleBasicResource, options *OutboundRuleClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "OutboundRuleClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, managedNetworkName, ruleName, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *OutboundRuleClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, ruleName string, body OutboundRuleBasicResource, _ *OutboundRuleClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/managedNetworks/{managedNetworkName}/outboundRules/{ruleName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if managedNetworkName == "" { + return nil, errors.New("parameter managedNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{managedNetworkName}", url.PathEscape(managedNetworkName)) + if ruleName == "" { + return nil, errors.New("parameter ruleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ruleName}", url.PathEscape(ruleName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - The DELETE API for deleting a single outbound rule of the managed network associated with the cognitive services +// account. +// +// The DELETE API for deleting a single outbound rule of the managed network associated with the cognitive services account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - managedNetworkName - Name of the managedNetwork associated with the cognitive services account. Only 'default' is supported. +// - ruleName - Name of the cognitive services account managed network outbound rule +// - options - OutboundRuleClientBeginDeleteOptions contains the optional parameters for the OutboundRuleClient.BeginDelete +// method. +func (client *OutboundRuleClient) BeginDelete(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, ruleName string, options *OutboundRuleClientBeginDeleteOptions) (*runtime.Poller[OutboundRuleClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, accountName, managedNetworkName, ruleName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[OutboundRuleClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[OutboundRuleClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - The DELETE API for deleting a single outbound rule of the managed network associated with the cognitive services +// account. +// +// The DELETE API for deleting a single outbound rule of the managed network associated with the cognitive services account. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *OutboundRuleClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, ruleName string, options *OutboundRuleClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "OutboundRuleClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, managedNetworkName, ruleName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *OutboundRuleClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, ruleName string, _ *OutboundRuleClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/managedNetworks/{managedNetworkName}/outboundRules/{ruleName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if managedNetworkName == "" { + return nil, errors.New("parameter managedNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{managedNetworkName}", url.PathEscape(managedNetworkName)) + if ruleName == "" { + return nil, errors.New("parameter ruleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ruleName}", url.PathEscape(ruleName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - The GET API for retrieving a single outbound rule of the managed network associated with the cognitive services account. +// +// The GET API for retrieving a single outbound rule of the managed network associated with the cognitive services account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - managedNetworkName - Name of the managedNetwork associated with the cognitive services account. Only 'default' is supported. +// - ruleName - Name of the cognitive services account managed network outbound rule +// - options - OutboundRuleClientGetOptions contains the optional parameters for the OutboundRuleClient.Get method. +func (client *OutboundRuleClient) Get(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, ruleName string, options *OutboundRuleClientGetOptions) (OutboundRuleClientGetResponse, error) { + var err error + const operationName = "OutboundRuleClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, managedNetworkName, ruleName, options) + if err != nil { + return OutboundRuleClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OutboundRuleClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OutboundRuleClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *OutboundRuleClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, ruleName string, _ *OutboundRuleClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/managedNetworks/{managedNetworkName}/outboundRules/{ruleName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if managedNetworkName == "" { + return nil, errors.New("parameter managedNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{managedNetworkName}", url.PathEscape(managedNetworkName)) + if ruleName == "" { + return nil, errors.New("parameter ruleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{ruleName}", url.PathEscape(ruleName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *OutboundRuleClient) getHandleResponse(resp *http.Response) (OutboundRuleClientGetResponse, error) { + result := OutboundRuleClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OutboundRuleBasicResource); err != nil { + return OutboundRuleClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - The GET API for retrieving the list of outbound rules of the managed network associated with the cognitive +// services account. +// +// The GET API for retrieving the list of outbound rules of the managed network associated with the cognitive services account. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - managedNetworkName - Name of the managedNetwork associated with the cognitive services account. Only 'default' is supported. +// - options - OutboundRuleClientListOptions contains the optional parameters for the OutboundRuleClient.NewListPager method. +func (client *OutboundRuleClient) NewListPager(resourceGroupName string, accountName string, managedNetworkName string, options *OutboundRuleClientListOptions) *runtime.Pager[OutboundRuleClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[OutboundRuleClientListResponse]{ + More: func(page OutboundRuleClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OutboundRuleClientListResponse) (OutboundRuleClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OutboundRuleClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, managedNetworkName, options) + }, nil) + if err != nil { + return OutboundRuleClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *OutboundRuleClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, _ *OutboundRuleClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/managedNetworks/{managedNetworkName}/outboundRules" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if managedNetworkName == "" { + return nil, errors.New("parameter managedNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{managedNetworkName}", url.PathEscape(managedNetworkName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OutboundRuleClient) listHandleResponse(resp *http.Response) (OutboundRuleClientListResponse, error) { + result := OutboundRuleClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OutboundRuleListResult); err != nil { + return OutboundRuleClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_outboundrules_client.go b/test/local/armcognitiveservices/zz_outboundrules_client.go new file mode 100644 index 000000000000..86fd05bf5099 --- /dev/null +++ b/test/local/armcognitiveservices/zz_outboundrules_client.go @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// OutboundRulesClient contains the methods for the OutboundRules group. +// Don't use this type directly, use NewOutboundRulesClient() instead. +// +// Generated from API version 2026-05-01 +type OutboundRulesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewOutboundRulesClient creates a new instance of OutboundRulesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewOutboundRulesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*OutboundRulesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OutboundRulesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginPost - The POST API for updating the outbound rules of the managed network associated with the cognitive services +// account. +// +// The POST API for updating the outbound rules of the managed network associated with the cognitive services account. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - managedNetworkName - Name of the managedNetwork associated with the cognitive services account. Only 'default' is supported. +// - body - The Managed Network Settings object of the account. +// - options - OutboundRulesClientBeginPostOptions contains the optional parameters for the OutboundRulesClient.BeginPost method. +func (client *OutboundRulesClient) BeginPost(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, body ManagedNetworkSettingsBasicResource, options *OutboundRulesClientBeginPostOptions) (*runtime.Poller[*runtime.Pager[OutboundRulesClientPostResponse]], error) { + pager := runtime.NewPager(runtime.PagingHandler[OutboundRulesClientPostResponse]{ + More: func(page OutboundRulesClientPostResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OutboundRulesClientPostResponse) (OutboundRulesClientPostResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OutboundRulesClient.BeginPost") + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), *page.NextLink, func(ctx context.Context) (*policy.Request, error) { + return client.postCreateRequest(ctx, resourceGroupName, accountName, managedNetworkName, body, options) + }, nil) + if err != nil { + return OutboundRulesClientPostResponse{}, err + } + return client.postHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) + if options == nil || options.ResumeToken == "" { + resp, err := client.post(ctx, resourceGroupName, accountName, managedNetworkName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[*runtime.Pager[OutboundRulesClientPostResponse]]{ + Response: &pager, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[*runtime.Pager[OutboundRulesClientPostResponse]]{ + Response: &pager, + Tracer: client.internal.Tracer(), + }) + } +} + +// Post - The POST API for updating the outbound rules of the managed network associated with the cognitive services account. +// +// The POST API for updating the outbound rules of the managed network associated with the cognitive services account. +func (client *OutboundRulesClient) post(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, body ManagedNetworkSettingsBasicResource, options *OutboundRulesClientBeginPostOptions) (*http.Response, error) { + var err error + const operationName = "OutboundRulesClient.BeginPost" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.postCreateRequest(ctx, resourceGroupName, accountName, managedNetworkName, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// postCreateRequest creates the Post request. +func (client *OutboundRulesClient) postCreateRequest(ctx context.Context, resourceGroupName string, accountName string, managedNetworkName string, body ManagedNetworkSettingsBasicResource, _ *OutboundRulesClientBeginPostOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/managedNetworks/{managedNetworkName}/batchOutboundRules" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if managedNetworkName == "" { + return nil, errors.New("parameter managedNetworkName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{managedNetworkName}", url.PathEscape(managedNetworkName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// postHandleResponse handles the Post response. +func (client *OutboundRulesClient) postHandleResponse(resp *http.Response) (OutboundRulesClientPostResponse, error) { + result := OutboundRulesClientPostResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OutboundRuleListResult); err != nil { + return OutboundRulesClientPostResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_polymorphic_helpers.go b/test/local/armcognitiveservices/zz_polymorphic_helpers.go new file mode 100644 index 000000000000..a89401dfaa6f --- /dev/null +++ b/test/local/armcognitiveservices/zz_polymorphic_helpers.go @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import "encoding/json" + +func unmarshalAgentDeploymentPropertiesClassification(rawMsg json.RawMessage) (AgentDeploymentPropertiesClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b AgentDeploymentPropertiesClassification + switch m["deploymentType"] { + case string(AgentDeploymentTypeHosted): + b = &HostedAgentDeployment{} + case string(AgentDeploymentTypeManaged): + b = &ManagedAgentDeployment{} + default: + b = &AgentDeploymentProperties{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} + +func unmarshalApplicationAuthorizationPolicyClassification(rawMsg json.RawMessage) (ApplicationAuthorizationPolicyClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b ApplicationAuthorizationPolicyClassification + switch m["type"] { + case string(BuiltInAuthorizationSchemeChannels): + b = &ChannelsBuiltInAuthorizationPolicy{} + case string(BuiltInAuthorizationSchemeDefault): + b = &RoleBasedBuiltInAuthorizationPolicy{} + case string(BuiltInAuthorizationSchemeOrganizationScope): + b = &OrganizationSharedBuiltInAuthorizationPolicy{} + default: + b = &ApplicationAuthorizationPolicy{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} + +func unmarshalConnectionPropertiesV2Classification(rawMsg json.RawMessage) (ConnectionPropertiesV2Classification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b ConnectionPropertiesV2Classification + switch m["authType"] { + case string(ConnectionAuthTypeAAD): + b = &AADAuthTypeConnectionProperties{} + case string(ConnectionAuthTypeAPIKey): + b = &APIKeyAuthConnectionProperties{} + case string(ConnectionAuthTypeAccessKey): + b = &AccessKeyAuthTypeConnectionProperties{} + case string(ConnectionAuthTypeAccountKey): + b = &AccountKeyAuthTypeConnectionProperties{} + case string(ConnectionAuthTypeCustomKeys): + b = &CustomKeysConnectionProperties{} + case string(ConnectionAuthTypeManagedIdentity): + b = &ManagedIdentityAuthTypeConnectionProperties{} + case string(ConnectionAuthTypeNone): + b = &NoneAuthTypeConnectionProperties{} + case string(ConnectionAuthTypeOAuth2): + b = &OAuth2AuthTypeConnectionProperties{} + case string(ConnectionAuthTypePAT): + b = &PATAuthTypeConnectionProperties{} + case string(ConnectionAuthTypeSAS): + b = &SASAuthTypeConnectionProperties{} + case string(ConnectionAuthTypeServicePrincipal): + b = &ServicePrincipalAuthTypeConnectionProperties{} + case string(ConnectionAuthTypeUsernamePassword): + b = &UsernamePasswordAuthTypeConnectionProperties{} + default: + b = &ConnectionPropertiesV2{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} + +func unmarshalOutboundRuleClassification(rawMsg json.RawMessage) (OutboundRuleClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b OutboundRuleClassification + switch m["type"] { + case string(RuleTypeFQDN): + b = &FqdnOutboundRule{} + case string(RuleTypePrivateEndpoint): + b = &PrivateEndpointOutboundRule{} + case string(RuleTypeServiceTag): + b = &ServiceTagOutboundRule{} + default: + b = &OutboundRule{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} + +func unmarshalOutboundRuleClassificationMap(rawMsg json.RawMessage) (map[string]OutboundRuleClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var rawMessages map[string]json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fMap := make(map[string]OutboundRuleClassification, len(rawMessages)) + for key, rawMessage := range rawMessages { + f, err := unmarshalOutboundRuleClassification(rawMessage) + if err != nil { + return nil, err + } + fMap[key] = f + } + return fMap, nil +} diff --git a/test/local/armcognitiveservices/zz_privateendpointconnections_client.go b/test/local/armcognitiveservices/zz_privateendpointconnections_client.go new file mode 100644 index 000000000000..e51e9a4f58e0 --- /dev/null +++ b/test/local/armcognitiveservices/zz_privateendpointconnections_client.go @@ -0,0 +1,332 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// PrivateEndpointConnectionsClient contains the methods for the PrivateEndpointConnections group. +// Don't use this type directly, use NewPrivateEndpointConnectionsClient() instead. +// +// Generated from API version 2026-05-01 +type PrivateEndpointConnectionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewPrivateEndpointConnectionsClient creates a new instance of PrivateEndpointConnectionsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewPrivateEndpointConnectionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*PrivateEndpointConnectionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &PrivateEndpointConnectionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Update the state of specified private endpoint connection associated with the Cognitive Services +// account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - privateEndpointConnectionName - The name of the private endpoint connection associated with the Cognitive Services Account +// - properties - The private endpoint connection properties. +// - options - PrivateEndpointConnectionsClientBeginCreateOrUpdateOptions contains the optional parameters for the PrivateEndpointConnectionsClient.BeginCreateOrUpdate +// method. +func (client *PrivateEndpointConnectionsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string, properties PrivateEndpointConnection, options *PrivateEndpointConnectionsClientBeginCreateOrUpdateOptions) (*runtime.Poller[PrivateEndpointConnectionsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, accountName, privateEndpointConnectionName, properties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PrivateEndpointConnectionsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PrivateEndpointConnectionsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Update the state of specified private endpoint connection associated with the Cognitive Services account. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *PrivateEndpointConnectionsClient) createOrUpdate(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string, properties PrivateEndpointConnection, options *PrivateEndpointConnectionsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "PrivateEndpointConnectionsClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, privateEndpointConnectionName, properties, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *PrivateEndpointConnectionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string, properties PrivateEndpointConnection, _ *PrivateEndpointConnectionsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if privateEndpointConnectionName == "" { + return nil, errors.New("parameter privateEndpointConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes the specified private endpoint connection associated with the Cognitive Services account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - privateEndpointConnectionName - The name of the private endpoint connection associated with the Cognitive Services Account +// - options - PrivateEndpointConnectionsClientBeginDeleteOptions contains the optional parameters for the PrivateEndpointConnectionsClient.BeginDelete +// method. +func (client *PrivateEndpointConnectionsClient) BeginDelete(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsClientBeginDeleteOptions) (*runtime.Poller[PrivateEndpointConnectionsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, accountName, privateEndpointConnectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PrivateEndpointConnectionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PrivateEndpointConnectionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified private endpoint connection associated with the Cognitive Services account. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *PrivateEndpointConnectionsClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "PrivateEndpointConnectionsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, privateEndpointConnectionName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *PrivateEndpointConnectionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string, _ *PrivateEndpointConnectionsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if privateEndpointConnectionName == "" { + return nil, errors.New("parameter privateEndpointConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Gets the specified private endpoint connection associated with the Cognitive Services account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - privateEndpointConnectionName - The name of the private endpoint connection associated with the Cognitive Services Account +// - options - PrivateEndpointConnectionsClientGetOptions contains the optional parameters for the PrivateEndpointConnectionsClient.Get +// method. +func (client *PrivateEndpointConnectionsClient) Get(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsClientGetOptions) (PrivateEndpointConnectionsClientGetResponse, error) { + var err error + const operationName = "PrivateEndpointConnectionsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, privateEndpointConnectionName, options) + if err != nil { + return PrivateEndpointConnectionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PrivateEndpointConnectionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PrivateEndpointConnectionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *PrivateEndpointConnectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string, _ *PrivateEndpointConnectionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if privateEndpointConnectionName == "" { + return nil, errors.New("parameter privateEndpointConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *PrivateEndpointConnectionsClient) getHandleResponse(resp *http.Response) (PrivateEndpointConnectionsClientGetResponse, error) { + result := PrivateEndpointConnectionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnection); err != nil { + return PrivateEndpointConnectionsClientGetResponse{}, err + } + return result, nil +} + +// List - Gets the private endpoint connections associated with the Cognitive Services account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - options - PrivateEndpointConnectionsClientListOptions contains the optional parameters for the PrivateEndpointConnectionsClient.List +// method. +func (client *PrivateEndpointConnectionsClient) List(ctx context.Context, resourceGroupName string, accountName string, options *PrivateEndpointConnectionsClientListOptions) (PrivateEndpointConnectionsClientListResponse, error) { + var err error + const operationName = "PrivateEndpointConnectionsClient.List" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return PrivateEndpointConnectionsClientListResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PrivateEndpointConnectionsClientListResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PrivateEndpointConnectionsClientListResponse{}, err + } + resp, err := client.listHandleResponse(httpResp) + return resp, err +} + +// listCreateRequest creates the List request. +func (client *PrivateEndpointConnectionsClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, _ *PrivateEndpointConnectionsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/privateEndpointConnections" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *PrivateEndpointConnectionsClient) listHandleResponse(resp *http.Response) (PrivateEndpointConnectionsClientListResponse, error) { + result := PrivateEndpointConnectionsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnectionListResult); err != nil { + return PrivateEndpointConnectionsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_privatelinkresources_client.go b/test/local/armcognitiveservices/zz_privatelinkresources_client.go new file mode 100644 index 000000000000..8d4568499666 --- /dev/null +++ b/test/local/armcognitiveservices/zz_privatelinkresources_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// PrivateLinkResourcesClient contains the methods for the PrivateLinkResources group. +// Don't use this type directly, use NewPrivateLinkResourcesClient() instead. +// +// Generated from API version 2026-05-01 +type PrivateLinkResourcesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewPrivateLinkResourcesClient creates a new instance of PrivateLinkResourcesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewPrivateLinkResourcesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*PrivateLinkResourcesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &PrivateLinkResourcesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// List - Gets the private link resources that need to be created for a Cognitive Services account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - options - PrivateLinkResourcesClientListOptions contains the optional parameters for the PrivateLinkResourcesClient.List +// method. +func (client *PrivateLinkResourcesClient) List(ctx context.Context, resourceGroupName string, accountName string, options *PrivateLinkResourcesClientListOptions) (PrivateLinkResourcesClientListResponse, error) { + var err error + const operationName = "PrivateLinkResourcesClient.List" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return PrivateLinkResourcesClientListResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PrivateLinkResourcesClientListResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PrivateLinkResourcesClientListResponse{}, err + } + resp, err := client.listHandleResponse(httpResp) + return resp, err +} + +// listCreateRequest creates the List request. +func (client *PrivateLinkResourcesClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, _ *PrivateLinkResourcesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/privateLinkResources" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *PrivateLinkResourcesClient) listHandleResponse(resp *http.Response) (PrivateLinkResourcesClientListResponse, error) { + result := PrivateLinkResourcesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateLinkResourceListResult); err != nil { + return PrivateLinkResourcesClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_projectcapabilityhosts_client.go b/test/local/armcognitiveservices/zz_projectcapabilityhosts_client.go new file mode 100644 index 000000000000..1611443c8d65 --- /dev/null +++ b/test/local/armcognitiveservices/zz_projectcapabilityhosts_client.go @@ -0,0 +1,364 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ProjectCapabilityHostsClient contains the methods for the ProjectCapabilityHosts group. +// Don't use this type directly, use NewProjectCapabilityHostsClient() instead. +// +// Generated from API version 2026-05-01 +type ProjectCapabilityHostsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewProjectCapabilityHostsClient creates a new instance of ProjectCapabilityHostsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewProjectCapabilityHostsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ProjectCapabilityHostsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ProjectCapabilityHostsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create or update project capabilityHost. +// +// Create or update project capabilityHost. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - projectName - The name of Cognitive Services account's project. +// - capabilityHostName - The name of the capability host associated with the Cognitive Services Resource +// - capabilityHost - CapabilityHost definition. +// - options - ProjectCapabilityHostsClientBeginCreateOrUpdateOptions contains the optional parameters for the ProjectCapabilityHostsClient.BeginCreateOrUpdate +// method. +func (client *ProjectCapabilityHostsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, projectName string, capabilityHostName string, capabilityHost ProjectCapabilityHost, options *ProjectCapabilityHostsClientBeginCreateOrUpdateOptions) (*runtime.Poller[ProjectCapabilityHostsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, accountName, projectName, capabilityHostName, capabilityHost, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ProjectCapabilityHostsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaOriginalURI, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ProjectCapabilityHostsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create or update project capabilityHost. +// +// Create or update project capabilityHost. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ProjectCapabilityHostsClient) createOrUpdate(ctx context.Context, resourceGroupName string, accountName string, projectName string, capabilityHostName string, capabilityHost ProjectCapabilityHost, options *ProjectCapabilityHostsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ProjectCapabilityHostsClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, projectName, capabilityHostName, capabilityHost, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *ProjectCapabilityHostsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, projectName string, capabilityHostName string, capabilityHost ProjectCapabilityHost, _ *ProjectCapabilityHostsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/projects/{projectName}/capabilityHosts/{capabilityHostName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if projectName == "" { + return nil, errors.New("parameter projectName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{projectName}", url.PathEscape(projectName)) + if capabilityHostName == "" { + return nil, errors.New("parameter capabilityHostName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{capabilityHostName}", url.PathEscape(capabilityHostName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, capabilityHost); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete project capabilityHost. +// +// Delete project capabilityHost. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - projectName - The name of Cognitive Services account's project. +// - capabilityHostName - The name of the capability host associated with the Cognitive Services Resource +// - options - ProjectCapabilityHostsClientBeginDeleteOptions contains the optional parameters for the ProjectCapabilityHostsClient.BeginDelete +// method. +func (client *ProjectCapabilityHostsClient) BeginDelete(ctx context.Context, resourceGroupName string, accountName string, projectName string, capabilityHostName string, options *ProjectCapabilityHostsClientBeginDeleteOptions) (*runtime.Poller[ProjectCapabilityHostsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, accountName, projectName, capabilityHostName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ProjectCapabilityHostsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ProjectCapabilityHostsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete project capabilityHost. +// +// Delete project capabilityHost. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ProjectCapabilityHostsClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, projectName string, capabilityHostName string, options *ProjectCapabilityHostsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ProjectCapabilityHostsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, projectName, capabilityHostName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ProjectCapabilityHostsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, projectName string, capabilityHostName string, _ *ProjectCapabilityHostsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/projects/{projectName}/capabilityHosts/{capabilityHostName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if projectName == "" { + return nil, errors.New("parameter projectName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{projectName}", url.PathEscape(projectName)) + if capabilityHostName == "" { + return nil, errors.New("parameter capabilityHostName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{capabilityHostName}", url.PathEscape(capabilityHostName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get project capabilityHost. +// +// Get project capabilityHost. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - projectName - The name of Cognitive Services account's project. +// - capabilityHostName - The name of the capability host associated with the Cognitive Services Resource +// - options - ProjectCapabilityHostsClientGetOptions contains the optional parameters for the ProjectCapabilityHostsClient.Get +// method. +func (client *ProjectCapabilityHostsClient) Get(ctx context.Context, resourceGroupName string, accountName string, projectName string, capabilityHostName string, options *ProjectCapabilityHostsClientGetOptions) (ProjectCapabilityHostsClientGetResponse, error) { + var err error + const operationName = "ProjectCapabilityHostsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, projectName, capabilityHostName, options) + if err != nil { + return ProjectCapabilityHostsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ProjectCapabilityHostsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ProjectCapabilityHostsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ProjectCapabilityHostsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, projectName string, capabilityHostName string, _ *ProjectCapabilityHostsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/projects/{projectName}/capabilityHosts/{capabilityHostName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if projectName == "" { + return nil, errors.New("parameter projectName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{projectName}", url.PathEscape(projectName)) + if capabilityHostName == "" { + return nil, errors.New("parameter capabilityHostName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{capabilityHostName}", url.PathEscape(capabilityHostName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ProjectCapabilityHostsClient) getHandleResponse(resp *http.Response) (ProjectCapabilityHostsClientGetResponse, error) { + result := ProjectCapabilityHostsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ProjectCapabilityHost); err != nil { + return ProjectCapabilityHostsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List capabilityHost. +// +// List capabilityHost. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - projectName - The name of Cognitive Services account's project. +// - options - ProjectCapabilityHostsClientListOptions contains the optional parameters for the ProjectCapabilityHostsClient.NewListPager +// method. +func (client *ProjectCapabilityHostsClient) NewListPager(resourceGroupName string, accountName string, projectName string, options *ProjectCapabilityHostsClientListOptions) *runtime.Pager[ProjectCapabilityHostsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ProjectCapabilityHostsClientListResponse]{ + More: func(page ProjectCapabilityHostsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ProjectCapabilityHostsClientListResponse) (ProjectCapabilityHostsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ProjectCapabilityHostsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, projectName, options) + }, nil) + if err != nil { + return ProjectCapabilityHostsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ProjectCapabilityHostsClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, projectName string, _ *ProjectCapabilityHostsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/projects/{projectName}/capabilityHosts" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if projectName == "" { + return nil, errors.New("parameter projectName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{projectName}", url.PathEscape(projectName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ProjectCapabilityHostsClient) listHandleResponse(resp *http.Response) (ProjectCapabilityHostsClientListResponse, error) { + result := ProjectCapabilityHostsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ProjectCapabilityHostResourceArmPaginatedResult); err != nil { + return ProjectCapabilityHostsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_projectconnections_client.go b/test/local/armcognitiveservices/zz_projectconnections_client.go new file mode 100644 index 000000000000..63034c71ca63 --- /dev/null +++ b/test/local/armcognitiveservices/zz_projectconnections_client.go @@ -0,0 +1,420 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" +) + +// ProjectConnectionsClient contains the methods for the ProjectConnections group. +// Don't use this type directly, use NewProjectConnectionsClient() instead. +// +// Generated from API version 2026-05-01 +type ProjectConnectionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewProjectConnectionsClient creates a new instance of ProjectConnectionsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewProjectConnectionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ProjectConnectionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ProjectConnectionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Create - Create or update Cognitive Services project connection under the specified project. +// +// Create or update Cognitive Services project connection under the specified project. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - projectName - The name of Cognitive Services account's project. +// - connectionName - Friendly name of the connection +// - connection - The object for creating or updating a new account connection +// - options - ProjectConnectionsClientCreateOptions contains the optional parameters for the ProjectConnectionsClient.Create +// method. +func (client *ProjectConnectionsClient) Create(ctx context.Context, resourceGroupName string, accountName string, projectName string, connectionName string, connection ConnectionPropertiesV2BasicResource, options *ProjectConnectionsClientCreateOptions) (ProjectConnectionsClientCreateResponse, error) { + var err error + const operationName = "ProjectConnectionsClient.Create" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, accountName, projectName, connectionName, connection, options) + if err != nil { + return ProjectConnectionsClientCreateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ProjectConnectionsClientCreateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ProjectConnectionsClientCreateResponse{}, err + } + resp, err := client.createHandleResponse(httpResp) + return resp, err +} + +// createCreateRequest creates the Create request. +func (client *ProjectConnectionsClient) createCreateRequest(ctx context.Context, resourceGroupName string, accountName string, projectName string, connectionName string, connection ConnectionPropertiesV2BasicResource, _ *ProjectConnectionsClientCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/projects/{projectName}/connections/{connectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if projectName == "" { + return nil, errors.New("parameter projectName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{projectName}", url.PathEscape(projectName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, connection); err != nil { + return nil, err + } + return req, nil +} + +// createHandleResponse handles the Create response. +func (client *ProjectConnectionsClient) createHandleResponse(resp *http.Response) (ProjectConnectionsClientCreateResponse, error) { + result := ProjectConnectionsClientCreateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ConnectionPropertiesV2BasicResource); err != nil { + return ProjectConnectionsClientCreateResponse{}, err + } + return result, nil +} + +// Delete - Delete Cognitive Services project connection by name. +// +// Delete Cognitive Services project connection by name. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - projectName - The name of Cognitive Services account's project. +// - connectionName - Friendly name of the connection +// - options - ProjectConnectionsClientDeleteOptions contains the optional parameters for the ProjectConnectionsClient.Delete +// method. +func (client *ProjectConnectionsClient) Delete(ctx context.Context, resourceGroupName string, accountName string, projectName string, connectionName string, options *ProjectConnectionsClientDeleteOptions) (ProjectConnectionsClientDeleteResponse, error) { + var err error + const operationName = "ProjectConnectionsClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, projectName, connectionName, options) + if err != nil { + return ProjectConnectionsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ProjectConnectionsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ProjectConnectionsClientDeleteResponse{}, err + } + return ProjectConnectionsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ProjectConnectionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, projectName string, connectionName string, _ *ProjectConnectionsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/projects/{projectName}/connections/{connectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if projectName == "" { + return nil, errors.New("parameter projectName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{projectName}", url.PathEscape(projectName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Lists Cognitive Services project connection by name. +// +// Lists Cognitive Services project connection by name. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - projectName - The name of Cognitive Services account's project. +// - connectionName - Friendly name of the connection +// - options - ProjectConnectionsClientGetOptions contains the optional parameters for the ProjectConnectionsClient.Get method. +func (client *ProjectConnectionsClient) Get(ctx context.Context, resourceGroupName string, accountName string, projectName string, connectionName string, options *ProjectConnectionsClientGetOptions) (ProjectConnectionsClientGetResponse, error) { + var err error + const operationName = "ProjectConnectionsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, projectName, connectionName, options) + if err != nil { + return ProjectConnectionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ProjectConnectionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ProjectConnectionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ProjectConnectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, projectName string, connectionName string, _ *ProjectConnectionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/projects/{projectName}/connections/{connectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if projectName == "" { + return nil, errors.New("parameter projectName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{projectName}", url.PathEscape(projectName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ProjectConnectionsClient) getHandleResponse(resp *http.Response) (ProjectConnectionsClientGetResponse, error) { + result := ProjectConnectionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ConnectionPropertiesV2BasicResource); err != nil { + return ProjectConnectionsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all the available Cognitive Services project connections under the specified project. +// +// Lists all the available Cognitive Services project connections under the specified project. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - projectName - The name of Cognitive Services account's project. +// - options - ProjectConnectionsClientListOptions contains the optional parameters for the ProjectConnectionsClient.NewListPager +// method. +func (client *ProjectConnectionsClient) NewListPager(resourceGroupName string, accountName string, projectName string, options *ProjectConnectionsClientListOptions) *runtime.Pager[ProjectConnectionsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ProjectConnectionsClientListResponse]{ + More: func(page ProjectConnectionsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ProjectConnectionsClientListResponse) (ProjectConnectionsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ProjectConnectionsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, projectName, options) + }, nil) + if err != nil { + return ProjectConnectionsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ProjectConnectionsClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, projectName string, options *ProjectConnectionsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/projects/{projectName}/connections" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if projectName == "" { + return nil, errors.New("parameter projectName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{projectName}", url.PathEscape(projectName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + if options != nil && options.Category != nil { + reqQP.Set("category", *options.Category) + } + if options != nil && options.IncludeAll != nil { + reqQP.Set("includeAll", strconv.FormatBool(*options.IncludeAll)) + } + if options != nil && options.Target != nil { + reqQP.Set("target", *options.Target) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ProjectConnectionsClient) listHandleResponse(resp *http.Response) (ProjectConnectionsClientListResponse, error) { + result := ProjectConnectionsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ConnectionPropertiesV2BasicResourceArmPaginatedResult); err != nil { + return ProjectConnectionsClientListResponse{}, err + } + return result, nil +} + +// Update - Update Cognitive Services project connection under the specified project. +// +// Update Cognitive Services project connection under the specified project. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - projectName - The name of Cognitive Services account's project. +// - connectionName - Friendly name of the connection +// - connection - Parameters for account connection update. +// - options - ProjectConnectionsClientUpdateOptions contains the optional parameters for the ProjectConnectionsClient.Update +// method. +func (client *ProjectConnectionsClient) Update(ctx context.Context, resourceGroupName string, accountName string, projectName string, connectionName string, connection ConnectionUpdateContent, options *ProjectConnectionsClientUpdateOptions) (ProjectConnectionsClientUpdateResponse, error) { + var err error + const operationName = "ProjectConnectionsClient.Update" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, accountName, projectName, connectionName, connection, options) + if err != nil { + return ProjectConnectionsClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ProjectConnectionsClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ProjectConnectionsClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *ProjectConnectionsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, projectName string, connectionName string, connection ConnectionUpdateContent, _ *ProjectConnectionsClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/projects/{projectName}/connections/{connectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if projectName == "" { + return nil, errors.New("parameter projectName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{projectName}", url.PathEscape(projectName)) + if connectionName == "" { + return nil, errors.New("parameter connectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{connectionName}", url.PathEscape(connectionName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, connection); err != nil { + return nil, err + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *ProjectConnectionsClient) updateHandleResponse(resp *http.Response) (ProjectConnectionsClientUpdateResponse, error) { + result := ProjectConnectionsClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ConnectionPropertiesV2BasicResource); err != nil { + return ProjectConnectionsClientUpdateResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_projects_client.go b/test/local/armcognitiveservices/zz_projects_client.go new file mode 100644 index 000000000000..28c66c44f3b5 --- /dev/null +++ b/test/local/armcognitiveservices/zz_projects_client.go @@ -0,0 +1,410 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ProjectsClient contains the methods for the Projects group. +// Don't use this type directly, use NewProjectsClient() instead. +// +// Generated from API version 2026-05-01 +type ProjectsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewProjectsClient creates a new instance of ProjectsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewProjectsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ProjectsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ProjectsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreate - Create Cognitive Services Account's Project. Project is a sub-resource of an account which give AI developer +// it's individual container to work on. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - projectName - The name of Cognitive Services account's project. +// - project - The parameters to provide for the created project. +// - options - ProjectsClientBeginCreateOptions contains the optional parameters for the ProjectsClient.BeginCreate method. +func (client *ProjectsClient) BeginCreate(ctx context.Context, resourceGroupName string, accountName string, projectName string, project Project, options *ProjectsClientBeginCreateOptions) (*runtime.Poller[ProjectsClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, resourceGroupName, accountName, projectName, project, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ProjectsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ProjectsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Create Cognitive Services Account's Project. Project is a sub-resource of an account which give AI developer it's +// individual container to work on. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ProjectsClient) create(ctx context.Context, resourceGroupName string, accountName string, projectName string, project Project, options *ProjectsClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "ProjectsClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, accountName, projectName, project, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *ProjectsClient) createCreateRequest(ctx context.Context, resourceGroupName string, accountName string, projectName string, project Project, _ *ProjectsClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/projects/{projectName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if projectName == "" { + return nil, errors.New("parameter projectName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{projectName}", url.PathEscape(projectName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, project); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a Cognitive Services project from the resource group. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - projectName - The name of Cognitive Services account's project. +// - options - ProjectsClientBeginDeleteOptions contains the optional parameters for the ProjectsClient.BeginDelete method. +func (client *ProjectsClient) BeginDelete(ctx context.Context, resourceGroupName string, accountName string, projectName string, options *ProjectsClientBeginDeleteOptions) (*runtime.Poller[ProjectsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, accountName, projectName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ProjectsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ProjectsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a Cognitive Services project from the resource group. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ProjectsClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, projectName string, options *ProjectsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ProjectsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, projectName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ProjectsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, projectName string, _ *ProjectsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/projects/{projectName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if projectName == "" { + return nil, errors.New("parameter projectName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{projectName}", url.PathEscape(projectName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Returns a Cognitive Services project specified by the parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - projectName - The name of Cognitive Services account's project. +// - options - ProjectsClientGetOptions contains the optional parameters for the ProjectsClient.Get method. +func (client *ProjectsClient) Get(ctx context.Context, resourceGroupName string, accountName string, projectName string, options *ProjectsClientGetOptions) (ProjectsClientGetResponse, error) { + var err error + const operationName = "ProjectsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, projectName, options) + if err != nil { + return ProjectsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ProjectsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ProjectsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ProjectsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, projectName string, _ *ProjectsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/projects/{projectName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if projectName == "" { + return nil, errors.New("parameter projectName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{projectName}", url.PathEscape(projectName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ProjectsClient) getHandleResponse(resp *http.Response) (ProjectsClientGetResponse, error) { + result := ProjectsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Project); err != nil { + return ProjectsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Returns all the projects in a Cognitive Services account. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - options - ProjectsClientListOptions contains the optional parameters for the ProjectsClient.NewListPager method. +func (client *ProjectsClient) NewListPager(resourceGroupName string, accountName string, options *ProjectsClientListOptions) *runtime.Pager[ProjectsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ProjectsClientListResponse]{ + More: func(page ProjectsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ProjectsClientListResponse) (ProjectsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ProjectsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, options) + }, nil) + if err != nil { + return ProjectsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ProjectsClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, _ *ProjectsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/projects" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ProjectsClient) listHandleResponse(resp *http.Response) (ProjectsClientListResponse, error) { + result := ProjectsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ProjectListResult); err != nil { + return ProjectsClientListResponse{}, err + } + return result, nil +} + +// BeginUpdate - Updates a Cognitive Services Project +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - projectName - The name of Cognitive Services account's project. +// - project - The parameters to provide for the created project. +// - options - ProjectsClientBeginUpdateOptions contains the optional parameters for the ProjectsClient.BeginUpdate method. +func (client *ProjectsClient) BeginUpdate(ctx context.Context, resourceGroupName string, accountName string, projectName string, project Project, options *ProjectsClientBeginUpdateOptions) (*runtime.Poller[ProjectsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, accountName, projectName, project, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ProjectsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ProjectsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Updates a Cognitive Services Project +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ProjectsClient) update(ctx context.Context, resourceGroupName string, accountName string, projectName string, project Project, options *ProjectsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ProjectsClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, accountName, projectName, project, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *ProjectsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, projectName string, project Project, _ *ProjectsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/projects/{projectName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if projectName == "" { + return nil, errors.New("parameter projectName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{projectName}", url.PathEscape(projectName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, project); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armcognitiveservices/zz_quotatiers_client.go b/test/local/armcognitiveservices/zz_quotatiers_client.go new file mode 100644 index 000000000000..6f7529eaaac4 --- /dev/null +++ b/test/local/armcognitiveservices/zz_quotatiers_client.go @@ -0,0 +1,286 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// QuotaTiersClient contains the methods for the QuotaTiers group. +// Don't use this type directly, use NewQuotaTiersClient() instead. +// +// Generated from API version 2026-05-01 +type QuotaTiersClient struct { + internal *arm.Client + subscriptionID string +} + +// NewQuotaTiersClient creates a new instance of QuotaTiersClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewQuotaTiersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*QuotaTiersClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &QuotaTiersClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Updates the Quota Tier resource for a subscription. +// +// Update the Quota Tier information for the given subscription. QuotaTiers is a subscription wide resource type. It holds +// current tier information. +// If the operation fails it returns an *azcore.ResponseError type. +// - defaultParam - Default parameter. Leave the value as default. +// - tier - The parameters to provide for the quota tier resource. +// - options - QuotaTiersClientCreateOrUpdateOptions contains the optional parameters for the QuotaTiersClient.CreateOrUpdate +// method. +func (client *QuotaTiersClient) CreateOrUpdate(ctx context.Context, defaultParam string, tier QuotaTier, options *QuotaTiersClientCreateOrUpdateOptions) (QuotaTiersClientCreateOrUpdateResponse, error) { + var err error + const operationName = "QuotaTiersClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, defaultParam, tier, options) + if err != nil { + return QuotaTiersClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return QuotaTiersClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return QuotaTiersClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *QuotaTiersClient) createOrUpdateCreateRequest(ctx context.Context, defaultParam string, tier QuotaTier, _ *QuotaTiersClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/quotaTiers/{default}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if defaultParam == "" { + return nil, errors.New("parameter defaultParam cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{default}", url.PathEscape(defaultParam)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, tier); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *QuotaTiersClient) createOrUpdateHandleResponse(resp *http.Response) (QuotaTiersClientCreateOrUpdateResponse, error) { + result := QuotaTiersClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.QuotaTier); err != nil { + return QuotaTiersClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Get - Gets the Quota Tier for a subscription +// +// Gets the Quota Tier information for the given subscription. QuotaTiers is a subscription wide resource type. It holds current +// tier information. +// If the operation fails it returns an *azcore.ResponseError type. +// - defaultParam - Default parameter. Leave the value as default. +// - options - QuotaTiersClientGetOptions contains the optional parameters for the QuotaTiersClient.Get method. +func (client *QuotaTiersClient) Get(ctx context.Context, defaultParam string, options *QuotaTiersClientGetOptions) (QuotaTiersClientGetResponse, error) { + var err error + const operationName = "QuotaTiersClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, defaultParam, options) + if err != nil { + return QuotaTiersClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return QuotaTiersClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return QuotaTiersClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *QuotaTiersClient) getCreateRequest(ctx context.Context, defaultParam string, _ *QuotaTiersClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/quotaTiers/{default}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if defaultParam == "" { + return nil, errors.New("parameter defaultParam cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{default}", url.PathEscape(defaultParam)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *QuotaTiersClient) getHandleResponse(resp *http.Response) (QuotaTiersClientGetResponse, error) { + result := QuotaTiersClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.QuotaTier); err != nil { + return QuotaTiersClientGetResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - Returns all the resources of a particular type belonging to a subscription. +// - options - QuotaTiersClientListBySubscriptionOptions contains the optional parameters for the QuotaTiersClient.NewListBySubscriptionPager +// method. +func (client *QuotaTiersClient) NewListBySubscriptionPager(options *QuotaTiersClientListBySubscriptionOptions) *runtime.Pager[QuotaTiersClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[QuotaTiersClientListBySubscriptionResponse]{ + More: func(page QuotaTiersClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *QuotaTiersClientListBySubscriptionResponse) (QuotaTiersClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "QuotaTiersClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return QuotaTiersClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *QuotaTiersClient) listBySubscriptionCreateRequest(ctx context.Context, _ *QuotaTiersClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/quotaTiers" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *QuotaTiersClient) listBySubscriptionHandleResponse(resp *http.Response) (QuotaTiersClientListBySubscriptionResponse, error) { + result := QuotaTiersClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.QuotaTierListResult); err != nil { + return QuotaTiersClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// Update - Updates the Quota Tier resource for a subscription. The only properties that can be updated are "tierUpgradePolicy" +// +// Update the Quota Tier information for the given subscription. QuotaTiers is a subscription wide resource type. It holds +// current tier information. +// If the operation fails it returns an *azcore.ResponseError type. +// - defaultParam - Default parameter. Leave the value as default. +// - tier - The parameters to provide for the quota tier resource. +// - options - QuotaTiersClientUpdateOptions contains the optional parameters for the QuotaTiersClient.Update method. +func (client *QuotaTiersClient) Update(ctx context.Context, defaultParam string, tier QuotaTier, options *QuotaTiersClientUpdateOptions) (QuotaTiersClientUpdateResponse, error) { + var err error + const operationName = "QuotaTiersClient.Update" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, defaultParam, tier, options) + if err != nil { + return QuotaTiersClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return QuotaTiersClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return QuotaTiersClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *QuotaTiersClient) updateCreateRequest(ctx context.Context, defaultParam string, tier QuotaTier, _ *QuotaTiersClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/quotaTiers/{default}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if defaultParam == "" { + return nil, errors.New("parameter defaultParam cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{default}", url.PathEscape(defaultParam)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, tier); err != nil { + return nil, err + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *QuotaTiersClient) updateHandleResponse(resp *http.Response) (QuotaTiersClientUpdateResponse, error) { + result := QuotaTiersClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.QuotaTier); err != nil { + return QuotaTiersClientUpdateResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_raiblocklistitems_client.go b/test/local/armcognitiveservices/zz_raiblocklistitems_client.go new file mode 100644 index 000000000000..e004aaab67c9 --- /dev/null +++ b/test/local/armcognitiveservices/zz_raiblocklistitems_client.go @@ -0,0 +1,476 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// RaiBlocklistItemsClient contains the methods for the RaiBlocklistItems group. +// Don't use this type directly, use NewRaiBlocklistItemsClient() instead. +// +// Generated from API version 2026-05-01 +type RaiBlocklistItemsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewRaiBlocklistItemsClient creates a new instance of RaiBlocklistItemsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewRaiBlocklistItemsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*RaiBlocklistItemsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &RaiBlocklistItemsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BatchAdd - Batch operation to add blocklist items. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - raiBlocklistName - The name of the RaiBlocklist associated with the Cognitive Services Account +// - raiBlocklistItems - Properties describing the custom blocklist items. +// - options - RaiBlocklistItemsClientBatchAddOptions contains the optional parameters for the RaiBlocklistItemsClient.BatchAdd +// method. +func (client *RaiBlocklistItemsClient) BatchAdd(ctx context.Context, resourceGroupName string, accountName string, raiBlocklistName string, raiBlocklistItems []*RaiBlocklistItemBulkRequest, options *RaiBlocklistItemsClientBatchAddOptions) (RaiBlocklistItemsClientBatchAddResponse, error) { + var err error + const operationName = "RaiBlocklistItemsClient.BatchAdd" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.batchAddCreateRequest(ctx, resourceGroupName, accountName, raiBlocklistName, raiBlocklistItems, options) + if err != nil { + return RaiBlocklistItemsClientBatchAddResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RaiBlocklistItemsClientBatchAddResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RaiBlocklistItemsClientBatchAddResponse{}, err + } + resp, err := client.batchAddHandleResponse(httpResp) + return resp, err +} + +// batchAddCreateRequest creates the BatchAdd request. +func (client *RaiBlocklistItemsClient) batchAddCreateRequest(ctx context.Context, resourceGroupName string, accountName string, raiBlocklistName string, raiBlocklistItems []*RaiBlocklistItemBulkRequest, _ *RaiBlocklistItemsClientBatchAddOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiBlocklists/{raiBlocklistName}/addRaiBlocklistItems" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if raiBlocklistName == "" { + return nil, errors.New("parameter raiBlocklistName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{raiBlocklistName}", url.PathEscape(raiBlocklistName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, raiBlocklistItems); err != nil { + return nil, err + } + return req, nil +} + +// batchAddHandleResponse handles the BatchAdd response. +func (client *RaiBlocklistItemsClient) batchAddHandleResponse(resp *http.Response) (RaiBlocklistItemsClientBatchAddResponse, error) { + result := RaiBlocklistItemsClientBatchAddResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RaiBlocklist); err != nil { + return RaiBlocklistItemsClientBatchAddResponse{}, err + } + return result, nil +} + +// BatchDelete - Batch operation to delete blocklist items. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - raiBlocklistName - The name of the RaiBlocklist associated with the Cognitive Services Account +// - raiBlocklistItemsNames - List of RAI Blocklist Items Names. +// - options - RaiBlocklistItemsClientBatchDeleteOptions contains the optional parameters for the RaiBlocklistItemsClient.BatchDelete +// method. +func (client *RaiBlocklistItemsClient) BatchDelete(ctx context.Context, resourceGroupName string, accountName string, raiBlocklistName string, raiBlocklistItemsNames []*string, options *RaiBlocklistItemsClientBatchDeleteOptions) (RaiBlocklistItemsClientBatchDeleteResponse, error) { + var err error + const operationName = "RaiBlocklistItemsClient.BatchDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.batchDeleteCreateRequest(ctx, resourceGroupName, accountName, raiBlocklistName, raiBlocklistItemsNames, options) + if err != nil { + return RaiBlocklistItemsClientBatchDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RaiBlocklistItemsClientBatchDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return RaiBlocklistItemsClientBatchDeleteResponse{}, err + } + return RaiBlocklistItemsClientBatchDeleteResponse{}, nil +} + +// batchDeleteCreateRequest creates the BatchDelete request. +func (client *RaiBlocklistItemsClient) batchDeleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, raiBlocklistName string, raiBlocklistItemsNames []*string, _ *RaiBlocklistItemsClientBatchDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiBlocklists/{raiBlocklistName}/deleteRaiBlocklistItems" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if raiBlocklistName == "" { + return nil, errors.New("parameter raiBlocklistName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{raiBlocklistName}", url.PathEscape(raiBlocklistName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, raiBlocklistItemsNames); err != nil { + return nil, err + } + return req, nil +} + +// CreateOrUpdate - Update the state of specified blocklist item associated with the Azure OpenAI account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - raiBlocklistName - The name of the RaiBlocklist associated with the Cognitive Services Account +// - raiBlocklistItemName - The name of the RaiBlocklist Item associated with the custom blocklist +// - raiBlocklistItem - Properties describing the custom blocklist. +// - options - RaiBlocklistItemsClientCreateOrUpdateOptions contains the optional parameters for the RaiBlocklistItemsClient.CreateOrUpdate +// method. +func (client *RaiBlocklistItemsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, raiBlocklistName string, raiBlocklistItemName string, raiBlocklistItem RaiBlocklistItem, options *RaiBlocklistItemsClientCreateOrUpdateOptions) (RaiBlocklistItemsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "RaiBlocklistItemsClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, raiBlocklistName, raiBlocklistItemName, raiBlocklistItem, options) + if err != nil { + return RaiBlocklistItemsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RaiBlocklistItemsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return RaiBlocklistItemsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *RaiBlocklistItemsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, raiBlocklistName string, raiBlocklistItemName string, raiBlocklistItem RaiBlocklistItem, _ *RaiBlocklistItemsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiBlocklists/{raiBlocklistName}/raiBlocklistItems/{raiBlocklistItemName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if raiBlocklistName == "" { + return nil, errors.New("parameter raiBlocklistName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{raiBlocklistName}", url.PathEscape(raiBlocklistName)) + if raiBlocklistItemName == "" { + return nil, errors.New("parameter raiBlocklistItemName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{raiBlocklistItemName}", url.PathEscape(raiBlocklistItemName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, raiBlocklistItem); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *RaiBlocklistItemsClient) createOrUpdateHandleResponse(resp *http.Response) (RaiBlocklistItemsClientCreateOrUpdateResponse, error) { + result := RaiBlocklistItemsClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RaiBlocklistItem); err != nil { + return RaiBlocklistItemsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// BeginDelete - Deletes the specified blocklist Item associated with the custom blocklist. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - raiBlocklistName - The name of the RaiBlocklist associated with the Cognitive Services Account +// - raiBlocklistItemName - The name of the RaiBlocklist Item associated with the custom blocklist +// - options - RaiBlocklistItemsClientBeginDeleteOptions contains the optional parameters for the RaiBlocklistItemsClient.BeginDelete +// method. +func (client *RaiBlocklistItemsClient) BeginDelete(ctx context.Context, resourceGroupName string, accountName string, raiBlocklistName string, raiBlocklistItemName string, options *RaiBlocklistItemsClientBeginDeleteOptions) (*runtime.Poller[RaiBlocklistItemsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, accountName, raiBlocklistName, raiBlocklistItemName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RaiBlocklistItemsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RaiBlocklistItemsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified blocklist Item associated with the custom blocklist. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *RaiBlocklistItemsClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, raiBlocklistName string, raiBlocklistItemName string, options *RaiBlocklistItemsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "RaiBlocklistItemsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, raiBlocklistName, raiBlocklistItemName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *RaiBlocklistItemsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, raiBlocklistName string, raiBlocklistItemName string, _ *RaiBlocklistItemsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiBlocklists/{raiBlocklistName}/raiBlocklistItems/{raiBlocklistItemName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if raiBlocklistName == "" { + return nil, errors.New("parameter raiBlocklistName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{raiBlocklistName}", url.PathEscape(raiBlocklistName)) + if raiBlocklistItemName == "" { + return nil, errors.New("parameter raiBlocklistItemName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{raiBlocklistItemName}", url.PathEscape(raiBlocklistItemName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Gets the specified custom blocklist Item associated with the custom blocklist. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - raiBlocklistName - The name of the RaiBlocklist associated with the Cognitive Services Account +// - raiBlocklistItemName - The name of the RaiBlocklist Item associated with the custom blocklist +// - options - RaiBlocklistItemsClientGetOptions contains the optional parameters for the RaiBlocklistItemsClient.Get method. +func (client *RaiBlocklistItemsClient) Get(ctx context.Context, resourceGroupName string, accountName string, raiBlocklistName string, raiBlocklistItemName string, options *RaiBlocklistItemsClientGetOptions) (RaiBlocklistItemsClientGetResponse, error) { + var err error + const operationName = "RaiBlocklistItemsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, raiBlocklistName, raiBlocklistItemName, options) + if err != nil { + return RaiBlocklistItemsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RaiBlocklistItemsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RaiBlocklistItemsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *RaiBlocklistItemsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, raiBlocklistName string, raiBlocklistItemName string, _ *RaiBlocklistItemsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiBlocklists/{raiBlocklistName}/raiBlocklistItems/{raiBlocklistItemName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if raiBlocklistName == "" { + return nil, errors.New("parameter raiBlocklistName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{raiBlocklistName}", url.PathEscape(raiBlocklistName)) + if raiBlocklistItemName == "" { + return nil, errors.New("parameter raiBlocklistItemName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{raiBlocklistItemName}", url.PathEscape(raiBlocklistItemName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *RaiBlocklistItemsClient) getHandleResponse(resp *http.Response) (RaiBlocklistItemsClientGetResponse, error) { + result := RaiBlocklistItemsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RaiBlocklistItem); err != nil { + return RaiBlocklistItemsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets the blocklist items associated with the custom blocklist. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - raiBlocklistName - The name of the RaiBlocklist associated with the Cognitive Services Account +// - options - RaiBlocklistItemsClientListOptions contains the optional parameters for the RaiBlocklistItemsClient.NewListPager +// method. +func (client *RaiBlocklistItemsClient) NewListPager(resourceGroupName string, accountName string, raiBlocklistName string, options *RaiBlocklistItemsClientListOptions) *runtime.Pager[RaiBlocklistItemsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[RaiBlocklistItemsClientListResponse]{ + More: func(page RaiBlocklistItemsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *RaiBlocklistItemsClientListResponse) (RaiBlocklistItemsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "RaiBlocklistItemsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, raiBlocklistName, options) + }, nil) + if err != nil { + return RaiBlocklistItemsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *RaiBlocklistItemsClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, raiBlocklistName string, _ *RaiBlocklistItemsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiBlocklists/{raiBlocklistName}/raiBlocklistItems" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if raiBlocklistName == "" { + return nil, errors.New("parameter raiBlocklistName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{raiBlocklistName}", url.PathEscape(raiBlocklistName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *RaiBlocklistItemsClient) listHandleResponse(resp *http.Response) (RaiBlocklistItemsClientListResponse, error) { + result := RaiBlocklistItemsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RaiBlockListItemsResult); err != nil { + return RaiBlocklistItemsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_raiblocklists_client.go b/test/local/armcognitiveservices/zz_raiblocklists_client.go new file mode 100644 index 000000000000..1ea915f4f404 --- /dev/null +++ b/test/local/armcognitiveservices/zz_raiblocklists_client.go @@ -0,0 +1,320 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// RaiBlocklistsClient contains the methods for the RaiBlocklists group. +// Don't use this type directly, use NewRaiBlocklistsClient() instead. +// +// Generated from API version 2026-05-01 +type RaiBlocklistsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewRaiBlocklistsClient creates a new instance of RaiBlocklistsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewRaiBlocklistsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*RaiBlocklistsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &RaiBlocklistsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Update the state of specified blocklist associated with the Azure OpenAI account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - raiBlocklistName - The name of the RaiBlocklist associated with the Cognitive Services Account +// - raiBlocklist - Properties describing the custom blocklist. +// - options - RaiBlocklistsClientCreateOrUpdateOptions contains the optional parameters for the RaiBlocklistsClient.CreateOrUpdate +// method. +func (client *RaiBlocklistsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, raiBlocklistName string, raiBlocklist RaiBlocklist, options *RaiBlocklistsClientCreateOrUpdateOptions) (RaiBlocklistsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "RaiBlocklistsClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, raiBlocklistName, raiBlocklist, options) + if err != nil { + return RaiBlocklistsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RaiBlocklistsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return RaiBlocklistsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *RaiBlocklistsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, raiBlocklistName string, raiBlocklist RaiBlocklist, _ *RaiBlocklistsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiBlocklists/{raiBlocklistName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if raiBlocklistName == "" { + return nil, errors.New("parameter raiBlocklistName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{raiBlocklistName}", url.PathEscape(raiBlocklistName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, raiBlocklist); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *RaiBlocklistsClient) createOrUpdateHandleResponse(resp *http.Response) (RaiBlocklistsClientCreateOrUpdateResponse, error) { + result := RaiBlocklistsClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RaiBlocklist); err != nil { + return RaiBlocklistsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// BeginDelete - Deletes the specified custom blocklist associated with the Azure OpenAI account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - raiBlocklistName - The name of the RaiBlocklist associated with the Cognitive Services Account +// - options - RaiBlocklistsClientBeginDeleteOptions contains the optional parameters for the RaiBlocklistsClient.BeginDelete +// method. +func (client *RaiBlocklistsClient) BeginDelete(ctx context.Context, resourceGroupName string, accountName string, raiBlocklistName string, options *RaiBlocklistsClientBeginDeleteOptions) (*runtime.Poller[RaiBlocklistsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, accountName, raiBlocklistName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RaiBlocklistsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RaiBlocklistsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified custom blocklist associated with the Azure OpenAI account. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *RaiBlocklistsClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, raiBlocklistName string, options *RaiBlocklistsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "RaiBlocklistsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, raiBlocklistName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *RaiBlocklistsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, raiBlocklistName string, _ *RaiBlocklistsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiBlocklists/{raiBlocklistName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if raiBlocklistName == "" { + return nil, errors.New("parameter raiBlocklistName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{raiBlocklistName}", url.PathEscape(raiBlocklistName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Gets the specified custom blocklist associated with the Azure OpenAI account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - raiBlocklistName - The name of the RaiBlocklist associated with the Cognitive Services Account +// - options - RaiBlocklistsClientGetOptions contains the optional parameters for the RaiBlocklistsClient.Get method. +func (client *RaiBlocklistsClient) Get(ctx context.Context, resourceGroupName string, accountName string, raiBlocklistName string, options *RaiBlocklistsClientGetOptions) (RaiBlocklistsClientGetResponse, error) { + var err error + const operationName = "RaiBlocklistsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, raiBlocklistName, options) + if err != nil { + return RaiBlocklistsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RaiBlocklistsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RaiBlocklistsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *RaiBlocklistsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, raiBlocklistName string, _ *RaiBlocklistsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiBlocklists/{raiBlocklistName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if raiBlocklistName == "" { + return nil, errors.New("parameter raiBlocklistName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{raiBlocklistName}", url.PathEscape(raiBlocklistName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *RaiBlocklistsClient) getHandleResponse(resp *http.Response) (RaiBlocklistsClientGetResponse, error) { + result := RaiBlocklistsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RaiBlocklist); err != nil { + return RaiBlocklistsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets the custom blocklists associated with the Azure OpenAI account. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - options - RaiBlocklistsClientListOptions contains the optional parameters for the RaiBlocklistsClient.NewListPager method. +func (client *RaiBlocklistsClient) NewListPager(resourceGroupName string, accountName string, options *RaiBlocklistsClientListOptions) *runtime.Pager[RaiBlocklistsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[RaiBlocklistsClientListResponse]{ + More: func(page RaiBlocklistsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *RaiBlocklistsClientListResponse) (RaiBlocklistsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "RaiBlocklistsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, options) + }, nil) + if err != nil { + return RaiBlocklistsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *RaiBlocklistsClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, _ *RaiBlocklistsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiBlocklists" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *RaiBlocklistsClient) listHandleResponse(resp *http.Response) (RaiBlocklistsClientListResponse, error) { + result := RaiBlocklistsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RaiBlockListResult); err != nil { + return RaiBlocklistsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_raicontentfilters_client.go b/test/local/armcognitiveservices/zz_raicontentfilters_client.go new file mode 100644 index 000000000000..e5b4a67d69b6 --- /dev/null +++ b/test/local/armcognitiveservices/zz_raicontentfilters_client.go @@ -0,0 +1,162 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// RaiContentFiltersClient contains the methods for the RaiContentFilters group. +// Don't use this type directly, use NewRaiContentFiltersClient() instead. +// +// Generated from API version 2026-05-01 +type RaiContentFiltersClient struct { + internal *arm.Client + subscriptionID string +} + +// NewRaiContentFiltersClient creates a new instance of RaiContentFiltersClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewRaiContentFiltersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*RaiContentFiltersClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &RaiContentFiltersClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get Content Filters by Name. +// If the operation fails it returns an *azcore.ResponseError type. +// - location - The name of the Azure region. +// - filterName - The name of the RAI Content Filter. +// - options - RaiContentFiltersClientGetOptions contains the optional parameters for the RaiContentFiltersClient.Get method. +func (client *RaiContentFiltersClient) Get(ctx context.Context, location string, filterName string, options *RaiContentFiltersClientGetOptions) (RaiContentFiltersClientGetResponse, error) { + var err error + const operationName = "RaiContentFiltersClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, location, filterName, options) + if err != nil { + return RaiContentFiltersClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RaiContentFiltersClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RaiContentFiltersClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *RaiContentFiltersClient) getCreateRequest(ctx context.Context, location string, filterName string, _ *RaiContentFiltersClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/raiContentFilters/{filterName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if filterName == "" { + return nil, errors.New("parameter filterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{filterName}", url.PathEscape(filterName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *RaiContentFiltersClient) getHandleResponse(resp *http.Response) (RaiContentFiltersClientGetResponse, error) { + result := RaiContentFiltersClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RaiContentFilter); err != nil { + return RaiContentFiltersClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List Content Filters types. +// - location - The name of the Azure region. +// - options - RaiContentFiltersClientListOptions contains the optional parameters for the RaiContentFiltersClient.NewListPager +// method. +func (client *RaiContentFiltersClient) NewListPager(location string, options *RaiContentFiltersClientListOptions) *runtime.Pager[RaiContentFiltersClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[RaiContentFiltersClientListResponse]{ + More: func(page RaiContentFiltersClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *RaiContentFiltersClientListResponse) (RaiContentFiltersClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "RaiContentFiltersClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, location, options) + }, nil) + if err != nil { + return RaiContentFiltersClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *RaiContentFiltersClient) listCreateRequest(ctx context.Context, location string, _ *RaiContentFiltersClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/raiContentFilters" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *RaiContentFiltersClient) listHandleResponse(resp *http.Response) (RaiContentFiltersClientListResponse, error) { + result := RaiContentFiltersClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RaiContentFilterListResult); err != nil { + return RaiContentFiltersClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_raiexternalsafetyprovider_client.go b/test/local/armcognitiveservices/zz_raiexternalsafetyprovider_client.go new file mode 100644 index 000000000000..97e363ac13ff --- /dev/null +++ b/test/local/armcognitiveservices/zz_raiexternalsafetyprovider_client.go @@ -0,0 +1,229 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// RaiExternalSafetyProviderClient contains the methods for the RaiExternalSafetyProvider group. +// Don't use this type directly, use NewRaiExternalSafetyProviderClient() instead. +// +// Generated from API version 2026-05-01 +type RaiExternalSafetyProviderClient struct { + internal *arm.Client + subscriptionID string +} + +// NewRaiExternalSafetyProviderClient creates a new instance of RaiExternalSafetyProviderClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewRaiExternalSafetyProviderClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*RaiExternalSafetyProviderClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &RaiExternalSafetyProviderClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Create the rai safety provider associated with the subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// - safetyProviderName - The name of the Rai External Safety Provider associated with the Cognitive Services Account +// - safetyProvider - Properties describing the rai external safety provider. +// - options - RaiExternalSafetyProviderClientCreateOrUpdateOptions contains the optional parameters for the RaiExternalSafetyProviderClient.CreateOrUpdate +// method. +func (client *RaiExternalSafetyProviderClient) CreateOrUpdate(ctx context.Context, safetyProviderName string, safetyProvider RaiExternalSafetyProviderSchema, options *RaiExternalSafetyProviderClientCreateOrUpdateOptions) (RaiExternalSafetyProviderClientCreateOrUpdateResponse, error) { + var err error + const operationName = "RaiExternalSafetyProviderClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, safetyProviderName, safetyProvider, options) + if err != nil { + return RaiExternalSafetyProviderClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RaiExternalSafetyProviderClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return RaiExternalSafetyProviderClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *RaiExternalSafetyProviderClient) createOrUpdateCreateRequest(ctx context.Context, safetyProviderName string, safetyProvider RaiExternalSafetyProviderSchema, _ *RaiExternalSafetyProviderClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/raiExternalSafetyProviders/{safetyProviderName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if safetyProviderName == "" { + return nil, errors.New("parameter safetyProviderName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{safetyProviderName}", url.PathEscape(safetyProviderName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, safetyProvider); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *RaiExternalSafetyProviderClient) createOrUpdateHandleResponse(resp *http.Response) (RaiExternalSafetyProviderClientCreateOrUpdateResponse, error) { + result := RaiExternalSafetyProviderClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RaiExternalSafetyProviderSchema); err != nil { + return RaiExternalSafetyProviderClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// BeginDelete - Deletes the specified custom topic associated with the subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// - safetyProviderName - The name of the Rai External Safety Provider associated with the Cognitive Services Account +// - options - RaiExternalSafetyProviderClientBeginDeleteOptions contains the optional parameters for the RaiExternalSafetyProviderClient.BeginDelete +// method. +func (client *RaiExternalSafetyProviderClient) BeginDelete(ctx context.Context, safetyProviderName string, options *RaiExternalSafetyProviderClientBeginDeleteOptions) (*runtime.Poller[RaiExternalSafetyProviderClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, safetyProviderName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RaiExternalSafetyProviderClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RaiExternalSafetyProviderClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified custom topic associated with the subscription. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *RaiExternalSafetyProviderClient) deleteOperation(ctx context.Context, safetyProviderName string, options *RaiExternalSafetyProviderClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "RaiExternalSafetyProviderClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, safetyProviderName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *RaiExternalSafetyProviderClient) deleteCreateRequest(ctx context.Context, safetyProviderName string, _ *RaiExternalSafetyProviderClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/raiExternalSafetyProviders/{safetyProviderName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if safetyProviderName == "" { + return nil, errors.New("parameter safetyProviderName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{safetyProviderName}", url.PathEscape(safetyProviderName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Gets the specified external safety provider associated with the Subscription +// If the operation fails it returns an *azcore.ResponseError type. +// - safetyProviderName - The name of the Rai External Safety Provider associated with the Cognitive Services Account +// - options - RaiExternalSafetyProviderClientGetOptions contains the optional parameters for the RaiExternalSafetyProviderClient.Get +// method. +func (client *RaiExternalSafetyProviderClient) Get(ctx context.Context, safetyProviderName string, options *RaiExternalSafetyProviderClientGetOptions) (RaiExternalSafetyProviderClientGetResponse, error) { + var err error + const operationName = "RaiExternalSafetyProviderClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, safetyProviderName, options) + if err != nil { + return RaiExternalSafetyProviderClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RaiExternalSafetyProviderClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RaiExternalSafetyProviderClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *RaiExternalSafetyProviderClient) getCreateRequest(ctx context.Context, safetyProviderName string, _ *RaiExternalSafetyProviderClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/raiExternalSafetyProviders/{safetyProviderName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if safetyProviderName == "" { + return nil, errors.New("parameter safetyProviderName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{safetyProviderName}", url.PathEscape(safetyProviderName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *RaiExternalSafetyProviderClient) getHandleResponse(resp *http.Response) (RaiExternalSafetyProviderClientGetResponse, error) { + result := RaiExternalSafetyProviderClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RaiExternalSafetyProviderSchema); err != nil { + return RaiExternalSafetyProviderClientGetResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_raiexternalsafetyproviders_client.go b/test/local/armcognitiveservices/zz_raiexternalsafetyproviders_client.go new file mode 100644 index 000000000000..33c28ca4540f --- /dev/null +++ b/test/local/armcognitiveservices/zz_raiexternalsafetyproviders_client.go @@ -0,0 +1,95 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// RaiExternalSafetyProvidersClient contains the methods for the RaiExternalSafetyProviders group. +// Don't use this type directly, use NewRaiExternalSafetyProvidersClient() instead. +// +// Generated from API version 2026-05-01 +type RaiExternalSafetyProvidersClient struct { + internal *arm.Client + subscriptionID string +} + +// NewRaiExternalSafetyProvidersClient creates a new instance of RaiExternalSafetyProvidersClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewRaiExternalSafetyProvidersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*RaiExternalSafetyProvidersClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &RaiExternalSafetyProvidersClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListPager - Gets the safety providers associated with the subscription +// - options - RaiExternalSafetyProvidersClientListOptions contains the optional parameters for the RaiExternalSafetyProvidersClient.NewListPager +// method. +func (client *RaiExternalSafetyProvidersClient) NewListPager(options *RaiExternalSafetyProvidersClientListOptions) *runtime.Pager[RaiExternalSafetyProvidersClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[RaiExternalSafetyProvidersClientListResponse]{ + More: func(page RaiExternalSafetyProvidersClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *RaiExternalSafetyProvidersClientListResponse) (RaiExternalSafetyProvidersClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "RaiExternalSafetyProvidersClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return RaiExternalSafetyProvidersClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *RaiExternalSafetyProvidersClient) listCreateRequest(ctx context.Context, _ *RaiExternalSafetyProvidersClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/raiExternalSafetyProviders" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *RaiExternalSafetyProvidersClient) listHandleResponse(resp *http.Response) (RaiExternalSafetyProvidersClientListResponse, error) { + result := RaiExternalSafetyProvidersClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RaiExternalSafetyProviderResult); err != nil { + return RaiExternalSafetyProvidersClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_raipolicies_client.go b/test/local/armcognitiveservices/zz_raipolicies_client.go new file mode 100644 index 000000000000..3e13a75f10fd --- /dev/null +++ b/test/local/armcognitiveservices/zz_raipolicies_client.go @@ -0,0 +1,319 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// RaiPoliciesClient contains the methods for the RaiPolicies group. +// Don't use this type directly, use NewRaiPoliciesClient() instead. +// +// Generated from API version 2026-05-01 +type RaiPoliciesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewRaiPoliciesClient creates a new instance of RaiPoliciesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewRaiPoliciesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*RaiPoliciesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &RaiPoliciesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Update the state of specified Content Filters associated with the Azure OpenAI account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - raiPolicyName - The name of the RaiPolicy associated with the Cognitive Services Account +// - raiPolicy - Properties describing the Content Filters. +// - options - RaiPoliciesClientCreateOrUpdateOptions contains the optional parameters for the RaiPoliciesClient.CreateOrUpdate +// method. +func (client *RaiPoliciesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, raiPolicyName string, raiPolicy RaiPolicy, options *RaiPoliciesClientCreateOrUpdateOptions) (RaiPoliciesClientCreateOrUpdateResponse, error) { + var err error + const operationName = "RaiPoliciesClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, raiPolicyName, raiPolicy, options) + if err != nil { + return RaiPoliciesClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RaiPoliciesClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return RaiPoliciesClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *RaiPoliciesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, raiPolicyName string, raiPolicy RaiPolicy, _ *RaiPoliciesClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiPolicies/{raiPolicyName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if raiPolicyName == "" { + return nil, errors.New("parameter raiPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{raiPolicyName}", url.PathEscape(raiPolicyName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, raiPolicy); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *RaiPoliciesClient) createOrUpdateHandleResponse(resp *http.Response) (RaiPoliciesClientCreateOrUpdateResponse, error) { + result := RaiPoliciesClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RaiPolicy); err != nil { + return RaiPoliciesClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// BeginDelete - Deletes the specified Content Filters associated with the Azure OpenAI account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - raiPolicyName - The name of the RaiPolicy associated with the Cognitive Services Account +// - options - RaiPoliciesClientBeginDeleteOptions contains the optional parameters for the RaiPoliciesClient.BeginDelete method. +func (client *RaiPoliciesClient) BeginDelete(ctx context.Context, resourceGroupName string, accountName string, raiPolicyName string, options *RaiPoliciesClientBeginDeleteOptions) (*runtime.Poller[RaiPoliciesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, accountName, raiPolicyName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RaiPoliciesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RaiPoliciesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified Content Filters associated with the Azure OpenAI account. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *RaiPoliciesClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, raiPolicyName string, options *RaiPoliciesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "RaiPoliciesClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, raiPolicyName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *RaiPoliciesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, raiPolicyName string, _ *RaiPoliciesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiPolicies/{raiPolicyName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if raiPolicyName == "" { + return nil, errors.New("parameter raiPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{raiPolicyName}", url.PathEscape(raiPolicyName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Gets the specified Content Filters associated with the Azure OpenAI account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - raiPolicyName - The name of the RaiPolicy associated with the Cognitive Services Account +// - options - RaiPoliciesClientGetOptions contains the optional parameters for the RaiPoliciesClient.Get method. +func (client *RaiPoliciesClient) Get(ctx context.Context, resourceGroupName string, accountName string, raiPolicyName string, options *RaiPoliciesClientGetOptions) (RaiPoliciesClientGetResponse, error) { + var err error + const operationName = "RaiPoliciesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, raiPolicyName, options) + if err != nil { + return RaiPoliciesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RaiPoliciesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RaiPoliciesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *RaiPoliciesClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, raiPolicyName string, _ *RaiPoliciesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiPolicies/{raiPolicyName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if raiPolicyName == "" { + return nil, errors.New("parameter raiPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{raiPolicyName}", url.PathEscape(raiPolicyName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *RaiPoliciesClient) getHandleResponse(resp *http.Response) (RaiPoliciesClientGetResponse, error) { + result := RaiPoliciesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RaiPolicy); err != nil { + return RaiPoliciesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets the content filters associated with the Azure OpenAI account. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - options - RaiPoliciesClientListOptions contains the optional parameters for the RaiPoliciesClient.NewListPager method. +func (client *RaiPoliciesClient) NewListPager(resourceGroupName string, accountName string, options *RaiPoliciesClientListOptions) *runtime.Pager[RaiPoliciesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[RaiPoliciesClientListResponse]{ + More: func(page RaiPoliciesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *RaiPoliciesClientListResponse) (RaiPoliciesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "RaiPoliciesClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, options) + }, nil) + if err != nil { + return RaiPoliciesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *RaiPoliciesClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, _ *RaiPoliciesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiPolicies" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *RaiPoliciesClient) listHandleResponse(resp *http.Response) (RaiPoliciesClientListResponse, error) { + result := RaiPoliciesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RaiPolicyListResult); err != nil { + return RaiPoliciesClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_raitoollabels_client.go b/test/local/armcognitiveservices/zz_raitoollabels_client.go new file mode 100644 index 000000000000..32f2fe3fcec9 --- /dev/null +++ b/test/local/armcognitiveservices/zz_raitoollabels_client.go @@ -0,0 +1,320 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// RaiToolLabelsClient contains the methods for the RaiToolLabels group. +// Don't use this type directly, use NewRaiToolLabelsClient() instead. +// +// Generated from API version 2026-05-01 +type RaiToolLabelsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewRaiToolLabelsClient creates a new instance of RaiToolLabelsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewRaiToolLabelsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*RaiToolLabelsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &RaiToolLabelsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Creates the RAI Tool Label associated with the Azure OpenAI account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - raiToolConnectionName - The name of the Rai Tool Label +// - raiToolLabel - Properties describing the RAI Tool Label. +// - options - RaiToolLabelsClientCreateOrUpdateOptions contains the optional parameters for the RaiToolLabelsClient.CreateOrUpdate +// method. +func (client *RaiToolLabelsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, raiToolConnectionName string, raiToolLabel RaiToolLabel, options *RaiToolLabelsClientCreateOrUpdateOptions) (RaiToolLabelsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "RaiToolLabelsClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, raiToolConnectionName, raiToolLabel, options) + if err != nil { + return RaiToolLabelsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RaiToolLabelsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return RaiToolLabelsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *RaiToolLabelsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, raiToolConnectionName string, raiToolLabel RaiToolLabel, _ *RaiToolLabelsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiToolLabels/{raiToolConnectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if raiToolConnectionName == "" { + return nil, errors.New("parameter raiToolConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{raiToolConnectionName}", url.PathEscape(raiToolConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, raiToolLabel); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *RaiToolLabelsClient) createOrUpdateHandleResponse(resp *http.Response) (RaiToolLabelsClientCreateOrUpdateResponse, error) { + result := RaiToolLabelsClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RaiToolLabel); err != nil { + return RaiToolLabelsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// BeginDelete - Deletes the specified RAI Tool Label associated with the Azure OpenAI account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - raiToolConnectionName - The name of the Rai Tool Label +// - options - RaiToolLabelsClientBeginDeleteOptions contains the optional parameters for the RaiToolLabelsClient.BeginDelete +// method. +func (client *RaiToolLabelsClient) BeginDelete(ctx context.Context, resourceGroupName string, accountName string, raiToolConnectionName string, options *RaiToolLabelsClientBeginDeleteOptions) (*runtime.Poller[RaiToolLabelsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, accountName, raiToolConnectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RaiToolLabelsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RaiToolLabelsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified RAI Tool Label associated with the Azure OpenAI account. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *RaiToolLabelsClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, raiToolConnectionName string, options *RaiToolLabelsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "RaiToolLabelsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, raiToolConnectionName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *RaiToolLabelsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, raiToolConnectionName string, _ *RaiToolLabelsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiToolLabels/{raiToolConnectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if raiToolConnectionName == "" { + return nil, errors.New("parameter raiToolConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{raiToolConnectionName}", url.PathEscape(raiToolConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Gets the specified RAI Tool Label associated with the Azure OpenAI account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - raiToolConnectionName - The name of the Rai Tool Label +// - options - RaiToolLabelsClientGetOptions contains the optional parameters for the RaiToolLabelsClient.Get method. +func (client *RaiToolLabelsClient) Get(ctx context.Context, resourceGroupName string, accountName string, raiToolConnectionName string, options *RaiToolLabelsClientGetOptions) (RaiToolLabelsClientGetResponse, error) { + var err error + const operationName = "RaiToolLabelsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, raiToolConnectionName, options) + if err != nil { + return RaiToolLabelsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RaiToolLabelsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RaiToolLabelsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *RaiToolLabelsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, raiToolConnectionName string, _ *RaiToolLabelsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiToolLabels/{raiToolConnectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if raiToolConnectionName == "" { + return nil, errors.New("parameter raiToolConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{raiToolConnectionName}", url.PathEscape(raiToolConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *RaiToolLabelsClient) getHandleResponse(resp *http.Response) (RaiToolLabelsClientGetResponse, error) { + result := RaiToolLabelsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RaiToolLabel); err != nil { + return RaiToolLabelsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Lists all RAI Tool Labels associated with the Azure OpenAI account. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - options - RaiToolLabelsClientListOptions contains the optional parameters for the RaiToolLabelsClient.NewListPager method. +func (client *RaiToolLabelsClient) NewListPager(resourceGroupName string, accountName string, options *RaiToolLabelsClientListOptions) *runtime.Pager[RaiToolLabelsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[RaiToolLabelsClientListResponse]{ + More: func(page RaiToolLabelsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *RaiToolLabelsClientListResponse) (RaiToolLabelsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "RaiToolLabelsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, options) + }, nil) + if err != nil { + return RaiToolLabelsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *RaiToolLabelsClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, _ *RaiToolLabelsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raiToolLabels" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *RaiToolLabelsClient) listHandleResponse(resp *http.Response) (RaiToolLabelsClientListResponse, error) { + result := RaiToolLabelsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RaiToolLabelResult); err != nil { + return RaiToolLabelsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_raitopics_client.go b/test/local/armcognitiveservices/zz_raitopics_client.go new file mode 100644 index 000000000000..60f19e788e98 --- /dev/null +++ b/test/local/armcognitiveservices/zz_raitopics_client.go @@ -0,0 +1,319 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// RaiTopicsClient contains the methods for the RaiTopics group. +// Don't use this type directly, use NewRaiTopicsClient() instead. +// +// Generated from API version 2026-05-01 +type RaiTopicsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewRaiTopicsClient creates a new instance of RaiTopicsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewRaiTopicsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*RaiTopicsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &RaiTopicsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Create the rai topic associated with the Azure OpenAI account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - raiTopicName - The name of the Rai Topic associated with the Cognitive Services Account +// - raiTopic - Properties describing the rai topic. +// - options - RaiTopicsClientCreateOrUpdateOptions contains the optional parameters for the RaiTopicsClient.CreateOrUpdate +// method. +func (client *RaiTopicsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, raiTopicName string, raiTopic RaiTopic, options *RaiTopicsClientCreateOrUpdateOptions) (RaiTopicsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "RaiTopicsClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, raiTopicName, raiTopic, options) + if err != nil { + return RaiTopicsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RaiTopicsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return RaiTopicsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *RaiTopicsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, raiTopicName string, raiTopic RaiTopic, _ *RaiTopicsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raitopics/{raiTopicName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if raiTopicName == "" { + return nil, errors.New("parameter raiTopicName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{raiTopicName}", url.PathEscape(raiTopicName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, raiTopic); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *RaiTopicsClient) createOrUpdateHandleResponse(resp *http.Response) (RaiTopicsClientCreateOrUpdateResponse, error) { + result := RaiTopicsClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RaiTopic); err != nil { + return RaiTopicsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// BeginDelete - Deletes the specified custom topic associated with the Azure OpenAI account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - raiTopicName - The name of the Rai Topic associated with the Cognitive Services Account +// - options - RaiTopicsClientBeginDeleteOptions contains the optional parameters for the RaiTopicsClient.BeginDelete method. +func (client *RaiTopicsClient) BeginDelete(ctx context.Context, resourceGroupName string, accountName string, raiTopicName string, options *RaiTopicsClientBeginDeleteOptions) (*runtime.Poller[RaiTopicsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, accountName, raiTopicName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[RaiTopicsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[RaiTopicsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified custom topic associated with the Azure OpenAI account. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *RaiTopicsClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, raiTopicName string, options *RaiTopicsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "RaiTopicsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, raiTopicName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *RaiTopicsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, raiTopicName string, _ *RaiTopicsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raitopics/{raiTopicName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if raiTopicName == "" { + return nil, errors.New("parameter raiTopicName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{raiTopicName}", url.PathEscape(raiTopicName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Gets the specified custom topic associated with the Azure OpenAI account. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - raiTopicName - The name of the Rai Topic associated with the Cognitive Services Account +// - options - RaiTopicsClientGetOptions contains the optional parameters for the RaiTopicsClient.Get method. +func (client *RaiTopicsClient) Get(ctx context.Context, resourceGroupName string, accountName string, raiTopicName string, options *RaiTopicsClientGetOptions) (RaiTopicsClientGetResponse, error) { + var err error + const operationName = "RaiTopicsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, raiTopicName, options) + if err != nil { + return RaiTopicsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RaiTopicsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RaiTopicsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *RaiTopicsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, raiTopicName string, _ *RaiTopicsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raitopics/{raiTopicName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if raiTopicName == "" { + return nil, errors.New("parameter raiTopicName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{raiTopicName}", url.PathEscape(raiTopicName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *RaiTopicsClient) getHandleResponse(resp *http.Response) (RaiTopicsClientGetResponse, error) { + result := RaiTopicsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RaiTopic); err != nil { + return RaiTopicsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Gets the custom topics associated with the Azure OpenAI account. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - options - RaiTopicsClientListOptions contains the optional parameters for the RaiTopicsClient.NewListPager method. +func (client *RaiTopicsClient) NewListPager(resourceGroupName string, accountName string, options *RaiTopicsClientListOptions) *runtime.Pager[RaiTopicsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[RaiTopicsClientListResponse]{ + More: func(page RaiTopicsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *RaiTopicsClientListResponse) (RaiTopicsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "RaiTopicsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, options) + }, nil) + if err != nil { + return RaiTopicsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *RaiTopicsClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, _ *RaiTopicsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/raitopics" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *RaiTopicsClient) listHandleResponse(resp *http.Response) (RaiTopicsClientListResponse, error) { + result := RaiTopicsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RaiTopicResult); err != nil { + return RaiTopicsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_resourceskus_client.go b/test/local/armcognitiveservices/zz_resourceskus_client.go new file mode 100644 index 000000000000..edb2956d070f --- /dev/null +++ b/test/local/armcognitiveservices/zz_resourceskus_client.go @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ResourceSKUsClient contains the methods for the ResourceSKUs group. +// Don't use this type directly, use NewResourceSKUsClient() instead. +// +// Generated from API version 2026-05-01 +type ResourceSKUsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewResourceSKUsClient creates a new instance of ResourceSKUsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewResourceSKUsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ResourceSKUsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ResourceSKUsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListPager - Gets the list of Microsoft.CognitiveServices SKUs available for your Subscription. +// - options - ResourceSKUsClientListOptions contains the optional parameters for the ResourceSKUsClient.NewListPager method. +func (client *ResourceSKUsClient) NewListPager(options *ResourceSKUsClientListOptions) *runtime.Pager[ResourceSKUsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ResourceSKUsClientListResponse]{ + More: func(page ResourceSKUsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ResourceSKUsClientListResponse) (ResourceSKUsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ResourceSKUsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return ResourceSKUsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ResourceSKUsClient) listCreateRequest(ctx context.Context, _ *ResourceSKUsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/skus" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ResourceSKUsClient) listHandleResponse(resp *http.Response) (ResourceSKUsClientListResponse, error) { + result := ResourceSKUsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ResourceSKUListResult); err != nil { + return ResourceSKUsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_responses.go b/test/local/armcognitiveservices/zz_responses.go new file mode 100644 index 000000000000..81ac7ec57d3c --- /dev/null +++ b/test/local/armcognitiveservices/zz_responses.go @@ -0,0 +1,847 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +// AccountCapabilityHostsClientCreateOrUpdateResponse contains the response from method AccountCapabilityHostsClient.BeginCreateOrUpdate. +type AccountCapabilityHostsClientCreateOrUpdateResponse struct { + // Azure Resource Manager resource envelope. + CapabilityHost +} + +// AccountCapabilityHostsClientDeleteResponse contains the response from method AccountCapabilityHostsClient.BeginDelete. +type AccountCapabilityHostsClientDeleteResponse struct { + // placeholder for future response values +} + +// AccountCapabilityHostsClientGetResponse contains the response from method AccountCapabilityHostsClient.Get. +type AccountCapabilityHostsClientGetResponse struct { + // Azure Resource Manager resource envelope. + CapabilityHost +} + +// AccountCapabilityHostsClientListResponse contains the response from method AccountCapabilityHostsClient.NewListPager. +type AccountCapabilityHostsClientListResponse struct { + // A paginated list of Capability Host entities. + CapabilityHostResourceArmPaginatedResult +} + +// AccountConnectionsClientCreateResponse contains the response from method AccountConnectionsClient.Create. +type AccountConnectionsClientCreateResponse struct { + // Connection base resource schema. + ConnectionPropertiesV2BasicResource +} + +// AccountConnectionsClientDeleteResponse contains the response from method AccountConnectionsClient.Delete. +type AccountConnectionsClientDeleteResponse struct { + // placeholder for future response values +} + +// AccountConnectionsClientGetResponse contains the response from method AccountConnectionsClient.Get. +type AccountConnectionsClientGetResponse struct { + // Connection base resource schema. + ConnectionPropertiesV2BasicResource +} + +// AccountConnectionsClientListResponse contains the response from method AccountConnectionsClient.NewListPager. +type AccountConnectionsClientListResponse struct { + ConnectionPropertiesV2BasicResourceArmPaginatedResult +} + +// AccountConnectionsClientUpdateResponse contains the response from method AccountConnectionsClient.Update. +type AccountConnectionsClientUpdateResponse struct { + // Connection base resource schema. + ConnectionPropertiesV2BasicResource +} + +// AccountsClientCreateResponse contains the response from method AccountsClient.BeginCreate. +type AccountsClientCreateResponse struct { + // Cognitive Services account is an Azure resource representing the provisioned account, it's type, location and SKU. + Account +} + +// AccountsClientDeleteResponse contains the response from method AccountsClient.BeginDelete. +type AccountsClientDeleteResponse struct { + // placeholder for future response values +} + +// AccountsClientGetResponse contains the response from method AccountsClient.Get. +type AccountsClientGetResponse struct { + // Cognitive Services account is an Azure resource representing the provisioned account, it's type, location and SKU. + Account +} + +// AccountsClientListByResourceGroupResponse contains the response from method AccountsClient.NewListByResourceGroupPager. +type AccountsClientListByResourceGroupResponse struct { + // The list of cognitive services accounts operation response. + AccountListResult +} + +// AccountsClientListKeysResponse contains the response from method AccountsClient.ListKeys. +type AccountsClientListKeysResponse struct { + // The access keys for the cognitive services account. + APIKeys +} + +// AccountsClientListModelsResponse contains the response from method AccountsClient.NewListModelsPager. +type AccountsClientListModelsResponse struct { + // The list of cognitive services accounts operation response. + AccountModelListResult +} + +// AccountsClientListResponse contains the response from method AccountsClient.NewListPager. +type AccountsClientListResponse struct { + // The list of cognitive services accounts operation response. + AccountListResult +} + +// AccountsClientListSKUsResponse contains the response from method AccountsClient.ListSKUs. +type AccountsClientListSKUsResponse struct { + // The list of cognitive services accounts operation response. + AccountSKUListResult +} + +// AccountsClientListUsagesResponse contains the response from method AccountsClient.ListUsages. +type AccountsClientListUsagesResponse struct { + // The response to a list usage request. + UsageListResult +} + +// AccountsClientRegenerateKeyResponse contains the response from method AccountsClient.RegenerateKey. +type AccountsClientRegenerateKeyResponse struct { + // The access keys for the cognitive services account. + APIKeys +} + +// AccountsClientUpdateResponse contains the response from method AccountsClient.BeginUpdate. +type AccountsClientUpdateResponse struct { + // Cognitive Services account is an Azure resource representing the provisioned account, it's type, location and SKU. + Account +} + +// AgentApplicationsClientCreateOrUpdateResponse contains the response from method AgentApplicationsClient.BeginCreateOrUpdate. +type AgentApplicationsClientCreateOrUpdateResponse struct { + // Agent Application resource + AgentApplication +} + +// AgentApplicationsClientDeleteResponse contains the response from method AgentApplicationsClient.BeginDelete. +type AgentApplicationsClientDeleteResponse struct { + // placeholder for future response values +} + +// AgentApplicationsClientDisableResponse contains the response from method AgentApplicationsClient.Disable. +type AgentApplicationsClientDisableResponse struct { + // placeholder for future response values +} + +// AgentApplicationsClientEnableResponse contains the response from method AgentApplicationsClient.Enable. +type AgentApplicationsClientEnableResponse struct { + // placeholder for future response values +} + +// AgentApplicationsClientGetResponse contains the response from method AgentApplicationsClient.Get. +type AgentApplicationsClientGetResponse struct { + // Agent Application resource + AgentApplication +} + +// AgentApplicationsClientListAgentsResponse contains the response from method AgentApplicationsClient.ListAgents. +type AgentApplicationsClientListAgentsResponse struct { + // A paginated list of Agent Reference entities. + AgentReferenceResourceArmPaginatedResult +} + +// AgentApplicationsClientListResponse contains the response from method AgentApplicationsClient.NewListPager. +type AgentApplicationsClientListResponse struct { + // A paginated list of Agent Application entities. + AgentApplicationResourceArmPaginatedResult +} + +// AgentDeploymentsClientCreateOrUpdateResponse contains the response from method AgentDeploymentsClient.BeginCreateOrUpdate. +type AgentDeploymentsClientCreateOrUpdateResponse struct { + // Agent Deployment resource + AgentDeployment +} + +// AgentDeploymentsClientDeleteResponse contains the response from method AgentDeploymentsClient.BeginDelete. +type AgentDeploymentsClientDeleteResponse struct { + // placeholder for future response values +} + +// AgentDeploymentsClientGetResponse contains the response from method AgentDeploymentsClient.Get. +type AgentDeploymentsClientGetResponse struct { + // Agent Deployment resource + AgentDeployment +} + +// AgentDeploymentsClientListResponse contains the response from method AgentDeploymentsClient.NewListPager. +type AgentDeploymentsClientListResponse struct { + // A paginated list of Agent Deployment entities. + AgentDeploymentResourceArmPaginatedResult +} + +// AgentDeploymentsClientStartResponse contains the response from method AgentDeploymentsClient.Start. +type AgentDeploymentsClientStartResponse struct { + // placeholder for future response values +} + +// AgentDeploymentsClientStopResponse contains the response from method AgentDeploymentsClient.Stop. +type AgentDeploymentsClientStopResponse struct { + // placeholder for future response values +} + +// CommitmentPlansClientCreateOrUpdateAssociationResponse contains the response from method CommitmentPlansClient.BeginCreateOrUpdateAssociation. +type CommitmentPlansClientCreateOrUpdateAssociationResponse struct { + // The commitment plan association. + CommitmentPlanAccountAssociation +} + +// CommitmentPlansClientCreateOrUpdatePlanResponse contains the response from method CommitmentPlansClient.BeginCreateOrUpdatePlan. +type CommitmentPlansClientCreateOrUpdatePlanResponse struct { + // Cognitive Services account commitment plan. + CommitmentPlan +} + +// CommitmentPlansClientCreateOrUpdateResponse contains the response from method CommitmentPlansClient.CreateOrUpdate. +type CommitmentPlansClientCreateOrUpdateResponse struct { + // Cognitive Services account commitment plan. + CommitmentPlan +} + +// CommitmentPlansClientDeleteAssociationResponse contains the response from method CommitmentPlansClient.BeginDeleteAssociation. +type CommitmentPlansClientDeleteAssociationResponse struct { + // placeholder for future response values +} + +// CommitmentPlansClientDeletePlanResponse contains the response from method CommitmentPlansClient.BeginDeletePlan. +type CommitmentPlansClientDeletePlanResponse struct { + // placeholder for future response values +} + +// CommitmentPlansClientDeleteResponse contains the response from method CommitmentPlansClient.BeginDelete. +type CommitmentPlansClientDeleteResponse struct { + // placeholder for future response values +} + +// CommitmentPlansClientGetAssociationResponse contains the response from method CommitmentPlansClient.GetAssociation. +type CommitmentPlansClientGetAssociationResponse struct { + // The commitment plan association. + CommitmentPlanAccountAssociation +} + +// CommitmentPlansClientGetPlanResponse contains the response from method CommitmentPlansClient.GetPlan. +type CommitmentPlansClientGetPlanResponse struct { + // Cognitive Services account commitment plan. + CommitmentPlan +} + +// CommitmentPlansClientGetResponse contains the response from method CommitmentPlansClient.Get. +type CommitmentPlansClientGetResponse struct { + // Cognitive Services account commitment plan. + CommitmentPlan +} + +// CommitmentPlansClientListAssociationsResponse contains the response from method CommitmentPlansClient.NewListAssociationsPager. +type CommitmentPlansClientListAssociationsResponse struct { + // The list of cognitive services Commitment Plan Account Association operation response. + CommitmentPlanAccountAssociationListResult +} + +// CommitmentPlansClientListPlansByResourceGroupResponse contains the response from method CommitmentPlansClient.NewListPlansByResourceGroupPager. +type CommitmentPlansClientListPlansByResourceGroupResponse struct { + // The list of cognitive services accounts operation response. + CommitmentPlanListResult +} + +// CommitmentPlansClientListPlansBySubscriptionResponse contains the response from method CommitmentPlansClient.NewListPlansBySubscriptionPager. +type CommitmentPlansClientListPlansBySubscriptionResponse struct { + // The list of cognitive services accounts operation response. + CommitmentPlanListResult +} + +// CommitmentPlansClientListResponse contains the response from method CommitmentPlansClient.NewListPager. +type CommitmentPlansClientListResponse struct { + // The list of cognitive services accounts operation response. + CommitmentPlanListResult +} + +// CommitmentPlansClientUpdatePlanResponse contains the response from method CommitmentPlansClient.BeginUpdatePlan. +type CommitmentPlansClientUpdatePlanResponse struct { + // Cognitive Services account commitment plan. + CommitmentPlan +} + +// CommitmentTiersClientListResponse contains the response from method CommitmentTiersClient.NewListPager. +type CommitmentTiersClientListResponse struct { + // The list of cognitive services accounts operation response. + CommitmentTierListResult +} + +// DefenderForAISettingsClientCreateOrUpdateResponse contains the response from method DefenderForAISettingsClient.CreateOrUpdate. +type DefenderForAISettingsClientCreateOrUpdateResponse struct { + // The Defender for AI resource. + DefenderForAISetting +} + +// DefenderForAISettingsClientGetResponse contains the response from method DefenderForAISettingsClient.Get. +type DefenderForAISettingsClientGetResponse struct { + // The Defender for AI resource. + DefenderForAISetting +} + +// DefenderForAISettingsClientListResponse contains the response from method DefenderForAISettingsClient.NewListPager. +type DefenderForAISettingsClientListResponse struct { + // The list of cognitive services Defender for AI Settings. + DefenderForAISettingResult +} + +// DefenderForAISettingsClientUpdateResponse contains the response from method DefenderForAISettingsClient.Update. +type DefenderForAISettingsClientUpdateResponse struct { + // The Defender for AI resource. + DefenderForAISetting +} + +// DeletedAccountsClientGetResponse contains the response from method DeletedAccountsClient.Get. +type DeletedAccountsClientGetResponse struct { + // Cognitive Services account is an Azure resource representing the provisioned account, it's type, location and SKU. + Account +} + +// DeletedAccountsClientListResponse contains the response from method DeletedAccountsClient.NewListPager. +type DeletedAccountsClientListResponse struct { + // The list of cognitive services accounts operation response. + AccountListResult +} + +// DeletedAccountsClientPurgeResponse contains the response from method DeletedAccountsClient.BeginPurge. +type DeletedAccountsClientPurgeResponse struct { + // placeholder for future response values +} + +// DeploymentsClientCreateOrUpdateResponse contains the response from method DeploymentsClient.BeginCreateOrUpdate. +type DeploymentsClientCreateOrUpdateResponse struct { + // Cognitive Services account deployment. + Deployment +} + +// DeploymentsClientDeleteResponse contains the response from method DeploymentsClient.BeginDelete. +type DeploymentsClientDeleteResponse struct { + // placeholder for future response values +} + +// DeploymentsClientGetResponse contains the response from method DeploymentsClient.Get. +type DeploymentsClientGetResponse struct { + // Cognitive Services account deployment. + Deployment +} + +// DeploymentsClientListResponse contains the response from method DeploymentsClient.NewListPager. +type DeploymentsClientListResponse struct { + // The list of cognitive services accounts operation response. + DeploymentListResult +} + +// DeploymentsClientListSKUsResponse contains the response from method DeploymentsClient.NewListSKUsPager. +type DeploymentsClientListSKUsResponse struct { + // The list of cognitive services accounts operation response. + DeploymentSKUListResult +} + +// DeploymentsClientPauseResponse contains the response from method DeploymentsClient.Pause. +type DeploymentsClientPauseResponse struct { + // Cognitive Services account deployment. + Deployment +} + +// DeploymentsClientResumeResponse contains the response from method DeploymentsClient.Resume. +type DeploymentsClientResumeResponse struct { + // Cognitive Services account deployment. + Deployment +} + +// DeploymentsClientUpdateResponse contains the response from method DeploymentsClient.BeginUpdate. +type DeploymentsClientUpdateResponse struct { + // Cognitive Services account deployment. + Deployment +} + +// EncryptionScopesClientCreateOrUpdateResponse contains the response from method EncryptionScopesClient.CreateOrUpdate. +type EncryptionScopesClientCreateOrUpdateResponse struct { + // Cognitive Services EncryptionScope + EncryptionScope +} + +// EncryptionScopesClientDeleteResponse contains the response from method EncryptionScopesClient.BeginDelete. +type EncryptionScopesClientDeleteResponse struct { + // placeholder for future response values +} + +// EncryptionScopesClientGetResponse contains the response from method EncryptionScopesClient.Get. +type EncryptionScopesClientGetResponse struct { + // Cognitive Services EncryptionScope + EncryptionScope +} + +// EncryptionScopesClientListResponse contains the response from method EncryptionScopesClient.NewListPager. +type EncryptionScopesClientListResponse struct { + // The list of cognitive services EncryptionScopes. + EncryptionScopeListResult +} + +// LocationBasedModelCapacitiesClientListResponse contains the response from method LocationBasedModelCapacitiesClient.NewListPager. +type LocationBasedModelCapacitiesClientListResponse struct { + // The list of cognitive services accounts operation response. + ModelCapacityListResult +} + +// ManagedNetworkProvisionsClientProvisionManagedNetworkResponse contains the response from method ManagedNetworkProvisionsClient.BeginProvisionManagedNetwork. +type ManagedNetworkProvisionsClientProvisionManagedNetworkResponse struct { + // Status of the Provisioning for the managed network of a cognitive services account. + ManagedNetworkProvisionStatus +} + +// ManagedNetworkSettingsClientDeleteResponse contains the response from method ManagedNetworkSettingsClient.BeginDelete. +type ManagedNetworkSettingsClientDeleteResponse struct { + // placeholder for future response values +} + +// ManagedNetworkSettingsClientGetResponse contains the response from method ManagedNetworkSettingsClient.Get. +type ManagedNetworkSettingsClientGetResponse struct { + // Concrete proxy resource types can be created by aliasing this type using a specific property type. + ManagedNetworkSettingsPropertiesBasicResource +} + +// ManagedNetworkSettingsClientListResponse contains the response from method ManagedNetworkSettingsClient.NewListPager. +type ManagedNetworkSettingsClientListResponse struct { + // List of managed networks of a cognitive services account. + ManagedNetworkListResult +} + +// ManagedNetworkSettingsClientPatchResponse contains the response from method ManagedNetworkSettingsClient.BeginPatch. +type ManagedNetworkSettingsClientPatchResponse struct { + // Concrete proxy resource types can be created by aliasing this type using a specific property type. + ManagedNetworkSettingsPropertiesBasicResource +} + +// ManagedNetworkSettingsClientPutResponse contains the response from method ManagedNetworkSettingsClient.BeginPut. +type ManagedNetworkSettingsClientPutResponse struct { + // Concrete proxy resource types can be created by aliasing this type using a specific property type. + ManagedNetworkSettingsPropertiesBasicResource +} + +// ManagementClientCalculateModelCapacityResponse contains the response from method ManagementClient.CalculateModelCapacity. +type ManagementClientCalculateModelCapacityResponse struct { + // Calculate Model Capacity result. + CalculateModelCapacityResult +} + +// ManagementClientCheckDomainAvailabilityResponse contains the response from method ManagementClient.CheckDomainAvailability. +type ManagementClientCheckDomainAvailabilityResponse struct { + // Domain availability. + DomainAvailability +} + +// ManagementClientCheckSKUAvailabilityResponse contains the response from method ManagementClient.CheckSKUAvailability. +type ManagementClientCheckSKUAvailabilityResponse struct { + // Check SKU availability result list. + SKUAvailabilityListResult +} + +// ModelCapacitiesClientListResponse contains the response from method ModelCapacitiesClient.NewListPager. +type ModelCapacitiesClientListResponse struct { + // The list of cognitive services accounts operation response. + ModelCapacityListResult +} + +// ModelsClientListResponse contains the response from method ModelsClient.NewListPager. +type ModelsClientListResponse struct { + // The list of cognitive services models. + ModelListResult +} + +// NetworkSecurityPerimeterConfigurationsClientGetResponse contains the response from method NetworkSecurityPerimeterConfigurationsClient.Get. +type NetworkSecurityPerimeterConfigurationsClientGetResponse struct { + // NSP Configuration for an Cognitive Services account. + NetworkSecurityPerimeterConfiguration +} + +// NetworkSecurityPerimeterConfigurationsClientListResponse contains the response from method NetworkSecurityPerimeterConfigurationsClient.NewListPager. +type NetworkSecurityPerimeterConfigurationsClientListResponse struct { + // A list of NSP configurations for an Cognitive Services account. + NetworkSecurityPerimeterConfigurationList +} + +// NetworkSecurityPerimeterConfigurationsClientReconcileResponse contains the response from method NetworkSecurityPerimeterConfigurationsClient.BeginReconcile. +type NetworkSecurityPerimeterConfigurationsClientReconcileResponse struct { + // NSP Configuration for an Cognitive Services account. + NetworkSecurityPerimeterConfiguration +} + +// OperationsClientListResponse contains the response from method OperationsClient.NewListPager. +type OperationsClientListResponse struct { + // A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. + OperationListResult +} + +// OutboundRuleClientCreateOrUpdateResponse contains the response from method OutboundRuleClient.BeginCreateOrUpdate. +type OutboundRuleClientCreateOrUpdateResponse struct { + // Concrete proxy resource types can be created by aliasing this type using a specific property type. + OutboundRuleBasicResource +} + +// OutboundRuleClientDeleteResponse contains the response from method OutboundRuleClient.BeginDelete. +type OutboundRuleClientDeleteResponse struct { + // placeholder for future response values +} + +// OutboundRuleClientGetResponse contains the response from method OutboundRuleClient.Get. +type OutboundRuleClientGetResponse struct { + // Concrete proxy resource types can be created by aliasing this type using a specific property type. + OutboundRuleBasicResource +} + +// OutboundRuleClientListResponse contains the response from method OutboundRuleClient.NewListPager. +type OutboundRuleClientListResponse struct { + // List of outbound rules for the managed network of a cognitive services account. + OutboundRuleListResult +} + +// OutboundRulesClientPostResponse contains the response from method OutboundRulesClient.BeginPost. +type OutboundRulesClientPostResponse struct { + // List of outbound rules for the managed network of a cognitive services account. + OutboundRuleListResult +} + +// PrivateEndpointConnectionsClientCreateOrUpdateResponse contains the response from method PrivateEndpointConnectionsClient.BeginCreateOrUpdate. +type PrivateEndpointConnectionsClientCreateOrUpdateResponse struct { + // The Private Endpoint Connection resource. + PrivateEndpointConnection +} + +// PrivateEndpointConnectionsClientDeleteResponse contains the response from method PrivateEndpointConnectionsClient.BeginDelete. +type PrivateEndpointConnectionsClientDeleteResponse struct { + // placeholder for future response values +} + +// PrivateEndpointConnectionsClientGetResponse contains the response from method PrivateEndpointConnectionsClient.Get. +type PrivateEndpointConnectionsClientGetResponse struct { + // The Private Endpoint Connection resource. + PrivateEndpointConnection +} + +// PrivateEndpointConnectionsClientListResponse contains the response from method PrivateEndpointConnectionsClient.List. +type PrivateEndpointConnectionsClientListResponse struct { + // A list of private endpoint connections + PrivateEndpointConnectionListResult +} + +// PrivateLinkResourcesClientListResponse contains the response from method PrivateLinkResourcesClient.List. +type PrivateLinkResourcesClientListResponse struct { + // A list of private link resources + PrivateLinkResourceListResult +} + +// ProjectCapabilityHostsClientCreateOrUpdateResponse contains the response from method ProjectCapabilityHostsClient.BeginCreateOrUpdate. +type ProjectCapabilityHostsClientCreateOrUpdateResponse struct { + // Azure Resource Manager resource envelope for Project CapabilityHost. + ProjectCapabilityHost +} + +// ProjectCapabilityHostsClientDeleteResponse contains the response from method ProjectCapabilityHostsClient.BeginDelete. +type ProjectCapabilityHostsClientDeleteResponse struct { + // placeholder for future response values +} + +// ProjectCapabilityHostsClientGetResponse contains the response from method ProjectCapabilityHostsClient.Get. +type ProjectCapabilityHostsClientGetResponse struct { + // Azure Resource Manager resource envelope for Project CapabilityHost. + ProjectCapabilityHost +} + +// ProjectCapabilityHostsClientListResponse contains the response from method ProjectCapabilityHostsClient.NewListPager. +type ProjectCapabilityHostsClientListResponse struct { + // A paginated list of Project Capability Host entities. + ProjectCapabilityHostResourceArmPaginatedResult +} + +// ProjectConnectionsClientCreateResponse contains the response from method ProjectConnectionsClient.Create. +type ProjectConnectionsClientCreateResponse struct { + // Connection base resource schema. + ConnectionPropertiesV2BasicResource +} + +// ProjectConnectionsClientDeleteResponse contains the response from method ProjectConnectionsClient.Delete. +type ProjectConnectionsClientDeleteResponse struct { + // placeholder for future response values +} + +// ProjectConnectionsClientGetResponse contains the response from method ProjectConnectionsClient.Get. +type ProjectConnectionsClientGetResponse struct { + // Connection base resource schema. + ConnectionPropertiesV2BasicResource +} + +// ProjectConnectionsClientListResponse contains the response from method ProjectConnectionsClient.NewListPager. +type ProjectConnectionsClientListResponse struct { + ConnectionPropertiesV2BasicResourceArmPaginatedResult +} + +// ProjectConnectionsClientUpdateResponse contains the response from method ProjectConnectionsClient.Update. +type ProjectConnectionsClientUpdateResponse struct { + // Connection base resource schema. + ConnectionPropertiesV2BasicResource +} + +// ProjectsClientCreateResponse contains the response from method ProjectsClient.BeginCreate. +type ProjectsClientCreateResponse struct { + // Cognitive Services project is an Azure resource representing the provisioned account's project, it's type, location and + // SKU. + Project +} + +// ProjectsClientDeleteResponse contains the response from method ProjectsClient.BeginDelete. +type ProjectsClientDeleteResponse struct { + // placeholder for future response values +} + +// ProjectsClientGetResponse contains the response from method ProjectsClient.Get. +type ProjectsClientGetResponse struct { + // Cognitive Services project is an Azure resource representing the provisioned account's project, it's type, location and + // SKU. + Project +} + +// ProjectsClientListResponse contains the response from method ProjectsClient.NewListPager. +type ProjectsClientListResponse struct { + // The list of cognitive services projects operation response. + ProjectListResult +} + +// ProjectsClientUpdateResponse contains the response from method ProjectsClient.BeginUpdate. +type ProjectsClientUpdateResponse struct { + // Cognitive Services project is an Azure resource representing the provisioned account's project, it's type, location and + // SKU. + Project +} + +// QuotaTiersClientCreateOrUpdateResponse contains the response from method QuotaTiersClient.CreateOrUpdate. +type QuotaTiersClientCreateOrUpdateResponse struct { + // The quota tier information for the subscription + QuotaTier +} + +// QuotaTiersClientGetResponse contains the response from method QuotaTiersClient.Get. +type QuotaTiersClientGetResponse struct { + // The quota tier information for the subscription + QuotaTier +} + +// QuotaTiersClientListBySubscriptionResponse contains the response from method QuotaTiersClient.NewListBySubscriptionPager. +type QuotaTiersClientListBySubscriptionResponse struct { + // The list of Quota Tiers response. + QuotaTierListResult +} + +// QuotaTiersClientUpdateResponse contains the response from method QuotaTiersClient.Update. +type QuotaTiersClientUpdateResponse struct { + // The quota tier information for the subscription + QuotaTier +} + +// RaiBlocklistItemsClientBatchAddResponse contains the response from method RaiBlocklistItemsClient.BatchAdd. +type RaiBlocklistItemsClientBatchAddResponse struct { + // Cognitive Services RaiBlocklist. + RaiBlocklist +} + +// RaiBlocklistItemsClientBatchDeleteResponse contains the response from method RaiBlocklistItemsClient.BatchDelete. +type RaiBlocklistItemsClientBatchDeleteResponse struct { + // placeholder for future response values +} + +// RaiBlocklistItemsClientCreateOrUpdateResponse contains the response from method RaiBlocklistItemsClient.CreateOrUpdate. +type RaiBlocklistItemsClientCreateOrUpdateResponse struct { + // Cognitive Services RaiBlocklist Item. + RaiBlocklistItem +} + +// RaiBlocklistItemsClientDeleteResponse contains the response from method RaiBlocklistItemsClient.BeginDelete. +type RaiBlocklistItemsClientDeleteResponse struct { + // placeholder for future response values +} + +// RaiBlocklistItemsClientGetResponse contains the response from method RaiBlocklistItemsClient.Get. +type RaiBlocklistItemsClientGetResponse struct { + // Cognitive Services RaiBlocklist Item. + RaiBlocklistItem +} + +// RaiBlocklistItemsClientListResponse contains the response from method RaiBlocklistItemsClient.NewListPager. +type RaiBlocklistItemsClientListResponse struct { + // The list of cognitive services RAI Blocklist Items. + RaiBlockListItemsResult +} + +// RaiBlocklistsClientCreateOrUpdateResponse contains the response from method RaiBlocklistsClient.CreateOrUpdate. +type RaiBlocklistsClientCreateOrUpdateResponse struct { + // Cognitive Services RaiBlocklist. + RaiBlocklist +} + +// RaiBlocklistsClientDeleteResponse contains the response from method RaiBlocklistsClient.BeginDelete. +type RaiBlocklistsClientDeleteResponse struct { + // placeholder for future response values +} + +// RaiBlocklistsClientGetResponse contains the response from method RaiBlocklistsClient.Get. +type RaiBlocklistsClientGetResponse struct { + // Cognitive Services RaiBlocklist. + RaiBlocklist +} + +// RaiBlocklistsClientListResponse contains the response from method RaiBlocklistsClient.NewListPager. +type RaiBlocklistsClientListResponse struct { + // The list of cognitive services RAI Blocklists. + RaiBlockListResult +} + +// RaiContentFiltersClientGetResponse contains the response from method RaiContentFiltersClient.Get. +type RaiContentFiltersClientGetResponse struct { + // Azure OpenAI Content Filter. + RaiContentFilter +} + +// RaiContentFiltersClientListResponse contains the response from method RaiContentFiltersClient.NewListPager. +type RaiContentFiltersClientListResponse struct { + // The list of Content Filters. + RaiContentFilterListResult +} + +// RaiExternalSafetyProviderClientCreateOrUpdateResponse contains the response from method RaiExternalSafetyProviderClient.CreateOrUpdate. +type RaiExternalSafetyProviderClientCreateOrUpdateResponse struct { + // Cognitive Services Rai External Safety provider Schema. + RaiExternalSafetyProviderSchema +} + +// RaiExternalSafetyProviderClientDeleteResponse contains the response from method RaiExternalSafetyProviderClient.BeginDelete. +type RaiExternalSafetyProviderClientDeleteResponse struct { + // placeholder for future response values +} + +// RaiExternalSafetyProviderClientGetResponse contains the response from method RaiExternalSafetyProviderClient.Get. +type RaiExternalSafetyProviderClientGetResponse struct { + // Cognitive Services Rai External Safety provider Schema. + RaiExternalSafetyProviderSchema +} + +// RaiExternalSafetyProvidersClientListResponse contains the response from method RaiExternalSafetyProvidersClient.NewListPager. +type RaiExternalSafetyProvidersClientListResponse struct { + // The list of cognitive services RAI External Safety Providers. + RaiExternalSafetyProviderResult +} + +// RaiPoliciesClientCreateOrUpdateResponse contains the response from method RaiPoliciesClient.CreateOrUpdate. +type RaiPoliciesClientCreateOrUpdateResponse struct { + // Cognitive Services RaiPolicy. + RaiPolicy +} + +// RaiPoliciesClientDeleteResponse contains the response from method RaiPoliciesClient.BeginDelete. +type RaiPoliciesClientDeleteResponse struct { + // placeholder for future response values +} + +// RaiPoliciesClientGetResponse contains the response from method RaiPoliciesClient.Get. +type RaiPoliciesClientGetResponse struct { + // Cognitive Services RaiPolicy. + RaiPolicy +} + +// RaiPoliciesClientListResponse contains the response from method RaiPoliciesClient.NewListPager. +type RaiPoliciesClientListResponse struct { + // The list of cognitive services RaiPolicies. + RaiPolicyListResult +} + +// RaiToolLabelsClientCreateOrUpdateResponse contains the response from method RaiToolLabelsClient.CreateOrUpdate. +type RaiToolLabelsClientCreateOrUpdateResponse struct { + // Cognitive Services RAI Tool Label resource. + RaiToolLabel +} + +// RaiToolLabelsClientDeleteResponse contains the response from method RaiToolLabelsClient.BeginDelete. +type RaiToolLabelsClientDeleteResponse struct { + // placeholder for future response values +} + +// RaiToolLabelsClientGetResponse contains the response from method RaiToolLabelsClient.Get. +type RaiToolLabelsClientGetResponse struct { + // Cognitive Services RAI Tool Label resource. + RaiToolLabel +} + +// RaiToolLabelsClientListResponse contains the response from method RaiToolLabelsClient.NewListPager. +type RaiToolLabelsClientListResponse struct { + // The list of Cognitive Services RAI Tool Labels. + RaiToolLabelResult +} + +// RaiTopicsClientCreateOrUpdateResponse contains the response from method RaiTopicsClient.CreateOrUpdate. +type RaiTopicsClientCreateOrUpdateResponse struct { + // Cognitive Services Rai Topic. + RaiTopic +} + +// RaiTopicsClientDeleteResponse contains the response from method RaiTopicsClient.BeginDelete. +type RaiTopicsClientDeleteResponse struct { + // placeholder for future response values +} + +// RaiTopicsClientGetResponse contains the response from method RaiTopicsClient.Get. +type RaiTopicsClientGetResponse struct { + // Cognitive Services Rai Topic. + RaiTopic +} + +// RaiTopicsClientListResponse contains the response from method RaiTopicsClient.NewListPager. +type RaiTopicsClientListResponse struct { + // The list of cognitive services RAI Topics. + RaiTopicResult +} + +// ResourceSKUsClientListResponse contains the response from method ResourceSKUsClient.NewListPager. +type ResourceSKUsClientListResponse struct { + // The Get Skus operation response. + ResourceSKUListResult +} + +// SubscriptionRaiPolicyClientCreateOrUpdateResponse contains the response from method SubscriptionRaiPolicyClient.CreateOrUpdate. +type SubscriptionRaiPolicyClientCreateOrUpdateResponse struct { + // Cognitive Services RaiPolicy. + RaiPolicy +} + +// SubscriptionRaiPolicyClientDeleteResponse contains the response from method SubscriptionRaiPolicyClient.BeginDelete. +type SubscriptionRaiPolicyClientDeleteResponse struct { + // placeholder for future response values +} + +// SubscriptionRaiPolicyClientGetResponse contains the response from method SubscriptionRaiPolicyClient.Get. +type SubscriptionRaiPolicyClientGetResponse struct { + // Cognitive Services RaiPolicy. + RaiPolicy +} + +// TestRaiExternalSafetyProviderClientCreateOrUpdateResponse contains the response from method TestRaiExternalSafetyProviderClient.CreateOrUpdate. +type TestRaiExternalSafetyProviderClientCreateOrUpdateResponse struct { + // Cognitive Services Rai External Safety provider Schema. + RaiExternalSafetyProviderSchema +} + +// UsagesClientListResponse contains the response from method UsagesClient.NewListPager. +type UsagesClientListResponse struct { + // The response to a list usage request. + UsageListResult +} diff --git a/test/local/armcognitiveservices/zz_subscriptionraipolicy_client.go b/test/local/armcognitiveservices/zz_subscriptionraipolicy_client.go new file mode 100644 index 000000000000..89767b234480 --- /dev/null +++ b/test/local/armcognitiveservices/zz_subscriptionraipolicy_client.go @@ -0,0 +1,229 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// SubscriptionRaiPolicyClient contains the methods for the SubscriptionRaiPolicy group. +// Don't use this type directly, use NewSubscriptionRaiPolicyClient() instead. +// +// Generated from API version 2026-05-01 +type SubscriptionRaiPolicyClient struct { + internal *arm.Client + subscriptionID string +} + +// NewSubscriptionRaiPolicyClient creates a new instance of SubscriptionRaiPolicyClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewSubscriptionRaiPolicyClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SubscriptionRaiPolicyClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SubscriptionRaiPolicyClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Update the state of specified Content Filters associated with the subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// - raiPolicyName - The name of the RaiPolicy associated with the Cognitive Services Account +// - raiPolicy - Properties describing the Content Filters. +// - options - SubscriptionRaiPolicyClientCreateOrUpdateOptions contains the optional parameters for the SubscriptionRaiPolicyClient.CreateOrUpdate +// method. +func (client *SubscriptionRaiPolicyClient) CreateOrUpdate(ctx context.Context, raiPolicyName string, raiPolicy RaiPolicy, options *SubscriptionRaiPolicyClientCreateOrUpdateOptions) (SubscriptionRaiPolicyClientCreateOrUpdateResponse, error) { + var err error + const operationName = "SubscriptionRaiPolicyClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, raiPolicyName, raiPolicy, options) + if err != nil { + return SubscriptionRaiPolicyClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SubscriptionRaiPolicyClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return SubscriptionRaiPolicyClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *SubscriptionRaiPolicyClient) createOrUpdateCreateRequest(ctx context.Context, raiPolicyName string, raiPolicy RaiPolicy, _ *SubscriptionRaiPolicyClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/raiPolicy/{raiPolicyName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if raiPolicyName == "" { + return nil, errors.New("parameter raiPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{raiPolicyName}", url.PathEscape(raiPolicyName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, raiPolicy); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *SubscriptionRaiPolicyClient) createOrUpdateHandleResponse(resp *http.Response) (SubscriptionRaiPolicyClientCreateOrUpdateResponse, error) { + result := SubscriptionRaiPolicyClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RaiPolicy); err != nil { + return SubscriptionRaiPolicyClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// BeginDelete - Deletes the specified Content Filters associated with the subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// - raiPolicyName - The name of the RaiPolicy associated with the Cognitive Services Account +// - options - SubscriptionRaiPolicyClientBeginDeleteOptions contains the optional parameters for the SubscriptionRaiPolicyClient.BeginDelete +// method. +func (client *SubscriptionRaiPolicyClient) BeginDelete(ctx context.Context, raiPolicyName string, options *SubscriptionRaiPolicyClientBeginDeleteOptions) (*runtime.Poller[SubscriptionRaiPolicyClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, raiPolicyName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SubscriptionRaiPolicyClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SubscriptionRaiPolicyClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified Content Filters associated with the subscription. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *SubscriptionRaiPolicyClient) deleteOperation(ctx context.Context, raiPolicyName string, options *SubscriptionRaiPolicyClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "SubscriptionRaiPolicyClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, raiPolicyName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *SubscriptionRaiPolicyClient) deleteCreateRequest(ctx context.Context, raiPolicyName string, _ *SubscriptionRaiPolicyClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/raiPolicy/{raiPolicyName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if raiPolicyName == "" { + return nil, errors.New("parameter raiPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{raiPolicyName}", url.PathEscape(raiPolicyName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Gets the specified Content Filters associated with the Subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// - raiPolicyName - The name of the RaiPolicy associated with the Cognitive Services Account +// - options - SubscriptionRaiPolicyClientGetOptions contains the optional parameters for the SubscriptionRaiPolicyClient.Get +// method. +func (client *SubscriptionRaiPolicyClient) Get(ctx context.Context, raiPolicyName string, options *SubscriptionRaiPolicyClientGetOptions) (SubscriptionRaiPolicyClientGetResponse, error) { + var err error + const operationName = "SubscriptionRaiPolicyClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, raiPolicyName, options) + if err != nil { + return SubscriptionRaiPolicyClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SubscriptionRaiPolicyClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SubscriptionRaiPolicyClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *SubscriptionRaiPolicyClient) getCreateRequest(ctx context.Context, raiPolicyName string, _ *SubscriptionRaiPolicyClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/raiPolicy/{raiPolicyName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if raiPolicyName == "" { + return nil, errors.New("parameter raiPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{raiPolicyName}", url.PathEscape(raiPolicyName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *SubscriptionRaiPolicyClient) getHandleResponse(resp *http.Response) (SubscriptionRaiPolicyClientGetResponse, error) { + result := SubscriptionRaiPolicyClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RaiPolicy); err != nil { + return SubscriptionRaiPolicyClientGetResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_testraiexternalsafetyprovider_client.go b/test/local/armcognitiveservices/zz_testraiexternalsafetyprovider_client.go new file mode 100644 index 000000000000..f9f3367df9d4 --- /dev/null +++ b/test/local/armcognitiveservices/zz_testraiexternalsafetyprovider_client.go @@ -0,0 +1,115 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// TestRaiExternalSafetyProviderClient contains the methods for the TestRaiExternalSafetyProvider group. +// Don't use this type directly, use NewTestRaiExternalSafetyProviderClient() instead. +// +// Generated from API version 2026-05-01 +type TestRaiExternalSafetyProviderClient struct { + internal *arm.Client + subscriptionID string +} + +// NewTestRaiExternalSafetyProviderClient creates a new instance of TestRaiExternalSafetyProviderClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewTestRaiExternalSafetyProviderClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*TestRaiExternalSafetyProviderClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &TestRaiExternalSafetyProviderClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Test the rai safety provider associated with the subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - accountName - The name of Cognitive Services account. +// - safetyProviderName - The name of the Rai External Safety Provider associated with the Cognitive Services Account +// - safetyProvider - Properties describing the rai external safety provider. +// - options - TestRaiExternalSafetyProviderClientCreateOrUpdateOptions contains the optional parameters for the TestRaiExternalSafetyProviderClient.CreateOrUpdate +// method. +func (client *TestRaiExternalSafetyProviderClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, safetyProviderName string, safetyProvider RaiExternalSafetyProviderSchema, options *TestRaiExternalSafetyProviderClientCreateOrUpdateOptions) (TestRaiExternalSafetyProviderClientCreateOrUpdateResponse, error) { + var err error + const operationName = "TestRaiExternalSafetyProviderClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, safetyProviderName, safetyProvider, options) + if err != nil { + return TestRaiExternalSafetyProviderClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TestRaiExternalSafetyProviderClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return TestRaiExternalSafetyProviderClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *TestRaiExternalSafetyProviderClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, safetyProviderName string, safetyProvider RaiExternalSafetyProviderSchema, _ *TestRaiExternalSafetyProviderClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/testRaiExternalSafetyProvider/{safetyProviderName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if safetyProviderName == "" { + return nil, errors.New("parameter safetyProviderName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{safetyProviderName}", url.PathEscape(safetyProviderName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, safetyProvider); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *TestRaiExternalSafetyProviderClient) createOrUpdateHandleResponse(resp *http.Response) (TestRaiExternalSafetyProviderClientCreateOrUpdateResponse, error) { + result := TestRaiExternalSafetyProviderClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RaiExternalSafetyProviderSchema); err != nil { + return TestRaiExternalSafetyProviderClientCreateOrUpdateResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_usages_client.go b/test/local/armcognitiveservices/zz_usages_client.go new file mode 100644 index 000000000000..4396eb2cea3f --- /dev/null +++ b/test/local/armcognitiveservices/zz_usages_client.go @@ -0,0 +1,102 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcognitiveservices + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// UsagesClient contains the methods for the Usages group. +// Don't use this type directly, use NewUsagesClient() instead. +// +// Generated from API version 2026-05-01 +type UsagesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewUsagesClient creates a new instance of UsagesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewUsagesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*UsagesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &UsagesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListPager - Get usages for the requested subscription +// - location - The location name. +// - options - UsagesClientListOptions contains the optional parameters for the UsagesClient.NewListPager method. +func (client *UsagesClient) NewListPager(location string, options *UsagesClientListOptions) *runtime.Pager[UsagesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[UsagesClientListResponse]{ + More: func(page UsagesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *UsagesClientListResponse) (UsagesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "UsagesClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, location, options) + }, nil) + if err != nil { + return UsagesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *UsagesClient) listCreateRequest(ctx context.Context, location string, options *UsagesClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/usages" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + reqQP.Set("api-version", version20260501) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *UsagesClient) listHandleResponse(resp *http.Response) (UsagesClientListResponse, error) { + result := UsagesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.UsageListResult); err != nil { + return UsagesClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armcognitiveservices/zz_version.go b/test/local/armcognitiveservices/zz_version.go new file mode 100644 index 000000000000..e59ac4c15a61 --- /dev/null +++ b/test/local/armcognitiveservices/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package armcognitiveservices + +const ( + moduleName = "armcognitiveservices" + moduleVersion = "v0.1.0" +) diff --git a/test/local/armcommunitymanagement/LICENSE.txt b/test/local/armcommunitymanagement/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/local/armcommunitymanagement/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/local/armcommunitymanagement/fake/zz_communitytrainings_server.go b/test/local/armcommunitymanagement/fake/zz_communitytrainings_server.go new file mode 100644 index 000000000000..c645056d8241 --- /dev/null +++ b/test/local/armcommunitymanagement/fake/zz_communitytrainings_server.go @@ -0,0 +1,370 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcommunitymanagement" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// CommunityTrainingsServer is a fake server for instances of the armcommunitymanagement.CommunityTrainingsClient type. +type CommunityTrainingsServer struct { + // BeginCreate is the fake for method CommunityTrainingsClient.BeginCreate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreate func(ctx context.Context, resourceGroupName string, communityTrainingName string, resource armcommunitymanagement.CommunityTraining, options *armcommunitymanagement.CommunityTrainingsClientBeginCreateOptions) (resp azfake.PollerResponder[armcommunitymanagement.CommunityTrainingsClientCreateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method CommunityTrainingsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, communityTrainingName string, options *armcommunitymanagement.CommunityTrainingsClientBeginDeleteOptions) (resp azfake.PollerResponder[armcommunitymanagement.CommunityTrainingsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method CommunityTrainingsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, communityTrainingName string, options *armcommunitymanagement.CommunityTrainingsClientGetOptions) (resp azfake.Responder[armcommunitymanagement.CommunityTrainingsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method CommunityTrainingsClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armcommunitymanagement.CommunityTrainingsClientListByResourceGroupOptions) (resp azfake.PagerResponder[armcommunitymanagement.CommunityTrainingsClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method CommunityTrainingsClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armcommunitymanagement.CommunityTrainingsClientListBySubscriptionOptions) (resp azfake.PagerResponder[armcommunitymanagement.CommunityTrainingsClientListBySubscriptionResponse]) + + // BeginUpdate is the fake for method CommunityTrainingsClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, communityTrainingName string, properties armcommunitymanagement.CommunityTrainingUpdate, options *armcommunitymanagement.CommunityTrainingsClientBeginUpdateOptions) (resp azfake.PollerResponder[armcommunitymanagement.CommunityTrainingsClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewCommunityTrainingsServerTransport creates a new instance of CommunityTrainingsServerTransport with the provided implementation. +// The returned CommunityTrainingsServerTransport instance is connected to an instance of armcommunitymanagement.CommunityTrainingsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewCommunityTrainingsServerTransport(srv *CommunityTrainingsServer) *CommunityTrainingsServerTransport { + return &CommunityTrainingsServerTransport{ + srv: srv, + beginCreate: newTracker[azfake.PollerResponder[armcommunitymanagement.CommunityTrainingsClientCreateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armcommunitymanagement.CommunityTrainingsClientDeleteResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armcommunitymanagement.CommunityTrainingsClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armcommunitymanagement.CommunityTrainingsClientListBySubscriptionResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armcommunitymanagement.CommunityTrainingsClientUpdateResponse]](), + } +} + +// CommunityTrainingsServerTransport connects instances of armcommunitymanagement.CommunityTrainingsClient to instances of CommunityTrainingsServer. +// Don't use this type directly, use NewCommunityTrainingsServerTransport instead. +type CommunityTrainingsServerTransport struct { + srv *CommunityTrainingsServer + beginCreate *tracker[azfake.PollerResponder[armcommunitymanagement.CommunityTrainingsClientCreateResponse]] + beginDelete *tracker[azfake.PollerResponder[armcommunitymanagement.CommunityTrainingsClientDeleteResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armcommunitymanagement.CommunityTrainingsClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armcommunitymanagement.CommunityTrainingsClientListBySubscriptionResponse]] + beginUpdate *tracker[azfake.PollerResponder[armcommunitymanagement.CommunityTrainingsClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for CommunityTrainingsServerTransport. +func (c *CommunityTrainingsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *CommunityTrainingsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if communityTrainingsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = communityTrainingsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "CommunityTrainingsClient.BeginCreate": + res.resp, res.err = c.dispatchBeginCreate(req) + case "CommunityTrainingsClient.BeginDelete": + res.resp, res.err = c.dispatchBeginDelete(req) + case "CommunityTrainingsClient.Get": + res.resp, res.err = c.dispatchGet(req) + case "CommunityTrainingsClient.NewListByResourceGroupPager": + res.resp, res.err = c.dispatchNewListByResourceGroupPager(req) + case "CommunityTrainingsClient.NewListBySubscriptionPager": + res.resp, res.err = c.dispatchNewListBySubscriptionPager(req) + case "CommunityTrainingsClient.BeginUpdate": + res.resp, res.err = c.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *CommunityTrainingsServerTransport) dispatchBeginCreate(req *http.Request) (*http.Response, error) { + if c.srv.BeginCreate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreate not implemented")} + } + beginCreate := c.beginCreate.get(req) + if beginCreate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Community/communityTrainings/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcommunitymanagement.CommunityTraining](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + communityTrainingNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("communityTrainingName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginCreate(req.Context(), resourceGroupNameParam, communityTrainingNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreate = &respr + c.beginCreate.add(req, beginCreate) + } + + resp, err := server.PollerResponderNext(beginCreate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + c.beginCreate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreate) { + c.beginCreate.remove(req) + } + + return resp, nil +} + +func (c *CommunityTrainingsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if c.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := c.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Community/communityTrainings/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + communityTrainingNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("communityTrainingName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginDelete(req.Context(), resourceGroupNameParam, communityTrainingNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + c.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + c.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + c.beginDelete.remove(req) + } + + return resp, nil +} + +func (c *CommunityTrainingsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if c.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Community/communityTrainings/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + communityTrainingNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("communityTrainingName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.Get(req.Context(), resourceGroupNameParam, communityTrainingNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CommunityTraining, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *CommunityTrainingsServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if c.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := c.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Community/communityTrainings` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := c.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + c.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armcommunitymanagement.CommunityTrainingsClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + c.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + c.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (c *CommunityTrainingsServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if c.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := c.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Community/communityTrainings` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := c.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + c.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armcommunitymanagement.CommunityTrainingsClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + c.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + c.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (c *CommunityTrainingsServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if c.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := c.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Community/communityTrainings/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcommunitymanagement.CommunityTrainingUpdate](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + communityTrainingNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("communityTrainingName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginUpdate(req.Context(), resourceGroupNameParam, communityTrainingNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + c.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + c.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + c.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to CommunityTrainingsServerTransport +var communityTrainingsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcommunitymanagement/fake/zz_internal.go b/test/local/armcommunitymanagement/fake/zz_internal.go new file mode 100644 index 000000000000..590b4d743e97 --- /dev/null +++ b/test/local/armcommunitymanagement/fake/zz_internal.go @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/local/armcommunitymanagement/fake/zz_operations_server.go b/test/local/armcommunitymanagement/fake/zz_operations_server.go new file mode 100644 index 000000000000..6c6dd15e0e96 --- /dev/null +++ b/test/local/armcommunitymanagement/fake/zz_operations_server.go @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcommunitymanagement" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "slices" +) + +// OperationsServer is a fake server for instances of the armcommunitymanagement.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armcommunitymanagement.OperationsClientListOptions) (resp azfake.PagerResponder[armcommunitymanagement.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of armcommunitymanagement.OperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOperationsServerTransport(srv *OperationsServer) *OperationsServerTransport { + return &OperationsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armcommunitymanagement.OperationsClientListResponse]](), + } +} + +// OperationsServerTransport connects instances of armcommunitymanagement.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[armcommunitymanagement.OperationsClientListResponse]] +} + +// Do implements the policy.Transporter interface for OperationsServerTransport. +func (o *OperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if operationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = operationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OperationsClient.NewListPager": + res.resp, res.err = o.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OperationsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := o.newListPager.get(req) + if newListPager == nil { + resp := o.srv.NewListPager(nil) + newListPager = &resp + o.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcommunitymanagement.OperationsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + o.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + o.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OperationsServerTransport +var operationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcommunitymanagement/fake/zz_server_factory.go b/test/local/armcommunitymanagement/fake/zz_server_factory.go new file mode 100644 index 000000000000..4eb667c39075 --- /dev/null +++ b/test/local/armcommunitymanagement/fake/zz_server_factory.go @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armcommunitymanagement.ClientFactory type. +type ServerFactory struct { + // CommunityTrainingsServer contains the fakes for client CommunityTrainingsClient + CommunityTrainingsServer CommunityTrainingsServer + + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armcommunitymanagement.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of armcommunitymanagement.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trCommunityTrainingsServer *CommunityTrainingsServerTransport + trOperationsServer *OperationsServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "CommunityTrainingsClient": + initServer(&s.trMu, &s.trCommunityTrainingsServer, func() *CommunityTrainingsServerTransport { + return NewCommunityTrainingsServerTransport(&s.srv.CommunityTrainingsServer) + }) + resp, err = s.trCommunityTrainingsServer.Do(req) + case "OperationsClient": + initServer(&s.trMu, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + resp, err = s.trOperationsServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} diff --git a/test/local/armcommunitymanagement/go.mod b/test/local/armcommunitymanagement/go.mod new file mode 100644 index 000000000000..236ce316d0a2 --- /dev/null +++ b/test/local/armcommunitymanagement/go.mod @@ -0,0 +1,11 @@ +module armcommunitymanagement + +go 1.25.0 + +require github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect +) diff --git a/test/local/armcommunitymanagement/go.sum b/test/local/armcommunitymanagement/go.sum new file mode 100644 index 000000000000..3fdb64caf441 --- /dev/null +++ b/test/local/armcommunitymanagement/go.sum @@ -0,0 +1,16 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/local/armcommunitymanagement/testdata/_metadata.json b/test/local/armcommunitymanagement/testdata/_metadata.json new file mode 100644 index 000000000000..d9a04ddc4395 --- /dev/null +++ b/test/local/armcommunitymanagement/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Microsoft.Community": "2023-11-01" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/local/armcommunitymanagement/zz_client_factory.go b/test/local/armcommunitymanagement/zz_client_factory.go new file mode 100644 index 000000000000..d1c96181be50 --- /dev/null +++ b/test/local/armcommunitymanagement/zz_client_factory.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcommunitymanagement + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + subscriptionID string + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, + internal: internal, + }, nil +} + +// NewCommunityTrainingsClient creates a new instance of CommunityTrainingsClient. +func (c *ClientFactory) NewCommunityTrainingsClient() *CommunityTrainingsClient { + return &CommunityTrainingsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: c.internal, + } +} diff --git a/test/local/armcommunitymanagement/zz_communitytrainings_client.go b/test/local/armcommunitymanagement/zz_communitytrainings_client.go new file mode 100644 index 000000000000..20ed3d9cb84a --- /dev/null +++ b/test/local/armcommunitymanagement/zz_communitytrainings_client.go @@ -0,0 +1,441 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcommunitymanagement + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// CommunityTrainingsClient contains the methods for the CommunityTrainings group. +// Don't use this type directly, use NewCommunityTrainingsClient() instead. +// +// Generated from API version 2023-11-01 +type CommunityTrainingsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewCommunityTrainingsClient creates a new instance of CommunityTrainingsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewCommunityTrainingsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CommunityTrainingsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CommunityTrainingsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreate - Create a CommunityTraining +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - communityTrainingName - The name of the Community Training Resource +// - resource - Resource create parameters. +// - options - CommunityTrainingsClientBeginCreateOptions contains the optional parameters for the CommunityTrainingsClient.BeginCreate +// method. +func (client *CommunityTrainingsClient) BeginCreate(ctx context.Context, resourceGroupName string, communityTrainingName string, resource CommunityTraining, options *CommunityTrainingsClientBeginCreateOptions) (*runtime.Poller[CommunityTrainingsClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, resourceGroupName, communityTrainingName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CommunityTrainingsClientCreateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CommunityTrainingsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Create a CommunityTraining +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CommunityTrainingsClient) create(ctx context.Context, resourceGroupName string, communityTrainingName string, resource CommunityTraining, options *CommunityTrainingsClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "CommunityTrainingsClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, communityTrainingName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *CommunityTrainingsClient) createCreateRequest(ctx context.Context, resourceGroupName string, communityTrainingName string, resource CommunityTraining, _ *CommunityTrainingsClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Community/communityTrainings/{communityTrainingName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if communityTrainingName == "" { + return nil, errors.New("parameter communityTrainingName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{communityTrainingName}", url.PathEscape(communityTrainingName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a CommunityTraining +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - communityTrainingName - The name of the Community Training Resource +// - options - CommunityTrainingsClientBeginDeleteOptions contains the optional parameters for the CommunityTrainingsClient.BeginDelete +// method. +func (client *CommunityTrainingsClient) BeginDelete(ctx context.Context, resourceGroupName string, communityTrainingName string, options *CommunityTrainingsClientBeginDeleteOptions) (*runtime.Poller[CommunityTrainingsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, communityTrainingName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CommunityTrainingsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CommunityTrainingsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a CommunityTraining +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CommunityTrainingsClient) deleteOperation(ctx context.Context, resourceGroupName string, communityTrainingName string, options *CommunityTrainingsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "CommunityTrainingsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, communityTrainingName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *CommunityTrainingsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, communityTrainingName string, _ *CommunityTrainingsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Community/communityTrainings/{communityTrainingName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if communityTrainingName == "" { + return nil, errors.New("parameter communityTrainingName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{communityTrainingName}", url.PathEscape(communityTrainingName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a CommunityTraining +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - communityTrainingName - The name of the Community Training Resource +// - options - CommunityTrainingsClientGetOptions contains the optional parameters for the CommunityTrainingsClient.Get method. +func (client *CommunityTrainingsClient) Get(ctx context.Context, resourceGroupName string, communityTrainingName string, options *CommunityTrainingsClientGetOptions) (CommunityTrainingsClientGetResponse, error) { + var err error + const operationName = "CommunityTrainingsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, communityTrainingName, options) + if err != nil { + return CommunityTrainingsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CommunityTrainingsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CommunityTrainingsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *CommunityTrainingsClient) getCreateRequest(ctx context.Context, resourceGroupName string, communityTrainingName string, _ *CommunityTrainingsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Community/communityTrainings/{communityTrainingName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if communityTrainingName == "" { + return nil, errors.New("parameter communityTrainingName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{communityTrainingName}", url.PathEscape(communityTrainingName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *CommunityTrainingsClient) getHandleResponse(resp *http.Response) (CommunityTrainingsClientGetResponse, error) { + result := CommunityTrainingsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CommunityTraining); err != nil { + return CommunityTrainingsClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - List CommunityTraining resources by resource group +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - CommunityTrainingsClientListByResourceGroupOptions contains the optional parameters for the CommunityTrainingsClient.NewListByResourceGroupPager +// method. +func (client *CommunityTrainingsClient) NewListByResourceGroupPager(resourceGroupName string, options *CommunityTrainingsClientListByResourceGroupOptions) *runtime.Pager[CommunityTrainingsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[CommunityTrainingsClientListByResourceGroupResponse]{ + More: func(page CommunityTrainingsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CommunityTrainingsClientListByResourceGroupResponse) (CommunityTrainingsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CommunityTrainingsClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return CommunityTrainingsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *CommunityTrainingsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *CommunityTrainingsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Community/communityTrainings" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *CommunityTrainingsClient) listByResourceGroupHandleResponse(resp *http.Response) (CommunityTrainingsClientListByResourceGroupResponse, error) { + result := CommunityTrainingsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CommunityTrainingListResult); err != nil { + return CommunityTrainingsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - List CommunityTraining resources by subscription ID +// - options - CommunityTrainingsClientListBySubscriptionOptions contains the optional parameters for the CommunityTrainingsClient.NewListBySubscriptionPager +// method. +func (client *CommunityTrainingsClient) NewListBySubscriptionPager(options *CommunityTrainingsClientListBySubscriptionOptions) *runtime.Pager[CommunityTrainingsClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[CommunityTrainingsClientListBySubscriptionResponse]{ + More: func(page CommunityTrainingsClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CommunityTrainingsClientListBySubscriptionResponse) (CommunityTrainingsClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CommunityTrainingsClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return CommunityTrainingsClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *CommunityTrainingsClient) listBySubscriptionCreateRequest(ctx context.Context, _ *CommunityTrainingsClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Community/communityTrainings" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *CommunityTrainingsClient) listBySubscriptionHandleResponse(resp *http.Response) (CommunityTrainingsClientListBySubscriptionResponse, error) { + result := CommunityTrainingsClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CommunityTrainingListResult); err != nil { + return CommunityTrainingsClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update a CommunityTraining +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - communityTrainingName - The name of the Community Training Resource +// - properties - The resource properties to be updated. +// - options - CommunityTrainingsClientBeginUpdateOptions contains the optional parameters for the CommunityTrainingsClient.BeginUpdate +// method. +func (client *CommunityTrainingsClient) BeginUpdate(ctx context.Context, resourceGroupName string, communityTrainingName string, properties CommunityTrainingUpdate, options *CommunityTrainingsClientBeginUpdateOptions) (*runtime.Poller[CommunityTrainingsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, communityTrainingName, properties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CommunityTrainingsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CommunityTrainingsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a CommunityTraining +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CommunityTrainingsClient) update(ctx context.Context, resourceGroupName string, communityTrainingName string, properties CommunityTrainingUpdate, options *CommunityTrainingsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "CommunityTrainingsClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, communityTrainingName, properties, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *CommunityTrainingsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, communityTrainingName string, properties CommunityTrainingUpdate, _ *CommunityTrainingsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Community/communityTrainings/{communityTrainingName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if communityTrainingName == "" { + return nil, errors.New("parameter communityTrainingName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{communityTrainingName}", url.PathEscape(communityTrainingName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armcommunitymanagement/zz_constants.go b/test/local/armcommunitymanagement/zz_constants.go new file mode 100644 index 000000000000..b7b661d8a94c --- /dev/null +++ b/test/local/armcommunitymanagement/zz_constants.go @@ -0,0 +1,128 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcommunitymanagement + +const ( + version20231101 string = "2023-11-01" +) + +// ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +type ActionType string + +const ( + // ActionTypeInternal - Actions are for internal-only APIs. + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// Origin - The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default +// value is "user,system" +type Origin string + +const ( + // OriginSystem - Indicates the operation is initiated by a system. + OriginSystem Origin = "system" + // OriginUser - Indicates the operation is initiated by a user. + OriginUser Origin = "user" + // OriginUserSystem - Indicates the operation is initiated by a user or system. + OriginUserSystem Origin = "user,system" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginSystem, + OriginUser, + OriginUserSystem, + } +} + +// ProvisioningState - The status of the current operation. +type ProvisioningState string + +const ( + // ProvisioningStateAccepted - Change accepted for processing + ProvisioningStateAccepted ProvisioningState = "Accepted" + // ProvisioningStateCanceled - Resource creation was canceled. + ProvisioningStateCanceled ProvisioningState = "Canceled" + // ProvisioningStateDeleting - Deletion in progress + ProvisioningStateDeleting ProvisioningState = "Deleting" + // ProvisioningStateFailed - Resource creation failed. + ProvisioningStateFailed ProvisioningState = "Failed" + // ProvisioningStateProvisioning - Initial provisioning in progress + ProvisioningStateProvisioning ProvisioningState = "Provisioning" + // ProvisioningStateSucceeded - Resource has been created. + ProvisioningStateSucceeded ProvisioningState = "Succeeded" + // ProvisioningStateUpdating - Update in progress + ProvisioningStateUpdating ProvisioningState = "Updating" +) + +// PossibleProvisioningStateValues returns the possible values for the ProvisioningState const type. +func PossibleProvisioningStateValues() []ProvisioningState { + return []ProvisioningState{ + ProvisioningStateAccepted, + ProvisioningStateCanceled, + ProvisioningStateDeleting, + ProvisioningStateFailed, + ProvisioningStateProvisioning, + ProvisioningStateSucceeded, + ProvisioningStateUpdating, + } +} + +// SKUTier - This field is required to be implemented by the Resource Provider if the service has more than one tier, but +// is not required on a PUT. +type SKUTier string + +const ( + // SKUTierBasic - The Basic service tier. + SKUTierBasic SKUTier = "Basic" + // SKUTierFree - The Free service tier. + SKUTierFree SKUTier = "Free" + // SKUTierPremium - The Premium service tier. + SKUTierPremium SKUTier = "Premium" + // SKUTierStandard - The Standard service tier. + SKUTierStandard SKUTier = "Standard" +) + +// PossibleSKUTierValues returns the possible values for the SKUTier const type. +func PossibleSKUTierValues() []SKUTier { + return []SKUTier{ + SKUTierBasic, + SKUTierFree, + SKUTierPremium, + SKUTierStandard, + } +} diff --git a/test/local/armcommunitymanagement/zz_models.go b/test/local/armcommunitymanagement/zz_models.go new file mode 100644 index 000000000000..35e6c58fe534 --- /dev/null +++ b/test/local/armcommunitymanagement/zz_models.go @@ -0,0 +1,211 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcommunitymanagement + +import "time" + +// CommunityTraining - A CommunityProviderHub resource +type CommunityTraining struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *CommunityTrainingProperties + + // The SKU (Stock Keeping Unit) assigned to this resource. + SKU *SKU + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// CommunityTrainingListResult - The response of a CommunityTraining list operation. +type CommunityTrainingListResult struct { + // REQUIRED; The CommunityTraining items on this page + Value []*CommunityTraining + + // The link to the next page of items + NextLink *string +} + +// CommunityTrainingProperties - Details of the Community CommunityTraining. +type CommunityTrainingProperties struct { + // REQUIRED; To indicate whether the Community Training instance has Disaster Recovery enabled + DisasterRecoveryEnabled *bool + + // REQUIRED; The identity configuration of the Community Training resource + IdentityConfiguration *IdentityConfigurationProperties + + // REQUIRED; The email address of the portal admin + PortalAdminEmailAddress *string + + // REQUIRED; The portal name (website name) of the Community Training instance + PortalName *string + + // REQUIRED; The email address of the portal owner. Will be used as the primary contact + PortalOwnerEmailAddress *string + + // REQUIRED; The organization name of the portal owner + PortalOwnerOrganizationName *string + + // REQUIRED; To indicate whether the Community Training instance has Zone Redundancy enabled + ZoneRedundancyEnabled *bool + + // READ-ONLY; The status of the last operation. + ProvisioningState *ProvisioningState +} + +// CommunityTrainingUpdate - The type used for update operations of the CommunityTraining. +type CommunityTrainingUpdate struct { + // The resource-specific properties for this resource. + Properties *CommunityTrainingUpdateProperties + + // The SKU (Stock Keeping Unit) assigned to this resource. + SKU *SKU + + // Resource tags. + Tags map[string]*string +} + +// CommunityTrainingUpdateProperties - The updatable properties of the CommunityTraining. +type CommunityTrainingUpdateProperties struct { + // The identity configuration of the Community Training resource + IdentityConfiguration *IdentityConfigurationProperties +} + +// IdentityConfigurationProperties - Details of the Community CommunityTraining Identity Configuration +type IdentityConfigurationProperties struct { + // REQUIRED; The clientId of the application registered in the selected identity provider for the Community Training Resource + ClientID *string + + // REQUIRED; The client secret of the application registered in the selected identity provider for the Community Training + // Resource + ClientSecret *string + + // REQUIRED; The domain name of the selected identity provider for the Community Training Resource + DomainName *string + + // REQUIRED; The identity type of the Community Training Resource + IdentityType *string + + // REQUIRED; The tenantId of the selected identity provider for the Community Training Resource + TenantID *string + + // The name of the authentication policy registered in ADB2C for the Community Training Resource + B2CAuthenticationPolicy *string + + // The name of the password reset policy registered in ADB2C for the Community Training Resource + B2CPasswordResetPolicy *string + + // The custom login parameters for the Community Training Resource + CustomLoginParameters *string + + // To indicate whether the Community Training Resource has Teams enabled + TeamsEnabled *bool +} + +// Operation - REST API Operation +// +// Details of a REST API operation, returned from the Resource Provider Operations API +type Operation struct { + // Localized display information for this particular operation. + Display *OperationDisplay + + // READ-ONLY; Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + ActionType *ActionType + + // READ-ONLY; Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure + // Resource Manager/control-plane operations. + IsDataAction *bool + + // READ-ONLY; The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + // "Microsoft.Compute/virtualMachines/capture/action" + Name *string + + // READ-ONLY; The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default + // value is "user,system" + Origin *Origin +} + +// OperationDisplay - Localized display information for an operation. +type OperationDisplay struct { + // READ-ONLY; The short, localized friendly description of the operation; suitable for tool tips and detailed views. + Description *string + + // READ-ONLY; The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual + // Machine", "Restart Virtual Machine". + Operation *string + + // READ-ONLY; The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft + // Compute". + Provider *string + + // READ-ONLY; The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job + // Schedule Collections". + Resource *string +} + +// OperationListResult - A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to +// get the next set of results. +type OperationListResult struct { + // REQUIRED; The Operation items on this page + Value []*Operation + + // The link to the next page of items + NextLink *string +} + +// SKU - The resource model definition representing SKU +type SKU struct { + // REQUIRED; The name of the SKU. Ex - P3. It is typically a letter+number code + Name *string + + // If the SKU supports scale out/in then the capacity integer should be included. If scale out/in is not possible for the + // resource this may be omitted. + Capacity *int32 + + // If the service has different generations of hardware, for the same SKU, then that can be captured here. + Family *string + + // The SKU size. When the name field is the combination of tier and some other value, this would be the standalone code. + Size *string + + // This field is required to be implemented by the Resource Provider if the service has more than one tier, but is not required + // on a PUT. + Tier *SKUTier +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time + + // The identity that created the resource. + CreatedBy *string + + // The type of identity that created the resource. + CreatedByType *CreatedByType + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time + + // The identity that last modified the resource. + LastModifiedBy *string + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType +} diff --git a/test/local/armcommunitymanagement/zz_models_serde.go b/test/local/armcommunitymanagement/zz_models_serde.go new file mode 100644 index 000000000000..79e24da75fbd --- /dev/null +++ b/test/local/armcommunitymanagement/zz_models_serde.go @@ -0,0 +1,527 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcommunitymanagement + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type CommunityTraining. +func (c CommunityTraining) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", c.ID) + populate(objectMap, "location", c.Location) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "sku", c.SKU) + populate(objectMap, "systemData", c.SystemData) + populate(objectMap, "tags", c.Tags) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CommunityTraining. +func (c *CommunityTraining) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &c.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &c.SKU) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &c.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &c.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CommunityTrainingListResult. +func (c CommunityTrainingListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", c.NextLink) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CommunityTrainingListResult. +func (c *CommunityTrainingListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &c.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &c.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CommunityTrainingProperties. +func (c CommunityTrainingProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "disasterRecoveryEnabled", c.DisasterRecoveryEnabled) + populate(objectMap, "identityConfiguration", c.IdentityConfiguration) + populate(objectMap, "portalAdminEmailAddress", c.PortalAdminEmailAddress) + populate(objectMap, "portalName", c.PortalName) + populate(objectMap, "portalOwnerEmailAddress", c.PortalOwnerEmailAddress) + populate(objectMap, "portalOwnerOrganizationName", c.PortalOwnerOrganizationName) + populate(objectMap, "provisioningState", c.ProvisioningState) + populate(objectMap, "zoneRedundancyEnabled", c.ZoneRedundancyEnabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CommunityTrainingProperties. +func (c *CommunityTrainingProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "disasterRecoveryEnabled": + err = unpopulate(val, "DisasterRecoveryEnabled", &c.DisasterRecoveryEnabled) + delete(rawMsg, key) + case "identityConfiguration": + err = unpopulate(val, "IdentityConfiguration", &c.IdentityConfiguration) + delete(rawMsg, key) + case "portalAdminEmailAddress": + err = unpopulate(val, "PortalAdminEmailAddress", &c.PortalAdminEmailAddress) + delete(rawMsg, key) + case "portalName": + err = unpopulate(val, "PortalName", &c.PortalName) + delete(rawMsg, key) + case "portalOwnerEmailAddress": + err = unpopulate(val, "PortalOwnerEmailAddress", &c.PortalOwnerEmailAddress) + delete(rawMsg, key) + case "portalOwnerOrganizationName": + err = unpopulate(val, "PortalOwnerOrganizationName", &c.PortalOwnerOrganizationName) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &c.ProvisioningState) + delete(rawMsg, key) + case "zoneRedundancyEnabled": + err = unpopulate(val, "ZoneRedundancyEnabled", &c.ZoneRedundancyEnabled) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CommunityTrainingUpdate. +func (c CommunityTrainingUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "sku", c.SKU) + populate(objectMap, "tags", c.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CommunityTrainingUpdate. +func (c *CommunityTrainingUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &c.SKU) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &c.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CommunityTrainingUpdateProperties. +func (c CommunityTrainingUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identityConfiguration", c.IdentityConfiguration) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CommunityTrainingUpdateProperties. +func (c *CommunityTrainingUpdateProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "identityConfiguration": + err = unpopulate(val, "IdentityConfiguration", &c.IdentityConfiguration) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type IdentityConfigurationProperties. +func (i IdentityConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "b2cAuthenticationPolicy", i.B2CAuthenticationPolicy) + populate(objectMap, "b2cPasswordResetPolicy", i.B2CPasswordResetPolicy) + populate(objectMap, "clientId", i.ClientID) + populate(objectMap, "clientSecret", i.ClientSecret) + populate(objectMap, "customLoginParameters", i.CustomLoginParameters) + populate(objectMap, "domainName", i.DomainName) + populate(objectMap, "identityType", i.IdentityType) + populate(objectMap, "teamsEnabled", i.TeamsEnabled) + populate(objectMap, "tenantId", i.TenantID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IdentityConfigurationProperties. +func (i *IdentityConfigurationProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "b2cAuthenticationPolicy": + err = unpopulate(val, "B2CAuthenticationPolicy", &i.B2CAuthenticationPolicy) + delete(rawMsg, key) + case "b2cPasswordResetPolicy": + err = unpopulate(val, "B2CPasswordResetPolicy", &i.B2CPasswordResetPolicy) + delete(rawMsg, key) + case "clientId": + err = unpopulate(val, "ClientID", &i.ClientID) + delete(rawMsg, key) + case "clientSecret": + err = unpopulate(val, "ClientSecret", &i.ClientSecret) + delete(rawMsg, key) + case "customLoginParameters": + err = unpopulate(val, "CustomLoginParameters", &i.CustomLoginParameters) + delete(rawMsg, key) + case "domainName": + err = unpopulate(val, "DomainName", &i.DomainName) + delete(rawMsg, key) + case "identityType": + err = unpopulate(val, "IdentityType", &i.IdentityType) + delete(rawMsg, key) + case "teamsEnabled": + err = unpopulate(val, "TeamsEnabled", &i.TeamsEnabled) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &i.TenantID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Operation. +func (o Operation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionType", o.ActionType) + populate(objectMap, "display", o.Display) + populate(objectMap, "isDataAction", o.IsDataAction) + populate(objectMap, "name", o.Name) + populate(objectMap, "origin", o.Origin) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Operation. +func (o *Operation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionType": + err = unpopulate(val, "ActionType", &o.ActionType) + delete(rawMsg, key) + case "display": + err = unpopulate(val, "Display", &o.Display) + delete(rawMsg, key) + case "isDataAction": + err = unpopulate(val, "IsDataAction", &o.IsDataAction) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "origin": + err = unpopulate(val, "Origin", &o.Origin) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationDisplay. +func (o OperationDisplay) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", o.Description) + populate(objectMap, "operation", o.Operation) + populate(objectMap, "provider", o.Provider) + populate(objectMap, "resource", o.Resource) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationDisplay. +func (o *OperationDisplay) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &o.Description) + delete(rawMsg, key) + case "operation": + err = unpopulate(val, "Operation", &o.Operation) + delete(rawMsg, key) + case "provider": + err = unpopulate(val, "Provider", &o.Provider) + delete(rawMsg, key) + case "resource": + err = unpopulate(val, "Resource", &o.Resource) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationListResult. +func (o *OperationListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &o.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SKU. +func (s SKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "capacity", s.Capacity) + populate(objectMap, "family", s.Family) + populate(objectMap, "name", s.Name) + populate(objectMap, "size", s.Size) + populate(objectMap, "tier", s.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SKU. +func (s *SKU) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "capacity": + err = unpopulate(val, "Capacity", &s.Capacity) + delete(rawMsg, key) + case "family": + err = unpopulate(val, "Family", &s.Family) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "size": + err = unpopulate(val, "Size", &s.Size) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &s.Tier) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateTime[datetime.RFC3339](objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateTime[datetime.RFC3339](val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateTime[datetime.RFC3339](val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/local/armcommunitymanagement/zz_operations_client.go b/test/local/armcommunitymanagement/zz_operations_client.go new file mode 100644 index 000000000000..0667aef3880f --- /dev/null +++ b/test/local/armcommunitymanagement/zz_operations_client.go @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcommunitymanagement + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +// +// Generated from API version 2023-11-01 +type OperationsClient struct { + internal *arm.Client +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*OperationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OperationsClient{ + internal: cl, + } + return client, nil +} + +// NewListPager - List the operations for the provider +// - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ + More: func(page OperationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OperationsClientListResponse) (OperationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OperationsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return OperationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, _ *OperationsClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Community/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20231101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsClientListResponse, error) { + result := OperationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armcommunitymanagement/zz_options.go b/test/local/armcommunitymanagement/zz_options.go new file mode 100644 index 000000000000..66e1247f6ca0 --- /dev/null +++ b/test/local/armcommunitymanagement/zz_options.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcommunitymanagement + +// CommunityTrainingsClientBeginCreateOptions contains the optional parameters for the CommunityTrainingsClient.BeginCreate +// method. +type CommunityTrainingsClientBeginCreateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CommunityTrainingsClientBeginDeleteOptions contains the optional parameters for the CommunityTrainingsClient.BeginDelete +// method. +type CommunityTrainingsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CommunityTrainingsClientBeginUpdateOptions contains the optional parameters for the CommunityTrainingsClient.BeginUpdate +// method. +type CommunityTrainingsClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CommunityTrainingsClientGetOptions contains the optional parameters for the CommunityTrainingsClient.Get method. +type CommunityTrainingsClientGetOptions struct { + // placeholder for future optional parameters +} + +// CommunityTrainingsClientListByResourceGroupOptions contains the optional parameters for the CommunityTrainingsClient.NewListByResourceGroupPager +// method. +type CommunityTrainingsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// CommunityTrainingsClientListBySubscriptionOptions contains the optional parameters for the CommunityTrainingsClient.NewListBySubscriptionPager +// method. +type CommunityTrainingsClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} diff --git a/test/local/armcommunitymanagement/zz_responses.go b/test/local/armcommunitymanagement/zz_responses.go new file mode 100644 index 000000000000..7e5d9ea0ec35 --- /dev/null +++ b/test/local/armcommunitymanagement/zz_responses.go @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcommunitymanagement + +// CommunityTrainingsClientCreateResponse contains the response from method CommunityTrainingsClient.BeginCreate. +type CommunityTrainingsClientCreateResponse struct { + // A CommunityProviderHub resource + CommunityTraining +} + +// CommunityTrainingsClientDeleteResponse contains the response from method CommunityTrainingsClient.BeginDelete. +type CommunityTrainingsClientDeleteResponse struct { + // placeholder for future response values +} + +// CommunityTrainingsClientGetResponse contains the response from method CommunityTrainingsClient.Get. +type CommunityTrainingsClientGetResponse struct { + // A CommunityProviderHub resource + CommunityTraining +} + +// CommunityTrainingsClientListByResourceGroupResponse contains the response from method CommunityTrainingsClient.NewListByResourceGroupPager. +type CommunityTrainingsClientListByResourceGroupResponse struct { + // The response of a CommunityTraining list operation. + CommunityTrainingListResult +} + +// CommunityTrainingsClientListBySubscriptionResponse contains the response from method CommunityTrainingsClient.NewListBySubscriptionPager. +type CommunityTrainingsClientListBySubscriptionResponse struct { + // The response of a CommunityTraining list operation. + CommunityTrainingListResult +} + +// CommunityTrainingsClientUpdateResponse contains the response from method CommunityTrainingsClient.BeginUpdate. +type CommunityTrainingsClientUpdateResponse struct { + // A CommunityProviderHub resource + CommunityTraining +} + +// OperationsClientListResponse contains the response from method OperationsClient.NewListPager. +type OperationsClientListResponse struct { + // A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. + OperationListResult +} diff --git a/test/local/armcommunitymanagement/zz_version.go b/test/local/armcommunitymanagement/zz_version.go new file mode 100644 index 000000000000..f1e2108eb577 --- /dev/null +++ b/test/local/armcommunitymanagement/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package armcommunitymanagement + +const ( + moduleName = "armcommunitymanagement" + moduleVersion = "v0.1.0" +) diff --git a/test/local/armcomputeschedule/LICENSE.txt b/test/local/armcomputeschedule/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/local/armcomputeschedule/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/local/armcomputeschedule/fake/zz_internal.go b/test/local/armcomputeschedule/fake/zz_internal.go new file mode 100644 index 000000000000..590b4d743e97 --- /dev/null +++ b/test/local/armcomputeschedule/fake/zz_internal.go @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/local/armcomputeschedule/fake/zz_occurrenceextension_server.go b/test/local/armcomputeschedule/fake/zz_occurrenceextension_server.go new file mode 100644 index 000000000000..8298254ee3b9 --- /dev/null +++ b/test/local/armcomputeschedule/fake/zz_occurrenceextension_server.go @@ -0,0 +1,125 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcomputeschedule" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// OccurrenceExtensionServer is a fake server for instances of the armcomputeschedule.OccurrenceExtensionClient type. +type OccurrenceExtensionServer struct { + // NewListOccurrenceByVMsPager is the fake for method OccurrenceExtensionClient.NewListOccurrenceByVMsPager + // HTTP status codes to indicate success: http.StatusOK + NewListOccurrenceByVMsPager func(resourceURI string, options *armcomputeschedule.OccurrenceExtensionClientListOccurrenceByVMsOptions) (resp azfake.PagerResponder[armcomputeschedule.OccurrenceExtensionClientListOccurrenceByVMsResponse]) +} + +// NewOccurrenceExtensionServerTransport creates a new instance of OccurrenceExtensionServerTransport with the provided implementation. +// The returned OccurrenceExtensionServerTransport instance is connected to an instance of armcomputeschedule.OccurrenceExtensionClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOccurrenceExtensionServerTransport(srv *OccurrenceExtensionServer) *OccurrenceExtensionServerTransport { + return &OccurrenceExtensionServerTransport{ + srv: srv, + newListOccurrenceByVMsPager: newTracker[azfake.PagerResponder[armcomputeschedule.OccurrenceExtensionClientListOccurrenceByVMsResponse]](), + } +} + +// OccurrenceExtensionServerTransport connects instances of armcomputeschedule.OccurrenceExtensionClient to instances of OccurrenceExtensionServer. +// Don't use this type directly, use NewOccurrenceExtensionServerTransport instead. +type OccurrenceExtensionServerTransport struct { + srv *OccurrenceExtensionServer + newListOccurrenceByVMsPager *tracker[azfake.PagerResponder[armcomputeschedule.OccurrenceExtensionClientListOccurrenceByVMsResponse]] +} + +// Do implements the policy.Transporter interface for OccurrenceExtensionServerTransport. +func (o *OccurrenceExtensionServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OccurrenceExtensionServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if occurrenceExtensionServerTransportInterceptor != nil { + res.resp, res.err, intercepted = occurrenceExtensionServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OccurrenceExtensionClient.NewListOccurrenceByVMsPager": + res.resp, res.err = o.dispatchNewListOccurrenceByVMsPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OccurrenceExtensionServerTransport) dispatchNewListOccurrenceByVMsPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListOccurrenceByVMsPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListOccurrenceByVMsPager not implemented")} + } + newListOccurrenceByVMsPager := o.newListOccurrenceByVMsPager.get(req) + if newListOccurrenceByVMsPager == nil { + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/associatedOccurrences` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + resp := o.srv.NewListOccurrenceByVMsPager(resourceURIParam, nil) + newListOccurrenceByVMsPager = &resp + o.newListOccurrenceByVMsPager.add(req, newListOccurrenceByVMsPager) + server.PagerResponderInjectNextLinks(newListOccurrenceByVMsPager, req, func(page *armcomputeschedule.OccurrenceExtensionClientListOccurrenceByVMsResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListOccurrenceByVMsPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + o.newListOccurrenceByVMsPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListOccurrenceByVMsPager) { + o.newListOccurrenceByVMsPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OccurrenceExtensionServerTransport +var occurrenceExtensionServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcomputeschedule/fake/zz_occurrences_server.go b/test/local/armcomputeschedule/fake/zz_occurrences_server.go new file mode 100644 index 000000000000..46b888274206 --- /dev/null +++ b/test/local/armcomputeschedule/fake/zz_occurrences_server.go @@ -0,0 +1,333 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcomputeschedule" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// OccurrencesServer is a fake server for instances of the armcomputeschedule.OccurrencesClient type. +type OccurrencesServer struct { + // Cancel is the fake for method OccurrencesClient.Cancel + // HTTP status codes to indicate success: http.StatusOK + Cancel func(ctx context.Context, resourceGroupName string, scheduledActionName string, occurrenceID string, body armcomputeschedule.CancelOccurrenceRequest, options *armcomputeschedule.OccurrencesClientCancelOptions) (resp azfake.Responder[armcomputeschedule.OccurrencesClientCancelResponse], errResp azfake.ErrorResponder) + + // BeginDelay is the fake for method OccurrencesClient.BeginDelay + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginDelay func(ctx context.Context, resourceGroupName string, scheduledActionName string, occurrenceID string, body armcomputeschedule.DelayRequest, options *armcomputeschedule.OccurrencesClientBeginDelayOptions) (resp azfake.PollerResponder[armcomputeschedule.OccurrencesClientDelayResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method OccurrencesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, scheduledActionName string, occurrenceID string, options *armcomputeschedule.OccurrencesClientGetOptions) (resp azfake.Responder[armcomputeschedule.OccurrencesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByScheduledActionPager is the fake for method OccurrencesClient.NewListByScheduledActionPager + // HTTP status codes to indicate success: http.StatusOK + NewListByScheduledActionPager func(resourceGroupName string, scheduledActionName string, options *armcomputeschedule.OccurrencesClientListByScheduledActionOptions) (resp azfake.PagerResponder[armcomputeschedule.OccurrencesClientListByScheduledActionResponse]) + + // NewListResourcesPager is the fake for method OccurrencesClient.NewListResourcesPager + // HTTP status codes to indicate success: http.StatusOK + NewListResourcesPager func(resourceGroupName string, scheduledActionName string, occurrenceID string, options *armcomputeschedule.OccurrencesClientListResourcesOptions) (resp azfake.PagerResponder[armcomputeschedule.OccurrencesClientListResourcesResponse]) +} + +// NewOccurrencesServerTransport creates a new instance of OccurrencesServerTransport with the provided implementation. +// The returned OccurrencesServerTransport instance is connected to an instance of armcomputeschedule.OccurrencesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOccurrencesServerTransport(srv *OccurrencesServer) *OccurrencesServerTransport { + return &OccurrencesServerTransport{ + srv: srv, + beginDelay: newTracker[azfake.PollerResponder[armcomputeschedule.OccurrencesClientDelayResponse]](), + newListByScheduledActionPager: newTracker[azfake.PagerResponder[armcomputeschedule.OccurrencesClientListByScheduledActionResponse]](), + newListResourcesPager: newTracker[azfake.PagerResponder[armcomputeschedule.OccurrencesClientListResourcesResponse]](), + } +} + +// OccurrencesServerTransport connects instances of armcomputeschedule.OccurrencesClient to instances of OccurrencesServer. +// Don't use this type directly, use NewOccurrencesServerTransport instead. +type OccurrencesServerTransport struct { + srv *OccurrencesServer + beginDelay *tracker[azfake.PollerResponder[armcomputeschedule.OccurrencesClientDelayResponse]] + newListByScheduledActionPager *tracker[azfake.PagerResponder[armcomputeschedule.OccurrencesClientListByScheduledActionResponse]] + newListResourcesPager *tracker[azfake.PagerResponder[armcomputeschedule.OccurrencesClientListResourcesResponse]] +} + +// Do implements the policy.Transporter interface for OccurrencesServerTransport. +func (o *OccurrencesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OccurrencesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if occurrencesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = occurrencesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OccurrencesClient.Cancel": + res.resp, res.err = o.dispatchCancel(req) + case "OccurrencesClient.BeginDelay": + res.resp, res.err = o.dispatchBeginDelay(req) + case "OccurrencesClient.Get": + res.resp, res.err = o.dispatchGet(req) + case "OccurrencesClient.NewListByScheduledActionPager": + res.resp, res.err = o.dispatchNewListByScheduledActionPager(req) + case "OccurrencesClient.NewListResourcesPager": + res.resp, res.err = o.dispatchNewListResourcesPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OccurrencesServerTransport) dispatchCancel(req *http.Request) (*http.Response, error) { + if o.srv.Cancel == nil { + return nil, &nonRetriableError{errors.New("fake for method Cancel not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/scheduledActions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/occurrences/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/cancel` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcomputeschedule.CancelOccurrenceRequest](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + scheduledActionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("scheduledActionName")]) + if err != nil { + return nil, err + } + occurrenceIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("occurrenceId")]) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.Cancel(req.Context(), resourceGroupNameParam, scheduledActionNameParam, occurrenceIDParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RecurringActionsResourceOperationResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OccurrencesServerTransport) dispatchBeginDelay(req *http.Request) (*http.Response, error) { + if o.srv.BeginDelay == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelay not implemented")} + } + beginDelay := o.beginDelay.get(req) + if beginDelay == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/scheduledActions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/occurrences/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/delay` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcomputeschedule.DelayRequest](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + scheduledActionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("scheduledActionName")]) + if err != nil { + return nil, err + } + occurrenceIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("occurrenceId")]) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.BeginDelay(req.Context(), resourceGroupNameParam, scheduledActionNameParam, occurrenceIDParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelay = &respr + o.beginDelay.add(req, beginDelay) + } + + resp, err := server.PollerResponderNext(beginDelay, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + o.beginDelay.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelay) { + o.beginDelay.remove(req) + } + + return resp, nil +} + +func (o *OccurrencesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if o.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/scheduledActions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/occurrences/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + scheduledActionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("scheduledActionName")]) + if err != nil { + return nil, err + } + occurrenceIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("occurrenceId")]) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.Get(req.Context(), resourceGroupNameParam, scheduledActionNameParam, occurrenceIDParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Occurrence, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OccurrencesServerTransport) dispatchNewListByScheduledActionPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListByScheduledActionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByScheduledActionPager not implemented")} + } + newListByScheduledActionPager := o.newListByScheduledActionPager.get(req) + if newListByScheduledActionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/scheduledActions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/occurrences` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + scheduledActionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("scheduledActionName")]) + if err != nil { + return nil, err + } + resp := o.srv.NewListByScheduledActionPager(resourceGroupNameParam, scheduledActionNameParam, nil) + newListByScheduledActionPager = &resp + o.newListByScheduledActionPager.add(req, newListByScheduledActionPager) + server.PagerResponderInjectNextLinks(newListByScheduledActionPager, req, func(page *armcomputeschedule.OccurrencesClientListByScheduledActionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByScheduledActionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + o.newListByScheduledActionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByScheduledActionPager) { + o.newListByScheduledActionPager.remove(req) + } + return resp, nil +} + +func (o *OccurrencesServerTransport) dispatchNewListResourcesPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListResourcesPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListResourcesPager not implemented")} + } + newListResourcesPager := o.newListResourcesPager.get(req) + if newListResourcesPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/scheduledActions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/occurrences/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resources` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + scheduledActionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("scheduledActionName")]) + if err != nil { + return nil, err + } + occurrenceIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("occurrenceId")]) + if err != nil { + return nil, err + } + resp := o.srv.NewListResourcesPager(resourceGroupNameParam, scheduledActionNameParam, occurrenceIDParam, nil) + newListResourcesPager = &resp + o.newListResourcesPager.add(req, newListResourcesPager) + server.PagerResponderInjectNextLinks(newListResourcesPager, req, func(page *armcomputeschedule.OccurrencesClientListResourcesResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListResourcesPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + o.newListResourcesPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListResourcesPager) { + o.newListResourcesPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OccurrencesServerTransport +var occurrencesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcomputeschedule/fake/zz_operations_server.go b/test/local/armcomputeschedule/fake/zz_operations_server.go new file mode 100644 index 000000000000..1b28331ee909 --- /dev/null +++ b/test/local/armcomputeschedule/fake/zz_operations_server.go @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcomputeschedule" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "slices" +) + +// OperationsServer is a fake server for instances of the armcomputeschedule.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armcomputeschedule.OperationsClientListOptions) (resp azfake.PagerResponder[armcomputeschedule.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of armcomputeschedule.OperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOperationsServerTransport(srv *OperationsServer) *OperationsServerTransport { + return &OperationsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armcomputeschedule.OperationsClientListResponse]](), + } +} + +// OperationsServerTransport connects instances of armcomputeschedule.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[armcomputeschedule.OperationsClientListResponse]] +} + +// Do implements the policy.Transporter interface for OperationsServerTransport. +func (o *OperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if operationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = operationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OperationsClient.NewListPager": + res.resp, res.err = o.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OperationsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := o.newListPager.get(req) + if newListPager == nil { + resp := o.srv.NewListPager(nil) + newListPager = &resp + o.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcomputeschedule.OperationsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + o.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + o.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OperationsServerTransport +var operationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcomputeschedule/fake/zz_scheduledactionextension_server.go b/test/local/armcomputeschedule/fake/zz_scheduledactionextension_server.go new file mode 100644 index 000000000000..039e36d65821 --- /dev/null +++ b/test/local/armcomputeschedule/fake/zz_scheduledactionextension_server.go @@ -0,0 +1,125 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcomputeschedule" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// ScheduledActionExtensionServer is a fake server for instances of the armcomputeschedule.ScheduledActionExtensionClient type. +type ScheduledActionExtensionServer struct { + // NewListByVMsPager is the fake for method ScheduledActionExtensionClient.NewListByVMsPager + // HTTP status codes to indicate success: http.StatusOK + NewListByVMsPager func(resourceURI string, options *armcomputeschedule.ScheduledActionExtensionClientListByVMsOptions) (resp azfake.PagerResponder[armcomputeschedule.ScheduledActionExtensionClientListByVMsResponse]) +} + +// NewScheduledActionExtensionServerTransport creates a new instance of ScheduledActionExtensionServerTransport with the provided implementation. +// The returned ScheduledActionExtensionServerTransport instance is connected to an instance of armcomputeschedule.ScheduledActionExtensionClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewScheduledActionExtensionServerTransport(srv *ScheduledActionExtensionServer) *ScheduledActionExtensionServerTransport { + return &ScheduledActionExtensionServerTransport{ + srv: srv, + newListByVMsPager: newTracker[azfake.PagerResponder[armcomputeschedule.ScheduledActionExtensionClientListByVMsResponse]](), + } +} + +// ScheduledActionExtensionServerTransport connects instances of armcomputeschedule.ScheduledActionExtensionClient to instances of ScheduledActionExtensionServer. +// Don't use this type directly, use NewScheduledActionExtensionServerTransport instead. +type ScheduledActionExtensionServerTransport struct { + srv *ScheduledActionExtensionServer + newListByVMsPager *tracker[azfake.PagerResponder[armcomputeschedule.ScheduledActionExtensionClientListByVMsResponse]] +} + +// Do implements the policy.Transporter interface for ScheduledActionExtensionServerTransport. +func (s *ScheduledActionExtensionServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ScheduledActionExtensionServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if scheduledActionExtensionServerTransportInterceptor != nil { + res.resp, res.err, intercepted = scheduledActionExtensionServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ScheduledActionExtensionClient.NewListByVMsPager": + res.resp, res.err = s.dispatchNewListByVMsPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ScheduledActionExtensionServerTransport) dispatchNewListByVMsPager(req *http.Request) (*http.Response, error) { + if s.srv.NewListByVMsPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByVMsPager not implemented")} + } + newListByVMsPager := s.newListByVMsPager.get(req) + if newListByVMsPager == nil { + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/associatedScheduledActions` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + resp := s.srv.NewListByVMsPager(resourceURIParam, nil) + newListByVMsPager = &resp + s.newListByVMsPager.add(req, newListByVMsPager) + server.PagerResponderInjectNextLinks(newListByVMsPager, req, func(page *armcomputeschedule.ScheduledActionExtensionClientListByVMsResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByVMsPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + s.newListByVMsPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByVMsPager) { + s.newListByVMsPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ScheduledActionExtensionServerTransport +var scheduledActionExtensionServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcomputeschedule/fake/zz_scheduledactions_server.go b/test/local/armcomputeschedule/fake/zz_scheduledactions_server.go new file mode 100644 index 000000000000..f550e68a9c61 --- /dev/null +++ b/test/local/armcomputeschedule/fake/zz_scheduledactions_server.go @@ -0,0 +1,1163 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcomputeschedule" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// ScheduledActionsServer is a fake server for instances of the armcomputeschedule.ScheduledActionsClient type. +type ScheduledActionsServer struct { + // AttachResources is the fake for method ScheduledActionsClient.AttachResources + // HTTP status codes to indicate success: http.StatusOK + AttachResources func(ctx context.Context, resourceGroupName string, scheduledActionName string, body armcomputeschedule.ResourceAttachRequest, options *armcomputeschedule.ScheduledActionsClientAttachResourcesOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientAttachResourcesResponse], errResp azfake.ErrorResponder) + + // CancelNextOccurrence is the fake for method ScheduledActionsClient.CancelNextOccurrence + // HTTP status codes to indicate success: http.StatusOK + CancelNextOccurrence func(ctx context.Context, resourceGroupName string, scheduledActionName string, body armcomputeschedule.CancelOccurrenceRequest, options *armcomputeschedule.ScheduledActionsClientCancelNextOccurrenceOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientCancelNextOccurrenceResponse], errResp azfake.ErrorResponder) + + // BeginCreateOrUpdate is the fake for method ScheduledActionsClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, scheduledActionName string, resource armcomputeschedule.ScheduledAction, options *armcomputeschedule.ScheduledActionsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armcomputeschedule.ScheduledActionsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method ScheduledActionsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, scheduledActionName string, options *armcomputeschedule.ScheduledActionsClientBeginDeleteOptions) (resp azfake.PollerResponder[armcomputeschedule.ScheduledActionsClientDeleteResponse], errResp azfake.ErrorResponder) + + // DetachResources is the fake for method ScheduledActionsClient.DetachResources + // HTTP status codes to indicate success: http.StatusOK + DetachResources func(ctx context.Context, resourceGroupName string, scheduledActionName string, body armcomputeschedule.ResourceDetachRequest, options *armcomputeschedule.ScheduledActionsClientDetachResourcesOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientDetachResourcesResponse], errResp azfake.ErrorResponder) + + // Disable is the fake for method ScheduledActionsClient.Disable + // HTTP status codes to indicate success: http.StatusOK + Disable func(ctx context.Context, resourceGroupName string, scheduledActionName string, options *armcomputeschedule.ScheduledActionsClientDisableOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientDisableResponse], errResp azfake.ErrorResponder) + + // Enable is the fake for method ScheduledActionsClient.Enable + // HTTP status codes to indicate success: http.StatusOK + Enable func(ctx context.Context, resourceGroupName string, scheduledActionName string, options *armcomputeschedule.ScheduledActionsClientEnableOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientEnableResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method ScheduledActionsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, scheduledActionName string, options *armcomputeschedule.ScheduledActionsClientGetOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method ScheduledActionsClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armcomputeschedule.ScheduledActionsClientListByResourceGroupOptions) (resp azfake.PagerResponder[armcomputeschedule.ScheduledActionsClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method ScheduledActionsClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armcomputeschedule.ScheduledActionsClientListBySubscriptionOptions) (resp azfake.PagerResponder[armcomputeschedule.ScheduledActionsClientListBySubscriptionResponse]) + + // NewListResourcesPager is the fake for method ScheduledActionsClient.NewListResourcesPager + // HTTP status codes to indicate success: http.StatusOK + NewListResourcesPager func(resourceGroupName string, scheduledActionName string, options *armcomputeschedule.ScheduledActionsClientListResourcesOptions) (resp azfake.PagerResponder[armcomputeschedule.ScheduledActionsClientListResourcesResponse]) + + // PatchResources is the fake for method ScheduledActionsClient.PatchResources + // HTTP status codes to indicate success: http.StatusOK + PatchResources func(ctx context.Context, resourceGroupName string, scheduledActionName string, body armcomputeschedule.ResourcePatchRequest, options *armcomputeschedule.ScheduledActionsClientPatchResourcesOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientPatchResourcesResponse], errResp azfake.ErrorResponder) + + // TriggerManualOccurrence is the fake for method ScheduledActionsClient.TriggerManualOccurrence + // HTTP status codes to indicate success: http.StatusOK + TriggerManualOccurrence func(ctx context.Context, resourceGroupName string, scheduledActionName string, options *armcomputeschedule.ScheduledActionsClientTriggerManualOccurrenceOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientTriggerManualOccurrenceResponse], errResp azfake.ErrorResponder) + + // Update is the fake for method ScheduledActionsClient.Update + // HTTP status codes to indicate success: http.StatusOK + Update func(ctx context.Context, resourceGroupName string, scheduledActionName string, properties armcomputeschedule.ScheduledActionUpdate, options *armcomputeschedule.ScheduledActionsClientUpdateOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientUpdateResponse], errResp azfake.ErrorResponder) + + // VirtualMachinesCancelOperations is the fake for method ScheduledActionsClient.VirtualMachinesCancelOperations + // HTTP status codes to indicate success: http.StatusOK + VirtualMachinesCancelOperations func(ctx context.Context, locationparameter string, requestBody armcomputeschedule.CancelOperationsRequest, options *armcomputeschedule.ScheduledActionsClientVirtualMachinesCancelOperationsOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientVirtualMachinesCancelOperationsResponse], errResp azfake.ErrorResponder) + + // VirtualMachinesExecuteCreate is the fake for method ScheduledActionsClient.VirtualMachinesExecuteCreate + // HTTP status codes to indicate success: http.StatusOK + VirtualMachinesExecuteCreate func(ctx context.Context, locationparameter string, requestBody armcomputeschedule.ExecuteCreateRequest, options *armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteCreateOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteCreateResponse], errResp azfake.ErrorResponder) + + // VirtualMachinesExecuteCreateFlex is the fake for method ScheduledActionsClient.VirtualMachinesExecuteCreateFlex + // HTTP status codes to indicate success: http.StatusOK + VirtualMachinesExecuteCreateFlex func(ctx context.Context, locationparameter string, body armcomputeschedule.ExecuteCreateFlexRequest, options *armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteCreateFlexOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteCreateFlexResponse], errResp azfake.ErrorResponder) + + // VirtualMachinesExecuteDeallocate is the fake for method ScheduledActionsClient.VirtualMachinesExecuteDeallocate + // HTTP status codes to indicate success: http.StatusOK + VirtualMachinesExecuteDeallocate func(ctx context.Context, locationparameter string, requestBody armcomputeschedule.ExecuteDeallocateRequest, options *armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteDeallocateOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteDeallocateResponse], errResp azfake.ErrorResponder) + + // VirtualMachinesExecuteDelete is the fake for method ScheduledActionsClient.VirtualMachinesExecuteDelete + // HTTP status codes to indicate success: http.StatusOK + VirtualMachinesExecuteDelete func(ctx context.Context, locationparameter string, requestBody armcomputeschedule.ExecuteDeleteRequest, options *armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteDeleteOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteDeleteResponse], errResp azfake.ErrorResponder) + + // VirtualMachinesExecuteHibernate is the fake for method ScheduledActionsClient.VirtualMachinesExecuteHibernate + // HTTP status codes to indicate success: http.StatusOK + VirtualMachinesExecuteHibernate func(ctx context.Context, locationparameter string, requestBody armcomputeschedule.ExecuteHibernateRequest, options *armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteHibernateOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteHibernateResponse], errResp azfake.ErrorResponder) + + // VirtualMachinesExecuteStart is the fake for method ScheduledActionsClient.VirtualMachinesExecuteStart + // HTTP status codes to indicate success: http.StatusOK + VirtualMachinesExecuteStart func(ctx context.Context, locationparameter string, requestBody armcomputeschedule.ExecuteStartRequest, options *armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteStartOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientVirtualMachinesExecuteStartResponse], errResp azfake.ErrorResponder) + + // VirtualMachinesGetOperationErrors is the fake for method ScheduledActionsClient.VirtualMachinesGetOperationErrors + // HTTP status codes to indicate success: http.StatusOK + VirtualMachinesGetOperationErrors func(ctx context.Context, locationparameter string, requestBody armcomputeschedule.GetOperationErrorsRequest, options *armcomputeschedule.ScheduledActionsClientVirtualMachinesGetOperationErrorsOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientVirtualMachinesGetOperationErrorsResponse], errResp azfake.ErrorResponder) + + // VirtualMachinesGetOperationStatus is the fake for method ScheduledActionsClient.VirtualMachinesGetOperationStatus + // HTTP status codes to indicate success: http.StatusOK + VirtualMachinesGetOperationStatus func(ctx context.Context, locationparameter string, requestBody armcomputeschedule.GetOperationStatusRequest, options *armcomputeschedule.ScheduledActionsClientVirtualMachinesGetOperationStatusOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientVirtualMachinesGetOperationStatusResponse], errResp azfake.ErrorResponder) + + // VirtualMachinesSubmitDeallocate is the fake for method ScheduledActionsClient.VirtualMachinesSubmitDeallocate + // HTTP status codes to indicate success: http.StatusOK + VirtualMachinesSubmitDeallocate func(ctx context.Context, locationparameter string, requestBody armcomputeschedule.SubmitDeallocateRequest, options *armcomputeschedule.ScheduledActionsClientVirtualMachinesSubmitDeallocateOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientVirtualMachinesSubmitDeallocateResponse], errResp azfake.ErrorResponder) + + // VirtualMachinesSubmitHibernate is the fake for method ScheduledActionsClient.VirtualMachinesSubmitHibernate + // HTTP status codes to indicate success: http.StatusOK + VirtualMachinesSubmitHibernate func(ctx context.Context, locationparameter string, requestBody armcomputeschedule.SubmitHibernateRequest, options *armcomputeschedule.ScheduledActionsClientVirtualMachinesSubmitHibernateOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientVirtualMachinesSubmitHibernateResponse], errResp azfake.ErrorResponder) + + // VirtualMachinesSubmitStart is the fake for method ScheduledActionsClient.VirtualMachinesSubmitStart + // HTTP status codes to indicate success: http.StatusOK + VirtualMachinesSubmitStart func(ctx context.Context, locationparameter string, requestBody armcomputeschedule.SubmitStartRequest, options *armcomputeschedule.ScheduledActionsClientVirtualMachinesSubmitStartOptions) (resp azfake.Responder[armcomputeschedule.ScheduledActionsClientVirtualMachinesSubmitStartResponse], errResp azfake.ErrorResponder) +} + +// NewScheduledActionsServerTransport creates a new instance of ScheduledActionsServerTransport with the provided implementation. +// The returned ScheduledActionsServerTransport instance is connected to an instance of armcomputeschedule.ScheduledActionsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewScheduledActionsServerTransport(srv *ScheduledActionsServer) *ScheduledActionsServerTransport { + return &ScheduledActionsServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armcomputeschedule.ScheduledActionsClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armcomputeschedule.ScheduledActionsClientDeleteResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armcomputeschedule.ScheduledActionsClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armcomputeschedule.ScheduledActionsClientListBySubscriptionResponse]](), + newListResourcesPager: newTracker[azfake.PagerResponder[armcomputeschedule.ScheduledActionsClientListResourcesResponse]](), + } +} + +// ScheduledActionsServerTransport connects instances of armcomputeschedule.ScheduledActionsClient to instances of ScheduledActionsServer. +// Don't use this type directly, use NewScheduledActionsServerTransport instead. +type ScheduledActionsServerTransport struct { + srv *ScheduledActionsServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armcomputeschedule.ScheduledActionsClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armcomputeschedule.ScheduledActionsClientDeleteResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armcomputeschedule.ScheduledActionsClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armcomputeschedule.ScheduledActionsClientListBySubscriptionResponse]] + newListResourcesPager *tracker[azfake.PagerResponder[armcomputeschedule.ScheduledActionsClientListResourcesResponse]] +} + +// Do implements the policy.Transporter interface for ScheduledActionsServerTransport. +func (s *ScheduledActionsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ScheduledActionsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if scheduledActionsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = scheduledActionsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ScheduledActionsClient.AttachResources": + res.resp, res.err = s.dispatchAttachResources(req) + case "ScheduledActionsClient.CancelNextOccurrence": + res.resp, res.err = s.dispatchCancelNextOccurrence(req) + case "ScheduledActionsClient.BeginCreateOrUpdate": + res.resp, res.err = s.dispatchBeginCreateOrUpdate(req) + case "ScheduledActionsClient.BeginDelete": + res.resp, res.err = s.dispatchBeginDelete(req) + case "ScheduledActionsClient.DetachResources": + res.resp, res.err = s.dispatchDetachResources(req) + case "ScheduledActionsClient.Disable": + res.resp, res.err = s.dispatchDisable(req) + case "ScheduledActionsClient.Enable": + res.resp, res.err = s.dispatchEnable(req) + case "ScheduledActionsClient.Get": + res.resp, res.err = s.dispatchGet(req) + case "ScheduledActionsClient.NewListByResourceGroupPager": + res.resp, res.err = s.dispatchNewListByResourceGroupPager(req) + case "ScheduledActionsClient.NewListBySubscriptionPager": + res.resp, res.err = s.dispatchNewListBySubscriptionPager(req) + case "ScheduledActionsClient.NewListResourcesPager": + res.resp, res.err = s.dispatchNewListResourcesPager(req) + case "ScheduledActionsClient.PatchResources": + res.resp, res.err = s.dispatchPatchResources(req) + case "ScheduledActionsClient.TriggerManualOccurrence": + res.resp, res.err = s.dispatchTriggerManualOccurrence(req) + case "ScheduledActionsClient.Update": + res.resp, res.err = s.dispatchUpdate(req) + case "ScheduledActionsClient.VirtualMachinesCancelOperations": + res.resp, res.err = s.dispatchVirtualMachinesCancelOperations(req) + case "ScheduledActionsClient.VirtualMachinesExecuteCreate": + res.resp, res.err = s.dispatchVirtualMachinesExecuteCreate(req) + case "ScheduledActionsClient.VirtualMachinesExecuteCreateFlex": + res.resp, res.err = s.dispatchVirtualMachinesExecuteCreateFlex(req) + case "ScheduledActionsClient.VirtualMachinesExecuteDeallocate": + res.resp, res.err = s.dispatchVirtualMachinesExecuteDeallocate(req) + case "ScheduledActionsClient.VirtualMachinesExecuteDelete": + res.resp, res.err = s.dispatchVirtualMachinesExecuteDelete(req) + case "ScheduledActionsClient.VirtualMachinesExecuteHibernate": + res.resp, res.err = s.dispatchVirtualMachinesExecuteHibernate(req) + case "ScheduledActionsClient.VirtualMachinesExecuteStart": + res.resp, res.err = s.dispatchVirtualMachinesExecuteStart(req) + case "ScheduledActionsClient.VirtualMachinesGetOperationErrors": + res.resp, res.err = s.dispatchVirtualMachinesGetOperationErrors(req) + case "ScheduledActionsClient.VirtualMachinesGetOperationStatus": + res.resp, res.err = s.dispatchVirtualMachinesGetOperationStatus(req) + case "ScheduledActionsClient.VirtualMachinesSubmitDeallocate": + res.resp, res.err = s.dispatchVirtualMachinesSubmitDeallocate(req) + case "ScheduledActionsClient.VirtualMachinesSubmitHibernate": + res.resp, res.err = s.dispatchVirtualMachinesSubmitHibernate(req) + case "ScheduledActionsClient.VirtualMachinesSubmitStart": + res.resp, res.err = s.dispatchVirtualMachinesSubmitStart(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ScheduledActionsServerTransport) dispatchAttachResources(req *http.Request) (*http.Response, error) { + if s.srv.AttachResources == nil { + return nil, &nonRetriableError{errors.New("fake for method AttachResources not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/scheduledActions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/attachResources` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcomputeschedule.ResourceAttachRequest](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + scheduledActionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("scheduledActionName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.AttachResources(req.Context(), resourceGroupNameParam, scheduledActionNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RecurringActionsResourceOperationResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScheduledActionsServerTransport) dispatchCancelNextOccurrence(req *http.Request) (*http.Response, error) { + if s.srv.CancelNextOccurrence == nil { + return nil, &nonRetriableError{errors.New("fake for method CancelNextOccurrence not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/scheduledActions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/cancelNextOccurrence` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcomputeschedule.CancelOccurrenceRequest](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + scheduledActionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("scheduledActionName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.CancelNextOccurrence(req.Context(), resourceGroupNameParam, scheduledActionNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RecurringActionsResourceOperationResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScheduledActionsServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if s.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := s.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/scheduledActions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcomputeschedule.ScheduledAction](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + scheduledActionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("scheduledActionName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, scheduledActionNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + s.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + s.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + s.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (s *ScheduledActionsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if s.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := s.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/scheduledActions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + scheduledActionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("scheduledActionName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.BeginDelete(req.Context(), resourceGroupNameParam, scheduledActionNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + s.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + s.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + s.beginDelete.remove(req) + } + + return resp, nil +} + +func (s *ScheduledActionsServerTransport) dispatchDetachResources(req *http.Request) (*http.Response, error) { + if s.srv.DetachResources == nil { + return nil, &nonRetriableError{errors.New("fake for method DetachResources not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/scheduledActions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/detachResources` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcomputeschedule.ResourceDetachRequest](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + scheduledActionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("scheduledActionName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.DetachResources(req.Context(), resourceGroupNameParam, scheduledActionNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RecurringActionsResourceOperationResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScheduledActionsServerTransport) dispatchDisable(req *http.Request) (*http.Response, error) { + if s.srv.Disable == nil { + return nil, &nonRetriableError{errors.New("fake for method Disable not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/scheduledActions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/disable` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + scheduledActionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("scheduledActionName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Disable(req.Context(), resourceGroupNameParam, scheduledActionNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScheduledActionsServerTransport) dispatchEnable(req *http.Request) (*http.Response, error) { + if s.srv.Enable == nil { + return nil, &nonRetriableError{errors.New("fake for method Enable not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/scheduledActions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/enable` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + scheduledActionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("scheduledActionName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Enable(req.Context(), resourceGroupNameParam, scheduledActionNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScheduledActionsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if s.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/scheduledActions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + scheduledActionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("scheduledActionName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Get(req.Context(), resourceGroupNameParam, scheduledActionNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ScheduledAction, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScheduledActionsServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if s.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := s.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/scheduledActions` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := s.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + s.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armcomputeschedule.ScheduledActionsClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + s.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + s.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (s *ScheduledActionsServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if s.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := s.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/scheduledActions` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := s.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + s.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armcomputeschedule.ScheduledActionsClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + s.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + s.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (s *ScheduledActionsServerTransport) dispatchNewListResourcesPager(req *http.Request) (*http.Response, error) { + if s.srv.NewListResourcesPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListResourcesPager not implemented")} + } + newListResourcesPager := s.newListResourcesPager.get(req) + if newListResourcesPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/scheduledActions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resources` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + scheduledActionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("scheduledActionName")]) + if err != nil { + return nil, err + } + resp := s.srv.NewListResourcesPager(resourceGroupNameParam, scheduledActionNameParam, nil) + newListResourcesPager = &resp + s.newListResourcesPager.add(req, newListResourcesPager) + server.PagerResponderInjectNextLinks(newListResourcesPager, req, func(page *armcomputeschedule.ScheduledActionsClientListResourcesResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListResourcesPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + s.newListResourcesPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListResourcesPager) { + s.newListResourcesPager.remove(req) + } + return resp, nil +} + +func (s *ScheduledActionsServerTransport) dispatchPatchResources(req *http.Request) (*http.Response, error) { + if s.srv.PatchResources == nil { + return nil, &nonRetriableError{errors.New("fake for method PatchResources not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/scheduledActions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/patchResources` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcomputeschedule.ResourcePatchRequest](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + scheduledActionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("scheduledActionName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.PatchResources(req.Context(), resourceGroupNameParam, scheduledActionNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RecurringActionsResourceOperationResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScheduledActionsServerTransport) dispatchTriggerManualOccurrence(req *http.Request) (*http.Response, error) { + if s.srv.TriggerManualOccurrence == nil { + return nil, &nonRetriableError{errors.New("fake for method TriggerManualOccurrence not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/scheduledActions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/triggerManualOccurrence` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + scheduledActionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("scheduledActionName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.TriggerManualOccurrence(req.Context(), resourceGroupNameParam, scheduledActionNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Occurrence, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScheduledActionsServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) { + if s.srv.Update == nil { + return nil, &nonRetriableError{errors.New("fake for method Update not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/scheduledActions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcomputeschedule.ScheduledActionUpdate](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + scheduledActionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("scheduledActionName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Update(req.Context(), resourceGroupNameParam, scheduledActionNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ScheduledAction, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScheduledActionsServerTransport) dispatchVirtualMachinesCancelOperations(req *http.Request) (*http.Response, error) { + if s.srv.VirtualMachinesCancelOperations == nil { + return nil, &nonRetriableError{errors.New("fake for method VirtualMachinesCancelOperations not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/virtualMachinesCancelOperations` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcomputeschedule.CancelOperationsRequest](req) + if err != nil { + return nil, err + } + locationparameterParam, err := url.PathUnescape(matches[regex.SubexpIndex("locationparameter")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.VirtualMachinesCancelOperations(req.Context(), locationparameterParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CancelOperationsResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScheduledActionsServerTransport) dispatchVirtualMachinesExecuteCreate(req *http.Request) (*http.Response, error) { + if s.srv.VirtualMachinesExecuteCreate == nil { + return nil, &nonRetriableError{errors.New("fake for method VirtualMachinesExecuteCreate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/virtualMachinesExecuteCreate` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcomputeschedule.ExecuteCreateRequest](req) + if err != nil { + return nil, err + } + locationparameterParam, err := url.PathUnescape(matches[regex.SubexpIndex("locationparameter")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.VirtualMachinesExecuteCreate(req.Context(), locationparameterParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CreateResourceOperationResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScheduledActionsServerTransport) dispatchVirtualMachinesExecuteCreateFlex(req *http.Request) (*http.Response, error) { + if s.srv.VirtualMachinesExecuteCreateFlex == nil { + return nil, &nonRetriableError{errors.New("fake for method VirtualMachinesExecuteCreateFlex not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/virtualMachinesExecuteCreateFlex` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcomputeschedule.ExecuteCreateFlexRequest](req) + if err != nil { + return nil, err + } + locationparameterParam, err := url.PathUnescape(matches[regex.SubexpIndex("locationparameter")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.VirtualMachinesExecuteCreateFlex(req.Context(), locationparameterParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CreateFlexResourceOperationResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScheduledActionsServerTransport) dispatchVirtualMachinesExecuteDeallocate(req *http.Request) (*http.Response, error) { + if s.srv.VirtualMachinesExecuteDeallocate == nil { + return nil, &nonRetriableError{errors.New("fake for method VirtualMachinesExecuteDeallocate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/virtualMachinesExecuteDeallocate` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcomputeschedule.ExecuteDeallocateRequest](req) + if err != nil { + return nil, err + } + locationparameterParam, err := url.PathUnescape(matches[regex.SubexpIndex("locationparameter")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.VirtualMachinesExecuteDeallocate(req.Context(), locationparameterParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DeallocateResourceOperationResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScheduledActionsServerTransport) dispatchVirtualMachinesExecuteDelete(req *http.Request) (*http.Response, error) { + if s.srv.VirtualMachinesExecuteDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method VirtualMachinesExecuteDelete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/virtualMachinesExecuteDelete` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcomputeschedule.ExecuteDeleteRequest](req) + if err != nil { + return nil, err + } + locationparameterParam, err := url.PathUnescape(matches[regex.SubexpIndex("locationparameter")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.VirtualMachinesExecuteDelete(req.Context(), locationparameterParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DeleteResourceOperationResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScheduledActionsServerTransport) dispatchVirtualMachinesExecuteHibernate(req *http.Request) (*http.Response, error) { + if s.srv.VirtualMachinesExecuteHibernate == nil { + return nil, &nonRetriableError{errors.New("fake for method VirtualMachinesExecuteHibernate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/virtualMachinesExecuteHibernate` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcomputeschedule.ExecuteHibernateRequest](req) + if err != nil { + return nil, err + } + locationparameterParam, err := url.PathUnescape(matches[regex.SubexpIndex("locationparameter")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.VirtualMachinesExecuteHibernate(req.Context(), locationparameterParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).HibernateResourceOperationResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScheduledActionsServerTransport) dispatchVirtualMachinesExecuteStart(req *http.Request) (*http.Response, error) { + if s.srv.VirtualMachinesExecuteStart == nil { + return nil, &nonRetriableError{errors.New("fake for method VirtualMachinesExecuteStart not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/virtualMachinesExecuteStart` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcomputeschedule.ExecuteStartRequest](req) + if err != nil { + return nil, err + } + locationparameterParam, err := url.PathUnescape(matches[regex.SubexpIndex("locationparameter")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.VirtualMachinesExecuteStart(req.Context(), locationparameterParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).StartResourceOperationResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScheduledActionsServerTransport) dispatchVirtualMachinesGetOperationErrors(req *http.Request) (*http.Response, error) { + if s.srv.VirtualMachinesGetOperationErrors == nil { + return nil, &nonRetriableError{errors.New("fake for method VirtualMachinesGetOperationErrors not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/virtualMachinesGetOperationErrors` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcomputeschedule.GetOperationErrorsRequest](req) + if err != nil { + return nil, err + } + locationparameterParam, err := url.PathUnescape(matches[regex.SubexpIndex("locationparameter")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.VirtualMachinesGetOperationErrors(req.Context(), locationparameterParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).GetOperationErrorsResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScheduledActionsServerTransport) dispatchVirtualMachinesGetOperationStatus(req *http.Request) (*http.Response, error) { + if s.srv.VirtualMachinesGetOperationStatus == nil { + return nil, &nonRetriableError{errors.New("fake for method VirtualMachinesGetOperationStatus not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/virtualMachinesGetOperationStatus` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcomputeschedule.GetOperationStatusRequest](req) + if err != nil { + return nil, err + } + locationparameterParam, err := url.PathUnescape(matches[regex.SubexpIndex("locationparameter")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.VirtualMachinesGetOperationStatus(req.Context(), locationparameterParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).GetOperationStatusResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScheduledActionsServerTransport) dispatchVirtualMachinesSubmitDeallocate(req *http.Request) (*http.Response, error) { + if s.srv.VirtualMachinesSubmitDeallocate == nil { + return nil, &nonRetriableError{errors.New("fake for method VirtualMachinesSubmitDeallocate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/virtualMachinesSubmitDeallocate` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcomputeschedule.SubmitDeallocateRequest](req) + if err != nil { + return nil, err + } + locationparameterParam, err := url.PathUnescape(matches[regex.SubexpIndex("locationparameter")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.VirtualMachinesSubmitDeallocate(req.Context(), locationparameterParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DeallocateResourceOperationResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScheduledActionsServerTransport) dispatchVirtualMachinesSubmitHibernate(req *http.Request) (*http.Response, error) { + if s.srv.VirtualMachinesSubmitHibernate == nil { + return nil, &nonRetriableError{errors.New("fake for method VirtualMachinesSubmitHibernate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/virtualMachinesSubmitHibernate` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcomputeschedule.SubmitHibernateRequest](req) + if err != nil { + return nil, err + } + locationparameterParam, err := url.PathUnescape(matches[regex.SubexpIndex("locationparameter")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.VirtualMachinesSubmitHibernate(req.Context(), locationparameterParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).HibernateResourceOperationResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ScheduledActionsServerTransport) dispatchVirtualMachinesSubmitStart(req *http.Request) (*http.Response, error) { + if s.srv.VirtualMachinesSubmitStart == nil { + return nil, &nonRetriableError{errors.New("fake for method VirtualMachinesSubmitStart not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.ComputeSchedule/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/virtualMachinesSubmitStart` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcomputeschedule.SubmitStartRequest](req) + if err != nil { + return nil, err + } + locationparameterParam, err := url.PathUnescape(matches[regex.SubexpIndex("locationparameter")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.VirtualMachinesSubmitStart(req.Context(), locationparameterParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).StartResourceOperationResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ScheduledActionsServerTransport +var scheduledActionsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcomputeschedule/fake/zz_server_factory.go b/test/local/armcomputeschedule/fake/zz_server_factory.go new file mode 100644 index 000000000000..f468075cb757 --- /dev/null +++ b/test/local/armcomputeschedule/fake/zz_server_factory.go @@ -0,0 +1,98 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armcomputeschedule.ClientFactory type. +type ServerFactory struct { + // OccurrenceExtensionServer contains the fakes for client OccurrenceExtensionClient + OccurrenceExtensionServer OccurrenceExtensionServer + + // OccurrencesServer contains the fakes for client OccurrencesClient + OccurrencesServer OccurrencesServer + + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer + + // ScheduledActionExtensionServer contains the fakes for client ScheduledActionExtensionClient + ScheduledActionExtensionServer ScheduledActionExtensionServer + + // ScheduledActionsServer contains the fakes for client ScheduledActionsClient + ScheduledActionsServer ScheduledActionsServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armcomputeschedule.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of armcomputeschedule.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trOccurrenceExtensionServer *OccurrenceExtensionServerTransport + trOccurrencesServer *OccurrencesServerTransport + trOperationsServer *OperationsServerTransport + trScheduledActionExtensionServer *ScheduledActionExtensionServerTransport + trScheduledActionsServer *ScheduledActionsServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "OccurrenceExtensionClient": + initServer(&s.trMu, &s.trOccurrenceExtensionServer, func() *OccurrenceExtensionServerTransport { + return NewOccurrenceExtensionServerTransport(&s.srv.OccurrenceExtensionServer) + }) + resp, err = s.trOccurrenceExtensionServer.Do(req) + case "OccurrencesClient": + initServer(&s.trMu, &s.trOccurrencesServer, func() *OccurrencesServerTransport { return NewOccurrencesServerTransport(&s.srv.OccurrencesServer) }) + resp, err = s.trOccurrencesServer.Do(req) + case "OperationsClient": + initServer(&s.trMu, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + resp, err = s.trOperationsServer.Do(req) + case "ScheduledActionExtensionClient": + initServer(&s.trMu, &s.trScheduledActionExtensionServer, func() *ScheduledActionExtensionServerTransport { + return NewScheduledActionExtensionServerTransport(&s.srv.ScheduledActionExtensionServer) + }) + resp, err = s.trScheduledActionExtensionServer.Do(req) + case "ScheduledActionsClient": + initServer(&s.trMu, &s.trScheduledActionsServer, func() *ScheduledActionsServerTransport { + return NewScheduledActionsServerTransport(&s.srv.ScheduledActionsServer) + }) + resp, err = s.trScheduledActionsServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} diff --git a/test/local/armcomputeschedule/go.mod b/test/local/armcomputeschedule/go.mod new file mode 100644 index 000000000000..7b8f5fcc7c8a --- /dev/null +++ b/test/local/armcomputeschedule/go.mod @@ -0,0 +1,11 @@ +module armcomputeschedule + +go 1.25.0 + +require github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect +) diff --git a/test/local/armcomputeschedule/go.sum b/test/local/armcomputeschedule/go.sum new file mode 100644 index 000000000000..3fdb64caf441 --- /dev/null +++ b/test/local/armcomputeschedule/go.sum @@ -0,0 +1,16 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/local/armcomputeschedule/testdata/_metadata.json b/test/local/armcomputeschedule/testdata/_metadata.json new file mode 100644 index 000000000000..e5c6d4e5657b --- /dev/null +++ b/test/local/armcomputeschedule/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Microsoft.ComputeSchedule": "2026-04-15-preview" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/local/armcomputeschedule/zz_client_factory.go b/test/local/armcomputeschedule/zz_client_factory.go new file mode 100644 index 000000000000..f311dd57e362 --- /dev/null +++ b/test/local/armcomputeschedule/zz_client_factory.go @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcomputeschedule + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + subscriptionID string + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, + internal: internal, + }, nil +} + +// NewOccurrenceExtensionClient creates a new instance of OccurrenceExtensionClient. +func (c *ClientFactory) NewOccurrenceExtensionClient() *OccurrenceExtensionClient { + return &OccurrenceExtensionClient{ + internal: c.internal, + } +} + +// NewOccurrencesClient creates a new instance of OccurrencesClient. +func (c *ClientFactory) NewOccurrencesClient() *OccurrencesClient { + return &OccurrencesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: c.internal, + } +} + +// NewScheduledActionExtensionClient creates a new instance of ScheduledActionExtensionClient. +func (c *ClientFactory) NewScheduledActionExtensionClient() *ScheduledActionExtensionClient { + return &ScheduledActionExtensionClient{ + internal: c.internal, + } +} + +// NewScheduledActionsClient creates a new instance of ScheduledActionsClient. +func (c *ClientFactory) NewScheduledActionsClient() *ScheduledActionsClient { + return &ScheduledActionsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} diff --git a/test/local/armcomputeschedule/zz_constants.go b/test/local/armcomputeschedule/zz_constants.go new file mode 100644 index 000000000000..bcc3528b14ef --- /dev/null +++ b/test/local/armcomputeschedule/zz_constants.go @@ -0,0 +1,1236 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcomputeschedule + +const ( + version20260415Preview string = "2026-04-15-preview" +) + +// ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +type ActionType string + +const ( + // ActionTypeInternal - Actions are for internal-only APIs. + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// AllocationStrategy - The allocation strategy for VM size selection +type AllocationStrategy string + +const ( + // AllocationStrategyCapacityOptimized - Platform prioritizes VM sizes with the highest available capacity first + AllocationStrategyCapacityOptimized AllocationStrategy = "CapacityOptimized" + // AllocationStrategyLowestPrice - Platform prioritizes VM sizes with the lowest hourly cost + AllocationStrategyLowestPrice AllocationStrategy = "LowestPrice" + // AllocationStrategyPrioritized - Customer specifies a rank for each VM size, platform uses VM sizes in rank order + AllocationStrategyPrioritized AllocationStrategy = "Prioritized" +) + +// PossibleAllocationStrategyValues returns the possible values for the AllocationStrategy const type. +func PossibleAllocationStrategyValues() []AllocationStrategy { + return []AllocationStrategy{ + AllocationStrategyCapacityOptimized, + AllocationStrategyLowestPrice, + AllocationStrategyPrioritized, + } +} + +// CachingTypes - Specifies the caching requirements. Possible values are: **None,** **ReadOnly,** **ReadWrite.** The default +// values are: **None for Standard storage. ReadOnly for Premium storage** +type CachingTypes string + +const ( + // CachingTypesNone - Caching type:None + CachingTypesNone CachingTypes = "None" + // CachingTypesReadOnly - Caching type:ReadOnly + CachingTypesReadOnly CachingTypes = "ReadOnly" + // CachingTypesReadWrite - Caching type:ReadWrite + CachingTypesReadWrite CachingTypes = "ReadWrite" +) + +// PossibleCachingTypesValues returns the possible values for the CachingTypes const type. +func PossibleCachingTypesValues() []CachingTypes { + return []CachingTypes{ + CachingTypesNone, + CachingTypesReadOnly, + CachingTypesReadWrite, + } +} + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// DeadlineType - The types of deadlines supported by ScheduledActions +type DeadlineType string + +const ( + // DeadlineTypeCompleteBy - Complete the operation by the given deadline. + DeadlineTypeCompleteBy DeadlineType = "CompleteBy" + // DeadlineTypeInitiateAt - Initiate the operation at the given deadline. + DeadlineTypeInitiateAt DeadlineType = "InitiateAt" + // DeadlineTypeUnknown - Default value of Unknown. + DeadlineTypeUnknown DeadlineType = "Unknown" +) + +// PossibleDeadlineTypeValues returns the possible values for the DeadlineType const type. +func PossibleDeadlineTypeValues() []DeadlineType { + return []DeadlineType{ + DeadlineTypeCompleteBy, + DeadlineTypeInitiateAt, + DeadlineTypeUnknown, + } +} + +// DeleteOptions - Specify what happens to the network interface when the VM is deleted +type DeleteOptions string + +const ( + // DeleteOptionsDelete - Delete network interface when the VM is deleted + DeleteOptionsDelete DeleteOptions = "Delete" + // DeleteOptionsDetach - Detach network interface when the VM is deleted + DeleteOptionsDetach DeleteOptions = "Detach" +) + +// PossibleDeleteOptionsValues returns the possible values for the DeleteOptions const type. +func PossibleDeleteOptionsValues() []DeleteOptions { + return []DeleteOptions{ + DeleteOptionsDelete, + DeleteOptionsDetach, + } +} + +// DiffDiskOptions - Specifies the ephemeral disk option for operating system disk. +type DiffDiskOptions string + +const ( + // DiffDiskOptionsLocal - Local Ephemeral disk option: Local + DiffDiskOptionsLocal DiffDiskOptions = "Local" +) + +// PossibleDiffDiskOptionsValues returns the possible values for the DiffDiskOptions const type. +func PossibleDiffDiskOptionsValues() []DiffDiskOptions { + return []DiffDiskOptions{ + DiffDiskOptionsLocal, + } +} + +// DiffDiskPlacement - Specifies the ephemeral disk placement for operating system disk. This property can be used by user +// in the request to choose the location i.e, cache disk, resource disk or nvme disk space for Ephemeral OS disk provisioning. +// For more information on Ephemeral OS disk size requirements, please refer Ephemeral OS disk size requirements for Windows +// VM at https://docs.microsoft.com/azure/virtual-machines/windows/ephemeral-os-disks#size-requirements and Linux VM at https://docs.microsoft.com/azure/virtual-machines/linux/ephemeral-os-disks#size-requirements. +// Minimum api-version for NvmeDisk: 2024-03-01. +type DiffDiskPlacement string + +const ( + // DiffDiskPlacementCacheDisk - CacheDisk disk placement + DiffDiskPlacementCacheDisk DiffDiskPlacement = "CacheDisk" + // DiffDiskPlacementNvmeDisk - NvmeDisk disk placement + DiffDiskPlacementNvmeDisk DiffDiskPlacement = "NvmeDisk" + // DiffDiskPlacementResourceDisk - ResourceDisk disk placement + DiffDiskPlacementResourceDisk DiffDiskPlacement = "ResourceDisk" +) + +// PossibleDiffDiskPlacementValues returns the possible values for the DiffDiskPlacement const type. +func PossibleDiffDiskPlacementValues() []DiffDiskPlacement { + return []DiffDiskPlacement{ + DiffDiskPlacementCacheDisk, + DiffDiskPlacementNvmeDisk, + DiffDiskPlacementResourceDisk, + } +} + +// DiskControllerTypes - Specifies the disk controller type configured for the VM and VirtualMachineScaleSet. This property +// is only supported for virtual machines whose operating system disk and VM sku supports Generation 2 (https://docs.microsoft.com/en-us/azure/virtual-machines/generation-2), +// please check the HyperVGenerations capability returned as part of VM sku capabilities in the response of Microsoft.Compute +// SKUs api for the region contains V2 (https://docs.microsoft.com/rest/api/compute/resourceskus/list). For more information +// about Disk Controller Types supported please refer to https://aka.ms/azure-diskcontrollertypes. +type DiskControllerTypes string + +const ( + // DiskControllerTypesNVMe - NVMe disk controller type + DiskControllerTypesNVMe DiskControllerTypes = "NVMe" + // DiskControllerTypesSCSI - SCSI disk controller type + DiskControllerTypesSCSI DiskControllerTypes = "SCSI" +) + +// PossibleDiskControllerTypesValues returns the possible values for the DiskControllerTypes const type. +func PossibleDiskControllerTypesValues() []DiskControllerTypes { + return []DiskControllerTypes{ + DiskControllerTypesNVMe, + DiskControllerTypesSCSI, + } +} + +// DiskCreateOptionTypes - Specifies how the virtual machine disk should be created. Possible values are **Attach:** This +// value is used when you are using a specialized disk to create the virtual machine. **FromImage:** This value is used when +// you are using an image to create the virtual machine. If you are using a platform image, you should also use the imageReference +// element described above. If you are using a marketplace image, you should also use the plan element previously described. +// **Empty:** This value is used when creating an empty data disk. **Copy:** This value is used to create a data disk from +// a snapshot or another disk. **Restore:** This value is used to create a data disk from a disk restore point. +type DiskCreateOptionTypes string + +const ( + // DiskCreateOptionTypesAttach - Create disk by Attach + DiskCreateOptionTypesAttach DiskCreateOptionTypes = "Attach" + // DiskCreateOptionTypesCopy - Create disk by Copy + DiskCreateOptionTypesCopy DiskCreateOptionTypes = "Copy" + // DiskCreateOptionTypesEmpty - Empty value + DiskCreateOptionTypesEmpty DiskCreateOptionTypes = "Empty" + // DiskCreateOptionTypesFromImage - Create disk FromImage + DiskCreateOptionTypesFromImage DiskCreateOptionTypes = "FromImage" + // DiskCreateOptionTypesRestore - Create disk by Restore + DiskCreateOptionTypesRestore DiskCreateOptionTypes = "Restore" +) + +// PossibleDiskCreateOptionTypesValues returns the possible values for the DiskCreateOptionTypes const type. +func PossibleDiskCreateOptionTypesValues() []DiskCreateOptionTypes { + return []DiskCreateOptionTypes{ + DiskCreateOptionTypesAttach, + DiskCreateOptionTypesCopy, + DiskCreateOptionTypesEmpty, + DiskCreateOptionTypesFromImage, + DiskCreateOptionTypesRestore, + } +} + +// DiskDeleteOptionTypes - Specifies the behavior of the managed disk when the VM gets deleted, for example whether the managed +// disk is deleted or detached. Supported values are: **Delete.** If this value is used, the managed disk is deleted when +// VM gets deleted. **Detach.** If this value is used, the managed disk is retained after VM gets deleted. Minimum api-version: +// 2021-03-01. +type DiskDeleteOptionTypes string + +const ( + // DiskDeleteOptionTypesDelete - Delete the disk upon VM deletion + DiskDeleteOptionTypesDelete DiskDeleteOptionTypes = "Delete" + // DiskDeleteOptionTypesDetach - Detach the disk upon VM deletion + DiskDeleteOptionTypesDetach DiskDeleteOptionTypes = "Detach" +) + +// PossibleDiskDeleteOptionTypesValues returns the possible values for the DiskDeleteOptionTypes const type. +func PossibleDiskDeleteOptionTypesValues() []DiskDeleteOptionTypes { + return []DiskDeleteOptionTypes{ + DiskDeleteOptionTypesDelete, + DiskDeleteOptionTypesDetach, + } +} + +// DiskDetachOptionTypes - Specifies the detach behavior to be used while detaching a disk or which is already in the process +// of detachment from the virtual machine. Supported values are: **ForceDetach.** detachOption: **ForceDetach** is applicable +// only for managed data disks. If a previous detachment attempt of the data disk did not complete due to an unexpected failure +// from the virtual machine and the disk is still not released then use force-detach as a last resort option to detach the +// disk forcibly from the VM. All writes might not have been flushed when using this detach behavior. **This feature is still +// in preview**. To force-detach a data disk update toBeDetached to 'true' along with setting detachOption: 'ForceDetach'. +type DiskDetachOptionTypes string + +const ( + // DiskDetachOptionTypesForceDetach - ForceDetach the disk + DiskDetachOptionTypesForceDetach DiskDetachOptionTypes = "ForceDetach" +) + +// PossibleDiskDetachOptionTypesValues returns the possible values for the DiskDetachOptionTypes const type. +func PossibleDiskDetachOptionTypesValues() []DiskDetachOptionTypes { + return []DiskDetachOptionTypes{ + DiskDetachOptionTypesForceDetach, + } +} + +// DistributionStrategy - The distribution strategy for zone allocation +type DistributionStrategy string + +const ( + // DistributionStrategyBestEffortBalanced - Platform attempts to evenly distribute VMs across all available zones with best + // effort + DistributionStrategyBestEffortBalanced DistributionStrategy = "BestEffortBalanced" + // DistributionStrategyBestEffortSingleZone - Platform attempts to place as many VMs as possible in a single zone, falls back + // to multiple zones if needed + DistributionStrategyBestEffortSingleZone DistributionStrategy = "BestEffortSingleZone" + // DistributionStrategyPrioritized - Platform uses customer-provided zone rankings to allocate VMs + DistributionStrategyPrioritized DistributionStrategy = "Prioritized" + // DistributionStrategyStrictBalanced - Platform must evenly distribute VMs across zones, request is rejected if exact balance + // cannot be achieved + DistributionStrategyStrictBalanced DistributionStrategy = "StrictBalanced" +) + +// PossibleDistributionStrategyValues returns the possible values for the DistributionStrategy const type. +func PossibleDistributionStrategyValues() []DistributionStrategy { + return []DistributionStrategy{ + DistributionStrategyBestEffortBalanced, + DistributionStrategyBestEffortSingleZone, + DistributionStrategyPrioritized, + DistributionStrategyStrictBalanced, + } +} + +// DomainNameLabelScopeTypes - The Domain name label scope.The concatenation of the hashed domain name label that generated +// according to the policy from domain name label scope and vm index will be the domain name labels of the PublicIPAddress +// resources that will be created +type DomainNameLabelScopeTypes string + +const ( + // DomainNameLabelScopeTypesNoReuse - NoReuse scope type + DomainNameLabelScopeTypesNoReuse DomainNameLabelScopeTypes = "NoReuse" + // DomainNameLabelScopeTypesResourceGroupReuse - ResourceGroupReuse scope type + DomainNameLabelScopeTypesResourceGroupReuse DomainNameLabelScopeTypes = "ResourceGroupReuse" + // DomainNameLabelScopeTypesSubscriptionReuse - SubscriptionReuse scope type + DomainNameLabelScopeTypesSubscriptionReuse DomainNameLabelScopeTypes = "SubscriptionReuse" + // DomainNameLabelScopeTypesTenantReuse - TenantReuse scope type + DomainNameLabelScopeTypesTenantReuse DomainNameLabelScopeTypes = "TenantReuse" +) + +// PossibleDomainNameLabelScopeTypesValues returns the possible values for the DomainNameLabelScopeTypes const type. +func PossibleDomainNameLabelScopeTypesValues() []DomainNameLabelScopeTypes { + return []DomainNameLabelScopeTypes{ + DomainNameLabelScopeTypesNoReuse, + DomainNameLabelScopeTypesResourceGroupReuse, + DomainNameLabelScopeTypesSubscriptionReuse, + DomainNameLabelScopeTypesTenantReuse, + } +} + +// ExtendedLocationType - The supported ExtendedLocation types. +type ExtendedLocationType string + +const ( + // ExtendedLocationTypeCustomLocation - Azure Custom Locations type + ExtendedLocationTypeCustomLocation ExtendedLocationType = "CustomLocation" + // ExtendedLocationTypeEdgeZone - Azure Edge Zones location type + ExtendedLocationTypeEdgeZone ExtendedLocationType = "EdgeZone" +) + +// PossibleExtendedLocationTypeValues returns the possible values for the ExtendedLocationType const type. +func PossibleExtendedLocationTypeValues() []ExtendedLocationType { + return []ExtendedLocationType{ + ExtendedLocationTypeCustomLocation, + ExtendedLocationTypeEdgeZone, + } +} + +// IPVersions - Available from compute Api-Version 2017-03-30 onwards, it represents whether the specific ipconfiguration +// is IPv4 or IPv6. Default is taken as IPv4. Possible values are: 'IPv4' and 'IPv6'. +type IPVersions string + +const ( + // IPVersionsIPv4 - IPv4 version + IPVersionsIPv4 IPVersions = "IPv4" + // IPVersionsIPv6 - IPv6 version + IPVersionsIPv6 IPVersions = "IPv6" +) + +// PossibleIPVersionsValues returns the possible values for the IPVersions const type. +func PossibleIPVersionsValues() []IPVersions { + return []IPVersions{ + IPVersionsIPv4, + IPVersionsIPv6, + } +} + +// Language - The notification languages currently supported +type Language string + +const ( + // LanguageEnUs - American english language + LanguageEnUs Language = "en-us" +) + +// PossibleLanguageValues returns the possible values for the Language const type. +func PossibleLanguageValues() []Language { + return []Language{ + LanguageEnUs, + } +} + +// LinuxPatchAssessmentMode - Specifies the mode of VM Guest Patch Assessment for the IaaS virtual machine.

Possible +// values are:

**ImageDefault** - You control the timing of patch assessments on a virtual machine.

**AutomaticByPlatform** - The platform will trigger periodic patch assessments. The property provisionVMAgent must be +// true. +type LinuxPatchAssessmentMode string + +const ( + // LinuxPatchAssessmentModeAutomaticByPlatform - AutomaticByPlatform mode + LinuxPatchAssessmentModeAutomaticByPlatform LinuxPatchAssessmentMode = "AutomaticByPlatform" + // LinuxPatchAssessmentModeImageDefault - ImageDefault mode + LinuxPatchAssessmentModeImageDefault LinuxPatchAssessmentMode = "ImageDefault" +) + +// PossibleLinuxPatchAssessmentModeValues returns the possible values for the LinuxPatchAssessmentMode const type. +func PossibleLinuxPatchAssessmentModeValues() []LinuxPatchAssessmentMode { + return []LinuxPatchAssessmentMode{ + LinuxPatchAssessmentModeAutomaticByPlatform, + LinuxPatchAssessmentModeImageDefault, + } +} + +// LinuxVMGuestPatchAutomaticByPlatformRebootSetting - Specifies the reboot setting for all AutomaticByPlatform patch installation +// operations. +type LinuxVMGuestPatchAutomaticByPlatformRebootSetting string + +const ( + // LinuxVMGuestPatchAutomaticByPlatformRebootSettingAlways - Always reboot + LinuxVMGuestPatchAutomaticByPlatformRebootSettingAlways LinuxVMGuestPatchAutomaticByPlatformRebootSetting = "Always" + // LinuxVMGuestPatchAutomaticByPlatformRebootSettingIfRequired - Reboot if required + LinuxVMGuestPatchAutomaticByPlatformRebootSettingIfRequired LinuxVMGuestPatchAutomaticByPlatformRebootSetting = "IfRequired" + // LinuxVMGuestPatchAutomaticByPlatformRebootSettingNever - Never reboot + LinuxVMGuestPatchAutomaticByPlatformRebootSettingNever LinuxVMGuestPatchAutomaticByPlatformRebootSetting = "Never" + // LinuxVMGuestPatchAutomaticByPlatformRebootSettingUnknown - Unknown reboot setting + LinuxVMGuestPatchAutomaticByPlatformRebootSettingUnknown LinuxVMGuestPatchAutomaticByPlatformRebootSetting = "Unknown" +) + +// PossibleLinuxVMGuestPatchAutomaticByPlatformRebootSettingValues returns the possible values for the LinuxVMGuestPatchAutomaticByPlatformRebootSetting const type. +func PossibleLinuxVMGuestPatchAutomaticByPlatformRebootSettingValues() []LinuxVMGuestPatchAutomaticByPlatformRebootSetting { + return []LinuxVMGuestPatchAutomaticByPlatformRebootSetting{ + LinuxVMGuestPatchAutomaticByPlatformRebootSettingAlways, + LinuxVMGuestPatchAutomaticByPlatformRebootSettingIfRequired, + LinuxVMGuestPatchAutomaticByPlatformRebootSettingNever, + LinuxVMGuestPatchAutomaticByPlatformRebootSettingUnknown, + } +} + +// LinuxVMGuestPatchMode - Specifies the mode of VM Guest Patching to IaaS virtual machine or virtual machines associated +// to virtual machine scale set with OrchestrationMode as Flexible.

Possible values are:

**ImageDefault** +// - The virtual machine's default patching configuration is used.

**AutomaticByPlatform** - The virtual machine +// will be automatically updated by the platform. The property provisionVMAgent must be true +type LinuxVMGuestPatchMode string + +const ( + // LinuxVMGuestPatchModeAutomaticByPlatform - AutomaticByPlatform linux VM guest patch mode + LinuxVMGuestPatchModeAutomaticByPlatform LinuxVMGuestPatchMode = "AutomaticByPlatform" + // LinuxVMGuestPatchModeImageDefault - ImageDefault linux VM guest patch mode + LinuxVMGuestPatchModeImageDefault LinuxVMGuestPatchMode = "ImageDefault" +) + +// PossibleLinuxVMGuestPatchModeValues returns the possible values for the LinuxVMGuestPatchMode const type. +func PossibleLinuxVMGuestPatchModeValues() []LinuxVMGuestPatchMode { + return []LinuxVMGuestPatchMode{ + LinuxVMGuestPatchModeAutomaticByPlatform, + LinuxVMGuestPatchModeImageDefault, + } +} + +// Mode - Specifies the mode that ProxyAgent will execute on if the feature is enabled. ProxyAgent will start to audit or +// monitor but not enforce access control over requests to host endpoints in Audit mode, while in Enforce mode it will enforce +// access control. The default value is Enforce mode. +type Mode string + +const ( + // ModeAudit - Audit mode + ModeAudit Mode = "Audit" + // ModeEnforce - Enforce mode + ModeEnforce Mode = "Enforce" +) + +// PossibleModeValues returns the possible values for the Mode const type. +func PossibleModeValues() []Mode { + return []Mode{ + ModeAudit, + ModeEnforce, + } +} + +// Modes - Specifies the execution mode. In Audit mode, the system acts as if it is enforcing the access control policy, including +// emitting access denial entries in the logs but it does not actually deny any requests to host endpoints. In Enforce mode, +// the system will enforce the access control and it is the recommended mode of operation. +type Modes string + +const ( + // ModesAudit - Audit mode + ModesAudit Modes = "Audit" + // ModesDisabled - Disabled mode + ModesDisabled Modes = "Disabled" + // ModesEnforce - Enforce mode + ModesEnforce Modes = "Enforce" +) + +// PossibleModesValues returns the possible values for the Modes const type. +func PossibleModesValues() []Modes { + return []Modes{ + ModesAudit, + ModesDisabled, + ModesEnforce, + } +} + +// Month - Representation of the months available selection in a gregorian calendar +type Month string + +const ( + // MonthAll - All months + MonthAll Month = "All" + // MonthApril - The April month. + MonthApril Month = "April" + // MonthAugust - The August month. + MonthAugust Month = "August" + // MonthDecember - The December month. + MonthDecember Month = "December" + // MonthFebruary - The February month. + MonthFebruary Month = "February" + // MonthJanuary - The January month. + MonthJanuary Month = "January" + // MonthJuly - The July month. + MonthJuly Month = "July" + // MonthJune - The June month. + MonthJune Month = "June" + // MonthMarch - The March month. + MonthMarch Month = "March" + // MonthMay - The May month. + MonthMay Month = "May" + // MonthNovember - The November month. + MonthNovember Month = "November" + // MonthOctober - The October month. + MonthOctober Month = "October" + // MonthSeptember - The September month. + MonthSeptember Month = "September" +) + +// PossibleMonthValues returns the possible values for the Month const type. +func PossibleMonthValues() []Month { + return []Month{ + MonthAll, + MonthApril, + MonthAugust, + MonthDecember, + MonthFebruary, + MonthJanuary, + MonthJuly, + MonthJune, + MonthMarch, + MonthMay, + MonthNovember, + MonthOctober, + MonthSeptember, + } +} + +// NetworkAPIVersion - Specifies the Microsoft.Network API version used when creating networking resources in the Network +// Interface Configurations +type NetworkAPIVersion string + +const ( + // NetworkAPIVersion20201101 - 2020-11-01 version + NetworkAPIVersion20201101 NetworkAPIVersion = "2020-11-01" + // NetworkAPIVersion20221101 - 2022-11-01 version + NetworkAPIVersion20221101 NetworkAPIVersion = "2022-11-01" +) + +// PossibleNetworkAPIVersionValues returns the possible values for the NetworkAPIVersion const type. +func PossibleNetworkAPIVersionValues() []NetworkAPIVersion { + return []NetworkAPIVersion{ + NetworkAPIVersion20201101, + NetworkAPIVersion20221101, + } +} + +// NetworkInterfaceAuxiliaryMode - Specifies whether the Auxiliary mode is enabled for the Network Interface resource. +type NetworkInterfaceAuxiliaryMode string + +const ( + // NetworkInterfaceAuxiliaryModeAcceleratedConnections - AcceleratedConnections mode + NetworkInterfaceAuxiliaryModeAcceleratedConnections NetworkInterfaceAuxiliaryMode = "AcceleratedConnections" + // NetworkInterfaceAuxiliaryModeFloating - Floating mode + NetworkInterfaceAuxiliaryModeFloating NetworkInterfaceAuxiliaryMode = "Floating" + // NetworkInterfaceAuxiliaryModeNone - None mode + NetworkInterfaceAuxiliaryModeNone NetworkInterfaceAuxiliaryMode = "None" +) + +// PossibleNetworkInterfaceAuxiliaryModeValues returns the possible values for the NetworkInterfaceAuxiliaryMode const type. +func PossibleNetworkInterfaceAuxiliaryModeValues() []NetworkInterfaceAuxiliaryMode { + return []NetworkInterfaceAuxiliaryMode{ + NetworkInterfaceAuxiliaryModeAcceleratedConnections, + NetworkInterfaceAuxiliaryModeFloating, + NetworkInterfaceAuxiliaryModeNone, + } +} + +// NetworkInterfaceAuxiliarySKU - Specifies whether the Auxiliary sku is enabled for the Network Interface resource. +type NetworkInterfaceAuxiliarySKU string + +const ( + // NetworkInterfaceAuxiliarySKUA1 - A1 sku + NetworkInterfaceAuxiliarySKUA1 NetworkInterfaceAuxiliarySKU = "A1" + // NetworkInterfaceAuxiliarySKUA2 - A2 sku + NetworkInterfaceAuxiliarySKUA2 NetworkInterfaceAuxiliarySKU = "A2" + // NetworkInterfaceAuxiliarySKUA4 - A4 sku + NetworkInterfaceAuxiliarySKUA4 NetworkInterfaceAuxiliarySKU = "A4" + // NetworkInterfaceAuxiliarySKUA8 - A8 sku + NetworkInterfaceAuxiliarySKUA8 NetworkInterfaceAuxiliarySKU = "A8" + // NetworkInterfaceAuxiliarySKUNone - None: None sku + NetworkInterfaceAuxiliarySKUNone NetworkInterfaceAuxiliarySKU = "None" +) + +// PossibleNetworkInterfaceAuxiliarySKUValues returns the possible values for the NetworkInterfaceAuxiliarySKU const type. +func PossibleNetworkInterfaceAuxiliarySKUValues() []NetworkInterfaceAuxiliarySKU { + return []NetworkInterfaceAuxiliarySKU{ + NetworkInterfaceAuxiliarySKUA1, + NetworkInterfaceAuxiliarySKUA2, + NetworkInterfaceAuxiliarySKUA4, + NetworkInterfaceAuxiliarySKUA8, + NetworkInterfaceAuxiliarySKUNone, + } +} + +// NotificationType - The type of notification supported +type NotificationType string + +const ( + // NotificationTypeEmail - Notify through e-mail + NotificationTypeEmail NotificationType = "Email" +) + +// PossibleNotificationTypeValues returns the possible values for the NotificationType const type. +func PossibleNotificationTypeValues() []NotificationType { + return []NotificationType{ + NotificationTypeEmail, + } +} + +// OccurrenceState - The state the occurrence is at a given time +type OccurrenceState string + +const ( + // OccurrenceStateCanceled - The occurrence has been canceled + OccurrenceStateCanceled OccurrenceState = "Canceled" + // OccurrenceStateCancelling - The occurrence is going through cancellation + OccurrenceStateCancelling OccurrenceState = "Cancelling" + // OccurrenceStateCreated - The occurrence was created + OccurrenceStateCreated OccurrenceState = "Created" + // OccurrenceStateFailed - The occurrence has failed during its scheduling + OccurrenceStateFailed OccurrenceState = "Failed" + // OccurrenceStateRescheduling - The occurrence is being rescheduled + OccurrenceStateRescheduling OccurrenceState = "Rescheduling" + // OccurrenceStateScheduled - The occurrence has been scheduled + OccurrenceStateScheduled OccurrenceState = "Scheduled" + // OccurrenceStateSucceeded - The occurrence has successfully ran + OccurrenceStateSucceeded OccurrenceState = "Succeeded" +) + +// PossibleOccurrenceStateValues returns the possible values for the OccurrenceState const type. +func PossibleOccurrenceStateValues() []OccurrenceState { + return []OccurrenceState{ + OccurrenceStateCanceled, + OccurrenceStateCancelling, + OccurrenceStateCreated, + OccurrenceStateFailed, + OccurrenceStateRescheduling, + OccurrenceStateScheduled, + OccurrenceStateSucceeded, + } +} + +// OperatingSystemTypes - This property allows you to specify the supported type of the OS that application is built for. +// Possible values are: **Windows,** **Linux.** +type OperatingSystemTypes string + +const ( + // OperatingSystemTypesLinux - Linux OS + OperatingSystemTypesLinux OperatingSystemTypes = "Linux" + // OperatingSystemTypesWindows - Windows OS + OperatingSystemTypesWindows OperatingSystemTypes = "Windows" +) + +// PossibleOperatingSystemTypesValues returns the possible values for the OperatingSystemTypes const type. +func PossibleOperatingSystemTypesValues() []OperatingSystemTypes { + return []OperatingSystemTypes{ + OperatingSystemTypesLinux, + OperatingSystemTypesWindows, + } +} + +// OperationState - Values that define the states of operations in Scheduled Actions +type OperationState string + +const ( + // OperationStateBlocked - Operations that are blocked + OperationStateBlocked OperationState = "Blocked" + // OperationStateCancelled - Operations that have been Cancelled by the user + OperationStateCancelled OperationState = "Cancelled" + // OperationStateExecuting - Operations that are in the process of being executed + OperationStateExecuting OperationState = "Executing" + // OperationStateFailed - Operations that have failed + OperationStateFailed OperationState = "Failed" + // OperationStatePendingExecution - Operations that are waiting to be executed + OperationStatePendingExecution OperationState = "PendingExecution" + // OperationStatePendingScheduling - Operations that are pending scheduling + OperationStatePendingScheduling OperationState = "PendingScheduling" + // OperationStateScheduled - Operations that have been scheduled + OperationStateScheduled OperationState = "Scheduled" + // OperationStateSucceeded - Operations that suceeded + OperationStateSucceeded OperationState = "Succeeded" + // OperationStateUnknown - The default value for the operation state enum + OperationStateUnknown OperationState = "Unknown" +) + +// PossibleOperationStateValues returns the possible values for the OperationState const type. +func PossibleOperationStateValues() []OperationState { + return []OperationState{ + OperationStateBlocked, + OperationStateCancelled, + OperationStateExecuting, + OperationStateFailed, + OperationStatePendingExecution, + OperationStatePendingScheduling, + OperationStateScheduled, + OperationStateSucceeded, + OperationStateUnknown, + } +} + +// OptimizationPreference - The preferences customers can select to optimize their requests to ScheduledActions +type OptimizationPreference string + +const ( + // OptimizationPreferenceAvailability - Optimize while considering availability of resources + OptimizationPreferenceAvailability OptimizationPreference = "Availability" + // OptimizationPreferenceCost - Optimize while considering cost savings + OptimizationPreferenceCost OptimizationPreference = "Cost" + // OptimizationPreferenceCostAvailabilityBalanced - Optimize while considering a balance of cost and availability + OptimizationPreferenceCostAvailabilityBalanced OptimizationPreference = "CostAvailabilityBalanced" +) + +// PossibleOptimizationPreferenceValues returns the possible values for the OptimizationPreference const type. +func PossibleOptimizationPreferenceValues() []OptimizationPreference { + return []OptimizationPreference{ + OptimizationPreferenceAvailability, + OptimizationPreferenceCost, + OptimizationPreferenceCostAvailabilityBalanced, + } +} + +// Origin - The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default +// value is "user,system" +type Origin string + +const ( + // OriginSystem - Indicates the operation is initiated by a system. + OriginSystem Origin = "system" + // OriginUser - Indicates the operation is initiated by a user. + OriginUser Origin = "user" + // OriginUserSystem - Indicates the operation is initiated by a user or system. + OriginUserSystem Origin = "user,system" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginSystem, + OriginUser, + OriginUserSystem, + } +} + +// OsType - The supported operating system types for flex VM creation +type OsType string + +const ( + // OsTypeLinux - Linux operating system + OsTypeLinux OsType = "Linux" + // OsTypeWindows - Windows operating system + OsTypeWindows OsType = "Windows" +) + +// PossibleOsTypeValues returns the possible values for the OsType const type. +func PossibleOsTypeValues() []OsType { + return []OsType{ + OsTypeLinux, + OsTypeWindows, + } +} + +// PriorityType - The priority type for VM allocation +type PriorityType string + +const ( + // PriorityTypeRegular - Regular priority VMs + PriorityTypeRegular PriorityType = "Regular" + // PriorityTypeSpot - Spot priority VMs + PriorityTypeSpot PriorityType = "Spot" +) + +// PossiblePriorityTypeValues returns the possible values for the PriorityType const type. +func PossiblePriorityTypeValues() []PriorityType { + return []PriorityType{ + PriorityTypeRegular, + PriorityTypeSpot, + } +} + +// ProtocolTypes - Specifies the protocol of WinRM listener. Possible values are: **http,** **https.** +type ProtocolTypes string + +const ( + // ProtocolTypesHTTP - Http protocol + ProtocolTypesHTTP ProtocolTypes = "Http" + // ProtocolTypesHTTPS - Https protocol + ProtocolTypesHTTPS ProtocolTypes = "Https" +) + +// PossibleProtocolTypesValues returns the possible values for the ProtocolTypes const type. +func PossibleProtocolTypesValues() []ProtocolTypes { + return []ProtocolTypes{ + ProtocolTypesHTTP, + ProtocolTypesHTTPS, + } +} + +// ProvisioningState - Provisioning state +type ProvisioningState string + +const ( + // ProvisioningStateCanceled - Resource creation was canceled. + ProvisioningStateCanceled ProvisioningState = "Canceled" + // ProvisioningStateDeleting - Resource is being deleted. + ProvisioningStateDeleting ProvisioningState = "Deleting" + // ProvisioningStateFailed - Resource creation failed. + ProvisioningStateFailed ProvisioningState = "Failed" + // ProvisioningStateSucceeded - Resource has been created. + ProvisioningStateSucceeded ProvisioningState = "Succeeded" +) + +// PossibleProvisioningStateValues returns the possible values for the ProvisioningState const type. +func PossibleProvisioningStateValues() []ProvisioningState { + return []ProvisioningState{ + ProvisioningStateCanceled, + ProvisioningStateDeleting, + ProvisioningStateFailed, + ProvisioningStateSucceeded, + } +} + +// PublicIPAddressSKUName - Specify public IP sku name +type PublicIPAddressSKUName string + +const ( + // PublicIPAddressSKUNameBasic - Basic IP sku name + PublicIPAddressSKUNameBasic PublicIPAddressSKUName = "Basic" + // PublicIPAddressSKUNameStandard - Standard IP sku name + PublicIPAddressSKUNameStandard PublicIPAddressSKUName = "Standard" +) + +// PossiblePublicIPAddressSKUNameValues returns the possible values for the PublicIPAddressSKUName const type. +func PossiblePublicIPAddressSKUNameValues() []PublicIPAddressSKUName { + return []PublicIPAddressSKUName{ + PublicIPAddressSKUNameBasic, + PublicIPAddressSKUNameStandard, + } +} + +// PublicIPAddressSKUTier - Specify public IP sku tier +type PublicIPAddressSKUTier string + +const ( + // PublicIPAddressSKUTierGlobal - Global IP address sku tier + PublicIPAddressSKUTierGlobal PublicIPAddressSKUTier = "Global" + // PublicIPAddressSKUTierRegional - Regional IP address sku tier + PublicIPAddressSKUTierRegional PublicIPAddressSKUTier = "Regional" +) + +// PossiblePublicIPAddressSKUTierValues returns the possible values for the PublicIPAddressSKUTier const type. +func PossiblePublicIPAddressSKUTierValues() []PublicIPAddressSKUTier { + return []PublicIPAddressSKUTier{ + PublicIPAddressSKUTierGlobal, + PublicIPAddressSKUTierRegional, + } +} + +// PublicIPAllocationMethod - Specify the public IP allocation type +type PublicIPAllocationMethod string + +const ( + // PublicIPAllocationMethodDynamic - Dynamic IP allocation + PublicIPAllocationMethodDynamic PublicIPAllocationMethod = "Dynamic" + // PublicIPAllocationMethodStatic - Static IP allocation + PublicIPAllocationMethodStatic PublicIPAllocationMethod = "Static" +) + +// PossiblePublicIPAllocationMethodValues returns the possible values for the PublicIPAllocationMethod const type. +func PossiblePublicIPAllocationMethodValues() []PublicIPAllocationMethod { + return []PublicIPAllocationMethod{ + PublicIPAllocationMethodDynamic, + PublicIPAllocationMethodStatic, + } +} + +// ResourceIdentityType - The type of identity used for the virtual machine scale set. The type 'SystemAssigned, UserAssigned' +// includes both an implicitly created identity and a set of user assigned identities. The type 'None' will remove any identities +// from the virtual machine scale set. +type ResourceIdentityType string + +const ( + ResourceIdentityTypeNone ResourceIdentityType = "None" + ResourceIdentityTypeSystemAssigned ResourceIdentityType = "SystemAssigned" + ResourceIdentityTypeSystemAssignedUserAssigned ResourceIdentityType = "SystemAssigned, UserAssigned" + ResourceIdentityTypeUserAssigned ResourceIdentityType = "UserAssigned" +) + +// PossibleResourceIdentityTypeValues returns the possible values for the ResourceIdentityType const type. +func PossibleResourceIdentityTypeValues() []ResourceIdentityType { + return []ResourceIdentityType{ + ResourceIdentityTypeNone, + ResourceIdentityTypeSystemAssigned, + ResourceIdentityTypeSystemAssignedUserAssigned, + ResourceIdentityTypeUserAssigned, + } +} + +// ResourceOperationStatus - The state the resource is on after the resource operation is applied +type ResourceOperationStatus string + +const ( + // ResourceOperationStatusFailed - The resource operation has failed. + ResourceOperationStatusFailed ResourceOperationStatus = "Failed" + // ResourceOperationStatusSucceeded - The resource operation was successful + ResourceOperationStatusSucceeded ResourceOperationStatus = "Succeeded" +) + +// PossibleResourceOperationStatusValues returns the possible values for the ResourceOperationStatus const type. +func PossibleResourceOperationStatusValues() []ResourceOperationStatus { + return []ResourceOperationStatus{ + ResourceOperationStatusFailed, + ResourceOperationStatusSucceeded, + } +} + +// ResourceOperationType - The kind of operation types that can be performed on resources using ScheduledActions +type ResourceOperationType string + +const ( + // ResourceOperationTypeCreate - Create operations on the resources + ResourceOperationTypeCreate ResourceOperationType = "Create" + // ResourceOperationTypeDeallocate - Deallocate operations on the resources + ResourceOperationTypeDeallocate ResourceOperationType = "Deallocate" + // ResourceOperationTypeDelete - Delete operations on the resources + ResourceOperationTypeDelete ResourceOperationType = "Delete" + // ResourceOperationTypeHibernate - Hibernate operations on the resources + ResourceOperationTypeHibernate ResourceOperationType = "Hibernate" + // ResourceOperationTypeStart - Start operations on the resources + ResourceOperationTypeStart ResourceOperationType = "Start" + // ResourceOperationTypeUnknown - The default value for this enum type + ResourceOperationTypeUnknown ResourceOperationType = "Unknown" +) + +// PossibleResourceOperationTypeValues returns the possible values for the ResourceOperationType const type. +func PossibleResourceOperationTypeValues() []ResourceOperationType { + return []ResourceOperationType{ + ResourceOperationTypeCreate, + ResourceOperationTypeDeallocate, + ResourceOperationTypeDelete, + ResourceOperationTypeHibernate, + ResourceOperationTypeStart, + ResourceOperationTypeUnknown, + } +} + +// ResourceProvisioningState - The provisioning state of a resource type. +type ResourceProvisioningState string + +const ( + // ResourceProvisioningStateCanceled - Resource creation was canceled. + ResourceProvisioningStateCanceled ResourceProvisioningState = "Canceled" + // ResourceProvisioningStateFailed - Resource creation failed. + ResourceProvisioningStateFailed ResourceProvisioningState = "Failed" + // ResourceProvisioningStateSucceeded - Resource has been created. + ResourceProvisioningStateSucceeded ResourceProvisioningState = "Succeeded" +) + +// PossibleResourceProvisioningStateValues returns the possible values for the ResourceProvisioningState const type. +func PossibleResourceProvisioningStateValues() []ResourceProvisioningState { + return []ResourceProvisioningState{ + ResourceProvisioningStateCanceled, + ResourceProvisioningStateFailed, + ResourceProvisioningStateSucceeded, + } +} + +// ResourceType - The type of resource being targeted +type ResourceType string + +const ( + // ResourceTypeVirtualMachine - Resources defined are Virtual Machines + ResourceTypeVirtualMachine ResourceType = "VirtualMachine" + // ResourceTypeVirtualMachineScaleSet - Resources defined are Virtual Machines Scale Sets + ResourceTypeVirtualMachineScaleSet ResourceType = "VirtualMachineScaleSet" +) + +// PossibleResourceTypeValues returns the possible values for the ResourceType const type. +func PossibleResourceTypeValues() []ResourceType { + return []ResourceType{ + ResourceTypeVirtualMachine, + ResourceTypeVirtualMachineScaleSet, + } +} + +// ScheduledActionType - Specify which action user wants to be performed on the resources +type ScheduledActionType string + +const ( + // ScheduledActionTypeDeallocate - Perform a deallocate action on the specified resources + ScheduledActionTypeDeallocate ScheduledActionType = "Deallocate" + // ScheduledActionTypeHibernate - Perform hibernate and deallocate on the specified resources + ScheduledActionTypeHibernate ScheduledActionType = "Hibernate" + // ScheduledActionTypeStart - Perform a start action on the specified resources + ScheduledActionTypeStart ScheduledActionType = "Start" +) + +// PossibleScheduledActionTypeValues returns the possible values for the ScheduledActionType const type. +func PossibleScheduledActionTypeValues() []ScheduledActionType { + return []ScheduledActionType{ + ScheduledActionTypeDeallocate, + ScheduledActionTypeHibernate, + ScheduledActionTypeStart, + } +} + +// SecurityEncryptionTypes - Specifies the EncryptionType of the managed disk. It is set to DiskWithVMGuestState for encryption +// of the managed disk along with VMGuestState blob, VMGuestStateOnly for encryption of just the VMGuestState blob, and NonPersistedTPM +// for not persisting firmware state in the VMGuestState blob.. **Note:** It can be set for only Confidential VMs. +type SecurityEncryptionTypes string + +const ( + // SecurityEncryptionTypesDiskWithVMGuestState - DiskWithVMGuestState encryption + SecurityEncryptionTypesDiskWithVMGuestState SecurityEncryptionTypes = "DiskWithVMGuestState" + // SecurityEncryptionTypesNonPersistedTPM - NonPersistedTPM encryption + SecurityEncryptionTypesNonPersistedTPM SecurityEncryptionTypes = "NonPersistedTPM" + // SecurityEncryptionTypesVMGuestStateOnly - VMGuestStateOnly encryption + SecurityEncryptionTypesVMGuestStateOnly SecurityEncryptionTypes = "VMGuestStateOnly" +) + +// PossibleSecurityEncryptionTypesValues returns the possible values for the SecurityEncryptionTypes const type. +func PossibleSecurityEncryptionTypesValues() []SecurityEncryptionTypes { + return []SecurityEncryptionTypes{ + SecurityEncryptionTypesDiskWithVMGuestState, + SecurityEncryptionTypesNonPersistedTPM, + SecurityEncryptionTypesVMGuestStateOnly, + } +} + +// SecurityTypes - Specifies the SecurityType of the virtual machine. It has to be set to any specified value to enable UefiSettings. +// The default behavior is: UefiSettings will not be enabled unless this property is set. +type SecurityTypes string + +const ( + // SecurityTypesConfidentialVM - ConfidentialVM security type + SecurityTypesConfidentialVM SecurityTypes = "ConfidentialVM" + // SecurityTypesTrustedLaunch - TrustedLaunch security type + SecurityTypesTrustedLaunch SecurityTypes = "TrustedLaunch" +) + +// PossibleSecurityTypesValues returns the possible values for the SecurityTypes const type. +func PossibleSecurityTypesValues() []SecurityTypes { + return []SecurityTypes{ + SecurityTypesConfidentialVM, + SecurityTypesTrustedLaunch, + } +} + +// SettingNames - Specifies the name of the setting to which the content applies. Possible values are: FirstLogonCommands +// and AutoLogon. +type SettingNames string + +const ( + // SettingNamesAutoLogon - AutoLogon mode + SettingNamesAutoLogon SettingNames = "AutoLogon" + // SettingNamesFirstLogonCommands - FirstLogonCommands mode + SettingNamesFirstLogonCommands SettingNames = "FirstLogonCommands" +) + +// PossibleSettingNamesValues returns the possible values for the SettingNames const type. +func PossibleSettingNamesValues() []SettingNames { + return []SettingNames{ + SettingNamesAutoLogon, + SettingNamesFirstLogonCommands, + } +} + +// StorageAccountTypes - Specifies the storage account type for the managed disk. Managed OS disk storage account type can +// only be set when you create the scale set. NOTE: UltraSSD_LRS can only be used with data disks. It cannot be used with +// OS Disk. Standard_LRS uses Standard HDD. StandardSSD_LRS uses Standard SSD. Premium_LRS uses Premium SSD. UltraSSD_LRS +// uses Ultra disk. Premium_ZRS uses Premium SSD zone redundant storage. StandardSSD_ZRS uses Standard SSD zone redundant +// storage. For more information regarding disks supported for Windows Virtual Machines, refer to https://docs.microsoft.com/azure/virtual-machines/windows/disks-types +// and, for Linux Virtual Machines, refer to https://docs.microsoft.com/azure/virtual-machines/linux/disks-types +type StorageAccountTypes string + +const ( + // StorageAccountTypesPremiumLRS - Premium_LRS storage account type + StorageAccountTypesPremiumLRS StorageAccountTypes = "Premium_LRS" + // StorageAccountTypesPremiumV2LRS - PremiumV2_LRS storage account type + StorageAccountTypesPremiumV2LRS StorageAccountTypes = "PremiumV2_LRS" + // StorageAccountTypesPremiumZRS - Premium_ZRS storage account type + StorageAccountTypesPremiumZRS StorageAccountTypes = "Premium_ZRS" + // StorageAccountTypesStandardLRS - Standard_LRS storage account type + StorageAccountTypesStandardLRS StorageAccountTypes = "Standard_LRS" + // StorageAccountTypesStandardSSDLRS - StandardSSD_LRS storage account type + StorageAccountTypesStandardSSDLRS StorageAccountTypes = "StandardSSD_LRS" + // StorageAccountTypesStandardSSDZRS - StandardSSD_ZRS storage account type + StorageAccountTypesStandardSSDZRS StorageAccountTypes = "StandardSSD_ZRS" + // StorageAccountTypesUltraSSDLRS - UltraSSD_LRS storage account type + StorageAccountTypesUltraSSDLRS StorageAccountTypes = "UltraSSD_LRS" +) + +// PossibleStorageAccountTypesValues returns the possible values for the StorageAccountTypes const type. +func PossibleStorageAccountTypesValues() []StorageAccountTypes { + return []StorageAccountTypes{ + StorageAccountTypesPremiumLRS, + StorageAccountTypesPremiumV2LRS, + StorageAccountTypesPremiumZRS, + StorageAccountTypesStandardLRS, + StorageAccountTypesStandardSSDLRS, + StorageAccountTypesStandardSSDZRS, + StorageAccountTypesUltraSSDLRS, + } +} + +// WeekDay - Representation of the possible selection of days in a week in a gregorian calendar +type WeekDay string + +const ( + // WeekDayAll - All week days + WeekDayAll WeekDay = "All" + // WeekDayFriday - Friday weekday. + WeekDayFriday WeekDay = "Friday" + // WeekDayMonday - Monday weekday. + WeekDayMonday WeekDay = "Monday" + // WeekDaySaturday - Saturday weekday. + WeekDaySaturday WeekDay = "Saturday" + // WeekDaySunday - Sunday weekday. + WeekDaySunday WeekDay = "Sunday" + // WeekDayThursday - Thursday weekday. + WeekDayThursday WeekDay = "Thursday" + // WeekDayTuesday - Tuesday weekday. + WeekDayTuesday WeekDay = "Tuesday" + // WeekDayWednesday - Wednesday weekday. + WeekDayWednesday WeekDay = "Wednesday" +) + +// PossibleWeekDayValues returns the possible values for the WeekDay const type. +func PossibleWeekDayValues() []WeekDay { + return []WeekDay{ + WeekDayAll, + WeekDayFriday, + WeekDayMonday, + WeekDaySaturday, + WeekDaySunday, + WeekDayThursday, + WeekDayTuesday, + WeekDayWednesday, + } +} + +// WindowsPatchAssessmentMode - Specifies the mode of VM Guest patch assessment for the IaaS virtual machine.

+// Possible values are:

**ImageDefault** - You control the timing of patch assessments on a virtual machine.

**AutomaticByPlatform** - The platform will trigger periodic patch assessments. The property provisionVMAgent +// must be true. +type WindowsPatchAssessmentMode string + +const ( + // WindowsPatchAssessmentModeAutomaticByPlatform - AutomaticByPlatform patch assessment mode + WindowsPatchAssessmentModeAutomaticByPlatform WindowsPatchAssessmentMode = "AutomaticByPlatform" + // WindowsPatchAssessmentModeImageDefault - ImageDefault patch assessment mode + WindowsPatchAssessmentModeImageDefault WindowsPatchAssessmentMode = "ImageDefault" +) + +// PossibleWindowsPatchAssessmentModeValues returns the possible values for the WindowsPatchAssessmentMode const type. +func PossibleWindowsPatchAssessmentModeValues() []WindowsPatchAssessmentMode { + return []WindowsPatchAssessmentMode{ + WindowsPatchAssessmentModeAutomaticByPlatform, + WindowsPatchAssessmentModeImageDefault, + } +} + +// WindowsVMGuestPatchAutomaticByPlatformRebootSetting - Specifies the reboot setting for all AutomaticByPlatform patch installation +// operations. +type WindowsVMGuestPatchAutomaticByPlatformRebootSetting string + +const ( + // WindowsVMGuestPatchAutomaticByPlatformRebootSettingAlways - Reboot setting for Always + WindowsVMGuestPatchAutomaticByPlatformRebootSettingAlways WindowsVMGuestPatchAutomaticByPlatformRebootSetting = "Always" + // WindowsVMGuestPatchAutomaticByPlatformRebootSettingIfRequired - Reboot setting for IfRequired + WindowsVMGuestPatchAutomaticByPlatformRebootSettingIfRequired WindowsVMGuestPatchAutomaticByPlatformRebootSetting = "IfRequired" + // WindowsVMGuestPatchAutomaticByPlatformRebootSettingNever - Reboot setting for Never + WindowsVMGuestPatchAutomaticByPlatformRebootSettingNever WindowsVMGuestPatchAutomaticByPlatformRebootSetting = "Never" + // WindowsVMGuestPatchAutomaticByPlatformRebootSettingUnknown - Reboot setting for Unknown + WindowsVMGuestPatchAutomaticByPlatformRebootSettingUnknown WindowsVMGuestPatchAutomaticByPlatformRebootSetting = "Unknown" +) + +// PossibleWindowsVMGuestPatchAutomaticByPlatformRebootSettingValues returns the possible values for the WindowsVMGuestPatchAutomaticByPlatformRebootSetting const type. +func PossibleWindowsVMGuestPatchAutomaticByPlatformRebootSettingValues() []WindowsVMGuestPatchAutomaticByPlatformRebootSetting { + return []WindowsVMGuestPatchAutomaticByPlatformRebootSetting{ + WindowsVMGuestPatchAutomaticByPlatformRebootSettingAlways, + WindowsVMGuestPatchAutomaticByPlatformRebootSettingIfRequired, + WindowsVMGuestPatchAutomaticByPlatformRebootSettingNever, + WindowsVMGuestPatchAutomaticByPlatformRebootSettingUnknown, + } +} + +// WindowsVMGuestPatchMode - Specifies the mode of VM Guest Patching to IaaS virtual machine or virtual machines associated +// to virtual machine scale set with OrchestrationMode as Flexible.

Possible values are:

**Manual** +// - You control the application of patches to a virtual machine. You do this by applying patches manually inside the VM. +// In this mode, automatic updates are disabled; the property WindowsConfiguration.enableAutomaticUpdates must be false

**AutomaticByOS** - The virtual machine will automatically be updated by the OS. The property WindowsConfiguration.enableAutomaticUpdates +// must be true.

**AutomaticByPlatform** - the virtual machine will automatically updated by the platform. The +// properties provisionVMAgent and WindowsConfiguration.enableAutomaticUpdates must be true +type WindowsVMGuestPatchMode string + +const ( + // WindowsVMGuestPatchModeAutomaticByOS - AutomaticByOS VM guest patch mode + WindowsVMGuestPatchModeAutomaticByOS WindowsVMGuestPatchMode = "AutomaticByOS" + // WindowsVMGuestPatchModeAutomaticByPlatform - AutomaticByPlatform VM guest patch mode + WindowsVMGuestPatchModeAutomaticByPlatform WindowsVMGuestPatchMode = "AutomaticByPlatform" + // WindowsVMGuestPatchModeManual - Manual VM guest patch mode + WindowsVMGuestPatchModeManual WindowsVMGuestPatchMode = "Manual" +) + +// PossibleWindowsVMGuestPatchModeValues returns the possible values for the WindowsVMGuestPatchMode const type. +func PossibleWindowsVMGuestPatchModeValues() []WindowsVMGuestPatchMode { + return []WindowsVMGuestPatchMode{ + WindowsVMGuestPatchModeAutomaticByOS, + WindowsVMGuestPatchModeAutomaticByPlatform, + WindowsVMGuestPatchModeManual, + } +} + +// ZonePlacementPolicyType - Specifies the policy for resource's placement in availability zone. Possible values are: **Any** +// (used for Virtual Machines), **Auto** (used for Virtual Machine Scale Sets) - An availability zone will be automatically +// picked by system as part of resource creation. +type ZonePlacementPolicyType string + +const ( + ZonePlacementPolicyTypeAny ZonePlacementPolicyType = "Any" + // ZonePlacementPolicyTypeAuto - The platform automatically selects an availability zone based on the request. + ZonePlacementPolicyTypeAuto ZonePlacementPolicyType = "Auto" +) + +// PossibleZonePlacementPolicyTypeValues returns the possible values for the ZonePlacementPolicyType const type. +func PossibleZonePlacementPolicyTypeValues() []ZonePlacementPolicyType { + return []ZonePlacementPolicyType{ + ZonePlacementPolicyTypeAny, + ZonePlacementPolicyTypeAuto, + } +} diff --git a/test/local/armcomputeschedule/zz_models.go b/test/local/armcomputeschedule/zz_models.go new file mode 100644 index 000000000000..2882723331fd --- /dev/null +++ b/test/local/armcomputeschedule/zz_models.go @@ -0,0 +1,2193 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcomputeschedule + +import "time" + +// APIEntityReference - The API entity reference. +type APIEntityReference struct { + // The ARM resource id in the form of /subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroupName}/... + ID *string +} + +// AdditionalCapabilities - Enables or disables a capability on the virtual machine or virtual machine scale set. +type AdditionalCapabilities struct { + // The flag that enables or disables hibernation capability on the VM. + HibernationEnabled *bool + + // The flag that enables or disables a capability to have one or more managed data disks with UltraSSD_LRS storage account + // type on the VM or VMSS. Managed disks with storage account type UltraSSD_LRS can be added to a virtual machine or virtual + // machine scale set only if this property is enabled. + UltraSSDEnabled *bool +} + +// AdditionalUnattendContent - Specifies additional XML formatted information that can be included in the Unattend.xml file, +// which is used by Windows Setup. Contents are defined by setting name, component name, and the pass in which the content +// is applied. +type AdditionalUnattendContent struct { + // FLAG; CONSTANT; The component name. Currently, the only allowable value is Microsoft-Windows-Shell-Setup. + // Field has constant value "Microsoft-Windows-Shell-Setup", any specified value is ignored. + ComponentName *string + + // Specifies the XML formatted content that is added to the unattend.xml file for the specified path and component. The XML + // must be less than 4KB and must include the root element for the setting or feature that is being inserted. + Content *string + + // FLAG; CONSTANT; The pass name. Currently, the only allowable value is OobeSystem. + // Field has constant value "OobeSystem", any specified value is ignored. + PassName *string + + // Specifies the name of the setting to which the content applies. Possible values are: FirstLogonCommands and AutoLogon. + SettingName *SettingNames +} + +// AllInstancesDown - Specifies if Scheduled Events should be auto-approved when all instances are down. +type AllInstancesDown struct { + // Specifies if Scheduled Events should be auto-approved when all instances are down. Its default value is true. + AutomaticallyApprove *bool +} + +// ApplicationProfile - Contains the list of gallery applications that should be made available to the VM +type ApplicationProfile struct { + // Specifies the gallery applications that should be made available to the VM + GalleryApplications []*VMGalleryApplication +} + +// BootDiagnostics - Boot Diagnostics is a debugging feature which allows you to view Console Output and Screenshot to diagnose +// VM status. You can easily view the output of your console log. Azure also enables you to see a screenshot of the VM from +// the hypervisor. +type BootDiagnostics struct { + // Whether boot diagnostics should be enabled on the Virtual Machine. + Enabled *bool + + // Uri of the storage account to use for placing the console output and screenshot. If storageUri is not specified while enabling + // boot diagnostics, managed storage will be used. + StorageURI *string +} + +// BulkActionVMExtension - Defines a virtual machine extension. +type BulkActionVMExtension struct { + // REQUIRED; The name of the virtual machine extension. + Name *string + + // REQUIRED; Properties of the virtual machine extension. + Properties *BulkActionVMExtensionProperties +} + +// BulkActionVMExtensionProperties - Describes the properties of a Virtual Machine Extension. +type BulkActionVMExtensionProperties struct { + // Indicates whether the extension should use a newer minor version if one is available at deployment time. Once deployed, + // however, the extension will not upgrade minor versions unless redeployed, even with this property set to true. + AutoUpgradeMinorVersion *bool + + // Indicates whether the extension should be automatically upgraded by the platform if there is a newer version of the extension + // available. + EnableAutomaticUpgrade *bool + + // How the extension handler should be forced to update even if the extension configuration has not changed. + ForceUpdateTag *string + + // The extension can contain either protectedSettings or protectedSettingsFromKeyVault or no protected settings at all. + ProtectedSettings map[string]any + + // The extensions protected settings that are passed by reference, and consumed from key vault + ProtectedSettingsFromKeyVault *KeyVaultSecretReference + + // Collection of extension names after which this extension needs to be provisioned. + ProvisionAfterExtensions []*string + + // The name of the extension handler publisher. + Publisher *string + + // JSON formatted public settings for the extension. + Settings map[string]any + + // Indicates whether failures stemming from the extension will be suppressed (Operational failures such as not connecting + // to the VM will not be suppressed regardless of this value). The default is false. + SuppressFailures *bool + + // Specifies the type of the extension; an example is 'CustomScriptExtension'. + Type *string + + // Specifies the version of the script handler. + TypeHandlerVersion *string +} + +// BulkActionVMProperties - Describes the properties of a Virtual Machine for create. +type BulkActionVMProperties struct { + // Specifies additional capabilities enabled or disabled on the virtual machine. + AdditionalCapabilities *AdditionalCapabilities + + // Specifies the gallery applications that should be made available to the VM. + ApplicationProfile *ApplicationProfile + + // Specifies information about the capacity reservation that is used to allocate virtual machine. Minimum compute api-version: + // 2021-04-01. + CapacityReservation *CapacityReservationProfile + + // Specifies the boot diagnostic settings state. Minimum compute api-version: 2015-06-15. + DiagnosticsProfile *DiagnosticsProfile + + // Specifies the time alloted for all extensions to start. The time duration should be between 15 minutes and 120 minutes + // (inclusive) and should be specified in ISO 8601 format. The default value is 90 minutes (PT1H30M). Minimum compute api-version: + // 2020-06-01. + ExtensionsTimeBudget *string + + // Specifies the hardware profile for the virtual machine. + HardwareProfile *HardwareProfile + + // Specifies that the image or disk that is being used was licensed on-premises.

Possible values for Windows Server + // operating system are:

Windows_Client

Windows_Server

Possible values for Linux Server operating + // system are:

RHEL_BYOS (for RHEL)

SLES_BYOS (for SUSE)

For more information, see [Azure Hybrid + // Use Benefit for Windows Server](https://docs.microsoft.com/azure/virtual-machines/windows/hybrid-use-benefit-licensing) + //

[Azure Hybrid Use Benefit for Linux Server](https://docs.microsoft.com/azure/virtual-machines/linux/azure-hybrid-benefit-linux) + //

Minimum api-version: 2015-06-15 + LicenseType *string + + // Specifies the network interfaces of the virtual machine. + NetworkProfile *NetworkProfile + + // Specifies the operating system settings used while creating the virtual machine. Some of the settings cannot be changed + // once VM is provisioned. + OSProfile *OSProfile + + // Specifies Redeploy, Reboot and ScheduledEventsAdditionalPublishingTargets Scheduled Event related configurations for the + // virtual machine. + ScheduledEventsPolicy *ScheduledEventsPolicy + + // Specifies Scheduled Event related configurations. + ScheduledEventsProfile *ScheduledEventsProfile + + // Specifies the Security related profile settings for the virtual machine. + SecurityProfile *SecurityProfile + + // Specifies the storage settings for the virtual machine disks. + StorageProfile *StorageProfile + + // UserData for the VM, which must be base-64 encoded. Customer should not pass any secrets in here. Minimum compute api-version: + // 2021-03-01. + UserData *string +} + +// BulkVMConfiguration - Specifies the configuration for a virtual machine operation +type BulkVMConfiguration struct { + // Specifies the Microsoft.Compute API version to use when creating underlying Virtual Machines. + ComputeAPIVersion *string + + // The extended location of the Virtual Machine. + ExtendedLocation *ExtendedLocation + + // The identity of the virtual machine, if configured. + Identity *VirtualMachineIdentity + + // Identifier for created virtual machine. If not passed, it will be created from resource prefix. + Name *string + + // Placement constraints for virtual machine hardware placement. + Placement *Placement + + // The marketplace image plan used for the virtual machine. + Plan *Plan + + // Specifies the properties of the virtual machine to be created. + Properties *BulkActionVMProperties + + // Resource group name for the virtual machine. + ResourceGroupName *string + + // Resource tags to apply to the virtual machines created by this bulk action. + Tags map[string]*string + + // Virtual Machine Extensions Array to be applied to the Virtual Machines. + VMExtensions []*BulkActionVMExtension + + // The availability zones. + Zones []*string +} + +// CancelOccurrenceRequest - The request to cancel an occurrence. +type CancelOccurrenceRequest struct { + // REQUIRED; The resources the cancellation should act on. If no resource is passed in the list, Scheduled Action will cancel + // the occurrence for all resources. + ResourceIDs []*string +} + +// CancelOperationsRequest - This is the request to cancel running operations in scheduled actions using the operation ids +type CancelOperationsRequest struct { + // REQUIRED; CorrelationId item + Correlationid *string + + // REQUIRED; The list of operation ids to cancel operations on + OperationIDs []*string +} + +// CancelOperationsResponse - This is the response from a cancel operations request +type CancelOperationsResponse struct { + // REQUIRED; An array of resource operations that were successfully cancelled + Results []*ResourceOperation +} + +// CapacityReservationProfile - The parameters of a capacity reservation Profile. +type CapacityReservationProfile struct { + // Specifies the capacity reservation group resource id that should be used for allocating the virtual machine provided enough + // capacity has been reserved. Please refer to https://aka.ms/CapacityReservation for more details. + CapacityReservationGroup *SubResource +} + +// CreateFlexResourceOperationResponse - The response from a create flex request +type CreateFlexResourceOperationResponse struct { + // REQUIRED; The description of the operation response + Description *string + + // REQUIRED; The location of the create flex request eg westus + Location *string + + // REQUIRED; The type of resources used in the create flex request eg virtual machines + Type *string + + // The results from the create flex request if no errors exist + Results []*ResourceOperation +} + +// CreateResourceOperationResponse - The response from a create request +type CreateResourceOperationResponse struct { + // REQUIRED; The description of the operation response + Description *string + + // REQUIRED; The location of the start request eg westus + Location *string + + // REQUIRED; The type of resources used in the create request eg virtual machines + Type *string + + // The results from the start request if no errors exist + Results []*ResourceOperation +} + +// DataDisk - Describes a data disk. +type DataDisk struct { + // REQUIRED; Specifies how the virtual machine disk should be created. Possible values are Attach, FromImage, Empty, Copy, + // Restore. + CreateOption *DiskCreateOptionTypes + + // REQUIRED; Specifies the logical unit number of the data disk. This value is used to identify data disks within the VM and + // therefore must be unique for each data disk attached to a VM. + Lun *int32 + + // Specifies the caching requirements. Possible values are: None, ReadOnly, ReadWrite. The defaulting behavior is: None for + // Standard storage. ReadOnly for Premium storage. + Caching *CachingTypes + + // Specifies whether data disk should be deleted or detached upon VM deletion. Possible values are: Delete, Detach. The default + // value is set to Detach. + DeleteOption *DiskDeleteOptionTypes + + // Specifies the detach behavior to be used while detaching a disk or which is already in the process of detachment from the + // virtual machine. Supported values: ForceDetach. This feature is still in preview. To force-detach a data disk update toBeDetached + // to 'true' along with setting detachOption: 'ForceDetach'. + DetachOption *DiskDetachOptionTypes + + // Specifies the size of an empty data disk in gigabytes. This element can be used to overwrite the size of the disk in a + // virtual machine image. The property 'diskSizeGB' is the number of bytes x 1024^3 for the disk and the value cannot be larger + // than 1023. + DiskSizeGB *int32 + + // The source user image virtual hard disk. The virtual hard disk will be copied before being attached to the virtual machine. + // If SourceImage is provided, the destination virtual hard drive must not exist. + Image *VirtualHardDisk + + // The managed disk parameters. + ManagedDisk *ManagedDiskParameters + + // The disk name. + Name *string + + // The source resource identifier. It can be a snapshot, or disk restore point from which to create a disk. + SourceResource *APIEntityReference + + // Specifies whether the data disk is in process of detachment from the VirtualMachine/VirtualMachineScaleset. + ToBeDetached *bool + + // The virtual hard disk. + Vhd *VirtualHardDisk + + // Specifies whether writeAccelerator should be enabled or disabled on the disk. + WriteAcceleratorEnabled *bool +} + +// DeallocateResourceOperationResponse - The response from a deallocate request +type DeallocateResourceOperationResponse struct { + // REQUIRED; The description of the operation response + Description *string + + // REQUIRED; The location of the deallocate request eg westus + Location *string + + // REQUIRED; The type of resources used in the deallocate request eg virtual machines + Type *string + + // The results from the deallocate request if no errors exist + Results []*ResourceOperation +} + +// DelayRequest - Request to ask for a delay in an occurrence, delay should be set to client local time eg (ACST) 2025-05-30T22:03:00+09:30, +// (PST) 2025-05-30T06:35:00-07:00 +type DelayRequest struct { + // REQUIRED; The exact time to delay the operations to + Delay *time.Time + + // REQUIRED; The resources that should be delayed. If empty, the delay will apply to the all resources in the occurrence. + ResourceIDs []*string +} + +// DeleteResourceOperationResponse - The response from a delete request +type DeleteResourceOperationResponse struct { + // REQUIRED; The description of the operation response + Description *string + + // REQUIRED; The location of the start request eg westus + Location *string + + // REQUIRED; The type of resources used in the delete request eg virtual machines + Type *string + + // The results from the start request if no errors exist + Results []*ResourceOperation +} + +// DiagnosticsProfile - Specifies the boot diagnostic settings state. Minimum compute api-version: 2015-06-15. +type DiagnosticsProfile struct { + // Boot Diagnostics is a debugging feature which allows you to view Console Output and Screenshot to diagnose VM status. **NOTE**: + // If storageUri is being specified then ensure that the storage account is in the same region and subscription as the VM. + // You can easily view the output of your console log. Azure also enables you to see a screenshot of the VM from the hypervisor. + BootDiagnostics *BootDiagnostics +} + +// DiffDiskSettings - Describes the parameters of ephemeral disk settings that can be specified for operating system disk. +// Note: The ephemeral disk settings can only be specified for managed disk. +type DiffDiskSettings struct { + // Specifies the ephemeral disk settings for operating system disk. + Option *DiffDiskOptions + + // Specifies the ephemeral disk placement for operating system disk. Possible values are: CacheDisk, ResourceDisk, NvmeDisk. + // The defaulting behavior is: CacheDisk if one is configured for the VM size otherwise ResourceDisk or NvmeDisk is used. + // Minimum api-version for NvmeDisk: 2024-03-01. + Placement *DiffDiskPlacement +} + +// DiskEncryptionSetParameters - Describes the parameter of customer managed disk encryption set resource id that can be specified +// for disk. **Note:** The disk encryption set resource id can only be specified for managed disk. Please refer https://aka.ms/mdssewithcmkoverview +// for more details. +type DiskEncryptionSetParameters struct { + // The ID of the sub-resource. + ID *string +} + +// DiskEncryptionSettings - Describes a Encryption Settings for a Disk +type DiskEncryptionSettings struct { + // Specifies the location of the disk encryption key, which is a Key Vault Secret. + DiskEncryptionKey *KeyVaultSecretReference + + // Specifies whether disk encryption should be enabled on the virtual machine. + Enabled *bool + + // Specifies the location of the key encryption key in Key Vault. + KeyEncryptionKey *KeyVaultKeyReference +} + +// EncryptionIdentity - Specifies the Managed Identity used by ADE to get access token for keyvault operations. +type EncryptionIdentity struct { + // Specifies ARM Resource ID of one of the user identities associated with the VM. + UserAssignedIdentityResourceID *string +} + +// Error - The error object. +type Error struct { + // REQUIRED; One of a server-defined set of error codes. + Code *string + + // REQUIRED; A human-readable representation of the error. + Message *string + + // An array of details about specific errors that led to this reported error. + Details []*Error + + // An object containing more specific information than the current object about the error. + Innererror *InnerError + + // The target of the error. + Target *string +} + +// EventGridAndResourceGraph - Specifies eventGridAndResourceGraph related Scheduled Event related configurations. +type EventGridAndResourceGraph struct { + // Specifies if event grid and resource graph is enabled for Scheduled event related configurations. + Enable *bool + + // Specifies the api-version to determine which Scheduled Events configuration schema version will be delivered. + ScheduledEventsAPIVersion *string +} + +// ExecuteCreateFlexRequest - The ExecuteCreateFlexRequest request for executeCreateFlex operations +type ExecuteCreateFlexRequest struct { + // REQUIRED; The execution parameters for the request + ExecutionParameters *ExecutionParameters + + // REQUIRED; Resource creation payload with flex properties + ResourceConfigParameters *ResourceProvisionFlexPayload + + // Correlationid item + Correlationid *string +} + +// ExecuteCreateRequest - The ExecuteCreateRequest request for create operations +type ExecuteCreateRequest struct { + // REQUIRED; The execution parameters for the request + ExecutionParameters *ExecutionParameters + + // REQUIRED; resource creation payload + ResourceConfigParameters *ResourceProvisionPayload + + // CorrelationId item + Correlationid *string +} + +// ExecuteDeallocateRequest - The ExecuteDeallocateRequest request for executeDeallocate operations +type ExecuteDeallocateRequest struct { + // REQUIRED; CorrelationId item + Correlationid *string + + // REQUIRED; The execution parameters for the request + ExecutionParameters *ExecutionParameters + + // REQUIRED; The resources for the request + Resources *Resources +} + +// ExecuteDeleteRequest - The ExecuteDeleteRequest for delete VM operation +type ExecuteDeleteRequest struct { + // REQUIRED; The execution parameters for the request + ExecutionParameters *ExecutionParameters + + // REQUIRED; The resources for the request + Resources *Resources + + // CorrelationId item + Correlationid *string + + // Forced delete resource item + ForceDeletion *bool +} + +// ExecuteHibernateRequest - The ExecuteHibernateRequest request for executeHibernate operations +type ExecuteHibernateRequest struct { + // REQUIRED; CorrelationId item + Correlationid *string + + // REQUIRED; The execution parameters for the request + ExecutionParameters *ExecutionParameters + + // REQUIRED; The resources for the request + Resources *Resources +} + +// ExecuteStartRequest - The ExecuteStartRequest request for executeStart operations +type ExecuteStartRequest struct { + // REQUIRED; CorrelationId item + Correlationid *string + + // REQUIRED; The execution parameters for the request + ExecutionParameters *ExecutionParameters + + // REQUIRED; The resources for the request + Resources *Resources +} + +// ExecutionParameters - Extra details needed to run the user's request +type ExecutionParameters struct { + // Details that could optimize the user's request + OptimizationPreference *OptimizationPreference + + // Retry policy the user can pass + RetryPolicy *RetryPolicy +} + +// ExtendedLocation - The complex type of the extended location. +type ExtendedLocation struct { + // REQUIRED; The name of the extended location. + Name *string + + // REQUIRED; The type of the extended location. + Type *ExtendedLocationType +} + +// FallbackOperationInfo - Describes the fallback operation that was performed +type FallbackOperationInfo struct { + // REQUIRED; The last operation type that was performed as a fallback + LastOpType *ResourceOperationType + + // REQUIRED; The status of the fallback operation + Status *string + + // The error code if the fallback operation failed + Error *ResourceOperationError +} + +// FlexProperties - The flex properties for flexible VM creation +type FlexProperties struct { + // REQUIRED; The operating system type for the VMs + OSType *OsType + + // REQUIRED; The priority profile for VM allocation + PriorityProfile *PriorityProfile + + // REQUIRED; The list of VM size profiles to use for flex creation + VMSizeProfiles []*VMSizeProfile + + // The zone allocation policy for distributing VMs across availability zones + ZoneAllocationPolicy *ZoneAllocationPolicy +} + +// GetOperationErrorsRequest - This is the request to get errors per vm operations +type GetOperationErrorsRequest struct { + // REQUIRED; The list of operation ids to query errors of + OperationIDs []*string +} + +// GetOperationErrorsResponse - This is the response from a get operations errors request +type GetOperationErrorsResponse struct { + // REQUIRED; An array of operationids and their corresponding errors if any + Results []*OperationErrorsResult +} + +// GetOperationStatusRequest - This is the request to get operation status using operationids +type GetOperationStatusRequest struct { + // REQUIRED; CorrelationId item + Correlationid *string + + // REQUIRED; The list of operation ids to get the status of + OperationIDs []*string +} + +// GetOperationStatusResponse - This is the response from a get operations status request +type GetOperationStatusResponse struct { + // REQUIRED; An array of resource operations based on their operation ids + Results []*ResourceOperation +} + +// HardwareProfile - Specifies the hardware profile for the virtual machine. +type HardwareProfile struct { + // Specifies the size of the virtual machine. The enum data type is currently deprecated and will be removed by December 23rd + // 2023. The recommended way to get the list of available sizes is using these APIs: [List all available virtual machine sizes + // in an availability set](https://docs.microsoft.com/rest/api/compute/availabilitysets/listavailablesizes), [List all available + // virtual machine sizes in a region]( https://docs.microsoft.com/rest/api/compute/resourceskus/list), [List all available + // virtual machine sizes for resizing](https://docs.microsoft.com/rest/api/compute/virtualmachines/listavailablesizes). For + // more information about virtual machine sizes, see [Sizes for virtual machines](https://docs.microsoft.com/azure/virtual-machines/sizes). + // The available VM sizes depend on region and availability set. + VMSize *string + + // Specifies the properties for customizing the size of the virtual machine. Minimum api-version: 2021-07-01. This feature + // is still in preview mode and is not supported for VirtualMachineScaleSet. Please follow the instructions in [VM Customization](https://aka.ms/vmcustomization) + // for more details. + VMSizeProperties *VMSizeProperties +} + +// HibernateResourceOperationResponse - The response from a Hibernate request +type HibernateResourceOperationResponse struct { + // REQUIRED; The description of the operation response + Description *string + + // REQUIRED; The location of the Hibernate request eg westus + Location *string + + // REQUIRED; The type of resources used in the Hibernate request eg virtual machines + Type *string + + // The results from the Hibernate request if no errors exist + Results []*ResourceOperation +} + +// HostEndpointSettings - Specifies particular host endpoint settings. +type HostEndpointSettings struct { + // Specifies the InVMAccessControlProfileVersion resource id in the format of /subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/inVMAccessControlProfiles/{profile}/versions/{version} + InVMAccessControlProfileReferenceID *string + + // Specifies the execution mode. In Audit mode, the system acts as if it is enforcing the access control policy, including + // emitting access denial entries in the logs but it does not actually deny any requests to host endpoints. In Enforce mode, + // the system will enforce the access control and it is the recommended mode of operation. + Mode *Modes +} + +// ImageReference - Specifies information about the image to use. You can specify information about platform images, marketplace +// images, or virtual machine images. This element is required when you want to use a platform image, marketplace image, or +// virtual machine image, but is not used in other creation operations. NOTE: Image reference publisher and offer can only +// be set when you create the scale set. +type ImageReference struct { + // Specified the community gallery image unique id for vm deployment. This can be fetched from community gallery image GET + // call. + CommunityGalleryImageID *string + + // The ID of the sub-resource. + ID *string + + // Specifies the offer of the platform image or marketplace image used to create the virtual machine. + Offer *string + + // The image publisher. + Publisher *string + + // The image SKU. + SKU *string + + // Specified the shared gallery image unique id for vm deployment. This can be fetched from shared gallery image GET call. + SharedGalleryImageID *string + + // Specifies the version of the platform image or marketplace image used to create the virtual machine. The allowed formats + // are Major.Minor.Build or 'latest'. Major, Minor, and Build are decimal numbers. Specify 'latest' to use the latest version + // of an image available at deploy time. Even if you use 'latest', the VM image will not automatically update after deploy + // time even if a new version becomes available. Please do not use field 'version' for gallery image deployment, gallery image + // should always use 'id' field for deployment, to use 'latest' version of gallery image, just set '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/images/{imageName}' + // in the 'id' field without version input. + Version *string +} + +// InnerError - An object containing more specific information about the error. As per Azure REST API guidelines - https://aka.ms/AzureRestApiGuidelines#handling-errors. +type InnerError struct { + // One of a server-defined set of error codes. + Code *string + + // Inner error. + Innererror *InnerError +} + +// KeyVaultKeyReference - Describes a reference to Key Vault Key +type KeyVaultKeyReference struct { + // REQUIRED; The URL referencing a key encryption key in Key Vault. + KeyURL *string + + // REQUIRED; The relative URL of the Key Vault containing the key. + SourceVault *SubResource +} + +// KeyVaultSecretReference - Describes a reference to Key Vault Secret +type KeyVaultSecretReference struct { + // REQUIRED; The URL referencing a secret in a Key Vault. + SecretURL *string + + // REQUIRED; The relative URL of the Key Vault containing the secret. + SourceVault *SubResource +} + +// LinuxConfiguration - Specifies the Linux operating system settings on the virtual machine. For a list of supported Linux +// distributions, see [Linux on Azure-Endorsed Distributions](https://docs.microsoft.com/azure/virtual-machines/linux/endorsed-distros). +type LinuxConfiguration struct { + // Specifies whether password authentication should be disabled. + DisablePasswordAuthentication *bool + + // Indicates whether VMAgent Platform Updates is enabled for the Linux virtual machine. Default value is false. + EnableVMAgentPlatformUpdates *bool + + // [Preview Feature] Specifies settings related to VM Guest Patching on Linux. + PatchSettings *LinuxPatchSettings + + // Indicates whether virtual machine agent should be provisioned on the virtual machine. When this property is not specified + // in the request body, default behavior is to set it to true. This will ensure that VM Agent is installed on the VM so that + // extensions can be added to the VM later. + ProvisionVMAgent *bool + + // Specifies the ssh key configuration for a Linux OS. + SSH *SSHConfiguration +} + +// LinuxPatchSettings - Specifies settings related to VM Guest Patching on Linux. +type LinuxPatchSettings struct { + // Specifies the mode of VM Guest Patch Assessment for the IaaS virtual machine.

Possible values are:

**ImageDefault** - You control the timing of patch assessments on a virtual machine.

**AutomaticByPlatform** + // - The platform will trigger periodic patch assessments. The property provisionVMAgent must be true. + AssessmentMode *LinuxPatchAssessmentMode + + // Specifies additional settings for patch mode AutomaticByPlatform in VM Guest Patching on Linux. + AutomaticByPlatformSettings *LinuxVMGuestPatchAutomaticByPlatformSettings + + // Specifies the mode of VM Guest Patching to IaaS virtual machine or virtual machines associated to virtual machine scale + // set with OrchestrationMode as Flexible.

Possible values are:

**ImageDefault** - The virtual machine's + // default patching configuration is used.

**AutomaticByPlatform** - The virtual machine will be automatically + // updated by the platform. The property provisionVMAgent must be true + PatchMode *LinuxVMGuestPatchMode +} + +// LinuxVMGuestPatchAutomaticByPlatformSettings - Specifies additional settings to be applied when patch mode AutomaticByPlatform +// is selected in Linux patch settings. +type LinuxVMGuestPatchAutomaticByPlatformSettings struct { + // Enables customer to schedule patching without accidental upgrades + BypassPlatformSafetyChecksOnUserSchedule *bool + + // Specifies the reboot setting for all AutomaticByPlatform patch installation operations. + RebootSetting *LinuxVMGuestPatchAutomaticByPlatformRebootSetting +} + +// ManagedDiskParameters - The parameters of a managed disk. +type ManagedDiskParameters struct { + // Specifies the customer managed disk encryption set resource id for the managed disk. + DiskEncryptionSet *DiskEncryptionSetParameters + + // The ID of the sub-resource. + ID *string + + // Specifies the security profile for the managed disk. + SecurityProfile *VMDiskSecurityProfile + + // Specifies the storage account type for the managed disk. NOTE: UltraSSD_LRS can only be used with data disks, it cannot + // be used with OS Disk. + StorageAccountType *StorageAccountTypes +} + +// NetworkInterfaceReference - Describes a network interface reference. +type NetworkInterfaceReference struct { + // The ID of the sub-resource. + ID *string + + // Describes a network interface reference properties. + Properties *NetworkInterfaceReferenceProperties +} + +// NetworkInterfaceReferenceProperties - Describes a network interface reference properties. +type NetworkInterfaceReferenceProperties struct { + // Specify what happens to the network interface when the VM is deleted + DeleteOption *DeleteOptions + + // Specifies the primary network interface in case the virtual machine has more than 1 network interface. + Primary *bool +} + +// NetworkProfile - Specifies the network interfaces or the networking configuration of the virtual machine. +type NetworkProfile struct { + // specifies the Microsoft.Network API version used when creating networking resources in the Network Interface Configurations + NetworkAPIVersion *NetworkAPIVersion + + // Specifies the networking configurations that will be used to create the virtual machine networking resources. + NetworkInterfaceConfigurations []*VirtualMachineNetworkInterfaceConfiguration + + // Specifies the list of resource Ids for the network interfaces associated with the virtual machine. + NetworkInterfaces []*NetworkInterfaceReference +} + +// NotificationProperties - The information about notifications to be send to about upcoming operations. +type NotificationProperties struct { + // REQUIRED; Where the notification should be sent. For email, it should follow email format. + Destination *string + + // REQUIRED; The language the notification should be sent on. + Language *Language + + // REQUIRED; Type of notification to be sent. + Type *NotificationType + + // Tells if the notification is enabled or not. + Disabled *bool +} + +// OSDisk - Specifies information about the operating system disk used by the virtual machine. For more information about +// disks, see [About disks and VHDs for Azure virtual machines](https://docs.microsoft.com/azure/virtual-machines/managed-disks-overview). +type OSDisk struct { + // REQUIRED; Specifies how the virtual machine disk should be created. Possible values are Attach, FromImage. If you are using + // a platform image, you should also use the imageReference element described above. If you are using a marketplace image, + // you should also use the plan element previously described. + CreateOption *DiskCreateOptionTypes + + // Specifies the caching requirements. Possible values are: None, ReadOnly, ReadWrite. The defaulting behavior is: None for + // Standard storage. ReadOnly for Premium storage. + Caching *CachingTypes + + // Specifies whether OS Disk should be deleted or detached upon VM deletion. Possible values are: Delete, Detach. The default + // value is set to Detach. For an ephemeral OS Disk, the default value is set to Delete. The user cannot change the delete + // option for an ephemeral OS Disk. + DeleteOption *DiskDeleteOptionTypes + + // Specifies the ephemeral Disk Settings for the operating system disk used by the virtual machine. + DiffDiskSettings *DiffDiskSettings + + // Specifies the size of an empty data disk in gigabytes. This element can be used to overwrite the size of the disk in a + // virtual machine image. The property 'diskSizeGB' is the number of bytes x 1024^3 for the disk and the value cannot be larger + // than 1023. + DiskSizeGB *int32 + + // Specifies the encryption settings for the OS Disk. Minimum compute api-version: 2015-06-15. + EncryptionSettings *DiskEncryptionSettings + + // The source user image virtual hard disk. The virtual hard disk will be copied before being attached to the virtual machine. + // If SourceImage is provided, the destination virtual hard drive must not exist. + Image *VirtualHardDisk + + // The managed disk parameters. + ManagedDisk *ManagedDiskParameters + + // The disk name. + Name *string + + // This property allows you to specify the type of the OS that is included in the disk if creating a VM from user-image or + // a specialized VHD. Possible values are: Windows, Linux. + OSType *OperatingSystemTypes + + // The virtual hard disk. + Vhd *VirtualHardDisk + + // Specifies whether writeAccelerator should be enabled or disabled on the disk. + WriteAcceleratorEnabled *bool +} + +// OSImageNotificationProfile - Profile for the OS Image Scheduled event. +type OSImageNotificationProfile struct { + // Specifies whether the OS Image Scheduled event is enabled or disabled. + Enable *bool + + // Length of time a Virtual Machine being reimaged or having its OS upgraded will have to potentially approve the OS Image + // Scheduled Event before the event is auto approved (timed out). The configuration is specified in ISO 8601 format, and the + // value must be 15 minutes (PT15M) + NotBeforeTimeout *string +} + +// OSProfile - Specifies the operating system settings for the virtual machine. Some of the settings cannot be changed once +// VM is provisioned. +type OSProfile struct { + // Specifies the password of the administrator account.

**Minimum-length (Windows):** 8 characters

**Minimum-length + // (Linux):** 6 characters

**Max-length (Windows):** 123 characters

**Max-length (Linux):** 72 characters + //

**Complexity requirements:** 3 out of 4 conditions below need to be fulfilled
Has lower characters
Has + // upper characters
Has a digit
Has a special character (Regex match [\W_])

**Disallowed values:** "abc@123", + // "P@$$w0rd", "P@ssw0rd", "P@ssword123", "Pa$$word", "pass@word1", "Password!", "Password1", "Password22", "iloveyou!"

+ // For resetting the password, see [How to reset the Remote Desktop service or its login password in a Windows VM](https://docs.microsoft.com/troubleshoot/azure/virtual-machines/reset-rdp) + //

For resetting root password, see [Manage users, SSH, and check or repair disks on Azure Linux VMs using the VMAccess + // Extension](https://docs.microsoft.com/troubleshoot/azure/virtual-machines/troubleshoot-ssh-connection) + AdminPassword *string + + // Specifies the name of the administrator account.

This property cannot be updated after the VM is created.

+ // **Windows-only restriction:** Cannot end in "."

**Disallowed values:** "administrator", "admin", "user", "user1", + // "test", "user2", "test1", "user3", "admin1", "1", "123", "a", "actuser", "adm", "admin2", "aspnet", "backup", "console", + // "david", "guest", "john", "owner", "root", "server", "sql", "support", "support_388945a0", "sys", "test2", "test3", "user4", + // "user5".

**Minimum-length (Linux):** 1 character

**Max-length (Linux):** 64 characters

**Max-length + // (Windows):** 20 characters. + AdminUsername *string + + // Specifies whether extension operations should be allowed on the virtual machine. This may only be set to False when no + // extensions are present on the virtual machine. + AllowExtensionOperations *bool + + // Specifies the host OS name of the virtual machine. This name cannot be updated after the VM is created. **Max-length (Windows):** + // 15 characters. **Max-length (Linux):** 64 characters. For naming conventions and restrictions see [Azure infrastructure + // services implementation guidelines](https://docs.microsoft.com/azure/azure-resource-manager/management/resource-name-rules). + ComputerName *string + + // Specifies a base-64 encoded string of custom data. The base-64 encoded string is decoded to a binary array that is saved + // as a file on the Virtual Machine. The maximum length of the binary array is 65535 bytes. **Note: Do not pass any secrets + // or passwords in customData property.** This property cannot be updated after the VM is created. The property 'customData' + // is passed to the VM to be saved as a file, for more information see [Custom Data on Azure VMs](https://azure.microsoft.com/blog/custom-data-and-cloud-init-on-windows-azure/). + // For using cloud-init for your Linux VM, see [Using cloud-init to customize a Linux VM during creation](https://docs.microsoft.com/azure/virtual-machines/linux/using-cloud-init). + CustomData *string + + // Specifies the Linux operating system settings on the virtual machine. For a list of supported Linux distributions, see + // [Linux on Azure-Endorsed Distributions](https://docs.microsoft.com/azure/virtual-machines/linux/endorsed-distros). + LinuxConfiguration *LinuxConfiguration + + // Optional property which must either be set to True or omitted. + RequireGuestProvisionSignal *bool + + // Specifies set of certificates that should be installed onto the virtual machine. To install certificates on a virtual machine + // it is recommended to use the [Azure Key Vault virtual machine extension for Linux](https://docs.microsoft.com/azure/virtual-machines/extensions/key-vault-linux) + // or the [Azure Key Vault virtual machine extension for Windows](https://docs.microsoft.com/azure/virtual-machines/extensions/key-vault-windows). + Secrets []*VaultSecretGroup + + // Specifies Windows operating system settings on the virtual machine. + WindowsConfiguration *WindowsConfiguration +} + +// Occurrence - Concrete proxy resource types can be created by aliasing this type using a specific property type. +type Occurrence struct { + // The resource-specific properties for this resource. + Properties *OccurrenceProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// OccurrenceExtensionProperties - The properties of the occurrence extension +type OccurrenceExtensionProperties struct { + // REQUIRED; The ARM Id of the resource. + // "subscriptions/{subId}/resourceGroups/{rgName}/providers/Microsoft.Compute/virtualMachines/{vmName}" + ResourceID *string + + // REQUIRED; The arm identifier of the scheduled action the occurrence belongs to + ScheduledActionID *string + + // READ-ONLY; The time the occurrence is scheduled for the resource. Specified in UTC. + ScheduledTime *time.Time + + // The desired notification settings for the specified resource. + NotificationSettings []*NotificationProperties + + // READ-ONLY; Error details for the resource. Only populated if resource is in failed state. + ErrorDetails *Error + + // READ-ONLY; The current state of the resource + ProvisioningState *ResourceProvisioningState +} + +// OccurrenceExtensionResource - The scheduled action extension +type OccurrenceExtensionResource struct { + // The resource-specific properties for this resource. + Properties *OccurrenceExtensionProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// OccurrenceExtensionResourceListResult - The response of a OccurrenceExtensionResource list operation. +type OccurrenceExtensionResourceListResult struct { + // REQUIRED; The OccurrenceExtensionResource items on this page + Value []*OccurrenceExtensionResource + + // The link to the next page of items + NextLink *string +} + +// OccurrenceListResult - The response of a Occurrence list operation. +type OccurrenceListResult struct { + // REQUIRED; The Occurrence items on this page + Value []*Occurrence + + // The link to the next page of items + NextLink *string +} + +// OccurrenceProperties - Properties for an occurrence +type OccurrenceProperties struct { + // READ-ONLY; The result for occurrences that achieved a terminal state + ResultSummary *OccurrenceResultSummary + + // READ-ONLY; The time the occurrence is scheduled for. This value can be changed by calling the delay API + ScheduledTime *time.Time + + // READ-ONLY; The aggregated provisioning state of the occurrence + ProvisioningState *OccurrenceState +} + +// OccurrenceResource - Represents an scheduled action resource metadata. +type OccurrenceResource struct { + // REQUIRED; The ARM Id of the resource. + // "subscriptions/{subId}/resourceGroups/{rgName}/providers/Microsoft.Compute/virtualMachines/{vmName}" + ResourceID *string + + // The desired notification settings for the specified resource. + NotificationSettings []*NotificationProperties + + // READ-ONLY; The compute RP resource id of the resource in the scheduled actions scope. + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; The time the occurrence is scheduled for the resource. + ScheduledTime *time.Time + + // READ-ONLY; Error details for the resource. Only populated if resource is in failed state. + ErrorDetails *Error + + // READ-ONLY; The current state of the resource + ProvisioningState *ResourceProvisioningState + + // READ-ONLY; The type of resource + Type *string +} + +// OccurrenceResourceListResponse - Paged collection of OccurrenceResource items +type OccurrenceResourceListResponse struct { + // REQUIRED; The OccurrenceResource items on this page + Value []*OccurrenceResource + + // The link to the next page of items + NextLink *string +} + +// OccurrenceResultSummary - The summarized provisioning result of an occurrence +type OccurrenceResultSummary struct { + // REQUIRED; The summarized status of the resources. + Statuses []*ResourceResultSummary + + // REQUIRED; The total number of resources that the occurrence was supposed to act on. + Total *int32 +} + +// Operation - REST API Operation +// +// Details of a REST API operation, returned from the Resource Provider Operations API +type Operation struct { + // Localized display information for this particular operation. + Display *OperationDisplay + + // READ-ONLY; Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + ActionType *ActionType + + // READ-ONLY; Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure + // Resource Manager/control-plane operations. + IsDataAction *bool + + // READ-ONLY; The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + // "Microsoft.Compute/virtualMachines/capture/action" + Name *string + + // READ-ONLY; The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default + // value is "user,system" + Origin *Origin +} + +// OperationDisplay - Localized display information for an operation. +type OperationDisplay struct { + // READ-ONLY; The short, localized friendly description of the operation; suitable for tool tips and detailed views. + Description *string + + // READ-ONLY; The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual + // Machine", "Restart Virtual Machine". + Operation *string + + // READ-ONLY; The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft + // Compute". + Provider *string + + // READ-ONLY; The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job + // Schedule Collections". + Resource *string +} + +// OperationErrorDetails - This defines a list of operation errors associated with a unique operationId +type OperationErrorDetails struct { + // REQUIRED; The error code of the operation + ErrorCode *string + + // REQUIRED; The error details of the operation + ErrorDetails *string + + // The compute operationid of the Start/Deallocate/Hibernate request + AzureOperationName *string + + // The compute operationid of the Start/Deallocate/Hibernate request + CrpOperationID *string + + // The timestamp of the error occurence + TimeStamp *time.Time + + // The timestamp of the error occurence + Timestamp *time.Time +} + +// OperationErrorsResult - This is the first level of operation errors from the request when clients get errors per vm operation +type OperationErrorsResult struct { + // The activation time of a vm operation + ActivationTime *time.Time + + // The completion time of the operation if the operation was completed + CompletedAt *time.Time + + // The creation time of the error result + CreationTime *time.Time + + // A list of errors associated with the operationid + OperationErrors []*OperationErrorDetails + + // The operationId identifying a vm operation + OperationID *string + + // Request level error code + RequestErrorCode *string + + // Request level error details + RequestErrorDetails *string +} + +// OperationListResult - A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to +// get the next set of results. +type OperationListResult struct { + // REQUIRED; The Operation items on this page + Value []*Operation + + // The link to the next page of items + NextLink *string +} + +// PatchSettings - Specifies settings related to VM Guest Patching on Windows. +type PatchSettings struct { + // Specifies the mode of VM Guest patch assessment for the IaaS virtual machine.

Possible values are:

**ImageDefault** - You control the timing of patch assessments on a virtual machine.

**AutomaticByPlatform** + // - The platform will trigger periodic patch assessments. The property provisionVMAgent must be true. + AssessmentMode *WindowsPatchAssessmentMode + + // Specifies additional settings for patch mode AutomaticByPlatform in VM Guest Patching on Windows. + AutomaticByPlatformSettings *WindowsVMGuestPatchAutomaticByPlatformSettings + + // Enables customers to patch their Azure VMs without requiring a reboot. For enableHotpatching, the 'provisionVMAgent' must + // be set to true and 'patchMode' must be set to 'AutomaticByPlatform'. + EnableHotpatching *bool + + // Specifies the mode of VM Guest Patching to IaaS virtual machine or virtual machines associated to virtual machine scale + // set with OrchestrationMode as Flexible.

Possible values are:

**Manual** - You control the application + // of patches to a virtual machine. You do this by applying patches manually inside the VM. In this mode, automatic updates + // are disabled; the property WindowsConfiguration.enableAutomaticUpdates must be false

**AutomaticByOS** - The + // virtual machine will automatically be updated by the OS. The property WindowsConfiguration.enableAutomaticUpdates must + // be true.

**AutomaticByPlatform** - the virtual machine will automatically updated by the platform. The properties + // provisionVMAgent and WindowsConfiguration.enableAutomaticUpdates must be true + PatchMode *WindowsVMGuestPatchMode +} + +// Placement - Describes the user-defined constraints for resource hardware placement. +type Placement struct { + // This property supplements the 'zonePlacementPolicy' property. If 'zonePlacementPolicy' is set to 'Any'/'Auto', availability + // zone selected by the system must not be present in the list of availability zones passed with 'excludeZones'. If 'excludeZones' + // is not provided, all availability zones in region will be considered for selection. + ExcludeZones []*string + + // This property supplements the 'zonePlacementPolicy' property. If 'zonePlacementPolicy' is set to 'Any'/'Auto', availability + // zone selected by the system must be present in the list of availability zones passed with 'includeZones'. If 'includeZones' + // is not provided, all availability zones in region will be considered for selection. + IncludeZones []*string + + // Specifies the policy for resource's placement in availability zone. Possible values are: **Any** (used for Virtual Machines), + // **Auto** (used for Virtual Machine Scale Sets) - An availability zone will be automatically picked by system as part of + // resource creation. + ZonePlacementPolicy *ZonePlacementPolicyType +} + +// Plan for the resource. +type Plan struct { + // REQUIRED; A user defined name of the 3rd Party Artifact that is being procured. + Name *string + + // REQUIRED; The 3rd Party artifact that is being procured. E.g. NewRelic. Product maps to the OfferID specified for the artifact + // at the time of Data Market onboarding. + Product *string + + // REQUIRED; The publisher of the 3rd Party Artifact that is being bought. E.g. NewRelic + Publisher *string + + // A publisher provided promotion code as provisioned in Data Market for the said product/artifact. + PromotionCode *string + + // The version of the desired product/artifact. + Version *string +} + +// PriorityProfile - The priority profile for flex VM creation +type PriorityProfile struct { + // The allocation strategy for VM size selection + AllocationStrategy *AllocationStrategy + + // The priority type for VM allocation + Type *PriorityType +} + +// ProxyAgentSettings - Specifies ProxyAgent settings for the virtual machine or virtual machine scale set. Minimum api-version: +// 2023-09-01. +type ProxyAgentSettings struct { + // Specify whether to implicitly install the ProxyAgent Extension. This option is currently applicable only for Linux Os. + AddProxyAgentExtension *bool + + // Specifies whether ProxyAgent feature should be enabled on the virtual machine or virtual machine scale set. + Enabled *bool + + // Specifies the IMDS endpoint settings while creating the virtual machine or virtual machine scale set. Minimum api-version: + // 2024-03-01. + Imds *HostEndpointSettings + + // Increase the value of this property allows users to reset the key used for securing communication channel between guest + // and host. + KeyIncarnationID *int32 + + // Specifies the mode that ProxyAgent will execute on. Warning: this property has been deprecated, please specify 'mode' under + // particular hostendpoint setting. + Mode *Mode + + // Specifies the Wire Server endpoint settings while creating the virtual machine or virtual machine scale set. Minimum api-version: + // 2024-03-01. + WireServer *HostEndpointSettings +} + +// PublicIPAddressSKU - Describes the public IP Sku. It can only be set with OrchestrationMode as Flexible. +type PublicIPAddressSKU struct { + // Specify public IP sku name + Name *PublicIPAddressSKUName + + // Specify public IP sku tier + Tier *PublicIPAddressSKUTier +} + +// RecurringActionsResourceOperationResult - The response from scheduled action resource requests, which contains the status +// of each resource +type RecurringActionsResourceOperationResult struct { + // REQUIRED; The resource status of for each resource + ResourcesStatuses []*ResourceStatus + + // REQUIRED; The total number of resources operated on + TotalResources *int32 +} + +// ResourceAttachRequest - Request model to attach a list of scheduled action resources. +type ResourceAttachRequest struct { + // REQUIRED; List of resources to be attached/patched + Resources []*ScheduledActionResource +} + +// ResourceDetachRequest - Request model to detach a list of scheduled action resources. +type ResourceDetachRequest struct { + // REQUIRED; List of resources to be detached + Resources []*string +} + +// ResourceListResponse - Paged collection of ScheduledActionResource items +type ResourceListResponse struct { + // REQUIRED; The ScheduledActionResource items on this page + Value []*ScheduledActionResource + + // The link to the next page of items + NextLink *string +} + +// ResourceOperation - High level response from an operation on a resource +type ResourceOperation struct { + // Resource level error code if it exists + ErrorCode *string + + // Resource level error details if they exist + ErrorDetails *string + + // Details of the operation performed on a resource + Operation *ResourceOperationDetails + + // Unique identifier for the resource involved in the operation, eg ArmId + ResourceID *string +} + +// ResourceOperationDetails - The details of a response from an operation on a resource +type ResourceOperationDetails struct { + // REQUIRED; Operation identifier for the unique operation + OperationID *string + + // Time the operation was complete if errors are null + CompletedAt *time.Time + + // Deadline for the operation + Deadline *time.Time + + // Type of deadline of the operation + DeadlineType *DeadlineType + + // Fallback operation details if a fallback was performed + FallbackOperationInfo *FallbackOperationInfo + + // Type of operation performed on the resources + OpType *ResourceOperationType + + // Unique identifier for the resource involved in the operation, eg ArmId + ResourceID *string + + // Operation level errors if they exist + ResourceOperationError *ResourceOperationError + + // Retry policy the user can pass + RetryPolicy *RetryPolicy + + // Current state of the operation + State *OperationState + + // Subscription id attached to the request + SubscriptionID *string + + // Timezone for the operation + TimeZone *string + + // Timezone for the operation + Timezone *string +} + +// ResourceOperationError - These describe errors that occur at the resource level +type ResourceOperationError struct { + // REQUIRED; Code for the error eg 404, 500 + ErrorCode *string + + // REQUIRED; Detailed message about the error + ErrorDetails *string +} + +// ResourcePatchRequest - Request model perform a resource operation in a list of resources +type ResourcePatchRequest struct { + // REQUIRED; The list of resources we watch to patch + Resources []*ScheduledActionResource +} + +// ResourceProvisionFlexPayload - Resource creation data model for flex VM provisioning +type ResourceProvisionFlexPayload struct { + // REQUIRED; The flex properties for flexible VM creation + FlexProperties *FlexProperties + + // REQUIRED; Number of VMs to be created + ResourceCount *int32 + + // If resourceOverrides doesn't contain name, service will create name based on prefix and resourceCount + ResourcePrefix *string + + // JSON object that contains VM properties that are common across all VMs in this batch + VirtualMachineBaseProfile *BulkVMConfiguration + + // JSON array that contains VM properties that should be overridden for each VM in the batch + VirtualMachineOverrides []*BulkVMConfiguration +} + +// ResourceProvisionPayload - Resource creation data model +type ResourceProvisionPayload struct { + // REQUIRED; Number of VMs to be created + ResourceCount *int32 + + // if resourceOverrides doesn't contain "name", service will create name based of prefix and ResourceCount e.g. resourceprefix-0,resourceprefix-1.. + ResourcePrefix *string + + // Virtual machine profile object that contains VM properties that are common across all VMs in this batch (if you want to + // create 100 VMs in this request, and they all have same vmSize, then include vmSize in baseProfile) + VirtualMachineBaseProfile *BulkVMConfiguration + + // Virtual machine profile array that contains VM properties that needs to be overridden for each VM in the batch (if you + // want to create 100 VMs, they all need a distinct computerName property, you pass computerNames for each VM in batch in + // this array), service will merge baseProfile with VM specific overrides and create a merged VMProfile. + VirtualMachineOverrides []*BulkVMConfiguration +} + +// ResourceResultSummary - The status of the resources +type ResourceResultSummary struct { + // REQUIRED; The error code for those resources. In case of success, code is populated with Success. + Code *string + + // REQUIRED; The number of resources that the code applies to. + Count *int32 + + // The error details for the resources. Not populated on success cases. + ErrorDetails *Error +} + +// ResourceStatus - The status of a resource after a resource level operation was performed +type ResourceStatus struct { + // REQUIRED; The arm identifier of the resource + ResourceID *string + + // REQUIRED; The state the resource is currently on + Status *ResourceOperationStatus + + // Errors encountered while trying to perform + Error *Error +} + +// Resources - The resources needed for the user request +type Resources struct { + // REQUIRED; The resource ids used for the request + IDs []*string +} + +// RetryPolicy - The retry policy for the user request +type RetryPolicy struct { + // Action to take on failure + OnFailureAction *ResourceOperationType + + // Retry count for user request + RetryCount *int32 + + // Retry window in minutes for user request + RetryWindowInMinutes *int32 +} + +// SSHConfiguration - SSH configuration for Linux based VMs running on Azure +type SSHConfiguration struct { + // The list of SSH public keys used to authenticate with linux based VMs. + PublicKeys []*SSHPublicKey +} + +// SSHPublicKey - Contains information about SSH certificate public key and the path on the Linux VM where the public key +// is placed. +type SSHPublicKey struct { + // SSH public key certificate used to authenticate with the VM through ssh. The key needs to be at least 2048-bit and in ssh-rsa + // format. For creating ssh keys, see [Create SSH keys on Linux and Mac for Linux VMs in Azure]https://docs.microsoft.com/azure/virtual-machines/linux/create-ssh-keys-detailed). + KeyData *string + + // Specifies the full path on the created VM where ssh public key is stored. If the file already exists, the specified key + // is appended to the file. Example: /home/user/.ssh/authorized_keys + Path *string +} + +// Schedule - The schedule details for the user request +type Schedule struct { + // REQUIRED; The deadlinetype of the operation, this can either be InitiateAt or CompleteBy + DeadlineType *DeadlineType + + // The deadline for the operation + DeadLine *time.Time + + // The deadline for the operation + Deadline *time.Time + + // The timezone for the operation + TimeZone *string + + // The timezone for the operation + Timezone *string +} + +// ScheduledAction - The scheduled action resource +type ScheduledAction struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *ScheduledActionProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ScheduledActionListResult - The response of a ScheduledAction list operation. +type ScheduledActionListResult struct { + // REQUIRED; The ScheduledAction items on this page + Value []*ScheduledAction + + // The link to the next page of items + NextLink *string +} + +// ScheduledActionProperties - Scheduled action properties +type ScheduledActionProperties struct { + // REQUIRED; The action the scheduled action should perform in the resources + ActionType *ScheduledActionType + + // REQUIRED; The notification settings for the scheduled action + NotificationSettings []*NotificationProperties + + // REQUIRED; The type of resource the scheduled action is targeting + ResourceType *ResourceType + + // REQUIRED; The schedule the scheduled action is supposed to follow + Schedule *ScheduledActionsSchedule + + // REQUIRED; The time which the scheduled action is supposed to start running + StartTime *time.Time + + // Tell if the scheduled action is disabled or not + Disabled *bool + + // The time when the scheduled action is supposed to stop scheduling + EndTime *time.Time + + // READ-ONLY; The status of the last provisioning operation performed on the resource. + ProvisioningState *ProvisioningState +} + +// ScheduledActionResource - Represents an scheduled action resource metadata. +type ScheduledActionResource struct { + // REQUIRED; The ARM Id of the resource. + // "subscriptions/{subId}/resourceGroups/{rgName}/providers/Microsoft.Compute/virtualMachines/{vmName}" + ResourceID *string + + // The desired notification settings for the specified resource. + NotificationSettings []*NotificationProperties + + // READ-ONLY; The compute RP resource id of the resource in the scheduled actions scope. + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; The type of resource + Type *string +} + +// ScheduledActionResources - The scheduled action extension +type ScheduledActionResources struct { + // The resource-specific properties for this resource. + Properties *ScheduledActionsExtensionProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ScheduledActionResourcesListResult - The response of a ScheduledActionResources list operation. +type ScheduledActionResourcesListResult struct { + // REQUIRED; The ScheduledActionResources items on this page + Value []*ScheduledActionResources + + // The link to the next page of items + NextLink *string +} + +// ScheduledActionUpdate - The type used for update operations of the ScheduledAction. +type ScheduledActionUpdate struct { + // The resource-specific properties for this resource. + Properties *ScheduledActionUpdateProperties + + // Resource tags. + Tags map[string]*string +} + +// ScheduledActionUpdateProperties - The updatable properties of the ScheduledAction. +type ScheduledActionUpdateProperties struct { + // The action the scheduled action should perform in the resources + ActionType *ScheduledActionType + + // Tell if the scheduled action is disabled or not + Disabled *bool + + // The time when the scheduled action is supposed to stop scheduling + EndTime *time.Time + + // The notification settings for the scheduled action + NotificationSettings []*NotificationProperties + + // The type of resource the scheduled action is targeting + ResourceType *ResourceType + + // The schedule the scheduled action is supposed to follow + Schedule *ScheduledActionsSchedule + + // The time which the scheduled action is supposed to start running + StartTime *time.Time +} + +// ScheduledActionsExtensionProperties - Scheduled action extension properties +type ScheduledActionsExtensionProperties struct { + // REQUIRED; The action the scheduled action should perform in the resources + ActionType *ScheduledActionType + + // REQUIRED; The notification settings for the scheduled action + NotificationSettings []*NotificationProperties + + // REQUIRED; The type of resource the scheduled action is targeting + ResourceType *ResourceType + + // REQUIRED; The schedule the scheduled action is supposed to follow + Schedule *ScheduledActionsSchedule + + // REQUIRED; The time which the scheduled action is supposed to start running + StartTime *time.Time + + // Tell if the scheduled action is disabled or not + Disabled *bool + + // The time when the scheduled action is supposed to stop scheduling + EndTime *time.Time + + // READ-ONLY; The status of the last provisioning operation performed on the resource. + ProvisioningState *ProvisioningState + + // READ-ONLY; The notification settings for the scheduled action at a resource level. Resource level notification settings + // are scope to specific resources only and submitted through attach requests. + ResourceNotificationSettings []*NotificationProperties +} + +// ScheduledActionsSchedule - Specify the schedule in which the scheduled action is supposed to follow +type ScheduledActionsSchedule struct { + // REQUIRED; The days of the month the scheduled action is supposed to run on. If empty, it means it will run on every day + // of the month. + RequestedDaysOfTheMonth []*int32 + + // REQUIRED; The months the scheduled action is supposed to run on + RequestedMonths []*Month + + // REQUIRED; The week days the scheduled action is supposed to run on + RequestedWeekDays []*WeekDay + + // REQUIRED; The time the scheduled action is supposed to run on + ScheduledTime *time.Time + + // REQUIRED; The timezone the scheduled time is specified on + TimeZone *string + + // The type of deadline the scheduled action is supposed to follow for the schedule. If no value is passed, it will default + // to InitiateAt. + DeadlineType *DeadlineType + + // The execution parameters the scheduled action is supposed to follow + ExecutionParameters *ExecutionParameters +} + +// ScheduledEventsAdditionalPublishingTargets - Specifies additional publishing targets for scheduled events. +type ScheduledEventsAdditionalPublishingTargets struct { + // The configuration parameters used while creating eventGridAndResourceGraph Scheduled Event setting. + EventGridAndResourceGraph *EventGridAndResourceGraph +} + +// ScheduledEventsPolicy - Specifies Redeploy, Reboot and ScheduledEventsAdditionalPublishingTargets Scheduled Event related +// configurations. +type ScheduledEventsPolicy struct { + // The configuration parameters used while creating AllInstancesDown scheduled event setting creation. + AllInstancesDown *AllInstancesDown + + // The configuration parameters used while publishing scheduledEventsAdditionalPublishingTargets. + ScheduledEventsAdditionalPublishingTargets *ScheduledEventsAdditionalPublishingTargets + + // The configuration parameters used while creating userInitiatedReboot scheduled event setting creation. + UserInitiatedReboot *UserInitiatedReboot + + // The configuration parameters used while creating userInitiatedRedeploy scheduled event setting creation. + UserInitiatedRedeploy *UserInitiatedRedeploy +} + +// ScheduledEventsProfile - Profile for the scheduled events. +type ScheduledEventsProfile struct { + // Specifies OS Image Scheduled Event related configurations. + OSImageNotificationProfile *OSImageNotificationProfile + + // Specifies Terminate Scheduled Event related configurations. + TerminateNotificationProfile *TerminateNotificationProfile +} + +// SecurityProfile - Specifies the Security profile settings for the virtual machine or virtual machine scale set. +type SecurityProfile struct { + // This property can be used by user in the request to enable or disable the Host Encryption for the virtual machine or virtual + // machine scale set. This will enable the encryption for all the disks including Resource/Temp disk at host itself. The default + // behavior is: The Encryption at host will be disabled unless this property is set to true for the resource. + EncryptionAtHost *bool + + // Specifies the Managed Identity used by ADE to get access token for keyvault operations. + EncryptionIdentity *EncryptionIdentity + + // Specifies ProxyAgent settings while creating the virtual machine. Minimum compute api-version: 2023-09-01. + ProxyAgentSettings *ProxyAgentSettings + + // Specifies the SecurityType of the virtual machine. It has to be set to any specified value to enable UefiSettings. The + // default behavior is: UefiSettings will not be enabled unless this property is set. + SecurityType *SecurityTypes + + // Specifies the security settings like secure boot and vTPM used while creating the virtual machine. Minimum compute api-version: + // 2020-12-01. + UefiSettings *UefiSettings +} + +// StartResourceOperationResponse - The response from a start request +type StartResourceOperationResponse struct { + // REQUIRED; The description of the operation response + Description *string + + // REQUIRED; The location of the start request eg westus + Location *string + + // REQUIRED; The type of resources used in the start request eg virtual machines + Type *string + + // The results from the start request if no errors exist + Results []*ResourceOperation +} + +// StorageProfile - Specifies the storage settings for the virtual machine disks. +type StorageProfile struct { + // Specifies the parameters that are used to add a data disk to a virtual machine. For more information about disks, see [About + // disks and VHDs for Azure virtual machines](https://docs.microsoft.com/azure/virtual-machines/managed-disks-overview). + DataDisks []*DataDisk + + // Specifies the disk controller type configured for the VM. **Note:** This property will be set to the default disk controller + // type if not specified provided virtual machine is being created with 'hyperVGeneration' set to V2 based on the capabilities + // of the operating system disk and VM size from the the specified minimum api version. You need to deallocate the VM before + // updating its disk controller type unless you are updating the VM size in the VM configuration which implicitly deallocates + // and reallocates the VM. Minimum api-version: 2022-08-01. + DiskControllerType *DiskControllerTypes + + // Specifies information about the image to use. You can specify information about platform images, marketplace images, or + // virtual machine images. This element is required when you want to use a platform image, marketplace image, or virtual machine + // image, but is not used in other creation operations. + ImageReference *ImageReference + + // Specifies information about the operating system disk used by the virtual machine. For more information about disks, see + // [About disks and VHDs for Azure virtual machines](https://docs.microsoft.com/azure/virtual-machines/managed-disks-overview). + OSDisk *OSDisk +} + +// SubResource - Describes a reference to a sub-resource. +type SubResource struct { + // The ID of the sub-resource. + ID *string +} + +// SubmitDeallocateRequest - The deallocate request for resources +type SubmitDeallocateRequest struct { + // REQUIRED; CorrelationId item + Correlationid *string + + // REQUIRED; The execution parameters for the request + ExecutionParameters *ExecutionParameters + + // REQUIRED; The resources for the request + Resources *Resources + + // REQUIRED; The schedule for the request + Schedule *Schedule +} + +// SubmitHibernateRequest - This is the request for hibernate +type SubmitHibernateRequest struct { + // REQUIRED; CorrelationId item + Correlationid *string + + // REQUIRED; The execution parameters for the request + ExecutionParameters *ExecutionParameters + + // REQUIRED; The resources for the request + Resources *Resources + + // REQUIRED; The schedule for the request + Schedule *Schedule +} + +// SubmitStartRequest - This is the request for start +type SubmitStartRequest struct { + // REQUIRED; CorrelationId item + Correlationid *string + + // REQUIRED; The execution parameters for the request + ExecutionParameters *ExecutionParameters + + // REQUIRED; The resources for the request + Resources *Resources + + // REQUIRED; The schedule for the request + Schedule *Schedule +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time + + // The identity that created the resource. + CreatedBy *string + + // The type of identity that created the resource. + CreatedByType *CreatedByType + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time + + // The identity that last modified the resource. + LastModifiedBy *string + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType +} + +// TerminateNotificationProfile - Profile properties for the Terminate Scheduled event. +type TerminateNotificationProfile struct { + // Specifies whether the Terminate Scheduled event is enabled or disabled. + Enable *bool + + // Configurable length of time a Virtual Machine being deleted will have to potentially approve the Terminate Scheduled Event + // before the event is auto approved (timed out). The configuration must be specified in ISO 8601 format, the default value + // is 5 minutes (PT5M) + NotBeforeTimeout *string +} + +// UefiSettings - Specifies the security settings like secure boot and vTPM used while creating the virtual machine. Minimum +// api-version: 2020-12-01. +type UefiSettings struct { + // Specifies whether secure boot should be enabled on the virtual machine. Minimum compute api-version: 2020-12-01. + SecureBootEnabled *bool + + // Specifies whether vTPM should be enabled on the virtual machine. Minimum compute api-version: 2020-12-01. + VTpmEnabled *bool +} + +type UserAssignedIdentitiesValue struct { + // READ-ONLY; The client id of user assigned identity. + ClientID *string + + // READ-ONLY; The principal id of user assigned identity. + PrincipalID *string +} + +// UserInitiatedReboot - Specifies Reboot related Scheduled Event related configurations. +type UserInitiatedReboot struct { + // Specifies Reboot Scheduled Event related configurations. + AutomaticallyApprove *bool +} + +// UserInitiatedRedeploy - Specifies Redeploy related Scheduled Event related configurations. +type UserInitiatedRedeploy struct { + // Specifies Redeploy Scheduled Event related configurations. + AutomaticallyApprove *bool +} + +// VMDiskSecurityProfile - Specifies the security profile settings for the managed disk. **Note:** It can only be set for +// Confidential VMs. +type VMDiskSecurityProfile struct { + // Specifies the customer managed disk encryption set resource id for the managed disk that is used for Customer Managed Key + // encrypted ConfidentialVM OS Disk and VMGuest blob. + DiskEncryptionSet *DiskEncryptionSetParameters + + // Specifies the EncryptionType of the managed disk. It is set to DiskWithVMGuestState for encryption of the managed disk + // along with VMGuestState blob, VMGuestStateOnly for encryption of just the VMGuestState blob, and NonPersistedTPM for not + // persisting firmware state in the VMGuestState blob.. **Note:** It can be set for only Confidential VMs. + SecurityEncryptionType *SecurityEncryptionTypes +} + +// VMGalleryApplication - Specifies the required information to reference a compute gallery application version +type VMGalleryApplication struct { + // REQUIRED; Specifies the GalleryApplicationVersion resource id on the form of /subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroupName}/providers/Microsoft.Compute/galleries/{galleryName}/applications/{application}/versions/{version} + PackageReferenceID *string + + // Optional, Specifies the uri to an azure blob that will replace the default configuration for the package if provided + ConfigurationReference *string + + // If set to true, when a new Gallery Application version is available in PIR/SIG, it will be automatically updated for the + // VM/VMSS + EnableAutomaticUpgrade *bool + + // Optional, Specifies the order in which the packages have to be installed + Order *int32 + + // Optional, Specifies a passthrough value for more generic context. + Tags *string + + // Optional, If true, any failure for any operation in the VmApplication will fail the deployment + TreatFailureAsDeploymentFailure *bool +} + +// VMSizeProfile - A VM size profile with a name and rank for flex VM creation +type VMSizeProfile struct { + // REQUIRED; The name of the VM size, eg Standard_D2ads_v5 + Name *string + + // The rank of this VM size in the priority order + Rank *int32 +} + +// VMSizeProperties - Specifies VM Size Property settings on the virtual machine. +type VMSizeProperties struct { + // Specifies the number of vCPUs available for the VM. When this property is not specified in the request body the default + // behavior is to set it to the value of vCPUs available for that VM size exposed in api response of [List all available virtual + // machine sizes in a region](https://docs.microsoft.com/en-us/rest/api/compute/resource-skus/list). + VCpusAvailable *int32 + + // Specifies the vCPU to physical core ratio. When this property is not specified in the request body the default behavior + // is set to the value of vCPUsPerCore for the VM Size exposed in api response of [List all available virtual machine sizes + // in a region](https://docs.microsoft.com/en-us/rest/api/compute/resource-skus/list). **Setting this property to 1 also means + // that hyper-threading is disabled.** + VCpusPerCore *int32 +} + +// VaultCertificate - Describes a single certificate reference in a Key Vault, and where the certificate should reside on +// the VM. +type VaultCertificate struct { + // For Windows VMs, specifies the certificate store on the Virtual Machine to which the certificate should be added. The specified + // certificate store is implicitly in the LocalMachine account. For Linux VMs, the certificate file is placed under the /var/lib/waagent + // directory, with the file name .crt for the X509 certificate file and .prv for + // private key. Both of these files are .pem formatted. + CertificateStore *string + + // This is the URL of a certificate that has been uploaded to Key Vault as a secret. For adding a secret to the Key Vault, + // see [Add a key or secret to the key vault](https://docs.microsoft.com/azure/key-vault/key-vault-get-started/#add). In this + // case, your certificate needs to be It is the Base64 encoding of the following JSON Object which is encoded in UTF-8:

+ // {
'data':'',
'dataType':'pfx',
'password':''
}
To install + // certificates on a virtual machine it is recommended to use the [Azure Key Vault virtual machine extension for Linux](https://docs.microsoft.com/azure/virtual-machines/extensions/key-vault-linux) + // or the [Azure Key Vault virtual machine extension for Windows](https://docs.microsoft.com/azure/virtual-machines/extensions/key-vault-windows). + CertificateURL *string +} + +// VaultSecretGroup - Describes a set of certificates which are all in the same Key Vault. +type VaultSecretGroup struct { + // The relative URL of the Key Vault containing all of the certificates in VaultCertificates. + SourceVault *SubResource + + // The list of key vault references in SourceVault which contain certificates. + VaultCertificates []*VaultCertificate +} + +// VirtualHardDisk - Describes the uri of a disk. +type VirtualHardDisk struct { + // Specifies the virtual hard disk's uri. + URI *string +} + +// VirtualMachineIPTag - Contains the IP tag associated with the public IP address. +type VirtualMachineIPTag struct { + // IP tag type. Example: FirstPartyUsage. + IPTagType *string + + // IP tag associated with the public IP. Example: SQL, Storage etc. + Tag *string +} + +// VirtualMachineIdentity - Identity for the virtual machine. +type VirtualMachineIdentity struct { + // The type of identity used for the virtual machine. The type 'SystemAssigned, UserAssigned' includes both an implicitly + // created identity and a set of user assigned identities. The type 'None' will remove any identities from the virtual machine. + Type *ResourceIdentityType + + // The list of user identities associated with the Virtual Machine. The user identity dictionary key references will be ARM + // resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. + UserAssignedIdentities map[string]*UserAssignedIdentitiesValue + + // READ-ONLY; The principal id of virtual machine identity. This property will only be provided for a system assigned identity. + PrincipalID *string + + // READ-ONLY; The tenant id associated with the virtual machine. This property will only be provided for a system assigned + // identity. + TenantID *string +} + +// VirtualMachineNetworkInterfaceConfiguration - Describes a virtual machine network interface configurations. +type VirtualMachineNetworkInterfaceConfiguration struct { + // REQUIRED; The network interface configuration name. + Name *string + + // Describes a virtual machine network profile's IP configuration. + Properties *VirtualMachineNetworkInterfaceConfigurationProperties + + // Resource tags applied to the networkInterface address created by this NetworkInterfaceConfiguration + Tags map[string]*string +} + +// VirtualMachineNetworkInterfaceConfigurationProperties - Describes a virtual machine network profile's IP configuration. +type VirtualMachineNetworkInterfaceConfigurationProperties struct { + // REQUIRED; Specifies the IP configurations of the network interface. + IPConfigurations []*VirtualMachineNetworkInterfaceIPConfiguration + + // Specifies whether the Auxiliary mode is enabled for the Network Interface resource. + AuxiliaryMode *NetworkInterfaceAuxiliaryMode + + // Specifies whether the Auxiliary sku is enabled for the Network Interface resource. + AuxiliarySKU *NetworkInterfaceAuxiliarySKU + + // The dns settings to be applied on the network interfaces. + DNSSettings *VirtualMachineNetworkInterfaceDNSSettingsConfiguration + + // Specify what happens to the network interface when the VM is deleted + DeleteOption *DeleteOptions + + // Specifies whether the network interface is disabled for tcp state tracking. + DisableTCPStateTracking *bool + + // The DSCP configuration for the network interface. + DscpConfiguration *SubResource + + // Specifies whether the network interface is accelerated networking-enabled. + EnableAcceleratedNetworking *bool + + // Specifies whether the network interface is FPGA networking-enabled. + EnableFpga *bool + + // Whether IP forwarding enabled on this NIC. + EnableIPForwarding *bool + + // The network security group. + NetworkSecurityGroup *SubResource + + // Specifies the primary network interface in case the virtual machine has more than 1 network interface. + Primary *bool +} + +// VirtualMachineNetworkInterfaceDNSSettingsConfiguration - Describes a virtual machines network configuration's DNS settings. +type VirtualMachineNetworkInterfaceDNSSettingsConfiguration struct { + // List of DNS servers IP addresses + DNSServers []*string +} + +// VirtualMachineNetworkInterfaceIPConfiguration - Describes a virtual machine network profile's IP configuration. +type VirtualMachineNetworkInterfaceIPConfiguration struct { + // REQUIRED; The IP configuration name. + Name *string + + // Describes a virtual machine network interface IP configuration properties. + Properties *VirtualMachineNetworkInterfaceIPConfigurationProperties +} + +// VirtualMachineNetworkInterfaceIPConfigurationProperties - Describes a virtual machine network interface IP configuration +// properties. +type VirtualMachineNetworkInterfaceIPConfigurationProperties struct { + // Specifies an array of references to backend address pools of application gateways. A virtual machine can reference backend + // address pools of multiple application gateways. Multiple virtual machines cannot use the same application gateway. + ApplicationGatewayBackendAddressPools []*SubResource + + // Specifies an array of references to application security group. + ApplicationSecurityGroups []*SubResource + + // Specifies an array of references to backend address pools of load balancers. A virtual machine can reference backend address + // pools of one public and one internal load balancer. [Multiple virtual machines cannot use the same basic sku load balancer]. + LoadBalancerBackendAddressPools []*SubResource + + // Specifies the primary network interface in case the virtual machine has more than 1 network interface. + Primary *bool + + // Available from Api-Version 2017-03-30 onwards, it represents whether the specific ipconfiguration is IPv4 or IPv6. Default + // is taken as IPv4. Possible values are: 'IPv4' and 'IPv6'. + PrivateIPAddressVersion *IPVersions + + // The publicIPAddressConfiguration. + PublicIPAddressConfiguration *VirtualMachinePublicIPAddressConfiguration + + // Specifies the identifier of the subnet. + Subnet *SubResource +} + +// VirtualMachinePublicIPAddressConfiguration - Describes a virtual machines IP Configuration's PublicIPAddress configuration +type VirtualMachinePublicIPAddressConfiguration struct { + // REQUIRED; The publicIP address configuration name. + Name *string + + // Describes a virtual machines IP Configuration's PublicIPAddress configuration + Properties *VirtualMachinePublicIPAddressConfigurationProperties + + // Describes the public IP Sku. It can only be set with OrchestrationMode as Flexible. + SKU *PublicIPAddressSKU + + // Resource tags applied to the publicIP address created by this PublicIPAddressConfiguration + Tags map[string]*string +} + +// VirtualMachinePublicIPAddressConfigurationProperties - Describes a virtual machines IP Configuration's PublicIPAddress +// configuration +type VirtualMachinePublicIPAddressConfigurationProperties struct { + // The dns settings to be applied on the publicIP addresses . + DNSSettings *VirtualMachinePublicIPAddressDNSSettingsConfiguration + + // Specify what happens to the public IP address when the VM is deleted + DeleteOption *DeleteOptions + + // The list of IP tags associated with the public IP address. + IPTags []*VirtualMachineIPTag + + // The idle timeout of the public IP address. + IdleTimeoutInMinutes *int32 + + // Available from Api-Version 2019-07-01 onwards, it represents whether the specific ipconfiguration is IPv4 or IPv6. Default + // is taken as IPv4. Possible values are: 'IPv4' and 'IPv6'. + PublicIPAddressVersion *IPVersions + + // Specify the public IP allocation type + PublicIPAllocationMethod *PublicIPAllocationMethod + + // The PublicIPPrefix from which to allocate publicIP addresses. + PublicIPPrefix *SubResource +} + +// VirtualMachinePublicIPAddressDNSSettingsConfiguration - Describes a virtual machines network configuration's DNS settings. +type VirtualMachinePublicIPAddressDNSSettingsConfiguration struct { + // REQUIRED; The Domain name label prefix of the PublicIPAddress resources that will be created. The generated name label + // is the concatenation of the domain name label and vm network profile unique ID. + DomainNameLabel *string + + // The Domain name label scope of the PublicIPAddress resources that will be created. The generated name label is the concatenation + // of the hashed domain name label with policy according to the domain name label scope and vm network profile unique ID. + DomainNameLabelScope *DomainNameLabelScopeTypes +} + +// WinRMConfiguration - Describes Windows Remote Management configuration of the VM +type WinRMConfiguration struct { + // The list of Windows Remote Management listeners + Listeners []*WinRMListener +} + +// WinRMListener - Describes Protocol and thumbprint of Windows Remote Management listener +type WinRMListener struct { + // This is the URL of a certificate that has been uploaded to Key Vault as a secret. For adding a secret to the Key Vault, + // see [Add a key or secret to the key vault](https://docs.microsoft.com/azure/key-vault/key-vault-get-started/#add). In this + // case, your certificate needs to be the Base64 encoding of the following JSON Object which is encoded in UTF-8:

+ // {
"data":"",
"dataType":"pfx",
"password":""
}
To install + // certificates on a virtual machine it is recommended to use the [Azure Key Vault virtual machine extension for Linux](https://docs.microsoft.com/azure/virtual-machines/extensions/key-vault-linux) + // or the [Azure Key Vault virtual machine extension for Windows](https://docs.microsoft.com/azure/virtual-machines/extensions/key-vault-windows). + CertificateURL *string + + // Specifies the protocol of WinRM listener. Possible values are: **http,** **https.** + Protocol *ProtocolTypes +} + +// WindowsConfiguration - Specifies Windows operating system settings on the virtual machine. +type WindowsConfiguration struct { + // Specifies additional base-64 encoded XML formatted information that can be included in the Unattend.xml file, which is + // used by Windows Setup. + AdditionalUnattendContent []*AdditionalUnattendContent + + // Indicates whether Automatic Updates is enabled for the Windows virtual machine. Default value is true. For virtual machine + // scale sets, this property can be updated and updates will take effect on OS reprovisioning. + EnableAutomaticUpdates *bool + + // [Preview Feature] Specifies settings related to VM Guest Patching on Windows. + PatchSettings *PatchSettings + + // Indicates whether virtual machine agent should be provisioned on the virtual machine. When this property is not specified + // in the request body, it is set to true by default. This will ensure that VM Agent is installed on the VM so that extensions + // can be added to the VM later. + ProvisionVMAgent *bool + + // Specifies the time zone of the virtual machine. e.g. "Pacific Standard Time". Possible values can be [TimeZoneInfo.Id](https://docs.microsoft.com/dotnet/api/system.timezoneinfo.id?#System_TimeZoneInfo_Id) + // value from time zones returned by [TimeZoneInfo.GetSystemTimeZones](https://docs.microsoft.com/dotnet/api/system.timezoneinfo.getsystemtimezones). + TimeZone *string + + // Specifies the Windows Remote Management listeners. This enables remote Windows PowerShell. + WinRM *WinRMConfiguration +} + +// WindowsVMGuestPatchAutomaticByPlatformSettings - Specifies additional settings to be applied when patch mode AutomaticByPlatform +// is selected in Windows patch settings. +type WindowsVMGuestPatchAutomaticByPlatformSettings struct { + // Enables customer to schedule patching without accidental upgrades + BypassPlatformSafetyChecksOnUserSchedule *bool + + // Specifies the reboot setting for all AutomaticByPlatform patch installation operations. + RebootSetting *WindowsVMGuestPatchAutomaticByPlatformRebootSetting +} + +// ZoneAllocationPolicy - The zone allocation policy for distributing VMs across availability zones +type ZoneAllocationPolicy struct { + // REQUIRED; The distribution strategy for zone allocation + DistributionStrategy *DistributionStrategy + + // The zone preferences for allocation priority + ZonePreferences []*ZonePreference +} + +// ZonePreference - A zone preference with a zone identifier and rank +type ZonePreference struct { + // REQUIRED; The zone identifier + Zone *string + + // The rank of this zone in the priority order + Rank *int32 +} diff --git a/test/local/armcomputeschedule/zz_models_serde.go b/test/local/armcomputeschedule/zz_models_serde.go new file mode 100644 index 000000000000..fff3a90e5be6 --- /dev/null +++ b/test/local/armcomputeschedule/zz_models_serde.go @@ -0,0 +1,5461 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcomputeschedule + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type APIEntityReference. +func (a APIEntityReference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APIEntityReference. +func (a *APIEntityReference) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AdditionalCapabilities. +func (a AdditionalCapabilities) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "hibernationEnabled", a.HibernationEnabled) + populate(objectMap, "ultraSSDEnabled", a.UltraSSDEnabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AdditionalCapabilities. +func (a *AdditionalCapabilities) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "hibernationEnabled": + err = unpopulate(val, "HibernationEnabled", &a.HibernationEnabled) + delete(rawMsg, key) + case "ultraSSDEnabled": + err = unpopulate(val, "UltraSSDEnabled", &a.UltraSSDEnabled) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AdditionalUnattendContent. +func (a AdditionalUnattendContent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + if a.ComponentName != nil { + objectMap["componentName"] = "Microsoft-Windows-Shell-Setup" + } + populate(objectMap, "content", a.Content) + if a.PassName != nil { + objectMap["passName"] = "OobeSystem" + } + populate(objectMap, "settingName", a.SettingName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AdditionalUnattendContent. +func (a *AdditionalUnattendContent) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "componentName": + err = unpopulate(val, "ComponentName", &a.ComponentName) + delete(rawMsg, key) + case "content": + err = unpopulate(val, "Content", &a.Content) + delete(rawMsg, key) + case "passName": + err = unpopulate(val, "PassName", &a.PassName) + delete(rawMsg, key) + case "settingName": + err = unpopulate(val, "SettingName", &a.SettingName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AllInstancesDown. +func (a AllInstancesDown) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "automaticallyApprove", a.AutomaticallyApprove) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AllInstancesDown. +func (a *AllInstancesDown) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "automaticallyApprove": + err = unpopulate(val, "AutomaticallyApprove", &a.AutomaticallyApprove) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ApplicationProfile. +func (a ApplicationProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "galleryApplications", a.GalleryApplications) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationProfile. +func (a *ApplicationProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "galleryApplications": + err = unpopulate(val, "GalleryApplications", &a.GalleryApplications) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BootDiagnostics. +func (b BootDiagnostics) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enabled", b.Enabled) + populate(objectMap, "storageUri", b.StorageURI) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BootDiagnostics. +func (b *BootDiagnostics) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "enabled": + err = unpopulate(val, "Enabled", &b.Enabled) + delete(rawMsg, key) + case "storageUri": + err = unpopulate(val, "StorageURI", &b.StorageURI) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BulkActionVMExtension. +func (b BulkActionVMExtension) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", b.Name) + populate(objectMap, "properties", b.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BulkActionVMExtension. +func (b *BulkActionVMExtension) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &b.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &b.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BulkActionVMExtensionProperties. +func (b BulkActionVMExtensionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "autoUpgradeMinorVersion", b.AutoUpgradeMinorVersion) + populate(objectMap, "enableAutomaticUpgrade", b.EnableAutomaticUpgrade) + populate(objectMap, "forceUpdateTag", b.ForceUpdateTag) + populate(objectMap, "protectedSettings", b.ProtectedSettings) + populate(objectMap, "protectedSettingsFromKeyVault", b.ProtectedSettingsFromKeyVault) + populate(objectMap, "provisionAfterExtensions", b.ProvisionAfterExtensions) + populate(objectMap, "publisher", b.Publisher) + populate(objectMap, "settings", b.Settings) + populate(objectMap, "suppressFailures", b.SuppressFailures) + populate(objectMap, "type", b.Type) + populate(objectMap, "typeHandlerVersion", b.TypeHandlerVersion) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BulkActionVMExtensionProperties. +func (b *BulkActionVMExtensionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "autoUpgradeMinorVersion": + err = unpopulate(val, "AutoUpgradeMinorVersion", &b.AutoUpgradeMinorVersion) + delete(rawMsg, key) + case "enableAutomaticUpgrade": + err = unpopulate(val, "EnableAutomaticUpgrade", &b.EnableAutomaticUpgrade) + delete(rawMsg, key) + case "forceUpdateTag": + err = unpopulate(val, "ForceUpdateTag", &b.ForceUpdateTag) + delete(rawMsg, key) + case "protectedSettings": + err = unpopulate(val, "ProtectedSettings", &b.ProtectedSettings) + delete(rawMsg, key) + case "protectedSettingsFromKeyVault": + err = unpopulate(val, "ProtectedSettingsFromKeyVault", &b.ProtectedSettingsFromKeyVault) + delete(rawMsg, key) + case "provisionAfterExtensions": + err = unpopulate(val, "ProvisionAfterExtensions", &b.ProvisionAfterExtensions) + delete(rawMsg, key) + case "publisher": + err = unpopulate(val, "Publisher", &b.Publisher) + delete(rawMsg, key) + case "settings": + err = unpopulate(val, "Settings", &b.Settings) + delete(rawMsg, key) + case "suppressFailures": + err = unpopulate(val, "SuppressFailures", &b.SuppressFailures) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &b.Type) + delete(rawMsg, key) + case "typeHandlerVersion": + err = unpopulate(val, "TypeHandlerVersion", &b.TypeHandlerVersion) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BulkActionVMProperties. +func (b BulkActionVMProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "additionalCapabilities", b.AdditionalCapabilities) + populate(objectMap, "applicationProfile", b.ApplicationProfile) + populate(objectMap, "capacityReservation", b.CapacityReservation) + populate(objectMap, "diagnosticsProfile", b.DiagnosticsProfile) + populate(objectMap, "extensionsTimeBudget", b.ExtensionsTimeBudget) + populate(objectMap, "hardwareProfile", b.HardwareProfile) + populate(objectMap, "licenseType", b.LicenseType) + populate(objectMap, "networkProfile", b.NetworkProfile) + populate(objectMap, "osProfile", b.OSProfile) + populate(objectMap, "scheduledEventsPolicy", b.ScheduledEventsPolicy) + populate(objectMap, "scheduledEventsProfile", b.ScheduledEventsProfile) + populate(objectMap, "securityProfile", b.SecurityProfile) + populate(objectMap, "storageProfile", b.StorageProfile) + populate(objectMap, "userData", b.UserData) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BulkActionVMProperties. +func (b *BulkActionVMProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "additionalCapabilities": + err = unpopulate(val, "AdditionalCapabilities", &b.AdditionalCapabilities) + delete(rawMsg, key) + case "applicationProfile": + err = unpopulate(val, "ApplicationProfile", &b.ApplicationProfile) + delete(rawMsg, key) + case "capacityReservation": + err = unpopulate(val, "CapacityReservation", &b.CapacityReservation) + delete(rawMsg, key) + case "diagnosticsProfile": + err = unpopulate(val, "DiagnosticsProfile", &b.DiagnosticsProfile) + delete(rawMsg, key) + case "extensionsTimeBudget": + err = unpopulate(val, "ExtensionsTimeBudget", &b.ExtensionsTimeBudget) + delete(rawMsg, key) + case "hardwareProfile": + err = unpopulate(val, "HardwareProfile", &b.HardwareProfile) + delete(rawMsg, key) + case "licenseType": + err = unpopulate(val, "LicenseType", &b.LicenseType) + delete(rawMsg, key) + case "networkProfile": + err = unpopulate(val, "NetworkProfile", &b.NetworkProfile) + delete(rawMsg, key) + case "osProfile": + err = unpopulate(val, "OSProfile", &b.OSProfile) + delete(rawMsg, key) + case "scheduledEventsPolicy": + err = unpopulate(val, "ScheduledEventsPolicy", &b.ScheduledEventsPolicy) + delete(rawMsg, key) + case "scheduledEventsProfile": + err = unpopulate(val, "ScheduledEventsProfile", &b.ScheduledEventsProfile) + delete(rawMsg, key) + case "securityProfile": + err = unpopulate(val, "SecurityProfile", &b.SecurityProfile) + delete(rawMsg, key) + case "storageProfile": + err = unpopulate(val, "StorageProfile", &b.StorageProfile) + delete(rawMsg, key) + case "userData": + err = unpopulate(val, "UserData", &b.UserData) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BulkVMConfiguration. +func (b BulkVMConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "computeApiVersion", b.ComputeAPIVersion) + populate(objectMap, "extendedLocation", b.ExtendedLocation) + populate(objectMap, "identity", b.Identity) + populate(objectMap, "name", b.Name) + populate(objectMap, "placement", b.Placement) + populate(objectMap, "plan", b.Plan) + populate(objectMap, "properties", b.Properties) + populate(objectMap, "resourceGroupName", b.ResourceGroupName) + populate(objectMap, "tags", b.Tags) + populate(objectMap, "vmExtensions", b.VMExtensions) + populate(objectMap, "zones", b.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BulkVMConfiguration. +func (b *BulkVMConfiguration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "computeApiVersion": + err = unpopulate(val, "ComputeAPIVersion", &b.ComputeAPIVersion) + delete(rawMsg, key) + case "extendedLocation": + err = unpopulate(val, "ExtendedLocation", &b.ExtendedLocation) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &b.Identity) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &b.Name) + delete(rawMsg, key) + case "placement": + err = unpopulate(val, "Placement", &b.Placement) + delete(rawMsg, key) + case "plan": + err = unpopulate(val, "Plan", &b.Plan) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &b.Properties) + delete(rawMsg, key) + case "resourceGroupName": + err = unpopulate(val, "ResourceGroupName", &b.ResourceGroupName) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &b.Tags) + delete(rawMsg, key) + case "vmExtensions": + err = unpopulate(val, "VMExtensions", &b.VMExtensions) + delete(rawMsg, key) + case "zones": + err = unpopulate(val, "Zones", &b.Zones) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CancelOccurrenceRequest. +func (c CancelOccurrenceRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "resourceIds", c.ResourceIDs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CancelOccurrenceRequest. +func (c *CancelOccurrenceRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "resourceIds": + err = unpopulate(val, "ResourceIDs", &c.ResourceIDs) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CancelOperationsRequest. +func (c CancelOperationsRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "correlationid", c.Correlationid) + populate(objectMap, "operationIds", c.OperationIDs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CancelOperationsRequest. +func (c *CancelOperationsRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "correlationid": + err = unpopulate(val, "Correlationid", &c.Correlationid) + delete(rawMsg, key) + case "operationIds": + err = unpopulate(val, "OperationIDs", &c.OperationIDs) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CancelOperationsResponse. +func (c CancelOperationsResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "results", c.Results) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CancelOperationsResponse. +func (c *CancelOperationsResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "results": + err = unpopulate(val, "Results", &c.Results) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CapacityReservationProfile. +func (c CapacityReservationProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "capacityReservationGroup", c.CapacityReservationGroup) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CapacityReservationProfile. +func (c *CapacityReservationProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "capacityReservationGroup": + err = unpopulate(val, "CapacityReservationGroup", &c.CapacityReservationGroup) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CreateFlexResourceOperationResponse. +func (c CreateFlexResourceOperationResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", c.Description) + populate(objectMap, "location", c.Location) + populate(objectMap, "results", c.Results) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CreateFlexResourceOperationResponse. +func (c *CreateFlexResourceOperationResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &c.Description) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &c.Location) + delete(rawMsg, key) + case "results": + err = unpopulate(val, "Results", &c.Results) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CreateResourceOperationResponse. +func (c CreateResourceOperationResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", c.Description) + populate(objectMap, "location", c.Location) + populate(objectMap, "results", c.Results) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CreateResourceOperationResponse. +func (c *CreateResourceOperationResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &c.Description) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &c.Location) + delete(rawMsg, key) + case "results": + err = unpopulate(val, "Results", &c.Results) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DataDisk. +func (d DataDisk) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "caching", d.Caching) + populate(objectMap, "createOption", d.CreateOption) + populate(objectMap, "deleteOption", d.DeleteOption) + populate(objectMap, "detachOption", d.DetachOption) + populate(objectMap, "diskSizeGB", d.DiskSizeGB) + populate(objectMap, "image", d.Image) + populate(objectMap, "lun", d.Lun) + populate(objectMap, "managedDisk", d.ManagedDisk) + populate(objectMap, "name", d.Name) + populate(objectMap, "sourceResource", d.SourceResource) + populate(objectMap, "toBeDetached", d.ToBeDetached) + populate(objectMap, "vhd", d.Vhd) + populate(objectMap, "writeAcceleratorEnabled", d.WriteAcceleratorEnabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DataDisk. +func (d *DataDisk) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "caching": + err = unpopulate(val, "Caching", &d.Caching) + delete(rawMsg, key) + case "createOption": + err = unpopulate(val, "CreateOption", &d.CreateOption) + delete(rawMsg, key) + case "deleteOption": + err = unpopulate(val, "DeleteOption", &d.DeleteOption) + delete(rawMsg, key) + case "detachOption": + err = unpopulate(val, "DetachOption", &d.DetachOption) + delete(rawMsg, key) + case "diskSizeGB": + err = unpopulate(val, "DiskSizeGB", &d.DiskSizeGB) + delete(rawMsg, key) + case "image": + err = unpopulate(val, "Image", &d.Image) + delete(rawMsg, key) + case "lun": + err = unpopulate(val, "Lun", &d.Lun) + delete(rawMsg, key) + case "managedDisk": + err = unpopulate(val, "ManagedDisk", &d.ManagedDisk) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "sourceResource": + err = unpopulate(val, "SourceResource", &d.SourceResource) + delete(rawMsg, key) + case "toBeDetached": + err = unpopulate(val, "ToBeDetached", &d.ToBeDetached) + delete(rawMsg, key) + case "vhd": + err = unpopulate(val, "Vhd", &d.Vhd) + delete(rawMsg, key) + case "writeAcceleratorEnabled": + err = unpopulate(val, "WriteAcceleratorEnabled", &d.WriteAcceleratorEnabled) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeallocateResourceOperationResponse. +func (d DeallocateResourceOperationResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", d.Description) + populate(objectMap, "location", d.Location) + populate(objectMap, "results", d.Results) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeallocateResourceOperationResponse. +func (d *DeallocateResourceOperationResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &d.Description) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &d.Location) + delete(rawMsg, key) + case "results": + err = unpopulate(val, "Results", &d.Results) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &d.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DelayRequest. +func (d DelayRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "delay", d.Delay) + populate(objectMap, "resourceIds", d.ResourceIDs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DelayRequest. +func (d *DelayRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "delay": + err = unpopulateTime[datetime.RFC3339](val, "Delay", &d.Delay) + delete(rawMsg, key) + case "resourceIds": + err = unpopulate(val, "ResourceIDs", &d.ResourceIDs) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeleteResourceOperationResponse. +func (d DeleteResourceOperationResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", d.Description) + populate(objectMap, "location", d.Location) + populate(objectMap, "results", d.Results) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeleteResourceOperationResponse. +func (d *DeleteResourceOperationResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &d.Description) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &d.Location) + delete(rawMsg, key) + case "results": + err = unpopulate(val, "Results", &d.Results) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &d.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DiagnosticsProfile. +func (d DiagnosticsProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "bootDiagnostics", d.BootDiagnostics) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiagnosticsProfile. +func (d *DiagnosticsProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "bootDiagnostics": + err = unpopulate(val, "BootDiagnostics", &d.BootDiagnostics) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DiffDiskSettings. +func (d DiffDiskSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "option", d.Option) + populate(objectMap, "placement", d.Placement) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiffDiskSettings. +func (d *DiffDiskSettings) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "option": + err = unpopulate(val, "Option", &d.Option) + delete(rawMsg, key) + case "placement": + err = unpopulate(val, "Placement", &d.Placement) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DiskEncryptionSetParameters. +func (d DiskEncryptionSetParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", d.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiskEncryptionSetParameters. +func (d *DiskEncryptionSetParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DiskEncryptionSettings. +func (d DiskEncryptionSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "diskEncryptionKey", d.DiskEncryptionKey) + populate(objectMap, "enabled", d.Enabled) + populate(objectMap, "keyEncryptionKey", d.KeyEncryptionKey) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiskEncryptionSettings. +func (d *DiskEncryptionSettings) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "diskEncryptionKey": + err = unpopulate(val, "DiskEncryptionKey", &d.DiskEncryptionKey) + delete(rawMsg, key) + case "enabled": + err = unpopulate(val, "Enabled", &d.Enabled) + delete(rawMsg, key) + case "keyEncryptionKey": + err = unpopulate(val, "KeyEncryptionKey", &d.KeyEncryptionKey) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EncryptionIdentity. +func (e EncryptionIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "userAssignedIdentityResourceId", e.UserAssignedIdentityResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EncryptionIdentity. +func (e *EncryptionIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "userAssignedIdentityResourceId": + err = unpopulate(val, "UserAssignedIdentityResourceID", &e.UserAssignedIdentityResourceID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Error. +func (e Error) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", e.Code) + populate(objectMap, "details", e.Details) + populate(objectMap, "innererror", e.Innererror) + populate(objectMap, "message", e.Message) + populate(objectMap, "target", e.Target) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Error. +func (e *Error) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "code": + err = unpopulate(val, "Code", &e.Code) + delete(rawMsg, key) + case "details": + err = unpopulate(val, "Details", &e.Details) + delete(rawMsg, key) + case "innererror": + err = unpopulate(val, "Innererror", &e.Innererror) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &e.Message) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &e.Target) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EventGridAndResourceGraph. +func (e EventGridAndResourceGraph) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enable", e.Enable) + populate(objectMap, "scheduledEventsApiVersion", e.ScheduledEventsAPIVersion) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EventGridAndResourceGraph. +func (e *EventGridAndResourceGraph) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "enable": + err = unpopulate(val, "Enable", &e.Enable) + delete(rawMsg, key) + case "scheduledEventsApiVersion": + err = unpopulate(val, "ScheduledEventsAPIVersion", &e.ScheduledEventsAPIVersion) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExecuteCreateFlexRequest. +func (e ExecuteCreateFlexRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "correlationid", e.Correlationid) + populate(objectMap, "executionParameters", e.ExecutionParameters) + populate(objectMap, "resourceConfigParameters", e.ResourceConfigParameters) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExecuteCreateFlexRequest. +func (e *ExecuteCreateFlexRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "correlationid": + err = unpopulate(val, "Correlationid", &e.Correlationid) + delete(rawMsg, key) + case "executionParameters": + err = unpopulate(val, "ExecutionParameters", &e.ExecutionParameters) + delete(rawMsg, key) + case "resourceConfigParameters": + err = unpopulate(val, "ResourceConfigParameters", &e.ResourceConfigParameters) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExecuteCreateRequest. +func (e ExecuteCreateRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "correlationid", e.Correlationid) + populate(objectMap, "executionParameters", e.ExecutionParameters) + populate(objectMap, "resourceConfigParameters", e.ResourceConfigParameters) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExecuteCreateRequest. +func (e *ExecuteCreateRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "correlationid": + err = unpopulate(val, "Correlationid", &e.Correlationid) + delete(rawMsg, key) + case "executionParameters": + err = unpopulate(val, "ExecutionParameters", &e.ExecutionParameters) + delete(rawMsg, key) + case "resourceConfigParameters": + err = unpopulate(val, "ResourceConfigParameters", &e.ResourceConfigParameters) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExecuteDeallocateRequest. +func (e ExecuteDeallocateRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "correlationid", e.Correlationid) + populate(objectMap, "executionParameters", e.ExecutionParameters) + populate(objectMap, "resources", e.Resources) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExecuteDeallocateRequest. +func (e *ExecuteDeallocateRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "correlationid": + err = unpopulate(val, "Correlationid", &e.Correlationid) + delete(rawMsg, key) + case "executionParameters": + err = unpopulate(val, "ExecutionParameters", &e.ExecutionParameters) + delete(rawMsg, key) + case "resources": + err = unpopulate(val, "Resources", &e.Resources) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExecuteDeleteRequest. +func (e ExecuteDeleteRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "correlationid", e.Correlationid) + populate(objectMap, "executionParameters", e.ExecutionParameters) + populate(objectMap, "forceDeletion", e.ForceDeletion) + populate(objectMap, "resources", e.Resources) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExecuteDeleteRequest. +func (e *ExecuteDeleteRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "correlationid": + err = unpopulate(val, "Correlationid", &e.Correlationid) + delete(rawMsg, key) + case "executionParameters": + err = unpopulate(val, "ExecutionParameters", &e.ExecutionParameters) + delete(rawMsg, key) + case "forceDeletion": + err = unpopulate(val, "ForceDeletion", &e.ForceDeletion) + delete(rawMsg, key) + case "resources": + err = unpopulate(val, "Resources", &e.Resources) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExecuteHibernateRequest. +func (e ExecuteHibernateRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "correlationid", e.Correlationid) + populate(objectMap, "executionParameters", e.ExecutionParameters) + populate(objectMap, "resources", e.Resources) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExecuteHibernateRequest. +func (e *ExecuteHibernateRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "correlationid": + err = unpopulate(val, "Correlationid", &e.Correlationid) + delete(rawMsg, key) + case "executionParameters": + err = unpopulate(val, "ExecutionParameters", &e.ExecutionParameters) + delete(rawMsg, key) + case "resources": + err = unpopulate(val, "Resources", &e.Resources) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExecuteStartRequest. +func (e ExecuteStartRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "correlationid", e.Correlationid) + populate(objectMap, "executionParameters", e.ExecutionParameters) + populate(objectMap, "resources", e.Resources) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExecuteStartRequest. +func (e *ExecuteStartRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "correlationid": + err = unpopulate(val, "Correlationid", &e.Correlationid) + delete(rawMsg, key) + case "executionParameters": + err = unpopulate(val, "ExecutionParameters", &e.ExecutionParameters) + delete(rawMsg, key) + case "resources": + err = unpopulate(val, "Resources", &e.Resources) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExecutionParameters. +func (e ExecutionParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "optimizationPreference", e.OptimizationPreference) + populate(objectMap, "retryPolicy", e.RetryPolicy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExecutionParameters. +func (e *ExecutionParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "optimizationPreference": + err = unpopulate(val, "OptimizationPreference", &e.OptimizationPreference) + delete(rawMsg, key) + case "retryPolicy": + err = unpopulate(val, "RetryPolicy", &e.RetryPolicy) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExtendedLocation. +func (e ExtendedLocation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", e.Name) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExtendedLocation. +func (e *ExtendedLocation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &e.Name) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &e.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FallbackOperationInfo. +func (f FallbackOperationInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "error", f.Error) + populate(objectMap, "lastOpType", f.LastOpType) + populate(objectMap, "status", f.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FallbackOperationInfo. +func (f *FallbackOperationInfo) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "error": + err = unpopulate(val, "Error", &f.Error) + delete(rawMsg, key) + case "lastOpType": + err = unpopulate(val, "LastOpType", &f.LastOpType) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &f.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FlexProperties. +func (f FlexProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "osType", f.OSType) + populate(objectMap, "priorityProfile", f.PriorityProfile) + populate(objectMap, "vmSizeProfiles", f.VMSizeProfiles) + populate(objectMap, "zoneAllocationPolicy", f.ZoneAllocationPolicy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FlexProperties. +func (f *FlexProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "osType": + err = unpopulate(val, "OSType", &f.OSType) + delete(rawMsg, key) + case "priorityProfile": + err = unpopulate(val, "PriorityProfile", &f.PriorityProfile) + delete(rawMsg, key) + case "vmSizeProfiles": + err = unpopulate(val, "VMSizeProfiles", &f.VMSizeProfiles) + delete(rawMsg, key) + case "zoneAllocationPolicy": + err = unpopulate(val, "ZoneAllocationPolicy", &f.ZoneAllocationPolicy) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type GetOperationErrorsRequest. +func (g GetOperationErrorsRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "operationIds", g.OperationIDs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GetOperationErrorsRequest. +func (g *GetOperationErrorsRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "operationIds": + err = unpopulate(val, "OperationIDs", &g.OperationIDs) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type GetOperationErrorsResponse. +func (g GetOperationErrorsResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "results", g.Results) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GetOperationErrorsResponse. +func (g *GetOperationErrorsResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "results": + err = unpopulate(val, "Results", &g.Results) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type GetOperationStatusRequest. +func (g GetOperationStatusRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "correlationid", g.Correlationid) + populate(objectMap, "operationIds", g.OperationIDs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GetOperationStatusRequest. +func (g *GetOperationStatusRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "correlationid": + err = unpopulate(val, "Correlationid", &g.Correlationid) + delete(rawMsg, key) + case "operationIds": + err = unpopulate(val, "OperationIDs", &g.OperationIDs) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type GetOperationStatusResponse. +func (g GetOperationStatusResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "results", g.Results) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GetOperationStatusResponse. +func (g *GetOperationStatusResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "results": + err = unpopulate(val, "Results", &g.Results) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HardwareProfile. +func (h HardwareProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "vmSize", h.VMSize) + populate(objectMap, "vmSizeProperties", h.VMSizeProperties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HardwareProfile. +func (h *HardwareProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "vmSize": + err = unpopulate(val, "VMSize", &h.VMSize) + delete(rawMsg, key) + case "vmSizeProperties": + err = unpopulate(val, "VMSizeProperties", &h.VMSizeProperties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HibernateResourceOperationResponse. +func (h HibernateResourceOperationResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", h.Description) + populate(objectMap, "location", h.Location) + populate(objectMap, "results", h.Results) + populate(objectMap, "type", h.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HibernateResourceOperationResponse. +func (h *HibernateResourceOperationResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &h.Description) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &h.Location) + delete(rawMsg, key) + case "results": + err = unpopulate(val, "Results", &h.Results) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &h.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HostEndpointSettings. +func (h HostEndpointSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "inVMAccessControlProfileReferenceId", h.InVMAccessControlProfileReferenceID) + populate(objectMap, "mode", h.Mode) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HostEndpointSettings. +func (h *HostEndpointSettings) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "inVMAccessControlProfileReferenceId": + err = unpopulate(val, "InVMAccessControlProfileReferenceID", &h.InVMAccessControlProfileReferenceID) + delete(rawMsg, key) + case "mode": + err = unpopulate(val, "Mode", &h.Mode) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ImageReference. +func (i ImageReference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "communityGalleryImageId", i.CommunityGalleryImageID) + populate(objectMap, "id", i.ID) + populate(objectMap, "offer", i.Offer) + populate(objectMap, "publisher", i.Publisher) + populate(objectMap, "sku", i.SKU) + populate(objectMap, "sharedGalleryImageId", i.SharedGalleryImageID) + populate(objectMap, "version", i.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImageReference. +func (i *ImageReference) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "communityGalleryImageId": + err = unpopulate(val, "CommunityGalleryImageID", &i.CommunityGalleryImageID) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &i.ID) + delete(rawMsg, key) + case "offer": + err = unpopulate(val, "Offer", &i.Offer) + delete(rawMsg, key) + case "publisher": + err = unpopulate(val, "Publisher", &i.Publisher) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &i.SKU) + delete(rawMsg, key) + case "sharedGalleryImageId": + err = unpopulate(val, "SharedGalleryImageID", &i.SharedGalleryImageID) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &i.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type InnerError. +func (i InnerError) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", i.Code) + populate(objectMap, "innererror", i.Innererror) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InnerError. +func (i *InnerError) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "code": + err = unpopulate(val, "Code", &i.Code) + delete(rawMsg, key) + case "innererror": + err = unpopulate(val, "Innererror", &i.Innererror) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyVaultKeyReference. +func (k KeyVaultKeyReference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "keyUrl", k.KeyURL) + populate(objectMap, "sourceVault", k.SourceVault) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyVaultKeyReference. +func (k *KeyVaultKeyReference) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "keyUrl": + err = unpopulate(val, "KeyURL", &k.KeyURL) + delete(rawMsg, key) + case "sourceVault": + err = unpopulate(val, "SourceVault", &k.SourceVault) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyVaultSecretReference. +func (k KeyVaultSecretReference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "secretUrl", k.SecretURL) + populate(objectMap, "sourceVault", k.SourceVault) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyVaultSecretReference. +func (k *KeyVaultSecretReference) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "secretUrl": + err = unpopulate(val, "SecretURL", &k.SecretURL) + delete(rawMsg, key) + case "sourceVault": + err = unpopulate(val, "SourceVault", &k.SourceVault) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LinuxConfiguration. +func (l LinuxConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "disablePasswordAuthentication", l.DisablePasswordAuthentication) + populate(objectMap, "enableVMAgentPlatformUpdates", l.EnableVMAgentPlatformUpdates) + populate(objectMap, "patchSettings", l.PatchSettings) + populate(objectMap, "provisionVMAgent", l.ProvisionVMAgent) + populate(objectMap, "ssh", l.SSH) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LinuxConfiguration. +func (l *LinuxConfiguration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "disablePasswordAuthentication": + err = unpopulate(val, "DisablePasswordAuthentication", &l.DisablePasswordAuthentication) + delete(rawMsg, key) + case "enableVMAgentPlatformUpdates": + err = unpopulate(val, "EnableVMAgentPlatformUpdates", &l.EnableVMAgentPlatformUpdates) + delete(rawMsg, key) + case "patchSettings": + err = unpopulate(val, "PatchSettings", &l.PatchSettings) + delete(rawMsg, key) + case "provisionVMAgent": + err = unpopulate(val, "ProvisionVMAgent", &l.ProvisionVMAgent) + delete(rawMsg, key) + case "ssh": + err = unpopulate(val, "SSH", &l.SSH) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LinuxPatchSettings. +func (l LinuxPatchSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "assessmentMode", l.AssessmentMode) + populate(objectMap, "automaticByPlatformSettings", l.AutomaticByPlatformSettings) + populate(objectMap, "patchMode", l.PatchMode) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LinuxPatchSettings. +func (l *LinuxPatchSettings) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "assessmentMode": + err = unpopulate(val, "AssessmentMode", &l.AssessmentMode) + delete(rawMsg, key) + case "automaticByPlatformSettings": + err = unpopulate(val, "AutomaticByPlatformSettings", &l.AutomaticByPlatformSettings) + delete(rawMsg, key) + case "patchMode": + err = unpopulate(val, "PatchMode", &l.PatchMode) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LinuxVMGuestPatchAutomaticByPlatformSettings. +func (l LinuxVMGuestPatchAutomaticByPlatformSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "bypassPlatformSafetyChecksOnUserSchedule", l.BypassPlatformSafetyChecksOnUserSchedule) + populate(objectMap, "rebootSetting", l.RebootSetting) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LinuxVMGuestPatchAutomaticByPlatformSettings. +func (l *LinuxVMGuestPatchAutomaticByPlatformSettings) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "bypassPlatformSafetyChecksOnUserSchedule": + err = unpopulate(val, "BypassPlatformSafetyChecksOnUserSchedule", &l.BypassPlatformSafetyChecksOnUserSchedule) + delete(rawMsg, key) + case "rebootSetting": + err = unpopulate(val, "RebootSetting", &l.RebootSetting) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedDiskParameters. +func (m ManagedDiskParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "diskEncryptionSet", m.DiskEncryptionSet) + populate(objectMap, "id", m.ID) + populate(objectMap, "securityProfile", m.SecurityProfile) + populate(objectMap, "storageAccountType", m.StorageAccountType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedDiskParameters. +func (m *ManagedDiskParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "diskEncryptionSet": + err = unpopulate(val, "DiskEncryptionSet", &m.DiskEncryptionSet) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &m.ID) + delete(rawMsg, key) + case "securityProfile": + err = unpopulate(val, "SecurityProfile", &m.SecurityProfile) + delete(rawMsg, key) + case "storageAccountType": + err = unpopulate(val, "StorageAccountType", &m.StorageAccountType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkInterfaceReference. +func (n NetworkInterfaceReference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", n.ID) + populate(objectMap, "properties", n.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkInterfaceReference. +func (n *NetworkInterfaceReference) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &n.ID) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &n.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkInterfaceReferenceProperties. +func (n NetworkInterfaceReferenceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "deleteOption", n.DeleteOption) + populate(objectMap, "primary", n.Primary) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkInterfaceReferenceProperties. +func (n *NetworkInterfaceReferenceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "deleteOption": + err = unpopulate(val, "DeleteOption", &n.DeleteOption) + delete(rawMsg, key) + case "primary": + err = unpopulate(val, "Primary", &n.Primary) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkProfile. +func (n NetworkProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "networkApiVersion", n.NetworkAPIVersion) + populate(objectMap, "networkInterfaceConfigurations", n.NetworkInterfaceConfigurations) + populate(objectMap, "networkInterfaces", n.NetworkInterfaces) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkProfile. +func (n *NetworkProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "networkApiVersion": + err = unpopulate(val, "NetworkAPIVersion", &n.NetworkAPIVersion) + delete(rawMsg, key) + case "networkInterfaceConfigurations": + err = unpopulate(val, "NetworkInterfaceConfigurations", &n.NetworkInterfaceConfigurations) + delete(rawMsg, key) + case "networkInterfaces": + err = unpopulate(val, "NetworkInterfaces", &n.NetworkInterfaces) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NotificationProperties. +func (n NotificationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "destination", n.Destination) + populate(objectMap, "disabled", n.Disabled) + populate(objectMap, "language", n.Language) + populate(objectMap, "type", n.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NotificationProperties. +func (n *NotificationProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "destination": + err = unpopulate(val, "Destination", &n.Destination) + delete(rawMsg, key) + case "disabled": + err = unpopulate(val, "Disabled", &n.Disabled) + delete(rawMsg, key) + case "language": + err = unpopulate(val, "Language", &n.Language) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &n.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OSDisk. +func (o OSDisk) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "caching", o.Caching) + populate(objectMap, "createOption", o.CreateOption) + populate(objectMap, "deleteOption", o.DeleteOption) + populate(objectMap, "diffDiskSettings", o.DiffDiskSettings) + populate(objectMap, "diskSizeGB", o.DiskSizeGB) + populate(objectMap, "encryptionSettings", o.EncryptionSettings) + populate(objectMap, "image", o.Image) + populate(objectMap, "managedDisk", o.ManagedDisk) + populate(objectMap, "name", o.Name) + populate(objectMap, "osType", o.OSType) + populate(objectMap, "vhd", o.Vhd) + populate(objectMap, "writeAcceleratorEnabled", o.WriteAcceleratorEnabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OSDisk. +func (o *OSDisk) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "caching": + err = unpopulate(val, "Caching", &o.Caching) + delete(rawMsg, key) + case "createOption": + err = unpopulate(val, "CreateOption", &o.CreateOption) + delete(rawMsg, key) + case "deleteOption": + err = unpopulate(val, "DeleteOption", &o.DeleteOption) + delete(rawMsg, key) + case "diffDiskSettings": + err = unpopulate(val, "DiffDiskSettings", &o.DiffDiskSettings) + delete(rawMsg, key) + case "diskSizeGB": + err = unpopulate(val, "DiskSizeGB", &o.DiskSizeGB) + delete(rawMsg, key) + case "encryptionSettings": + err = unpopulate(val, "EncryptionSettings", &o.EncryptionSettings) + delete(rawMsg, key) + case "image": + err = unpopulate(val, "Image", &o.Image) + delete(rawMsg, key) + case "managedDisk": + err = unpopulate(val, "ManagedDisk", &o.ManagedDisk) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "osType": + err = unpopulate(val, "OSType", &o.OSType) + delete(rawMsg, key) + case "vhd": + err = unpopulate(val, "Vhd", &o.Vhd) + delete(rawMsg, key) + case "writeAcceleratorEnabled": + err = unpopulate(val, "WriteAcceleratorEnabled", &o.WriteAcceleratorEnabled) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OSImageNotificationProfile. +func (o OSImageNotificationProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enable", o.Enable) + populate(objectMap, "notBeforeTimeout", o.NotBeforeTimeout) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OSImageNotificationProfile. +func (o *OSImageNotificationProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "enable": + err = unpopulate(val, "Enable", &o.Enable) + delete(rawMsg, key) + case "notBeforeTimeout": + err = unpopulate(val, "NotBeforeTimeout", &o.NotBeforeTimeout) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OSProfile. +func (o OSProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "adminPassword", o.AdminPassword) + populate(objectMap, "adminUsername", o.AdminUsername) + populate(objectMap, "allowExtensionOperations", o.AllowExtensionOperations) + populate(objectMap, "computerName", o.ComputerName) + populate(objectMap, "customData", o.CustomData) + populate(objectMap, "linuxConfiguration", o.LinuxConfiguration) + populate(objectMap, "requireGuestProvisionSignal", o.RequireGuestProvisionSignal) + populate(objectMap, "secrets", o.Secrets) + populate(objectMap, "windowsConfiguration", o.WindowsConfiguration) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OSProfile. +func (o *OSProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "adminPassword": + err = unpopulate(val, "AdminPassword", &o.AdminPassword) + delete(rawMsg, key) + case "adminUsername": + err = unpopulate(val, "AdminUsername", &o.AdminUsername) + delete(rawMsg, key) + case "allowExtensionOperations": + err = unpopulate(val, "AllowExtensionOperations", &o.AllowExtensionOperations) + delete(rawMsg, key) + case "computerName": + err = unpopulate(val, "ComputerName", &o.ComputerName) + delete(rawMsg, key) + case "customData": + err = unpopulate(val, "CustomData", &o.CustomData) + delete(rawMsg, key) + case "linuxConfiguration": + err = unpopulate(val, "LinuxConfiguration", &o.LinuxConfiguration) + delete(rawMsg, key) + case "requireGuestProvisionSignal": + err = unpopulate(val, "RequireGuestProvisionSignal", &o.RequireGuestProvisionSignal) + delete(rawMsg, key) + case "secrets": + err = unpopulate(val, "Secrets", &o.Secrets) + delete(rawMsg, key) + case "windowsConfiguration": + err = unpopulate(val, "WindowsConfiguration", &o.WindowsConfiguration) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Occurrence. +func (o Occurrence) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", o.ID) + populate(objectMap, "name", o.Name) + populate(objectMap, "properties", o.Properties) + populate(objectMap, "systemData", o.SystemData) + populate(objectMap, "type", o.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Occurrence. +func (o *Occurrence) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &o.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &o.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &o.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &o.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OccurrenceExtensionProperties. +func (o OccurrenceExtensionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "errorDetails", o.ErrorDetails) + populate(objectMap, "notificationSettings", o.NotificationSettings) + populate(objectMap, "provisioningState", o.ProvisioningState) + populate(objectMap, "resourceId", o.ResourceID) + populate(objectMap, "scheduledActionId", o.ScheduledActionID) + populateTime[datetime.RFC3339](objectMap, "scheduledTime", o.ScheduledTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OccurrenceExtensionProperties. +func (o *OccurrenceExtensionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "errorDetails": + err = unpopulate(val, "ErrorDetails", &o.ErrorDetails) + delete(rawMsg, key) + case "notificationSettings": + err = unpopulate(val, "NotificationSettings", &o.NotificationSettings) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &o.ProvisioningState) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &o.ResourceID) + delete(rawMsg, key) + case "scheduledActionId": + err = unpopulate(val, "ScheduledActionID", &o.ScheduledActionID) + delete(rawMsg, key) + case "scheduledTime": + err = unpopulateTime[datetime.RFC3339](val, "ScheduledTime", &o.ScheduledTime) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OccurrenceExtensionResource. +func (o OccurrenceExtensionResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", o.ID) + populate(objectMap, "name", o.Name) + populate(objectMap, "properties", o.Properties) + populate(objectMap, "systemData", o.SystemData) + populate(objectMap, "type", o.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OccurrenceExtensionResource. +func (o *OccurrenceExtensionResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &o.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &o.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &o.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &o.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OccurrenceExtensionResourceListResult. +func (o OccurrenceExtensionResourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OccurrenceExtensionResourceListResult. +func (o *OccurrenceExtensionResourceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &o.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OccurrenceListResult. +func (o OccurrenceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OccurrenceListResult. +func (o *OccurrenceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &o.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OccurrenceProperties. +func (o OccurrenceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", o.ProvisioningState) + populate(objectMap, "resultSummary", o.ResultSummary) + populateTime[datetime.RFC3339](objectMap, "scheduledTime", o.ScheduledTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OccurrenceProperties. +func (o *OccurrenceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &o.ProvisioningState) + delete(rawMsg, key) + case "resultSummary": + err = unpopulate(val, "ResultSummary", &o.ResultSummary) + delete(rawMsg, key) + case "scheduledTime": + err = unpopulateTime[datetime.RFC3339](val, "ScheduledTime", &o.ScheduledTime) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OccurrenceResource. +func (o OccurrenceResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "errorDetails", o.ErrorDetails) + populate(objectMap, "id", o.ID) + populate(objectMap, "name", o.Name) + populate(objectMap, "notificationSettings", o.NotificationSettings) + populate(objectMap, "provisioningState", o.ProvisioningState) + populate(objectMap, "resourceId", o.ResourceID) + populateTime[datetime.RFC3339](objectMap, "scheduledTime", o.ScheduledTime) + populate(objectMap, "type", o.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OccurrenceResource. +func (o *OccurrenceResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "errorDetails": + err = unpopulate(val, "ErrorDetails", &o.ErrorDetails) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &o.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "notificationSettings": + err = unpopulate(val, "NotificationSettings", &o.NotificationSettings) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &o.ProvisioningState) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &o.ResourceID) + delete(rawMsg, key) + case "scheduledTime": + err = unpopulateTime[datetime.RFC3339](val, "ScheduledTime", &o.ScheduledTime) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &o.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OccurrenceResourceListResponse. +func (o OccurrenceResourceListResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OccurrenceResourceListResponse. +func (o *OccurrenceResourceListResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &o.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OccurrenceResultSummary. +func (o OccurrenceResultSummary) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "statuses", o.Statuses) + populate(objectMap, "total", o.Total) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OccurrenceResultSummary. +func (o *OccurrenceResultSummary) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "statuses": + err = unpopulate(val, "Statuses", &o.Statuses) + delete(rawMsg, key) + case "total": + err = unpopulate(val, "Total", &o.Total) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Operation. +func (o Operation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionType", o.ActionType) + populate(objectMap, "display", o.Display) + populate(objectMap, "isDataAction", o.IsDataAction) + populate(objectMap, "name", o.Name) + populate(objectMap, "origin", o.Origin) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Operation. +func (o *Operation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionType": + err = unpopulate(val, "ActionType", &o.ActionType) + delete(rawMsg, key) + case "display": + err = unpopulate(val, "Display", &o.Display) + delete(rawMsg, key) + case "isDataAction": + err = unpopulate(val, "IsDataAction", &o.IsDataAction) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "origin": + err = unpopulate(val, "Origin", &o.Origin) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationDisplay. +func (o OperationDisplay) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", o.Description) + populate(objectMap, "operation", o.Operation) + populate(objectMap, "provider", o.Provider) + populate(objectMap, "resource", o.Resource) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationDisplay. +func (o *OperationDisplay) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &o.Description) + delete(rawMsg, key) + case "operation": + err = unpopulate(val, "Operation", &o.Operation) + delete(rawMsg, key) + case "provider": + err = unpopulate(val, "Provider", &o.Provider) + delete(rawMsg, key) + case "resource": + err = unpopulate(val, "Resource", &o.Resource) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationErrorDetails. +func (o OperationErrorDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "azureOperationName", o.AzureOperationName) + populate(objectMap, "crpOperationId", o.CrpOperationID) + populate(objectMap, "errorCode", o.ErrorCode) + populate(objectMap, "errorDetails", o.ErrorDetails) + populateTime[datetime.RFC3339](objectMap, "timeStamp", o.TimeStamp) + populateTime[datetime.RFC3339](objectMap, "timestamp", o.Timestamp) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationErrorDetails. +func (o *OperationErrorDetails) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "azureOperationName": + err = unpopulate(val, "AzureOperationName", &o.AzureOperationName) + delete(rawMsg, key) + case "crpOperationId": + err = unpopulate(val, "CrpOperationID", &o.CrpOperationID) + delete(rawMsg, key) + case "errorCode": + err = unpopulate(val, "ErrorCode", &o.ErrorCode) + delete(rawMsg, key) + case "errorDetails": + err = unpopulate(val, "ErrorDetails", &o.ErrorDetails) + delete(rawMsg, key) + case "timeStamp": + err = unpopulateTime[datetime.RFC3339](val, "TimeStamp", &o.TimeStamp) + delete(rawMsg, key) + case "timestamp": + err = unpopulateTime[datetime.RFC3339](val, "Timestamp", &o.Timestamp) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationErrorsResult. +func (o OperationErrorsResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "activationTime", o.ActivationTime) + populateTime[datetime.RFC3339](objectMap, "completedAt", o.CompletedAt) + populateTime[datetime.RFC3339](objectMap, "creationTime", o.CreationTime) + populate(objectMap, "operationErrors", o.OperationErrors) + populate(objectMap, "operationId", o.OperationID) + populate(objectMap, "requestErrorCode", o.RequestErrorCode) + populate(objectMap, "requestErrorDetails", o.RequestErrorDetails) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationErrorsResult. +func (o *OperationErrorsResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "activationTime": + err = unpopulateTime[datetime.RFC3339](val, "ActivationTime", &o.ActivationTime) + delete(rawMsg, key) + case "completedAt": + err = unpopulateTime[datetime.RFC3339](val, "CompletedAt", &o.CompletedAt) + delete(rawMsg, key) + case "creationTime": + err = unpopulateTime[datetime.RFC3339](val, "CreationTime", &o.CreationTime) + delete(rawMsg, key) + case "operationErrors": + err = unpopulate(val, "OperationErrors", &o.OperationErrors) + delete(rawMsg, key) + case "operationId": + err = unpopulate(val, "OperationID", &o.OperationID) + delete(rawMsg, key) + case "requestErrorCode": + err = unpopulate(val, "RequestErrorCode", &o.RequestErrorCode) + delete(rawMsg, key) + case "requestErrorDetails": + err = unpopulate(val, "RequestErrorDetails", &o.RequestErrorDetails) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationListResult. +func (o *OperationListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &o.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PatchSettings. +func (p PatchSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "assessmentMode", p.AssessmentMode) + populate(objectMap, "automaticByPlatformSettings", p.AutomaticByPlatformSettings) + populate(objectMap, "enableHotpatching", p.EnableHotpatching) + populate(objectMap, "patchMode", p.PatchMode) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PatchSettings. +func (p *PatchSettings) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "assessmentMode": + err = unpopulate(val, "AssessmentMode", &p.AssessmentMode) + delete(rawMsg, key) + case "automaticByPlatformSettings": + err = unpopulate(val, "AutomaticByPlatformSettings", &p.AutomaticByPlatformSettings) + delete(rawMsg, key) + case "enableHotpatching": + err = unpopulate(val, "EnableHotpatching", &p.EnableHotpatching) + delete(rawMsg, key) + case "patchMode": + err = unpopulate(val, "PatchMode", &p.PatchMode) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Placement. +func (p Placement) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "excludeZones", p.ExcludeZones) + populate(objectMap, "includeZones", p.IncludeZones) + populate(objectMap, "zonePlacementPolicy", p.ZonePlacementPolicy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Placement. +func (p *Placement) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "excludeZones": + err = unpopulate(val, "ExcludeZones", &p.ExcludeZones) + delete(rawMsg, key) + case "includeZones": + err = unpopulate(val, "IncludeZones", &p.IncludeZones) + delete(rawMsg, key) + case "zonePlacementPolicy": + err = unpopulate(val, "ZonePlacementPolicy", &p.ZonePlacementPolicy) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Plan. +func (p Plan) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", p.Name) + populate(objectMap, "product", p.Product) + populate(objectMap, "promotionCode", p.PromotionCode) + populate(objectMap, "publisher", p.Publisher) + populate(objectMap, "version", p.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Plan. +func (p *Plan) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "product": + err = unpopulate(val, "Product", &p.Product) + delete(rawMsg, key) + case "promotionCode": + err = unpopulate(val, "PromotionCode", &p.PromotionCode) + delete(rawMsg, key) + case "publisher": + err = unpopulate(val, "Publisher", &p.Publisher) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &p.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PriorityProfile. +func (p PriorityProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allocationStrategy", p.AllocationStrategy) + populate(objectMap, "type", p.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PriorityProfile. +func (p *PriorityProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "allocationStrategy": + err = unpopulate(val, "AllocationStrategy", &p.AllocationStrategy) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &p.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ProxyAgentSettings. +func (p ProxyAgentSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addProxyAgentExtension", p.AddProxyAgentExtension) + populate(objectMap, "enabled", p.Enabled) + populate(objectMap, "imds", p.Imds) + populate(objectMap, "keyIncarnationId", p.KeyIncarnationID) + populate(objectMap, "mode", p.Mode) + populate(objectMap, "wireServer", p.WireServer) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ProxyAgentSettings. +func (p *ProxyAgentSettings) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "addProxyAgentExtension": + err = unpopulate(val, "AddProxyAgentExtension", &p.AddProxyAgentExtension) + delete(rawMsg, key) + case "enabled": + err = unpopulate(val, "Enabled", &p.Enabled) + delete(rawMsg, key) + case "imds": + err = unpopulate(val, "Imds", &p.Imds) + delete(rawMsg, key) + case "keyIncarnationId": + err = unpopulate(val, "KeyIncarnationID", &p.KeyIncarnationID) + delete(rawMsg, key) + case "mode": + err = unpopulate(val, "Mode", &p.Mode) + delete(rawMsg, key) + case "wireServer": + err = unpopulate(val, "WireServer", &p.WireServer) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PublicIPAddressSKU. +func (p PublicIPAddressSKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", p.Name) + populate(objectMap, "tier", p.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PublicIPAddressSKU. +func (p *PublicIPAddressSKU) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &p.Tier) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RecurringActionsResourceOperationResult. +func (r RecurringActionsResourceOperationResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "resourcesStatuses", r.ResourcesStatuses) + populate(objectMap, "totalResources", r.TotalResources) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RecurringActionsResourceOperationResult. +func (r *RecurringActionsResourceOperationResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "resourcesStatuses": + err = unpopulate(val, "ResourcesStatuses", &r.ResourcesStatuses) + delete(rawMsg, key) + case "totalResources": + err = unpopulate(val, "TotalResources", &r.TotalResources) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceAttachRequest. +func (r ResourceAttachRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "resources", r.Resources) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceAttachRequest. +func (r *ResourceAttachRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "resources": + err = unpopulate(val, "Resources", &r.Resources) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceDetachRequest. +func (r ResourceDetachRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "resources", r.Resources) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceDetachRequest. +func (r *ResourceDetachRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "resources": + err = unpopulate(val, "Resources", &r.Resources) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceListResponse. +func (r ResourceListResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", r.NextLink) + populate(objectMap, "value", r.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceListResponse. +func (r *ResourceListResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &r.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &r.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceOperation. +func (r ResourceOperation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "errorCode", r.ErrorCode) + populate(objectMap, "errorDetails", r.ErrorDetails) + populate(objectMap, "operation", r.Operation) + populate(objectMap, "resourceId", r.ResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceOperation. +func (r *ResourceOperation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "errorCode": + err = unpopulate(val, "ErrorCode", &r.ErrorCode) + delete(rawMsg, key) + case "errorDetails": + err = unpopulate(val, "ErrorDetails", &r.ErrorDetails) + delete(rawMsg, key) + case "operation": + err = unpopulate(val, "Operation", &r.Operation) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &r.ResourceID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceOperationDetails. +func (r ResourceOperationDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "completedAt", r.CompletedAt) + populateTime[datetime.RFC3339](objectMap, "deadline", r.Deadline) + populate(objectMap, "deadlineType", r.DeadlineType) + populate(objectMap, "fallbackOperationInfo", r.FallbackOperationInfo) + populate(objectMap, "opType", r.OpType) + populate(objectMap, "operationId", r.OperationID) + populate(objectMap, "resourceId", r.ResourceID) + populate(objectMap, "resourceOperationError", r.ResourceOperationError) + populate(objectMap, "retryPolicy", r.RetryPolicy) + populate(objectMap, "state", r.State) + populate(objectMap, "subscriptionId", r.SubscriptionID) + populate(objectMap, "timeZone", r.TimeZone) + populate(objectMap, "timezone", r.Timezone) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceOperationDetails. +func (r *ResourceOperationDetails) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "completedAt": + err = unpopulateTime[datetime.RFC3339](val, "CompletedAt", &r.CompletedAt) + delete(rawMsg, key) + case "deadline": + err = unpopulateTime[datetime.RFC3339](val, "Deadline", &r.Deadline) + delete(rawMsg, key) + case "deadlineType": + err = unpopulate(val, "DeadlineType", &r.DeadlineType) + delete(rawMsg, key) + case "fallbackOperationInfo": + err = unpopulate(val, "FallbackOperationInfo", &r.FallbackOperationInfo) + delete(rawMsg, key) + case "opType": + err = unpopulate(val, "OpType", &r.OpType) + delete(rawMsg, key) + case "operationId": + err = unpopulate(val, "OperationID", &r.OperationID) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &r.ResourceID) + delete(rawMsg, key) + case "resourceOperationError": + err = unpopulate(val, "ResourceOperationError", &r.ResourceOperationError) + delete(rawMsg, key) + case "retryPolicy": + err = unpopulate(val, "RetryPolicy", &r.RetryPolicy) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &r.State) + delete(rawMsg, key) + case "subscriptionId": + err = unpopulate(val, "SubscriptionID", &r.SubscriptionID) + delete(rawMsg, key) + case "timeZone": + err = unpopulate(val, "TimeZone", &r.TimeZone) + delete(rawMsg, key) + case "timezone": + err = unpopulate(val, "Timezone", &r.Timezone) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceOperationError. +func (r ResourceOperationError) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "errorCode", r.ErrorCode) + populate(objectMap, "errorDetails", r.ErrorDetails) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceOperationError. +func (r *ResourceOperationError) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "errorCode": + err = unpopulate(val, "ErrorCode", &r.ErrorCode) + delete(rawMsg, key) + case "errorDetails": + err = unpopulate(val, "ErrorDetails", &r.ErrorDetails) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourcePatchRequest. +func (r ResourcePatchRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "resources", r.Resources) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourcePatchRequest. +func (r *ResourcePatchRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "resources": + err = unpopulate(val, "Resources", &r.Resources) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceProvisionFlexPayload. +func (r ResourceProvisionFlexPayload) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "flexProperties", r.FlexProperties) + populate(objectMap, "resourceCount", r.ResourceCount) + populate(objectMap, "resourcePrefix", r.ResourcePrefix) + populate(objectMap, "virtualMachineBaseProfile", r.VirtualMachineBaseProfile) + populate(objectMap, "virtualMachineOverrides", r.VirtualMachineOverrides) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceProvisionFlexPayload. +func (r *ResourceProvisionFlexPayload) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "flexProperties": + err = unpopulate(val, "FlexProperties", &r.FlexProperties) + delete(rawMsg, key) + case "resourceCount": + err = unpopulate(val, "ResourceCount", &r.ResourceCount) + delete(rawMsg, key) + case "resourcePrefix": + err = unpopulate(val, "ResourcePrefix", &r.ResourcePrefix) + delete(rawMsg, key) + case "virtualMachineBaseProfile": + err = unpopulate(val, "VirtualMachineBaseProfile", &r.VirtualMachineBaseProfile) + delete(rawMsg, key) + case "virtualMachineOverrides": + err = unpopulate(val, "VirtualMachineOverrides", &r.VirtualMachineOverrides) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceProvisionPayload. +func (r ResourceProvisionPayload) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "resourceCount", r.ResourceCount) + populate(objectMap, "resourcePrefix", r.ResourcePrefix) + populate(objectMap, "virtualMachineBaseProfile", r.VirtualMachineBaseProfile) + populate(objectMap, "virtualMachineOverrides", r.VirtualMachineOverrides) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceProvisionPayload. +func (r *ResourceProvisionPayload) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "resourceCount": + err = unpopulate(val, "ResourceCount", &r.ResourceCount) + delete(rawMsg, key) + case "resourcePrefix": + err = unpopulate(val, "ResourcePrefix", &r.ResourcePrefix) + delete(rawMsg, key) + case "virtualMachineBaseProfile": + err = unpopulate(val, "VirtualMachineBaseProfile", &r.VirtualMachineBaseProfile) + delete(rawMsg, key) + case "virtualMachineOverrides": + err = unpopulate(val, "VirtualMachineOverrides", &r.VirtualMachineOverrides) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceResultSummary. +func (r ResourceResultSummary) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", r.Code) + populate(objectMap, "count", r.Count) + populate(objectMap, "errorDetails", r.ErrorDetails) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceResultSummary. +func (r *ResourceResultSummary) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "code": + err = unpopulate(val, "Code", &r.Code) + delete(rawMsg, key) + case "count": + err = unpopulate(val, "Count", &r.Count) + delete(rawMsg, key) + case "errorDetails": + err = unpopulate(val, "ErrorDetails", &r.ErrorDetails) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceStatus. +func (r ResourceStatus) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "error", r.Error) + populate(objectMap, "resourceId", r.ResourceID) + populate(objectMap, "status", r.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceStatus. +func (r *ResourceStatus) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "error": + err = unpopulate(val, "Error", &r.Error) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &r.ResourceID) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &r.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Resources. +func (r Resources) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ids", r.IDs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Resources. +func (r *Resources) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "ids": + err = unpopulate(val, "IDs", &r.IDs) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RetryPolicy. +func (r RetryPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "onFailureAction", r.OnFailureAction) + populate(objectMap, "retryCount", r.RetryCount) + populate(objectMap, "retryWindowInMinutes", r.RetryWindowInMinutes) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RetryPolicy. +func (r *RetryPolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "onFailureAction": + err = unpopulate(val, "OnFailureAction", &r.OnFailureAction) + delete(rawMsg, key) + case "retryCount": + err = unpopulate(val, "RetryCount", &r.RetryCount) + delete(rawMsg, key) + case "retryWindowInMinutes": + err = unpopulate(val, "RetryWindowInMinutes", &r.RetryWindowInMinutes) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SSHConfiguration. +func (s SSHConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "publicKeys", s.PublicKeys) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SSHConfiguration. +func (s *SSHConfiguration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "publicKeys": + err = unpopulate(val, "PublicKeys", &s.PublicKeys) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SSHPublicKey. +func (s SSHPublicKey) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "keyData", s.KeyData) + populate(objectMap, "path", s.Path) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SSHPublicKey. +func (s *SSHPublicKey) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "keyData": + err = unpopulate(val, "KeyData", &s.KeyData) + delete(rawMsg, key) + case "path": + err = unpopulate(val, "Path", &s.Path) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Schedule. +func (s Schedule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "deadLine", s.DeadLine) + populateTime[datetime.RFC3339](objectMap, "deadline", s.Deadline) + populate(objectMap, "deadlineType", s.DeadlineType) + populate(objectMap, "timeZone", s.TimeZone) + populate(objectMap, "timezone", s.Timezone) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Schedule. +func (s *Schedule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "deadLine": + err = unpopulateTime[datetime.RFC3339](val, "DeadLine", &s.DeadLine) + delete(rawMsg, key) + case "deadline": + err = unpopulateTime[datetime.RFC3339](val, "Deadline", &s.Deadline) + delete(rawMsg, key) + case "deadlineType": + err = unpopulate(val, "DeadlineType", &s.DeadlineType) + delete(rawMsg, key) + case "timeZone": + err = unpopulate(val, "TimeZone", &s.TimeZone) + delete(rawMsg, key) + case "timezone": + err = unpopulate(val, "Timezone", &s.Timezone) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ScheduledAction. +func (s ScheduledAction) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + populate(objectMap, "location", s.Location) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "systemData", s.SystemData) + populate(objectMap, "tags", s.Tags) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScheduledAction. +func (s *ScheduledAction) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &s.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &s.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &s.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ScheduledActionListResult. +func (s ScheduledActionListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScheduledActionListResult. +func (s *ScheduledActionListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &s.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ScheduledActionProperties. +func (s ScheduledActionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionType", s.ActionType) + populate(objectMap, "disabled", s.Disabled) + populateTime[datetime.RFC3339](objectMap, "endTime", s.EndTime) + populate(objectMap, "notificationSettings", s.NotificationSettings) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "resourceType", s.ResourceType) + populate(objectMap, "schedule", s.Schedule) + populateTime[datetime.RFC3339](objectMap, "startTime", s.StartTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScheduledActionProperties. +func (s *ScheduledActionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionType": + err = unpopulate(val, "ActionType", &s.ActionType) + delete(rawMsg, key) + case "disabled": + err = unpopulate(val, "Disabled", &s.Disabled) + delete(rawMsg, key) + case "endTime": + err = unpopulateTime[datetime.RFC3339](val, "EndTime", &s.EndTime) + delete(rawMsg, key) + case "notificationSettings": + err = unpopulate(val, "NotificationSettings", &s.NotificationSettings) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + case "resourceType": + err = unpopulate(val, "ResourceType", &s.ResourceType) + delete(rawMsg, key) + case "schedule": + err = unpopulate(val, "Schedule", &s.Schedule) + delete(rawMsg, key) + case "startTime": + err = unpopulateTime[datetime.RFC3339](val, "StartTime", &s.StartTime) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ScheduledActionResource. +func (s ScheduledActionResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + populate(objectMap, "name", s.Name) + populate(objectMap, "notificationSettings", s.NotificationSettings) + populate(objectMap, "resourceId", s.ResourceID) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScheduledActionResource. +func (s *ScheduledActionResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "notificationSettings": + err = unpopulate(val, "NotificationSettings", &s.NotificationSettings) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &s.ResourceID) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ScheduledActionResources. +func (s ScheduledActionResources) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "systemData", s.SystemData) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScheduledActionResources. +func (s *ScheduledActionResources) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &s.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ScheduledActionResourcesListResult. +func (s ScheduledActionResourcesListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScheduledActionResourcesListResult. +func (s *ScheduledActionResourcesListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &s.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ScheduledActionUpdate. +func (s ScheduledActionUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "tags", s.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScheduledActionUpdate. +func (s *ScheduledActionUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &s.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ScheduledActionUpdateProperties. +func (s ScheduledActionUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionType", s.ActionType) + populate(objectMap, "disabled", s.Disabled) + populateTime[datetime.RFC3339](objectMap, "endTime", s.EndTime) + populate(objectMap, "notificationSettings", s.NotificationSettings) + populate(objectMap, "resourceType", s.ResourceType) + populate(objectMap, "schedule", s.Schedule) + populateTime[datetime.RFC3339](objectMap, "startTime", s.StartTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScheduledActionUpdateProperties. +func (s *ScheduledActionUpdateProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionType": + err = unpopulate(val, "ActionType", &s.ActionType) + delete(rawMsg, key) + case "disabled": + err = unpopulate(val, "Disabled", &s.Disabled) + delete(rawMsg, key) + case "endTime": + err = unpopulateTime[datetime.RFC3339](val, "EndTime", &s.EndTime) + delete(rawMsg, key) + case "notificationSettings": + err = unpopulate(val, "NotificationSettings", &s.NotificationSettings) + delete(rawMsg, key) + case "resourceType": + err = unpopulate(val, "ResourceType", &s.ResourceType) + delete(rawMsg, key) + case "schedule": + err = unpopulate(val, "Schedule", &s.Schedule) + delete(rawMsg, key) + case "startTime": + err = unpopulateTime[datetime.RFC3339](val, "StartTime", &s.StartTime) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ScheduledActionsExtensionProperties. +func (s ScheduledActionsExtensionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionType", s.ActionType) + populate(objectMap, "disabled", s.Disabled) + populateTime[datetime.RFC3339](objectMap, "endTime", s.EndTime) + populate(objectMap, "notificationSettings", s.NotificationSettings) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "resourceNotificationSettings", s.ResourceNotificationSettings) + populate(objectMap, "resourceType", s.ResourceType) + populate(objectMap, "schedule", s.Schedule) + populateTime[datetime.RFC3339](objectMap, "startTime", s.StartTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScheduledActionsExtensionProperties. +func (s *ScheduledActionsExtensionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionType": + err = unpopulate(val, "ActionType", &s.ActionType) + delete(rawMsg, key) + case "disabled": + err = unpopulate(val, "Disabled", &s.Disabled) + delete(rawMsg, key) + case "endTime": + err = unpopulateTime[datetime.RFC3339](val, "EndTime", &s.EndTime) + delete(rawMsg, key) + case "notificationSettings": + err = unpopulate(val, "NotificationSettings", &s.NotificationSettings) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + case "resourceNotificationSettings": + err = unpopulate(val, "ResourceNotificationSettings", &s.ResourceNotificationSettings) + delete(rawMsg, key) + case "resourceType": + err = unpopulate(val, "ResourceType", &s.ResourceType) + delete(rawMsg, key) + case "schedule": + err = unpopulate(val, "Schedule", &s.Schedule) + delete(rawMsg, key) + case "startTime": + err = unpopulateTime[datetime.RFC3339](val, "StartTime", &s.StartTime) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ScheduledActionsSchedule. +func (s ScheduledActionsSchedule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "deadlineType", s.DeadlineType) + populate(objectMap, "executionParameters", s.ExecutionParameters) + populate(objectMap, "requestedDaysOfTheMonth", s.RequestedDaysOfTheMonth) + populate(objectMap, "requestedMonths", s.RequestedMonths) + populate(objectMap, "requestedWeekDays", s.RequestedWeekDays) + populateTime[datetime.PlainTime](objectMap, "scheduledTime", s.ScheduledTime) + populate(objectMap, "timeZone", s.TimeZone) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScheduledActionsSchedule. +func (s *ScheduledActionsSchedule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "deadlineType": + err = unpopulate(val, "DeadlineType", &s.DeadlineType) + delete(rawMsg, key) + case "executionParameters": + err = unpopulate(val, "ExecutionParameters", &s.ExecutionParameters) + delete(rawMsg, key) + case "requestedDaysOfTheMonth": + err = unpopulate(val, "RequestedDaysOfTheMonth", &s.RequestedDaysOfTheMonth) + delete(rawMsg, key) + case "requestedMonths": + err = unpopulate(val, "RequestedMonths", &s.RequestedMonths) + delete(rawMsg, key) + case "requestedWeekDays": + err = unpopulate(val, "RequestedWeekDays", &s.RequestedWeekDays) + delete(rawMsg, key) + case "scheduledTime": + err = unpopulateTime[datetime.PlainTime](val, "ScheduledTime", &s.ScheduledTime) + delete(rawMsg, key) + case "timeZone": + err = unpopulate(val, "TimeZone", &s.TimeZone) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ScheduledEventsAdditionalPublishingTargets. +func (s ScheduledEventsAdditionalPublishingTargets) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "eventGridAndResourceGraph", s.EventGridAndResourceGraph) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScheduledEventsAdditionalPublishingTargets. +func (s *ScheduledEventsAdditionalPublishingTargets) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "eventGridAndResourceGraph": + err = unpopulate(val, "EventGridAndResourceGraph", &s.EventGridAndResourceGraph) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ScheduledEventsPolicy. +func (s ScheduledEventsPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allInstancesDown", s.AllInstancesDown) + populate(objectMap, "scheduledEventsAdditionalPublishingTargets", s.ScheduledEventsAdditionalPublishingTargets) + populate(objectMap, "userInitiatedReboot", s.UserInitiatedReboot) + populate(objectMap, "userInitiatedRedeploy", s.UserInitiatedRedeploy) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScheduledEventsPolicy. +func (s *ScheduledEventsPolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "allInstancesDown": + err = unpopulate(val, "AllInstancesDown", &s.AllInstancesDown) + delete(rawMsg, key) + case "scheduledEventsAdditionalPublishingTargets": + err = unpopulate(val, "ScheduledEventsAdditionalPublishingTargets", &s.ScheduledEventsAdditionalPublishingTargets) + delete(rawMsg, key) + case "userInitiatedReboot": + err = unpopulate(val, "UserInitiatedReboot", &s.UserInitiatedReboot) + delete(rawMsg, key) + case "userInitiatedRedeploy": + err = unpopulate(val, "UserInitiatedRedeploy", &s.UserInitiatedRedeploy) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ScheduledEventsProfile. +func (s ScheduledEventsProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "osImageNotificationProfile", s.OSImageNotificationProfile) + populate(objectMap, "terminateNotificationProfile", s.TerminateNotificationProfile) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScheduledEventsProfile. +func (s *ScheduledEventsProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "osImageNotificationProfile": + err = unpopulate(val, "OSImageNotificationProfile", &s.OSImageNotificationProfile) + delete(rawMsg, key) + case "terminateNotificationProfile": + err = unpopulate(val, "TerminateNotificationProfile", &s.TerminateNotificationProfile) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SecurityProfile. +func (s SecurityProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "encryptionAtHost", s.EncryptionAtHost) + populate(objectMap, "encryptionIdentity", s.EncryptionIdentity) + populate(objectMap, "proxyAgentSettings", s.ProxyAgentSettings) + populate(objectMap, "securityType", s.SecurityType) + populate(objectMap, "uefiSettings", s.UefiSettings) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecurityProfile. +func (s *SecurityProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "encryptionAtHost": + err = unpopulate(val, "EncryptionAtHost", &s.EncryptionAtHost) + delete(rawMsg, key) + case "encryptionIdentity": + err = unpopulate(val, "EncryptionIdentity", &s.EncryptionIdentity) + delete(rawMsg, key) + case "proxyAgentSettings": + err = unpopulate(val, "ProxyAgentSettings", &s.ProxyAgentSettings) + delete(rawMsg, key) + case "securityType": + err = unpopulate(val, "SecurityType", &s.SecurityType) + delete(rawMsg, key) + case "uefiSettings": + err = unpopulate(val, "UefiSettings", &s.UefiSettings) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type StartResourceOperationResponse. +func (s StartResourceOperationResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", s.Description) + populate(objectMap, "location", s.Location) + populate(objectMap, "results", s.Results) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StartResourceOperationResponse. +func (s *StartResourceOperationResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &s.Description) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &s.Location) + delete(rawMsg, key) + case "results": + err = unpopulate(val, "Results", &s.Results) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type StorageProfile. +func (s StorageProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dataDisks", s.DataDisks) + populate(objectMap, "diskControllerType", s.DiskControllerType) + populate(objectMap, "imageReference", s.ImageReference) + populate(objectMap, "osDisk", s.OSDisk) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StorageProfile. +func (s *StorageProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "dataDisks": + err = unpopulate(val, "DataDisks", &s.DataDisks) + delete(rawMsg, key) + case "diskControllerType": + err = unpopulate(val, "DiskControllerType", &s.DiskControllerType) + delete(rawMsg, key) + case "imageReference": + err = unpopulate(val, "ImageReference", &s.ImageReference) + delete(rawMsg, key) + case "osDisk": + err = unpopulate(val, "OSDisk", &s.OSDisk) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SubResource. +func (s SubResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SubResource. +func (s *SubResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SubmitDeallocateRequest. +func (s SubmitDeallocateRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "correlationid", s.Correlationid) + populate(objectMap, "executionParameters", s.ExecutionParameters) + populate(objectMap, "resources", s.Resources) + populate(objectMap, "schedule", s.Schedule) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SubmitDeallocateRequest. +func (s *SubmitDeallocateRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "correlationid": + err = unpopulate(val, "Correlationid", &s.Correlationid) + delete(rawMsg, key) + case "executionParameters": + err = unpopulate(val, "ExecutionParameters", &s.ExecutionParameters) + delete(rawMsg, key) + case "resources": + err = unpopulate(val, "Resources", &s.Resources) + delete(rawMsg, key) + case "schedule": + err = unpopulate(val, "Schedule", &s.Schedule) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SubmitHibernateRequest. +func (s SubmitHibernateRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "correlationid", s.Correlationid) + populate(objectMap, "executionParameters", s.ExecutionParameters) + populate(objectMap, "resources", s.Resources) + populate(objectMap, "schedule", s.Schedule) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SubmitHibernateRequest. +func (s *SubmitHibernateRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "correlationid": + err = unpopulate(val, "Correlationid", &s.Correlationid) + delete(rawMsg, key) + case "executionParameters": + err = unpopulate(val, "ExecutionParameters", &s.ExecutionParameters) + delete(rawMsg, key) + case "resources": + err = unpopulate(val, "Resources", &s.Resources) + delete(rawMsg, key) + case "schedule": + err = unpopulate(val, "Schedule", &s.Schedule) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SubmitStartRequest. +func (s SubmitStartRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "correlationid", s.Correlationid) + populate(objectMap, "executionParameters", s.ExecutionParameters) + populate(objectMap, "resources", s.Resources) + populate(objectMap, "schedule", s.Schedule) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SubmitStartRequest. +func (s *SubmitStartRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "correlationid": + err = unpopulate(val, "Correlationid", &s.Correlationid) + delete(rawMsg, key) + case "executionParameters": + err = unpopulate(val, "ExecutionParameters", &s.ExecutionParameters) + delete(rawMsg, key) + case "resources": + err = unpopulate(val, "Resources", &s.Resources) + delete(rawMsg, key) + case "schedule": + err = unpopulate(val, "Schedule", &s.Schedule) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateTime[datetime.RFC3339](objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateTime[datetime.RFC3339](val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateTime[datetime.RFC3339](val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TerminateNotificationProfile. +func (t TerminateNotificationProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enable", t.Enable) + populate(objectMap, "notBeforeTimeout", t.NotBeforeTimeout) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TerminateNotificationProfile. +func (t *TerminateNotificationProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "enable": + err = unpopulate(val, "Enable", &t.Enable) + delete(rawMsg, key) + case "notBeforeTimeout": + err = unpopulate(val, "NotBeforeTimeout", &t.NotBeforeTimeout) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UefiSettings. +func (u UefiSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "secureBootEnabled", u.SecureBootEnabled) + populate(objectMap, "vTpmEnabled", u.VTpmEnabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UefiSettings. +func (u *UefiSettings) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "secureBootEnabled": + err = unpopulate(val, "SecureBootEnabled", &u.SecureBootEnabled) + delete(rawMsg, key) + case "vTpmEnabled": + err = unpopulate(val, "VTpmEnabled", &u.VTpmEnabled) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserAssignedIdentitiesValue. +func (u UserAssignedIdentitiesValue) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clientId", u.ClientID) + populate(objectMap, "principalId", u.PrincipalID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserAssignedIdentitiesValue. +func (u *UserAssignedIdentitiesValue) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "clientId": + err = unpopulate(val, "ClientID", &u.ClientID) + delete(rawMsg, key) + case "principalId": + err = unpopulate(val, "PrincipalID", &u.PrincipalID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserInitiatedReboot. +func (u UserInitiatedReboot) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "automaticallyApprove", u.AutomaticallyApprove) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserInitiatedReboot. +func (u *UserInitiatedReboot) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "automaticallyApprove": + err = unpopulate(val, "AutomaticallyApprove", &u.AutomaticallyApprove) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserInitiatedRedeploy. +func (u UserInitiatedRedeploy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "automaticallyApprove", u.AutomaticallyApprove) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserInitiatedRedeploy. +func (u *UserInitiatedRedeploy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "automaticallyApprove": + err = unpopulate(val, "AutomaticallyApprove", &u.AutomaticallyApprove) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VMDiskSecurityProfile. +func (v VMDiskSecurityProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "diskEncryptionSet", v.DiskEncryptionSet) + populate(objectMap, "securityEncryptionType", v.SecurityEncryptionType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VMDiskSecurityProfile. +func (v *VMDiskSecurityProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "diskEncryptionSet": + err = unpopulate(val, "DiskEncryptionSet", &v.DiskEncryptionSet) + delete(rawMsg, key) + case "securityEncryptionType": + err = unpopulate(val, "SecurityEncryptionType", &v.SecurityEncryptionType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VMGalleryApplication. +func (v VMGalleryApplication) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "configurationReference", v.ConfigurationReference) + populate(objectMap, "enableAutomaticUpgrade", v.EnableAutomaticUpgrade) + populate(objectMap, "order", v.Order) + populate(objectMap, "packageReferenceId", v.PackageReferenceID) + populate(objectMap, "tags", v.Tags) + populate(objectMap, "treatFailureAsDeploymentFailure", v.TreatFailureAsDeploymentFailure) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VMGalleryApplication. +func (v *VMGalleryApplication) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "configurationReference": + err = unpopulate(val, "ConfigurationReference", &v.ConfigurationReference) + delete(rawMsg, key) + case "enableAutomaticUpgrade": + err = unpopulate(val, "EnableAutomaticUpgrade", &v.EnableAutomaticUpgrade) + delete(rawMsg, key) + case "order": + err = unpopulate(val, "Order", &v.Order) + delete(rawMsg, key) + case "packageReferenceId": + err = unpopulate(val, "PackageReferenceID", &v.PackageReferenceID) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &v.Tags) + delete(rawMsg, key) + case "treatFailureAsDeploymentFailure": + err = unpopulate(val, "TreatFailureAsDeploymentFailure", &v.TreatFailureAsDeploymentFailure) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VMSizeProfile. +func (v VMSizeProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", v.Name) + populate(objectMap, "rank", v.Rank) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VMSizeProfile. +func (v *VMSizeProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &v.Name) + delete(rawMsg, key) + case "rank": + err = unpopulate(val, "Rank", &v.Rank) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VMSizeProperties. +func (v VMSizeProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "vCpusAvailable", v.VCpusAvailable) + populate(objectMap, "vCpusPerCore", v.VCpusPerCore) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VMSizeProperties. +func (v *VMSizeProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "vCpusAvailable": + err = unpopulate(val, "VCpusAvailable", &v.VCpusAvailable) + delete(rawMsg, key) + case "vCpusPerCore": + err = unpopulate(val, "VCpusPerCore", &v.VCpusPerCore) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VaultCertificate. +func (v VaultCertificate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "certificateStore", v.CertificateStore) + populate(objectMap, "certificateUrl", v.CertificateURL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VaultCertificate. +func (v *VaultCertificate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "certificateStore": + err = unpopulate(val, "CertificateStore", &v.CertificateStore) + delete(rawMsg, key) + case "certificateUrl": + err = unpopulate(val, "CertificateURL", &v.CertificateURL) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VaultSecretGroup. +func (v VaultSecretGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "sourceVault", v.SourceVault) + populate(objectMap, "vaultCertificates", v.VaultCertificates) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VaultSecretGroup. +func (v *VaultSecretGroup) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "sourceVault": + err = unpopulate(val, "SourceVault", &v.SourceVault) + delete(rawMsg, key) + case "vaultCertificates": + err = unpopulate(val, "VaultCertificates", &v.VaultCertificates) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualHardDisk. +func (v VirtualHardDisk) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "uri", v.URI) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualHardDisk. +func (v *VirtualHardDisk) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "uri": + err = unpopulate(val, "URI", &v.URI) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualMachineIPTag. +func (v VirtualMachineIPTag) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ipTagType", v.IPTagType) + populate(objectMap, "tag", v.Tag) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineIPTag. +func (v *VirtualMachineIPTag) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "ipTagType": + err = unpopulate(val, "IPTagType", &v.IPTagType) + delete(rawMsg, key) + case "tag": + err = unpopulate(val, "Tag", &v.Tag) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualMachineIdentity. +func (v VirtualMachineIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "principalId", v.PrincipalID) + populate(objectMap, "tenantId", v.TenantID) + populate(objectMap, "type", v.Type) + populate(objectMap, "userAssignedIdentities", v.UserAssignedIdentities) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineIdentity. +func (v *VirtualMachineIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "principalId": + err = unpopulate(val, "PrincipalID", &v.PrincipalID) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &v.TenantID) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &v.Type) + delete(rawMsg, key) + case "userAssignedIdentities": + err = unpopulate(val, "UserAssignedIdentities", &v.UserAssignedIdentities) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualMachineNetworkInterfaceConfiguration. +func (v VirtualMachineNetworkInterfaceConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "tags", v.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineNetworkInterfaceConfiguration. +func (v *VirtualMachineNetworkInterfaceConfiguration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &v.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &v.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &v.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualMachineNetworkInterfaceConfigurationProperties. +func (v VirtualMachineNetworkInterfaceConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "auxiliaryMode", v.AuxiliaryMode) + populate(objectMap, "auxiliarySku", v.AuxiliarySKU) + populate(objectMap, "dnsSettings", v.DNSSettings) + populate(objectMap, "deleteOption", v.DeleteOption) + populate(objectMap, "disableTcpStateTracking", v.DisableTCPStateTracking) + populate(objectMap, "dscpConfiguration", v.DscpConfiguration) + populate(objectMap, "enableAcceleratedNetworking", v.EnableAcceleratedNetworking) + populate(objectMap, "enableFpga", v.EnableFpga) + populate(objectMap, "enableIPForwarding", v.EnableIPForwarding) + populate(objectMap, "ipConfigurations", v.IPConfigurations) + populate(objectMap, "networkSecurityGroup", v.NetworkSecurityGroup) + populate(objectMap, "primary", v.Primary) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineNetworkInterfaceConfigurationProperties. +func (v *VirtualMachineNetworkInterfaceConfigurationProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "auxiliaryMode": + err = unpopulate(val, "AuxiliaryMode", &v.AuxiliaryMode) + delete(rawMsg, key) + case "auxiliarySku": + err = unpopulate(val, "AuxiliarySKU", &v.AuxiliarySKU) + delete(rawMsg, key) + case "dnsSettings": + err = unpopulate(val, "DNSSettings", &v.DNSSettings) + delete(rawMsg, key) + case "deleteOption": + err = unpopulate(val, "DeleteOption", &v.DeleteOption) + delete(rawMsg, key) + case "disableTcpStateTracking": + err = unpopulate(val, "DisableTCPStateTracking", &v.DisableTCPStateTracking) + delete(rawMsg, key) + case "dscpConfiguration": + err = unpopulate(val, "DscpConfiguration", &v.DscpConfiguration) + delete(rawMsg, key) + case "enableAcceleratedNetworking": + err = unpopulate(val, "EnableAcceleratedNetworking", &v.EnableAcceleratedNetworking) + delete(rawMsg, key) + case "enableFpga": + err = unpopulate(val, "EnableFpga", &v.EnableFpga) + delete(rawMsg, key) + case "enableIPForwarding": + err = unpopulate(val, "EnableIPForwarding", &v.EnableIPForwarding) + delete(rawMsg, key) + case "ipConfigurations": + err = unpopulate(val, "IPConfigurations", &v.IPConfigurations) + delete(rawMsg, key) + case "networkSecurityGroup": + err = unpopulate(val, "NetworkSecurityGroup", &v.NetworkSecurityGroup) + delete(rawMsg, key) + case "primary": + err = unpopulate(val, "Primary", &v.Primary) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualMachineNetworkInterfaceDNSSettingsConfiguration. +func (v VirtualMachineNetworkInterfaceDNSSettingsConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dnsServers", v.DNSServers) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineNetworkInterfaceDNSSettingsConfiguration. +func (v *VirtualMachineNetworkInterfaceDNSSettingsConfiguration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "dnsServers": + err = unpopulate(val, "DNSServers", &v.DNSServers) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualMachineNetworkInterfaceIPConfiguration. +func (v VirtualMachineNetworkInterfaceIPConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineNetworkInterfaceIPConfiguration. +func (v *VirtualMachineNetworkInterfaceIPConfiguration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &v.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &v.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualMachineNetworkInterfaceIPConfigurationProperties. +func (v VirtualMachineNetworkInterfaceIPConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "applicationGatewayBackendAddressPools", v.ApplicationGatewayBackendAddressPools) + populate(objectMap, "applicationSecurityGroups", v.ApplicationSecurityGroups) + populate(objectMap, "loadBalancerBackendAddressPools", v.LoadBalancerBackendAddressPools) + populate(objectMap, "primary", v.Primary) + populate(objectMap, "privateIPAddressVersion", v.PrivateIPAddressVersion) + populate(objectMap, "publicIPAddressConfiguration", v.PublicIPAddressConfiguration) + populate(objectMap, "subnet", v.Subnet) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachineNetworkInterfaceIPConfigurationProperties. +func (v *VirtualMachineNetworkInterfaceIPConfigurationProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "applicationGatewayBackendAddressPools": + err = unpopulate(val, "ApplicationGatewayBackendAddressPools", &v.ApplicationGatewayBackendAddressPools) + delete(rawMsg, key) + case "applicationSecurityGroups": + err = unpopulate(val, "ApplicationSecurityGroups", &v.ApplicationSecurityGroups) + delete(rawMsg, key) + case "loadBalancerBackendAddressPools": + err = unpopulate(val, "LoadBalancerBackendAddressPools", &v.LoadBalancerBackendAddressPools) + delete(rawMsg, key) + case "primary": + err = unpopulate(val, "Primary", &v.Primary) + delete(rawMsg, key) + case "privateIPAddressVersion": + err = unpopulate(val, "PrivateIPAddressVersion", &v.PrivateIPAddressVersion) + delete(rawMsg, key) + case "publicIPAddressConfiguration": + err = unpopulate(val, "PublicIPAddressConfiguration", &v.PublicIPAddressConfiguration) + delete(rawMsg, key) + case "subnet": + err = unpopulate(val, "Subnet", &v.Subnet) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualMachinePublicIPAddressConfiguration. +func (v VirtualMachinePublicIPAddressConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "sku", v.SKU) + populate(objectMap, "tags", v.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachinePublicIPAddressConfiguration. +func (v *VirtualMachinePublicIPAddressConfiguration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &v.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &v.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &v.SKU) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &v.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualMachinePublicIPAddressConfigurationProperties. +func (v VirtualMachinePublicIPAddressConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dnsSettings", v.DNSSettings) + populate(objectMap, "deleteOption", v.DeleteOption) + populate(objectMap, "ipTags", v.IPTags) + populate(objectMap, "idleTimeoutInMinutes", v.IdleTimeoutInMinutes) + populate(objectMap, "publicIPAddressVersion", v.PublicIPAddressVersion) + populate(objectMap, "publicIPAllocationMethod", v.PublicIPAllocationMethod) + populate(objectMap, "publicIPPrefix", v.PublicIPPrefix) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachinePublicIPAddressConfigurationProperties. +func (v *VirtualMachinePublicIPAddressConfigurationProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "dnsSettings": + err = unpopulate(val, "DNSSettings", &v.DNSSettings) + delete(rawMsg, key) + case "deleteOption": + err = unpopulate(val, "DeleteOption", &v.DeleteOption) + delete(rawMsg, key) + case "ipTags": + err = unpopulate(val, "IPTags", &v.IPTags) + delete(rawMsg, key) + case "idleTimeoutInMinutes": + err = unpopulate(val, "IdleTimeoutInMinutes", &v.IdleTimeoutInMinutes) + delete(rawMsg, key) + case "publicIPAddressVersion": + err = unpopulate(val, "PublicIPAddressVersion", &v.PublicIPAddressVersion) + delete(rawMsg, key) + case "publicIPAllocationMethod": + err = unpopulate(val, "PublicIPAllocationMethod", &v.PublicIPAllocationMethod) + delete(rawMsg, key) + case "publicIPPrefix": + err = unpopulate(val, "PublicIPPrefix", &v.PublicIPPrefix) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualMachinePublicIPAddressDNSSettingsConfiguration. +func (v VirtualMachinePublicIPAddressDNSSettingsConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "domainNameLabel", v.DomainNameLabel) + populate(objectMap, "domainNameLabelScope", v.DomainNameLabelScope) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualMachinePublicIPAddressDNSSettingsConfiguration. +func (v *VirtualMachinePublicIPAddressDNSSettingsConfiguration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "domainNameLabel": + err = unpopulate(val, "DomainNameLabel", &v.DomainNameLabel) + delete(rawMsg, key) + case "domainNameLabelScope": + err = unpopulate(val, "DomainNameLabelScope", &v.DomainNameLabelScope) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type WinRMConfiguration. +func (w WinRMConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "listeners", w.Listeners) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WinRMConfiguration. +func (w *WinRMConfiguration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "listeners": + err = unpopulate(val, "Listeners", &w.Listeners) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type WinRMListener. +func (w WinRMListener) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "certificateUrl", w.CertificateURL) + populate(objectMap, "protocol", w.Protocol) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WinRMListener. +func (w *WinRMListener) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "certificateUrl": + err = unpopulate(val, "CertificateURL", &w.CertificateURL) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &w.Protocol) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type WindowsConfiguration. +func (w WindowsConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "additionalUnattendContent", w.AdditionalUnattendContent) + populate(objectMap, "enableAutomaticUpdates", w.EnableAutomaticUpdates) + populate(objectMap, "patchSettings", w.PatchSettings) + populate(objectMap, "provisionVMAgent", w.ProvisionVMAgent) + populate(objectMap, "timeZone", w.TimeZone) + populate(objectMap, "winRM", w.WinRM) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WindowsConfiguration. +func (w *WindowsConfiguration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "additionalUnattendContent": + err = unpopulate(val, "AdditionalUnattendContent", &w.AdditionalUnattendContent) + delete(rawMsg, key) + case "enableAutomaticUpdates": + err = unpopulate(val, "EnableAutomaticUpdates", &w.EnableAutomaticUpdates) + delete(rawMsg, key) + case "patchSettings": + err = unpopulate(val, "PatchSettings", &w.PatchSettings) + delete(rawMsg, key) + case "provisionVMAgent": + err = unpopulate(val, "ProvisionVMAgent", &w.ProvisionVMAgent) + delete(rawMsg, key) + case "timeZone": + err = unpopulate(val, "TimeZone", &w.TimeZone) + delete(rawMsg, key) + case "winRM": + err = unpopulate(val, "WinRM", &w.WinRM) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type WindowsVMGuestPatchAutomaticByPlatformSettings. +func (w WindowsVMGuestPatchAutomaticByPlatformSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "bypassPlatformSafetyChecksOnUserSchedule", w.BypassPlatformSafetyChecksOnUserSchedule) + populate(objectMap, "rebootSetting", w.RebootSetting) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WindowsVMGuestPatchAutomaticByPlatformSettings. +func (w *WindowsVMGuestPatchAutomaticByPlatformSettings) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "bypassPlatformSafetyChecksOnUserSchedule": + err = unpopulate(val, "BypassPlatformSafetyChecksOnUserSchedule", &w.BypassPlatformSafetyChecksOnUserSchedule) + delete(rawMsg, key) + case "rebootSetting": + err = unpopulate(val, "RebootSetting", &w.RebootSetting) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ZoneAllocationPolicy. +func (z ZoneAllocationPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "distributionStrategy", z.DistributionStrategy) + populate(objectMap, "zonePreferences", z.ZonePreferences) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ZoneAllocationPolicy. +func (z *ZoneAllocationPolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", z, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "distributionStrategy": + err = unpopulate(val, "DistributionStrategy", &z.DistributionStrategy) + delete(rawMsg, key) + case "zonePreferences": + err = unpopulate(val, "ZonePreferences", &z.ZonePreferences) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", z, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ZonePreference. +func (z ZonePreference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "rank", z.Rank) + populate(objectMap, "zone", z.Zone) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ZonePreference. +func (z *ZonePreference) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", z, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "rank": + err = unpopulate(val, "Rank", &z.Rank) + delete(rawMsg, key) + case "zone": + err = unpopulate(val, "Zone", &z.Zone) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", z, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/local/armcomputeschedule/zz_occurrenceextension_client.go b/test/local/armcomputeschedule/zz_occurrenceextension_client.go new file mode 100644 index 000000000000..250dbc4647bc --- /dev/null +++ b/test/local/armcomputeschedule/zz_occurrenceextension_client.go @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcomputeschedule + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// OccurrenceExtensionClient contains the methods for the OccurrenceExtension group. +// Don't use this type directly, use NewOccurrenceExtensionClient() instead. +// +// Generated from API version 2026-04-15-preview +type OccurrenceExtensionClient struct { + internal *arm.Client +} + +// NewOccurrenceExtensionClient creates a new instance of OccurrenceExtensionClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewOccurrenceExtensionClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*OccurrenceExtensionClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OccurrenceExtensionClient{ + internal: cl, + } + return client, nil +} + +// NewListOccurrenceByVMsPager - List OccurrenceExtensionResource resources by parent +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - options - OccurrenceExtensionClientListOccurrenceByVMsOptions contains the optional parameters for the OccurrenceExtensionClient.NewListOccurrenceByVMsPager +// method. +func (client *OccurrenceExtensionClient) NewListOccurrenceByVMsPager(resourceURI string, options *OccurrenceExtensionClientListOccurrenceByVMsOptions) *runtime.Pager[OccurrenceExtensionClientListOccurrenceByVMsResponse] { + return runtime.NewPager(runtime.PagingHandler[OccurrenceExtensionClientListOccurrenceByVMsResponse]{ + More: func(page OccurrenceExtensionClientListOccurrenceByVMsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OccurrenceExtensionClientListOccurrenceByVMsResponse) (OccurrenceExtensionClientListOccurrenceByVMsResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OccurrenceExtensionClient.NewListOccurrenceByVMsPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listOccurrenceByVMsCreateRequest(ctx, resourceURI, options) + }, nil) + if err != nil { + return OccurrenceExtensionClientListOccurrenceByVMsResponse{}, err + } + return client.listOccurrenceByVMsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listOccurrenceByVMsCreateRequest creates the ListOccurrenceByVMs request. +func (client *OccurrenceExtensionClient) listOccurrenceByVMsCreateRequest(ctx context.Context, resourceURI string, _ *OccurrenceExtensionClientListOccurrenceByVMsOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.ComputeSchedule/associatedOccurrences" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listOccurrenceByVMsHandleResponse handles the ListOccurrenceByVMs response. +func (client *OccurrenceExtensionClient) listOccurrenceByVMsHandleResponse(resp *http.Response) (OccurrenceExtensionClientListOccurrenceByVMsResponse, error) { + result := OccurrenceExtensionClientListOccurrenceByVMsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OccurrenceExtensionResourceListResult); err != nil { + return OccurrenceExtensionClientListOccurrenceByVMsResponse{}, err + } + return result, nil +} diff --git a/test/local/armcomputeschedule/zz_occurrences_client.go b/test/local/armcomputeschedule/zz_occurrences_client.go new file mode 100644 index 000000000000..b0890c54a88a --- /dev/null +++ b/test/local/armcomputeschedule/zz_occurrences_client.go @@ -0,0 +1,393 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcomputeschedule + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// OccurrencesClient contains the methods for the Occurrences group. +// Don't use this type directly, use NewOccurrencesClient() instead. +// +// Generated from API version 2026-04-15-preview +type OccurrencesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewOccurrencesClient creates a new instance of OccurrencesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewOccurrencesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*OccurrencesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OccurrencesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Cancel - A synchronous resource action. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - scheduledActionName - The name of the ScheduledAction +// - occurrenceID - The name of the Occurrence +// - body - The content of the action request +// - options - OccurrencesClientCancelOptions contains the optional parameters for the OccurrencesClient.Cancel method. +func (client *OccurrencesClient) Cancel(ctx context.Context, resourceGroupName string, scheduledActionName string, occurrenceID string, body CancelOccurrenceRequest, options *OccurrencesClientCancelOptions) (OccurrencesClientCancelResponse, error) { + var err error + const operationName = "OccurrencesClient.Cancel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.cancelCreateRequest(ctx, resourceGroupName, scheduledActionName, occurrenceID, body, options) + if err != nil { + return OccurrencesClientCancelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OccurrencesClientCancelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OccurrencesClientCancelResponse{}, err + } + resp, err := client.cancelHandleResponse(httpResp) + return resp, err +} + +// cancelCreateRequest creates the Cancel request. +func (client *OccurrencesClient) cancelCreateRequest(ctx context.Context, resourceGroupName string, scheduledActionName string, occurrenceID string, body CancelOccurrenceRequest, _ *OccurrencesClientCancelOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ComputeSchedule/scheduledActions/{scheduledActionName}/occurrences/{occurrenceId}/cancel" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if scheduledActionName == "" { + return nil, errors.New("parameter scheduledActionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scheduledActionName}", url.PathEscape(scheduledActionName)) + if occurrenceID == "" { + return nil, errors.New("parameter occurrenceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{occurrenceId}", url.PathEscape(occurrenceID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// cancelHandleResponse handles the Cancel response. +func (client *OccurrencesClient) cancelHandleResponse(resp *http.Response) (OccurrencesClientCancelResponse, error) { + result := OccurrencesClientCancelResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RecurringActionsResourceOperationResult); err != nil { + return OccurrencesClientCancelResponse{}, err + } + return result, nil +} + +// BeginDelay - A long-running resource action. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - scheduledActionName - The name of the ScheduledAction +// - occurrenceID - The name of the Occurrence +// - body - The content of the action request +// - options - OccurrencesClientBeginDelayOptions contains the optional parameters for the OccurrencesClient.BeginDelay method. +func (client *OccurrencesClient) BeginDelay(ctx context.Context, resourceGroupName string, scheduledActionName string, occurrenceID string, body DelayRequest, options *OccurrencesClientBeginDelayOptions) (*runtime.Poller[OccurrencesClientDelayResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.delay(ctx, resourceGroupName, scheduledActionName, occurrenceID, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[OccurrencesClientDelayResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[OccurrencesClientDelayResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delay - A long-running resource action. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *OccurrencesClient) delay(ctx context.Context, resourceGroupName string, scheduledActionName string, occurrenceID string, body DelayRequest, options *OccurrencesClientBeginDelayOptions) (*http.Response, error) { + var err error + const operationName = "OccurrencesClient.BeginDelay" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.delayCreateRequest(ctx, resourceGroupName, scheduledActionName, occurrenceID, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// delayCreateRequest creates the Delay request. +func (client *OccurrencesClient) delayCreateRequest(ctx context.Context, resourceGroupName string, scheduledActionName string, occurrenceID string, body DelayRequest, _ *OccurrencesClientBeginDelayOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ComputeSchedule/scheduledActions/{scheduledActionName}/occurrences/{occurrenceId}/delay" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if scheduledActionName == "" { + return nil, errors.New("parameter scheduledActionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scheduledActionName}", url.PathEscape(scheduledActionName)) + if occurrenceID == "" { + return nil, errors.New("parameter occurrenceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{occurrenceId}", url.PathEscape(occurrenceID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// Get - Get a Occurrence +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - scheduledActionName - The name of the ScheduledAction +// - occurrenceID - The name of the Occurrence +// - options - OccurrencesClientGetOptions contains the optional parameters for the OccurrencesClient.Get method. +func (client *OccurrencesClient) Get(ctx context.Context, resourceGroupName string, scheduledActionName string, occurrenceID string, options *OccurrencesClientGetOptions) (OccurrencesClientGetResponse, error) { + var err error + const operationName = "OccurrencesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, scheduledActionName, occurrenceID, options) + if err != nil { + return OccurrencesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OccurrencesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OccurrencesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *OccurrencesClient) getCreateRequest(ctx context.Context, resourceGroupName string, scheduledActionName string, occurrenceID string, _ *OccurrencesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ComputeSchedule/scheduledActions/{scheduledActionName}/occurrences/{occurrenceId}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if scheduledActionName == "" { + return nil, errors.New("parameter scheduledActionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scheduledActionName}", url.PathEscape(scheduledActionName)) + if occurrenceID == "" { + return nil, errors.New("parameter occurrenceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{occurrenceId}", url.PathEscape(occurrenceID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *OccurrencesClient) getHandleResponse(resp *http.Response) (OccurrencesClientGetResponse, error) { + result := OccurrencesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Occurrence); err != nil { + return OccurrencesClientGetResponse{}, err + } + return result, nil +} + +// NewListByScheduledActionPager - List Occurrence resources by ScheduledAction +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - scheduledActionName - The name of the ScheduledAction +// - options - OccurrencesClientListByScheduledActionOptions contains the optional parameters for the OccurrencesClient.NewListByScheduledActionPager +// method. +func (client *OccurrencesClient) NewListByScheduledActionPager(resourceGroupName string, scheduledActionName string, options *OccurrencesClientListByScheduledActionOptions) *runtime.Pager[OccurrencesClientListByScheduledActionResponse] { + return runtime.NewPager(runtime.PagingHandler[OccurrencesClientListByScheduledActionResponse]{ + More: func(page OccurrencesClientListByScheduledActionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OccurrencesClientListByScheduledActionResponse) (OccurrencesClientListByScheduledActionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OccurrencesClient.NewListByScheduledActionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByScheduledActionCreateRequest(ctx, resourceGroupName, scheduledActionName, options) + }, nil) + if err != nil { + return OccurrencesClientListByScheduledActionResponse{}, err + } + return client.listByScheduledActionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByScheduledActionCreateRequest creates the ListByScheduledAction request. +func (client *OccurrencesClient) listByScheduledActionCreateRequest(ctx context.Context, resourceGroupName string, scheduledActionName string, _ *OccurrencesClientListByScheduledActionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ComputeSchedule/scheduledActions/{scheduledActionName}/occurrences" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if scheduledActionName == "" { + return nil, errors.New("parameter scheduledActionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scheduledActionName}", url.PathEscape(scheduledActionName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByScheduledActionHandleResponse handles the ListByScheduledAction response. +func (client *OccurrencesClient) listByScheduledActionHandleResponse(resp *http.Response) (OccurrencesClientListByScheduledActionResponse, error) { + result := OccurrencesClientListByScheduledActionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OccurrenceListResult); err != nil { + return OccurrencesClientListByScheduledActionResponse{}, err + } + return result, nil +} + +// NewListResourcesPager - List resources attached to Scheduled Actions for the given occurrence +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - scheduledActionName - The name of the ScheduledAction +// - occurrenceID - The name of the Occurrence +// - options - OccurrencesClientListResourcesOptions contains the optional parameters for the OccurrencesClient.NewListResourcesPager +// method. +func (client *OccurrencesClient) NewListResourcesPager(resourceGroupName string, scheduledActionName string, occurrenceID string, options *OccurrencesClientListResourcesOptions) *runtime.Pager[OccurrencesClientListResourcesResponse] { + return runtime.NewPager(runtime.PagingHandler[OccurrencesClientListResourcesResponse]{ + More: func(page OccurrencesClientListResourcesResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OccurrencesClientListResourcesResponse) (OccurrencesClientListResourcesResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OccurrencesClient.NewListResourcesPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listResourcesCreateRequest(ctx, resourceGroupName, scheduledActionName, occurrenceID, options) + }, nil) + if err != nil { + return OccurrencesClientListResourcesResponse{}, err + } + return client.listResourcesHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listResourcesCreateRequest creates the ListResources request. +func (client *OccurrencesClient) listResourcesCreateRequest(ctx context.Context, resourceGroupName string, scheduledActionName string, occurrenceID string, _ *OccurrencesClientListResourcesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ComputeSchedule/scheduledActions/{scheduledActionName}/occurrences/{occurrenceId}/resources" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if scheduledActionName == "" { + return nil, errors.New("parameter scheduledActionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scheduledActionName}", url.PathEscape(scheduledActionName)) + if occurrenceID == "" { + return nil, errors.New("parameter occurrenceID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{occurrenceId}", url.PathEscape(occurrenceID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listResourcesHandleResponse handles the ListResources response. +func (client *OccurrencesClient) listResourcesHandleResponse(resp *http.Response) (OccurrencesClientListResourcesResponse, error) { + result := OccurrencesClientListResourcesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OccurrenceResourceListResponse); err != nil { + return OccurrencesClientListResourcesResponse{}, err + } + return result, nil +} diff --git a/test/local/armcomputeschedule/zz_operations_client.go b/test/local/armcomputeschedule/zz_operations_client.go new file mode 100644 index 000000000000..056b95f2f698 --- /dev/null +++ b/test/local/armcomputeschedule/zz_operations_client.go @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcomputeschedule + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +// +// Generated from API version 2026-04-15-preview +type OperationsClient struct { + internal *arm.Client +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*OperationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OperationsClient{ + internal: cl, + } + return client, nil +} + +// NewListPager - List the operations for the provider +// - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ + More: func(page OperationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OperationsClientListResponse) (OperationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OperationsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return OperationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, _ *OperationsClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.ComputeSchedule/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsClientListResponse, error) { + result := OperationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armcomputeschedule/zz_options.go b/test/local/armcomputeschedule/zz_options.go new file mode 100644 index 000000000000..cc379dc9e59b --- /dev/null +++ b/test/local/armcomputeschedule/zz_options.go @@ -0,0 +1,203 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcomputeschedule + +// OccurrenceExtensionClientListOccurrenceByVMsOptions contains the optional parameters for the OccurrenceExtensionClient.NewListOccurrenceByVMsPager +// method. +type OccurrenceExtensionClientListOccurrenceByVMsOptions struct { + // placeholder for future optional parameters +} + +// OccurrencesClientBeginDelayOptions contains the optional parameters for the OccurrencesClient.BeginDelay method. +type OccurrencesClientBeginDelayOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// OccurrencesClientCancelOptions contains the optional parameters for the OccurrencesClient.Cancel method. +type OccurrencesClientCancelOptions struct { + // placeholder for future optional parameters +} + +// OccurrencesClientGetOptions contains the optional parameters for the OccurrencesClient.Get method. +type OccurrencesClientGetOptions struct { + // placeholder for future optional parameters +} + +// OccurrencesClientListByScheduledActionOptions contains the optional parameters for the OccurrencesClient.NewListByScheduledActionPager +// method. +type OccurrencesClientListByScheduledActionOptions struct { + // placeholder for future optional parameters +} + +// OccurrencesClientListResourcesOptions contains the optional parameters for the OccurrencesClient.NewListResourcesPager +// method. +type OccurrencesClientListResourcesOptions struct { + // placeholder for future optional parameters +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} + +// ScheduledActionExtensionClientListByVMsOptions contains the optional parameters for the ScheduledActionExtensionClient.NewListByVMsPager +// method. +type ScheduledActionExtensionClientListByVMsOptions struct { + // placeholder for future optional parameters +} + +// ScheduledActionsClientAttachResourcesOptions contains the optional parameters for the ScheduledActionsClient.AttachResources +// method. +type ScheduledActionsClientAttachResourcesOptions struct { + // placeholder for future optional parameters +} + +// ScheduledActionsClientBeginCreateOrUpdateOptions contains the optional parameters for the ScheduledActionsClient.BeginCreateOrUpdate +// method. +type ScheduledActionsClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ScheduledActionsClientBeginDeleteOptions contains the optional parameters for the ScheduledActionsClient.BeginDelete method. +type ScheduledActionsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ScheduledActionsClientCancelNextOccurrenceOptions contains the optional parameters for the ScheduledActionsClient.CancelNextOccurrence +// method. +type ScheduledActionsClientCancelNextOccurrenceOptions struct { + // placeholder for future optional parameters +} + +// ScheduledActionsClientDetachResourcesOptions contains the optional parameters for the ScheduledActionsClient.DetachResources +// method. +type ScheduledActionsClientDetachResourcesOptions struct { + // placeholder for future optional parameters +} + +// ScheduledActionsClientDisableOptions contains the optional parameters for the ScheduledActionsClient.Disable method. +type ScheduledActionsClientDisableOptions struct { + // placeholder for future optional parameters +} + +// ScheduledActionsClientEnableOptions contains the optional parameters for the ScheduledActionsClient.Enable method. +type ScheduledActionsClientEnableOptions struct { + // placeholder for future optional parameters +} + +// ScheduledActionsClientGetOptions contains the optional parameters for the ScheduledActionsClient.Get method. +type ScheduledActionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ScheduledActionsClientListByResourceGroupOptions contains the optional parameters for the ScheduledActionsClient.NewListByResourceGroupPager +// method. +type ScheduledActionsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// ScheduledActionsClientListBySubscriptionOptions contains the optional parameters for the ScheduledActionsClient.NewListBySubscriptionPager +// method. +type ScheduledActionsClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// ScheduledActionsClientListResourcesOptions contains the optional parameters for the ScheduledActionsClient.NewListResourcesPager +// method. +type ScheduledActionsClientListResourcesOptions struct { + // placeholder for future optional parameters +} + +// ScheduledActionsClientPatchResourcesOptions contains the optional parameters for the ScheduledActionsClient.PatchResources +// method. +type ScheduledActionsClientPatchResourcesOptions struct { + // placeholder for future optional parameters +} + +// ScheduledActionsClientTriggerManualOccurrenceOptions contains the optional parameters for the ScheduledActionsClient.TriggerManualOccurrence +// method. +type ScheduledActionsClientTriggerManualOccurrenceOptions struct { + // placeholder for future optional parameters +} + +// ScheduledActionsClientUpdateOptions contains the optional parameters for the ScheduledActionsClient.Update method. +type ScheduledActionsClientUpdateOptions struct { + // placeholder for future optional parameters +} + +// ScheduledActionsClientVirtualMachinesCancelOperationsOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesCancelOperations +// method. +type ScheduledActionsClientVirtualMachinesCancelOperationsOptions struct { + // placeholder for future optional parameters +} + +// ScheduledActionsClientVirtualMachinesExecuteCreateFlexOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesExecuteCreateFlex +// method. +type ScheduledActionsClientVirtualMachinesExecuteCreateFlexOptions struct { + // placeholder for future optional parameters +} + +// ScheduledActionsClientVirtualMachinesExecuteCreateOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesExecuteCreate +// method. +type ScheduledActionsClientVirtualMachinesExecuteCreateOptions struct { + // placeholder for future optional parameters +} + +// ScheduledActionsClientVirtualMachinesExecuteDeallocateOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesExecuteDeallocate +// method. +type ScheduledActionsClientVirtualMachinesExecuteDeallocateOptions struct { + // placeholder for future optional parameters +} + +// ScheduledActionsClientVirtualMachinesExecuteDeleteOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesExecuteDelete +// method. +type ScheduledActionsClientVirtualMachinesExecuteDeleteOptions struct { + // placeholder for future optional parameters +} + +// ScheduledActionsClientVirtualMachinesExecuteHibernateOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesExecuteHibernate +// method. +type ScheduledActionsClientVirtualMachinesExecuteHibernateOptions struct { + // placeholder for future optional parameters +} + +// ScheduledActionsClientVirtualMachinesExecuteStartOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesExecuteStart +// method. +type ScheduledActionsClientVirtualMachinesExecuteStartOptions struct { + // placeholder for future optional parameters +} + +// ScheduledActionsClientVirtualMachinesGetOperationErrorsOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesGetOperationErrors +// method. +type ScheduledActionsClientVirtualMachinesGetOperationErrorsOptions struct { + // placeholder for future optional parameters +} + +// ScheduledActionsClientVirtualMachinesGetOperationStatusOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesGetOperationStatus +// method. +type ScheduledActionsClientVirtualMachinesGetOperationStatusOptions struct { + // placeholder for future optional parameters +} + +// ScheduledActionsClientVirtualMachinesSubmitDeallocateOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesSubmitDeallocate +// method. +type ScheduledActionsClientVirtualMachinesSubmitDeallocateOptions struct { + // placeholder for future optional parameters +} + +// ScheduledActionsClientVirtualMachinesSubmitHibernateOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesSubmitHibernate +// method. +type ScheduledActionsClientVirtualMachinesSubmitHibernateOptions struct { + // placeholder for future optional parameters +} + +// ScheduledActionsClientVirtualMachinesSubmitStartOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesSubmitStart +// method. +type ScheduledActionsClientVirtualMachinesSubmitStartOptions struct { + // placeholder for future optional parameters +} diff --git a/test/local/armcomputeschedule/zz_responses.go b/test/local/armcomputeschedule/zz_responses.go new file mode 100644 index 000000000000..fe58ca477457 --- /dev/null +++ b/test/local/armcomputeschedule/zz_responses.go @@ -0,0 +1,206 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcomputeschedule + +// OccurrenceExtensionClientListOccurrenceByVMsResponse contains the response from method OccurrenceExtensionClient.NewListOccurrenceByVMsPager. +type OccurrenceExtensionClientListOccurrenceByVMsResponse struct { + // The response of a OccurrenceExtensionResource list operation. + OccurrenceExtensionResourceListResult +} + +// OccurrencesClientCancelResponse contains the response from method OccurrencesClient.Cancel. +type OccurrencesClientCancelResponse struct { + // The response from scheduled action resource requests, which contains the status of each resource + RecurringActionsResourceOperationResult +} + +// OccurrencesClientDelayResponse contains the response from method OccurrencesClient.BeginDelay. +type OccurrencesClientDelayResponse struct { + // The response from scheduled action resource requests, which contains the status of each resource + RecurringActionsResourceOperationResult +} + +// OccurrencesClientGetResponse contains the response from method OccurrencesClient.Get. +type OccurrencesClientGetResponse struct { + // Concrete proxy resource types can be created by aliasing this type using a specific property type. + Occurrence +} + +// OccurrencesClientListByScheduledActionResponse contains the response from method OccurrencesClient.NewListByScheduledActionPager. +type OccurrencesClientListByScheduledActionResponse struct { + // The response of a Occurrence list operation. + OccurrenceListResult +} + +// OccurrencesClientListResourcesResponse contains the response from method OccurrencesClient.NewListResourcesPager. +type OccurrencesClientListResourcesResponse struct { + // Paged collection of OccurrenceResource items + OccurrenceResourceListResponse +} + +// OperationsClientListResponse contains the response from method OperationsClient.NewListPager. +type OperationsClientListResponse struct { + // A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. + OperationListResult +} + +// ScheduledActionExtensionClientListByVMsResponse contains the response from method ScheduledActionExtensionClient.NewListByVMsPager. +type ScheduledActionExtensionClientListByVMsResponse struct { + // The response of a ScheduledActionResources list operation. + ScheduledActionResourcesListResult +} + +// ScheduledActionsClientAttachResourcesResponse contains the response from method ScheduledActionsClient.AttachResources. +type ScheduledActionsClientAttachResourcesResponse struct { + // The response from scheduled action resource requests, which contains the status of each resource + RecurringActionsResourceOperationResult +} + +// ScheduledActionsClientCancelNextOccurrenceResponse contains the response from method ScheduledActionsClient.CancelNextOccurrence. +type ScheduledActionsClientCancelNextOccurrenceResponse struct { + // The response from scheduled action resource requests, which contains the status of each resource + RecurringActionsResourceOperationResult +} + +// ScheduledActionsClientCreateOrUpdateResponse contains the response from method ScheduledActionsClient.BeginCreateOrUpdate. +type ScheduledActionsClientCreateOrUpdateResponse struct { + // The scheduled action resource + ScheduledAction +} + +// ScheduledActionsClientDeleteResponse contains the response from method ScheduledActionsClient.BeginDelete. +type ScheduledActionsClientDeleteResponse struct { + // placeholder for future response values +} + +// ScheduledActionsClientDetachResourcesResponse contains the response from method ScheduledActionsClient.DetachResources. +type ScheduledActionsClientDetachResourcesResponse struct { + // The response from scheduled action resource requests, which contains the status of each resource + RecurringActionsResourceOperationResult +} + +// ScheduledActionsClientDisableResponse contains the response from method ScheduledActionsClient.Disable. +type ScheduledActionsClientDisableResponse struct { + // placeholder for future response values +} + +// ScheduledActionsClientEnableResponse contains the response from method ScheduledActionsClient.Enable. +type ScheduledActionsClientEnableResponse struct { + // placeholder for future response values +} + +// ScheduledActionsClientGetResponse contains the response from method ScheduledActionsClient.Get. +type ScheduledActionsClientGetResponse struct { + // The scheduled action resource + ScheduledAction +} + +// ScheduledActionsClientListByResourceGroupResponse contains the response from method ScheduledActionsClient.NewListByResourceGroupPager. +type ScheduledActionsClientListByResourceGroupResponse struct { + // The response of a ScheduledAction list operation. + ScheduledActionListResult +} + +// ScheduledActionsClientListBySubscriptionResponse contains the response from method ScheduledActionsClient.NewListBySubscriptionPager. +type ScheduledActionsClientListBySubscriptionResponse struct { + // The response of a ScheduledAction list operation. + ScheduledActionListResult +} + +// ScheduledActionsClientListResourcesResponse contains the response from method ScheduledActionsClient.NewListResourcesPager. +type ScheduledActionsClientListResourcesResponse struct { + // Paged collection of ScheduledActionResource items + ResourceListResponse +} + +// ScheduledActionsClientPatchResourcesResponse contains the response from method ScheduledActionsClient.PatchResources. +type ScheduledActionsClientPatchResourcesResponse struct { + // The response from scheduled action resource requests, which contains the status of each resource + RecurringActionsResourceOperationResult +} + +// ScheduledActionsClientTriggerManualOccurrenceResponse contains the response from method ScheduledActionsClient.TriggerManualOccurrence. +type ScheduledActionsClientTriggerManualOccurrenceResponse struct { + // Concrete proxy resource types can be created by aliasing this type using a specific property type. + Occurrence +} + +// ScheduledActionsClientUpdateResponse contains the response from method ScheduledActionsClient.Update. +type ScheduledActionsClientUpdateResponse struct { + // The scheduled action resource + ScheduledAction +} + +// ScheduledActionsClientVirtualMachinesCancelOperationsResponse contains the response from method ScheduledActionsClient.VirtualMachinesCancelOperations. +type ScheduledActionsClientVirtualMachinesCancelOperationsResponse struct { + // This is the response from a cancel operations request + CancelOperationsResponse +} + +// ScheduledActionsClientVirtualMachinesExecuteCreateFlexResponse contains the response from method ScheduledActionsClient.VirtualMachinesExecuteCreateFlex. +type ScheduledActionsClientVirtualMachinesExecuteCreateFlexResponse struct { + // The response from a create flex request + CreateFlexResourceOperationResponse +} + +// ScheduledActionsClientVirtualMachinesExecuteCreateResponse contains the response from method ScheduledActionsClient.VirtualMachinesExecuteCreate. +type ScheduledActionsClientVirtualMachinesExecuteCreateResponse struct { + // The response from a create request + CreateResourceOperationResponse +} + +// ScheduledActionsClientVirtualMachinesExecuteDeallocateResponse contains the response from method ScheduledActionsClient.VirtualMachinesExecuteDeallocate. +type ScheduledActionsClientVirtualMachinesExecuteDeallocateResponse struct { + // The response from a deallocate request + DeallocateResourceOperationResponse +} + +// ScheduledActionsClientVirtualMachinesExecuteDeleteResponse contains the response from method ScheduledActionsClient.VirtualMachinesExecuteDelete. +type ScheduledActionsClientVirtualMachinesExecuteDeleteResponse struct { + // The response from a delete request + DeleteResourceOperationResponse +} + +// ScheduledActionsClientVirtualMachinesExecuteHibernateResponse contains the response from method ScheduledActionsClient.VirtualMachinesExecuteHibernate. +type ScheduledActionsClientVirtualMachinesExecuteHibernateResponse struct { + // The response from a Hibernate request + HibernateResourceOperationResponse +} + +// ScheduledActionsClientVirtualMachinesExecuteStartResponse contains the response from method ScheduledActionsClient.VirtualMachinesExecuteStart. +type ScheduledActionsClientVirtualMachinesExecuteStartResponse struct { + // The response from a start request + StartResourceOperationResponse +} + +// ScheduledActionsClientVirtualMachinesGetOperationErrorsResponse contains the response from method ScheduledActionsClient.VirtualMachinesGetOperationErrors. +type ScheduledActionsClientVirtualMachinesGetOperationErrorsResponse struct { + // This is the response from a get operations errors request + GetOperationErrorsResponse +} + +// ScheduledActionsClientVirtualMachinesGetOperationStatusResponse contains the response from method ScheduledActionsClient.VirtualMachinesGetOperationStatus. +type ScheduledActionsClientVirtualMachinesGetOperationStatusResponse struct { + // This is the response from a get operations status request + GetOperationStatusResponse +} + +// ScheduledActionsClientVirtualMachinesSubmitDeallocateResponse contains the response from method ScheduledActionsClient.VirtualMachinesSubmitDeallocate. +type ScheduledActionsClientVirtualMachinesSubmitDeallocateResponse struct { + // The response from a deallocate request + DeallocateResourceOperationResponse +} + +// ScheduledActionsClientVirtualMachinesSubmitHibernateResponse contains the response from method ScheduledActionsClient.VirtualMachinesSubmitHibernate. +type ScheduledActionsClientVirtualMachinesSubmitHibernateResponse struct { + // The response from a Hibernate request + HibernateResourceOperationResponse +} + +// ScheduledActionsClientVirtualMachinesSubmitStartResponse contains the response from method ScheduledActionsClient.VirtualMachinesSubmitStart. +type ScheduledActionsClientVirtualMachinesSubmitStartResponse struct { + // The response from a start request + StartResourceOperationResponse +} diff --git a/test/local/armcomputeschedule/zz_scheduledactionextension_client.go b/test/local/armcomputeschedule/zz_scheduledactionextension_client.go new file mode 100644 index 000000000000..5eef78a54cc0 --- /dev/null +++ b/test/local/armcomputeschedule/zz_scheduledactionextension_client.go @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcomputeschedule + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// ScheduledActionExtensionClient contains the methods for the ScheduledActionExtension group. +// Don't use this type directly, use NewScheduledActionExtensionClient() instead. +// +// Generated from API version 2026-04-15-preview +type ScheduledActionExtensionClient struct { + internal *arm.Client +} + +// NewScheduledActionExtensionClient creates a new instance of ScheduledActionExtensionClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewScheduledActionExtensionClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*ScheduledActionExtensionClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ScheduledActionExtensionClient{ + internal: cl, + } + return client, nil +} + +// NewListByVMsPager - List ScheduledActionResources resources by parent +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - options - ScheduledActionExtensionClientListByVMsOptions contains the optional parameters for the ScheduledActionExtensionClient.NewListByVMsPager +// method. +func (client *ScheduledActionExtensionClient) NewListByVMsPager(resourceURI string, options *ScheduledActionExtensionClientListByVMsOptions) *runtime.Pager[ScheduledActionExtensionClientListByVMsResponse] { + return runtime.NewPager(runtime.PagingHandler[ScheduledActionExtensionClientListByVMsResponse]{ + More: func(page ScheduledActionExtensionClientListByVMsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ScheduledActionExtensionClientListByVMsResponse) (ScheduledActionExtensionClientListByVMsResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ScheduledActionExtensionClient.NewListByVMsPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByVMsCreateRequest(ctx, resourceURI, options) + }, nil) + if err != nil { + return ScheduledActionExtensionClientListByVMsResponse{}, err + } + return client.listByVMsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByVMsCreateRequest creates the ListByVMs request. +func (client *ScheduledActionExtensionClient) listByVMsCreateRequest(ctx context.Context, resourceURI string, _ *ScheduledActionExtensionClientListByVMsOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.ComputeSchedule/associatedScheduledActions" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByVMsHandleResponse handles the ListByVMs response. +func (client *ScheduledActionExtensionClient) listByVMsHandleResponse(resp *http.Response) (ScheduledActionExtensionClientListByVMsResponse, error) { + result := ScheduledActionExtensionClientListByVMsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ScheduledActionResourcesListResult); err != nil { + return ScheduledActionExtensionClientListByVMsResponse{}, err + } + return result, nil +} diff --git a/test/local/armcomputeschedule/zz_scheduledactions_client.go b/test/local/armcomputeschedule/zz_scheduledactions_client.go new file mode 100644 index 000000000000..4a611a84d338 --- /dev/null +++ b/test/local/armcomputeschedule/zz_scheduledactions_client.go @@ -0,0 +1,1699 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcomputeschedule + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ScheduledActionsClient contains the methods for the ScheduledActions group. +// Don't use this type directly, use NewScheduledActionsClient() instead. +// +// Generated from API version 2026-04-15-preview +type ScheduledActionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewScheduledActionsClient creates a new instance of ScheduledActionsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewScheduledActionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ScheduledActionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ScheduledActionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// AttachResources - A synchronous resource action. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - scheduledActionName - The name of the ScheduledAction +// - body - The content of the action request +// - options - ScheduledActionsClientAttachResourcesOptions contains the optional parameters for the ScheduledActionsClient.AttachResources +// method. +func (client *ScheduledActionsClient) AttachResources(ctx context.Context, resourceGroupName string, scheduledActionName string, body ResourceAttachRequest, options *ScheduledActionsClientAttachResourcesOptions) (ScheduledActionsClientAttachResourcesResponse, error) { + var err error + const operationName = "ScheduledActionsClient.AttachResources" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.attachResourcesCreateRequest(ctx, resourceGroupName, scheduledActionName, body, options) + if err != nil { + return ScheduledActionsClientAttachResourcesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScheduledActionsClientAttachResourcesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScheduledActionsClientAttachResourcesResponse{}, err + } + resp, err := client.attachResourcesHandleResponse(httpResp) + return resp, err +} + +// attachResourcesCreateRequest creates the AttachResources request. +func (client *ScheduledActionsClient) attachResourcesCreateRequest(ctx context.Context, resourceGroupName string, scheduledActionName string, body ResourceAttachRequest, _ *ScheduledActionsClientAttachResourcesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ComputeSchedule/scheduledActions/{scheduledActionName}/attachResources" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if scheduledActionName == "" { + return nil, errors.New("parameter scheduledActionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scheduledActionName}", url.PathEscape(scheduledActionName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// attachResourcesHandleResponse handles the AttachResources response. +func (client *ScheduledActionsClient) attachResourcesHandleResponse(resp *http.Response) (ScheduledActionsClientAttachResourcesResponse, error) { + result := ScheduledActionsClientAttachResourcesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RecurringActionsResourceOperationResult); err != nil { + return ScheduledActionsClientAttachResourcesResponse{}, err + } + return result, nil +} + +// CancelNextOccurrence - A synchronous resource action. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - scheduledActionName - The name of the ScheduledAction +// - body - The content of the action request +// - options - ScheduledActionsClientCancelNextOccurrenceOptions contains the optional parameters for the ScheduledActionsClient.CancelNextOccurrence +// method. +func (client *ScheduledActionsClient) CancelNextOccurrence(ctx context.Context, resourceGroupName string, scheduledActionName string, body CancelOccurrenceRequest, options *ScheduledActionsClientCancelNextOccurrenceOptions) (ScheduledActionsClientCancelNextOccurrenceResponse, error) { + var err error + const operationName = "ScheduledActionsClient.CancelNextOccurrence" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.cancelNextOccurrenceCreateRequest(ctx, resourceGroupName, scheduledActionName, body, options) + if err != nil { + return ScheduledActionsClientCancelNextOccurrenceResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScheduledActionsClientCancelNextOccurrenceResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScheduledActionsClientCancelNextOccurrenceResponse{}, err + } + resp, err := client.cancelNextOccurrenceHandleResponse(httpResp) + return resp, err +} + +// cancelNextOccurrenceCreateRequest creates the CancelNextOccurrence request. +func (client *ScheduledActionsClient) cancelNextOccurrenceCreateRequest(ctx context.Context, resourceGroupName string, scheduledActionName string, body CancelOccurrenceRequest, _ *ScheduledActionsClientCancelNextOccurrenceOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ComputeSchedule/scheduledActions/{scheduledActionName}/cancelNextOccurrence" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if scheduledActionName == "" { + return nil, errors.New("parameter scheduledActionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scheduledActionName}", url.PathEscape(scheduledActionName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// cancelNextOccurrenceHandleResponse handles the CancelNextOccurrence response. +func (client *ScheduledActionsClient) cancelNextOccurrenceHandleResponse(resp *http.Response) (ScheduledActionsClientCancelNextOccurrenceResponse, error) { + result := ScheduledActionsClientCancelNextOccurrenceResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RecurringActionsResourceOperationResult); err != nil { + return ScheduledActionsClientCancelNextOccurrenceResponse{}, err + } + return result, nil +} + +// BeginCreateOrUpdate - Create a ScheduledAction +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - scheduledActionName - The name of the ScheduledAction +// - resource - Resource create parameters. +// - options - ScheduledActionsClientBeginCreateOrUpdateOptions contains the optional parameters for the ScheduledActionsClient.BeginCreateOrUpdate +// method. +func (client *ScheduledActionsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, scheduledActionName string, resource ScheduledAction, options *ScheduledActionsClientBeginCreateOrUpdateOptions) (*runtime.Poller[ScheduledActionsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, scheduledActionName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ScheduledActionsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ScheduledActionsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create a ScheduledAction +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ScheduledActionsClient) createOrUpdate(ctx context.Context, resourceGroupName string, scheduledActionName string, resource ScheduledAction, options *ScheduledActionsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ScheduledActionsClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, scheduledActionName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *ScheduledActionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, scheduledActionName string, resource ScheduledAction, _ *ScheduledActionsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ComputeSchedule/scheduledActions/{scheduledActionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if scheduledActionName == "" { + return nil, errors.New("parameter scheduledActionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scheduledActionName}", url.PathEscape(scheduledActionName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a ScheduledAction +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - scheduledActionName - The name of the ScheduledAction +// - options - ScheduledActionsClientBeginDeleteOptions contains the optional parameters for the ScheduledActionsClient.BeginDelete +// method. +func (client *ScheduledActionsClient) BeginDelete(ctx context.Context, resourceGroupName string, scheduledActionName string, options *ScheduledActionsClientBeginDeleteOptions) (*runtime.Poller[ScheduledActionsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, scheduledActionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ScheduledActionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ScheduledActionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a ScheduledAction +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ScheduledActionsClient) deleteOperation(ctx context.Context, resourceGroupName string, scheduledActionName string, options *ScheduledActionsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ScheduledActionsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, scheduledActionName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ScheduledActionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, scheduledActionName string, _ *ScheduledActionsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ComputeSchedule/scheduledActions/{scheduledActionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if scheduledActionName == "" { + return nil, errors.New("parameter scheduledActionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scheduledActionName}", url.PathEscape(scheduledActionName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// DetachResources - A synchronous resource action. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - scheduledActionName - The name of the ScheduledAction +// - body - The content of the action request +// - options - ScheduledActionsClientDetachResourcesOptions contains the optional parameters for the ScheduledActionsClient.DetachResources +// method. +func (client *ScheduledActionsClient) DetachResources(ctx context.Context, resourceGroupName string, scheduledActionName string, body ResourceDetachRequest, options *ScheduledActionsClientDetachResourcesOptions) (ScheduledActionsClientDetachResourcesResponse, error) { + var err error + const operationName = "ScheduledActionsClient.DetachResources" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.detachResourcesCreateRequest(ctx, resourceGroupName, scheduledActionName, body, options) + if err != nil { + return ScheduledActionsClientDetachResourcesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScheduledActionsClientDetachResourcesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScheduledActionsClientDetachResourcesResponse{}, err + } + resp, err := client.detachResourcesHandleResponse(httpResp) + return resp, err +} + +// detachResourcesCreateRequest creates the DetachResources request. +func (client *ScheduledActionsClient) detachResourcesCreateRequest(ctx context.Context, resourceGroupName string, scheduledActionName string, body ResourceDetachRequest, _ *ScheduledActionsClientDetachResourcesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ComputeSchedule/scheduledActions/{scheduledActionName}/detachResources" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if scheduledActionName == "" { + return nil, errors.New("parameter scheduledActionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scheduledActionName}", url.PathEscape(scheduledActionName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// detachResourcesHandleResponse handles the DetachResources response. +func (client *ScheduledActionsClient) detachResourcesHandleResponse(resp *http.Response) (ScheduledActionsClientDetachResourcesResponse, error) { + result := ScheduledActionsClientDetachResourcesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RecurringActionsResourceOperationResult); err != nil { + return ScheduledActionsClientDetachResourcesResponse{}, err + } + return result, nil +} + +// Disable - A synchronous resource action. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - scheduledActionName - The name of the ScheduledAction +// - options - ScheduledActionsClientDisableOptions contains the optional parameters for the ScheduledActionsClient.Disable +// method. +func (client *ScheduledActionsClient) Disable(ctx context.Context, resourceGroupName string, scheduledActionName string, options *ScheduledActionsClientDisableOptions) (ScheduledActionsClientDisableResponse, error) { + var err error + const operationName = "ScheduledActionsClient.Disable" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.disableCreateRequest(ctx, resourceGroupName, scheduledActionName, options) + if err != nil { + return ScheduledActionsClientDisableResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScheduledActionsClientDisableResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScheduledActionsClientDisableResponse{}, err + } + return ScheduledActionsClientDisableResponse{}, nil +} + +// disableCreateRequest creates the Disable request. +func (client *ScheduledActionsClient) disableCreateRequest(ctx context.Context, resourceGroupName string, scheduledActionName string, _ *ScheduledActionsClientDisableOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ComputeSchedule/scheduledActions/{scheduledActionName}/disable" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if scheduledActionName == "" { + return nil, errors.New("parameter scheduledActionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scheduledActionName}", url.PathEscape(scheduledActionName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Enable - A synchronous resource action. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - scheduledActionName - The name of the ScheduledAction +// - options - ScheduledActionsClientEnableOptions contains the optional parameters for the ScheduledActionsClient.Enable method. +func (client *ScheduledActionsClient) Enable(ctx context.Context, resourceGroupName string, scheduledActionName string, options *ScheduledActionsClientEnableOptions) (ScheduledActionsClientEnableResponse, error) { + var err error + const operationName = "ScheduledActionsClient.Enable" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.enableCreateRequest(ctx, resourceGroupName, scheduledActionName, options) + if err != nil { + return ScheduledActionsClientEnableResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScheduledActionsClientEnableResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScheduledActionsClientEnableResponse{}, err + } + return ScheduledActionsClientEnableResponse{}, nil +} + +// enableCreateRequest creates the Enable request. +func (client *ScheduledActionsClient) enableCreateRequest(ctx context.Context, resourceGroupName string, scheduledActionName string, _ *ScheduledActionsClientEnableOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ComputeSchedule/scheduledActions/{scheduledActionName}/enable" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if scheduledActionName == "" { + return nil, errors.New("parameter scheduledActionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scheduledActionName}", url.PathEscape(scheduledActionName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a ScheduledAction +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - scheduledActionName - The name of the ScheduledAction +// - options - ScheduledActionsClientGetOptions contains the optional parameters for the ScheduledActionsClient.Get method. +func (client *ScheduledActionsClient) Get(ctx context.Context, resourceGroupName string, scheduledActionName string, options *ScheduledActionsClientGetOptions) (ScheduledActionsClientGetResponse, error) { + var err error + const operationName = "ScheduledActionsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, scheduledActionName, options) + if err != nil { + return ScheduledActionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScheduledActionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScheduledActionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ScheduledActionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, scheduledActionName string, _ *ScheduledActionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ComputeSchedule/scheduledActions/{scheduledActionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if scheduledActionName == "" { + return nil, errors.New("parameter scheduledActionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scheduledActionName}", url.PathEscape(scheduledActionName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ScheduledActionsClient) getHandleResponse(resp *http.Response) (ScheduledActionsClientGetResponse, error) { + result := ScheduledActionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ScheduledAction); err != nil { + return ScheduledActionsClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - List ScheduledAction resources by resource group +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - ScheduledActionsClientListByResourceGroupOptions contains the optional parameters for the ScheduledActionsClient.NewListByResourceGroupPager +// method. +func (client *ScheduledActionsClient) NewListByResourceGroupPager(resourceGroupName string, options *ScheduledActionsClientListByResourceGroupOptions) *runtime.Pager[ScheduledActionsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[ScheduledActionsClientListByResourceGroupResponse]{ + More: func(page ScheduledActionsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ScheduledActionsClientListByResourceGroupResponse) (ScheduledActionsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ScheduledActionsClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return ScheduledActionsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *ScheduledActionsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *ScheduledActionsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ComputeSchedule/scheduledActions" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *ScheduledActionsClient) listByResourceGroupHandleResponse(resp *http.Response) (ScheduledActionsClientListByResourceGroupResponse, error) { + result := ScheduledActionsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ScheduledActionListResult); err != nil { + return ScheduledActionsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - List ScheduledAction resources by subscription ID +// - options - ScheduledActionsClientListBySubscriptionOptions contains the optional parameters for the ScheduledActionsClient.NewListBySubscriptionPager +// method. +func (client *ScheduledActionsClient) NewListBySubscriptionPager(options *ScheduledActionsClientListBySubscriptionOptions) *runtime.Pager[ScheduledActionsClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[ScheduledActionsClientListBySubscriptionResponse]{ + More: func(page ScheduledActionsClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ScheduledActionsClientListBySubscriptionResponse) (ScheduledActionsClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ScheduledActionsClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return ScheduledActionsClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *ScheduledActionsClient) listBySubscriptionCreateRequest(ctx context.Context, _ *ScheduledActionsClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ComputeSchedule/scheduledActions" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *ScheduledActionsClient) listBySubscriptionHandleResponse(resp *http.Response) (ScheduledActionsClientListBySubscriptionResponse, error) { + result := ScheduledActionsClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ScheduledActionListResult); err != nil { + return ScheduledActionsClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// NewListResourcesPager - List resources attached to Scheduled Actions +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - scheduledActionName - The name of the ScheduledAction +// - options - ScheduledActionsClientListResourcesOptions contains the optional parameters for the ScheduledActionsClient.NewListResourcesPager +// method. +func (client *ScheduledActionsClient) NewListResourcesPager(resourceGroupName string, scheduledActionName string, options *ScheduledActionsClientListResourcesOptions) *runtime.Pager[ScheduledActionsClientListResourcesResponse] { + return runtime.NewPager(runtime.PagingHandler[ScheduledActionsClientListResourcesResponse]{ + More: func(page ScheduledActionsClientListResourcesResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ScheduledActionsClientListResourcesResponse) (ScheduledActionsClientListResourcesResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ScheduledActionsClient.NewListResourcesPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listResourcesCreateRequest(ctx, resourceGroupName, scheduledActionName, options) + }, nil) + if err != nil { + return ScheduledActionsClientListResourcesResponse{}, err + } + return client.listResourcesHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listResourcesCreateRequest creates the ListResources request. +func (client *ScheduledActionsClient) listResourcesCreateRequest(ctx context.Context, resourceGroupName string, scheduledActionName string, _ *ScheduledActionsClientListResourcesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ComputeSchedule/scheduledActions/{scheduledActionName}/resources" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if scheduledActionName == "" { + return nil, errors.New("parameter scheduledActionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scheduledActionName}", url.PathEscape(scheduledActionName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listResourcesHandleResponse handles the ListResources response. +func (client *ScheduledActionsClient) listResourcesHandleResponse(resp *http.Response) (ScheduledActionsClientListResourcesResponse, error) { + result := ScheduledActionsClientListResourcesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ResourceListResponse); err != nil { + return ScheduledActionsClientListResourcesResponse{}, err + } + return result, nil +} + +// PatchResources - A synchronous resource action. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - scheduledActionName - The name of the ScheduledAction +// - body - The content of the action request +// - options - ScheduledActionsClientPatchResourcesOptions contains the optional parameters for the ScheduledActionsClient.PatchResources +// method. +func (client *ScheduledActionsClient) PatchResources(ctx context.Context, resourceGroupName string, scheduledActionName string, body ResourcePatchRequest, options *ScheduledActionsClientPatchResourcesOptions) (ScheduledActionsClientPatchResourcesResponse, error) { + var err error + const operationName = "ScheduledActionsClient.PatchResources" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.patchResourcesCreateRequest(ctx, resourceGroupName, scheduledActionName, body, options) + if err != nil { + return ScheduledActionsClientPatchResourcesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScheduledActionsClientPatchResourcesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScheduledActionsClientPatchResourcesResponse{}, err + } + resp, err := client.patchResourcesHandleResponse(httpResp) + return resp, err +} + +// patchResourcesCreateRequest creates the PatchResources request. +func (client *ScheduledActionsClient) patchResourcesCreateRequest(ctx context.Context, resourceGroupName string, scheduledActionName string, body ResourcePatchRequest, _ *ScheduledActionsClientPatchResourcesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ComputeSchedule/scheduledActions/{scheduledActionName}/patchResources" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if scheduledActionName == "" { + return nil, errors.New("parameter scheduledActionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scheduledActionName}", url.PathEscape(scheduledActionName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// patchResourcesHandleResponse handles the PatchResources response. +func (client *ScheduledActionsClient) patchResourcesHandleResponse(resp *http.Response) (ScheduledActionsClientPatchResourcesResponse, error) { + result := ScheduledActionsClientPatchResourcesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RecurringActionsResourceOperationResult); err != nil { + return ScheduledActionsClientPatchResourcesResponse{}, err + } + return result, nil +} + +// TriggerManualOccurrence - A synchronous resource action. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - scheduledActionName - The name of the ScheduledAction +// - options - ScheduledActionsClientTriggerManualOccurrenceOptions contains the optional parameters for the ScheduledActionsClient.TriggerManualOccurrence +// method. +func (client *ScheduledActionsClient) TriggerManualOccurrence(ctx context.Context, resourceGroupName string, scheduledActionName string, options *ScheduledActionsClientTriggerManualOccurrenceOptions) (ScheduledActionsClientTriggerManualOccurrenceResponse, error) { + var err error + const operationName = "ScheduledActionsClient.TriggerManualOccurrence" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.triggerManualOccurrenceCreateRequest(ctx, resourceGroupName, scheduledActionName, options) + if err != nil { + return ScheduledActionsClientTriggerManualOccurrenceResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScheduledActionsClientTriggerManualOccurrenceResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScheduledActionsClientTriggerManualOccurrenceResponse{}, err + } + resp, err := client.triggerManualOccurrenceHandleResponse(httpResp) + return resp, err +} + +// triggerManualOccurrenceCreateRequest creates the TriggerManualOccurrence request. +func (client *ScheduledActionsClient) triggerManualOccurrenceCreateRequest(ctx context.Context, resourceGroupName string, scheduledActionName string, _ *ScheduledActionsClientTriggerManualOccurrenceOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ComputeSchedule/scheduledActions/{scheduledActionName}/triggerManualOccurrence" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if scheduledActionName == "" { + return nil, errors.New("parameter scheduledActionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scheduledActionName}", url.PathEscape(scheduledActionName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// triggerManualOccurrenceHandleResponse handles the TriggerManualOccurrence response. +func (client *ScheduledActionsClient) triggerManualOccurrenceHandleResponse(resp *http.Response) (ScheduledActionsClientTriggerManualOccurrenceResponse, error) { + result := ScheduledActionsClientTriggerManualOccurrenceResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Occurrence); err != nil { + return ScheduledActionsClientTriggerManualOccurrenceResponse{}, err + } + return result, nil +} + +// Update - Update a ScheduledAction +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - scheduledActionName - The name of the ScheduledAction +// - properties - The resource properties to be updated. +// - options - ScheduledActionsClientUpdateOptions contains the optional parameters for the ScheduledActionsClient.Update method. +func (client *ScheduledActionsClient) Update(ctx context.Context, resourceGroupName string, scheduledActionName string, properties ScheduledActionUpdate, options *ScheduledActionsClientUpdateOptions) (ScheduledActionsClientUpdateResponse, error) { + var err error + const operationName = "ScheduledActionsClient.Update" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, scheduledActionName, properties, options) + if err != nil { + return ScheduledActionsClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScheduledActionsClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScheduledActionsClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *ScheduledActionsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, scheduledActionName string, properties ScheduledActionUpdate, _ *ScheduledActionsClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ComputeSchedule/scheduledActions/{scheduledActionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if scheduledActionName == "" { + return nil, errors.New("parameter scheduledActionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{scheduledActionName}", url.PathEscape(scheduledActionName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *ScheduledActionsClient) updateHandleResponse(resp *http.Response) (ScheduledActionsClientUpdateResponse, error) { + result := ScheduledActionsClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ScheduledAction); err != nil { + return ScheduledActionsClientUpdateResponse{}, err + } + return result, nil +} + +// VirtualMachinesCancelOperations - VirtualMachinesCancelOperations: Cancel a previously submitted (start/deallocate/hibernate) +// request +// If the operation fails it returns an *azcore.ResponseError type. +// - locationparameter - The location name. +// - requestBody - The request body +// - options - ScheduledActionsClientVirtualMachinesCancelOperationsOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesCancelOperations +// method. +func (client *ScheduledActionsClient) VirtualMachinesCancelOperations(ctx context.Context, locationparameter string, requestBody CancelOperationsRequest, options *ScheduledActionsClientVirtualMachinesCancelOperationsOptions) (ScheduledActionsClientVirtualMachinesCancelOperationsResponse, error) { + var err error + const operationName = "ScheduledActionsClient.VirtualMachinesCancelOperations" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.virtualMachinesCancelOperationsCreateRequest(ctx, locationparameter, requestBody, options) + if err != nil { + return ScheduledActionsClientVirtualMachinesCancelOperationsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScheduledActionsClientVirtualMachinesCancelOperationsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScheduledActionsClientVirtualMachinesCancelOperationsResponse{}, err + } + resp, err := client.virtualMachinesCancelOperationsHandleResponse(httpResp) + return resp, err +} + +// virtualMachinesCancelOperationsCreateRequest creates the VirtualMachinesCancelOperations request. +func (client *ScheduledActionsClient) virtualMachinesCancelOperationsCreateRequest(ctx context.Context, locationparameter string, requestBody CancelOperationsRequest, _ *ScheduledActionsClientVirtualMachinesCancelOperationsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ComputeSchedule/locations/{locationparameter}/virtualMachinesCancelOperations" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if locationparameter == "" { + return nil, errors.New("parameter locationparameter cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{locationparameter}", url.PathEscape(locationparameter)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, requestBody); err != nil { + return nil, err + } + return req, nil +} + +// virtualMachinesCancelOperationsHandleResponse handles the VirtualMachinesCancelOperations response. +func (client *ScheduledActionsClient) virtualMachinesCancelOperationsHandleResponse(resp *http.Response) (ScheduledActionsClientVirtualMachinesCancelOperationsResponse, error) { + result := ScheduledActionsClientVirtualMachinesCancelOperationsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CancelOperationsResponse); err != nil { + return ScheduledActionsClientVirtualMachinesCancelOperationsResponse{}, err + } + return result, nil +} + +// VirtualMachinesExecuteCreate - [PRIVATE PREVIEW]: VirtualMachinesExecuteCreate: Execute create operation for a batch of +// virtual machines, this operation is triggered as soon as Computeschedule receives it. +// If the operation fails it returns an *azcore.ResponseError type. +// - locationparameter - The location name. +// - requestBody - The request body +// - options - ScheduledActionsClientVirtualMachinesExecuteCreateOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesExecuteCreate +// method. +func (client *ScheduledActionsClient) VirtualMachinesExecuteCreate(ctx context.Context, locationparameter string, requestBody ExecuteCreateRequest, options *ScheduledActionsClientVirtualMachinesExecuteCreateOptions) (ScheduledActionsClientVirtualMachinesExecuteCreateResponse, error) { + var err error + const operationName = "ScheduledActionsClient.VirtualMachinesExecuteCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.virtualMachinesExecuteCreateCreateRequest(ctx, locationparameter, requestBody, options) + if err != nil { + return ScheduledActionsClientVirtualMachinesExecuteCreateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScheduledActionsClientVirtualMachinesExecuteCreateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScheduledActionsClientVirtualMachinesExecuteCreateResponse{}, err + } + resp, err := client.virtualMachinesExecuteCreateHandleResponse(httpResp) + return resp, err +} + +// virtualMachinesExecuteCreateCreateRequest creates the VirtualMachinesExecuteCreate request. +func (client *ScheduledActionsClient) virtualMachinesExecuteCreateCreateRequest(ctx context.Context, locationparameter string, requestBody ExecuteCreateRequest, _ *ScheduledActionsClientVirtualMachinesExecuteCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ComputeSchedule/locations/{locationparameter}/virtualMachinesExecuteCreate" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if locationparameter == "" { + return nil, errors.New("parameter locationparameter cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{locationparameter}", url.PathEscape(locationparameter)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, requestBody); err != nil { + return nil, err + } + return req, nil +} + +// virtualMachinesExecuteCreateHandleResponse handles the VirtualMachinesExecuteCreate response. +func (client *ScheduledActionsClient) virtualMachinesExecuteCreateHandleResponse(resp *http.Response) (ScheduledActionsClientVirtualMachinesExecuteCreateResponse, error) { + result := ScheduledActionsClientVirtualMachinesExecuteCreateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CreateResourceOperationResponse); err != nil { + return ScheduledActionsClientVirtualMachinesExecuteCreateResponse{}, err + } + return result, nil +} + +// VirtualMachinesExecuteCreateFlex - VirtualMachinesExecuteCreateFlex: Execute create operation for a batch of virtual machines +// with flex properties, this operation is triggered as soon as Computeschedule receives it. +// If the operation fails it returns an *azcore.ResponseError type. +// - locationparameter - The location name. +// - body - The request body +// - options - ScheduledActionsClientVirtualMachinesExecuteCreateFlexOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesExecuteCreateFlex +// method. +func (client *ScheduledActionsClient) VirtualMachinesExecuteCreateFlex(ctx context.Context, locationparameter string, body ExecuteCreateFlexRequest, options *ScheduledActionsClientVirtualMachinesExecuteCreateFlexOptions) (ScheduledActionsClientVirtualMachinesExecuteCreateFlexResponse, error) { + var err error + const operationName = "ScheduledActionsClient.VirtualMachinesExecuteCreateFlex" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.virtualMachinesExecuteCreateFlexCreateRequest(ctx, locationparameter, body, options) + if err != nil { + return ScheduledActionsClientVirtualMachinesExecuteCreateFlexResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScheduledActionsClientVirtualMachinesExecuteCreateFlexResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScheduledActionsClientVirtualMachinesExecuteCreateFlexResponse{}, err + } + resp, err := client.virtualMachinesExecuteCreateFlexHandleResponse(httpResp) + return resp, err +} + +// virtualMachinesExecuteCreateFlexCreateRequest creates the VirtualMachinesExecuteCreateFlex request. +func (client *ScheduledActionsClient) virtualMachinesExecuteCreateFlexCreateRequest(ctx context.Context, locationparameter string, body ExecuteCreateFlexRequest, _ *ScheduledActionsClientVirtualMachinesExecuteCreateFlexOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ComputeSchedule/locations/{locationparameter}/virtualMachinesExecuteCreateFlex" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if locationparameter == "" { + return nil, errors.New("parameter locationparameter cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{locationparameter}", url.PathEscape(locationparameter)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// virtualMachinesExecuteCreateFlexHandleResponse handles the VirtualMachinesExecuteCreateFlex response. +func (client *ScheduledActionsClient) virtualMachinesExecuteCreateFlexHandleResponse(resp *http.Response) (ScheduledActionsClientVirtualMachinesExecuteCreateFlexResponse, error) { + result := ScheduledActionsClientVirtualMachinesExecuteCreateFlexResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CreateFlexResourceOperationResponse); err != nil { + return ScheduledActionsClientVirtualMachinesExecuteCreateFlexResponse{}, err + } + return result, nil +} + +// VirtualMachinesExecuteDeallocate - VirtualMachinesExecuteDeallocate: Execute deallocate operation for a batch of virtual +// machines, this operation is triggered as soon as Computeschedule receives it. +// If the operation fails it returns an *azcore.ResponseError type. +// - locationparameter - The location name. +// - requestBody - The request body +// - options - ScheduledActionsClientVirtualMachinesExecuteDeallocateOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesExecuteDeallocate +// method. +func (client *ScheduledActionsClient) VirtualMachinesExecuteDeallocate(ctx context.Context, locationparameter string, requestBody ExecuteDeallocateRequest, options *ScheduledActionsClientVirtualMachinesExecuteDeallocateOptions) (ScheduledActionsClientVirtualMachinesExecuteDeallocateResponse, error) { + var err error + const operationName = "ScheduledActionsClient.VirtualMachinesExecuteDeallocate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.virtualMachinesExecuteDeallocateCreateRequest(ctx, locationparameter, requestBody, options) + if err != nil { + return ScheduledActionsClientVirtualMachinesExecuteDeallocateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScheduledActionsClientVirtualMachinesExecuteDeallocateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScheduledActionsClientVirtualMachinesExecuteDeallocateResponse{}, err + } + resp, err := client.virtualMachinesExecuteDeallocateHandleResponse(httpResp) + return resp, err +} + +// virtualMachinesExecuteDeallocateCreateRequest creates the VirtualMachinesExecuteDeallocate request. +func (client *ScheduledActionsClient) virtualMachinesExecuteDeallocateCreateRequest(ctx context.Context, locationparameter string, requestBody ExecuteDeallocateRequest, _ *ScheduledActionsClientVirtualMachinesExecuteDeallocateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ComputeSchedule/locations/{locationparameter}/virtualMachinesExecuteDeallocate" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if locationparameter == "" { + return nil, errors.New("parameter locationparameter cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{locationparameter}", url.PathEscape(locationparameter)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, requestBody); err != nil { + return nil, err + } + return req, nil +} + +// virtualMachinesExecuteDeallocateHandleResponse handles the VirtualMachinesExecuteDeallocate response. +func (client *ScheduledActionsClient) virtualMachinesExecuteDeallocateHandleResponse(resp *http.Response) (ScheduledActionsClientVirtualMachinesExecuteDeallocateResponse, error) { + result := ScheduledActionsClientVirtualMachinesExecuteDeallocateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DeallocateResourceOperationResponse); err != nil { + return ScheduledActionsClientVirtualMachinesExecuteDeallocateResponse{}, err + } + return result, nil +} + +// VirtualMachinesExecuteDelete - [PRIVATE PREVIEW]: VirtualMachinesExecuteDelete: Execute delete operation for a batch of +// virtual machines, this operation is triggered as soon as Computeschedule receives it. +// If the operation fails it returns an *azcore.ResponseError type. +// - locationparameter - The location name. +// - requestBody - The request body +// - options - ScheduledActionsClientVirtualMachinesExecuteDeleteOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesExecuteDelete +// method. +func (client *ScheduledActionsClient) VirtualMachinesExecuteDelete(ctx context.Context, locationparameter string, requestBody ExecuteDeleteRequest, options *ScheduledActionsClientVirtualMachinesExecuteDeleteOptions) (ScheduledActionsClientVirtualMachinesExecuteDeleteResponse, error) { + var err error + const operationName = "ScheduledActionsClient.VirtualMachinesExecuteDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.virtualMachinesExecuteDeleteCreateRequest(ctx, locationparameter, requestBody, options) + if err != nil { + return ScheduledActionsClientVirtualMachinesExecuteDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScheduledActionsClientVirtualMachinesExecuteDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScheduledActionsClientVirtualMachinesExecuteDeleteResponse{}, err + } + resp, err := client.virtualMachinesExecuteDeleteHandleResponse(httpResp) + return resp, err +} + +// virtualMachinesExecuteDeleteCreateRequest creates the VirtualMachinesExecuteDelete request. +func (client *ScheduledActionsClient) virtualMachinesExecuteDeleteCreateRequest(ctx context.Context, locationparameter string, requestBody ExecuteDeleteRequest, _ *ScheduledActionsClientVirtualMachinesExecuteDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ComputeSchedule/locations/{locationparameter}/virtualMachinesExecuteDelete" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if locationparameter == "" { + return nil, errors.New("parameter locationparameter cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{locationparameter}", url.PathEscape(locationparameter)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, requestBody); err != nil { + return nil, err + } + return req, nil +} + +// virtualMachinesExecuteDeleteHandleResponse handles the VirtualMachinesExecuteDelete response. +func (client *ScheduledActionsClient) virtualMachinesExecuteDeleteHandleResponse(resp *http.Response) (ScheduledActionsClientVirtualMachinesExecuteDeleteResponse, error) { + result := ScheduledActionsClientVirtualMachinesExecuteDeleteResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DeleteResourceOperationResponse); err != nil { + return ScheduledActionsClientVirtualMachinesExecuteDeleteResponse{}, err + } + return result, nil +} + +// VirtualMachinesExecuteHibernate - VirtualMachinesExecuteHibernate: Execute hibernate operation for a batch of virtual machines, +// this operation is triggered as soon as Computeschedule receives it. +// If the operation fails it returns an *azcore.ResponseError type. +// - locationparameter - The location name. +// - requestBody - The request body +// - options - ScheduledActionsClientVirtualMachinesExecuteHibernateOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesExecuteHibernate +// method. +func (client *ScheduledActionsClient) VirtualMachinesExecuteHibernate(ctx context.Context, locationparameter string, requestBody ExecuteHibernateRequest, options *ScheduledActionsClientVirtualMachinesExecuteHibernateOptions) (ScheduledActionsClientVirtualMachinesExecuteHibernateResponse, error) { + var err error + const operationName = "ScheduledActionsClient.VirtualMachinesExecuteHibernate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.virtualMachinesExecuteHibernateCreateRequest(ctx, locationparameter, requestBody, options) + if err != nil { + return ScheduledActionsClientVirtualMachinesExecuteHibernateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScheduledActionsClientVirtualMachinesExecuteHibernateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScheduledActionsClientVirtualMachinesExecuteHibernateResponse{}, err + } + resp, err := client.virtualMachinesExecuteHibernateHandleResponse(httpResp) + return resp, err +} + +// virtualMachinesExecuteHibernateCreateRequest creates the VirtualMachinesExecuteHibernate request. +func (client *ScheduledActionsClient) virtualMachinesExecuteHibernateCreateRequest(ctx context.Context, locationparameter string, requestBody ExecuteHibernateRequest, _ *ScheduledActionsClientVirtualMachinesExecuteHibernateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ComputeSchedule/locations/{locationparameter}/virtualMachinesExecuteHibernate" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if locationparameter == "" { + return nil, errors.New("parameter locationparameter cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{locationparameter}", url.PathEscape(locationparameter)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, requestBody); err != nil { + return nil, err + } + return req, nil +} + +// virtualMachinesExecuteHibernateHandleResponse handles the VirtualMachinesExecuteHibernate response. +func (client *ScheduledActionsClient) virtualMachinesExecuteHibernateHandleResponse(resp *http.Response) (ScheduledActionsClientVirtualMachinesExecuteHibernateResponse, error) { + result := ScheduledActionsClientVirtualMachinesExecuteHibernateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.HibernateResourceOperationResponse); err != nil { + return ScheduledActionsClientVirtualMachinesExecuteHibernateResponse{}, err + } + return result, nil +} + +// VirtualMachinesExecuteStart - VirtualMachinesExecuteStart: Execute start operation for a batch of virtual machines, this +// operation is triggered as soon as Computeschedule receives it. +// If the operation fails it returns an *azcore.ResponseError type. +// - locationparameter - The location name. +// - requestBody - The request body +// - options - ScheduledActionsClientVirtualMachinesExecuteStartOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesExecuteStart +// method. +func (client *ScheduledActionsClient) VirtualMachinesExecuteStart(ctx context.Context, locationparameter string, requestBody ExecuteStartRequest, options *ScheduledActionsClientVirtualMachinesExecuteStartOptions) (ScheduledActionsClientVirtualMachinesExecuteStartResponse, error) { + var err error + const operationName = "ScheduledActionsClient.VirtualMachinesExecuteStart" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.virtualMachinesExecuteStartCreateRequest(ctx, locationparameter, requestBody, options) + if err != nil { + return ScheduledActionsClientVirtualMachinesExecuteStartResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScheduledActionsClientVirtualMachinesExecuteStartResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScheduledActionsClientVirtualMachinesExecuteStartResponse{}, err + } + resp, err := client.virtualMachinesExecuteStartHandleResponse(httpResp) + return resp, err +} + +// virtualMachinesExecuteStartCreateRequest creates the VirtualMachinesExecuteStart request. +func (client *ScheduledActionsClient) virtualMachinesExecuteStartCreateRequest(ctx context.Context, locationparameter string, requestBody ExecuteStartRequest, _ *ScheduledActionsClientVirtualMachinesExecuteStartOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ComputeSchedule/locations/{locationparameter}/virtualMachinesExecuteStart" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if locationparameter == "" { + return nil, errors.New("parameter locationparameter cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{locationparameter}", url.PathEscape(locationparameter)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, requestBody); err != nil { + return nil, err + } + return req, nil +} + +// virtualMachinesExecuteStartHandleResponse handles the VirtualMachinesExecuteStart response. +func (client *ScheduledActionsClient) virtualMachinesExecuteStartHandleResponse(resp *http.Response) (ScheduledActionsClientVirtualMachinesExecuteStartResponse, error) { + result := ScheduledActionsClientVirtualMachinesExecuteStartResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.StartResourceOperationResponse); err != nil { + return ScheduledActionsClientVirtualMachinesExecuteStartResponse{}, err + } + return result, nil +} + +// VirtualMachinesGetOperationErrors - VirtualMachinesGetOperationErrors: Get error details on operation errors (like transient +// errors encountered, additional logs) if they exist. +// If the operation fails it returns an *azcore.ResponseError type. +// - locationparameter - The location name. +// - requestBody - The request body +// - options - ScheduledActionsClientVirtualMachinesGetOperationErrorsOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesGetOperationErrors +// method. +func (client *ScheduledActionsClient) VirtualMachinesGetOperationErrors(ctx context.Context, locationparameter string, requestBody GetOperationErrorsRequest, options *ScheduledActionsClientVirtualMachinesGetOperationErrorsOptions) (ScheduledActionsClientVirtualMachinesGetOperationErrorsResponse, error) { + var err error + const operationName = "ScheduledActionsClient.VirtualMachinesGetOperationErrors" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.virtualMachinesGetOperationErrorsCreateRequest(ctx, locationparameter, requestBody, options) + if err != nil { + return ScheduledActionsClientVirtualMachinesGetOperationErrorsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScheduledActionsClientVirtualMachinesGetOperationErrorsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScheduledActionsClientVirtualMachinesGetOperationErrorsResponse{}, err + } + resp, err := client.virtualMachinesGetOperationErrorsHandleResponse(httpResp) + return resp, err +} + +// virtualMachinesGetOperationErrorsCreateRequest creates the VirtualMachinesGetOperationErrors request. +func (client *ScheduledActionsClient) virtualMachinesGetOperationErrorsCreateRequest(ctx context.Context, locationparameter string, requestBody GetOperationErrorsRequest, _ *ScheduledActionsClientVirtualMachinesGetOperationErrorsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ComputeSchedule/locations/{locationparameter}/virtualMachinesGetOperationErrors" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if locationparameter == "" { + return nil, errors.New("parameter locationparameter cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{locationparameter}", url.PathEscape(locationparameter)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, requestBody); err != nil { + return nil, err + } + return req, nil +} + +// virtualMachinesGetOperationErrorsHandleResponse handles the VirtualMachinesGetOperationErrors response. +func (client *ScheduledActionsClient) virtualMachinesGetOperationErrorsHandleResponse(resp *http.Response) (ScheduledActionsClientVirtualMachinesGetOperationErrorsResponse, error) { + result := ScheduledActionsClientVirtualMachinesGetOperationErrorsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.GetOperationErrorsResponse); err != nil { + return ScheduledActionsClientVirtualMachinesGetOperationErrorsResponse{}, err + } + return result, nil +} + +// VirtualMachinesGetOperationStatus - VirtualMachinesGetOperationStatus: Polling endpoint to read status of operations performed +// on virtual machines +// If the operation fails it returns an *azcore.ResponseError type. +// - locationparameter - The location name. +// - requestBody - The request body +// - options - ScheduledActionsClientVirtualMachinesGetOperationStatusOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesGetOperationStatus +// method. +func (client *ScheduledActionsClient) VirtualMachinesGetOperationStatus(ctx context.Context, locationparameter string, requestBody GetOperationStatusRequest, options *ScheduledActionsClientVirtualMachinesGetOperationStatusOptions) (ScheduledActionsClientVirtualMachinesGetOperationStatusResponse, error) { + var err error + const operationName = "ScheduledActionsClient.VirtualMachinesGetOperationStatus" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.virtualMachinesGetOperationStatusCreateRequest(ctx, locationparameter, requestBody, options) + if err != nil { + return ScheduledActionsClientVirtualMachinesGetOperationStatusResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScheduledActionsClientVirtualMachinesGetOperationStatusResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScheduledActionsClientVirtualMachinesGetOperationStatusResponse{}, err + } + resp, err := client.virtualMachinesGetOperationStatusHandleResponse(httpResp) + return resp, err +} + +// virtualMachinesGetOperationStatusCreateRequest creates the VirtualMachinesGetOperationStatus request. +func (client *ScheduledActionsClient) virtualMachinesGetOperationStatusCreateRequest(ctx context.Context, locationparameter string, requestBody GetOperationStatusRequest, _ *ScheduledActionsClientVirtualMachinesGetOperationStatusOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ComputeSchedule/locations/{locationparameter}/virtualMachinesGetOperationStatus" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if locationparameter == "" { + return nil, errors.New("parameter locationparameter cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{locationparameter}", url.PathEscape(locationparameter)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, requestBody); err != nil { + return nil, err + } + return req, nil +} + +// virtualMachinesGetOperationStatusHandleResponse handles the VirtualMachinesGetOperationStatus response. +func (client *ScheduledActionsClient) virtualMachinesGetOperationStatusHandleResponse(resp *http.Response) (ScheduledActionsClientVirtualMachinesGetOperationStatusResponse, error) { + result := ScheduledActionsClientVirtualMachinesGetOperationStatusResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.GetOperationStatusResponse); err != nil { + return ScheduledActionsClientVirtualMachinesGetOperationStatusResponse{}, err + } + return result, nil +} + +// VirtualMachinesSubmitDeallocate - VirtualMachinesSubmitDeallocate: Schedule deallocate operation for a batch of virtual +// machines at datetime in future. +// If the operation fails it returns an *azcore.ResponseError type. +// - locationparameter - The location name. +// - requestBody - The request body +// - options - ScheduledActionsClientVirtualMachinesSubmitDeallocateOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesSubmitDeallocate +// method. +func (client *ScheduledActionsClient) VirtualMachinesSubmitDeallocate(ctx context.Context, locationparameter string, requestBody SubmitDeallocateRequest, options *ScheduledActionsClientVirtualMachinesSubmitDeallocateOptions) (ScheduledActionsClientVirtualMachinesSubmitDeallocateResponse, error) { + var err error + const operationName = "ScheduledActionsClient.VirtualMachinesSubmitDeallocate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.virtualMachinesSubmitDeallocateCreateRequest(ctx, locationparameter, requestBody, options) + if err != nil { + return ScheduledActionsClientVirtualMachinesSubmitDeallocateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScheduledActionsClientVirtualMachinesSubmitDeallocateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScheduledActionsClientVirtualMachinesSubmitDeallocateResponse{}, err + } + resp, err := client.virtualMachinesSubmitDeallocateHandleResponse(httpResp) + return resp, err +} + +// virtualMachinesSubmitDeallocateCreateRequest creates the VirtualMachinesSubmitDeallocate request. +func (client *ScheduledActionsClient) virtualMachinesSubmitDeallocateCreateRequest(ctx context.Context, locationparameter string, requestBody SubmitDeallocateRequest, _ *ScheduledActionsClientVirtualMachinesSubmitDeallocateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ComputeSchedule/locations/{locationparameter}/virtualMachinesSubmitDeallocate" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if locationparameter == "" { + return nil, errors.New("parameter locationparameter cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{locationparameter}", url.PathEscape(locationparameter)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, requestBody); err != nil { + return nil, err + } + return req, nil +} + +// virtualMachinesSubmitDeallocateHandleResponse handles the VirtualMachinesSubmitDeallocate response. +func (client *ScheduledActionsClient) virtualMachinesSubmitDeallocateHandleResponse(resp *http.Response) (ScheduledActionsClientVirtualMachinesSubmitDeallocateResponse, error) { + result := ScheduledActionsClientVirtualMachinesSubmitDeallocateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DeallocateResourceOperationResponse); err != nil { + return ScheduledActionsClientVirtualMachinesSubmitDeallocateResponse{}, err + } + return result, nil +} + +// VirtualMachinesSubmitHibernate - VirtualMachinesSubmitHibernate: Schedule hibernate operation for a batch of virtual machines +// at datetime in future. +// If the operation fails it returns an *azcore.ResponseError type. +// - locationparameter - The location name. +// - requestBody - The request body +// - options - ScheduledActionsClientVirtualMachinesSubmitHibernateOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesSubmitHibernate +// method. +func (client *ScheduledActionsClient) VirtualMachinesSubmitHibernate(ctx context.Context, locationparameter string, requestBody SubmitHibernateRequest, options *ScheduledActionsClientVirtualMachinesSubmitHibernateOptions) (ScheduledActionsClientVirtualMachinesSubmitHibernateResponse, error) { + var err error + const operationName = "ScheduledActionsClient.VirtualMachinesSubmitHibernate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.virtualMachinesSubmitHibernateCreateRequest(ctx, locationparameter, requestBody, options) + if err != nil { + return ScheduledActionsClientVirtualMachinesSubmitHibernateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScheduledActionsClientVirtualMachinesSubmitHibernateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScheduledActionsClientVirtualMachinesSubmitHibernateResponse{}, err + } + resp, err := client.virtualMachinesSubmitHibernateHandleResponse(httpResp) + return resp, err +} + +// virtualMachinesSubmitHibernateCreateRequest creates the VirtualMachinesSubmitHibernate request. +func (client *ScheduledActionsClient) virtualMachinesSubmitHibernateCreateRequest(ctx context.Context, locationparameter string, requestBody SubmitHibernateRequest, _ *ScheduledActionsClientVirtualMachinesSubmitHibernateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ComputeSchedule/locations/{locationparameter}/virtualMachinesSubmitHibernate" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if locationparameter == "" { + return nil, errors.New("parameter locationparameter cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{locationparameter}", url.PathEscape(locationparameter)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, requestBody); err != nil { + return nil, err + } + return req, nil +} + +// virtualMachinesSubmitHibernateHandleResponse handles the VirtualMachinesSubmitHibernate response. +func (client *ScheduledActionsClient) virtualMachinesSubmitHibernateHandleResponse(resp *http.Response) (ScheduledActionsClientVirtualMachinesSubmitHibernateResponse, error) { + result := ScheduledActionsClientVirtualMachinesSubmitHibernateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.HibernateResourceOperationResponse); err != nil { + return ScheduledActionsClientVirtualMachinesSubmitHibernateResponse{}, err + } + return result, nil +} + +// VirtualMachinesSubmitStart - VirtualMachinesSubmitStart: Schedule start operation for a batch of virtual machines at datetime +// in future. +// If the operation fails it returns an *azcore.ResponseError type. +// - locationparameter - The location name. +// - requestBody - The request body +// - options - ScheduledActionsClientVirtualMachinesSubmitStartOptions contains the optional parameters for the ScheduledActionsClient.VirtualMachinesSubmitStart +// method. +func (client *ScheduledActionsClient) VirtualMachinesSubmitStart(ctx context.Context, locationparameter string, requestBody SubmitStartRequest, options *ScheduledActionsClientVirtualMachinesSubmitStartOptions) (ScheduledActionsClientVirtualMachinesSubmitStartResponse, error) { + var err error + const operationName = "ScheduledActionsClient.VirtualMachinesSubmitStart" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.virtualMachinesSubmitStartCreateRequest(ctx, locationparameter, requestBody, options) + if err != nil { + return ScheduledActionsClientVirtualMachinesSubmitStartResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ScheduledActionsClientVirtualMachinesSubmitStartResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ScheduledActionsClientVirtualMachinesSubmitStartResponse{}, err + } + resp, err := client.virtualMachinesSubmitStartHandleResponse(httpResp) + return resp, err +} + +// virtualMachinesSubmitStartCreateRequest creates the VirtualMachinesSubmitStart request. +func (client *ScheduledActionsClient) virtualMachinesSubmitStartCreateRequest(ctx context.Context, locationparameter string, requestBody SubmitStartRequest, _ *ScheduledActionsClientVirtualMachinesSubmitStartOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ComputeSchedule/locations/{locationparameter}/virtualMachinesSubmitStart" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if locationparameter == "" { + return nil, errors.New("parameter locationparameter cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{locationparameter}", url.PathEscape(locationparameter)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260415Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, requestBody); err != nil { + return nil, err + } + return req, nil +} + +// virtualMachinesSubmitStartHandleResponse handles the VirtualMachinesSubmitStart response. +func (client *ScheduledActionsClient) virtualMachinesSubmitStartHandleResponse(resp *http.Response) (ScheduledActionsClientVirtualMachinesSubmitStartResponse, error) { + result := ScheduledActionsClientVirtualMachinesSubmitStartResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.StartResourceOperationResponse); err != nil { + return ScheduledActionsClientVirtualMachinesSubmitStartResponse{}, err + } + return result, nil +} diff --git a/test/local/armcomputeschedule/zz_version.go b/test/local/armcomputeschedule/zz_version.go new file mode 100644 index 000000000000..4ceacfc1f817 --- /dev/null +++ b/test/local/armcomputeschedule/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package armcomputeschedule + +const ( + moduleName = "armcomputeschedule" + moduleVersion = "v0.1.0" +) diff --git a/test/local/armcontainerorchestratorruntime/LICENSE.txt b/test/local/armcontainerorchestratorruntime/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/local/armcontainerorchestratorruntime/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/local/armcontainerorchestratorruntime/fake/zz_bgppeers_server.go b/test/local/armcontainerorchestratorruntime/fake/zz_bgppeers_server.go new file mode 100644 index 000000000000..97938732f355 --- /dev/null +++ b/test/local/armcontainerorchestratorruntime/fake/zz_bgppeers_server.go @@ -0,0 +1,260 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcontainerorchestratorruntime" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// BgpPeersServer is a fake server for instances of the armcontainerorchestratorruntime.BgpPeersClient type. +type BgpPeersServer struct { + // BeginCreateOrUpdate is the fake for method BgpPeersClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceURI string, bgpPeerName string, resource armcontainerorchestratorruntime.BgpPeer, options *armcontainerorchestratorruntime.BgpPeersClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armcontainerorchestratorruntime.BgpPeersClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method BgpPeersClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceURI string, bgpPeerName string, options *armcontainerorchestratorruntime.BgpPeersClientDeleteOptions) (resp azfake.Responder[armcontainerorchestratorruntime.BgpPeersClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method BgpPeersClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceURI string, bgpPeerName string, options *armcontainerorchestratorruntime.BgpPeersClientGetOptions) (resp azfake.Responder[armcontainerorchestratorruntime.BgpPeersClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method BgpPeersClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceURI string, options *armcontainerorchestratorruntime.BgpPeersClientListOptions) (resp azfake.PagerResponder[armcontainerorchestratorruntime.BgpPeersClientListResponse]) +} + +// NewBgpPeersServerTransport creates a new instance of BgpPeersServerTransport with the provided implementation. +// The returned BgpPeersServerTransport instance is connected to an instance of armcontainerorchestratorruntime.BgpPeersClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewBgpPeersServerTransport(srv *BgpPeersServer) *BgpPeersServerTransport { + return &BgpPeersServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armcontainerorchestratorruntime.BgpPeersClientCreateOrUpdateResponse]](), + newListPager: newTracker[azfake.PagerResponder[armcontainerorchestratorruntime.BgpPeersClientListResponse]](), + } +} + +// BgpPeersServerTransport connects instances of armcontainerorchestratorruntime.BgpPeersClient to instances of BgpPeersServer. +// Don't use this type directly, use NewBgpPeersServerTransport instead. +type BgpPeersServerTransport struct { + srv *BgpPeersServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armcontainerorchestratorruntime.BgpPeersClientCreateOrUpdateResponse]] + newListPager *tracker[azfake.PagerResponder[armcontainerorchestratorruntime.BgpPeersClientListResponse]] +} + +// Do implements the policy.Transporter interface for BgpPeersServerTransport. +func (b *BgpPeersServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return b.dispatchToMethodFake(req, method) +} + +func (b *BgpPeersServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if bgpPeersServerTransportInterceptor != nil { + res.resp, res.err, intercepted = bgpPeersServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "BgpPeersClient.BeginCreateOrUpdate": + res.resp, res.err = b.dispatchBeginCreateOrUpdate(req) + case "BgpPeersClient.Delete": + res.resp, res.err = b.dispatchDelete(req) + case "BgpPeersClient.Get": + res.resp, res.err = b.dispatchGet(req) + case "BgpPeersClient.NewListPager": + res.resp, res.err = b.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (b *BgpPeersServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if b.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := b.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.KubernetesRuntime/bgpPeers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcontainerorchestratorruntime.BgpPeer](req) + if err != nil { + return nil, err + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + bgpPeerNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("bgpPeerName")]) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.BeginCreateOrUpdate(req.Context(), resourceURIParam, bgpPeerNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + b.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + b.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + b.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (b *BgpPeersServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if b.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.KubernetesRuntime/bgpPeers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + bgpPeerNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("bgpPeerName")]) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.Delete(req.Context(), resourceURIParam, bgpPeerNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BgpPeersServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if b.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.KubernetesRuntime/bgpPeers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + bgpPeerNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("bgpPeerName")]) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.Get(req.Context(), resourceURIParam, bgpPeerNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BgpPeer, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BgpPeersServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if b.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := b.newListPager.get(req) + if newListPager == nil { + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.KubernetesRuntime/bgpPeers` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + resp := b.srv.NewListPager(resourceURIParam, nil) + newListPager = &resp + b.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcontainerorchestratorruntime.BgpPeersClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + b.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + b.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to BgpPeersServerTransport +var bgpPeersServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcontainerorchestratorruntime/fake/zz_internal.go b/test/local/armcontainerorchestratorruntime/fake/zz_internal.go new file mode 100644 index 000000000000..590b4d743e97 --- /dev/null +++ b/test/local/armcontainerorchestratorruntime/fake/zz_internal.go @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/local/armcontainerorchestratorruntime/fake/zz_loadbalancers_server.go b/test/local/armcontainerorchestratorruntime/fake/zz_loadbalancers_server.go new file mode 100644 index 000000000000..160a0014a4e5 --- /dev/null +++ b/test/local/armcontainerorchestratorruntime/fake/zz_loadbalancers_server.go @@ -0,0 +1,260 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcontainerorchestratorruntime" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// LoadBalancersServer is a fake server for instances of the armcontainerorchestratorruntime.LoadBalancersClient type. +type LoadBalancersServer struct { + // BeginCreateOrUpdate is the fake for method LoadBalancersClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceURI string, loadBalancerName string, resource armcontainerorchestratorruntime.LoadBalancer, options *armcontainerorchestratorruntime.LoadBalancersClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armcontainerorchestratorruntime.LoadBalancersClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method LoadBalancersClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceURI string, loadBalancerName string, options *armcontainerorchestratorruntime.LoadBalancersClientDeleteOptions) (resp azfake.Responder[armcontainerorchestratorruntime.LoadBalancersClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method LoadBalancersClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceURI string, loadBalancerName string, options *armcontainerorchestratorruntime.LoadBalancersClientGetOptions) (resp azfake.Responder[armcontainerorchestratorruntime.LoadBalancersClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method LoadBalancersClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceURI string, options *armcontainerorchestratorruntime.LoadBalancersClientListOptions) (resp azfake.PagerResponder[armcontainerorchestratorruntime.LoadBalancersClientListResponse]) +} + +// NewLoadBalancersServerTransport creates a new instance of LoadBalancersServerTransport with the provided implementation. +// The returned LoadBalancersServerTransport instance is connected to an instance of armcontainerorchestratorruntime.LoadBalancersClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewLoadBalancersServerTransport(srv *LoadBalancersServer) *LoadBalancersServerTransport { + return &LoadBalancersServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armcontainerorchestratorruntime.LoadBalancersClientCreateOrUpdateResponse]](), + newListPager: newTracker[azfake.PagerResponder[armcontainerorchestratorruntime.LoadBalancersClientListResponse]](), + } +} + +// LoadBalancersServerTransport connects instances of armcontainerorchestratorruntime.LoadBalancersClient to instances of LoadBalancersServer. +// Don't use this type directly, use NewLoadBalancersServerTransport instead. +type LoadBalancersServerTransport struct { + srv *LoadBalancersServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armcontainerorchestratorruntime.LoadBalancersClientCreateOrUpdateResponse]] + newListPager *tracker[azfake.PagerResponder[armcontainerorchestratorruntime.LoadBalancersClientListResponse]] +} + +// Do implements the policy.Transporter interface for LoadBalancersServerTransport. +func (l *LoadBalancersServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return l.dispatchToMethodFake(req, method) +} + +func (l *LoadBalancersServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if loadBalancersServerTransportInterceptor != nil { + res.resp, res.err, intercepted = loadBalancersServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "LoadBalancersClient.BeginCreateOrUpdate": + res.resp, res.err = l.dispatchBeginCreateOrUpdate(req) + case "LoadBalancersClient.Delete": + res.resp, res.err = l.dispatchDelete(req) + case "LoadBalancersClient.Get": + res.resp, res.err = l.dispatchGet(req) + case "LoadBalancersClient.NewListPager": + res.resp, res.err = l.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (l *LoadBalancersServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if l.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := l.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.KubernetesRuntime/loadBalancers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcontainerorchestratorruntime.LoadBalancer](req) + if err != nil { + return nil, err + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + loadBalancerNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("loadBalancerName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.BeginCreateOrUpdate(req.Context(), resourceURIParam, loadBalancerNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + l.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + l.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + l.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (l *LoadBalancersServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if l.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.KubernetesRuntime/loadBalancers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + loadBalancerNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("loadBalancerName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.Delete(req.Context(), resourceURIParam, loadBalancerNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (l *LoadBalancersServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if l.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.KubernetesRuntime/loadBalancers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + loadBalancerNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("loadBalancerName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.Get(req.Context(), resourceURIParam, loadBalancerNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).LoadBalancer, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (l *LoadBalancersServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if l.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := l.newListPager.get(req) + if newListPager == nil { + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.KubernetesRuntime/loadBalancers` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + resp := l.srv.NewListPager(resourceURIParam, nil) + newListPager = &resp + l.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcontainerorchestratorruntime.LoadBalancersClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + l.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + l.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to LoadBalancersServerTransport +var loadBalancersServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcontainerorchestratorruntime/fake/zz_operations_server.go b/test/local/armcontainerorchestratorruntime/fake/zz_operations_server.go new file mode 100644 index 000000000000..06b5dae9ff85 --- /dev/null +++ b/test/local/armcontainerorchestratorruntime/fake/zz_operations_server.go @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcontainerorchestratorruntime" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "slices" +) + +// OperationsServer is a fake server for instances of the armcontainerorchestratorruntime.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armcontainerorchestratorruntime.OperationsClientListOptions) (resp azfake.PagerResponder[armcontainerorchestratorruntime.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of armcontainerorchestratorruntime.OperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOperationsServerTransport(srv *OperationsServer) *OperationsServerTransport { + return &OperationsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armcontainerorchestratorruntime.OperationsClientListResponse]](), + } +} + +// OperationsServerTransport connects instances of armcontainerorchestratorruntime.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[armcontainerorchestratorruntime.OperationsClientListResponse]] +} + +// Do implements the policy.Transporter interface for OperationsServerTransport. +func (o *OperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if operationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = operationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OperationsClient.NewListPager": + res.resp, res.err = o.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OperationsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := o.newListPager.get(req) + if newListPager == nil { + resp := o.srv.NewListPager(nil) + newListPager = &resp + o.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcontainerorchestratorruntime.OperationsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + o.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + o.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OperationsServerTransport +var operationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcontainerorchestratorruntime/fake/zz_server_factory.go b/test/local/armcontainerorchestratorruntime/fake/zz_server_factory.go new file mode 100644 index 000000000000..054ea82fddd3 --- /dev/null +++ b/test/local/armcontainerorchestratorruntime/fake/zz_server_factory.go @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armcontainerorchestratorruntime.ClientFactory type. +type ServerFactory struct { + // BgpPeersServer contains the fakes for client BgpPeersClient + BgpPeersServer BgpPeersServer + + // LoadBalancersServer contains the fakes for client LoadBalancersClient + LoadBalancersServer LoadBalancersServer + + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer + + // ServicesServer contains the fakes for client ServicesClient + ServicesServer ServicesServer + + // StorageClassServer contains the fakes for client StorageClassClient + StorageClassServer StorageClassServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armcontainerorchestratorruntime.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of armcontainerorchestratorruntime.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trBgpPeersServer *BgpPeersServerTransport + trLoadBalancersServer *LoadBalancersServerTransport + trOperationsServer *OperationsServerTransport + trServicesServer *ServicesServerTransport + trStorageClassServer *StorageClassServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "BgpPeersClient": + initServer(&s.trMu, &s.trBgpPeersServer, func() *BgpPeersServerTransport { return NewBgpPeersServerTransport(&s.srv.BgpPeersServer) }) + resp, err = s.trBgpPeersServer.Do(req) + case "LoadBalancersClient": + initServer(&s.trMu, &s.trLoadBalancersServer, func() *LoadBalancersServerTransport { + return NewLoadBalancersServerTransport(&s.srv.LoadBalancersServer) + }) + resp, err = s.trLoadBalancersServer.Do(req) + case "OperationsClient": + initServer(&s.trMu, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + resp, err = s.trOperationsServer.Do(req) + case "ServicesClient": + initServer(&s.trMu, &s.trServicesServer, func() *ServicesServerTransport { return NewServicesServerTransport(&s.srv.ServicesServer) }) + resp, err = s.trServicesServer.Do(req) + case "StorageClassClient": + initServer(&s.trMu, &s.trStorageClassServer, func() *StorageClassServerTransport { return NewStorageClassServerTransport(&s.srv.StorageClassServer) }) + resp, err = s.trStorageClassServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} diff --git a/test/local/armcontainerorchestratorruntime/fake/zz_services_server.go b/test/local/armcontainerorchestratorruntime/fake/zz_services_server.go new file mode 100644 index 000000000000..0801941e915e --- /dev/null +++ b/test/local/armcontainerorchestratorruntime/fake/zz_services_server.go @@ -0,0 +1,247 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcontainerorchestratorruntime" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// ServicesServer is a fake server for instances of the armcontainerorchestratorruntime.ServicesClient type. +type ServicesServer struct { + // CreateOrUpdate is the fake for method ServicesClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceURI string, serviceName string, resource armcontainerorchestratorruntime.ServiceResource, options *armcontainerorchestratorruntime.ServicesClientCreateOrUpdateOptions) (resp azfake.Responder[armcontainerorchestratorruntime.ServicesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method ServicesClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceURI string, serviceName string, options *armcontainerorchestratorruntime.ServicesClientDeleteOptions) (resp azfake.Responder[armcontainerorchestratorruntime.ServicesClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method ServicesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceURI string, serviceName string, options *armcontainerorchestratorruntime.ServicesClientGetOptions) (resp azfake.Responder[armcontainerorchestratorruntime.ServicesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method ServicesClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceURI string, options *armcontainerorchestratorruntime.ServicesClientListOptions) (resp azfake.PagerResponder[armcontainerorchestratorruntime.ServicesClientListResponse]) +} + +// NewServicesServerTransport creates a new instance of ServicesServerTransport with the provided implementation. +// The returned ServicesServerTransport instance is connected to an instance of armcontainerorchestratorruntime.ServicesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServicesServerTransport(srv *ServicesServer) *ServicesServerTransport { + return &ServicesServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armcontainerorchestratorruntime.ServicesClientListResponse]](), + } +} + +// ServicesServerTransport connects instances of armcontainerorchestratorruntime.ServicesClient to instances of ServicesServer. +// Don't use this type directly, use NewServicesServerTransport instead. +type ServicesServerTransport struct { + srv *ServicesServer + newListPager *tracker[azfake.PagerResponder[armcontainerorchestratorruntime.ServicesClientListResponse]] +} + +// Do implements the policy.Transporter interface for ServicesServerTransport. +func (s *ServicesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ServicesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if servicesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = servicesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ServicesClient.CreateOrUpdate": + res.resp, res.err = s.dispatchCreateOrUpdate(req) + case "ServicesClient.Delete": + res.resp, res.err = s.dispatchDelete(req) + case "ServicesClient.Get": + res.resp, res.err = s.dispatchGet(req) + case "ServicesClient.NewListPager": + res.resp, res.err = s.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ServicesServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if s.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.KubernetesRuntime/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcontainerorchestratorruntime.ServiceResource](req) + if err != nil { + return nil, err + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.CreateOrUpdate(req.Context(), resourceURIParam, serviceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ServiceResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServicesServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if s.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.KubernetesRuntime/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Delete(req.Context(), resourceURIParam, serviceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServicesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if s.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.KubernetesRuntime/services/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + serviceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("serviceName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Get(req.Context(), resourceURIParam, serviceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ServiceResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServicesServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if s.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := s.newListPager.get(req) + if newListPager == nil { + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.KubernetesRuntime/services` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + resp := s.srv.NewListPager(resourceURIParam, nil) + newListPager = &resp + s.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcontainerorchestratorruntime.ServicesClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + s.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + s.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ServicesServerTransport +var servicesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcontainerorchestratorruntime/fake/zz_storageclass_server.go b/test/local/armcontainerorchestratorruntime/fake/zz_storageclass_server.go new file mode 100644 index 000000000000..ee72c4a76699 --- /dev/null +++ b/test/local/armcontainerorchestratorruntime/fake/zz_storageclass_server.go @@ -0,0 +1,329 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armcontainerorchestratorruntime" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// StorageClassServer is a fake server for instances of the armcontainerorchestratorruntime.StorageClassClient type. +type StorageClassServer struct { + // BeginCreateOrUpdate is the fake for method StorageClassClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceURI string, storageClassName string, resource armcontainerorchestratorruntime.StorageClassResource, options *armcontainerorchestratorruntime.StorageClassClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armcontainerorchestratorruntime.StorageClassClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method StorageClassClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceURI string, storageClassName string, options *armcontainerorchestratorruntime.StorageClassClientBeginDeleteOptions) (resp azfake.PollerResponder[armcontainerorchestratorruntime.StorageClassClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method StorageClassClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceURI string, storageClassName string, options *armcontainerorchestratorruntime.StorageClassClientGetOptions) (resp azfake.Responder[armcontainerorchestratorruntime.StorageClassClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method StorageClassClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceURI string, options *armcontainerorchestratorruntime.StorageClassClientListOptions) (resp azfake.PagerResponder[armcontainerorchestratorruntime.StorageClassClientListResponse]) + + // BeginUpdate is the fake for method StorageClassClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceURI string, storageClassName string, properties armcontainerorchestratorruntime.StorageClassResourceUpdate, options *armcontainerorchestratorruntime.StorageClassClientBeginUpdateOptions) (resp azfake.PollerResponder[armcontainerorchestratorruntime.StorageClassClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewStorageClassServerTransport creates a new instance of StorageClassServerTransport with the provided implementation. +// The returned StorageClassServerTransport instance is connected to an instance of armcontainerorchestratorruntime.StorageClassClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewStorageClassServerTransport(srv *StorageClassServer) *StorageClassServerTransport { + return &StorageClassServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armcontainerorchestratorruntime.StorageClassClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armcontainerorchestratorruntime.StorageClassClientDeleteResponse]](), + newListPager: newTracker[azfake.PagerResponder[armcontainerorchestratorruntime.StorageClassClientListResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armcontainerorchestratorruntime.StorageClassClientUpdateResponse]](), + } +} + +// StorageClassServerTransport connects instances of armcontainerorchestratorruntime.StorageClassClient to instances of StorageClassServer. +// Don't use this type directly, use NewStorageClassServerTransport instead. +type StorageClassServerTransport struct { + srv *StorageClassServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armcontainerorchestratorruntime.StorageClassClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armcontainerorchestratorruntime.StorageClassClientDeleteResponse]] + newListPager *tracker[azfake.PagerResponder[armcontainerorchestratorruntime.StorageClassClientListResponse]] + beginUpdate *tracker[azfake.PollerResponder[armcontainerorchestratorruntime.StorageClassClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for StorageClassServerTransport. +func (s *StorageClassServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *StorageClassServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if storageClassServerTransportInterceptor != nil { + res.resp, res.err, intercepted = storageClassServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "StorageClassClient.BeginCreateOrUpdate": + res.resp, res.err = s.dispatchBeginCreateOrUpdate(req) + case "StorageClassClient.BeginDelete": + res.resp, res.err = s.dispatchBeginDelete(req) + case "StorageClassClient.Get": + res.resp, res.err = s.dispatchGet(req) + case "StorageClassClient.NewListPager": + res.resp, res.err = s.dispatchNewListPager(req) + case "StorageClassClient.BeginUpdate": + res.resp, res.err = s.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *StorageClassServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if s.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := s.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.KubernetesRuntime/storageClasses/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcontainerorchestratorruntime.StorageClassResource](req) + if err != nil { + return nil, err + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + storageClassNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("storageClassName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.BeginCreateOrUpdate(req.Context(), resourceURIParam, storageClassNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + s.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + s.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + s.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (s *StorageClassServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if s.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := s.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.KubernetesRuntime/storageClasses/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + storageClassNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("storageClassName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.BeginDelete(req.Context(), resourceURIParam, storageClassNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + s.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + s.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + s.beginDelete.remove(req) + } + + return resp, nil +} + +func (s *StorageClassServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if s.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.KubernetesRuntime/storageClasses/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + storageClassNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("storageClassName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Get(req.Context(), resourceURIParam, storageClassNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).StorageClassResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *StorageClassServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if s.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := s.newListPager.get(req) + if newListPager == nil { + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.KubernetesRuntime/storageClasses` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + resp := s.srv.NewListPager(resourceURIParam, nil) + newListPager = &resp + s.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armcontainerorchestratorruntime.StorageClassClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + s.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + s.newListPager.remove(req) + } + return resp, nil +} + +func (s *StorageClassServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if s.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := s.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.KubernetesRuntime/storageClasses/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armcontainerorchestratorruntime.StorageClassResourceUpdate](req) + if err != nil { + return nil, err + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + storageClassNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("storageClassName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.BeginUpdate(req.Context(), resourceURIParam, storageClassNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + s.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + s.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + s.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to StorageClassServerTransport +var storageClassServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armcontainerorchestratorruntime/go.mod b/test/local/armcontainerorchestratorruntime/go.mod new file mode 100644 index 000000000000..a288b26562f9 --- /dev/null +++ b/test/local/armcontainerorchestratorruntime/go.mod @@ -0,0 +1,11 @@ +module armcontainerorchestratorruntime + +go 1.25.0 + +require github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect +) diff --git a/test/local/armcontainerorchestratorruntime/go.sum b/test/local/armcontainerorchestratorruntime/go.sum new file mode 100644 index 000000000000..3fdb64caf441 --- /dev/null +++ b/test/local/armcontainerorchestratorruntime/go.sum @@ -0,0 +1,16 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/local/armcontainerorchestratorruntime/testdata/_metadata.json b/test/local/armcontainerorchestratorruntime/testdata/_metadata.json new file mode 100644 index 000000000000..57f87f70ef14 --- /dev/null +++ b/test/local/armcontainerorchestratorruntime/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Microsoft.KubernetesRuntime": "2024-03-01" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/local/armcontainerorchestratorruntime/zz_bgppeers_client.go b/test/local/armcontainerorchestratorruntime/zz_bgppeers_client.go new file mode 100644 index 000000000000..97dbd9f1a0d8 --- /dev/null +++ b/test/local/armcontainerorchestratorruntime/zz_bgppeers_client.go @@ -0,0 +1,271 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcontainerorchestratorruntime + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// BgpPeersClient contains the methods for the BgpPeers group. +// Don't use this type directly, use NewBgpPeersClient() instead. +// +// Generated from API version 2024-03-01 +type BgpPeersClient struct { + internal *arm.Client +} + +// NewBgpPeersClient creates a new instance of BgpPeersClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewBgpPeersClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*BgpPeersClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &BgpPeersClient{ + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create a BgpPeer +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - bgpPeerName - The name of the BgpPeer +// - resource - Resource create parameters. +// - options - BgpPeersClientBeginCreateOrUpdateOptions contains the optional parameters for the BgpPeersClient.BeginCreateOrUpdate +// method. +func (client *BgpPeersClient) BeginCreateOrUpdate(ctx context.Context, resourceURI string, bgpPeerName string, resource BgpPeer, options *BgpPeersClientBeginCreateOrUpdateOptions) (*runtime.Poller[BgpPeersClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceURI, bgpPeerName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[BgpPeersClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[BgpPeersClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create a BgpPeer +// If the operation fails it returns an *azcore.ResponseError type. +func (client *BgpPeersClient) createOrUpdate(ctx context.Context, resourceURI string, bgpPeerName string, resource BgpPeer, options *BgpPeersClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "BgpPeersClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceURI, bgpPeerName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *BgpPeersClient) createOrUpdateCreateRequest(ctx context.Context, resourceURI string, bgpPeerName string, resource BgpPeer, _ *BgpPeersClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.KubernetesRuntime/bgpPeers/{bgpPeerName}" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + if bgpPeerName == "" { + return nil, errors.New("parameter bgpPeerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{bgpPeerName}", url.PathEscape(bgpPeerName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240301) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// Delete - Delete a BgpPeer +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - bgpPeerName - The name of the BgpPeer +// - options - BgpPeersClientDeleteOptions contains the optional parameters for the BgpPeersClient.Delete method. +func (client *BgpPeersClient) Delete(ctx context.Context, resourceURI string, bgpPeerName string, options *BgpPeersClientDeleteOptions) (BgpPeersClientDeleteResponse, error) { + var err error + const operationName = "BgpPeersClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceURI, bgpPeerName, options) + if err != nil { + return BgpPeersClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BgpPeersClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return BgpPeersClientDeleteResponse{}, err + } + return BgpPeersClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *BgpPeersClient) deleteCreateRequest(ctx context.Context, resourceURI string, bgpPeerName string, _ *BgpPeersClientDeleteOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.KubernetesRuntime/bgpPeers/{bgpPeerName}" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + if bgpPeerName == "" { + return nil, errors.New("parameter bgpPeerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{bgpPeerName}", url.PathEscape(bgpPeerName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240301) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a BgpPeer +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - bgpPeerName - The name of the BgpPeer +// - options - BgpPeersClientGetOptions contains the optional parameters for the BgpPeersClient.Get method. +func (client *BgpPeersClient) Get(ctx context.Context, resourceURI string, bgpPeerName string, options *BgpPeersClientGetOptions) (BgpPeersClientGetResponse, error) { + var err error + const operationName = "BgpPeersClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceURI, bgpPeerName, options) + if err != nil { + return BgpPeersClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BgpPeersClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BgpPeersClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *BgpPeersClient) getCreateRequest(ctx context.Context, resourceURI string, bgpPeerName string, _ *BgpPeersClientGetOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.KubernetesRuntime/bgpPeers/{bgpPeerName}" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + if bgpPeerName == "" { + return nil, errors.New("parameter bgpPeerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{bgpPeerName}", url.PathEscape(bgpPeerName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240301) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *BgpPeersClient) getHandleResponse(resp *http.Response) (BgpPeersClientGetResponse, error) { + result := BgpPeersClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BgpPeer); err != nil { + return BgpPeersClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List BgpPeer resources by parent +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - options - BgpPeersClientListOptions contains the optional parameters for the BgpPeersClient.NewListPager method. +func (client *BgpPeersClient) NewListPager(resourceURI string, options *BgpPeersClientListOptions) *runtime.Pager[BgpPeersClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[BgpPeersClientListResponse]{ + More: func(page BgpPeersClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *BgpPeersClientListResponse) (BgpPeersClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "BgpPeersClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceURI, options) + }, nil) + if err != nil { + return BgpPeersClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *BgpPeersClient) listCreateRequest(ctx context.Context, resourceURI string, _ *BgpPeersClientListOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.KubernetesRuntime/bgpPeers" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240301) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *BgpPeersClient) listHandleResponse(resp *http.Response) (BgpPeersClientListResponse, error) { + result := BgpPeersClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BgpPeerListResult); err != nil { + return BgpPeersClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armcontainerorchestratorruntime/zz_client_factory.go b/test/local/armcontainerorchestratorruntime/zz_client_factory.go new file mode 100644 index 000000000000..25f645ec0479 --- /dev/null +++ b/test/local/armcontainerorchestratorruntime/zz_client_factory.go @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcontainerorchestratorruntime + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + internal: internal, + }, nil +} + +// NewBgpPeersClient creates a new instance of BgpPeersClient. +func (c *ClientFactory) NewBgpPeersClient() *BgpPeersClient { + return &BgpPeersClient{ + internal: c.internal, + } +} + +// NewLoadBalancersClient creates a new instance of LoadBalancersClient. +func (c *ClientFactory) NewLoadBalancersClient() *LoadBalancersClient { + return &LoadBalancersClient{ + internal: c.internal, + } +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: c.internal, + } +} + +// NewServicesClient creates a new instance of ServicesClient. +func (c *ClientFactory) NewServicesClient() *ServicesClient { + return &ServicesClient{ + internal: c.internal, + } +} + +// NewStorageClassClient creates a new instance of StorageClassClient. +func (c *ClientFactory) NewStorageClassClient() *StorageClassClient { + return &StorageClassClient{ + internal: c.internal, + } +} diff --git a/test/local/armcontainerorchestratorruntime/zz_constants.go b/test/local/armcontainerorchestratorruntime/zz_constants.go new file mode 100644 index 000000000000..587ad0cb76d2 --- /dev/null +++ b/test/local/armcontainerorchestratorruntime/zz_constants.go @@ -0,0 +1,292 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcontainerorchestratorruntime + +const ( + version20240301 string = "2024-03-01" +) + +// AccessMode - Storage Class Access Mode +type AccessMode string + +const ( + // AccessModeReadWriteMany - Read Write Many (RWX) access mode + AccessModeReadWriteMany AccessMode = "ReadWriteMany" + // AccessModeReadWriteOnce - Read Write Once (RWO) access mode + AccessModeReadWriteOnce AccessMode = "ReadWriteOnce" +) + +// PossibleAccessModeValues returns the possible values for the AccessMode const type. +func PossibleAccessModeValues() []AccessMode { + return []AccessMode{ + AccessModeReadWriteMany, + AccessModeReadWriteOnce, + } +} + +// ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +type ActionType string + +const ( + // ActionTypeInternal - Actions are for internal-only APIs. + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// AdvertiseMode - Enum of advertise mode +type AdvertiseMode string + +const ( + // AdvertiseModeARP - ARP advertise mode + AdvertiseModeARP AdvertiseMode = "ARP" + // AdvertiseModeBGP - BGP advertise mode + AdvertiseModeBGP AdvertiseMode = "BGP" + // AdvertiseModeBoth - both ARP and BGP advertise mode + AdvertiseModeBoth AdvertiseMode = "Both" +) + +// PossibleAdvertiseModeValues returns the possible values for the AdvertiseMode const type. +func PossibleAdvertiseModeValues() []AdvertiseMode { + return []AdvertiseMode{ + AdvertiseModeARP, + AdvertiseModeBGP, + AdvertiseModeBoth, + } +} + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// DataResilienceTier - Data resilience tier of a storage class +type DataResilienceTier string + +const ( + // DataResilienceTierDataResilient - Data resilient + DataResilienceTierDataResilient DataResilienceTier = "DataResilient" + // DataResilienceTierNotDataResilient - Not data resilient + DataResilienceTierNotDataResilient DataResilienceTier = "NotDataResilient" +) + +// PossibleDataResilienceTierValues returns the possible values for the DataResilienceTier const type. +func PossibleDataResilienceTierValues() []DataResilienceTier { + return []DataResilienceTier{ + DataResilienceTierDataResilient, + DataResilienceTierNotDataResilient, + } +} + +// FailoverTier - Failover tier of a storage class +type FailoverTier string + +const ( + // FailoverTierFast - Fast Failover Tier + FailoverTierFast FailoverTier = "Fast" + // FailoverTierNotAvailable - Not available Failover Tier + FailoverTierNotAvailable FailoverTier = "NotAvailable" + // FailoverTierSlow - Slow Failover Tier + FailoverTierSlow FailoverTier = "Slow" + // FailoverTierSuper - Super Failover Tier + FailoverTierSuper FailoverTier = "Super" +) + +// PossibleFailoverTierValues returns the possible values for the FailoverTier const type. +func PossibleFailoverTierValues() []FailoverTier { + return []FailoverTier{ + FailoverTierFast, + FailoverTierNotAvailable, + FailoverTierSlow, + FailoverTierSuper, + } +} + +// NfsDirectoryActionOnVolumeDeletion - The action to take when a NFS volume is deleted +type NfsDirectoryActionOnVolumeDeletion string + +const ( + // NfsDirectoryActionOnVolumeDeletionDelete - When the volume is deleted, delete the directory + NfsDirectoryActionOnVolumeDeletionDelete NfsDirectoryActionOnVolumeDeletion = "Delete" + // NfsDirectoryActionOnVolumeDeletionRetain - When the volume is deleted, retain the directory + NfsDirectoryActionOnVolumeDeletionRetain NfsDirectoryActionOnVolumeDeletion = "Retain" +) + +// PossibleNfsDirectoryActionOnVolumeDeletionValues returns the possible values for the NfsDirectoryActionOnVolumeDeletion const type. +func PossibleNfsDirectoryActionOnVolumeDeletionValues() []NfsDirectoryActionOnVolumeDeletion { + return []NfsDirectoryActionOnVolumeDeletion{ + NfsDirectoryActionOnVolumeDeletionDelete, + NfsDirectoryActionOnVolumeDeletionRetain, + } +} + +// Origin - The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default +// value is "user,system" +type Origin string + +const ( + // OriginSystem - Indicates the operation is initiated by a system. + OriginSystem Origin = "system" + // OriginUser - Indicates the operation is initiated by a user. + OriginUser Origin = "user" + // OriginUserSystem - Indicates the operation is initiated by a user or system. + OriginUserSystem Origin = "user,system" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginSystem, + OriginUser, + OriginUserSystem, + } +} + +// PerformanceTier - Performance tier of a storage class +type PerformanceTier string + +const ( + // PerformanceTierBasic - Basic Performance Tier + PerformanceTierBasic PerformanceTier = "Basic" + // PerformanceTierPremium - Premium Performance Tier + PerformanceTierPremium PerformanceTier = "Premium" + // PerformanceTierStandard - Standard Performance Tier + PerformanceTierStandard PerformanceTier = "Standard" + // PerformanceTierUltra - Ultra Performance Tier + PerformanceTierUltra PerformanceTier = "Ultra" + // PerformanceTierUndefined - Undefined Performance Tier + PerformanceTierUndefined PerformanceTier = "Undefined" +) + +// PossiblePerformanceTierValues returns the possible values for the PerformanceTier const type. +func PossiblePerformanceTierValues() []PerformanceTier { + return []PerformanceTier{ + PerformanceTierBasic, + PerformanceTierPremium, + PerformanceTierStandard, + PerformanceTierUltra, + PerformanceTierUndefined, + } +} + +// ProvisioningState - The status of the current operation. +type ProvisioningState string + +const ( + // ProvisioningStateAccepted - Change accepted for processing + ProvisioningStateAccepted ProvisioningState = "Accepted" + // ProvisioningStateCanceled - Resource creation was canceled. + ProvisioningStateCanceled ProvisioningState = "Canceled" + // ProvisioningStateDeleting - Deletion in progress + ProvisioningStateDeleting ProvisioningState = "Deleting" + // ProvisioningStateFailed - Resource creation failed. + ProvisioningStateFailed ProvisioningState = "Failed" + // ProvisioningStateProvisioning - Initial provisioning in progress + ProvisioningStateProvisioning ProvisioningState = "Provisioning" + // ProvisioningStateSucceeded - Resource has been created. + ProvisioningStateSucceeded ProvisioningState = "Succeeded" + // ProvisioningStateUpdating - Update in progress + ProvisioningStateUpdating ProvisioningState = "Updating" +) + +// PossibleProvisioningStateValues returns the possible values for the ProvisioningState const type. +func PossibleProvisioningStateValues() []ProvisioningState { + return []ProvisioningState{ + ProvisioningStateAccepted, + ProvisioningStateCanceled, + ProvisioningStateDeleting, + ProvisioningStateFailed, + ProvisioningStateProvisioning, + ProvisioningStateSucceeded, + ProvisioningStateUpdating, + } +} + +// SCType - Type of a storage class +type SCType string + +const ( + // SCTypeBlob - Blob storage class + SCTypeBlob SCType = "Blob" + // SCTypeNFS - NFS storage class + SCTypeNFS SCType = "NFS" + // SCTypeNative - Native storage class + SCTypeNative SCType = "Native" + // SCTypeRWX - RWX storage class + SCTypeRWX SCType = "RWX" + // SCTypeSMB - SMB storage class + SCTypeSMB SCType = "SMB" +) + +// PossibleSCTypeValues returns the possible values for the SCType const type. +func PossibleSCTypeValues() []SCType { + return []SCType{ + SCTypeBlob, + SCTypeNFS, + SCTypeNative, + SCTypeRWX, + SCTypeSMB, + } +} + +// VolumeBindingMode - Storage class volume binding mode +type VolumeBindingMode string + +const ( + // VolumeBindingModeImmediate - Immediate binding mode + VolumeBindingModeImmediate VolumeBindingMode = "Immediate" + // VolumeBindingModeWaitForFirstConsumer - Wait for first consumer binding mode + VolumeBindingModeWaitForFirstConsumer VolumeBindingMode = "WaitForFirstConsumer" +) + +// PossibleVolumeBindingModeValues returns the possible values for the VolumeBindingMode const type. +func PossibleVolumeBindingModeValues() []VolumeBindingMode { + return []VolumeBindingMode{ + VolumeBindingModeImmediate, + VolumeBindingModeWaitForFirstConsumer, + } +} + +// VolumeExpansion - Ability to expand volumes of a storage class +type VolumeExpansion string + +const ( + // VolumeExpansionAllow - Allow volume expansion + VolumeExpansionAllow VolumeExpansion = "Allow" + // VolumeExpansionDisallow - Disallow volume expansion + VolumeExpansionDisallow VolumeExpansion = "Disallow" +) + +// PossibleVolumeExpansionValues returns the possible values for the VolumeExpansion const type. +func PossibleVolumeExpansionValues() []VolumeExpansion { + return []VolumeExpansion{ + VolumeExpansionAllow, + VolumeExpansionDisallow, + } +} diff --git a/test/local/armcontainerorchestratorruntime/zz_interfaces.go b/test/local/armcontainerorchestratorruntime/zz_interfaces.go new file mode 100644 index 000000000000..21e3f4ef4b59 --- /dev/null +++ b/test/local/armcontainerorchestratorruntime/zz_interfaces.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcontainerorchestratorruntime + +// StorageClassTypePropertiesClassification provides polymorphic access to related types. +// Call the interface's GetStorageClassTypeProperties() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *BlobStorageClassTypeProperties, *NativeStorageClassTypeProperties, *NfsStorageClassTypeProperties, *RwxStorageClassTypeProperties, +// - *SmbStorageClassTypeProperties, *StorageClassTypeProperties +type StorageClassTypePropertiesClassification interface { + // GetStorageClassTypeProperties returns the StorageClassTypeProperties content of the underlying type. + GetStorageClassTypeProperties() *StorageClassTypeProperties +} diff --git a/test/local/armcontainerorchestratorruntime/zz_loadbalancers_client.go b/test/local/armcontainerorchestratorruntime/zz_loadbalancers_client.go new file mode 100644 index 000000000000..5c317e7ba6cf --- /dev/null +++ b/test/local/armcontainerorchestratorruntime/zz_loadbalancers_client.go @@ -0,0 +1,271 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcontainerorchestratorruntime + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// LoadBalancersClient contains the methods for the LoadBalancers group. +// Don't use this type directly, use NewLoadBalancersClient() instead. +// +// Generated from API version 2024-03-01 +type LoadBalancersClient struct { + internal *arm.Client +} + +// NewLoadBalancersClient creates a new instance of LoadBalancersClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewLoadBalancersClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*LoadBalancersClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &LoadBalancersClient{ + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create a LoadBalancer +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - loadBalancerName - The name of the LoadBalancer +// - resource - Resource create parameters. +// - options - LoadBalancersClientBeginCreateOrUpdateOptions contains the optional parameters for the LoadBalancersClient.BeginCreateOrUpdate +// method. +func (client *LoadBalancersClient) BeginCreateOrUpdate(ctx context.Context, resourceURI string, loadBalancerName string, resource LoadBalancer, options *LoadBalancersClientBeginCreateOrUpdateOptions) (*runtime.Poller[LoadBalancersClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceURI, loadBalancerName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[LoadBalancersClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[LoadBalancersClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create a LoadBalancer +// If the operation fails it returns an *azcore.ResponseError type. +func (client *LoadBalancersClient) createOrUpdate(ctx context.Context, resourceURI string, loadBalancerName string, resource LoadBalancer, options *LoadBalancersClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "LoadBalancersClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceURI, loadBalancerName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *LoadBalancersClient) createOrUpdateCreateRequest(ctx context.Context, resourceURI string, loadBalancerName string, resource LoadBalancer, _ *LoadBalancersClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.KubernetesRuntime/loadBalancers/{loadBalancerName}" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + if loadBalancerName == "" { + return nil, errors.New("parameter loadBalancerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadBalancerName}", url.PathEscape(loadBalancerName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240301) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// Delete - Delete a LoadBalancer +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - loadBalancerName - The name of the LoadBalancer +// - options - LoadBalancersClientDeleteOptions contains the optional parameters for the LoadBalancersClient.Delete method. +func (client *LoadBalancersClient) Delete(ctx context.Context, resourceURI string, loadBalancerName string, options *LoadBalancersClientDeleteOptions) (LoadBalancersClientDeleteResponse, error) { + var err error + const operationName = "LoadBalancersClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceURI, loadBalancerName, options) + if err != nil { + return LoadBalancersClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LoadBalancersClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return LoadBalancersClientDeleteResponse{}, err + } + return LoadBalancersClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *LoadBalancersClient) deleteCreateRequest(ctx context.Context, resourceURI string, loadBalancerName string, _ *LoadBalancersClientDeleteOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.KubernetesRuntime/loadBalancers/{loadBalancerName}" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + if loadBalancerName == "" { + return nil, errors.New("parameter loadBalancerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadBalancerName}", url.PathEscape(loadBalancerName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240301) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a LoadBalancer +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - loadBalancerName - The name of the LoadBalancer +// - options - LoadBalancersClientGetOptions contains the optional parameters for the LoadBalancersClient.Get method. +func (client *LoadBalancersClient) Get(ctx context.Context, resourceURI string, loadBalancerName string, options *LoadBalancersClientGetOptions) (LoadBalancersClientGetResponse, error) { + var err error + const operationName = "LoadBalancersClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceURI, loadBalancerName, options) + if err != nil { + return LoadBalancersClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LoadBalancersClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return LoadBalancersClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *LoadBalancersClient) getCreateRequest(ctx context.Context, resourceURI string, loadBalancerName string, _ *LoadBalancersClientGetOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.KubernetesRuntime/loadBalancers/{loadBalancerName}" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + if loadBalancerName == "" { + return nil, errors.New("parameter loadBalancerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadBalancerName}", url.PathEscape(loadBalancerName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240301) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *LoadBalancersClient) getHandleResponse(resp *http.Response) (LoadBalancersClientGetResponse, error) { + result := LoadBalancersClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LoadBalancer); err != nil { + return LoadBalancersClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List LoadBalancer resources by parent +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - options - LoadBalancersClientListOptions contains the optional parameters for the LoadBalancersClient.NewListPager method. +func (client *LoadBalancersClient) NewListPager(resourceURI string, options *LoadBalancersClientListOptions) *runtime.Pager[LoadBalancersClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[LoadBalancersClientListResponse]{ + More: func(page LoadBalancersClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *LoadBalancersClientListResponse) (LoadBalancersClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "LoadBalancersClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceURI, options) + }, nil) + if err != nil { + return LoadBalancersClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *LoadBalancersClient) listCreateRequest(ctx context.Context, resourceURI string, _ *LoadBalancersClientListOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.KubernetesRuntime/loadBalancers" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240301) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *LoadBalancersClient) listHandleResponse(resp *http.Response) (LoadBalancersClientListResponse, error) { + result := LoadBalancersClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LoadBalancerListResult); err != nil { + return LoadBalancersClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armcontainerorchestratorruntime/zz_models.go b/test/local/armcontainerorchestratorruntime/zz_models.go new file mode 100644 index 000000000000..4b4927f35fef --- /dev/null +++ b/test/local/armcontainerorchestratorruntime/zz_models.go @@ -0,0 +1,464 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcontainerorchestratorruntime + +import "time" + +// BgpPeer - A BgpPeer resource for an Arc connected cluster (Microsoft.Kubernetes/connectedClusters) +type BgpPeer struct { + // The resource-specific properties for this resource. + Properties *BgpPeerProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// BgpPeerListResult - The response of a BgpPeer list operation. +type BgpPeerListResult struct { + // REQUIRED; The BgpPeer items on this page + Value []*BgpPeer + + // The link to the next page of items + NextLink *string +} + +// BgpPeerProperties - Details of the BgpPeer. +type BgpPeerProperties struct { + // REQUIRED; My ASN + MyAsn *int32 + + // REQUIRED; Peer Address + PeerAddress *string + + // REQUIRED; Peer ASN + PeerAsn *int32 + + // READ-ONLY; Resource provision state + ProvisioningState *ProvisioningState +} + +// BlobStorageClassTypeProperties - The properties of Blob StorageClass +type BlobStorageClassTypeProperties struct { + // REQUIRED; Azure Storage Account Key + AzureStorageAccountKey *string + + // REQUIRED; Azure Storage Account Name + AzureStorageAccountName *string + + // CONSTANT; Blob StorageClass + // Field has constant value SCTypeBlob, any specified value is ignored. + Type *SCType +} + +// GetStorageClassTypeProperties implements the StorageClassTypePropertiesClassification interface for type BlobStorageClassTypeProperties. +func (b *BlobStorageClassTypeProperties) GetStorageClassTypeProperties() *StorageClassTypeProperties { + return &StorageClassTypeProperties{ + Type: b.Type, + } +} + +// LoadBalancer - A LoadBalancer resource for an Arc connected cluster (Microsoft.Kubernetes/connectedClusters) +type LoadBalancer struct { + // The resource-specific properties for this resource. + Properties *LoadBalancerProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// LoadBalancerListResult - The response of a LoadBalancer list operation. +type LoadBalancerListResult struct { + // REQUIRED; The LoadBalancer items on this page + Value []*LoadBalancer + + // The link to the next page of items + NextLink *string +} + +// LoadBalancerProperties - Details of the LoadBalancer. +type LoadBalancerProperties struct { + // REQUIRED; IP Range + Addresses []*string + + // REQUIRED; Advertise Mode + AdvertiseMode *AdvertiseMode + + // The list of BGP peers it should advertise to. Null or empty means to advertise to all peers. + BgpPeers []*string + + // A dynamic label mapping to select related services. For instance, if you want to create a load balancer only for services + // with label "a=b", then please specify {"a": "b"} in the field. + ServiceSelector map[string]*string + + // READ-ONLY; Resource provision state + ProvisioningState *ProvisioningState +} + +// NativeStorageClassTypeProperties - The properties of Native StorageClass +type NativeStorageClassTypeProperties struct { + // CONSTANT; Native StorageClass + // Field has constant value SCTypeNative, any specified value is ignored. + Type *SCType +} + +// GetStorageClassTypeProperties implements the StorageClassTypePropertiesClassification interface for type NativeStorageClassTypeProperties. +func (n *NativeStorageClassTypeProperties) GetStorageClassTypeProperties() *StorageClassTypeProperties { + return &StorageClassTypeProperties{ + Type: n.Type, + } +} + +// NfsStorageClassTypeProperties - The properties of NFS StorageClass +type NfsStorageClassTypeProperties struct { + // REQUIRED; NFS Server + Server *string + + // REQUIRED; NFS share + Share *string + + // CONSTANT; NFS StorageClass + // Field has constant value SCTypeNFS, any specified value is ignored. + Type *SCType + + // Mounted folder permissions. Default is 0. If set as non-zero, driver will perform `chmod` after mount + MountPermissions *string + + // The action to take when a NFS volume is deleted. Default is Delete + OnDelete *NfsDirectoryActionOnVolumeDeletion + + // Sub directory under share. If the sub directory doesn't exist, driver will create it + SubDir *string +} + +// GetStorageClassTypeProperties implements the StorageClassTypePropertiesClassification interface for type NfsStorageClassTypeProperties. +func (n *NfsStorageClassTypeProperties) GetStorageClassTypeProperties() *StorageClassTypeProperties { + return &StorageClassTypeProperties{ + Type: n.Type, + } +} + +// Operation - REST API Operation +// +// Details of a REST API operation, returned from the Resource Provider Operations API +type Operation struct { + // Localized display information for this particular operation. + Display *OperationDisplay + + // READ-ONLY; Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + ActionType *ActionType + + // READ-ONLY; Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure + // Resource Manager/control-plane operations. + IsDataAction *bool + + // READ-ONLY; The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + // "Microsoft.Compute/virtualMachines/capture/action" + Name *string + + // READ-ONLY; The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default + // value is "user,system" + Origin *Origin +} + +// OperationDisplay - Localized display information for an operation. +type OperationDisplay struct { + // READ-ONLY; The short, localized friendly description of the operation; suitable for tool tips and detailed views. + Description *string + + // READ-ONLY; The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual + // Machine", "Restart Virtual Machine". + Operation *string + + // READ-ONLY; The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft + // Compute". + Provider *string + + // READ-ONLY; The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job + // Schedule Collections". + Resource *string +} + +// OperationListResult - A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to +// get the next set of results. +type OperationListResult struct { + // REQUIRED; The Operation items on this page + Value []*Operation + + // The link to the next page of items + NextLink *string +} + +// RwxStorageClassTypeProperties - The properties of RWX StorageClass +type RwxStorageClassTypeProperties struct { + // REQUIRED; The backing storageclass used to create new storageclass + BackingStorageClassName *string + + // CONSTANT; RWX StorageClass + // Field has constant value SCTypeRWX, any specified value is ignored. + Type *SCType +} + +// GetStorageClassTypeProperties implements the StorageClassTypePropertiesClassification interface for type RwxStorageClassTypeProperties. +func (r *RwxStorageClassTypeProperties) GetStorageClassTypeProperties() *StorageClassTypeProperties { + return &StorageClassTypeProperties{ + Type: r.Type, + } +} + +// ServiceProperties - Properties for the service resource +type ServiceProperties struct { + // READ-ONLY; Resource provision state + ProvisioningState *ProvisioningState + + // READ-ONLY; The object id of the service principal of the RP provisioned in the tenant + RpObjectID *string +} + +// ServiceResource - A Service resource for an Arc connected cluster (Microsoft.Kubernetes/connectedClusters) +type ServiceResource struct { + // The resource-specific properties for this resource. + Properties *ServiceProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ServiceResourceListResult - The response of a ServiceResource list operation. +type ServiceResourceListResult struct { + // REQUIRED; The ServiceResource items on this page + Value []*ServiceResource + + // The link to the next page of items + NextLink *string +} + +// SmbStorageClassTypeProperties - The properties of SMB StorageClass +type SmbStorageClassTypeProperties struct { + // REQUIRED; SMB Source + Source *string + + // CONSTANT; SMB StorageClass + // Field has constant value SCTypeSMB, any specified value is ignored. + Type *SCType + + // Server domain + Domain *string + + // Server password + Password *string + + // Sub directory under share. If the sub directory doesn't exist, driver will create it + SubDir *string + + // Server username + Username *string +} + +// GetStorageClassTypeProperties implements the StorageClassTypePropertiesClassification interface for type SmbStorageClassTypeProperties. +func (s *SmbStorageClassTypeProperties) GetStorageClassTypeProperties() *StorageClassTypeProperties { + return &StorageClassTypeProperties{ + Type: s.Type, + } +} + +// StorageClassProperties - Details of the StorageClass StorageClass. +type StorageClassProperties struct { + // REQUIRED; Properties of the StorageClass + TypeProperties StorageClassTypePropertiesClassification + + // The access mode: [ReadWriteOnce, ReadWriteMany] or [ReadWriteOnce] + AccessModes []*AccessMode + + // Volume can be expanded or not + AllowVolumeExpansion *VolumeExpansion + + // Allow single data node failure + DataResilience *DataResilienceTier + + // Failover speed: NA, Slow, Fast + FailoverSpeed *FailoverTier + + // Limitations of the storage class + Limitations []*string + + // Additional mount options + MountOptions []*string + + // Performance tier + Performance *PerformanceTier + + // Selection priority when multiple storage classes meet the criteria. 0: Highest, -1: Never use + Priority *int64 + + // Provisioner name + Provisioner *string + + // Binding mode of volumes: Immediate, WaitForFirstConsumer + VolumeBindingMode *VolumeBindingMode + + // READ-ONLY; Resource provision state + ProvisioningState *ProvisioningState +} + +// StorageClassPropertiesUpdate - The model for updating storageClass properties +type StorageClassPropertiesUpdate struct { + // The access mode: [ReadWriteOnce, ReadWriteMany] or [ReadWriteOnce] + AccessModes []*AccessMode + + // Volume can be expanded or not + AllowVolumeExpansion *VolumeExpansion + + // Allow single data node failure + DataResilience *DataResilienceTier + + // Failover speed: NA, Slow, Fast + FailoverSpeed *FailoverTier + + // Limitations of the storage class + Limitations []*string + + // Additional mount options + MountOptions []*string + + // Performance tier + Performance *PerformanceTier + + // Selection priority when multiple storage classes meet the criteria. 0: Highest, -1: Never use + Priority *int64 + + // New storage class type of storageClass + TypeProperties *StorageClassTypePropertiesUpdate +} + +// StorageClassResource - A StorageClass resource for an Arc connected cluster (Microsoft.Kubernetes/connectedClusters) +type StorageClassResource struct { + // The resource-specific properties for this resource. + Properties *StorageClassProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// StorageClassResourceListResult - The response of a StorageClassResource list operation. +type StorageClassResourceListResult struct { + // REQUIRED; The StorageClassResource items on this page + Value []*StorageClassResource + + // The link to the next page of items + NextLink *string +} + +// StorageClassResourceUpdate - The model for updating a storageClass +type StorageClassResourceUpdate struct { + // The properties of StorageClass + Properties *StorageClassPropertiesUpdate +} + +// StorageClassTypeProperties - The properties of storage class of the StorageClass +type StorageClassTypeProperties struct { + // REQUIRED; Type of the storage class. + Type *SCType +} + +// GetStorageClassTypeProperties implements the StorageClassTypePropertiesClassification interface for type StorageClassTypeProperties. +func (s *StorageClassTypeProperties) GetStorageClassTypeProperties() *StorageClassTypeProperties { + return s +} + +// StorageClassTypePropertiesUpdate - The model for update a storageClass +type StorageClassTypePropertiesUpdate struct { + // Azure Storage Account Key + AzureStorageAccountKey *string + + // Azure Storage Account Name + AzureStorageAccountName *string + + // The backing storageclass used to create new storageclass + BackingStorageClassName *string + + // Server domain + Domain *string + + // Mounted folder permissions. Default is 0. If set as non-zero, driver will perform `chmod` after mount + MountPermissions *string + + // The action to take when a NFS volume is deleted. Default is Delete + OnDelete *NfsDirectoryActionOnVolumeDeletion + + // Server password + Password *string + + // NFS Server + Server *string + + // NFS share + Share *string + + // SMB Source + Source *string + + // Sub directory under share. If the sub directory doesn't exist, driver will create it + SubDir *string + + // Server username + Username *string +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time + + // The identity that created the resource. + CreatedBy *string + + // The type of identity that created the resource. + CreatedByType *CreatedByType + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time + + // The identity that last modified the resource. + LastModifiedBy *string + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType +} diff --git a/test/local/armcontainerorchestratorruntime/zz_models_serde.go b/test/local/armcontainerorchestratorruntime/zz_models_serde.go new file mode 100644 index 000000000000..a7be988c0ff5 --- /dev/null +++ b/test/local/armcontainerorchestratorruntime/zz_models_serde.go @@ -0,0 +1,1073 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcontainerorchestratorruntime + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type BgpPeer. +func (b BgpPeer) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", b.ID) + populate(objectMap, "name", b.Name) + populate(objectMap, "properties", b.Properties) + populate(objectMap, "systemData", b.SystemData) + populate(objectMap, "type", b.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BgpPeer. +func (b *BgpPeer) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &b.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &b.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &b.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &b.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &b.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BgpPeerListResult. +func (b BgpPeerListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", b.NextLink) + populate(objectMap, "value", b.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BgpPeerListResult. +func (b *BgpPeerListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &b.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &b.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BgpPeerProperties. +func (b BgpPeerProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "myAsn", b.MyAsn) + populate(objectMap, "peerAddress", b.PeerAddress) + populate(objectMap, "peerAsn", b.PeerAsn) + populate(objectMap, "provisioningState", b.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BgpPeerProperties. +func (b *BgpPeerProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "myAsn": + err = unpopulate(val, "MyAsn", &b.MyAsn) + delete(rawMsg, key) + case "peerAddress": + err = unpopulate(val, "PeerAddress", &b.PeerAddress) + delete(rawMsg, key) + case "peerAsn": + err = unpopulate(val, "PeerAsn", &b.PeerAsn) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &b.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BlobStorageClassTypeProperties. +func (b BlobStorageClassTypeProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "azureStorageAccountKey", b.AzureStorageAccountKey) + populate(objectMap, "azureStorageAccountName", b.AzureStorageAccountName) + objectMap["type"] = SCTypeBlob + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BlobStorageClassTypeProperties. +func (b *BlobStorageClassTypeProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "azureStorageAccountKey": + err = unpopulate(val, "AzureStorageAccountKey", &b.AzureStorageAccountKey) + delete(rawMsg, key) + case "azureStorageAccountName": + err = unpopulate(val, "AzureStorageAccountName", &b.AzureStorageAccountName) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &b.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LoadBalancer. +func (l LoadBalancer) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", l.ID) + populate(objectMap, "name", l.Name) + populate(objectMap, "properties", l.Properties) + populate(objectMap, "systemData", l.SystemData) + populate(objectMap, "type", l.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadBalancer. +func (l *LoadBalancer) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &l.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &l.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &l.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &l.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &l.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LoadBalancerListResult. +func (l LoadBalancerListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", l.NextLink) + populate(objectMap, "value", l.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadBalancerListResult. +func (l *LoadBalancerListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &l.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &l.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LoadBalancerProperties. +func (l LoadBalancerProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addresses", l.Addresses) + populate(objectMap, "advertiseMode", l.AdvertiseMode) + populate(objectMap, "bgpPeers", l.BgpPeers) + populate(objectMap, "provisioningState", l.ProvisioningState) + populate(objectMap, "serviceSelector", l.ServiceSelector) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadBalancerProperties. +func (l *LoadBalancerProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "addresses": + err = unpopulate(val, "Addresses", &l.Addresses) + delete(rawMsg, key) + case "advertiseMode": + err = unpopulate(val, "AdvertiseMode", &l.AdvertiseMode) + delete(rawMsg, key) + case "bgpPeers": + err = unpopulate(val, "BgpPeers", &l.BgpPeers) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &l.ProvisioningState) + delete(rawMsg, key) + case "serviceSelector": + err = unpopulate(val, "ServiceSelector", &l.ServiceSelector) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NativeStorageClassTypeProperties. +func (n NativeStorageClassTypeProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["type"] = SCTypeNative + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NativeStorageClassTypeProperties. +func (n *NativeStorageClassTypeProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "type": + err = unpopulate(val, "Type", &n.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NfsStorageClassTypeProperties. +func (n NfsStorageClassTypeProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "mountPermissions", n.MountPermissions) + populate(objectMap, "onDelete", n.OnDelete) + populate(objectMap, "server", n.Server) + populate(objectMap, "share", n.Share) + populate(objectMap, "subDir", n.SubDir) + objectMap["type"] = SCTypeNFS + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NfsStorageClassTypeProperties. +func (n *NfsStorageClassTypeProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "mountPermissions": + err = unpopulate(val, "MountPermissions", &n.MountPermissions) + delete(rawMsg, key) + case "onDelete": + err = unpopulate(val, "OnDelete", &n.OnDelete) + delete(rawMsg, key) + case "server": + err = unpopulate(val, "Server", &n.Server) + delete(rawMsg, key) + case "share": + err = unpopulate(val, "Share", &n.Share) + delete(rawMsg, key) + case "subDir": + err = unpopulate(val, "SubDir", &n.SubDir) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &n.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Operation. +func (o Operation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionType", o.ActionType) + populate(objectMap, "display", o.Display) + populate(objectMap, "isDataAction", o.IsDataAction) + populate(objectMap, "name", o.Name) + populate(objectMap, "origin", o.Origin) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Operation. +func (o *Operation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionType": + err = unpopulate(val, "ActionType", &o.ActionType) + delete(rawMsg, key) + case "display": + err = unpopulate(val, "Display", &o.Display) + delete(rawMsg, key) + case "isDataAction": + err = unpopulate(val, "IsDataAction", &o.IsDataAction) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "origin": + err = unpopulate(val, "Origin", &o.Origin) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationDisplay. +func (o OperationDisplay) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", o.Description) + populate(objectMap, "operation", o.Operation) + populate(objectMap, "provider", o.Provider) + populate(objectMap, "resource", o.Resource) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationDisplay. +func (o *OperationDisplay) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &o.Description) + delete(rawMsg, key) + case "operation": + err = unpopulate(val, "Operation", &o.Operation) + delete(rawMsg, key) + case "provider": + err = unpopulate(val, "Provider", &o.Provider) + delete(rawMsg, key) + case "resource": + err = unpopulate(val, "Resource", &o.Resource) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationListResult. +func (o *OperationListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &o.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RwxStorageClassTypeProperties. +func (r RwxStorageClassTypeProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "backingStorageClassName", r.BackingStorageClassName) + objectMap["type"] = SCTypeRWX + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RwxStorageClassTypeProperties. +func (r *RwxStorageClassTypeProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "backingStorageClassName": + err = unpopulate(val, "BackingStorageClassName", &r.BackingStorageClassName) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ServiceProperties. +func (s ServiceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "rpObjectId", s.RpObjectID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceProperties. +func (s *ServiceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + case "rpObjectId": + err = unpopulate(val, "RpObjectID", &s.RpObjectID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ServiceResource. +func (s ServiceResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "systemData", s.SystemData) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceResource. +func (s *ServiceResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &s.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ServiceResourceListResult. +func (s ServiceResourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceResourceListResult. +func (s *ServiceResourceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &s.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SmbStorageClassTypeProperties. +func (s SmbStorageClassTypeProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "domain", s.Domain) + populate(objectMap, "password", s.Password) + populate(objectMap, "source", s.Source) + populate(objectMap, "subDir", s.SubDir) + objectMap["type"] = SCTypeSMB + populate(objectMap, "username", s.Username) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SmbStorageClassTypeProperties. +func (s *SmbStorageClassTypeProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "domain": + err = unpopulate(val, "Domain", &s.Domain) + delete(rawMsg, key) + case "password": + err = unpopulate(val, "Password", &s.Password) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &s.Source) + delete(rawMsg, key) + case "subDir": + err = unpopulate(val, "SubDir", &s.SubDir) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + case "username": + err = unpopulate(val, "Username", &s.Username) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type StorageClassProperties. +func (s StorageClassProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "accessModes", s.AccessModes) + populate(objectMap, "allowVolumeExpansion", s.AllowVolumeExpansion) + populate(objectMap, "dataResilience", s.DataResilience) + populate(objectMap, "failoverSpeed", s.FailoverSpeed) + populate(objectMap, "limitations", s.Limitations) + populate(objectMap, "mountOptions", s.MountOptions) + populate(objectMap, "performance", s.Performance) + populate(objectMap, "priority", s.Priority) + populate(objectMap, "provisioner", s.Provisioner) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "typeProperties", s.TypeProperties) + populate(objectMap, "volumeBindingMode", s.VolumeBindingMode) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StorageClassProperties. +func (s *StorageClassProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "accessModes": + err = unpopulate(val, "AccessModes", &s.AccessModes) + delete(rawMsg, key) + case "allowVolumeExpansion": + err = unpopulate(val, "AllowVolumeExpansion", &s.AllowVolumeExpansion) + delete(rawMsg, key) + case "dataResilience": + err = unpopulate(val, "DataResilience", &s.DataResilience) + delete(rawMsg, key) + case "failoverSpeed": + err = unpopulate(val, "FailoverSpeed", &s.FailoverSpeed) + delete(rawMsg, key) + case "limitations": + err = unpopulate(val, "Limitations", &s.Limitations) + delete(rawMsg, key) + case "mountOptions": + err = unpopulate(val, "MountOptions", &s.MountOptions) + delete(rawMsg, key) + case "performance": + err = unpopulate(val, "Performance", &s.Performance) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, "Priority", &s.Priority) + delete(rawMsg, key) + case "provisioner": + err = unpopulate(val, "Provisioner", &s.Provisioner) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + case "typeProperties": + s.TypeProperties, err = unmarshalStorageClassTypePropertiesClassification(val) + delete(rawMsg, key) + case "volumeBindingMode": + err = unpopulate(val, "VolumeBindingMode", &s.VolumeBindingMode) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type StorageClassPropertiesUpdate. +func (s StorageClassPropertiesUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "accessModes", s.AccessModes) + populate(objectMap, "allowVolumeExpansion", s.AllowVolumeExpansion) + populate(objectMap, "dataResilience", s.DataResilience) + populate(objectMap, "failoverSpeed", s.FailoverSpeed) + populate(objectMap, "limitations", s.Limitations) + populate(objectMap, "mountOptions", s.MountOptions) + populate(objectMap, "performance", s.Performance) + populate(objectMap, "priority", s.Priority) + populate(objectMap, "typeProperties", s.TypeProperties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StorageClassPropertiesUpdate. +func (s *StorageClassPropertiesUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "accessModes": + err = unpopulate(val, "AccessModes", &s.AccessModes) + delete(rawMsg, key) + case "allowVolumeExpansion": + err = unpopulate(val, "AllowVolumeExpansion", &s.AllowVolumeExpansion) + delete(rawMsg, key) + case "dataResilience": + err = unpopulate(val, "DataResilience", &s.DataResilience) + delete(rawMsg, key) + case "failoverSpeed": + err = unpopulate(val, "FailoverSpeed", &s.FailoverSpeed) + delete(rawMsg, key) + case "limitations": + err = unpopulate(val, "Limitations", &s.Limitations) + delete(rawMsg, key) + case "mountOptions": + err = unpopulate(val, "MountOptions", &s.MountOptions) + delete(rawMsg, key) + case "performance": + err = unpopulate(val, "Performance", &s.Performance) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, "Priority", &s.Priority) + delete(rawMsg, key) + case "typeProperties": + err = unpopulate(val, "TypeProperties", &s.TypeProperties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type StorageClassResource. +func (s StorageClassResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "systemData", s.SystemData) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StorageClassResource. +func (s *StorageClassResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &s.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type StorageClassResourceListResult. +func (s StorageClassResourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StorageClassResourceListResult. +func (s *StorageClassResourceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &s.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type StorageClassResourceUpdate. +func (s StorageClassResourceUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", s.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StorageClassResourceUpdate. +func (s *StorageClassResourceUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type StorageClassTypeProperties. +func (s StorageClassTypeProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StorageClassTypeProperties. +func (s *StorageClassTypeProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type StorageClassTypePropertiesUpdate. +func (s StorageClassTypePropertiesUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "azureStorageAccountKey", s.AzureStorageAccountKey) + populate(objectMap, "azureStorageAccountName", s.AzureStorageAccountName) + populate(objectMap, "backingStorageClassName", s.BackingStorageClassName) + populate(objectMap, "domain", s.Domain) + populate(objectMap, "mountPermissions", s.MountPermissions) + populate(objectMap, "onDelete", s.OnDelete) + populate(objectMap, "password", s.Password) + populate(objectMap, "server", s.Server) + populate(objectMap, "share", s.Share) + populate(objectMap, "source", s.Source) + populate(objectMap, "subDir", s.SubDir) + populate(objectMap, "username", s.Username) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StorageClassTypePropertiesUpdate. +func (s *StorageClassTypePropertiesUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "azureStorageAccountKey": + err = unpopulate(val, "AzureStorageAccountKey", &s.AzureStorageAccountKey) + delete(rawMsg, key) + case "azureStorageAccountName": + err = unpopulate(val, "AzureStorageAccountName", &s.AzureStorageAccountName) + delete(rawMsg, key) + case "backingStorageClassName": + err = unpopulate(val, "BackingStorageClassName", &s.BackingStorageClassName) + delete(rawMsg, key) + case "domain": + err = unpopulate(val, "Domain", &s.Domain) + delete(rawMsg, key) + case "mountPermissions": + err = unpopulate(val, "MountPermissions", &s.MountPermissions) + delete(rawMsg, key) + case "onDelete": + err = unpopulate(val, "OnDelete", &s.OnDelete) + delete(rawMsg, key) + case "password": + err = unpopulate(val, "Password", &s.Password) + delete(rawMsg, key) + case "server": + err = unpopulate(val, "Server", &s.Server) + delete(rawMsg, key) + case "share": + err = unpopulate(val, "Share", &s.Share) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &s.Source) + delete(rawMsg, key) + case "subDir": + err = unpopulate(val, "SubDir", &s.SubDir) + delete(rawMsg, key) + case "username": + err = unpopulate(val, "Username", &s.Username) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateTime[datetime.RFC3339](objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateTime[datetime.RFC3339](val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateTime[datetime.RFC3339](val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/local/armcontainerorchestratorruntime/zz_operations_client.go b/test/local/armcontainerorchestratorruntime/zz_operations_client.go new file mode 100644 index 000000000000..312ee02ca7b3 --- /dev/null +++ b/test/local/armcontainerorchestratorruntime/zz_operations_client.go @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcontainerorchestratorruntime + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +// +// Generated from API version 2024-03-01 +type OperationsClient struct { + internal *arm.Client +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*OperationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OperationsClient{ + internal: cl, + } + return client, nil +} + +// NewListPager - List the operations for the provider +// - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ + More: func(page OperationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OperationsClientListResponse) (OperationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OperationsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return OperationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, _ *OperationsClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.KubernetesRuntime/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240301) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsClientListResponse, error) { + result := OperationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armcontainerorchestratorruntime/zz_options.go b/test/local/armcontainerorchestratorruntime/zz_options.go new file mode 100644 index 000000000000..941dd87f4ad2 --- /dev/null +++ b/test/local/armcontainerorchestratorruntime/zz_options.go @@ -0,0 +1,102 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcontainerorchestratorruntime + +// BgpPeersClientBeginCreateOrUpdateOptions contains the optional parameters for the BgpPeersClient.BeginCreateOrUpdate method. +type BgpPeersClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// BgpPeersClientDeleteOptions contains the optional parameters for the BgpPeersClient.Delete method. +type BgpPeersClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// BgpPeersClientGetOptions contains the optional parameters for the BgpPeersClient.Get method. +type BgpPeersClientGetOptions struct { + // placeholder for future optional parameters +} + +// BgpPeersClientListOptions contains the optional parameters for the BgpPeersClient.NewListPager method. +type BgpPeersClientListOptions struct { + // placeholder for future optional parameters +} + +// LoadBalancersClientBeginCreateOrUpdateOptions contains the optional parameters for the LoadBalancersClient.BeginCreateOrUpdate +// method. +type LoadBalancersClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// LoadBalancersClientDeleteOptions contains the optional parameters for the LoadBalancersClient.Delete method. +type LoadBalancersClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// LoadBalancersClientGetOptions contains the optional parameters for the LoadBalancersClient.Get method. +type LoadBalancersClientGetOptions struct { + // placeholder for future optional parameters +} + +// LoadBalancersClientListOptions contains the optional parameters for the LoadBalancersClient.NewListPager method. +type LoadBalancersClientListOptions struct { + // placeholder for future optional parameters +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} + +// ServicesClientCreateOrUpdateOptions contains the optional parameters for the ServicesClient.CreateOrUpdate method. +type ServicesClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// ServicesClientDeleteOptions contains the optional parameters for the ServicesClient.Delete method. +type ServicesClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// ServicesClientGetOptions contains the optional parameters for the ServicesClient.Get method. +type ServicesClientGetOptions struct { + // placeholder for future optional parameters +} + +// ServicesClientListOptions contains the optional parameters for the ServicesClient.NewListPager method. +type ServicesClientListOptions struct { + // placeholder for future optional parameters +} + +// StorageClassClientBeginCreateOrUpdateOptions contains the optional parameters for the StorageClassClient.BeginCreateOrUpdate +// method. +type StorageClassClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// StorageClassClientBeginDeleteOptions contains the optional parameters for the StorageClassClient.BeginDelete method. +type StorageClassClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// StorageClassClientBeginUpdateOptions contains the optional parameters for the StorageClassClient.BeginUpdate method. +type StorageClassClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// StorageClassClientGetOptions contains the optional parameters for the StorageClassClient.Get method. +type StorageClassClientGetOptions struct { + // placeholder for future optional parameters +} + +// StorageClassClientListOptions contains the optional parameters for the StorageClassClient.NewListPager method. +type StorageClassClientListOptions struct { + // placeholder for future optional parameters +} diff --git a/test/local/armcontainerorchestratorruntime/zz_polymorphic_helpers.go b/test/local/armcontainerorchestratorruntime/zz_polymorphic_helpers.go new file mode 100644 index 000000000000..d9ee53fb79a3 --- /dev/null +++ b/test/local/armcontainerorchestratorruntime/zz_polymorphic_helpers.go @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcontainerorchestratorruntime + +import "encoding/json" + +func unmarshalStorageClassTypePropertiesClassification(rawMsg json.RawMessage) (StorageClassTypePropertiesClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b StorageClassTypePropertiesClassification + switch m["type"] { + case string(SCTypeBlob): + b = &BlobStorageClassTypeProperties{} + case string(SCTypeNFS): + b = &NfsStorageClassTypeProperties{} + case string(SCTypeNative): + b = &NativeStorageClassTypeProperties{} + case string(SCTypeRWX): + b = &RwxStorageClassTypeProperties{} + case string(SCTypeSMB): + b = &SmbStorageClassTypeProperties{} + default: + b = &StorageClassTypeProperties{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} diff --git a/test/local/armcontainerorchestratorruntime/zz_responses.go b/test/local/armcontainerorchestratorruntime/zz_responses.go new file mode 100644 index 000000000000..90869c054503 --- /dev/null +++ b/test/local/armcontainerorchestratorruntime/zz_responses.go @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcontainerorchestratorruntime + +// BgpPeersClientCreateOrUpdateResponse contains the response from method BgpPeersClient.BeginCreateOrUpdate. +type BgpPeersClientCreateOrUpdateResponse struct { + // A BgpPeer resource for an Arc connected cluster (Microsoft.Kubernetes/connectedClusters) + BgpPeer +} + +// BgpPeersClientDeleteResponse contains the response from method BgpPeersClient.Delete. +type BgpPeersClientDeleteResponse struct { + // placeholder for future response values +} + +// BgpPeersClientGetResponse contains the response from method BgpPeersClient.Get. +type BgpPeersClientGetResponse struct { + // A BgpPeer resource for an Arc connected cluster (Microsoft.Kubernetes/connectedClusters) + BgpPeer +} + +// BgpPeersClientListResponse contains the response from method BgpPeersClient.NewListPager. +type BgpPeersClientListResponse struct { + // The response of a BgpPeer list operation. + BgpPeerListResult +} + +// LoadBalancersClientCreateOrUpdateResponse contains the response from method LoadBalancersClient.BeginCreateOrUpdate. +type LoadBalancersClientCreateOrUpdateResponse struct { + // A LoadBalancer resource for an Arc connected cluster (Microsoft.Kubernetes/connectedClusters) + LoadBalancer +} + +// LoadBalancersClientDeleteResponse contains the response from method LoadBalancersClient.Delete. +type LoadBalancersClientDeleteResponse struct { + // placeholder for future response values +} + +// LoadBalancersClientGetResponse contains the response from method LoadBalancersClient.Get. +type LoadBalancersClientGetResponse struct { + // A LoadBalancer resource for an Arc connected cluster (Microsoft.Kubernetes/connectedClusters) + LoadBalancer +} + +// LoadBalancersClientListResponse contains the response from method LoadBalancersClient.NewListPager. +type LoadBalancersClientListResponse struct { + // The response of a LoadBalancer list operation. + LoadBalancerListResult +} + +// OperationsClientListResponse contains the response from method OperationsClient.NewListPager. +type OperationsClientListResponse struct { + // A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. + OperationListResult +} + +// ServicesClientCreateOrUpdateResponse contains the response from method ServicesClient.CreateOrUpdate. +type ServicesClientCreateOrUpdateResponse struct { + // A Service resource for an Arc connected cluster (Microsoft.Kubernetes/connectedClusters) + ServiceResource +} + +// ServicesClientDeleteResponse contains the response from method ServicesClient.Delete. +type ServicesClientDeleteResponse struct { + // placeholder for future response values +} + +// ServicesClientGetResponse contains the response from method ServicesClient.Get. +type ServicesClientGetResponse struct { + // A Service resource for an Arc connected cluster (Microsoft.Kubernetes/connectedClusters) + ServiceResource +} + +// ServicesClientListResponse contains the response from method ServicesClient.NewListPager. +type ServicesClientListResponse struct { + // The response of a ServiceResource list operation. + ServiceResourceListResult +} + +// StorageClassClientCreateOrUpdateResponse contains the response from method StorageClassClient.BeginCreateOrUpdate. +type StorageClassClientCreateOrUpdateResponse struct { + // A StorageClass resource for an Arc connected cluster (Microsoft.Kubernetes/connectedClusters) + StorageClassResource +} + +// StorageClassClientDeleteResponse contains the response from method StorageClassClient.BeginDelete. +type StorageClassClientDeleteResponse struct { + // placeholder for future response values +} + +// StorageClassClientGetResponse contains the response from method StorageClassClient.Get. +type StorageClassClientGetResponse struct { + // A StorageClass resource for an Arc connected cluster (Microsoft.Kubernetes/connectedClusters) + StorageClassResource +} + +// StorageClassClientListResponse contains the response from method StorageClassClient.NewListPager. +type StorageClassClientListResponse struct { + // The response of a StorageClassResource list operation. + StorageClassResourceListResult +} + +// StorageClassClientUpdateResponse contains the response from method StorageClassClient.BeginUpdate. +type StorageClassClientUpdateResponse struct { + // A StorageClass resource for an Arc connected cluster (Microsoft.Kubernetes/connectedClusters) + StorageClassResource +} diff --git a/test/local/armcontainerorchestratorruntime/zz_services_client.go b/test/local/armcontainerorchestratorruntime/zz_services_client.go new file mode 100644 index 000000000000..e38357756e94 --- /dev/null +++ b/test/local/armcontainerorchestratorruntime/zz_services_client.go @@ -0,0 +1,260 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcontainerorchestratorruntime + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ServicesClient contains the methods for the Services group. +// Don't use this type directly, use NewServicesClient() instead. +// +// Generated from API version 2024-03-01 +type ServicesClient struct { + internal *arm.Client +} + +// NewServicesClient creates a new instance of ServicesClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewServicesClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*ServicesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ServicesClient{ + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Create a ServiceResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - serviceName - The name of the the service +// - resource - Resource create parameters. +// - options - ServicesClientCreateOrUpdateOptions contains the optional parameters for the ServicesClient.CreateOrUpdate method. +func (client *ServicesClient) CreateOrUpdate(ctx context.Context, resourceURI string, serviceName string, resource ServiceResource, options *ServicesClientCreateOrUpdateOptions) (ServicesClientCreateOrUpdateResponse, error) { + var err error + const operationName = "ServicesClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceURI, serviceName, resource, options) + if err != nil { + return ServicesClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServicesClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return ServicesClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *ServicesClient) createOrUpdateCreateRequest(ctx context.Context, resourceURI string, serviceName string, resource ServiceResource, _ *ServicesClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.KubernetesRuntime/services/{serviceName}" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240301) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *ServicesClient) createOrUpdateHandleResponse(resp *http.Response) (ServicesClientCreateOrUpdateResponse, error) { + result := ServicesClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ServiceResource); err != nil { + return ServicesClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Delete a ServiceResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - serviceName - The name of the the service +// - options - ServicesClientDeleteOptions contains the optional parameters for the ServicesClient.Delete method. +func (client *ServicesClient) Delete(ctx context.Context, resourceURI string, serviceName string, options *ServicesClientDeleteOptions) (ServicesClientDeleteResponse, error) { + var err error + const operationName = "ServicesClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceURI, serviceName, options) + if err != nil { + return ServicesClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServicesClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ServicesClientDeleteResponse{}, err + } + return ServicesClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ServicesClient) deleteCreateRequest(ctx context.Context, resourceURI string, serviceName string, _ *ServicesClientDeleteOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.KubernetesRuntime/services/{serviceName}" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240301) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a ServiceResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - serviceName - The name of the the service +// - options - ServicesClientGetOptions contains the optional parameters for the ServicesClient.Get method. +func (client *ServicesClient) Get(ctx context.Context, resourceURI string, serviceName string, options *ServicesClientGetOptions) (ServicesClientGetResponse, error) { + var err error + const operationName = "ServicesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceURI, serviceName, options) + if err != nil { + return ServicesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServicesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ServicesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ServicesClient) getCreateRequest(ctx context.Context, resourceURI string, serviceName string, _ *ServicesClientGetOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.KubernetesRuntime/services/{serviceName}" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + if serviceName == "" { + return nil, errors.New("parameter serviceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{serviceName}", url.PathEscape(serviceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240301) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ServicesClient) getHandleResponse(resp *http.Response) (ServicesClientGetResponse, error) { + result := ServicesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ServiceResource); err != nil { + return ServicesClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List ServiceResource resources by parent +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - options - ServicesClientListOptions contains the optional parameters for the ServicesClient.NewListPager method. +func (client *ServicesClient) NewListPager(resourceURI string, options *ServicesClientListOptions) *runtime.Pager[ServicesClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[ServicesClientListResponse]{ + More: func(page ServicesClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ServicesClientListResponse) (ServicesClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ServicesClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceURI, options) + }, nil) + if err != nil { + return ServicesClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *ServicesClient) listCreateRequest(ctx context.Context, resourceURI string, _ *ServicesClientListOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.KubernetesRuntime/services" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240301) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ServicesClient) listHandleResponse(resp *http.Response) (ServicesClientListResponse, error) { + result := ServicesClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ServiceResourceListResult); err != nil { + return ServicesClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armcontainerorchestratorruntime/zz_storageclass_client.go b/test/local/armcontainerorchestratorruntime/zz_storageclass_client.go new file mode 100644 index 000000000000..67c086498eac --- /dev/null +++ b/test/local/armcontainerorchestratorruntime/zz_storageclass_client.go @@ -0,0 +1,364 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armcontainerorchestratorruntime + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// StorageClassClient contains the methods for the StorageClass group. +// Don't use this type directly, use NewStorageClassClient() instead. +// +// Generated from API version 2024-03-01 +type StorageClassClient struct { + internal *arm.Client +} + +// NewStorageClassClient creates a new instance of StorageClassClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewStorageClassClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*StorageClassClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &StorageClassClient{ + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create a StorageClassResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - storageClassName - The name of the the storage class +// - resource - Resource create parameters. +// - options - StorageClassClientBeginCreateOrUpdateOptions contains the optional parameters for the StorageClassClient.BeginCreateOrUpdate +// method. +func (client *StorageClassClient) BeginCreateOrUpdate(ctx context.Context, resourceURI string, storageClassName string, resource StorageClassResource, options *StorageClassClientBeginCreateOrUpdateOptions) (*runtime.Poller[StorageClassClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceURI, storageClassName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[StorageClassClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[StorageClassClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create a StorageClassResource +// If the operation fails it returns an *azcore.ResponseError type. +func (client *StorageClassClient) createOrUpdate(ctx context.Context, resourceURI string, storageClassName string, resource StorageClassResource, options *StorageClassClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "StorageClassClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceURI, storageClassName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *StorageClassClient) createOrUpdateCreateRequest(ctx context.Context, resourceURI string, storageClassName string, resource StorageClassResource, _ *StorageClassClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.KubernetesRuntime/storageClasses/{storageClassName}" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + if storageClassName == "" { + return nil, errors.New("parameter storageClassName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{storageClassName}", url.PathEscape(storageClassName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240301) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a StorageClassResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - storageClassName - The name of the the storage class +// - options - StorageClassClientBeginDeleteOptions contains the optional parameters for the StorageClassClient.BeginDelete +// method. +func (client *StorageClassClient) BeginDelete(ctx context.Context, resourceURI string, storageClassName string, options *StorageClassClientBeginDeleteOptions) (*runtime.Poller[StorageClassClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceURI, storageClassName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[StorageClassClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[StorageClassClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a StorageClassResource +// If the operation fails it returns an *azcore.ResponseError type. +func (client *StorageClassClient) deleteOperation(ctx context.Context, resourceURI string, storageClassName string, options *StorageClassClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "StorageClassClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceURI, storageClassName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *StorageClassClient) deleteCreateRequest(ctx context.Context, resourceURI string, storageClassName string, _ *StorageClassClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.KubernetesRuntime/storageClasses/{storageClassName}" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + if storageClassName == "" { + return nil, errors.New("parameter storageClassName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{storageClassName}", url.PathEscape(storageClassName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240301) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a StorageClassResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - storageClassName - The name of the the storage class +// - options - StorageClassClientGetOptions contains the optional parameters for the StorageClassClient.Get method. +func (client *StorageClassClient) Get(ctx context.Context, resourceURI string, storageClassName string, options *StorageClassClientGetOptions) (StorageClassClientGetResponse, error) { + var err error + const operationName = "StorageClassClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceURI, storageClassName, options) + if err != nil { + return StorageClassClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return StorageClassClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return StorageClassClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *StorageClassClient) getCreateRequest(ctx context.Context, resourceURI string, storageClassName string, _ *StorageClassClientGetOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.KubernetesRuntime/storageClasses/{storageClassName}" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + if storageClassName == "" { + return nil, errors.New("parameter storageClassName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{storageClassName}", url.PathEscape(storageClassName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240301) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *StorageClassClient) getHandleResponse(resp *http.Response) (StorageClassClientGetResponse, error) { + result := StorageClassClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.StorageClassResource); err != nil { + return StorageClassClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List StorageClassResource resources by parent +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - options - StorageClassClientListOptions contains the optional parameters for the StorageClassClient.NewListPager method. +func (client *StorageClassClient) NewListPager(resourceURI string, options *StorageClassClientListOptions) *runtime.Pager[StorageClassClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[StorageClassClientListResponse]{ + More: func(page StorageClassClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *StorageClassClientListResponse) (StorageClassClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "StorageClassClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceURI, options) + }, nil) + if err != nil { + return StorageClassClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *StorageClassClient) listCreateRequest(ctx context.Context, resourceURI string, _ *StorageClassClientListOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.KubernetesRuntime/storageClasses" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240301) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *StorageClassClient) listHandleResponse(resp *http.Response) (StorageClassClientListResponse, error) { + result := StorageClassClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.StorageClassResourceListResult); err != nil { + return StorageClassClientListResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update a StorageClassResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - storageClassName - The name of the the storage class +// - properties - The resource properties to be updated. +// - options - StorageClassClientBeginUpdateOptions contains the optional parameters for the StorageClassClient.BeginUpdate +// method. +func (client *StorageClassClient) BeginUpdate(ctx context.Context, resourceURI string, storageClassName string, properties StorageClassResourceUpdate, options *StorageClassClientBeginUpdateOptions) (*runtime.Poller[StorageClassClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceURI, storageClassName, properties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[StorageClassClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[StorageClassClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a StorageClassResource +// If the operation fails it returns an *azcore.ResponseError type. +func (client *StorageClassClient) update(ctx context.Context, resourceURI string, storageClassName string, properties StorageClassResourceUpdate, options *StorageClassClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "StorageClassClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceURI, storageClassName, properties, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *StorageClassClient) updateCreateRequest(ctx context.Context, resourceURI string, storageClassName string, properties StorageClassResourceUpdate, _ *StorageClassClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.KubernetesRuntime/storageClasses/{storageClassName}" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + if storageClassName == "" { + return nil, errors.New("parameter storageClassName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{storageClassName}", url.PathEscape(storageClassName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240301) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armcontainerorchestratorruntime/zz_version.go b/test/local/armcontainerorchestratorruntime/zz_version.go new file mode 100644 index 000000000000..a1c8712e7324 --- /dev/null +++ b/test/local/armcontainerorchestratorruntime/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package armcontainerorchestratorruntime + +const ( + moduleName = "armcontainerorchestratorruntime" + moduleVersion = "v0.1.0" +) diff --git a/test/local/armdatabasewatcher/LICENSE.txt b/test/local/armdatabasewatcher/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/local/armdatabasewatcher/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/local/armdatabasewatcher/fake/zz_alertruleresources_server.go b/test/local/armdatabasewatcher/fake/zz_alertruleresources_server.go new file mode 100644 index 000000000000..f46a25de5864 --- /dev/null +++ b/test/local/armdatabasewatcher/fake/zz_alertruleresources_server.go @@ -0,0 +1,263 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armdatabasewatcher" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// AlertRuleResourcesServer is a fake server for instances of the armdatabasewatcher.AlertRuleResourcesClient type. +type AlertRuleResourcesServer struct { + // CreateOrUpdate is the fake for method AlertRuleResourcesClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, watcherName string, alertRuleResourceName string, resource armdatabasewatcher.AlertRuleResource, options *armdatabasewatcher.AlertRuleResourcesClientCreateOrUpdateOptions) (resp azfake.Responder[armdatabasewatcher.AlertRuleResourcesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method AlertRuleResourcesClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceGroupName string, watcherName string, alertRuleResourceName string, options *armdatabasewatcher.AlertRuleResourcesClientDeleteOptions) (resp azfake.Responder[armdatabasewatcher.AlertRuleResourcesClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method AlertRuleResourcesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, watcherName string, alertRuleResourceName string, options *armdatabasewatcher.AlertRuleResourcesClientGetOptions) (resp azfake.Responder[armdatabasewatcher.AlertRuleResourcesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByParentPager is the fake for method AlertRuleResourcesClient.NewListByParentPager + // HTTP status codes to indicate success: http.StatusOK + NewListByParentPager func(resourceGroupName string, watcherName string, options *armdatabasewatcher.AlertRuleResourcesClientListByParentOptions) (resp azfake.PagerResponder[armdatabasewatcher.AlertRuleResourcesClientListByParentResponse]) +} + +// NewAlertRuleResourcesServerTransport creates a new instance of AlertRuleResourcesServerTransport with the provided implementation. +// The returned AlertRuleResourcesServerTransport instance is connected to an instance of armdatabasewatcher.AlertRuleResourcesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAlertRuleResourcesServerTransport(srv *AlertRuleResourcesServer) *AlertRuleResourcesServerTransport { + return &AlertRuleResourcesServerTransport{ + srv: srv, + newListByParentPager: newTracker[azfake.PagerResponder[armdatabasewatcher.AlertRuleResourcesClientListByParentResponse]](), + } +} + +// AlertRuleResourcesServerTransport connects instances of armdatabasewatcher.AlertRuleResourcesClient to instances of AlertRuleResourcesServer. +// Don't use this type directly, use NewAlertRuleResourcesServerTransport instead. +type AlertRuleResourcesServerTransport struct { + srv *AlertRuleResourcesServer + newListByParentPager *tracker[azfake.PagerResponder[armdatabasewatcher.AlertRuleResourcesClientListByParentResponse]] +} + +// Do implements the policy.Transporter interface for AlertRuleResourcesServerTransport. +func (a *AlertRuleResourcesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *AlertRuleResourcesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if alertRuleResourcesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = alertRuleResourcesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "AlertRuleResourcesClient.CreateOrUpdate": + res.resp, res.err = a.dispatchCreateOrUpdate(req) + case "AlertRuleResourcesClient.Delete": + res.resp, res.err = a.dispatchDelete(req) + case "AlertRuleResourcesClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "AlertRuleResourcesClient.NewListByParentPager": + res.resp, res.err = a.dispatchNewListByParentPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *AlertRuleResourcesServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if a.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseWatcher/watchers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/alertRuleResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armdatabasewatcher.AlertRuleResource](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + watcherNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("watcherName")]) + if err != nil { + return nil, err + } + alertRuleResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("alertRuleResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, watcherNameParam, alertRuleResourceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).AlertRuleResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AlertRuleResourcesServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if a.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseWatcher/watchers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/alertRuleResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + watcherNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("watcherName")]) + if err != nil { + return nil, err + } + alertRuleResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("alertRuleResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Delete(req.Context(), resourceGroupNameParam, watcherNameParam, alertRuleResourceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AlertRuleResourcesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseWatcher/watchers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/alertRuleResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + watcherNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("watcherName")]) + if err != nil { + return nil, err + } + alertRuleResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("alertRuleResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Get(req.Context(), resourceGroupNameParam, watcherNameParam, alertRuleResourceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).AlertRuleResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AlertRuleResourcesServerTransport) dispatchNewListByParentPager(req *http.Request) (*http.Response, error) { + if a.srv.NewListByParentPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByParentPager not implemented")} + } + newListByParentPager := a.newListByParentPager.get(req) + if newListByParentPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseWatcher/watchers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/alertRuleResources` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + watcherNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("watcherName")]) + if err != nil { + return nil, err + } + resp := a.srv.NewListByParentPager(resourceGroupNameParam, watcherNameParam, nil) + newListByParentPager = &resp + a.newListByParentPager.add(req, newListByParentPager) + server.PagerResponderInjectNextLinks(newListByParentPager, req, func(page *armdatabasewatcher.AlertRuleResourcesClientListByParentResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByParentPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListByParentPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByParentPager) { + a.newListByParentPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to AlertRuleResourcesServerTransport +var alertRuleResourcesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armdatabasewatcher/fake/zz_healthvalidations_server.go b/test/local/armdatabasewatcher/fake/zz_healthvalidations_server.go new file mode 100644 index 000000000000..a387361d9bcc --- /dev/null +++ b/test/local/armdatabasewatcher/fake/zz_healthvalidations_server.go @@ -0,0 +1,229 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armdatabasewatcher" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// HealthValidationsServer is a fake server for instances of the armdatabasewatcher.HealthValidationsClient type. +type HealthValidationsServer struct { + // Get is the fake for method HealthValidationsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, watcherName string, healthValidationName string, options *armdatabasewatcher.HealthValidationsClientGetOptions) (resp azfake.Responder[armdatabasewatcher.HealthValidationsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByParentPager is the fake for method HealthValidationsClient.NewListByParentPager + // HTTP status codes to indicate success: http.StatusOK + NewListByParentPager func(resourceGroupName string, watcherName string, options *armdatabasewatcher.HealthValidationsClientListByParentOptions) (resp azfake.PagerResponder[armdatabasewatcher.HealthValidationsClientListByParentResponse]) + + // BeginStartValidation is the fake for method HealthValidationsClient.BeginStartValidation + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginStartValidation func(ctx context.Context, resourceGroupName string, watcherName string, healthValidationName string, options *armdatabasewatcher.HealthValidationsClientBeginStartValidationOptions) (resp azfake.PollerResponder[armdatabasewatcher.HealthValidationsClientStartValidationResponse], errResp azfake.ErrorResponder) +} + +// NewHealthValidationsServerTransport creates a new instance of HealthValidationsServerTransport with the provided implementation. +// The returned HealthValidationsServerTransport instance is connected to an instance of armdatabasewatcher.HealthValidationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewHealthValidationsServerTransport(srv *HealthValidationsServer) *HealthValidationsServerTransport { + return &HealthValidationsServerTransport{ + srv: srv, + newListByParentPager: newTracker[azfake.PagerResponder[armdatabasewatcher.HealthValidationsClientListByParentResponse]](), + beginStartValidation: newTracker[azfake.PollerResponder[armdatabasewatcher.HealthValidationsClientStartValidationResponse]](), + } +} + +// HealthValidationsServerTransport connects instances of armdatabasewatcher.HealthValidationsClient to instances of HealthValidationsServer. +// Don't use this type directly, use NewHealthValidationsServerTransport instead. +type HealthValidationsServerTransport struct { + srv *HealthValidationsServer + newListByParentPager *tracker[azfake.PagerResponder[armdatabasewatcher.HealthValidationsClientListByParentResponse]] + beginStartValidation *tracker[azfake.PollerResponder[armdatabasewatcher.HealthValidationsClientStartValidationResponse]] +} + +// Do implements the policy.Transporter interface for HealthValidationsServerTransport. +func (h *HealthValidationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return h.dispatchToMethodFake(req, method) +} + +func (h *HealthValidationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if healthValidationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = healthValidationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "HealthValidationsClient.Get": + res.resp, res.err = h.dispatchGet(req) + case "HealthValidationsClient.NewListByParentPager": + res.resp, res.err = h.dispatchNewListByParentPager(req) + case "HealthValidationsClient.BeginStartValidation": + res.resp, res.err = h.dispatchBeginStartValidation(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (h *HealthValidationsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if h.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseWatcher/watchers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/healthValidations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + watcherNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("watcherName")]) + if err != nil { + return nil, err + } + healthValidationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthValidationName")]) + if err != nil { + return nil, err + } + respr, errRespr := h.srv.Get(req.Context(), resourceGroupNameParam, watcherNameParam, healthValidationNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).HealthValidation, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (h *HealthValidationsServerTransport) dispatchNewListByParentPager(req *http.Request) (*http.Response, error) { + if h.srv.NewListByParentPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByParentPager not implemented")} + } + newListByParentPager := h.newListByParentPager.get(req) + if newListByParentPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseWatcher/watchers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/healthValidations` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + watcherNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("watcherName")]) + if err != nil { + return nil, err + } + resp := h.srv.NewListByParentPager(resourceGroupNameParam, watcherNameParam, nil) + newListByParentPager = &resp + h.newListByParentPager.add(req, newListByParentPager) + server.PagerResponderInjectNextLinks(newListByParentPager, req, func(page *armdatabasewatcher.HealthValidationsClientListByParentResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByParentPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + h.newListByParentPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByParentPager) { + h.newListByParentPager.remove(req) + } + return resp, nil +} + +func (h *HealthValidationsServerTransport) dispatchBeginStartValidation(req *http.Request) (*http.Response, error) { + if h.srv.BeginStartValidation == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginStartValidation not implemented")} + } + beginStartValidation := h.beginStartValidation.get(req) + if beginStartValidation == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseWatcher/watchers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/healthValidations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/startValidation` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + watcherNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("watcherName")]) + if err != nil { + return nil, err + } + healthValidationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("healthValidationName")]) + if err != nil { + return nil, err + } + respr, errRespr := h.srv.BeginStartValidation(req.Context(), resourceGroupNameParam, watcherNameParam, healthValidationNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginStartValidation = &respr + h.beginStartValidation.add(req, beginStartValidation) + } + + resp, err := server.PollerResponderNext(beginStartValidation, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + h.beginStartValidation.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginStartValidation) { + h.beginStartValidation.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to HealthValidationsServerTransport +var healthValidationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armdatabasewatcher/fake/zz_internal.go b/test/local/armdatabasewatcher/fake/zz_internal.go new file mode 100644 index 000000000000..590b4d743e97 --- /dev/null +++ b/test/local/armdatabasewatcher/fake/zz_internal.go @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/local/armdatabasewatcher/fake/zz_operations_server.go b/test/local/armdatabasewatcher/fake/zz_operations_server.go new file mode 100644 index 000000000000..7b2bf375a60d --- /dev/null +++ b/test/local/armdatabasewatcher/fake/zz_operations_server.go @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armdatabasewatcher" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "slices" +) + +// OperationsServer is a fake server for instances of the armdatabasewatcher.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armdatabasewatcher.OperationsClientListOptions) (resp azfake.PagerResponder[armdatabasewatcher.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of armdatabasewatcher.OperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOperationsServerTransport(srv *OperationsServer) *OperationsServerTransport { + return &OperationsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armdatabasewatcher.OperationsClientListResponse]](), + } +} + +// OperationsServerTransport connects instances of armdatabasewatcher.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[armdatabasewatcher.OperationsClientListResponse]] +} + +// Do implements the policy.Transporter interface for OperationsServerTransport. +func (o *OperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if operationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = operationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OperationsClient.NewListPager": + res.resp, res.err = o.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OperationsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := o.newListPager.get(req) + if newListPager == nil { + resp := o.srv.NewListPager(nil) + newListPager = &resp + o.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armdatabasewatcher.OperationsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + o.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + o.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OperationsServerTransport +var operationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armdatabasewatcher/fake/zz_server_factory.go b/test/local/armdatabasewatcher/fake/zz_server_factory.go new file mode 100644 index 000000000000..65a7fb9c7f2c --- /dev/null +++ b/test/local/armdatabasewatcher/fake/zz_server_factory.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armdatabasewatcher.ClientFactory type. +type ServerFactory struct { + // AlertRuleResourcesServer contains the fakes for client AlertRuleResourcesClient + AlertRuleResourcesServer AlertRuleResourcesServer + + // HealthValidationsServer contains the fakes for client HealthValidationsClient + HealthValidationsServer HealthValidationsServer + + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer + + // SharedPrivateLinkResourcesServer contains the fakes for client SharedPrivateLinkResourcesClient + SharedPrivateLinkResourcesServer SharedPrivateLinkResourcesServer + + // TargetsServer contains the fakes for client TargetsClient + TargetsServer TargetsServer + + // WatchersServer contains the fakes for client WatchersClient + WatchersServer WatchersServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armdatabasewatcher.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of armdatabasewatcher.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trAlertRuleResourcesServer *AlertRuleResourcesServerTransport + trHealthValidationsServer *HealthValidationsServerTransport + trOperationsServer *OperationsServerTransport + trSharedPrivateLinkResourcesServer *SharedPrivateLinkResourcesServerTransport + trTargetsServer *TargetsServerTransport + trWatchersServer *WatchersServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "AlertRuleResourcesClient": + initServer(&s.trMu, &s.trAlertRuleResourcesServer, func() *AlertRuleResourcesServerTransport { + return NewAlertRuleResourcesServerTransport(&s.srv.AlertRuleResourcesServer) + }) + resp, err = s.trAlertRuleResourcesServer.Do(req) + case "HealthValidationsClient": + initServer(&s.trMu, &s.trHealthValidationsServer, func() *HealthValidationsServerTransport { + return NewHealthValidationsServerTransport(&s.srv.HealthValidationsServer) + }) + resp, err = s.trHealthValidationsServer.Do(req) + case "OperationsClient": + initServer(&s.trMu, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + resp, err = s.trOperationsServer.Do(req) + case "SharedPrivateLinkResourcesClient": + initServer(&s.trMu, &s.trSharedPrivateLinkResourcesServer, func() *SharedPrivateLinkResourcesServerTransport { + return NewSharedPrivateLinkResourcesServerTransport(&s.srv.SharedPrivateLinkResourcesServer) + }) + resp, err = s.trSharedPrivateLinkResourcesServer.Do(req) + case "TargetsClient": + initServer(&s.trMu, &s.trTargetsServer, func() *TargetsServerTransport { return NewTargetsServerTransport(&s.srv.TargetsServer) }) + resp, err = s.trTargetsServer.Do(req) + case "WatchersClient": + initServer(&s.trMu, &s.trWatchersServer, func() *WatchersServerTransport { return NewWatchersServerTransport(&s.srv.WatchersServer) }) + resp, err = s.trWatchersServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} diff --git a/test/local/armdatabasewatcher/fake/zz_sharedprivatelinkresources_server.go b/test/local/armdatabasewatcher/fake/zz_sharedprivatelinkresources_server.go new file mode 100644 index 000000000000..0418297101d4 --- /dev/null +++ b/test/local/armdatabasewatcher/fake/zz_sharedprivatelinkresources_server.go @@ -0,0 +1,289 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armdatabasewatcher" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// SharedPrivateLinkResourcesServer is a fake server for instances of the armdatabasewatcher.SharedPrivateLinkResourcesClient type. +type SharedPrivateLinkResourcesServer struct { + // BeginCreate is the fake for method SharedPrivateLinkResourcesClient.BeginCreate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreate func(ctx context.Context, resourceGroupName string, watcherName string, sharedPrivateLinkResourceName string, resource armdatabasewatcher.SharedPrivateLinkResource, options *armdatabasewatcher.SharedPrivateLinkResourcesClientBeginCreateOptions) (resp azfake.PollerResponder[armdatabasewatcher.SharedPrivateLinkResourcesClientCreateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method SharedPrivateLinkResourcesClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, watcherName string, sharedPrivateLinkResourceName string, options *armdatabasewatcher.SharedPrivateLinkResourcesClientBeginDeleteOptions) (resp azfake.PollerResponder[armdatabasewatcher.SharedPrivateLinkResourcesClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method SharedPrivateLinkResourcesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, watcherName string, sharedPrivateLinkResourceName string, options *armdatabasewatcher.SharedPrivateLinkResourcesClientGetOptions) (resp azfake.Responder[armdatabasewatcher.SharedPrivateLinkResourcesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByWatcherPager is the fake for method SharedPrivateLinkResourcesClient.NewListByWatcherPager + // HTTP status codes to indicate success: http.StatusOK + NewListByWatcherPager func(resourceGroupName string, watcherName string, options *armdatabasewatcher.SharedPrivateLinkResourcesClientListByWatcherOptions) (resp azfake.PagerResponder[armdatabasewatcher.SharedPrivateLinkResourcesClientListByWatcherResponse]) +} + +// NewSharedPrivateLinkResourcesServerTransport creates a new instance of SharedPrivateLinkResourcesServerTransport with the provided implementation. +// The returned SharedPrivateLinkResourcesServerTransport instance is connected to an instance of armdatabasewatcher.SharedPrivateLinkResourcesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSharedPrivateLinkResourcesServerTransport(srv *SharedPrivateLinkResourcesServer) *SharedPrivateLinkResourcesServerTransport { + return &SharedPrivateLinkResourcesServerTransport{ + srv: srv, + beginCreate: newTracker[azfake.PollerResponder[armdatabasewatcher.SharedPrivateLinkResourcesClientCreateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armdatabasewatcher.SharedPrivateLinkResourcesClientDeleteResponse]](), + newListByWatcherPager: newTracker[azfake.PagerResponder[armdatabasewatcher.SharedPrivateLinkResourcesClientListByWatcherResponse]](), + } +} + +// SharedPrivateLinkResourcesServerTransport connects instances of armdatabasewatcher.SharedPrivateLinkResourcesClient to instances of SharedPrivateLinkResourcesServer. +// Don't use this type directly, use NewSharedPrivateLinkResourcesServerTransport instead. +type SharedPrivateLinkResourcesServerTransport struct { + srv *SharedPrivateLinkResourcesServer + beginCreate *tracker[azfake.PollerResponder[armdatabasewatcher.SharedPrivateLinkResourcesClientCreateResponse]] + beginDelete *tracker[azfake.PollerResponder[armdatabasewatcher.SharedPrivateLinkResourcesClientDeleteResponse]] + newListByWatcherPager *tracker[azfake.PagerResponder[armdatabasewatcher.SharedPrivateLinkResourcesClientListByWatcherResponse]] +} + +// Do implements the policy.Transporter interface for SharedPrivateLinkResourcesServerTransport. +func (s *SharedPrivateLinkResourcesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *SharedPrivateLinkResourcesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if sharedPrivateLinkResourcesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = sharedPrivateLinkResourcesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SharedPrivateLinkResourcesClient.BeginCreate": + res.resp, res.err = s.dispatchBeginCreate(req) + case "SharedPrivateLinkResourcesClient.BeginDelete": + res.resp, res.err = s.dispatchBeginDelete(req) + case "SharedPrivateLinkResourcesClient.Get": + res.resp, res.err = s.dispatchGet(req) + case "SharedPrivateLinkResourcesClient.NewListByWatcherPager": + res.resp, res.err = s.dispatchNewListByWatcherPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *SharedPrivateLinkResourcesServerTransport) dispatchBeginCreate(req *http.Request) (*http.Response, error) { + if s.srv.BeginCreate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreate not implemented")} + } + beginCreate := s.beginCreate.get(req) + if beginCreate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseWatcher/watchers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/sharedPrivateLinkResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armdatabasewatcher.SharedPrivateLinkResource](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + watcherNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("watcherName")]) + if err != nil { + return nil, err + } + sharedPrivateLinkResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("sharedPrivateLinkResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.BeginCreate(req.Context(), resourceGroupNameParam, watcherNameParam, sharedPrivateLinkResourceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreate = &respr + s.beginCreate.add(req, beginCreate) + } + + resp, err := server.PollerResponderNext(beginCreate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + s.beginCreate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreate) { + s.beginCreate.remove(req) + } + + return resp, nil +} + +func (s *SharedPrivateLinkResourcesServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if s.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := s.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseWatcher/watchers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/sharedPrivateLinkResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + watcherNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("watcherName")]) + if err != nil { + return nil, err + } + sharedPrivateLinkResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("sharedPrivateLinkResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.BeginDelete(req.Context(), resourceGroupNameParam, watcherNameParam, sharedPrivateLinkResourceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + s.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + s.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + s.beginDelete.remove(req) + } + + return resp, nil +} + +func (s *SharedPrivateLinkResourcesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if s.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseWatcher/watchers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/sharedPrivateLinkResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + watcherNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("watcherName")]) + if err != nil { + return nil, err + } + sharedPrivateLinkResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("sharedPrivateLinkResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Get(req.Context(), resourceGroupNameParam, watcherNameParam, sharedPrivateLinkResourceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).SharedPrivateLinkResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SharedPrivateLinkResourcesServerTransport) dispatchNewListByWatcherPager(req *http.Request) (*http.Response, error) { + if s.srv.NewListByWatcherPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByWatcherPager not implemented")} + } + newListByWatcherPager := s.newListByWatcherPager.get(req) + if newListByWatcherPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseWatcher/watchers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/sharedPrivateLinkResources` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + watcherNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("watcherName")]) + if err != nil { + return nil, err + } + resp := s.srv.NewListByWatcherPager(resourceGroupNameParam, watcherNameParam, nil) + newListByWatcherPager = &resp + s.newListByWatcherPager.add(req, newListByWatcherPager) + server.PagerResponderInjectNextLinks(newListByWatcherPager, req, func(page *armdatabasewatcher.SharedPrivateLinkResourcesClientListByWatcherResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByWatcherPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + s.newListByWatcherPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByWatcherPager) { + s.newListByWatcherPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SharedPrivateLinkResourcesServerTransport +var sharedPrivateLinkResourcesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armdatabasewatcher/fake/zz_targets_server.go b/test/local/armdatabasewatcher/fake/zz_targets_server.go new file mode 100644 index 000000000000..386a60967b9d --- /dev/null +++ b/test/local/armdatabasewatcher/fake/zz_targets_server.go @@ -0,0 +1,263 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armdatabasewatcher" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// TargetsServer is a fake server for instances of the armdatabasewatcher.TargetsClient type. +type TargetsServer struct { + // CreateOrUpdate is the fake for method TargetsClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceGroupName string, watcherName string, targetName string, resource armdatabasewatcher.Target, options *armdatabasewatcher.TargetsClientCreateOrUpdateOptions) (resp azfake.Responder[armdatabasewatcher.TargetsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method TargetsClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceGroupName string, watcherName string, targetName string, options *armdatabasewatcher.TargetsClientDeleteOptions) (resp azfake.Responder[armdatabasewatcher.TargetsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method TargetsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, watcherName string, targetName string, options *armdatabasewatcher.TargetsClientGetOptions) (resp azfake.Responder[armdatabasewatcher.TargetsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByWatcherPager is the fake for method TargetsClient.NewListByWatcherPager + // HTTP status codes to indicate success: http.StatusOK + NewListByWatcherPager func(resourceGroupName string, watcherName string, options *armdatabasewatcher.TargetsClientListByWatcherOptions) (resp azfake.PagerResponder[armdatabasewatcher.TargetsClientListByWatcherResponse]) +} + +// NewTargetsServerTransport creates a new instance of TargetsServerTransport with the provided implementation. +// The returned TargetsServerTransport instance is connected to an instance of armdatabasewatcher.TargetsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewTargetsServerTransport(srv *TargetsServer) *TargetsServerTransport { + return &TargetsServerTransport{ + srv: srv, + newListByWatcherPager: newTracker[azfake.PagerResponder[armdatabasewatcher.TargetsClientListByWatcherResponse]](), + } +} + +// TargetsServerTransport connects instances of armdatabasewatcher.TargetsClient to instances of TargetsServer. +// Don't use this type directly, use NewTargetsServerTransport instead. +type TargetsServerTransport struct { + srv *TargetsServer + newListByWatcherPager *tracker[azfake.PagerResponder[armdatabasewatcher.TargetsClientListByWatcherResponse]] +} + +// Do implements the policy.Transporter interface for TargetsServerTransport. +func (t *TargetsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return t.dispatchToMethodFake(req, method) +} + +func (t *TargetsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if targetsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = targetsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "TargetsClient.CreateOrUpdate": + res.resp, res.err = t.dispatchCreateOrUpdate(req) + case "TargetsClient.Delete": + res.resp, res.err = t.dispatchDelete(req) + case "TargetsClient.Get": + res.resp, res.err = t.dispatchGet(req) + case "TargetsClient.NewListByWatcherPager": + res.resp, res.err = t.dispatchNewListByWatcherPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (t *TargetsServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if t.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseWatcher/watchers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/targets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armdatabasewatcher.Target](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + watcherNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("watcherName")]) + if err != nil { + return nil, err + } + targetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("targetName")]) + if err != nil { + return nil, err + } + respr, errRespr := t.srv.CreateOrUpdate(req.Context(), resourceGroupNameParam, watcherNameParam, targetNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Target, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (t *TargetsServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if t.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseWatcher/watchers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/targets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + watcherNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("watcherName")]) + if err != nil { + return nil, err + } + targetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("targetName")]) + if err != nil { + return nil, err + } + respr, errRespr := t.srv.Delete(req.Context(), resourceGroupNameParam, watcherNameParam, targetNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (t *TargetsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if t.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseWatcher/watchers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/targets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + watcherNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("watcherName")]) + if err != nil { + return nil, err + } + targetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("targetName")]) + if err != nil { + return nil, err + } + respr, errRespr := t.srv.Get(req.Context(), resourceGroupNameParam, watcherNameParam, targetNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Target, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (t *TargetsServerTransport) dispatchNewListByWatcherPager(req *http.Request) (*http.Response, error) { + if t.srv.NewListByWatcherPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByWatcherPager not implemented")} + } + newListByWatcherPager := t.newListByWatcherPager.get(req) + if newListByWatcherPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseWatcher/watchers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/targets` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + watcherNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("watcherName")]) + if err != nil { + return nil, err + } + resp := t.srv.NewListByWatcherPager(resourceGroupNameParam, watcherNameParam, nil) + newListByWatcherPager = &resp + t.newListByWatcherPager.add(req, newListByWatcherPager) + server.PagerResponderInjectNextLinks(newListByWatcherPager, req, func(page *armdatabasewatcher.TargetsClientListByWatcherResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByWatcherPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + t.newListByWatcherPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByWatcherPager) { + t.newListByWatcherPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to TargetsServerTransport +var targetsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armdatabasewatcher/fake/zz_watchers_server.go b/test/local/armdatabasewatcher/fake/zz_watchers_server.go new file mode 100644 index 000000000000..9dbf3b6bbeb1 --- /dev/null +++ b/test/local/armdatabasewatcher/fake/zz_watchers_server.go @@ -0,0 +1,474 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armdatabasewatcher" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// WatchersServer is a fake server for instances of the armdatabasewatcher.WatchersClient type. +type WatchersServer struct { + // BeginCreateOrUpdate is the fake for method WatchersClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, watcherName string, resource armdatabasewatcher.Watcher, options *armdatabasewatcher.WatchersClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armdatabasewatcher.WatchersClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method WatchersClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, watcherName string, options *armdatabasewatcher.WatchersClientBeginDeleteOptions) (resp azfake.PollerResponder[armdatabasewatcher.WatchersClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method WatchersClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, watcherName string, options *armdatabasewatcher.WatchersClientGetOptions) (resp azfake.Responder[armdatabasewatcher.WatchersClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method WatchersClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armdatabasewatcher.WatchersClientListByResourceGroupOptions) (resp azfake.PagerResponder[armdatabasewatcher.WatchersClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method WatchersClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armdatabasewatcher.WatchersClientListBySubscriptionOptions) (resp azfake.PagerResponder[armdatabasewatcher.WatchersClientListBySubscriptionResponse]) + + // BeginStart is the fake for method WatchersClient.BeginStart + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginStart func(ctx context.Context, resourceGroupName string, watcherName string, options *armdatabasewatcher.WatchersClientBeginStartOptions) (resp azfake.PollerResponder[armdatabasewatcher.WatchersClientStartResponse], errResp azfake.ErrorResponder) + + // BeginStop is the fake for method WatchersClient.BeginStop + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginStop func(ctx context.Context, resourceGroupName string, watcherName string, options *armdatabasewatcher.WatchersClientBeginStopOptions) (resp azfake.PollerResponder[armdatabasewatcher.WatchersClientStopResponse], errResp azfake.ErrorResponder) + + // BeginUpdate is the fake for method WatchersClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, watcherName string, properties armdatabasewatcher.WatcherUpdate, options *armdatabasewatcher.WatchersClientBeginUpdateOptions) (resp azfake.PollerResponder[armdatabasewatcher.WatchersClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewWatchersServerTransport creates a new instance of WatchersServerTransport with the provided implementation. +// The returned WatchersServerTransport instance is connected to an instance of armdatabasewatcher.WatchersClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewWatchersServerTransport(srv *WatchersServer) *WatchersServerTransport { + return &WatchersServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armdatabasewatcher.WatchersClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armdatabasewatcher.WatchersClientDeleteResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armdatabasewatcher.WatchersClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armdatabasewatcher.WatchersClientListBySubscriptionResponse]](), + beginStart: newTracker[azfake.PollerResponder[armdatabasewatcher.WatchersClientStartResponse]](), + beginStop: newTracker[azfake.PollerResponder[armdatabasewatcher.WatchersClientStopResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armdatabasewatcher.WatchersClientUpdateResponse]](), + } +} + +// WatchersServerTransport connects instances of armdatabasewatcher.WatchersClient to instances of WatchersServer. +// Don't use this type directly, use NewWatchersServerTransport instead. +type WatchersServerTransport struct { + srv *WatchersServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armdatabasewatcher.WatchersClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armdatabasewatcher.WatchersClientDeleteResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armdatabasewatcher.WatchersClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armdatabasewatcher.WatchersClientListBySubscriptionResponse]] + beginStart *tracker[azfake.PollerResponder[armdatabasewatcher.WatchersClientStartResponse]] + beginStop *tracker[azfake.PollerResponder[armdatabasewatcher.WatchersClientStopResponse]] + beginUpdate *tracker[azfake.PollerResponder[armdatabasewatcher.WatchersClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for WatchersServerTransport. +func (w *WatchersServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return w.dispatchToMethodFake(req, method) +} + +func (w *WatchersServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if watchersServerTransportInterceptor != nil { + res.resp, res.err, intercepted = watchersServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "WatchersClient.BeginCreateOrUpdate": + res.resp, res.err = w.dispatchBeginCreateOrUpdate(req) + case "WatchersClient.BeginDelete": + res.resp, res.err = w.dispatchBeginDelete(req) + case "WatchersClient.Get": + res.resp, res.err = w.dispatchGet(req) + case "WatchersClient.NewListByResourceGroupPager": + res.resp, res.err = w.dispatchNewListByResourceGroupPager(req) + case "WatchersClient.NewListBySubscriptionPager": + res.resp, res.err = w.dispatchNewListBySubscriptionPager(req) + case "WatchersClient.BeginStart": + res.resp, res.err = w.dispatchBeginStart(req) + case "WatchersClient.BeginStop": + res.resp, res.err = w.dispatchBeginStop(req) + case "WatchersClient.BeginUpdate": + res.resp, res.err = w.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (w *WatchersServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if w.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := w.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseWatcher/watchers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armdatabasewatcher.Watcher](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + watcherNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("watcherName")]) + if err != nil { + return nil, err + } + respr, errRespr := w.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, watcherNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + w.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + w.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + w.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (w *WatchersServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if w.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := w.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseWatcher/watchers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + watcherNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("watcherName")]) + if err != nil { + return nil, err + } + respr, errRespr := w.srv.BeginDelete(req.Context(), resourceGroupNameParam, watcherNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + w.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + w.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + w.beginDelete.remove(req) + } + + return resp, nil +} + +func (w *WatchersServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if w.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseWatcher/watchers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + watcherNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("watcherName")]) + if err != nil { + return nil, err + } + respr, errRespr := w.srv.Get(req.Context(), resourceGroupNameParam, watcherNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Watcher, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (w *WatchersServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if w.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := w.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseWatcher/watchers` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := w.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + w.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armdatabasewatcher.WatchersClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + w.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + w.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (w *WatchersServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if w.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := w.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseWatcher/watchers` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := w.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + w.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armdatabasewatcher.WatchersClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + w.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + w.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (w *WatchersServerTransport) dispatchBeginStart(req *http.Request) (*http.Response, error) { + if w.srv.BeginStart == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginStart not implemented")} + } + beginStart := w.beginStart.get(req) + if beginStart == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseWatcher/watchers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/start` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + watcherNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("watcherName")]) + if err != nil { + return nil, err + } + respr, errRespr := w.srv.BeginStart(req.Context(), resourceGroupNameParam, watcherNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginStart = &respr + w.beginStart.add(req, beginStart) + } + + resp, err := server.PollerResponderNext(beginStart, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + w.beginStart.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginStart) { + w.beginStart.remove(req) + } + + return resp, nil +} + +func (w *WatchersServerTransport) dispatchBeginStop(req *http.Request) (*http.Response, error) { + if w.srv.BeginStop == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginStop not implemented")} + } + beginStop := w.beginStop.get(req) + if beginStop == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseWatcher/watchers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/stop` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + watcherNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("watcherName")]) + if err != nil { + return nil, err + } + respr, errRespr := w.srv.BeginStop(req.Context(), resourceGroupNameParam, watcherNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginStop = &respr + w.beginStop.add(req, beginStop) + } + + resp, err := server.PollerResponderNext(beginStop, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + w.beginStop.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginStop) { + w.beginStop.remove(req) + } + + return resp, nil +} + +func (w *WatchersServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if w.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := w.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DatabaseWatcher/watchers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armdatabasewatcher.WatcherUpdate](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + watcherNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("watcherName")]) + if err != nil { + return nil, err + } + respr, errRespr := w.srv.BeginUpdate(req.Context(), resourceGroupNameParam, watcherNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + w.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + w.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + w.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to WatchersServerTransport +var watchersServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armdatabasewatcher/go.mod b/test/local/armdatabasewatcher/go.mod new file mode 100644 index 000000000000..c6f270e42207 --- /dev/null +++ b/test/local/armdatabasewatcher/go.mod @@ -0,0 +1,11 @@ +module armdatabasewatcher + +go 1.25.0 + +require github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect +) diff --git a/test/local/armdatabasewatcher/go.sum b/test/local/armdatabasewatcher/go.sum new file mode 100644 index 000000000000..3fdb64caf441 --- /dev/null +++ b/test/local/armdatabasewatcher/go.sum @@ -0,0 +1,16 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/local/armdatabasewatcher/testdata/_metadata.json b/test/local/armdatabasewatcher/testdata/_metadata.json new file mode 100644 index 000000000000..3f83ed0f64aa --- /dev/null +++ b/test/local/armdatabasewatcher/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Microsoft.DatabaseWatcher": "2025-01-02" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/local/armdatabasewatcher/zz_alertruleresources_client.go b/test/local/armdatabasewatcher/zz_alertruleresources_client.go new file mode 100644 index 000000000000..93b9f70e4a0b --- /dev/null +++ b/test/local/armdatabasewatcher/zz_alertruleresources_client.go @@ -0,0 +1,302 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasewatcher + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// AlertRuleResourcesClient contains the methods for the AlertRuleResources group. +// Don't use this type directly, use NewAlertRuleResourcesClient() instead. +// +// Generated from API version 2025-01-02 +type AlertRuleResourcesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAlertRuleResourcesClient creates a new instance of AlertRuleResourcesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewAlertRuleResourcesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AlertRuleResourcesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AlertRuleResourcesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Create a AlertRuleResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - watcherName - The database watcher name. +// - alertRuleResourceName - The alert rule proxy resource name. +// - resource - Resource create parameters. +// - options - AlertRuleResourcesClientCreateOrUpdateOptions contains the optional parameters for the AlertRuleResourcesClient.CreateOrUpdate +// method. +func (client *AlertRuleResourcesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, watcherName string, alertRuleResourceName string, resource AlertRuleResource, options *AlertRuleResourcesClientCreateOrUpdateOptions) (AlertRuleResourcesClientCreateOrUpdateResponse, error) { + var err error + const operationName = "AlertRuleResourcesClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, watcherName, alertRuleResourceName, resource, options) + if err != nil { + return AlertRuleResourcesClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AlertRuleResourcesClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return AlertRuleResourcesClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *AlertRuleResourcesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, watcherName string, alertRuleResourceName string, resource AlertRuleResource, _ *AlertRuleResourcesClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/alertRuleResources/{alertRuleResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if watcherName == "" { + return nil, errors.New("parameter watcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{watcherName}", url.PathEscape(watcherName)) + if alertRuleResourceName == "" { + return nil, errors.New("parameter alertRuleResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{alertRuleResourceName}", url.PathEscape(alertRuleResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250102) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *AlertRuleResourcesClient) createOrUpdateHandleResponse(resp *http.Response) (AlertRuleResourcesClientCreateOrUpdateResponse, error) { + result := AlertRuleResourcesClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AlertRuleResource); err != nil { + return AlertRuleResourcesClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Delete a AlertRuleResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - watcherName - The database watcher name. +// - alertRuleResourceName - The alert rule proxy resource name. +// - options - AlertRuleResourcesClientDeleteOptions contains the optional parameters for the AlertRuleResourcesClient.Delete +// method. +func (client *AlertRuleResourcesClient) Delete(ctx context.Context, resourceGroupName string, watcherName string, alertRuleResourceName string, options *AlertRuleResourcesClientDeleteOptions) (AlertRuleResourcesClientDeleteResponse, error) { + var err error + const operationName = "AlertRuleResourcesClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, watcherName, alertRuleResourceName, options) + if err != nil { + return AlertRuleResourcesClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AlertRuleResourcesClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return AlertRuleResourcesClientDeleteResponse{}, err + } + return AlertRuleResourcesClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *AlertRuleResourcesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, watcherName string, alertRuleResourceName string, _ *AlertRuleResourcesClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/alertRuleResources/{alertRuleResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if watcherName == "" { + return nil, errors.New("parameter watcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{watcherName}", url.PathEscape(watcherName)) + if alertRuleResourceName == "" { + return nil, errors.New("parameter alertRuleResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{alertRuleResourceName}", url.PathEscape(alertRuleResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250102) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a AlertRuleResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - watcherName - The database watcher name. +// - alertRuleResourceName - The alert rule proxy resource name. +// - options - AlertRuleResourcesClientGetOptions contains the optional parameters for the AlertRuleResourcesClient.Get method. +func (client *AlertRuleResourcesClient) Get(ctx context.Context, resourceGroupName string, watcherName string, alertRuleResourceName string, options *AlertRuleResourcesClientGetOptions) (AlertRuleResourcesClientGetResponse, error) { + var err error + const operationName = "AlertRuleResourcesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, watcherName, alertRuleResourceName, options) + if err != nil { + return AlertRuleResourcesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AlertRuleResourcesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AlertRuleResourcesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *AlertRuleResourcesClient) getCreateRequest(ctx context.Context, resourceGroupName string, watcherName string, alertRuleResourceName string, _ *AlertRuleResourcesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/alertRuleResources/{alertRuleResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if watcherName == "" { + return nil, errors.New("parameter watcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{watcherName}", url.PathEscape(watcherName)) + if alertRuleResourceName == "" { + return nil, errors.New("parameter alertRuleResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{alertRuleResourceName}", url.PathEscape(alertRuleResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250102) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *AlertRuleResourcesClient) getHandleResponse(resp *http.Response) (AlertRuleResourcesClientGetResponse, error) { + result := AlertRuleResourcesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AlertRuleResource); err != nil { + return AlertRuleResourcesClientGetResponse{}, err + } + return result, nil +} + +// NewListByParentPager - List AlertRuleResource resources by Watcher +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - watcherName - The database watcher name. +// - options - AlertRuleResourcesClientListByParentOptions contains the optional parameters for the AlertRuleResourcesClient.NewListByParentPager +// method. +func (client *AlertRuleResourcesClient) NewListByParentPager(resourceGroupName string, watcherName string, options *AlertRuleResourcesClientListByParentOptions) *runtime.Pager[AlertRuleResourcesClientListByParentResponse] { + return runtime.NewPager(runtime.PagingHandler[AlertRuleResourcesClientListByParentResponse]{ + More: func(page AlertRuleResourcesClientListByParentResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AlertRuleResourcesClientListByParentResponse) (AlertRuleResourcesClientListByParentResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AlertRuleResourcesClient.NewListByParentPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByParentCreateRequest(ctx, resourceGroupName, watcherName, options) + }, nil) + if err != nil { + return AlertRuleResourcesClientListByParentResponse{}, err + } + return client.listByParentHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByParentCreateRequest creates the ListByParent request. +func (client *AlertRuleResourcesClient) listByParentCreateRequest(ctx context.Context, resourceGroupName string, watcherName string, _ *AlertRuleResourcesClientListByParentOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/alertRuleResources" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if watcherName == "" { + return nil, errors.New("parameter watcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{watcherName}", url.PathEscape(watcherName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250102) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByParentHandleResponse handles the ListByParent response. +func (client *AlertRuleResourcesClient) listByParentHandleResponse(resp *http.Response) (AlertRuleResourcesClientListByParentResponse, error) { + result := AlertRuleResourcesClientListByParentResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AlertRuleResourceListResult); err != nil { + return AlertRuleResourcesClientListByParentResponse{}, err + } + return result, nil +} diff --git a/test/local/armdatabasewatcher/zz_client_factory.go b/test/local/armdatabasewatcher/zz_client_factory.go new file mode 100644 index 000000000000..db28bbe342ae --- /dev/null +++ b/test/local/armdatabasewatcher/zz_client_factory.go @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasewatcher + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + subscriptionID string + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, + internal: internal, + }, nil +} + +// NewAlertRuleResourcesClient creates a new instance of AlertRuleResourcesClient. +func (c *ClientFactory) NewAlertRuleResourcesClient() *AlertRuleResourcesClient { + return &AlertRuleResourcesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewHealthValidationsClient creates a new instance of HealthValidationsClient. +func (c *ClientFactory) NewHealthValidationsClient() *HealthValidationsClient { + return &HealthValidationsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: c.internal, + } +} + +// NewSharedPrivateLinkResourcesClient creates a new instance of SharedPrivateLinkResourcesClient. +func (c *ClientFactory) NewSharedPrivateLinkResourcesClient() *SharedPrivateLinkResourcesClient { + return &SharedPrivateLinkResourcesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewTargetsClient creates a new instance of TargetsClient. +func (c *ClientFactory) NewTargetsClient() *TargetsClient { + return &TargetsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewWatchersClient creates a new instance of WatchersClient. +func (c *ClientFactory) NewWatchersClient() *WatchersClient { + return &WatchersClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} diff --git a/test/local/armdatabasewatcher/zz_constants.go b/test/local/armdatabasewatcher/zz_constants.go new file mode 100644 index 000000000000..d68fecd91156 --- /dev/null +++ b/test/local/armdatabasewatcher/zz_constants.go @@ -0,0 +1,276 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasewatcher + +const ( + version20250102 string = "2025-01-02" +) + +// ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +type ActionType string + +const ( + // ActionTypeInternal - Actions are for internal-only APIs. + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// AlertRuleCreationProperties - The properties with which the alert rule resource was created. +type AlertRuleCreationProperties string + +const ( + // AlertRuleCreationPropertiesCreatedWithActionGroup - The alert rule was created with an action group. + AlertRuleCreationPropertiesCreatedWithActionGroup AlertRuleCreationProperties = "CreatedWithActionGroup" + // AlertRuleCreationPropertiesNone - The alert rule was created with no properties. + AlertRuleCreationPropertiesNone AlertRuleCreationProperties = "None" +) + +// PossibleAlertRuleCreationPropertiesValues returns the possible values for the AlertRuleCreationProperties const type. +func PossibleAlertRuleCreationPropertiesValues() []AlertRuleCreationProperties { + return []AlertRuleCreationProperties{ + AlertRuleCreationPropertiesCreatedWithActionGroup, + AlertRuleCreationPropertiesNone, + } +} + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// DatabaseWatcherProvisioningState - The status of the last provisioning operation performed on the resource. +type DatabaseWatcherProvisioningState string + +const ( + // DatabaseWatcherProvisioningStateCanceled - Resource creation was canceled. + DatabaseWatcherProvisioningStateCanceled DatabaseWatcherProvisioningState = "Canceled" + // DatabaseWatcherProvisioningStateFailed - Resource creation failed. + DatabaseWatcherProvisioningStateFailed DatabaseWatcherProvisioningState = "Failed" + // DatabaseWatcherProvisioningStateSucceeded - Resource has been created. + DatabaseWatcherProvisioningStateSucceeded DatabaseWatcherProvisioningState = "Succeeded" +) + +// PossibleDatabaseWatcherProvisioningStateValues returns the possible values for the DatabaseWatcherProvisioningState const type. +func PossibleDatabaseWatcherProvisioningStateValues() []DatabaseWatcherProvisioningState { + return []DatabaseWatcherProvisioningState{ + DatabaseWatcherProvisioningStateCanceled, + DatabaseWatcherProvisioningStateFailed, + DatabaseWatcherProvisioningStateSucceeded, + } +} + +// KustoOfferingType - The type of Kusto offering. +type KustoOfferingType string + +const ( + // KustoOfferingTypeAdx - The Azure Data Explorer cluster Kusto offering. + KustoOfferingTypeAdx KustoOfferingType = "adx" + // KustoOfferingTypeFabric - The Fabric Real-Time Analytics Kusto offering. + KustoOfferingTypeFabric KustoOfferingType = "fabric" + // KustoOfferingTypeFree - The free Azure Data Explorer cluster Kusto offering. + KustoOfferingTypeFree KustoOfferingType = "free" +) + +// PossibleKustoOfferingTypeValues returns the possible values for the KustoOfferingType const type. +func PossibleKustoOfferingTypeValues() []KustoOfferingType { + return []KustoOfferingType{ + KustoOfferingTypeAdx, + KustoOfferingTypeFabric, + KustoOfferingTypeFree, + } +} + +// ManagedServiceIdentityType - Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). +type ManagedServiceIdentityType string + +const ( + // ManagedServiceIdentityTypeNone - No managed identity. + ManagedServiceIdentityTypeNone ManagedServiceIdentityType = "None" + // ManagedServiceIdentityTypeSystemAndUserAssigned - System and user assigned managed identity. + ManagedServiceIdentityTypeSystemAndUserAssigned ManagedServiceIdentityType = "SystemAssigned, UserAssigned" + // ManagedServiceIdentityTypeSystemAssigned - System assigned managed identity. + ManagedServiceIdentityTypeSystemAssigned ManagedServiceIdentityType = "SystemAssigned" + // ManagedServiceIdentityTypeUserAssigned - User assigned managed identity. + ManagedServiceIdentityTypeUserAssigned ManagedServiceIdentityType = "UserAssigned" +) + +// PossibleManagedServiceIdentityTypeValues returns the possible values for the ManagedServiceIdentityType const type. +func PossibleManagedServiceIdentityTypeValues() []ManagedServiceIdentityType { + return []ManagedServiceIdentityType{ + ManagedServiceIdentityTypeNone, + ManagedServiceIdentityTypeSystemAndUserAssigned, + ManagedServiceIdentityTypeSystemAssigned, + ManagedServiceIdentityTypeUserAssigned, + } +} + +// Origin - The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default +// value is "user,system" +type Origin string + +const ( + // OriginSystem - Indicates the operation is initiated by a system. + OriginSystem Origin = "system" + // OriginUser - Indicates the operation is initiated by a user. + OriginUser Origin = "user" + // OriginUserSystem - Indicates the operation is initiated by a user or system. + OriginUserSystem Origin = "user,system" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginSystem, + OriginUser, + OriginUserSystem, + } +} + +// ResourceProvisioningState - The provisioning state of a resource type. +type ResourceProvisioningState string + +const ( + // ResourceProvisioningStateCanceled - Resource creation was canceled. + ResourceProvisioningStateCanceled ResourceProvisioningState = "Canceled" + // ResourceProvisioningStateFailed - Resource creation failed. + ResourceProvisioningStateFailed ResourceProvisioningState = "Failed" + // ResourceProvisioningStateSucceeded - Resource has been created. + ResourceProvisioningStateSucceeded ResourceProvisioningState = "Succeeded" +) + +// PossibleResourceProvisioningStateValues returns the possible values for the ResourceProvisioningState const type. +func PossibleResourceProvisioningStateValues() []ResourceProvisioningState { + return []ResourceProvisioningState{ + ResourceProvisioningStateCanceled, + ResourceProvisioningStateFailed, + ResourceProvisioningStateSucceeded, + } +} + +// SharedPrivateLinkResourceStatus - Status of the shared private link resource. Can be Pending, Approved, Rejected or Disconnected. +type SharedPrivateLinkResourceStatus string + +const ( + // SharedPrivateLinkResourceStatusApproved - The shared private link connection request was approved by the resource owner. + SharedPrivateLinkResourceStatusApproved SharedPrivateLinkResourceStatus = "Approved" + // SharedPrivateLinkResourceStatusDisconnected - The shared private link connection request was disconnected by the resource + // owner. + SharedPrivateLinkResourceStatusDisconnected SharedPrivateLinkResourceStatus = "Disconnected" + // SharedPrivateLinkResourceStatusPending - The shared private link connection request was not yet authorized by the resource + // owner. + SharedPrivateLinkResourceStatusPending SharedPrivateLinkResourceStatus = "Pending" + // SharedPrivateLinkResourceStatusRejected - The shared private link connection request was rejected by the resource owner. + SharedPrivateLinkResourceStatusRejected SharedPrivateLinkResourceStatus = "Rejected" +) + +// PossibleSharedPrivateLinkResourceStatusValues returns the possible values for the SharedPrivateLinkResourceStatus const type. +func PossibleSharedPrivateLinkResourceStatusValues() []SharedPrivateLinkResourceStatus { + return []SharedPrivateLinkResourceStatus{ + SharedPrivateLinkResourceStatusApproved, + SharedPrivateLinkResourceStatusDisconnected, + SharedPrivateLinkResourceStatusPending, + SharedPrivateLinkResourceStatusRejected, + } +} + +// TargetAuthenticationType - The type of authentication to use when connecting to a target. +type TargetAuthenticationType string + +const ( + // TargetAuthenticationTypeAAD - The Azure Active Directory authentication. + TargetAuthenticationTypeAAD TargetAuthenticationType = "Aad" + // TargetAuthenticationTypeSQL - The SQL password authentication. + TargetAuthenticationTypeSQL TargetAuthenticationType = "Sql" +) + +// PossibleTargetAuthenticationTypeValues returns the possible values for the TargetAuthenticationType const type. +func PossibleTargetAuthenticationTypeValues() []TargetAuthenticationType { + return []TargetAuthenticationType{ + TargetAuthenticationTypeAAD, + TargetAuthenticationTypeSQL, + } +} + +// ValidationStatus - Health validation status. +type ValidationStatus string + +const ( + // ValidationStatusCanceled - Health validation was canceled. + ValidationStatusCanceled ValidationStatus = "Canceled" + // ValidationStatusFailed - Health validation failed. + ValidationStatusFailed ValidationStatus = "Failed" + // ValidationStatusNotStarted - Health validation has not started. + ValidationStatusNotStarted ValidationStatus = "NotStarted" + // ValidationStatusRunning - Health validation is running. + ValidationStatusRunning ValidationStatus = "Running" + // ValidationStatusSucceeded - Health validation completed successfully. + ValidationStatusSucceeded ValidationStatus = "Succeeded" + // ValidationStatusTimedOut - Health validation timed out. + ValidationStatusTimedOut ValidationStatus = "TimedOut" +) + +// PossibleValidationStatusValues returns the possible values for the ValidationStatus const type. +func PossibleValidationStatusValues() []ValidationStatus { + return []ValidationStatus{ + ValidationStatusCanceled, + ValidationStatusFailed, + ValidationStatusNotStarted, + ValidationStatusRunning, + ValidationStatusSucceeded, + ValidationStatusTimedOut, + } +} + +// WatcherStatus - The monitoring collection status of a watcher. +type WatcherStatus string + +const ( + // WatcherStatusDeleting - Denotes the watcher is in a deleting state. + WatcherStatusDeleting WatcherStatus = "Deleting" + // WatcherStatusRunning - Denotes the watcher is in a running state. + WatcherStatusRunning WatcherStatus = "Running" + // WatcherStatusStarting - Denotes the watcher is in a starting state. + WatcherStatusStarting WatcherStatus = "Starting" + // WatcherStatusStopped - Denotes the watcher is in a stopped state. + WatcherStatusStopped WatcherStatus = "Stopped" + // WatcherStatusStopping - Denotes the watcher is in a stopping state. + WatcherStatusStopping WatcherStatus = "Stopping" +) + +// PossibleWatcherStatusValues returns the possible values for the WatcherStatus const type. +func PossibleWatcherStatusValues() []WatcherStatus { + return []WatcherStatus{ + WatcherStatusDeleting, + WatcherStatusRunning, + WatcherStatusStarting, + WatcherStatusStopped, + WatcherStatusStopping, + } +} diff --git a/test/local/armdatabasewatcher/zz_healthvalidations_client.go b/test/local/armdatabasewatcher/zz_healthvalidations_client.go new file mode 100644 index 000000000000..d5de36e5d150 --- /dev/null +++ b/test/local/armdatabasewatcher/zz_healthvalidations_client.go @@ -0,0 +1,249 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasewatcher + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// HealthValidationsClient contains the methods for the HealthValidations group. +// Don't use this type directly, use NewHealthValidationsClient() instead. +// +// Generated from API version 2025-01-02 +type HealthValidationsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewHealthValidationsClient creates a new instance of HealthValidationsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewHealthValidationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*HealthValidationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &HealthValidationsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get a HealthValidation +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - watcherName - The database watcher name. +// - healthValidationName - The health validation resource name. +// - options - HealthValidationsClientGetOptions contains the optional parameters for the HealthValidationsClient.Get method. +func (client *HealthValidationsClient) Get(ctx context.Context, resourceGroupName string, watcherName string, healthValidationName string, options *HealthValidationsClientGetOptions) (HealthValidationsClientGetResponse, error) { + var err error + const operationName = "HealthValidationsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, watcherName, healthValidationName, options) + if err != nil { + return HealthValidationsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return HealthValidationsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return HealthValidationsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *HealthValidationsClient) getCreateRequest(ctx context.Context, resourceGroupName string, watcherName string, healthValidationName string, _ *HealthValidationsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/healthValidations/{healthValidationName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if watcherName == "" { + return nil, errors.New("parameter watcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{watcherName}", url.PathEscape(watcherName)) + if healthValidationName == "" { + return nil, errors.New("parameter healthValidationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{healthValidationName}", url.PathEscape(healthValidationName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250102) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *HealthValidationsClient) getHandleResponse(resp *http.Response) (HealthValidationsClientGetResponse, error) { + result := HealthValidationsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.HealthValidation); err != nil { + return HealthValidationsClientGetResponse{}, err + } + return result, nil +} + +// NewListByParentPager - List HealthValidation resources by Watcher +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - watcherName - The database watcher name. +// - options - HealthValidationsClientListByParentOptions contains the optional parameters for the HealthValidationsClient.NewListByParentPager +// method. +func (client *HealthValidationsClient) NewListByParentPager(resourceGroupName string, watcherName string, options *HealthValidationsClientListByParentOptions) *runtime.Pager[HealthValidationsClientListByParentResponse] { + return runtime.NewPager(runtime.PagingHandler[HealthValidationsClientListByParentResponse]{ + More: func(page HealthValidationsClientListByParentResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *HealthValidationsClientListByParentResponse) (HealthValidationsClientListByParentResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "HealthValidationsClient.NewListByParentPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByParentCreateRequest(ctx, resourceGroupName, watcherName, options) + }, nil) + if err != nil { + return HealthValidationsClientListByParentResponse{}, err + } + return client.listByParentHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByParentCreateRequest creates the ListByParent request. +func (client *HealthValidationsClient) listByParentCreateRequest(ctx context.Context, resourceGroupName string, watcherName string, _ *HealthValidationsClientListByParentOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/healthValidations" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if watcherName == "" { + return nil, errors.New("parameter watcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{watcherName}", url.PathEscape(watcherName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250102) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByParentHandleResponse handles the ListByParent response. +func (client *HealthValidationsClient) listByParentHandleResponse(resp *http.Response) (HealthValidationsClientListByParentResponse, error) { + result := HealthValidationsClientListByParentResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.HealthValidationListResult); err != nil { + return HealthValidationsClientListByParentResponse{}, err + } + return result, nil +} + +// BeginStartValidation - Starts health validation for a watcher. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - watcherName - The database watcher name. +// - healthValidationName - The health validation resource name. +// - options - HealthValidationsClientBeginStartValidationOptions contains the optional parameters for the HealthValidationsClient.BeginStartValidation +// method. +func (client *HealthValidationsClient) BeginStartValidation(ctx context.Context, resourceGroupName string, watcherName string, healthValidationName string, options *HealthValidationsClientBeginStartValidationOptions) (*runtime.Poller[HealthValidationsClientStartValidationResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.startValidation(ctx, resourceGroupName, watcherName, healthValidationName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[HealthValidationsClientStartValidationResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[HealthValidationsClientStartValidationResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// StartValidation - Starts health validation for a watcher. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *HealthValidationsClient) startValidation(ctx context.Context, resourceGroupName string, watcherName string, healthValidationName string, options *HealthValidationsClientBeginStartValidationOptions) (*http.Response, error) { + var err error + const operationName = "HealthValidationsClient.BeginStartValidation" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.startValidationCreateRequest(ctx, resourceGroupName, watcherName, healthValidationName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// startValidationCreateRequest creates the StartValidation request. +func (client *HealthValidationsClient) startValidationCreateRequest(ctx context.Context, resourceGroupName string, watcherName string, healthValidationName string, _ *HealthValidationsClientBeginStartValidationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/healthValidations/{healthValidationName}/startValidation" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if watcherName == "" { + return nil, errors.New("parameter watcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{watcherName}", url.PathEscape(watcherName)) + if healthValidationName == "" { + return nil, errors.New("parameter healthValidationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{healthValidationName}", url.PathEscape(healthValidationName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250102) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} diff --git a/test/local/armdatabasewatcher/zz_interfaces.go b/test/local/armdatabasewatcher/zz_interfaces.go new file mode 100644 index 000000000000..19fec6f8296b --- /dev/null +++ b/test/local/armdatabasewatcher/zz_interfaces.go @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasewatcher + +// TargetPropertiesClassification provides polymorphic access to related types. +// Call the interface's GetTargetProperties() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *SQLDbElasticPoolTargetProperties, *SQLDbSingleDatabaseTargetProperties, *SQLMiTargetProperties, *TargetProperties +type TargetPropertiesClassification interface { + // GetTargetProperties returns the TargetProperties content of the underlying type. + GetTargetProperties() *TargetProperties +} diff --git a/test/local/armdatabasewatcher/zz_models.go b/test/local/armdatabasewatcher/zz_models.go new file mode 100644 index 000000000000..ea54eaf20867 --- /dev/null +++ b/test/local/armdatabasewatcher/zz_models.go @@ -0,0 +1,556 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasewatcher + +import "time" + +// AlertRuleResource - Concrete proxy resource types can be created by aliasing this type using a specific property type. +type AlertRuleResource struct { + // The resource-specific properties for this resource. + Properties *AlertRuleResourceProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// AlertRuleResourceListResult - The response of a AlertRuleResource list operation. +type AlertRuleResourceListResult struct { + // REQUIRED; The AlertRuleResource items on this page + Value []*AlertRuleResource + + // The link to the next page of items + NextLink *string +} + +// AlertRuleResourceProperties - The generic properties of the alert rule proxy resource. +type AlertRuleResourceProperties struct { + // REQUIRED; The resource ID of the alert rule resource. + AlertRuleResourceID *string + + // REQUIRED; The template ID associated with alert rule resource. + AlertRuleTemplateID *string + + // REQUIRED; The alert rule template version. + AlertRuleTemplateVersion *string + + // REQUIRED; The properties with which the alert rule resource was created. + CreatedWithProperties *AlertRuleCreationProperties + + // REQUIRED; The creation time of the alert rule resource. + CreationTime *time.Time + + // READ-ONLY; The provisioning state of the alert rule resource. + ProvisioningState *ResourceProvisioningState +} + +// Datastore - The properties of a data store. +type Datastore struct { + // REQUIRED; The Kusto cluster URI. + KustoClusterURI *string + + // REQUIRED; The Kusto data ingestion URI. + KustoDataIngestionURI *string + + // REQUIRED; The name of a Kusto database. + KustoDatabaseName *string + + // REQUIRED; The Kusto management URL. + KustoManagementURL *string + + // REQUIRED; The type of a Kusto offering. + KustoOfferingType *KustoOfferingType + + // The Azure resource ID of an Azure Data Explorer cluster. + AdxClusterResourceID *string + + // The Kusto cluster display name. + KustoClusterDisplayName *string +} + +// HealthValidation - Concrete proxy resource types can be created by aliasing this type using a specific property type. +type HealthValidation struct { + // The resource-specific properties for this resource. + Properties *HealthValidationProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// HealthValidationListResult - The response of a HealthValidation list operation. +type HealthValidationListResult struct { + // REQUIRED; The HealthValidation items on this page + Value []*HealthValidation + + // The link to the next page of items + NextLink *string +} + +// HealthValidationProperties - The generic properties of the health validation resource. +type HealthValidationProperties struct { + // READ-ONLY; The end time of health validation, in UTC. + EndTime *time.Time + + // READ-ONLY; The list of issues found by health validation. + Issues []*ValidationIssue + + // READ-ONLY; The start time of health validation, in UTC. + StartTime *time.Time + + // READ-ONLY; The current health validation status. + Status *ValidationStatus + + // READ-ONLY; The provisioning state of the health validation resource. + ProvisioningState *ResourceProvisioningState +} + +// ManagedServiceIdentityV4 - Managed service identity (system assigned and/or user assigned identities) +type ManagedServiceIdentityV4 struct { + // REQUIRED; The type of managed identity assigned to this resource. + Type *ManagedServiceIdentityType + + // The identities assigned to this resource by the user. + UserAssignedIdentities map[string]*UserAssignedIdentity + + // READ-ONLY; The service principal ID of the system assigned identity. This property will only be provided for a system assigned + // identity. + PrincipalID *string + + // READ-ONLY; The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + TenantID *string +} + +// Operation - REST API Operation +// +// Details of a REST API operation, returned from the Resource Provider Operations API +type Operation struct { + // Localized display information for this particular operation. + Display *OperationDisplay + + // READ-ONLY; Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + ActionType *ActionType + + // READ-ONLY; Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure + // Resource Manager/control-plane operations. + IsDataAction *bool + + // READ-ONLY; The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + // "Microsoft.Compute/virtualMachines/capture/action" + Name *string + + // READ-ONLY; The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default + // value is "user,system" + Origin *Origin +} + +// OperationDisplay - Localized display information for an operation. +type OperationDisplay struct { + // READ-ONLY; The short, localized friendly description of the operation; suitable for tool tips and detailed views. + Description *string + + // READ-ONLY; The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual + // Machine", "Restart Virtual Machine". + Operation *string + + // READ-ONLY; The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft + // Compute". + Provider *string + + // READ-ONLY; The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job + // Schedule Collections". + Resource *string +} + +// OperationListResult - A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to +// get the next set of results. +type OperationListResult struct { + // REQUIRED; The Operation items on this page + Value []*Operation + + // The link to the next page of items + NextLink *string +} + +// SQLDbElasticPoolTargetProperties - The properties specific to an elastic pool in Azure SQL Database. +type SQLDbElasticPoolTargetProperties struct { + // REQUIRED; The Azure resource ID of the anchor database used to connect to an elastic pool. + AnchorDatabaseResourceID *string + + // REQUIRED; The FQDN host name of the server to use in the connection string when connecting to a target. For example, for + // an Azure SQL logical server in the Azure commercial cloud, the value might be 'sql-logical-server-22092780.database.windows.net'; + // for an Azure SQL managed instance in the Azure commercial cloud, the value might be 'sql-mi-39441134.767d5869f605.database.windows.net'. + // Port number and instance name must be specified separately. + ConnectionServerName *string + + // REQUIRED; The Azure resource ID of an Azure SQL DB elastic pool target. + SQLEpResourceID *string + + // REQUIRED; The type of authentication to use when connecting to a target. + TargetAuthenticationType *TargetAuthenticationType + + // CONSTANT; The Azure SQL DB elastic pool target. + // Field has constant value "SqlEp", any specified value is ignored. + TargetType *string + + // Set to true to monitor a high availability replica of specified target, if any. + ReadIntent *bool + + // To use SQL authentication when connecting to targets, specify the vault where the login name and password secrets are stored. + TargetVault *VaultSecret + + // READ-ONLY; The provisioning state of the resource. + ProvisioningState *ResourceProvisioningState +} + +// GetTargetProperties implements the TargetPropertiesClassification interface for type SQLDbElasticPoolTargetProperties. +func (s *SQLDbElasticPoolTargetProperties) GetTargetProperties() *TargetProperties { + return &TargetProperties{ + ConnectionServerName: s.ConnectionServerName, + ProvisioningState: s.ProvisioningState, + TargetAuthenticationType: s.TargetAuthenticationType, + TargetType: s.TargetType, + TargetVault: s.TargetVault, + } +} + +// SQLDbSingleDatabaseTargetProperties - The properties specific to a database in Azure SQL Database. +type SQLDbSingleDatabaseTargetProperties struct { + // REQUIRED; The FQDN host name of the server to use in the connection string when connecting to a target. For example, for + // an Azure SQL logical server in the Azure commercial cloud, the value might be 'sql-logical-server-22092780.database.windows.net'; + // for an Azure SQL managed instance in the Azure commercial cloud, the value might be 'sql-mi-39441134.767d5869f605.database.windows.net'. + // Port number and instance name must be specified separately. + ConnectionServerName *string + + // REQUIRED; The Azure resource ID of an Azure SQL DB database target. + SQLDbResourceID *string + + // REQUIRED; The type of authentication to use when connecting to a target. + TargetAuthenticationType *TargetAuthenticationType + + // CONSTANT; The Azure SQL DB single database target. + // Field has constant value "SqlDb", any specified value is ignored. + TargetType *string + + // Set to true to monitor a high availability replica of specified target, if any. + ReadIntent *bool + + // To use SQL authentication when connecting to targets, specify the vault where the login name and password secrets are stored. + TargetVault *VaultSecret + + // READ-ONLY; The provisioning state of the resource. + ProvisioningState *ResourceProvisioningState +} + +// GetTargetProperties implements the TargetPropertiesClassification interface for type SQLDbSingleDatabaseTargetProperties. +func (s *SQLDbSingleDatabaseTargetProperties) GetTargetProperties() *TargetProperties { + return &TargetProperties{ + ConnectionServerName: s.ConnectionServerName, + ProvisioningState: s.ProvisioningState, + TargetAuthenticationType: s.TargetAuthenticationType, + TargetType: s.TargetType, + TargetVault: s.TargetVault, + } +} + +// SQLMiTargetProperties - The properties specific to Azure SQL Managed Instance targets. +type SQLMiTargetProperties struct { + // REQUIRED; The FQDN host name of the server to use in the connection string when connecting to a target. For example, for + // an Azure SQL logical server in the Azure commercial cloud, the value might be 'sql-logical-server-22092780.database.windows.net'; + // for an Azure SQL managed instance in the Azure commercial cloud, the value might be 'sql-mi-39441134.767d5869f605.database.windows.net'. + // Port number and instance name must be specified separately. + ConnectionServerName *string + + // REQUIRED; The Azure resource ID of an Azure SQL Managed Instance target. + SQLMiResourceID *string + + // REQUIRED; The type of authentication to use when connecting to a target. + TargetAuthenticationType *TargetAuthenticationType + + // CONSTANT; The Azure SQL Managed Instance target. + // Field has constant value "SqlMi", any specified value is ignored. + TargetType *string + + // The TCP port number to optionally use in the connection string when connecting to an Azure SQL Managed Instance target. + ConnectionTCPPort *int32 + + // Set to true to monitor a high availability replica of specified target, if any. + ReadIntent *bool + + // To use SQL authentication when connecting to targets, specify the vault where the login name and password secrets are stored. + TargetVault *VaultSecret + + // READ-ONLY; The provisioning state of the resource. + ProvisioningState *ResourceProvisioningState +} + +// GetTargetProperties implements the TargetPropertiesClassification interface for type SQLMiTargetProperties. +func (s *SQLMiTargetProperties) GetTargetProperties() *TargetProperties { + return &TargetProperties{ + ConnectionServerName: s.ConnectionServerName, + ProvisioningState: s.ProvisioningState, + TargetAuthenticationType: s.TargetAuthenticationType, + TargetType: s.TargetType, + TargetVault: s.TargetVault, + } +} + +// SharedPrivateLinkResource - Concrete proxy resource types can be created by aliasing this type using a specific property +// type. +type SharedPrivateLinkResource struct { + // The resource-specific properties for this resource. + Properties *SharedPrivateLinkResourceProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// SharedPrivateLinkResourceListResult - The response of a SharedPrivateLinkResource list operation. +type SharedPrivateLinkResourceListResult struct { + // REQUIRED; The SharedPrivateLinkResource items on this page + Value []*SharedPrivateLinkResource + + // The link to the next page of items + NextLink *string +} + +// SharedPrivateLinkResourceProperties - The generic properties of a Shared Private Link resource. +type SharedPrivateLinkResourceProperties struct { + // REQUIRED; The group id from the provider of resource the shared private link resource is for. + GroupID *string + + // REQUIRED; The resource ID of the resource the shared private link resource is for. + PrivateLinkResourceID *string + + // REQUIRED; The request message for requesting approval of the shared private link resource. + RequestMessage *string + + // The DNS zone segment to be included in the DNS name of the shared private link. Value is required for Azure Data Explorer + // clusters and SQL managed instances, and must be omitted for SQL logical servers and key vaults. The value is the second + // segment of the host FQDN name of the resource that the shared private link resource is for. For example: if the host name + // is 'adx-cluster-21187695.eastus.kusto.windows.net', then the value is 'eastus'; if the host name is 'sql-mi-23961134.767d5869f605.database.windows.net', + // then the value is '767d5869f605'. + DNSZone *string + + // READ-ONLY; The provisioning state of the resource. + ProvisioningState *ResourceProvisioningState + + // READ-ONLY; Status of the shared private link resource. Can be Pending, Approved, Rejected or Disconnected. + Status *SharedPrivateLinkResourceStatus +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time + + // The identity that created the resource. + CreatedBy *string + + // The type of identity that created the resource. + CreatedByType *CreatedByType + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time + + // The identity that last modified the resource. + LastModifiedBy *string + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType +} + +// Target - Concrete proxy resource types can be created by aliasing this type using a specific property type. +type Target struct { + // The resource-specific properties for this resource. + Properties TargetPropertiesClassification + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// TargetListResult - The response of a Target list operation. +type TargetListResult struct { + // REQUIRED; The Target items on this page + Value []*Target + + // The link to the next page of items + NextLink *string +} + +// TargetProperties - The generic properties of a target. +type TargetProperties struct { + // REQUIRED; The FQDN host name of the server to use in the connection string when connecting to a target. For example, for + // an Azure SQL logical server in the Azure commercial cloud, the value might be 'sql-logical-server-22092780.database.windows.net'; + // for an Azure SQL managed instance in the Azure commercial cloud, the value might be 'sql-mi-39441134.767d5869f605.database.windows.net'. + // Port number and instance name must be specified separately. + ConnectionServerName *string + + // REQUIRED; The type of authentication to use when connecting to a target. + TargetAuthenticationType *TargetAuthenticationType + + // REQUIRED; Discriminator property for TargetProperties. + TargetType *string + + // To use SQL authentication when connecting to targets, specify the vault where the login name and password secrets are stored. + TargetVault *VaultSecret + + // READ-ONLY; The provisioning state of the resource. + ProvisioningState *ResourceProvisioningState +} + +// GetTargetProperties implements the TargetPropertiesClassification interface for type TargetProperties. +func (t *TargetProperties) GetTargetProperties() *TargetProperties { return t } + +// UserAssignedIdentity - User assigned identity properties +type UserAssignedIdentity struct { + // READ-ONLY; The client ID of the assigned identity. + ClientID *string + + // READ-ONLY; The principal ID of the assigned identity. + PrincipalID *string +} + +// ValidationIssue - The model of a health validation issue. +type ValidationIssue struct { + // READ-ONLY; The error code of the issue. + ErrorCode *string + + // READ-ONLY; The error message of the issue. + ErrorMessage *string + + // READ-ONLY; The recommendation for resolving the issue. + RecommendationMessage *string + + // READ-ONLY; The additional details for the issue. + AdditionalDetails *string + + // READ-ONLY; The URL related to resolving the issue. + RecommendationURL *string + + // READ-ONLY; The resource ID of the Azure resource related to the issue. + RelatedResourceID *string + + // READ-ONLY; The type of the Azure resource related to the issue. + RelatedResourceType *string +} + +// VaultSecret - The vault specific details required if using SQL authentication to connect to a target. +type VaultSecret struct { + // The Azure resource ID of the Key Vault instance storing database authentication secrets. + AkvResourceID *string + + // The path to the Key Vault secret storing the password for authentication to a target. + AkvTargetPassword *string + + // The path to the Key Vault secret storing the login name (aka user name, aka account name) for authentication to a target. + AkvTargetUser *string +} + +// Watcher - The DatabaseWatcherProviderHub resource. +type Watcher struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The managed service identities assigned to this resource. + Identity *ManagedServiceIdentityV4 + + // The resource-specific properties for this resource. + Properties *WatcherProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// WatcherListResult - The response of a Watcher list operation. +type WatcherListResult struct { + // REQUIRED; The Watcher items on this page + Value []*Watcher + + // The link to the next page of items + NextLink *string +} + +// WatcherProperties - The RP specific properties of the resource. +type WatcherProperties struct { + // The data store for collected monitoring data. + Datastore *Datastore + + // The resource ID of a user-assigned managed identity that will be assigned to a new alert rule. + DefaultAlertRuleIdentityResourceID *string + + // READ-ONLY; The provisioning state of the resource watcher. + ProvisioningState *DatabaseWatcherProvisioningState + + // READ-ONLY; The monitoring collection status of the watcher. + Status *WatcherStatus +} + +// WatcherUpdate - The type used for update operations of the Watcher. +type WatcherUpdate struct { + // The managed service identities assigned to this resource. + Identity *ManagedServiceIdentityV4 + + // The resource-specific properties for this resource. + Properties *WatcherUpdateProperties + + // Resource tags. + Tags map[string]*string +} + +// WatcherUpdateProperties - The updatable properties of the Watcher. +type WatcherUpdateProperties struct { + // The data store for collected monitoring data. + Datastore *Datastore + + // The resource ID of a user-assigned managed identity that will be assigned to a new alert rule. + DefaultAlertRuleIdentityResourceID *string +} diff --git a/test/local/armdatabasewatcher/zz_models_serde.go b/test/local/armdatabasewatcher/zz_models_serde.go new file mode 100644 index 000000000000..718dbfb4c018 --- /dev/null +++ b/test/local/armdatabasewatcher/zz_models_serde.go @@ -0,0 +1,1257 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasewatcher + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type AlertRuleResource. +func (a AlertRuleResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AlertRuleResource. +func (a *AlertRuleResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &a.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AlertRuleResourceListResult. +func (a AlertRuleResourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AlertRuleResourceListResult. +func (a *AlertRuleResourceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &a.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AlertRuleResourceProperties. +func (a AlertRuleResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "alertRuleResourceId", a.AlertRuleResourceID) + populate(objectMap, "alertRuleTemplateId", a.AlertRuleTemplateID) + populate(objectMap, "alertRuleTemplateVersion", a.AlertRuleTemplateVersion) + populate(objectMap, "createdWithProperties", a.CreatedWithProperties) + populateTime[datetime.RFC3339](objectMap, "creationTime", a.CreationTime) + populate(objectMap, "provisioningState", a.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AlertRuleResourceProperties. +func (a *AlertRuleResourceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "alertRuleResourceId": + err = unpopulate(val, "AlertRuleResourceID", &a.AlertRuleResourceID) + delete(rawMsg, key) + case "alertRuleTemplateId": + err = unpopulate(val, "AlertRuleTemplateID", &a.AlertRuleTemplateID) + delete(rawMsg, key) + case "alertRuleTemplateVersion": + err = unpopulate(val, "AlertRuleTemplateVersion", &a.AlertRuleTemplateVersion) + delete(rawMsg, key) + case "createdWithProperties": + err = unpopulate(val, "CreatedWithProperties", &a.CreatedWithProperties) + delete(rawMsg, key) + case "creationTime": + err = unpopulateTime[datetime.RFC3339](val, "CreationTime", &a.CreationTime) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Datastore. +func (d Datastore) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "adxClusterResourceId", d.AdxClusterResourceID) + populate(objectMap, "kustoClusterDisplayName", d.KustoClusterDisplayName) + populate(objectMap, "kustoClusterUri", d.KustoClusterURI) + populate(objectMap, "kustoDataIngestionUri", d.KustoDataIngestionURI) + populate(objectMap, "kustoDatabaseName", d.KustoDatabaseName) + populate(objectMap, "kustoManagementUrl", d.KustoManagementURL) + populate(objectMap, "kustoOfferingType", d.KustoOfferingType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Datastore. +func (d *Datastore) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "adxClusterResourceId": + err = unpopulate(val, "AdxClusterResourceID", &d.AdxClusterResourceID) + delete(rawMsg, key) + case "kustoClusterDisplayName": + err = unpopulate(val, "KustoClusterDisplayName", &d.KustoClusterDisplayName) + delete(rawMsg, key) + case "kustoClusterUri": + err = unpopulate(val, "KustoClusterURI", &d.KustoClusterURI) + delete(rawMsg, key) + case "kustoDataIngestionUri": + err = unpopulate(val, "KustoDataIngestionURI", &d.KustoDataIngestionURI) + delete(rawMsg, key) + case "kustoDatabaseName": + err = unpopulate(val, "KustoDatabaseName", &d.KustoDatabaseName) + delete(rawMsg, key) + case "kustoManagementUrl": + err = unpopulate(val, "KustoManagementURL", &d.KustoManagementURL) + delete(rawMsg, key) + case "kustoOfferingType": + err = unpopulate(val, "KustoOfferingType", &d.KustoOfferingType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HealthValidation. +func (h HealthValidation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", h.ID) + populate(objectMap, "name", h.Name) + populate(objectMap, "properties", h.Properties) + populate(objectMap, "systemData", h.SystemData) + populate(objectMap, "type", h.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HealthValidation. +func (h *HealthValidation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &h.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &h.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &h.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &h.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &h.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HealthValidationListResult. +func (h HealthValidationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", h.NextLink) + populate(objectMap, "value", h.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HealthValidationListResult. +func (h *HealthValidationListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &h.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &h.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HealthValidationProperties. +func (h HealthValidationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "endTime", h.EndTime) + populate(objectMap, "issues", h.Issues) + populate(objectMap, "provisioningState", h.ProvisioningState) + populateTime[datetime.RFC3339](objectMap, "startTime", h.StartTime) + populate(objectMap, "status", h.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HealthValidationProperties. +func (h *HealthValidationProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "endTime": + err = unpopulateTime[datetime.RFC3339](val, "EndTime", &h.EndTime) + delete(rawMsg, key) + case "issues": + err = unpopulate(val, "Issues", &h.Issues) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &h.ProvisioningState) + delete(rawMsg, key) + case "startTime": + err = unpopulateTime[datetime.RFC3339](val, "StartTime", &h.StartTime) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &h.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedServiceIdentityV4. +func (m ManagedServiceIdentityV4) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "principalId", m.PrincipalID) + populate(objectMap, "tenantId", m.TenantID) + populate(objectMap, "type", m.Type) + populate(objectMap, "userAssignedIdentities", m.UserAssignedIdentities) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedServiceIdentityV4. +func (m *ManagedServiceIdentityV4) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "principalId": + err = unpopulate(val, "PrincipalID", &m.PrincipalID) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &m.TenantID) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + case "userAssignedIdentities": + err = unpopulate(val, "UserAssignedIdentities", &m.UserAssignedIdentities) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Operation. +func (o Operation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionType", o.ActionType) + populate(objectMap, "display", o.Display) + populate(objectMap, "isDataAction", o.IsDataAction) + populate(objectMap, "name", o.Name) + populate(objectMap, "origin", o.Origin) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Operation. +func (o *Operation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionType": + err = unpopulate(val, "ActionType", &o.ActionType) + delete(rawMsg, key) + case "display": + err = unpopulate(val, "Display", &o.Display) + delete(rawMsg, key) + case "isDataAction": + err = unpopulate(val, "IsDataAction", &o.IsDataAction) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "origin": + err = unpopulate(val, "Origin", &o.Origin) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationDisplay. +func (o OperationDisplay) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", o.Description) + populate(objectMap, "operation", o.Operation) + populate(objectMap, "provider", o.Provider) + populate(objectMap, "resource", o.Resource) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationDisplay. +func (o *OperationDisplay) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &o.Description) + delete(rawMsg, key) + case "operation": + err = unpopulate(val, "Operation", &o.Operation) + delete(rawMsg, key) + case "provider": + err = unpopulate(val, "Provider", &o.Provider) + delete(rawMsg, key) + case "resource": + err = unpopulate(val, "Resource", &o.Resource) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationListResult. +func (o *OperationListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &o.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SQLDbElasticPoolTargetProperties. +func (s SQLDbElasticPoolTargetProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "anchorDatabaseResourceId", s.AnchorDatabaseResourceID) + populate(objectMap, "connectionServerName", s.ConnectionServerName) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "readIntent", s.ReadIntent) + populate(objectMap, "sqlEpResourceId", s.SQLEpResourceID) + populate(objectMap, "targetAuthenticationType", s.TargetAuthenticationType) + objectMap["targetType"] = "SqlEp" + populate(objectMap, "targetVault", s.TargetVault) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SQLDbElasticPoolTargetProperties. +func (s *SQLDbElasticPoolTargetProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "anchorDatabaseResourceId": + err = unpopulate(val, "AnchorDatabaseResourceID", &s.AnchorDatabaseResourceID) + delete(rawMsg, key) + case "connectionServerName": + err = unpopulate(val, "ConnectionServerName", &s.ConnectionServerName) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + case "readIntent": + err = unpopulate(val, "ReadIntent", &s.ReadIntent) + delete(rawMsg, key) + case "sqlEpResourceId": + err = unpopulate(val, "SQLEpResourceID", &s.SQLEpResourceID) + delete(rawMsg, key) + case "targetAuthenticationType": + err = unpopulate(val, "TargetAuthenticationType", &s.TargetAuthenticationType) + delete(rawMsg, key) + case "targetType": + err = unpopulate(val, "TargetType", &s.TargetType) + delete(rawMsg, key) + case "targetVault": + err = unpopulate(val, "TargetVault", &s.TargetVault) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SQLDbSingleDatabaseTargetProperties. +func (s SQLDbSingleDatabaseTargetProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "connectionServerName", s.ConnectionServerName) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "readIntent", s.ReadIntent) + populate(objectMap, "sqlDbResourceId", s.SQLDbResourceID) + populate(objectMap, "targetAuthenticationType", s.TargetAuthenticationType) + objectMap["targetType"] = "SqlDb" + populate(objectMap, "targetVault", s.TargetVault) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SQLDbSingleDatabaseTargetProperties. +func (s *SQLDbSingleDatabaseTargetProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "connectionServerName": + err = unpopulate(val, "ConnectionServerName", &s.ConnectionServerName) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + case "readIntent": + err = unpopulate(val, "ReadIntent", &s.ReadIntent) + delete(rawMsg, key) + case "sqlDbResourceId": + err = unpopulate(val, "SQLDbResourceID", &s.SQLDbResourceID) + delete(rawMsg, key) + case "targetAuthenticationType": + err = unpopulate(val, "TargetAuthenticationType", &s.TargetAuthenticationType) + delete(rawMsg, key) + case "targetType": + err = unpopulate(val, "TargetType", &s.TargetType) + delete(rawMsg, key) + case "targetVault": + err = unpopulate(val, "TargetVault", &s.TargetVault) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SQLMiTargetProperties. +func (s SQLMiTargetProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "connectionServerName", s.ConnectionServerName) + populate(objectMap, "connectionTcpPort", s.ConnectionTCPPort) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "readIntent", s.ReadIntent) + populate(objectMap, "sqlMiResourceId", s.SQLMiResourceID) + populate(objectMap, "targetAuthenticationType", s.TargetAuthenticationType) + objectMap["targetType"] = "SqlMi" + populate(objectMap, "targetVault", s.TargetVault) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SQLMiTargetProperties. +func (s *SQLMiTargetProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "connectionServerName": + err = unpopulate(val, "ConnectionServerName", &s.ConnectionServerName) + delete(rawMsg, key) + case "connectionTcpPort": + err = unpopulate(val, "ConnectionTCPPort", &s.ConnectionTCPPort) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + case "readIntent": + err = unpopulate(val, "ReadIntent", &s.ReadIntent) + delete(rawMsg, key) + case "sqlMiResourceId": + err = unpopulate(val, "SQLMiResourceID", &s.SQLMiResourceID) + delete(rawMsg, key) + case "targetAuthenticationType": + err = unpopulate(val, "TargetAuthenticationType", &s.TargetAuthenticationType) + delete(rawMsg, key) + case "targetType": + err = unpopulate(val, "TargetType", &s.TargetType) + delete(rawMsg, key) + case "targetVault": + err = unpopulate(val, "TargetVault", &s.TargetVault) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SharedPrivateLinkResource. +func (s SharedPrivateLinkResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "systemData", s.SystemData) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SharedPrivateLinkResource. +func (s *SharedPrivateLinkResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &s.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SharedPrivateLinkResourceListResult. +func (s SharedPrivateLinkResourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SharedPrivateLinkResourceListResult. +func (s *SharedPrivateLinkResourceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &s.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SharedPrivateLinkResourceProperties. +func (s SharedPrivateLinkResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dnsZone", s.DNSZone) + populate(objectMap, "groupId", s.GroupID) + populate(objectMap, "privateLinkResourceId", s.PrivateLinkResourceID) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "requestMessage", s.RequestMessage) + populate(objectMap, "status", s.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SharedPrivateLinkResourceProperties. +func (s *SharedPrivateLinkResourceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "dnsZone": + err = unpopulate(val, "DNSZone", &s.DNSZone) + delete(rawMsg, key) + case "groupId": + err = unpopulate(val, "GroupID", &s.GroupID) + delete(rawMsg, key) + case "privateLinkResourceId": + err = unpopulate(val, "PrivateLinkResourceID", &s.PrivateLinkResourceID) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + case "requestMessage": + err = unpopulate(val, "RequestMessage", &s.RequestMessage) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &s.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateTime[datetime.RFC3339](objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateTime[datetime.RFC3339](val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateTime[datetime.RFC3339](val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Target. +func (t Target) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", t.ID) + populate(objectMap, "name", t.Name) + populate(objectMap, "properties", t.Properties) + populate(objectMap, "systemData", t.SystemData) + populate(objectMap, "type", t.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Target. +func (t *Target) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &t.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &t.Name) + delete(rawMsg, key) + case "properties": + t.Properties, err = unmarshalTargetPropertiesClassification(val) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &t.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &t.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TargetListResult. +func (t TargetListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", t.NextLink) + populate(objectMap, "value", t.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TargetListResult. +func (t *TargetListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &t.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &t.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TargetProperties. +func (t TargetProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "connectionServerName", t.ConnectionServerName) + populate(objectMap, "provisioningState", t.ProvisioningState) + populate(objectMap, "targetAuthenticationType", t.TargetAuthenticationType) + populate(objectMap, "targetType", t.TargetType) + populate(objectMap, "targetVault", t.TargetVault) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TargetProperties. +func (t *TargetProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "connectionServerName": + err = unpopulate(val, "ConnectionServerName", &t.ConnectionServerName) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &t.ProvisioningState) + delete(rawMsg, key) + case "targetAuthenticationType": + err = unpopulate(val, "TargetAuthenticationType", &t.TargetAuthenticationType) + delete(rawMsg, key) + case "targetType": + err = unpopulate(val, "TargetType", &t.TargetType) + delete(rawMsg, key) + case "targetVault": + err = unpopulate(val, "TargetVault", &t.TargetVault) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserAssignedIdentity. +func (u UserAssignedIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clientId", u.ClientID) + populate(objectMap, "principalId", u.PrincipalID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserAssignedIdentity. +func (u *UserAssignedIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "clientId": + err = unpopulate(val, "ClientID", &u.ClientID) + delete(rawMsg, key) + case "principalId": + err = unpopulate(val, "PrincipalID", &u.PrincipalID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ValidationIssue. +func (v ValidationIssue) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "additionalDetails", v.AdditionalDetails) + populate(objectMap, "errorCode", v.ErrorCode) + populate(objectMap, "errorMessage", v.ErrorMessage) + populate(objectMap, "recommendationMessage", v.RecommendationMessage) + populate(objectMap, "recommendationUrl", v.RecommendationURL) + populate(objectMap, "relatedResourceId", v.RelatedResourceID) + populate(objectMap, "relatedResourceType", v.RelatedResourceType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ValidationIssue. +func (v *ValidationIssue) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "additionalDetails": + err = unpopulate(val, "AdditionalDetails", &v.AdditionalDetails) + delete(rawMsg, key) + case "errorCode": + err = unpopulate(val, "ErrorCode", &v.ErrorCode) + delete(rawMsg, key) + case "errorMessage": + err = unpopulate(val, "ErrorMessage", &v.ErrorMessage) + delete(rawMsg, key) + case "recommendationMessage": + err = unpopulate(val, "RecommendationMessage", &v.RecommendationMessage) + delete(rawMsg, key) + case "recommendationUrl": + err = unpopulate(val, "RecommendationURL", &v.RecommendationURL) + delete(rawMsg, key) + case "relatedResourceId": + err = unpopulate(val, "RelatedResourceID", &v.RelatedResourceID) + delete(rawMsg, key) + case "relatedResourceType": + err = unpopulate(val, "RelatedResourceType", &v.RelatedResourceType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VaultSecret. +func (v VaultSecret) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "akvResourceId", v.AkvResourceID) + populate(objectMap, "akvTargetPassword", v.AkvTargetPassword) + populate(objectMap, "akvTargetUser", v.AkvTargetUser) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VaultSecret. +func (v *VaultSecret) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "akvResourceId": + err = unpopulate(val, "AkvResourceID", &v.AkvResourceID) + delete(rawMsg, key) + case "akvTargetPassword": + err = unpopulate(val, "AkvTargetPassword", &v.AkvTargetPassword) + delete(rawMsg, key) + case "akvTargetUser": + err = unpopulate(val, "AkvTargetUser", &v.AkvTargetUser) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Watcher. +func (w Watcher) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", w.ID) + populate(objectMap, "identity", w.Identity) + populate(objectMap, "location", w.Location) + populate(objectMap, "name", w.Name) + populate(objectMap, "properties", w.Properties) + populate(objectMap, "systemData", w.SystemData) + populate(objectMap, "tags", w.Tags) + populate(objectMap, "type", w.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Watcher. +func (w *Watcher) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &w.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &w.Identity) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &w.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &w.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &w.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &w.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &w.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &w.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type WatcherListResult. +func (w WatcherListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", w.NextLink) + populate(objectMap, "value", w.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WatcherListResult. +func (w *WatcherListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &w.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &w.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type WatcherProperties. +func (w WatcherProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "datastore", w.Datastore) + populate(objectMap, "defaultAlertRuleIdentityResourceId", w.DefaultAlertRuleIdentityResourceID) + populate(objectMap, "provisioningState", w.ProvisioningState) + populate(objectMap, "status", w.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WatcherProperties. +func (w *WatcherProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "datastore": + err = unpopulate(val, "Datastore", &w.Datastore) + delete(rawMsg, key) + case "defaultAlertRuleIdentityResourceId": + err = unpopulate(val, "DefaultAlertRuleIdentityResourceID", &w.DefaultAlertRuleIdentityResourceID) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &w.ProvisioningState) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &w.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type WatcherUpdate. +func (w WatcherUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identity", w.Identity) + populate(objectMap, "properties", w.Properties) + populate(objectMap, "tags", w.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WatcherUpdate. +func (w *WatcherUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "identity": + err = unpopulate(val, "Identity", &w.Identity) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &w.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &w.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type WatcherUpdateProperties. +func (w WatcherUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "datastore", w.Datastore) + populate(objectMap, "defaultAlertRuleIdentityResourceId", w.DefaultAlertRuleIdentityResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WatcherUpdateProperties. +func (w *WatcherUpdateProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "datastore": + err = unpopulate(val, "Datastore", &w.Datastore) + delete(rawMsg, key) + case "defaultAlertRuleIdentityResourceId": + err = unpopulate(val, "DefaultAlertRuleIdentityResourceID", &w.DefaultAlertRuleIdentityResourceID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/local/armdatabasewatcher/zz_operations_client.go b/test/local/armdatabasewatcher/zz_operations_client.go new file mode 100644 index 000000000000..81a039964abc --- /dev/null +++ b/test/local/armdatabasewatcher/zz_operations_client.go @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasewatcher + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +// +// Generated from API version 2025-01-02 +type OperationsClient struct { + internal *arm.Client +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*OperationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OperationsClient{ + internal: cl, + } + return client, nil +} + +// NewListPager - List the operations for the provider +// - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ + More: func(page OperationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OperationsClientListResponse) (OperationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OperationsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return OperationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, _ *OperationsClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.DatabaseWatcher/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250102) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsClientListResponse, error) { + result := OperationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armdatabasewatcher/zz_options.go b/test/local/armdatabasewatcher/zz_options.go new file mode 100644 index 000000000000..62604d77b938 --- /dev/null +++ b/test/local/armdatabasewatcher/zz_options.go @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasewatcher + +// AlertRuleResourcesClientCreateOrUpdateOptions contains the optional parameters for the AlertRuleResourcesClient.CreateOrUpdate +// method. +type AlertRuleResourcesClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// AlertRuleResourcesClientDeleteOptions contains the optional parameters for the AlertRuleResourcesClient.Delete method. +type AlertRuleResourcesClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// AlertRuleResourcesClientGetOptions contains the optional parameters for the AlertRuleResourcesClient.Get method. +type AlertRuleResourcesClientGetOptions struct { + // placeholder for future optional parameters +} + +// AlertRuleResourcesClientListByParentOptions contains the optional parameters for the AlertRuleResourcesClient.NewListByParentPager +// method. +type AlertRuleResourcesClientListByParentOptions struct { + // placeholder for future optional parameters +} + +// HealthValidationsClientBeginStartValidationOptions contains the optional parameters for the HealthValidationsClient.BeginStartValidation +// method. +type HealthValidationsClientBeginStartValidationOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// HealthValidationsClientGetOptions contains the optional parameters for the HealthValidationsClient.Get method. +type HealthValidationsClientGetOptions struct { + // placeholder for future optional parameters +} + +// HealthValidationsClientListByParentOptions contains the optional parameters for the HealthValidationsClient.NewListByParentPager +// method. +type HealthValidationsClientListByParentOptions struct { + // placeholder for future optional parameters +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} + +// SharedPrivateLinkResourcesClientBeginCreateOptions contains the optional parameters for the SharedPrivateLinkResourcesClient.BeginCreate +// method. +type SharedPrivateLinkResourcesClientBeginCreateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// SharedPrivateLinkResourcesClientBeginDeleteOptions contains the optional parameters for the SharedPrivateLinkResourcesClient.BeginDelete +// method. +type SharedPrivateLinkResourcesClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// SharedPrivateLinkResourcesClientGetOptions contains the optional parameters for the SharedPrivateLinkResourcesClient.Get +// method. +type SharedPrivateLinkResourcesClientGetOptions struct { + // placeholder for future optional parameters +} + +// SharedPrivateLinkResourcesClientListByWatcherOptions contains the optional parameters for the SharedPrivateLinkResourcesClient.NewListByWatcherPager +// method. +type SharedPrivateLinkResourcesClientListByWatcherOptions struct { + // placeholder for future optional parameters +} + +// TargetsClientCreateOrUpdateOptions contains the optional parameters for the TargetsClient.CreateOrUpdate method. +type TargetsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// TargetsClientDeleteOptions contains the optional parameters for the TargetsClient.Delete method. +type TargetsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// TargetsClientGetOptions contains the optional parameters for the TargetsClient.Get method. +type TargetsClientGetOptions struct { + // placeholder for future optional parameters +} + +// TargetsClientListByWatcherOptions contains the optional parameters for the TargetsClient.NewListByWatcherPager method. +type TargetsClientListByWatcherOptions struct { + // placeholder for future optional parameters +} + +// WatchersClientBeginCreateOrUpdateOptions contains the optional parameters for the WatchersClient.BeginCreateOrUpdate method. +type WatchersClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// WatchersClientBeginDeleteOptions contains the optional parameters for the WatchersClient.BeginDelete method. +type WatchersClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// WatchersClientBeginStartOptions contains the optional parameters for the WatchersClient.BeginStart method. +type WatchersClientBeginStartOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// WatchersClientBeginStopOptions contains the optional parameters for the WatchersClient.BeginStop method. +type WatchersClientBeginStopOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// WatchersClientBeginUpdateOptions contains the optional parameters for the WatchersClient.BeginUpdate method. +type WatchersClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// WatchersClientGetOptions contains the optional parameters for the WatchersClient.Get method. +type WatchersClientGetOptions struct { + // placeholder for future optional parameters +} + +// WatchersClientListByResourceGroupOptions contains the optional parameters for the WatchersClient.NewListByResourceGroupPager +// method. +type WatchersClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// WatchersClientListBySubscriptionOptions contains the optional parameters for the WatchersClient.NewListBySubscriptionPager +// method. +type WatchersClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} diff --git a/test/local/armdatabasewatcher/zz_polymorphic_helpers.go b/test/local/armdatabasewatcher/zz_polymorphic_helpers.go new file mode 100644 index 000000000000..23f16ce00208 --- /dev/null +++ b/test/local/armdatabasewatcher/zz_polymorphic_helpers.go @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasewatcher + +import "encoding/json" + +func unmarshalTargetPropertiesClassification(rawMsg json.RawMessage) (TargetPropertiesClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b TargetPropertiesClassification + switch m["targetType"] { + case "SqlDb": + b = &SQLDbSingleDatabaseTargetProperties{} + case "SqlEp": + b = &SQLDbElasticPoolTargetProperties{} + case "SqlMi": + b = &SQLMiTargetProperties{} + default: + b = &TargetProperties{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} diff --git a/test/local/armdatabasewatcher/zz_responses.go b/test/local/armdatabasewatcher/zz_responses.go new file mode 100644 index 000000000000..ddd743dc6a42 --- /dev/null +++ b/test/local/armdatabasewatcher/zz_responses.go @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasewatcher + +// AlertRuleResourcesClientCreateOrUpdateResponse contains the response from method AlertRuleResourcesClient.CreateOrUpdate. +type AlertRuleResourcesClientCreateOrUpdateResponse struct { + // Concrete proxy resource types can be created by aliasing this type using a specific property type. + AlertRuleResource +} + +// AlertRuleResourcesClientDeleteResponse contains the response from method AlertRuleResourcesClient.Delete. +type AlertRuleResourcesClientDeleteResponse struct { + // placeholder for future response values +} + +// AlertRuleResourcesClientGetResponse contains the response from method AlertRuleResourcesClient.Get. +type AlertRuleResourcesClientGetResponse struct { + // Concrete proxy resource types can be created by aliasing this type using a specific property type. + AlertRuleResource +} + +// AlertRuleResourcesClientListByParentResponse contains the response from method AlertRuleResourcesClient.NewListByParentPager. +type AlertRuleResourcesClientListByParentResponse struct { + // The response of a AlertRuleResource list operation. + AlertRuleResourceListResult +} + +// HealthValidationsClientGetResponse contains the response from method HealthValidationsClient.Get. +type HealthValidationsClientGetResponse struct { + // Concrete proxy resource types can be created by aliasing this type using a specific property type. + HealthValidation +} + +// HealthValidationsClientListByParentResponse contains the response from method HealthValidationsClient.NewListByParentPager. +type HealthValidationsClientListByParentResponse struct { + // The response of a HealthValidation list operation. + HealthValidationListResult +} + +// HealthValidationsClientStartValidationResponse contains the response from method HealthValidationsClient.BeginStartValidation. +type HealthValidationsClientStartValidationResponse struct { + // Concrete proxy resource types can be created by aliasing this type using a specific property type. + HealthValidation +} + +// OperationsClientListResponse contains the response from method OperationsClient.NewListPager. +type OperationsClientListResponse struct { + // A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. + OperationListResult +} + +// SharedPrivateLinkResourcesClientCreateResponse contains the response from method SharedPrivateLinkResourcesClient.BeginCreate. +type SharedPrivateLinkResourcesClientCreateResponse struct { + // Concrete proxy resource types can be created by aliasing this type using a specific property type. + SharedPrivateLinkResource +} + +// SharedPrivateLinkResourcesClientDeleteResponse contains the response from method SharedPrivateLinkResourcesClient.BeginDelete. +type SharedPrivateLinkResourcesClientDeleteResponse struct { + // placeholder for future response values +} + +// SharedPrivateLinkResourcesClientGetResponse contains the response from method SharedPrivateLinkResourcesClient.Get. +type SharedPrivateLinkResourcesClientGetResponse struct { + // Concrete proxy resource types can be created by aliasing this type using a specific property type. + SharedPrivateLinkResource +} + +// SharedPrivateLinkResourcesClientListByWatcherResponse contains the response from method SharedPrivateLinkResourcesClient.NewListByWatcherPager. +type SharedPrivateLinkResourcesClientListByWatcherResponse struct { + // The response of a SharedPrivateLinkResource list operation. + SharedPrivateLinkResourceListResult +} + +// TargetsClientCreateOrUpdateResponse contains the response from method TargetsClient.CreateOrUpdate. +type TargetsClientCreateOrUpdateResponse struct { + // Concrete proxy resource types can be created by aliasing this type using a specific property type. + Target +} + +// TargetsClientDeleteResponse contains the response from method TargetsClient.Delete. +type TargetsClientDeleteResponse struct { + // placeholder for future response values +} + +// TargetsClientGetResponse contains the response from method TargetsClient.Get. +type TargetsClientGetResponse struct { + // Concrete proxy resource types can be created by aliasing this type using a specific property type. + Target +} + +// TargetsClientListByWatcherResponse contains the response from method TargetsClient.NewListByWatcherPager. +type TargetsClientListByWatcherResponse struct { + // The response of a Target list operation. + TargetListResult +} + +// WatchersClientCreateOrUpdateResponse contains the response from method WatchersClient.BeginCreateOrUpdate. +type WatchersClientCreateOrUpdateResponse struct { + // The DatabaseWatcherProviderHub resource. + Watcher +} + +// WatchersClientDeleteResponse contains the response from method WatchersClient.BeginDelete. +type WatchersClientDeleteResponse struct { + // placeholder for future response values +} + +// WatchersClientGetResponse contains the response from method WatchersClient.Get. +type WatchersClientGetResponse struct { + // The DatabaseWatcherProviderHub resource. + Watcher +} + +// WatchersClientListByResourceGroupResponse contains the response from method WatchersClient.NewListByResourceGroupPager. +type WatchersClientListByResourceGroupResponse struct { + // The response of a Watcher list operation. + WatcherListResult +} + +// WatchersClientListBySubscriptionResponse contains the response from method WatchersClient.NewListBySubscriptionPager. +type WatchersClientListBySubscriptionResponse struct { + // The response of a Watcher list operation. + WatcherListResult +} + +// WatchersClientStartResponse contains the response from method WatchersClient.BeginStart. +type WatchersClientStartResponse struct { + // placeholder for future response values +} + +// WatchersClientStopResponse contains the response from method WatchersClient.BeginStop. +type WatchersClientStopResponse struct { + // placeholder for future response values +} + +// WatchersClientUpdateResponse contains the response from method WatchersClient.BeginUpdate. +type WatchersClientUpdateResponse struct { + // The DatabaseWatcherProviderHub resource. + Watcher +} diff --git a/test/local/armdatabasewatcher/zz_sharedprivatelinkresources_client.go b/test/local/armdatabasewatcher/zz_sharedprivatelinkresources_client.go new file mode 100644 index 000000000000..2ed3c8119f8d --- /dev/null +++ b/test/local/armdatabasewatcher/zz_sharedprivatelinkresources_client.go @@ -0,0 +1,332 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasewatcher + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// SharedPrivateLinkResourcesClient contains the methods for the SharedPrivateLinkResources group. +// Don't use this type directly, use NewSharedPrivateLinkResourcesClient() instead. +// +// Generated from API version 2025-01-02 +type SharedPrivateLinkResourcesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewSharedPrivateLinkResourcesClient creates a new instance of SharedPrivateLinkResourcesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewSharedPrivateLinkResourcesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SharedPrivateLinkResourcesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SharedPrivateLinkResourcesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreate - Create a SharedPrivateLinkResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - watcherName - The database watcher name. +// - sharedPrivateLinkResourceName - The Shared Private Link resource name. +// - resource - Resource create parameters. +// - options - SharedPrivateLinkResourcesClientBeginCreateOptions contains the optional parameters for the SharedPrivateLinkResourcesClient.BeginCreate +// method. +func (client *SharedPrivateLinkResourcesClient) BeginCreate(ctx context.Context, resourceGroupName string, watcherName string, sharedPrivateLinkResourceName string, resource SharedPrivateLinkResource, options *SharedPrivateLinkResourcesClientBeginCreateOptions) (*runtime.Poller[SharedPrivateLinkResourcesClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, resourceGroupName, watcherName, sharedPrivateLinkResourceName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SharedPrivateLinkResourcesClientCreateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SharedPrivateLinkResourcesClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Create a SharedPrivateLinkResource +// If the operation fails it returns an *azcore.ResponseError type. +func (client *SharedPrivateLinkResourcesClient) create(ctx context.Context, resourceGroupName string, watcherName string, sharedPrivateLinkResourceName string, resource SharedPrivateLinkResource, options *SharedPrivateLinkResourcesClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "SharedPrivateLinkResourcesClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, watcherName, sharedPrivateLinkResourceName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *SharedPrivateLinkResourcesClient) createCreateRequest(ctx context.Context, resourceGroupName string, watcherName string, sharedPrivateLinkResourceName string, resource SharedPrivateLinkResource, _ *SharedPrivateLinkResourcesClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if watcherName == "" { + return nil, errors.New("parameter watcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{watcherName}", url.PathEscape(watcherName)) + if sharedPrivateLinkResourceName == "" { + return nil, errors.New("parameter sharedPrivateLinkResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{sharedPrivateLinkResourceName}", url.PathEscape(sharedPrivateLinkResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250102) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a SharedPrivateLinkResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - watcherName - The database watcher name. +// - sharedPrivateLinkResourceName - The Shared Private Link resource name. +// - options - SharedPrivateLinkResourcesClientBeginDeleteOptions contains the optional parameters for the SharedPrivateLinkResourcesClient.BeginDelete +// method. +func (client *SharedPrivateLinkResourcesClient) BeginDelete(ctx context.Context, resourceGroupName string, watcherName string, sharedPrivateLinkResourceName string, options *SharedPrivateLinkResourcesClientBeginDeleteOptions) (*runtime.Poller[SharedPrivateLinkResourcesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, watcherName, sharedPrivateLinkResourceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[SharedPrivateLinkResourcesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[SharedPrivateLinkResourcesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a SharedPrivateLinkResource +// If the operation fails it returns an *azcore.ResponseError type. +func (client *SharedPrivateLinkResourcesClient) deleteOperation(ctx context.Context, resourceGroupName string, watcherName string, sharedPrivateLinkResourceName string, options *SharedPrivateLinkResourcesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "SharedPrivateLinkResourcesClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, watcherName, sharedPrivateLinkResourceName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *SharedPrivateLinkResourcesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, watcherName string, sharedPrivateLinkResourceName string, _ *SharedPrivateLinkResourcesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if watcherName == "" { + return nil, errors.New("parameter watcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{watcherName}", url.PathEscape(watcherName)) + if sharedPrivateLinkResourceName == "" { + return nil, errors.New("parameter sharedPrivateLinkResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{sharedPrivateLinkResourceName}", url.PathEscape(sharedPrivateLinkResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250102) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a SharedPrivateLinkResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - watcherName - The database watcher name. +// - sharedPrivateLinkResourceName - The Shared Private Link resource name. +// - options - SharedPrivateLinkResourcesClientGetOptions contains the optional parameters for the SharedPrivateLinkResourcesClient.Get +// method. +func (client *SharedPrivateLinkResourcesClient) Get(ctx context.Context, resourceGroupName string, watcherName string, sharedPrivateLinkResourceName string, options *SharedPrivateLinkResourcesClientGetOptions) (SharedPrivateLinkResourcesClientGetResponse, error) { + var err error + const operationName = "SharedPrivateLinkResourcesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, watcherName, sharedPrivateLinkResourceName, options) + if err != nil { + return SharedPrivateLinkResourcesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SharedPrivateLinkResourcesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SharedPrivateLinkResourcesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *SharedPrivateLinkResourcesClient) getCreateRequest(ctx context.Context, resourceGroupName string, watcherName string, sharedPrivateLinkResourceName string, _ *SharedPrivateLinkResourcesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if watcherName == "" { + return nil, errors.New("parameter watcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{watcherName}", url.PathEscape(watcherName)) + if sharedPrivateLinkResourceName == "" { + return nil, errors.New("parameter sharedPrivateLinkResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{sharedPrivateLinkResourceName}", url.PathEscape(sharedPrivateLinkResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250102) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *SharedPrivateLinkResourcesClient) getHandleResponse(resp *http.Response) (SharedPrivateLinkResourcesClientGetResponse, error) { + result := SharedPrivateLinkResourcesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SharedPrivateLinkResource); err != nil { + return SharedPrivateLinkResourcesClientGetResponse{}, err + } + return result, nil +} + +// NewListByWatcherPager - List SharedPrivateLinkResource resources by Watcher +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - watcherName - The database watcher name. +// - options - SharedPrivateLinkResourcesClientListByWatcherOptions contains the optional parameters for the SharedPrivateLinkResourcesClient.NewListByWatcherPager +// method. +func (client *SharedPrivateLinkResourcesClient) NewListByWatcherPager(resourceGroupName string, watcherName string, options *SharedPrivateLinkResourcesClientListByWatcherOptions) *runtime.Pager[SharedPrivateLinkResourcesClientListByWatcherResponse] { + return runtime.NewPager(runtime.PagingHandler[SharedPrivateLinkResourcesClientListByWatcherResponse]{ + More: func(page SharedPrivateLinkResourcesClientListByWatcherResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SharedPrivateLinkResourcesClientListByWatcherResponse) (SharedPrivateLinkResourcesClientListByWatcherResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SharedPrivateLinkResourcesClient.NewListByWatcherPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByWatcherCreateRequest(ctx, resourceGroupName, watcherName, options) + }, nil) + if err != nil { + return SharedPrivateLinkResourcesClientListByWatcherResponse{}, err + } + return client.listByWatcherHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByWatcherCreateRequest creates the ListByWatcher request. +func (client *SharedPrivateLinkResourcesClient) listByWatcherCreateRequest(ctx context.Context, resourceGroupName string, watcherName string, _ *SharedPrivateLinkResourcesClientListByWatcherOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/sharedPrivateLinkResources" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if watcherName == "" { + return nil, errors.New("parameter watcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{watcherName}", url.PathEscape(watcherName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250102) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByWatcherHandleResponse handles the ListByWatcher response. +func (client *SharedPrivateLinkResourcesClient) listByWatcherHandleResponse(resp *http.Response) (SharedPrivateLinkResourcesClientListByWatcherResponse, error) { + result := SharedPrivateLinkResourcesClientListByWatcherResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SharedPrivateLinkResourceListResult); err != nil { + return SharedPrivateLinkResourcesClientListByWatcherResponse{}, err + } + return result, nil +} diff --git a/test/local/armdatabasewatcher/zz_targets_client.go b/test/local/armdatabasewatcher/zz_targets_client.go new file mode 100644 index 000000000000..485d0a00bb2d --- /dev/null +++ b/test/local/armdatabasewatcher/zz_targets_client.go @@ -0,0 +1,300 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasewatcher + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// TargetsClient contains the methods for the Targets group. +// Don't use this type directly, use NewTargetsClient() instead. +// +// Generated from API version 2025-01-02 +type TargetsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewTargetsClient creates a new instance of TargetsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewTargetsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*TargetsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &TargetsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Create a Target +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - watcherName - The database watcher name. +// - targetName - The target resource name. +// - resource - Resource create parameters. +// - options - TargetsClientCreateOrUpdateOptions contains the optional parameters for the TargetsClient.CreateOrUpdate method. +func (client *TargetsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, watcherName string, targetName string, resource Target, options *TargetsClientCreateOrUpdateOptions) (TargetsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "TargetsClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, watcherName, targetName, resource, options) + if err != nil { + return TargetsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TargetsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return TargetsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *TargetsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, watcherName string, targetName string, resource Target, _ *TargetsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/targets/{targetName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if watcherName == "" { + return nil, errors.New("parameter watcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{watcherName}", url.PathEscape(watcherName)) + if targetName == "" { + return nil, errors.New("parameter targetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{targetName}", url.PathEscape(targetName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250102) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *TargetsClient) createOrUpdateHandleResponse(resp *http.Response) (TargetsClientCreateOrUpdateResponse, error) { + result := TargetsClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Target); err != nil { + return TargetsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Delete a Target +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - watcherName - The database watcher name. +// - targetName - The target resource name. +// - options - TargetsClientDeleteOptions contains the optional parameters for the TargetsClient.Delete method. +func (client *TargetsClient) Delete(ctx context.Context, resourceGroupName string, watcherName string, targetName string, options *TargetsClientDeleteOptions) (TargetsClientDeleteResponse, error) { + var err error + const operationName = "TargetsClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, watcherName, targetName, options) + if err != nil { + return TargetsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TargetsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return TargetsClientDeleteResponse{}, err + } + return TargetsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *TargetsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, watcherName string, targetName string, _ *TargetsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/targets/{targetName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if watcherName == "" { + return nil, errors.New("parameter watcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{watcherName}", url.PathEscape(watcherName)) + if targetName == "" { + return nil, errors.New("parameter targetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{targetName}", url.PathEscape(targetName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250102) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a Target +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - watcherName - The database watcher name. +// - targetName - The target resource name. +// - options - TargetsClientGetOptions contains the optional parameters for the TargetsClient.Get method. +func (client *TargetsClient) Get(ctx context.Context, resourceGroupName string, watcherName string, targetName string, options *TargetsClientGetOptions) (TargetsClientGetResponse, error) { + var err error + const operationName = "TargetsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, watcherName, targetName, options) + if err != nil { + return TargetsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TargetsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return TargetsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *TargetsClient) getCreateRequest(ctx context.Context, resourceGroupName string, watcherName string, targetName string, _ *TargetsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/targets/{targetName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if watcherName == "" { + return nil, errors.New("parameter watcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{watcherName}", url.PathEscape(watcherName)) + if targetName == "" { + return nil, errors.New("parameter targetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{targetName}", url.PathEscape(targetName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250102) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *TargetsClient) getHandleResponse(resp *http.Response) (TargetsClientGetResponse, error) { + result := TargetsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Target); err != nil { + return TargetsClientGetResponse{}, err + } + return result, nil +} + +// NewListByWatcherPager - List Target resources by Watcher +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - watcherName - The database watcher name. +// - options - TargetsClientListByWatcherOptions contains the optional parameters for the TargetsClient.NewListByWatcherPager +// method. +func (client *TargetsClient) NewListByWatcherPager(resourceGroupName string, watcherName string, options *TargetsClientListByWatcherOptions) *runtime.Pager[TargetsClientListByWatcherResponse] { + return runtime.NewPager(runtime.PagingHandler[TargetsClientListByWatcherResponse]{ + More: func(page TargetsClientListByWatcherResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *TargetsClientListByWatcherResponse) (TargetsClientListByWatcherResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "TargetsClient.NewListByWatcherPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByWatcherCreateRequest(ctx, resourceGroupName, watcherName, options) + }, nil) + if err != nil { + return TargetsClientListByWatcherResponse{}, err + } + return client.listByWatcherHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByWatcherCreateRequest creates the ListByWatcher request. +func (client *TargetsClient) listByWatcherCreateRequest(ctx context.Context, resourceGroupName string, watcherName string, _ *TargetsClientListByWatcherOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/targets" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if watcherName == "" { + return nil, errors.New("parameter watcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{watcherName}", url.PathEscape(watcherName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250102) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByWatcherHandleResponse handles the ListByWatcher response. +func (client *TargetsClient) listByWatcherHandleResponse(resp *http.Response) (TargetsClientListByWatcherResponse, error) { + result := TargetsClientListByWatcherResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.TargetListResult); err != nil { + return TargetsClientListByWatcherResponse{}, err + } + return result, nil +} diff --git a/test/local/armdatabasewatcher/zz_version.go b/test/local/armdatabasewatcher/zz_version.go new file mode 100644 index 000000000000..a043215bd8d8 --- /dev/null +++ b/test/local/armdatabasewatcher/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package armdatabasewatcher + +const ( + moduleName = "armdatabasewatcher" + moduleVersion = "v0.1.0" +) diff --git a/test/local/armdatabasewatcher/zz_watchers_client.go b/test/local/armdatabasewatcher/zz_watchers_client.go new file mode 100644 index 000000000000..136cc361df21 --- /dev/null +++ b/test/local/armdatabasewatcher/zz_watchers_client.go @@ -0,0 +1,581 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdatabasewatcher + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// WatchersClient contains the methods for the Watchers group. +// Don't use this type directly, use NewWatchersClient() instead. +// +// Generated from API version 2025-01-02 +type WatchersClient struct { + internal *arm.Client + subscriptionID string +} + +// NewWatchersClient creates a new instance of WatchersClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewWatchersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*WatchersClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &WatchersClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create a Watcher +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - watcherName - The database watcher name. +// - resource - Resource create parameters. +// - options - WatchersClientBeginCreateOrUpdateOptions contains the optional parameters for the WatchersClient.BeginCreateOrUpdate +// method. +func (client *WatchersClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, watcherName string, resource Watcher, options *WatchersClientBeginCreateOrUpdateOptions) (*runtime.Poller[WatchersClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, watcherName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[WatchersClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[WatchersClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create a Watcher +// If the operation fails it returns an *azcore.ResponseError type. +func (client *WatchersClient) createOrUpdate(ctx context.Context, resourceGroupName string, watcherName string, resource Watcher, options *WatchersClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "WatchersClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, watcherName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *WatchersClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, watcherName string, resource Watcher, _ *WatchersClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if watcherName == "" { + return nil, errors.New("parameter watcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{watcherName}", url.PathEscape(watcherName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250102) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a Watcher +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - watcherName - The database watcher name. +// - options - WatchersClientBeginDeleteOptions contains the optional parameters for the WatchersClient.BeginDelete method. +func (client *WatchersClient) BeginDelete(ctx context.Context, resourceGroupName string, watcherName string, options *WatchersClientBeginDeleteOptions) (*runtime.Poller[WatchersClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, watcherName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[WatchersClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[WatchersClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a Watcher +// If the operation fails it returns an *azcore.ResponseError type. +func (client *WatchersClient) deleteOperation(ctx context.Context, resourceGroupName string, watcherName string, options *WatchersClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "WatchersClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, watcherName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *WatchersClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, watcherName string, _ *WatchersClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if watcherName == "" { + return nil, errors.New("parameter watcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{watcherName}", url.PathEscape(watcherName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250102) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a Watcher +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - watcherName - The database watcher name. +// - options - WatchersClientGetOptions contains the optional parameters for the WatchersClient.Get method. +func (client *WatchersClient) Get(ctx context.Context, resourceGroupName string, watcherName string, options *WatchersClientGetOptions) (WatchersClientGetResponse, error) { + var err error + const operationName = "WatchersClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, watcherName, options) + if err != nil { + return WatchersClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return WatchersClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return WatchersClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *WatchersClient) getCreateRequest(ctx context.Context, resourceGroupName string, watcherName string, _ *WatchersClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if watcherName == "" { + return nil, errors.New("parameter watcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{watcherName}", url.PathEscape(watcherName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250102) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *WatchersClient) getHandleResponse(resp *http.Response) (WatchersClientGetResponse, error) { + result := WatchersClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Watcher); err != nil { + return WatchersClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - List Watcher resources by resource group +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - WatchersClientListByResourceGroupOptions contains the optional parameters for the WatchersClient.NewListByResourceGroupPager +// method. +func (client *WatchersClient) NewListByResourceGroupPager(resourceGroupName string, options *WatchersClientListByResourceGroupOptions) *runtime.Pager[WatchersClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[WatchersClientListByResourceGroupResponse]{ + More: func(page WatchersClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *WatchersClientListByResourceGroupResponse) (WatchersClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "WatchersClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return WatchersClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *WatchersClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *WatchersClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250102) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *WatchersClient) listByResourceGroupHandleResponse(resp *http.Response) (WatchersClientListByResourceGroupResponse, error) { + result := WatchersClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.WatcherListResult); err != nil { + return WatchersClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - List Watcher resources by subscription ID +// - options - WatchersClientListBySubscriptionOptions contains the optional parameters for the WatchersClient.NewListBySubscriptionPager +// method. +func (client *WatchersClient) NewListBySubscriptionPager(options *WatchersClientListBySubscriptionOptions) *runtime.Pager[WatchersClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[WatchersClientListBySubscriptionResponse]{ + More: func(page WatchersClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *WatchersClientListBySubscriptionResponse) (WatchersClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "WatchersClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return WatchersClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *WatchersClient) listBySubscriptionCreateRequest(ctx context.Context, _ *WatchersClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.DatabaseWatcher/watchers" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250102) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *WatchersClient) listBySubscriptionHandleResponse(resp *http.Response) (WatchersClientListBySubscriptionResponse, error) { + result := WatchersClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.WatcherListResult); err != nil { + return WatchersClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// BeginStart - The action to start monitoring all targets configured for a database watcher. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - watcherName - The database watcher name. +// - options - WatchersClientBeginStartOptions contains the optional parameters for the WatchersClient.BeginStart method. +func (client *WatchersClient) BeginStart(ctx context.Context, resourceGroupName string, watcherName string, options *WatchersClientBeginStartOptions) (*runtime.Poller[WatchersClientStartResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.start(ctx, resourceGroupName, watcherName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[WatchersClientStartResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[WatchersClientStartResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Start - The action to start monitoring all targets configured for a database watcher. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *WatchersClient) start(ctx context.Context, resourceGroupName string, watcherName string, options *WatchersClientBeginStartOptions) (*http.Response, error) { + var err error + const operationName = "WatchersClient.BeginStart" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.startCreateRequest(ctx, resourceGroupName, watcherName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// startCreateRequest creates the Start request. +func (client *WatchersClient) startCreateRequest(ctx context.Context, resourceGroupName string, watcherName string, _ *WatchersClientBeginStartOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/start" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if watcherName == "" { + return nil, errors.New("parameter watcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{watcherName}", url.PathEscape(watcherName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250102) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginStop - The action to stop monitoring all targets configured for a database watcher. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - watcherName - The database watcher name. +// - options - WatchersClientBeginStopOptions contains the optional parameters for the WatchersClient.BeginStop method. +func (client *WatchersClient) BeginStop(ctx context.Context, resourceGroupName string, watcherName string, options *WatchersClientBeginStopOptions) (*runtime.Poller[WatchersClientStopResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.stop(ctx, resourceGroupName, watcherName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[WatchersClientStopResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[WatchersClientStopResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Stop - The action to stop monitoring all targets configured for a database watcher. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *WatchersClient) stop(ctx context.Context, resourceGroupName string, watcherName string, options *WatchersClientBeginStopOptions) (*http.Response, error) { + var err error + const operationName = "WatchersClient.BeginStop" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.stopCreateRequest(ctx, resourceGroupName, watcherName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// stopCreateRequest creates the Stop request. +func (client *WatchersClient) stopCreateRequest(ctx context.Context, resourceGroupName string, watcherName string, _ *WatchersClientBeginStopOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}/stop" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if watcherName == "" { + return nil, errors.New("parameter watcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{watcherName}", url.PathEscape(watcherName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250102) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginUpdate - Update a Watcher +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - watcherName - The database watcher name. +// - properties - The resource properties to be updated. +// - options - WatchersClientBeginUpdateOptions contains the optional parameters for the WatchersClient.BeginUpdate method. +func (client *WatchersClient) BeginUpdate(ctx context.Context, resourceGroupName string, watcherName string, properties WatcherUpdate, options *WatchersClientBeginUpdateOptions) (*runtime.Poller[WatchersClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, watcherName, properties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[WatchersClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[WatchersClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a Watcher +// If the operation fails it returns an *azcore.ResponseError type. +func (client *WatchersClient) update(ctx context.Context, resourceGroupName string, watcherName string, properties WatcherUpdate, options *WatchersClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "WatchersClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, watcherName, properties, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *WatchersClient) updateCreateRequest(ctx context.Context, resourceGroupName string, watcherName string, properties WatcherUpdate, _ *WatchersClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DatabaseWatcher/watchers/{watcherName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if watcherName == "" { + return nil, errors.New("parameter watcherName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{watcherName}", url.PathEscape(watcherName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250102) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armdevopsinfrastructure/LICENSE.txt b/test/local/armdevopsinfrastructure/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/local/armdevopsinfrastructure/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/local/armdevopsinfrastructure/fake/zz_imageversions_server.go b/test/local/armdevopsinfrastructure/fake/zz_imageversions_server.go new file mode 100644 index 000000000000..1d25c483231b --- /dev/null +++ b/test/local/armdevopsinfrastructure/fake/zz_imageversions_server.go @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armdevopsinfrastructure" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// ImageVersionsServer is a fake server for instances of the armdevopsinfrastructure.ImageVersionsClient type. +type ImageVersionsServer struct { + // NewListByImagePager is the fake for method ImageVersionsClient.NewListByImagePager + // HTTP status codes to indicate success: http.StatusOK + NewListByImagePager func(resourceGroupName string, imageName string, options *armdevopsinfrastructure.ImageVersionsClientListByImageOptions) (resp azfake.PagerResponder[armdevopsinfrastructure.ImageVersionsClientListByImageResponse]) +} + +// NewImageVersionsServerTransport creates a new instance of ImageVersionsServerTransport with the provided implementation. +// The returned ImageVersionsServerTransport instance is connected to an instance of armdevopsinfrastructure.ImageVersionsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewImageVersionsServerTransport(srv *ImageVersionsServer) *ImageVersionsServerTransport { + return &ImageVersionsServerTransport{ + srv: srv, + newListByImagePager: newTracker[azfake.PagerResponder[armdevopsinfrastructure.ImageVersionsClientListByImageResponse]](), + } +} + +// ImageVersionsServerTransport connects instances of armdevopsinfrastructure.ImageVersionsClient to instances of ImageVersionsServer. +// Don't use this type directly, use NewImageVersionsServerTransport instead. +type ImageVersionsServerTransport struct { + srv *ImageVersionsServer + newListByImagePager *tracker[azfake.PagerResponder[armdevopsinfrastructure.ImageVersionsClientListByImageResponse]] +} + +// Do implements the policy.Transporter interface for ImageVersionsServerTransport. +func (i *ImageVersionsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return i.dispatchToMethodFake(req, method) +} + +func (i *ImageVersionsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if imageVersionsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = imageVersionsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ImageVersionsClient.NewListByImagePager": + res.resp, res.err = i.dispatchNewListByImagePager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (i *ImageVersionsServerTransport) dispatchNewListByImagePager(req *http.Request) (*http.Response, error) { + if i.srv.NewListByImagePager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByImagePager not implemented")} + } + newListByImagePager := i.newListByImagePager.get(req) + if newListByImagePager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DevOpsInfrastructure/images/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/versions` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + imageNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("imageName")]) + if err != nil { + return nil, err + } + resp := i.srv.NewListByImagePager(resourceGroupNameParam, imageNameParam, nil) + newListByImagePager = &resp + i.newListByImagePager.add(req, newListByImagePager) + server.PagerResponderInjectNextLinks(newListByImagePager, req, func(page *armdevopsinfrastructure.ImageVersionsClientListByImageResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByImagePager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + i.newListByImagePager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByImagePager) { + i.newListByImagePager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ImageVersionsServerTransport +var imageVersionsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armdevopsinfrastructure/fake/zz_internal.go b/test/local/armdevopsinfrastructure/fake/zz_internal.go new file mode 100644 index 000000000000..590b4d743e97 --- /dev/null +++ b/test/local/armdevopsinfrastructure/fake/zz_internal.go @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/local/armdevopsinfrastructure/fake/zz_operations_server.go b/test/local/armdevopsinfrastructure/fake/zz_operations_server.go new file mode 100644 index 000000000000..7657682b03fc --- /dev/null +++ b/test/local/armdevopsinfrastructure/fake/zz_operations_server.go @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armdevopsinfrastructure" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "slices" +) + +// OperationsServer is a fake server for instances of the armdevopsinfrastructure.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armdevopsinfrastructure.OperationsClientListOptions) (resp azfake.PagerResponder[armdevopsinfrastructure.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of armdevopsinfrastructure.OperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOperationsServerTransport(srv *OperationsServer) *OperationsServerTransport { + return &OperationsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armdevopsinfrastructure.OperationsClientListResponse]](), + } +} + +// OperationsServerTransport connects instances of armdevopsinfrastructure.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[armdevopsinfrastructure.OperationsClientListResponse]] +} + +// Do implements the policy.Transporter interface for OperationsServerTransport. +func (o *OperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if operationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = operationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OperationsClient.NewListPager": + res.resp, res.err = o.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OperationsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := o.newListPager.get(req) + if newListPager == nil { + resp := o.srv.NewListPager(nil) + newListPager = &resp + o.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armdevopsinfrastructure.OperationsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + o.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + o.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OperationsServerTransport +var operationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armdevopsinfrastructure/fake/zz_pools_server.go b/test/local/armdevopsinfrastructure/fake/zz_pools_server.go new file mode 100644 index 000000000000..28d523080cd0 --- /dev/null +++ b/test/local/armdevopsinfrastructure/fake/zz_pools_server.go @@ -0,0 +1,448 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armdevopsinfrastructure" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// PoolsServer is a fake server for instances of the armdevopsinfrastructure.PoolsClient type. +type PoolsServer struct { + // CheckNameAvailability is the fake for method PoolsClient.CheckNameAvailability + // HTTP status codes to indicate success: http.StatusOK + CheckNameAvailability func(ctx context.Context, body armdevopsinfrastructure.CheckNameAvailability, options *armdevopsinfrastructure.PoolsClientCheckNameAvailabilityOptions) (resp azfake.Responder[armdevopsinfrastructure.PoolsClientCheckNameAvailabilityResponse], errResp azfake.ErrorResponder) + + // BeginCreateOrUpdate is the fake for method PoolsClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, poolName string, resource armdevopsinfrastructure.Pool, options *armdevopsinfrastructure.PoolsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armdevopsinfrastructure.PoolsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method PoolsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, poolName string, options *armdevopsinfrastructure.PoolsClientBeginDeleteOptions) (resp azfake.PollerResponder[armdevopsinfrastructure.PoolsClientDeleteResponse], errResp azfake.ErrorResponder) + + // DeleteResources is the fake for method PoolsClient.DeleteResources + // HTTP status codes to indicate success: http.StatusOK + DeleteResources func(ctx context.Context, resourceGroupName string, poolName string, body armdevopsinfrastructure.DeleteResourcesDetails, options *armdevopsinfrastructure.PoolsClientDeleteResourcesOptions) (resp azfake.Responder[armdevopsinfrastructure.PoolsClientDeleteResourcesResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method PoolsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, poolName string, options *armdevopsinfrastructure.PoolsClientGetOptions) (resp azfake.Responder[armdevopsinfrastructure.PoolsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method PoolsClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armdevopsinfrastructure.PoolsClientListByResourceGroupOptions) (resp azfake.PagerResponder[armdevopsinfrastructure.PoolsClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method PoolsClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armdevopsinfrastructure.PoolsClientListBySubscriptionOptions) (resp azfake.PagerResponder[armdevopsinfrastructure.PoolsClientListBySubscriptionResponse]) + + // BeginUpdate is the fake for method PoolsClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, poolName string, properties armdevopsinfrastructure.PoolUpdate, options *armdevopsinfrastructure.PoolsClientBeginUpdateOptions) (resp azfake.PollerResponder[armdevopsinfrastructure.PoolsClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewPoolsServerTransport creates a new instance of PoolsServerTransport with the provided implementation. +// The returned PoolsServerTransport instance is connected to an instance of armdevopsinfrastructure.PoolsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewPoolsServerTransport(srv *PoolsServer) *PoolsServerTransport { + return &PoolsServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armdevopsinfrastructure.PoolsClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armdevopsinfrastructure.PoolsClientDeleteResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armdevopsinfrastructure.PoolsClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armdevopsinfrastructure.PoolsClientListBySubscriptionResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armdevopsinfrastructure.PoolsClientUpdateResponse]](), + } +} + +// PoolsServerTransport connects instances of armdevopsinfrastructure.PoolsClient to instances of PoolsServer. +// Don't use this type directly, use NewPoolsServerTransport instead. +type PoolsServerTransport struct { + srv *PoolsServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armdevopsinfrastructure.PoolsClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armdevopsinfrastructure.PoolsClientDeleteResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armdevopsinfrastructure.PoolsClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armdevopsinfrastructure.PoolsClientListBySubscriptionResponse]] + beginUpdate *tracker[azfake.PollerResponder[armdevopsinfrastructure.PoolsClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for PoolsServerTransport. +func (p *PoolsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return p.dispatchToMethodFake(req, method) +} + +func (p *PoolsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if poolsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = poolsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "PoolsClient.CheckNameAvailability": + res.resp, res.err = p.dispatchCheckNameAvailability(req) + case "PoolsClient.BeginCreateOrUpdate": + res.resp, res.err = p.dispatchBeginCreateOrUpdate(req) + case "PoolsClient.BeginDelete": + res.resp, res.err = p.dispatchBeginDelete(req) + case "PoolsClient.DeleteResources": + res.resp, res.err = p.dispatchDeleteResources(req) + case "PoolsClient.Get": + res.resp, res.err = p.dispatchGet(req) + case "PoolsClient.NewListByResourceGroupPager": + res.resp, res.err = p.dispatchNewListByResourceGroupPager(req) + case "PoolsClient.NewListBySubscriptionPager": + res.resp, res.err = p.dispatchNewListBySubscriptionPager(req) + case "PoolsClient.BeginUpdate": + res.resp, res.err = p.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (p *PoolsServerTransport) dispatchCheckNameAvailability(req *http.Request) (*http.Response, error) { + if p.srv.CheckNameAvailability == nil { + return nil, &nonRetriableError{errors.New("fake for method CheckNameAvailability not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DevOpsInfrastructure/checkNameAvailability` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armdevopsinfrastructure.CheckNameAvailability](req) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.CheckNameAvailability(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CheckNameAvailabilityResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (p *PoolsServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if p.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := p.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DevOpsInfrastructure/pools/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armdevopsinfrastructure.Pool](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + poolNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("poolName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, poolNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + p.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + p.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + p.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (p *PoolsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if p.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := p.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DevOpsInfrastructure/pools/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + poolNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("poolName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.BeginDelete(req.Context(), resourceGroupNameParam, poolNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + p.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + p.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + p.beginDelete.remove(req) + } + + return resp, nil +} + +func (p *PoolsServerTransport) dispatchDeleteResources(req *http.Request) (*http.Response, error) { + if p.srv.DeleteResources == nil { + return nil, &nonRetriableError{errors.New("fake for method DeleteResources not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DevOpsInfrastructure/pools/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resources` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armdevopsinfrastructure.DeleteResourcesDetails](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + poolNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("poolName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.DeleteResources(req.Context(), resourceGroupNameParam, poolNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (p *PoolsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if p.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DevOpsInfrastructure/pools/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + poolNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("poolName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.Get(req.Context(), resourceGroupNameParam, poolNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Pool, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (p *PoolsServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if p.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := p.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DevOpsInfrastructure/pools` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := p.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + p.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armdevopsinfrastructure.PoolsClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + p.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (p *PoolsServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if p.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := p.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DevOpsInfrastructure/pools` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := p.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + p.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armdevopsinfrastructure.PoolsClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + p.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (p *PoolsServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if p.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := p.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DevOpsInfrastructure/pools/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armdevopsinfrastructure.PoolUpdate](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + poolNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("poolName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.BeginUpdate(req.Context(), resourceGroupNameParam, poolNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + p.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + p.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + p.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to PoolsServerTransport +var poolsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armdevopsinfrastructure/fake/zz_resourcedetails_server.go b/test/local/armdevopsinfrastructure/fake/zz_resourcedetails_server.go new file mode 100644 index 000000000000..db8b8d4285ba --- /dev/null +++ b/test/local/armdevopsinfrastructure/fake/zz_resourcedetails_server.go @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armdevopsinfrastructure" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// ResourceDetailsServer is a fake server for instances of the armdevopsinfrastructure.ResourceDetailsClient type. +type ResourceDetailsServer struct { + // NewListByPoolPager is the fake for method ResourceDetailsClient.NewListByPoolPager + // HTTP status codes to indicate success: http.StatusOK + NewListByPoolPager func(resourceGroupName string, poolName string, options *armdevopsinfrastructure.ResourceDetailsClientListByPoolOptions) (resp azfake.PagerResponder[armdevopsinfrastructure.ResourceDetailsClientListByPoolResponse]) +} + +// NewResourceDetailsServerTransport creates a new instance of ResourceDetailsServerTransport with the provided implementation. +// The returned ResourceDetailsServerTransport instance is connected to an instance of armdevopsinfrastructure.ResourceDetailsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewResourceDetailsServerTransport(srv *ResourceDetailsServer) *ResourceDetailsServerTransport { + return &ResourceDetailsServerTransport{ + srv: srv, + newListByPoolPager: newTracker[azfake.PagerResponder[armdevopsinfrastructure.ResourceDetailsClientListByPoolResponse]](), + } +} + +// ResourceDetailsServerTransport connects instances of armdevopsinfrastructure.ResourceDetailsClient to instances of ResourceDetailsServer. +// Don't use this type directly, use NewResourceDetailsServerTransport instead. +type ResourceDetailsServerTransport struct { + srv *ResourceDetailsServer + newListByPoolPager *tracker[azfake.PagerResponder[armdevopsinfrastructure.ResourceDetailsClientListByPoolResponse]] +} + +// Do implements the policy.Transporter interface for ResourceDetailsServerTransport. +func (r *ResourceDetailsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return r.dispatchToMethodFake(req, method) +} + +func (r *ResourceDetailsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if resourceDetailsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = resourceDetailsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ResourceDetailsClient.NewListByPoolPager": + res.resp, res.err = r.dispatchNewListByPoolPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (r *ResourceDetailsServerTransport) dispatchNewListByPoolPager(req *http.Request) (*http.Response, error) { + if r.srv.NewListByPoolPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByPoolPager not implemented")} + } + newListByPoolPager := r.newListByPoolPager.get(req) + if newListByPoolPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DevOpsInfrastructure/pools/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resources` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + poolNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("poolName")]) + if err != nil { + return nil, err + } + resp := r.srv.NewListByPoolPager(resourceGroupNameParam, poolNameParam, nil) + newListByPoolPager = &resp + r.newListByPoolPager.add(req, newListByPoolPager) + server.PagerResponderInjectNextLinks(newListByPoolPager, req, func(page *armdevopsinfrastructure.ResourceDetailsClientListByPoolResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByPoolPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + r.newListByPoolPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByPoolPager) { + r.newListByPoolPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ResourceDetailsServerTransport +var resourceDetailsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armdevopsinfrastructure/fake/zz_server_factory.go b/test/local/armdevopsinfrastructure/fake/zz_server_factory.go new file mode 100644 index 000000000000..0b02b771a612 --- /dev/null +++ b/test/local/armdevopsinfrastructure/fake/zz_server_factory.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armdevopsinfrastructure.ClientFactory type. +type ServerFactory struct { + // ImageVersionsServer contains the fakes for client ImageVersionsClient + ImageVersionsServer ImageVersionsServer + + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer + + // PoolsServer contains the fakes for client PoolsClient + PoolsServer PoolsServer + + // ResourceDetailsServer contains the fakes for client ResourceDetailsClient + ResourceDetailsServer ResourceDetailsServer + + // SKUServer contains the fakes for client SKUClient + SKUServer SKUServer + + // SubscriptionUsagesServer contains the fakes for client SubscriptionUsagesClient + SubscriptionUsagesServer SubscriptionUsagesServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armdevopsinfrastructure.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of armdevopsinfrastructure.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trImageVersionsServer *ImageVersionsServerTransport + trOperationsServer *OperationsServerTransport + trPoolsServer *PoolsServerTransport + trResourceDetailsServer *ResourceDetailsServerTransport + trSKUServer *SKUServerTransport + trSubscriptionUsagesServer *SubscriptionUsagesServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "ImageVersionsClient": + initServer(&s.trMu, &s.trImageVersionsServer, func() *ImageVersionsServerTransport { + return NewImageVersionsServerTransport(&s.srv.ImageVersionsServer) + }) + resp, err = s.trImageVersionsServer.Do(req) + case "OperationsClient": + initServer(&s.trMu, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + resp, err = s.trOperationsServer.Do(req) + case "PoolsClient": + initServer(&s.trMu, &s.trPoolsServer, func() *PoolsServerTransport { return NewPoolsServerTransport(&s.srv.PoolsServer) }) + resp, err = s.trPoolsServer.Do(req) + case "ResourceDetailsClient": + initServer(&s.trMu, &s.trResourceDetailsServer, func() *ResourceDetailsServerTransport { + return NewResourceDetailsServerTransport(&s.srv.ResourceDetailsServer) + }) + resp, err = s.trResourceDetailsServer.Do(req) + case "SKUClient": + initServer(&s.trMu, &s.trSKUServer, func() *SKUServerTransport { return NewSKUServerTransport(&s.srv.SKUServer) }) + resp, err = s.trSKUServer.Do(req) + case "SubscriptionUsagesClient": + initServer(&s.trMu, &s.trSubscriptionUsagesServer, func() *SubscriptionUsagesServerTransport { + return NewSubscriptionUsagesServerTransport(&s.srv.SubscriptionUsagesServer) + }) + resp, err = s.trSubscriptionUsagesServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} diff --git a/test/local/armdevopsinfrastructure/fake/zz_sku_server.go b/test/local/armdevopsinfrastructure/fake/zz_sku_server.go new file mode 100644 index 000000000000..0b9eb14d4f5e --- /dev/null +++ b/test/local/armdevopsinfrastructure/fake/zz_sku_server.go @@ -0,0 +1,125 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armdevopsinfrastructure" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// SKUServer is a fake server for instances of the armdevopsinfrastructure.SKUClient type. +type SKUServer struct { + // NewListByLocationPager is the fake for method SKUClient.NewListByLocationPager + // HTTP status codes to indicate success: http.StatusOK + NewListByLocationPager func(locationName string, options *armdevopsinfrastructure.SKUClientListByLocationOptions) (resp azfake.PagerResponder[armdevopsinfrastructure.SKUClientListByLocationResponse]) +} + +// NewSKUServerTransport creates a new instance of SKUServerTransport with the provided implementation. +// The returned SKUServerTransport instance is connected to an instance of armdevopsinfrastructure.SKUClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSKUServerTransport(srv *SKUServer) *SKUServerTransport { + return &SKUServerTransport{ + srv: srv, + newListByLocationPager: newTracker[azfake.PagerResponder[armdevopsinfrastructure.SKUClientListByLocationResponse]](), + } +} + +// SKUServerTransport connects instances of armdevopsinfrastructure.SKUClient to instances of SKUServer. +// Don't use this type directly, use NewSKUServerTransport instead. +type SKUServerTransport struct { + srv *SKUServer + newListByLocationPager *tracker[azfake.PagerResponder[armdevopsinfrastructure.SKUClientListByLocationResponse]] +} + +// Do implements the policy.Transporter interface for SKUServerTransport. +func (s *SKUServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *SKUServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if skuServerTransportInterceptor != nil { + res.resp, res.err, intercepted = skuServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SKUClient.NewListByLocationPager": + res.resp, res.err = s.dispatchNewListByLocationPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *SKUServerTransport) dispatchNewListByLocationPager(req *http.Request) (*http.Response, error) { + if s.srv.NewListByLocationPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByLocationPager not implemented")} + } + newListByLocationPager := s.newListByLocationPager.get(req) + if newListByLocationPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DevOpsInfrastructure/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/skus` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("locationName")]) + if err != nil { + return nil, err + } + resp := s.srv.NewListByLocationPager(locationNameParam, nil) + newListByLocationPager = &resp + s.newListByLocationPager.add(req, newListByLocationPager) + server.PagerResponderInjectNextLinks(newListByLocationPager, req, func(page *armdevopsinfrastructure.SKUClientListByLocationResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByLocationPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + s.newListByLocationPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByLocationPager) { + s.newListByLocationPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SKUServerTransport +var skuServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armdevopsinfrastructure/fake/zz_subscriptionusages_server.go b/test/local/armdevopsinfrastructure/fake/zz_subscriptionusages_server.go new file mode 100644 index 000000000000..cda5363f9506 --- /dev/null +++ b/test/local/armdevopsinfrastructure/fake/zz_subscriptionusages_server.go @@ -0,0 +1,125 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armdevopsinfrastructure" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// SubscriptionUsagesServer is a fake server for instances of the armdevopsinfrastructure.SubscriptionUsagesClient type. +type SubscriptionUsagesServer struct { + // NewUsagesPager is the fake for method SubscriptionUsagesClient.NewUsagesPager + // HTTP status codes to indicate success: http.StatusOK + NewUsagesPager func(location string, options *armdevopsinfrastructure.SubscriptionUsagesClientUsagesOptions) (resp azfake.PagerResponder[armdevopsinfrastructure.SubscriptionUsagesClientUsagesResponse]) +} + +// NewSubscriptionUsagesServerTransport creates a new instance of SubscriptionUsagesServerTransport with the provided implementation. +// The returned SubscriptionUsagesServerTransport instance is connected to an instance of armdevopsinfrastructure.SubscriptionUsagesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSubscriptionUsagesServerTransport(srv *SubscriptionUsagesServer) *SubscriptionUsagesServerTransport { + return &SubscriptionUsagesServerTransport{ + srv: srv, + newUsagesPager: newTracker[azfake.PagerResponder[armdevopsinfrastructure.SubscriptionUsagesClientUsagesResponse]](), + } +} + +// SubscriptionUsagesServerTransport connects instances of armdevopsinfrastructure.SubscriptionUsagesClient to instances of SubscriptionUsagesServer. +// Don't use this type directly, use NewSubscriptionUsagesServerTransport instead. +type SubscriptionUsagesServerTransport struct { + srv *SubscriptionUsagesServer + newUsagesPager *tracker[azfake.PagerResponder[armdevopsinfrastructure.SubscriptionUsagesClientUsagesResponse]] +} + +// Do implements the policy.Transporter interface for SubscriptionUsagesServerTransport. +func (s *SubscriptionUsagesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *SubscriptionUsagesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if subscriptionUsagesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = subscriptionUsagesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SubscriptionUsagesClient.NewUsagesPager": + res.resp, res.err = s.dispatchNewUsagesPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *SubscriptionUsagesServerTransport) dispatchNewUsagesPager(req *http.Request) (*http.Response, error) { + if s.srv.NewUsagesPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewUsagesPager not implemented")} + } + newUsagesPager := s.newUsagesPager.get(req) + if newUsagesPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DevOpsInfrastructure/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/usages` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + resp := s.srv.NewUsagesPager(locationParam, nil) + newUsagesPager = &resp + s.newUsagesPager.add(req, newUsagesPager) + server.PagerResponderInjectNextLinks(newUsagesPager, req, func(page *armdevopsinfrastructure.SubscriptionUsagesClientUsagesResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newUsagesPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + s.newUsagesPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newUsagesPager) { + s.newUsagesPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SubscriptionUsagesServerTransport +var subscriptionUsagesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armdevopsinfrastructure/go.mod b/test/local/armdevopsinfrastructure/go.mod new file mode 100644 index 000000000000..fac34a1ed8ec --- /dev/null +++ b/test/local/armdevopsinfrastructure/go.mod @@ -0,0 +1,11 @@ +module armdevopsinfrastructure + +go 1.25.0 + +require github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect +) diff --git a/test/local/armdevopsinfrastructure/go.sum b/test/local/armdevopsinfrastructure/go.sum new file mode 100644 index 000000000000..3fdb64caf441 --- /dev/null +++ b/test/local/armdevopsinfrastructure/go.sum @@ -0,0 +1,16 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/local/armdevopsinfrastructure/testdata/_metadata.json b/test/local/armdevopsinfrastructure/testdata/_metadata.json new file mode 100644 index 000000000000..aad006c464b2 --- /dev/null +++ b/test/local/armdevopsinfrastructure/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Microsoft.DevOpsInfrastructure": "2026-04-17-preview" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/local/armdevopsinfrastructure/zz_client_factory.go b/test/local/armdevopsinfrastructure/zz_client_factory.go new file mode 100644 index 000000000000..1f7ea53e09ba --- /dev/null +++ b/test/local/armdevopsinfrastructure/zz_client_factory.go @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdevopsinfrastructure + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + subscriptionID string + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, + internal: internal, + }, nil +} + +// NewImageVersionsClient creates a new instance of ImageVersionsClient. +func (c *ClientFactory) NewImageVersionsClient() *ImageVersionsClient { + return &ImageVersionsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: c.internal, + } +} + +// NewPoolsClient creates a new instance of PoolsClient. +func (c *ClientFactory) NewPoolsClient() *PoolsClient { + return &PoolsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewResourceDetailsClient creates a new instance of ResourceDetailsClient. +func (c *ClientFactory) NewResourceDetailsClient() *ResourceDetailsClient { + return &ResourceDetailsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewSKUClient creates a new instance of SKUClient. +func (c *ClientFactory) NewSKUClient() *SKUClient { + return &SKUClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewSubscriptionUsagesClient creates a new instance of SubscriptionUsagesClient. +func (c *ClientFactory) NewSubscriptionUsagesClient() *SubscriptionUsagesClient { + return &SubscriptionUsagesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} diff --git a/test/local/armdevopsinfrastructure/zz_constants.go b/test/local/armdevopsinfrastructure/zz_constants.go new file mode 100644 index 000000000000..e22e03762987 --- /dev/null +++ b/test/local/armdevopsinfrastructure/zz_constants.go @@ -0,0 +1,451 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdevopsinfrastructure + +const ( + version20260417Preview string = "2026-04-17-preview" +) + +// ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +type ActionType string + +const ( + // ActionTypeInternal - Actions are for internal-only APIs. + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// AvailabilityStatus - AvailabilityStatus of a name. +type AvailabilityStatus string + +const ( + // AvailabilityStatusAvailable - The name is available. + AvailabilityStatusAvailable AvailabilityStatus = "Available" + // AvailabilityStatusUnavailable - The name is unavailable + AvailabilityStatusUnavailable AvailabilityStatus = "Unavailable" +) + +// PossibleAvailabilityStatusValues returns the possible values for the AvailabilityStatus const type. +func PossibleAvailabilityStatusValues() []AvailabilityStatus { + return []AvailabilityStatus{ + AvailabilityStatusAvailable, + AvailabilityStatusUnavailable, + } +} + +// AzureDevOpsPermissionType - Determines who has admin permissions to the Azure DevOps pool. +type AzureDevOpsPermissionType string + +const ( + // AzureDevOpsPermissionTypeCreatorOnly - Only the pool creator will be an admin of the pool. + AzureDevOpsPermissionTypeCreatorOnly AzureDevOpsPermissionType = "CreatorOnly" + // AzureDevOpsPermissionTypeInherit - Pool will inherit permissions from the project or organization. + AzureDevOpsPermissionTypeInherit AzureDevOpsPermissionType = "Inherit" + // AzureDevOpsPermissionTypeSpecificAccounts - Only the specified accounts will be admins of the pool. + AzureDevOpsPermissionTypeSpecificAccounts AzureDevOpsPermissionType = "SpecificAccounts" +) + +// PossibleAzureDevOpsPermissionTypeValues returns the possible values for the AzureDevOpsPermissionType const type. +func PossibleAzureDevOpsPermissionTypeValues() []AzureDevOpsPermissionType { + return []AzureDevOpsPermissionType{ + AzureDevOpsPermissionTypeCreatorOnly, + AzureDevOpsPermissionTypeInherit, + AzureDevOpsPermissionTypeSpecificAccounts, + } +} + +// CachingType - The type of caching in a data disk. +type CachingType string + +const ( + // CachingTypeNone - Don't use host caching. + CachingTypeNone CachingType = "None" + // CachingTypeReadOnly - For workloads that only do read operations. + CachingTypeReadOnly CachingType = "ReadOnly" + // CachingTypeReadWrite - For workloads that do a balance of read and write operations. + CachingTypeReadWrite CachingType = "ReadWrite" +) + +// PossibleCachingTypeValues returns the possible values for the CachingType const type. +func PossibleCachingTypeValues() []CachingType { + return []CachingType{ + CachingTypeNone, + CachingTypeReadOnly, + CachingTypeReadWrite, + } +} + +// CertificateStoreNameOption - The certificate store name type +type CertificateStoreNameOption string + +const ( + // CertificateStoreNameOptionMy - The X.509 certificate store for personal certificates. + CertificateStoreNameOptionMy CertificateStoreNameOption = "My" + // CertificateStoreNameOptionRoot - The X.509 certificate store for trusted root certificate authorities (CAs). + CertificateStoreNameOptionRoot CertificateStoreNameOption = "Root" +) + +// PossibleCertificateStoreNameOptionValues returns the possible values for the CertificateStoreNameOption const type. +func PossibleCertificateStoreNameOptionValues() []CertificateStoreNameOption { + return []CertificateStoreNameOption{ + CertificateStoreNameOptionMy, + CertificateStoreNameOptionRoot, + } +} + +// CheckNameAvailabilityReason - The reason code explaining why the name is unavailable. Will be null if the name is available. +type CheckNameAvailabilityReason string + +const ( + // CheckNameAvailabilityReasonAlreadyExists - The name already exists. + CheckNameAvailabilityReasonAlreadyExists CheckNameAvailabilityReason = "AlreadyExists" + // CheckNameAvailabilityReasonInvalid - The name is invalid. + CheckNameAvailabilityReasonInvalid CheckNameAvailabilityReason = "Invalid" +) + +// PossibleCheckNameAvailabilityReasonValues returns the possible values for the CheckNameAvailabilityReason const type. +func PossibleCheckNameAvailabilityReasonValues() []CheckNameAvailabilityReason { + return []CheckNameAvailabilityReason{ + CheckNameAvailabilityReasonAlreadyExists, + CheckNameAvailabilityReasonInvalid, + } +} + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// EphemeralType - The type of Ephemeral option the pool will use on underlying VMs when loading this image. +type EphemeralType string + +const ( + // EphemeralTypeAutomatic - Ephemeral is handled by Managed DevOps Pools service. + EphemeralTypeAutomatic EphemeralType = "Automatic" + // EphemeralTypeCacheDisk - CacheDisk ephemeral only, requires that the SKU has a cache that is large enough for the image. + EphemeralTypeCacheDisk EphemeralType = "CacheDisk" + // EphemeralTypeResourceDisk - ResourceDisk ephemeral only, requires only that the SKU supports it. + EphemeralTypeResourceDisk EphemeralType = "ResourceDisk" +) + +// PossibleEphemeralTypeValues returns the possible values for the EphemeralType const type. +func PossibleEphemeralTypeValues() []EphemeralType { + return []EphemeralType{ + EphemeralTypeAutomatic, + EphemeralTypeCacheDisk, + EphemeralTypeResourceDisk, + } +} + +// LogonType - Determines how the service should be run. +type LogonType string + +const ( + // LogonTypeInteractive - Run in interactive mode. + LogonTypeInteractive LogonType = "Interactive" + // LogonTypeService - Run as a service. + LogonTypeService LogonType = "Service" +) + +// PossibleLogonTypeValues returns the possible values for the LogonType const type. +func PossibleLogonTypeValues() []LogonType { + return []LogonType{ + LogonTypeInteractive, + LogonTypeService, + } +} + +// ManagedServiceIdentityType - Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). +type ManagedServiceIdentityType string + +const ( + // ManagedServiceIdentityTypeNone - No managed identity. + ManagedServiceIdentityTypeNone ManagedServiceIdentityType = "None" + // ManagedServiceIdentityTypeSystemAssigned - System assigned managed identity. + ManagedServiceIdentityTypeSystemAssigned ManagedServiceIdentityType = "SystemAssigned" + // ManagedServiceIdentityTypeSystemAssignedUserAssigned - System and user assigned managed identity. + ManagedServiceIdentityTypeSystemAssignedUserAssigned ManagedServiceIdentityType = "SystemAssigned,UserAssigned" + // ManagedServiceIdentityTypeUserAssigned - User assigned managed identity. + ManagedServiceIdentityTypeUserAssigned ManagedServiceIdentityType = "UserAssigned" +) + +// PossibleManagedServiceIdentityTypeValues returns the possible values for the ManagedServiceIdentityType const type. +func PossibleManagedServiceIdentityTypeValues() []ManagedServiceIdentityType { + return []ManagedServiceIdentityType{ + ManagedServiceIdentityTypeNone, + ManagedServiceIdentityTypeSystemAssigned, + ManagedServiceIdentityTypeSystemAssignedUserAssigned, + ManagedServiceIdentityTypeUserAssigned, + } +} + +// Origin - The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default +// value is "user,system" +type Origin string + +const ( + // OriginSystem - Indicates the operation is initiated by a system. + OriginSystem Origin = "system" + // OriginUser - Indicates the operation is initiated by a user. + OriginUser Origin = "user" + // OriginUserSystem - Indicates the operation is initiated by a user or system. + OriginUserSystem Origin = "user,system" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginSystem, + OriginUser, + OriginUserSystem, + } +} + +// OsDiskStorageAccountType - The storage account type of the OS disk. +type OsDiskStorageAccountType string + +const ( + // OsDiskStorageAccountTypePremium - Premium OS disk type. + OsDiskStorageAccountTypePremium OsDiskStorageAccountType = "Premium" + // OsDiskStorageAccountTypeStandard - Standard OS disk type. + OsDiskStorageAccountTypeStandard OsDiskStorageAccountType = "Standard" + // OsDiskStorageAccountTypeStandardSSD - Standard SSD OS disk type. + OsDiskStorageAccountTypeStandardSSD OsDiskStorageAccountType = "StandardSSD" +) + +// PossibleOsDiskStorageAccountTypeValues returns the possible values for the OsDiskStorageAccountType const type. +func PossibleOsDiskStorageAccountTypeValues() []OsDiskStorageAccountType { + return []OsDiskStorageAccountType{ + OsDiskStorageAccountTypePremium, + OsDiskStorageAccountTypeStandard, + OsDiskStorageAccountTypeStandardSSD, + } +} + +// PredictionPreference - Determines the balance between cost and performance. +type PredictionPreference string + +const ( + // PredictionPreferenceBalanced - Balance between cost and performance. + PredictionPreferenceBalanced PredictionPreference = "Balanced" + // PredictionPreferenceBestPerformance - Optimizes for performance over cost. + PredictionPreferenceBestPerformance PredictionPreference = "BestPerformance" + // PredictionPreferenceMoreCostEffective - Halfway through cost and balanced. + PredictionPreferenceMoreCostEffective PredictionPreference = "MoreCostEffective" + // PredictionPreferenceMorePerformance - Halfway through balanced and performance. + PredictionPreferenceMorePerformance PredictionPreference = "MorePerformance" + // PredictionPreferenceMostCostEffective - Optimizes for cost over performance. + PredictionPreferenceMostCostEffective PredictionPreference = "MostCostEffective" +) + +// PossiblePredictionPreferenceValues returns the possible values for the PredictionPreference const type. +func PossiblePredictionPreferenceValues() []PredictionPreference { + return []PredictionPreference{ + PredictionPreferenceBalanced, + PredictionPreferenceBestPerformance, + PredictionPreferenceMoreCostEffective, + PredictionPreferenceMorePerformance, + PredictionPreferenceMostCostEffective, + } +} + +// ProvisioningState - The status of the current operation. +type ProvisioningState string + +const ( + // ProvisioningStateAccepted - Represents an accepted operation. + ProvisioningStateAccepted ProvisioningState = "Accepted" + // ProvisioningStateCanceled - Represents a canceled operation. + ProvisioningStateCanceled ProvisioningState = "Canceled" + // ProvisioningStateDeleting - Represents an operation under deletion. + ProvisioningStateDeleting ProvisioningState = "Deleting" + // ProvisioningStateFailed - Represents a failed operation. + ProvisioningStateFailed ProvisioningState = "Failed" + // ProvisioningStateProvisioning - Represents a pending operation. + ProvisioningStateProvisioning ProvisioningState = "Provisioning" + // ProvisioningStateSucceeded - Represents a succeeded operation. + ProvisioningStateSucceeded ProvisioningState = "Succeeded" + // ProvisioningStateUpdating - Represents a pending operation. + ProvisioningStateUpdating ProvisioningState = "Updating" +) + +// PossibleProvisioningStateValues returns the possible values for the ProvisioningState const type. +func PossibleProvisioningStateValues() []ProvisioningState { + return []ProvisioningState{ + ProvisioningStateAccepted, + ProvisioningStateCanceled, + ProvisioningStateDeleting, + ProvisioningStateFailed, + ProvisioningStateProvisioning, + ProvisioningStateSucceeded, + ProvisioningStateUpdating, + } +} + +// ResourcePredictionsProfileType - Determines how the stand-by scheme should be provided. +type ResourcePredictionsProfileType string + +const ( + // ResourcePredictionsProfileTypeAutomatic - The stand-by agent scheme is determined based on historical demand. + ResourcePredictionsProfileTypeAutomatic ResourcePredictionsProfileType = "Automatic" + // ResourcePredictionsProfileTypeManual - Customer provides the stand-by agent scheme. + ResourcePredictionsProfileTypeManual ResourcePredictionsProfileType = "Manual" +) + +// PossibleResourcePredictionsProfileTypeValues returns the possible values for the ResourcePredictionsProfileType const type. +func PossibleResourcePredictionsProfileTypeValues() []ResourcePredictionsProfileType { + return []ResourcePredictionsProfileType{ + ResourcePredictionsProfileTypeAutomatic, + ResourcePredictionsProfileTypeManual, + } +} + +// ResourceSKURestrictionsReasonCode - Describes the reason for SKU restriction. +type ResourceSKURestrictionsReasonCode string + +const ( + // ResourceSKURestrictionsReasonCodeNotAvailableForSubscription - The restriction is not available for this subscription. + ResourceSKURestrictionsReasonCodeNotAvailableForSubscription ResourceSKURestrictionsReasonCode = "NotAvailableForSubscription" + // ResourceSKURestrictionsReasonCodeQuotaID - The restriction is due to exceeding a quota limitation. + ResourceSKURestrictionsReasonCodeQuotaID ResourceSKURestrictionsReasonCode = "QuotaId" +) + +// PossibleResourceSKURestrictionsReasonCodeValues returns the possible values for the ResourceSKURestrictionsReasonCode const type. +func PossibleResourceSKURestrictionsReasonCodeValues() []ResourceSKURestrictionsReasonCode { + return []ResourceSKURestrictionsReasonCode{ + ResourceSKURestrictionsReasonCodeNotAvailableForSubscription, + ResourceSKURestrictionsReasonCodeQuotaID, + } +} + +// ResourceSKURestrictionsType - Describes the kind of SKU restrictions that can exist +type ResourceSKURestrictionsType string + +const ( + // ResourceSKURestrictionsTypeLocation - SKU restricted by location. + ResourceSKURestrictionsTypeLocation ResourceSKURestrictionsType = "Location" + // ResourceSKURestrictionsTypeZone - SKU restricted by availability zone. + ResourceSKURestrictionsTypeZone ResourceSKURestrictionsType = "Zone" +) + +// PossibleResourceSKURestrictionsTypeValues returns the possible values for the ResourceSKURestrictionsType const type. +func PossibleResourceSKURestrictionsTypeValues() []ResourceSKURestrictionsType { + return []ResourceSKURestrictionsType{ + ResourceSKURestrictionsTypeLocation, + ResourceSKURestrictionsTypeZone, + } +} + +// ResourceStatus - The status of the machine resource. +type ResourceStatus string + +const ( + // ResourceStatusAllocated - Represents a machine resource that is allocated. + ResourceStatusAllocated ResourceStatus = "Allocated" + // ResourceStatusLeased - Represents a machine resource that is leased. + ResourceStatusLeased ResourceStatus = "Leased" + // ResourceStatusNotReady - Represents a machine resource that is not ready. + ResourceStatusNotReady ResourceStatus = "NotReady" + // ResourceStatusPendingReimage - Represents a machine resource that is pending reimage. + ResourceStatusPendingReimage ResourceStatus = "PendingReimage" + // ResourceStatusPendingReturn - Represents a machine resource that is pending return. + ResourceStatusPendingReturn ResourceStatus = "PendingReturn" + // ResourceStatusProvisioning - Represents a machine resource that is provisioning. + ResourceStatusProvisioning ResourceStatus = "Provisioning" + // ResourceStatusReady - Represents a machine resource that is ready. + ResourceStatusReady ResourceStatus = "Ready" + // ResourceStatusReimaging - Represents a machine resource that is reimaging. + ResourceStatusReimaging ResourceStatus = "Reimaging" + // ResourceStatusReturned - Represents a machine resource that is returned. + ResourceStatusReturned ResourceStatus = "Returned" + // ResourceStatusStarting - Represents a machine resource that is starting. + ResourceStatusStarting ResourceStatus = "Starting" + // ResourceStatusUpdating - Represents a machine resource that is updating. + ResourceStatusUpdating ResourceStatus = "Updating" +) + +// PossibleResourceStatusValues returns the possible values for the ResourceStatus const type. +func PossibleResourceStatusValues() []ResourceStatus { + return []ResourceStatus{ + ResourceStatusAllocated, + ResourceStatusLeased, + ResourceStatusNotReady, + ResourceStatusPendingReimage, + ResourceStatusPendingReturn, + ResourceStatusProvisioning, + ResourceStatusReady, + ResourceStatusReimaging, + ResourceStatusReturned, + ResourceStatusStarting, + ResourceStatusUpdating, + } +} + +// ResourceType - The type of resource. +type ResourceType string + +const ( + // ResourceTypeMicrosoftDevOpsInfrastructurePools - DevOpsInfrastructure pool resource. + ResourceTypeMicrosoftDevOpsInfrastructurePools ResourceType = "Microsoft.DevOpsInfrastructure/pools" +) + +// PossibleResourceTypeValues returns the possible values for the ResourceType const type. +func PossibleResourceTypeValues() []ResourceType { + return []ResourceType{ + ResourceTypeMicrosoftDevOpsInfrastructurePools, + } +} + +// StorageAccountType - StorageAccountType enums +type StorageAccountType string + +const ( + // StorageAccountTypePremiumLRS - The data disk should use premium locally redundant storage. + StorageAccountTypePremiumLRS StorageAccountType = "Premium_LRS" + // StorageAccountTypePremiumZRS - The data disk should use premium SSD zonal redundant storage. + StorageAccountTypePremiumZRS StorageAccountType = "Premium_ZRS" + // StorageAccountTypeStandardLRS - The data disk should use standard locally redundant storage. + StorageAccountTypeStandardLRS StorageAccountType = "Standard_LRS" + // StorageAccountTypeStandardSSDLRS - The data disk should use standard SSD locally redundant storage. + StorageAccountTypeStandardSSDLRS StorageAccountType = "StandardSSD_LRS" + // StorageAccountTypeStandardSSDZRS - The data disk should use standard SSD zonal redundant storage. + StorageAccountTypeStandardSSDZRS StorageAccountType = "StandardSSD_ZRS" +) + +// PossibleStorageAccountTypeValues returns the possible values for the StorageAccountType const type. +func PossibleStorageAccountTypeValues() []StorageAccountType { + return []StorageAccountType{ + StorageAccountTypePremiumLRS, + StorageAccountTypePremiumZRS, + StorageAccountTypeStandardLRS, + StorageAccountTypeStandardSSDLRS, + StorageAccountTypeStandardSSDZRS, + } +} diff --git a/test/local/armdevopsinfrastructure/zz_imageversions_client.go b/test/local/armdevopsinfrastructure/zz_imageversions_client.go new file mode 100644 index 000000000000..e3fb2d4b66d0 --- /dev/null +++ b/test/local/armdevopsinfrastructure/zz_imageversions_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdevopsinfrastructure + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ImageVersionsClient contains the methods for the ImageVersions group. +// Don't use this type directly, use NewImageVersionsClient() instead. +// +// Generated from API version 2026-04-17-preview +type ImageVersionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewImageVersionsClient creates a new instance of ImageVersionsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewImageVersionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ImageVersionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ImageVersionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListByImagePager - List ImageVersion resources by Image +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - imageName - Name of the image. +// - options - ImageVersionsClientListByImageOptions contains the optional parameters for the ImageVersionsClient.NewListByImagePager +// method. +func (client *ImageVersionsClient) NewListByImagePager(resourceGroupName string, imageName string, options *ImageVersionsClientListByImageOptions) *runtime.Pager[ImageVersionsClientListByImageResponse] { + return runtime.NewPager(runtime.PagingHandler[ImageVersionsClientListByImageResponse]{ + More: func(page ImageVersionsClientListByImageResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ImageVersionsClientListByImageResponse) (ImageVersionsClientListByImageResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ImageVersionsClient.NewListByImagePager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByImageCreateRequest(ctx, resourceGroupName, imageName, options) + }, nil) + if err != nil { + return ImageVersionsClientListByImageResponse{}, err + } + return client.listByImageHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByImageCreateRequest creates the ListByImage request. +func (client *ImageVersionsClient) listByImageCreateRequest(ctx context.Context, resourceGroupName string, imageName string, _ *ImageVersionsClientListByImageOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevOpsInfrastructure/images/{imageName}/versions" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if imageName == "" { + return nil, errors.New("parameter imageName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{imageName}", url.PathEscape(imageName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260417Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByImageHandleResponse handles the ListByImage response. +func (client *ImageVersionsClient) listByImageHandleResponse(resp *http.Response) (ImageVersionsClientListByImageResponse, error) { + result := ImageVersionsClientListByImageResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ImageVersionListResult); err != nil { + return ImageVersionsClientListByImageResponse{}, err + } + return result, nil +} diff --git a/test/local/armdevopsinfrastructure/zz_interfaces.go b/test/local/armdevopsinfrastructure/zz_interfaces.go new file mode 100644 index 000000000000..741df79d72aa --- /dev/null +++ b/test/local/armdevopsinfrastructure/zz_interfaces.go @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdevopsinfrastructure + +// AgentProfileClassification provides polymorphic access to related types. +// Call the interface's GetAgentProfile() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *AgentProfile, *Stateful, *StatelessAgentProfile +type AgentProfileClassification interface { + // GetAgentProfile returns the AgentProfile content of the underlying type. + GetAgentProfile() *AgentProfile +} + +// FabricProfileClassification provides polymorphic access to related types. +// Call the interface's GetFabricProfile() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *FabricProfile, *VmssFabricProfile +type FabricProfileClassification interface { + // GetFabricProfile returns the FabricProfile content of the underlying type. + GetFabricProfile() *FabricProfile +} + +// OrganizationProfileClassification provides polymorphic access to related types. +// Call the interface's GetOrganizationProfile() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *AzureDevOpsOrganizationProfile, *GitHubOrganizationProfile, *OrganizationProfile +type OrganizationProfileClassification interface { + // GetOrganizationProfile returns the OrganizationProfile content of the underlying type. + GetOrganizationProfile() *OrganizationProfile +} + +// ResourcePredictionsProfileClassification provides polymorphic access to related types. +// Call the interface's GetResourcePredictionsProfile() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *AutomaticResourcePredictionsProfile, *ManualResourcePredictionsProfile, *ResourcePredictionsProfile +type ResourcePredictionsProfileClassification interface { + // GetResourcePredictionsProfile returns the ResourcePredictionsProfile content of the underlying type. + GetResourcePredictionsProfile() *ResourcePredictionsProfile +} diff --git a/test/local/armdevopsinfrastructure/zz_models.go b/test/local/armdevopsinfrastructure/zz_models.go new file mode 100644 index 000000000000..91ef7143a8a8 --- /dev/null +++ b/test/local/armdevopsinfrastructure/zz_models.go @@ -0,0 +1,786 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdevopsinfrastructure + +import "time" + +// AgentProfile - The agent profile of the machines in the pool. +type AgentProfile struct { + // REQUIRED; Discriminator property for AgentProfile. + Kind *string + + // Defines pool buffer/stand-by agents. + ResourcePredictions *ResourcePredictions + + // Defines how the pool buffer/stand-by agents is provided. + ResourcePredictionsProfile ResourcePredictionsProfileClassification +} + +// GetAgentProfile implements the AgentProfileClassification interface for type AgentProfile. +func (a *AgentProfile) GetAgentProfile() *AgentProfile { return a } + +// AutomaticResourcePredictionsProfile - The stand-by agent scheme is determined based on historical demand. +type AutomaticResourcePredictionsProfile struct { + // CONSTANT; The stand-by agent scheme is determined based on historical demand. + // Field has constant value ResourcePredictionsProfileTypeAutomatic, any specified value is ignored. + Kind *ResourcePredictionsProfileType + + // Determines the balance between cost and performance. + PredictionPreference *PredictionPreference +} + +// GetResourcePredictionsProfile implements the ResourcePredictionsProfileClassification interface for type AutomaticResourcePredictionsProfile. +func (a *AutomaticResourcePredictionsProfile) GetResourcePredictionsProfile() *ResourcePredictionsProfile { + return &ResourcePredictionsProfile{ + Kind: a.Kind, + } +} + +// AzureDevOpsOrganizationProfile - Azure DevOps organization profile +type AzureDevOpsOrganizationProfile struct { + // CONSTANT; Azure DevOps organization profile + // Field has constant value "AzureDevOps", any specified value is ignored. + Kind *string + + // REQUIRED; The list of Azure DevOps organizations the pool should be present in. + Organizations []*Organization + + // An alias to reference the Azure DevOps pool name. + Alias *string + + // The type of permission which determines which accounts are admins on the Azure DevOps pool. + PermissionProfile *AzureDevOpsPermissionProfile +} + +// GetOrganizationProfile implements the OrganizationProfileClassification interface for type AzureDevOpsOrganizationProfile. +func (a *AzureDevOpsOrganizationProfile) GetOrganizationProfile() *OrganizationProfile { + return &OrganizationProfile{ + Kind: a.Kind, + } +} + +// AzureDevOpsPermissionProfile - Defines the type of Azure DevOps pool permission. +type AzureDevOpsPermissionProfile struct { + // REQUIRED; Determines who has admin permissions to the Azure DevOps pool. + Kind *AzureDevOpsPermissionType + + // Group email addresses + Groups []*string + + // User email addresses + Users []*string +} + +// CheckNameAvailability - The parameters used to check the availability of a resource. +type CheckNameAvailability struct { + // REQUIRED; The name of the resource. + Name *string + + // REQUIRED; The type of resource that is used as the scope of the availability check. + Type *ResourceType +} + +// CheckNameAvailabilityResult - The CheckNameAvailability operation response. +type CheckNameAvailabilityResult struct { + // REQUIRED; Availability status of the name. + Available *AvailabilityStatus + + // REQUIRED; A message explaining why the name is unavailable. Will be null if the name is available. + Message *string + + // REQUIRED; The name whose availability was checked. + Name *string + + // REQUIRED; The reason code explaining why the name is unavailable. Will be null if the name is available. + Reason *CheckNameAvailabilityReason +} + +// DataDisk - The data disk of the VMSS. +type DataDisk struct { + // The type of caching to be enabled for the data disks. The default value for caching is readwrite. For information about + // the caching options see: https://blogs.msdn.microsoft.com/windowsazurestorage/2012/06/27/exploring-windows-azure-drives-disks-and-images/. + Caching *CachingType + + // The initial disk size in gigabytes. + DiskSizeGiB *int32 + + // The drive letter for the empty data disk. If not specified, it will be the first available letter. + DriveLetter *string + + // The storage Account type to be used for the data disk. If omitted, the default is "standard_lrs". + StorageAccountType *StorageAccountType +} + +// DeleteResourcesDetails - Request body for deleting many resources by their IDs. +type DeleteResourcesDetails struct { + // REQUIRED; List of resource IDs to delete. + ResourceIDs []*string +} + +// DevOpsAzureSKU - The Azure SKU of the machines in the pool. +type DevOpsAzureSKU struct { + // REQUIRED; The Azure SKU name of the machines in the pool. + Name *string + + // The mount path for the NVMe striped volume on Linux (e.g., '/mnt/azure_nvme_temp'). Defaults to '/mnt/azure_nvme_temp' + // when not specified. + LinuxNvmePath *string + + // The drive letter for the NVMe striped volume on Windows (e.g., 'N'). Defaults to 'N' when not specified. + WindowsNvmeDrive *string +} + +// FabricProfile - Defines the type of fabric the agent will run on. +type FabricProfile struct { + // REQUIRED; Discriminator property for FabricProfile. + Kind *string +} + +// GetFabricProfile implements the FabricProfileClassification interface for type FabricProfile. +func (f *FabricProfile) GetFabricProfile() *FabricProfile { return f } + +// GitHubOrganization - Defines a GitHub organization +type GitHubOrganization struct { + // REQUIRED; The GitHub organization URL in which the pool should be created. + URL *string + + // Optional list of repositories in which the pool should be created. + Repositories []*string +} + +// GitHubOrganizationProfile - GitHub organization profile +type GitHubOrganizationProfile struct { + // CONSTANT; GitHub organization profile + // Field has constant value "GitHub", any specified value is ignored. + Kind *string + + // REQUIRED; The list of GitHub organizations/repositories the pool should be present in. + Organizations []*GitHubOrganization +} + +// GetOrganizationProfile implements the OrganizationProfileClassification interface for type GitHubOrganizationProfile. +func (g *GitHubOrganizationProfile) GetOrganizationProfile() *OrganizationProfile { + return &OrganizationProfile{ + Kind: g.Kind, + } +} + +// ImageVersion - An image version object +type ImageVersion struct { + // The resource-specific properties for this resource. + Properties *ImageVersionProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ImageVersionListResult - The response of a ImageVersion list operation. +type ImageVersionListResult struct { + // REQUIRED; The ImageVersion items on this page + Value []*ImageVersion + + // The link to the next page of items + NextLink *string +} + +// ImageVersionProperties - Details of the ImageVersionProperties. +type ImageVersionProperties struct { + // REQUIRED; Version of the image. + Version *string +} + +// ManagedServiceIdentity - Managed service identity (system assigned and/or user assigned identities) +type ManagedServiceIdentity struct { + // REQUIRED; The type of managed identity assigned to this resource. + Type *ManagedServiceIdentityType + + // The identities assigned to this resource by the user. + UserAssignedIdentities map[string]*UserAssignedIdentity + + // READ-ONLY; The service principal ID of the system assigned identity. This property will only be provided for a system assigned + // identity. + PrincipalID *string + + // READ-ONLY; The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + TenantID *string +} + +// ManualResourcePredictionsProfile - Customer provides the stand-by agent scheme. +type ManualResourcePredictionsProfile struct { + // CONSTANT; Customer provides the stand-by agent scheme. + // Field has constant value ResourcePredictionsProfileTypeManual, any specified value is ignored. + Kind *ResourcePredictionsProfileType +} + +// GetResourcePredictionsProfile implements the ResourcePredictionsProfileClassification interface for type ManualResourcePredictionsProfile. +func (m *ManualResourcePredictionsProfile) GetResourcePredictionsProfile() *ResourcePredictionsProfile { + return &ResourcePredictionsProfile{ + Kind: m.Kind, + } +} + +// NetworkProfile - The network profile of the machines in the pool. +type NetworkProfile struct { + // The number of static public IP addresses for outgoing connections assigned to the pool. + StaticIPAddressCount *int32 + + // The subnet id on which to put all machines created in the pool. + SubnetID *string + + // READ-ONLY; Read only. The list of static public IP addresses for outgoing connections assigned to the pool. + IPAddresses []*string +} + +// Operation - REST API Operation +// +// Details of a REST API operation, returned from the Resource Provider Operations API +type Operation struct { + // Localized display information for this particular operation. + Display *OperationDisplay + + // READ-ONLY; Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + ActionType *ActionType + + // READ-ONLY; Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure + // Resource Manager/control-plane operations. + IsDataAction *bool + + // READ-ONLY; The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + // "Microsoft.Compute/virtualMachines/capture/action" + Name *string + + // READ-ONLY; The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default + // value is "user,system" + Origin *Origin +} + +// OperationDisplay - Localized display information for an operation. +type OperationDisplay struct { + // READ-ONLY; The short, localized friendly description of the operation; suitable for tool tips and detailed views. + Description *string + + // READ-ONLY; The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual + // Machine", "Restart Virtual Machine". + Operation *string + + // READ-ONLY; The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft + // Compute". + Provider *string + + // READ-ONLY; The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job + // Schedule Collections". + Resource *string +} + +// OperationListResult - A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to +// get the next set of results. +type OperationListResult struct { + // REQUIRED; The Operation items on this page + Value []*Operation + + // The link to the next page of items + NextLink *string +} + +// Organization - Defines an Azure DevOps organization. +type Organization struct { + // REQUIRED; The Azure DevOps organization URL in which the pool should be created. + URL *string + + // An alias to reference the Azure DevOps pool name. + Alias *string + + // Determines if the pool should have open access to all projects in this organization. + OpenAccess *bool + + // How many machines can be created at maximum in this organization out of the maximumConcurrency of the pool. + Parallelism *int32 + + // Optional list of projects in which the pool should be created. + Projects []*string +} + +// OrganizationProfile - Defines the organization in which the pool will be used. +type OrganizationProfile struct { + // REQUIRED; Discriminator property for OrganizationProfile. + Kind *string +} + +// GetOrganizationProfile implements the OrganizationProfileClassification interface for type OrganizationProfile. +func (o *OrganizationProfile) GetOrganizationProfile() *OrganizationProfile { return o } + +// OsProfile - The OS profile of the machines in the pool. +type OsProfile struct { + // Determines how the service should be run. By default, this will be set to Service. + LogonType *LogonType + + // The secret management settings of the machines in the pool. + SecretsManagementSettings *SecretsManagementSettings +} + +// PagedQuota - Paged collection of Quota items +type PagedQuota struct { + // REQUIRED; The Quota items on this page + Value []*Quota + + // The link to the next page of items + NextLink *string +} + +// Pool - Concrete tracked resource types can be created by aliasing this type using a specific property type. +type Pool struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The managed service identities assigned to this resource. + Identity *ManagedServiceIdentity + + // The resource-specific properties for this resource. + Properties *PoolProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// PoolImage - The VM image of the machines in the pool. +type PoolImage struct { + // List of aliases to reference the image by. + Aliases []*string + + // The percentage of the buffer to be allocated to this image. + Buffer *string + + // The ephemeral type of the image. + EphemeralType *EphemeralType + + // The resource id of the image. + ResourceID *string + + // The image to use from a well-known set of images made available to customers. + WellKnownImageName *string + + // READ-ONLY; Read only. Determines if the image is ephemeral. + IsEphemeral *bool +} + +// PoolListResult - The response of a Pool list operation. +type PoolListResult struct { + // REQUIRED; The Pool items on this page + Value []*Pool + + // The link to the next page of items + NextLink *string +} + +// PoolProperties - Pool properties +type PoolProperties struct { + // REQUIRED; Defines how the machine will be handled once it executed a job. + AgentProfile AgentProfileClassification + + // REQUIRED; The resource id of the DevCenter Project the pool belongs to. + DevCenterProjectResourceID *string + + // REQUIRED; Defines the type of fabric the agent will run on. + FabricProfile FabricProfileClassification + + // REQUIRED; Defines how many resources can there be created at any given time. + MaximumConcurrency *int32 + + // REQUIRED; Defines the organization in which the pool will be used. + OrganizationProfile OrganizationProfileClassification + + // The status of the current operation. + ProvisioningState *ProvisioningState + + // The runtime configuration of the pool. + RuntimeConfiguration *RuntimeConfiguration +} + +// PoolUpdate - The type used for update operations of the Pool. +type PoolUpdate struct { + // The managed service identities assigned to this resource. + Identity *ManagedServiceIdentity + + // The resource-specific properties for this resource. + Properties *PoolUpdateProperties + + // Resource tags. + Tags map[string]*string +} + +// PoolUpdateProperties - The updatable properties of the Pool. +type PoolUpdateProperties struct { + // Defines how the machine will be handled once it executed a job. + AgentProfile AgentProfileClassification + + // The resource id of the DevCenter Project the pool belongs to. + DevCenterProjectResourceID *string + + // Defines the type of fabric the agent will run on. + FabricProfile FabricProfileClassification + + // Defines how many resources can there be created at any given time. + MaximumConcurrency *int32 + + // Defines the organization in which the pool will be used. + OrganizationProfile OrganizationProfileClassification + + // The status of the current operation. + ProvisioningState *ProvisioningState + + // The runtime configuration of the pool. + RuntimeConfiguration *RuntimeConfiguration +} + +// Quota - Describes Resource Quota +type Quota struct { + // REQUIRED; The current usage of the resource. + CurrentValue *int64 + + // REQUIRED; Fully qualified ARM resource id + ID *string + + // REQUIRED; The maximum permitted usage of the resource. + Limit *int64 + + // REQUIRED; The unit of usage measurement. + Unit *string + + // READ-ONLY; The name of the quota. + Name *QuotaName +} + +// QuotaName - The Quota Names +type QuotaName struct { + // The localized name of the resource. + LocalizedValue *string + + // The name of the resource. + Value *string +} + +// ResourceDetailsObject - A ResourceDetailsObject +type ResourceDetailsObject struct { + // The resource-specific properties for this resource. + Properties *ResourceDetailsObjectProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ResourceDetailsObjectListResult - The response of a ResourceDetailsObject list operation. +type ResourceDetailsObjectListResult struct { + // REQUIRED; The ResourceDetailsObject items on this page + Value []*ResourceDetailsObject + + // The link to the next page of items + NextLink *string +} + +// ResourceDetailsObjectProperties - Details of the ResourceDetailsObject. +type ResourceDetailsObjectProperties struct { + // REQUIRED; The image name of the resource. + Image *string + + // REQUIRED; The version of the image running on the resource. + ImageVersion *string + + // REQUIRED; The status of the resource. + Status *ResourceStatus +} + +// ResourcePredictions - Defines pool buffer. +type ResourcePredictions struct { +} + +// ResourcePredictionsProfile - Determines how the stand-by scheme should be provided. +type ResourcePredictionsProfile struct { + // REQUIRED; Determines how the stand-by scheme should be provided. + Kind *ResourcePredictionsProfileType +} + +// GetResourcePredictionsProfile implements the ResourcePredictionsProfileClassification interface for type ResourcePredictionsProfile. +func (r *ResourcePredictionsProfile) GetResourcePredictionsProfile() *ResourcePredictionsProfile { + return r +} + +// ResourceSKU - A ResourceSku +type ResourceSKU struct { + // The resource-specific properties for this resource. + Properties *ResourceSKUProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ResourceSKUCapabilities - Describes The SKU capabilities object. +type ResourceSKUCapabilities struct { + // REQUIRED; The name of the SKU capability. + Name *string + + // REQUIRED; The value of the SKU capability. + Value *string +} + +// ResourceSKUListResult - The response of a ResourceSku list operation. +type ResourceSKUListResult struct { + // REQUIRED; The ResourceSku items on this page + Value []*ResourceSKU + + // The link to the next page of items + NextLink *string +} + +// ResourceSKULocationInfo - Describes an available Compute SKU Location Information. +type ResourceSKULocationInfo struct { + // REQUIRED; Location of the SKU + Location *string + + // REQUIRED; Gets details of capabilities available to a SKU in specific zones. + ZoneDetails []*ResourceSKUZoneDetails + + // REQUIRED; List of availability zones where the SKU is supported. + Zones []*string +} + +// ResourceSKUProperties - Properties of a ResourceSku +type ResourceSKUProperties struct { + // REQUIRED; Name value pairs to describe the capability. + Capabilities []*ResourceSKUCapabilities + + // REQUIRED; The family of the SKU. + Family *string + + // REQUIRED; A list of locations and availability zones in those locations where the SKU is available + LocationInfo []*ResourceSKULocationInfo + + // REQUIRED; The set of locations that the SKU is available. + Locations []*string + + // REQUIRED; The type of resource the SKU applies to. + ResourceType *string + + // REQUIRED; The restrictions of the SKU. + Restrictions []*ResourceSKURestrictions + + // REQUIRED; The size of the SKU. + Size *string + + // REQUIRED; The tier of virtual machines in a scale set + Tier *string +} + +// ResourceSKURestrictionInfo - Describes an available Compute SKU Restriction Information. +type ResourceSKURestrictionInfo struct { + // Locations where the SKU is restricted + Locations []*string + + // List of availability zones where the SKU is restricted. + Zones []*string +} + +// ResourceSKURestrictions - The restrictions of the SKU. +type ResourceSKURestrictions struct { + // REQUIRED; The information about the restriction where the SKU cannot be used. + RestrictionInfo *ResourceSKURestrictionInfo + + // REQUIRED; The value of restrictions. If the restriction type is set to location. This would be different locations where + // the SKU is restricted. + Values []*string + + // the reason for restriction. + ReasonCode *ResourceSKURestrictionsReasonCode + + // the type of restrictions. + Type *ResourceSKURestrictionsType +} + +// ResourceSKUZoneDetails - Describes The zonal capabilities of a SKU. +type ResourceSKUZoneDetails struct { + // REQUIRED; A list of capabilities that are available for the SKU in the specified list of zones. + Capabilities []*ResourceSKUCapabilities + + // REQUIRED; Gets the set of zones that the SKU is available in with the specified capabilities. + Name []*string +} + +// RuntimeConfiguration - The runtime configuration of the pool. +type RuntimeConfiguration struct { + // The target work folder of the task agent on the machine. + WorkFolder *string +} + +// SecretsManagementSettings - The secret management settings of the machines in the pool. +type SecretsManagementSettings struct { + // REQUIRED; Defines if the key of the certificates should be exportable. + KeyExportable *bool + + // REQUIRED; The list of certificates to install on all machines in the pool. + ObservedCertificates []*string + + // Where to store certificates on the machine. + CertificateStoreLocation *string + + // Name of the certificate store to use on the machine, currently 'My' and 'Root' are supported. + CertificateStoreName *CertificateStoreNameOption +} + +// Stateful profile meaning that the machines will be returned to the pool after running a job. +type Stateful struct { + // CONSTANT; Stateful profile meaning that the machines will be returned to the pool after running a job. + // Field has constant value "Stateful", any specified value is ignored. + Kind *string + + // How long should the machine be kept around after it ran a workload when there are no stand-by agents. The maximum is one + // week. + GracePeriodTimeSpan *string + + // How long should stateful machines be kept around. The maximum is one week. + MaxAgentLifetime *string + + // Defines pool buffer/stand-by agents. + ResourcePredictions *ResourcePredictions + + // Defines how the pool buffer/stand-by agents is provided. + ResourcePredictionsProfile ResourcePredictionsProfileClassification +} + +// GetAgentProfile implements the AgentProfileClassification interface for type Stateful. +func (s *Stateful) GetAgentProfile() *AgentProfile { + return &AgentProfile{ + Kind: s.Kind, + ResourcePredictions: s.ResourcePredictions, + ResourcePredictionsProfile: s.ResourcePredictionsProfile, + } +} + +// StatelessAgentProfile - Stateless profile meaning that the machines will be cleaned up after running a job. +type StatelessAgentProfile struct { + // CONSTANT; Stateless profile meaning that the machines will be cleaned up after running a job. + // Field has constant value "Stateless", any specified value is ignored. + Kind *string + + // Defines pool buffer/stand-by agents. + ResourcePredictions *ResourcePredictions + + // Defines how the pool buffer/stand-by agents is provided. + ResourcePredictionsProfile ResourcePredictionsProfileClassification +} + +// GetAgentProfile implements the AgentProfileClassification interface for type StatelessAgentProfile. +func (s *StatelessAgentProfile) GetAgentProfile() *AgentProfile { + return &AgentProfile{ + Kind: s.Kind, + ResourcePredictions: s.ResourcePredictions, + ResourcePredictionsProfile: s.ResourcePredictionsProfile, + } +} + +// StorageProfile - The storage profile of the VMSS. +type StorageProfile struct { + // A list of empty data disks to attach. + DataDisks []*DataDisk + + // The Azure SKU name of the machines in the pool. + OSDiskStorageAccountType *OsDiskStorageAccountType +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time + + // The identity that created the resource. + CreatedBy *string + + // The type of identity that created the resource. + CreatedByType *CreatedByType + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time + + // The identity that last modified the resource. + LastModifiedBy *string + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType +} + +// UserAssignedIdentity - User assigned identity properties +type UserAssignedIdentity struct { + // READ-ONLY; The client ID of the assigned identity. + ClientID *string + + // READ-ONLY; The principal ID of the assigned identity. + PrincipalID *string +} + +// VmssFabricProfile - The agents will run on Virtual Machine Scale Sets. +type VmssFabricProfile struct { + // REQUIRED; The VM images of the machines in the pool. + Images []*PoolImage + + // CONSTANT; Virtual Machine Scale Sets + // Field has constant value "Vmss", any specified value is ignored. + Kind *string + + // REQUIRED; The Azure SKU of the machines in the pool. + SKU *DevOpsAzureSKU + + // The network profile of the machines in the pool. + NetworkProfile *NetworkProfile + + // The OS profile of the machines in the pool. + OSProfile *OsProfile + + // The storage profile of the machines in the pool. + StorageProfile *StorageProfile +} + +// GetFabricProfile implements the FabricProfileClassification interface for type VmssFabricProfile. +func (v *VmssFabricProfile) GetFabricProfile() *FabricProfile { + return &FabricProfile{ + Kind: v.Kind, + } +} diff --git a/test/local/armdevopsinfrastructure/zz_models_serde.go b/test/local/armdevopsinfrastructure/zz_models_serde.go new file mode 100644 index 000000000000..738cf71651e1 --- /dev/null +++ b/test/local/armdevopsinfrastructure/zz_models_serde.go @@ -0,0 +1,1985 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdevopsinfrastructure + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type AgentProfile. +func (a AgentProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "kind", a.Kind) + populate(objectMap, "resourcePredictions", a.ResourcePredictions) + populate(objectMap, "resourcePredictionsProfile", a.ResourcePredictionsProfile) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AgentProfile. +func (a *AgentProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &a.Kind) + delete(rawMsg, key) + case "resourcePredictions": + err = unpopulate(val, "ResourcePredictions", &a.ResourcePredictions) + delete(rawMsg, key) + case "resourcePredictionsProfile": + a.ResourcePredictionsProfile, err = unmarshalResourcePredictionsProfileClassification(val) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutomaticResourcePredictionsProfile. +func (a AutomaticResourcePredictionsProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["kind"] = ResourcePredictionsProfileTypeAutomatic + populate(objectMap, "predictionPreference", a.PredictionPreference) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutomaticResourcePredictionsProfile. +func (a *AutomaticResourcePredictionsProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &a.Kind) + delete(rawMsg, key) + case "predictionPreference": + err = unpopulate(val, "PredictionPreference", &a.PredictionPreference) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AzureDevOpsOrganizationProfile. +func (a AzureDevOpsOrganizationProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "alias", a.Alias) + objectMap["kind"] = "AzureDevOps" + populate(objectMap, "organizations", a.Organizations) + populate(objectMap, "permissionProfile", a.PermissionProfile) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureDevOpsOrganizationProfile. +func (a *AzureDevOpsOrganizationProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "alias": + err = unpopulate(val, "Alias", &a.Alias) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &a.Kind) + delete(rawMsg, key) + case "organizations": + err = unpopulate(val, "Organizations", &a.Organizations) + delete(rawMsg, key) + case "permissionProfile": + err = unpopulate(val, "PermissionProfile", &a.PermissionProfile) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AzureDevOpsPermissionProfile. +func (a AzureDevOpsPermissionProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "groups", a.Groups) + populate(objectMap, "kind", a.Kind) + populate(objectMap, "users", a.Users) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureDevOpsPermissionProfile. +func (a *AzureDevOpsPermissionProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "groups": + err = unpopulate(val, "Groups", &a.Groups) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &a.Kind) + delete(rawMsg, key) + case "users": + err = unpopulate(val, "Users", &a.Users) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CheckNameAvailability. +func (c CheckNameAvailability) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", c.Name) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CheckNameAvailability. +func (c *CheckNameAvailability) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CheckNameAvailabilityResult. +func (c CheckNameAvailabilityResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "available", c.Available) + populate(objectMap, "message", c.Message) + populate(objectMap, "name", c.Name) + populate(objectMap, "reason", c.Reason) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CheckNameAvailabilityResult. +func (c *CheckNameAvailabilityResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "available": + err = unpopulate(val, "Available", &c.Available) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &c.Message) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "reason": + err = unpopulate(val, "Reason", &c.Reason) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DataDisk. +func (d DataDisk) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "caching", d.Caching) + populate(objectMap, "diskSizeGiB", d.DiskSizeGiB) + populate(objectMap, "driveLetter", d.DriveLetter) + populate(objectMap, "storageAccountType", d.StorageAccountType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DataDisk. +func (d *DataDisk) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "caching": + err = unpopulate(val, "Caching", &d.Caching) + delete(rawMsg, key) + case "diskSizeGiB": + err = unpopulate(val, "DiskSizeGiB", &d.DiskSizeGiB) + delete(rawMsg, key) + case "driveLetter": + err = unpopulate(val, "DriveLetter", &d.DriveLetter) + delete(rawMsg, key) + case "storageAccountType": + err = unpopulate(val, "StorageAccountType", &d.StorageAccountType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeleteResourcesDetails. +func (d DeleteResourcesDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "resourceIds", d.ResourceIDs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeleteResourcesDetails. +func (d *DeleteResourcesDetails) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "resourceIds": + err = unpopulate(val, "ResourceIDs", &d.ResourceIDs) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DevOpsAzureSKU. +func (d DevOpsAzureSKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "linuxNvmePath", d.LinuxNvmePath) + populate(objectMap, "name", d.Name) + populate(objectMap, "windowsNvmeDrive", d.WindowsNvmeDrive) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DevOpsAzureSKU. +func (d *DevOpsAzureSKU) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "linuxNvmePath": + err = unpopulate(val, "LinuxNvmePath", &d.LinuxNvmePath) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "windowsNvmeDrive": + err = unpopulate(val, "WindowsNvmeDrive", &d.WindowsNvmeDrive) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FabricProfile. +func (f FabricProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "kind", f.Kind) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FabricProfile. +func (f *FabricProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &f.Kind) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type GitHubOrganization. +func (g GitHubOrganization) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "repositories", g.Repositories) + populate(objectMap, "url", g.URL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GitHubOrganization. +func (g *GitHubOrganization) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "repositories": + err = unpopulate(val, "Repositories", &g.Repositories) + delete(rawMsg, key) + case "url": + err = unpopulate(val, "URL", &g.URL) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type GitHubOrganizationProfile. +func (g GitHubOrganizationProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["kind"] = "GitHub" + populate(objectMap, "organizations", g.Organizations) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GitHubOrganizationProfile. +func (g *GitHubOrganizationProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &g.Kind) + delete(rawMsg, key) + case "organizations": + err = unpopulate(val, "Organizations", &g.Organizations) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ImageVersion. +func (i ImageVersion) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", i.ID) + populate(objectMap, "name", i.Name) + populate(objectMap, "properties", i.Properties) + populate(objectMap, "systemData", i.SystemData) + populate(objectMap, "type", i.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImageVersion. +func (i *ImageVersion) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &i.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &i.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &i.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &i.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &i.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ImageVersionListResult. +func (i ImageVersionListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", i.NextLink) + populate(objectMap, "value", i.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImageVersionListResult. +func (i *ImageVersionListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &i.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &i.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ImageVersionProperties. +func (i ImageVersionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "version", i.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImageVersionProperties. +func (i *ImageVersionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "version": + err = unpopulate(val, "Version", &i.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedServiceIdentity. +func (m ManagedServiceIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "principalId", m.PrincipalID) + populate(objectMap, "tenantId", m.TenantID) + populate(objectMap, "type", m.Type) + populate(objectMap, "userAssignedIdentities", m.UserAssignedIdentities) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedServiceIdentity. +func (m *ManagedServiceIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "principalId": + err = unpopulate(val, "PrincipalID", &m.PrincipalID) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &m.TenantID) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + case "userAssignedIdentities": + err = unpopulate(val, "UserAssignedIdentities", &m.UserAssignedIdentities) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManualResourcePredictionsProfile. +func (m ManualResourcePredictionsProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["kind"] = ResourcePredictionsProfileTypeManual + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManualResourcePredictionsProfile. +func (m *ManualResourcePredictionsProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &m.Kind) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkProfile. +func (n NetworkProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ipAddresses", n.IPAddresses) + populate(objectMap, "staticIpAddressCount", n.StaticIPAddressCount) + populate(objectMap, "subnetId", n.SubnetID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkProfile. +func (n *NetworkProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "ipAddresses": + err = unpopulate(val, "IPAddresses", &n.IPAddresses) + delete(rawMsg, key) + case "staticIpAddressCount": + err = unpopulate(val, "StaticIPAddressCount", &n.StaticIPAddressCount) + delete(rawMsg, key) + case "subnetId": + err = unpopulate(val, "SubnetID", &n.SubnetID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Operation. +func (o Operation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionType", o.ActionType) + populate(objectMap, "display", o.Display) + populate(objectMap, "isDataAction", o.IsDataAction) + populate(objectMap, "name", o.Name) + populate(objectMap, "origin", o.Origin) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Operation. +func (o *Operation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionType": + err = unpopulate(val, "ActionType", &o.ActionType) + delete(rawMsg, key) + case "display": + err = unpopulate(val, "Display", &o.Display) + delete(rawMsg, key) + case "isDataAction": + err = unpopulate(val, "IsDataAction", &o.IsDataAction) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "origin": + err = unpopulate(val, "Origin", &o.Origin) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationDisplay. +func (o OperationDisplay) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", o.Description) + populate(objectMap, "operation", o.Operation) + populate(objectMap, "provider", o.Provider) + populate(objectMap, "resource", o.Resource) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationDisplay. +func (o *OperationDisplay) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &o.Description) + delete(rawMsg, key) + case "operation": + err = unpopulate(val, "Operation", &o.Operation) + delete(rawMsg, key) + case "provider": + err = unpopulate(val, "Provider", &o.Provider) + delete(rawMsg, key) + case "resource": + err = unpopulate(val, "Resource", &o.Resource) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationListResult. +func (o *OperationListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &o.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Organization. +func (o Organization) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "alias", o.Alias) + populate(objectMap, "openAccess", o.OpenAccess) + populate(objectMap, "parallelism", o.Parallelism) + populate(objectMap, "projects", o.Projects) + populate(objectMap, "url", o.URL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Organization. +func (o *Organization) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "alias": + err = unpopulate(val, "Alias", &o.Alias) + delete(rawMsg, key) + case "openAccess": + err = unpopulate(val, "OpenAccess", &o.OpenAccess) + delete(rawMsg, key) + case "parallelism": + err = unpopulate(val, "Parallelism", &o.Parallelism) + delete(rawMsg, key) + case "projects": + err = unpopulate(val, "Projects", &o.Projects) + delete(rawMsg, key) + case "url": + err = unpopulate(val, "URL", &o.URL) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OrganizationProfile. +func (o OrganizationProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "kind", o.Kind) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OrganizationProfile. +func (o *OrganizationProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &o.Kind) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OsProfile. +func (o OsProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "logonType", o.LogonType) + populate(objectMap, "secretsManagementSettings", o.SecretsManagementSettings) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OsProfile. +func (o *OsProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "logonType": + err = unpopulate(val, "LogonType", &o.LogonType) + delete(rawMsg, key) + case "secretsManagementSettings": + err = unpopulate(val, "SecretsManagementSettings", &o.SecretsManagementSettings) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PagedQuota. +func (p PagedQuota) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", p.NextLink) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PagedQuota. +func (p *PagedQuota) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &p.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Pool. +func (p Pool) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", p.ID) + populate(objectMap, "identity", p.Identity) + populate(objectMap, "location", p.Location) + populate(objectMap, "name", p.Name) + populate(objectMap, "properties", p.Properties) + populate(objectMap, "systemData", p.SystemData) + populate(objectMap, "tags", p.Tags) + populate(objectMap, "type", p.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Pool. +func (p *Pool) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &p.Identity) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &p.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &p.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &p.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &p.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &p.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PoolImage. +func (p PoolImage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "aliases", p.Aliases) + populate(objectMap, "buffer", p.Buffer) + populate(objectMap, "ephemeralType", p.EphemeralType) + populate(objectMap, "isEphemeral", p.IsEphemeral) + populate(objectMap, "resourceId", p.ResourceID) + populate(objectMap, "wellKnownImageName", p.WellKnownImageName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PoolImage. +func (p *PoolImage) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "aliases": + err = unpopulate(val, "Aliases", &p.Aliases) + delete(rawMsg, key) + case "buffer": + err = unpopulate(val, "Buffer", &p.Buffer) + delete(rawMsg, key) + case "ephemeralType": + err = unpopulate(val, "EphemeralType", &p.EphemeralType) + delete(rawMsg, key) + case "isEphemeral": + err = unpopulate(val, "IsEphemeral", &p.IsEphemeral) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &p.ResourceID) + delete(rawMsg, key) + case "wellKnownImageName": + err = unpopulate(val, "WellKnownImageName", &p.WellKnownImageName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PoolListResult. +func (p PoolListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", p.NextLink) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PoolListResult. +func (p *PoolListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &p.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PoolProperties. +func (p PoolProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "agentProfile", p.AgentProfile) + populate(objectMap, "devCenterProjectResourceId", p.DevCenterProjectResourceID) + populate(objectMap, "fabricProfile", p.FabricProfile) + populate(objectMap, "maximumConcurrency", p.MaximumConcurrency) + populate(objectMap, "organizationProfile", p.OrganizationProfile) + populate(objectMap, "provisioningState", p.ProvisioningState) + populate(objectMap, "runtimeConfiguration", p.RuntimeConfiguration) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PoolProperties. +func (p *PoolProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "agentProfile": + p.AgentProfile, err = unmarshalAgentProfileClassification(val) + delete(rawMsg, key) + case "devCenterProjectResourceId": + err = unpopulate(val, "DevCenterProjectResourceID", &p.DevCenterProjectResourceID) + delete(rawMsg, key) + case "fabricProfile": + p.FabricProfile, err = unmarshalFabricProfileClassification(val) + delete(rawMsg, key) + case "maximumConcurrency": + err = unpopulate(val, "MaximumConcurrency", &p.MaximumConcurrency) + delete(rawMsg, key) + case "organizationProfile": + p.OrganizationProfile, err = unmarshalOrganizationProfileClassification(val) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + case "runtimeConfiguration": + err = unpopulate(val, "RuntimeConfiguration", &p.RuntimeConfiguration) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PoolUpdate. +func (p PoolUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identity", p.Identity) + populate(objectMap, "properties", p.Properties) + populate(objectMap, "tags", p.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PoolUpdate. +func (p *PoolUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "identity": + err = unpopulate(val, "Identity", &p.Identity) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &p.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &p.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PoolUpdateProperties. +func (p PoolUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "agentProfile", p.AgentProfile) + populate(objectMap, "devCenterProjectResourceId", p.DevCenterProjectResourceID) + populate(objectMap, "fabricProfile", p.FabricProfile) + populate(objectMap, "maximumConcurrency", p.MaximumConcurrency) + populate(objectMap, "organizationProfile", p.OrganizationProfile) + populate(objectMap, "provisioningState", p.ProvisioningState) + populate(objectMap, "runtimeConfiguration", p.RuntimeConfiguration) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PoolUpdateProperties. +func (p *PoolUpdateProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "agentProfile": + p.AgentProfile, err = unmarshalAgentProfileClassification(val) + delete(rawMsg, key) + case "devCenterProjectResourceId": + err = unpopulate(val, "DevCenterProjectResourceID", &p.DevCenterProjectResourceID) + delete(rawMsg, key) + case "fabricProfile": + p.FabricProfile, err = unmarshalFabricProfileClassification(val) + delete(rawMsg, key) + case "maximumConcurrency": + err = unpopulate(val, "MaximumConcurrency", &p.MaximumConcurrency) + delete(rawMsg, key) + case "organizationProfile": + p.OrganizationProfile, err = unmarshalOrganizationProfileClassification(val) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + case "runtimeConfiguration": + err = unpopulate(val, "RuntimeConfiguration", &p.RuntimeConfiguration) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Quota. +func (q Quota) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "currentValue", q.CurrentValue) + populate(objectMap, "id", q.ID) + populate(objectMap, "limit", q.Limit) + populate(objectMap, "name", q.Name) + populate(objectMap, "unit", q.Unit) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Quota. +func (q *Quota) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "currentValue": + err = unpopulate(val, "CurrentValue", &q.CurrentValue) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &q.ID) + delete(rawMsg, key) + case "limit": + err = unpopulate(val, "Limit", &q.Limit) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &q.Name) + delete(rawMsg, key) + case "unit": + err = unpopulate(val, "Unit", &q.Unit) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type QuotaName. +func (q QuotaName) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "localizedValue", q.LocalizedValue) + populate(objectMap, "value", q.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type QuotaName. +func (q *QuotaName) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "localizedValue": + err = unpopulate(val, "LocalizedValue", &q.LocalizedValue) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &q.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceDetailsObject. +func (r ResourceDetailsObject) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "systemData", r.SystemData) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceDetailsObject. +func (r *ResourceDetailsObject) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &r.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &r.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceDetailsObjectListResult. +func (r ResourceDetailsObjectListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", r.NextLink) + populate(objectMap, "value", r.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceDetailsObjectListResult. +func (r *ResourceDetailsObjectListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &r.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &r.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceDetailsObjectProperties. +func (r ResourceDetailsObjectProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "image", r.Image) + populate(objectMap, "imageVersion", r.ImageVersion) + populate(objectMap, "status", r.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceDetailsObjectProperties. +func (r *ResourceDetailsObjectProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "image": + err = unpopulate(val, "Image", &r.Image) + delete(rawMsg, key) + case "imageVersion": + err = unpopulate(val, "ImageVersion", &r.ImageVersion) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &r.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourcePredictionsProfile. +func (r ResourcePredictionsProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "kind", r.Kind) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourcePredictionsProfile. +func (r *ResourcePredictionsProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &r.Kind) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceSKU. +func (r ResourceSKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "systemData", r.SystemData) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceSKU. +func (r *ResourceSKU) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &r.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &r.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceSKUCapabilities. +func (r ResourceSKUCapabilities) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", r.Name) + populate(objectMap, "value", r.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceSKUCapabilities. +func (r *ResourceSKUCapabilities) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &r.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceSKUListResult. +func (r ResourceSKUListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", r.NextLink) + populate(objectMap, "value", r.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceSKUListResult. +func (r *ResourceSKUListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &r.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &r.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceSKULocationInfo. +func (r ResourceSKULocationInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "location", r.Location) + populate(objectMap, "zoneDetails", r.ZoneDetails) + populate(objectMap, "zones", r.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceSKULocationInfo. +func (r *ResourceSKULocationInfo) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "location": + err = unpopulate(val, "Location", &r.Location) + delete(rawMsg, key) + case "zoneDetails": + err = unpopulate(val, "ZoneDetails", &r.ZoneDetails) + delete(rawMsg, key) + case "zones": + err = unpopulate(val, "Zones", &r.Zones) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceSKUProperties. +func (r ResourceSKUProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "capabilities", r.Capabilities) + populate(objectMap, "family", r.Family) + populate(objectMap, "locationInfo", r.LocationInfo) + populate(objectMap, "locations", r.Locations) + populate(objectMap, "resourceType", r.ResourceType) + populate(objectMap, "restrictions", r.Restrictions) + populate(objectMap, "size", r.Size) + populate(objectMap, "tier", r.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceSKUProperties. +func (r *ResourceSKUProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "capabilities": + err = unpopulate(val, "Capabilities", &r.Capabilities) + delete(rawMsg, key) + case "family": + err = unpopulate(val, "Family", &r.Family) + delete(rawMsg, key) + case "locationInfo": + err = unpopulate(val, "LocationInfo", &r.LocationInfo) + delete(rawMsg, key) + case "locations": + err = unpopulate(val, "Locations", &r.Locations) + delete(rawMsg, key) + case "resourceType": + err = unpopulate(val, "ResourceType", &r.ResourceType) + delete(rawMsg, key) + case "restrictions": + err = unpopulate(val, "Restrictions", &r.Restrictions) + delete(rawMsg, key) + case "size": + err = unpopulate(val, "Size", &r.Size) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &r.Tier) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceSKURestrictionInfo. +func (r ResourceSKURestrictionInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "locations", r.Locations) + populate(objectMap, "zones", r.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceSKURestrictionInfo. +func (r *ResourceSKURestrictionInfo) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "locations": + err = unpopulate(val, "Locations", &r.Locations) + delete(rawMsg, key) + case "zones": + err = unpopulate(val, "Zones", &r.Zones) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceSKURestrictions. +func (r ResourceSKURestrictions) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "reasonCode", r.ReasonCode) + populate(objectMap, "restrictionInfo", r.RestrictionInfo) + populate(objectMap, "type", r.Type) + populate(objectMap, "values", r.Values) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceSKURestrictions. +func (r *ResourceSKURestrictions) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "reasonCode": + err = unpopulate(val, "ReasonCode", &r.ReasonCode) + delete(rawMsg, key) + case "restrictionInfo": + err = unpopulate(val, "RestrictionInfo", &r.RestrictionInfo) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + case "values": + err = unpopulate(val, "Values", &r.Values) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceSKUZoneDetails. +func (r ResourceSKUZoneDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "capabilities", r.Capabilities) + populate(objectMap, "name", r.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceSKUZoneDetails. +func (r *ResourceSKUZoneDetails) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "capabilities": + err = unpopulate(val, "Capabilities", &r.Capabilities) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RuntimeConfiguration. +func (r RuntimeConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "workFolder", r.WorkFolder) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RuntimeConfiguration. +func (r *RuntimeConfiguration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "workFolder": + err = unpopulate(val, "WorkFolder", &r.WorkFolder) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SecretsManagementSettings. +func (s SecretsManagementSettings) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "certificateStoreLocation", s.CertificateStoreLocation) + populate(objectMap, "certificateStoreName", s.CertificateStoreName) + populate(objectMap, "keyExportable", s.KeyExportable) + populate(objectMap, "observedCertificates", s.ObservedCertificates) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecretsManagementSettings. +func (s *SecretsManagementSettings) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "certificateStoreLocation": + err = unpopulate(val, "CertificateStoreLocation", &s.CertificateStoreLocation) + delete(rawMsg, key) + case "certificateStoreName": + err = unpopulate(val, "CertificateStoreName", &s.CertificateStoreName) + delete(rawMsg, key) + case "keyExportable": + err = unpopulate(val, "KeyExportable", &s.KeyExportable) + delete(rawMsg, key) + case "observedCertificates": + err = unpopulate(val, "ObservedCertificates", &s.ObservedCertificates) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Stateful. +func (s Stateful) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "gracePeriodTimeSpan", s.GracePeriodTimeSpan) + objectMap["kind"] = "Stateful" + populate(objectMap, "maxAgentLifetime", s.MaxAgentLifetime) + populate(objectMap, "resourcePredictions", s.ResourcePredictions) + populate(objectMap, "resourcePredictionsProfile", s.ResourcePredictionsProfile) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Stateful. +func (s *Stateful) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "gracePeriodTimeSpan": + err = unpopulate(val, "GracePeriodTimeSpan", &s.GracePeriodTimeSpan) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &s.Kind) + delete(rawMsg, key) + case "maxAgentLifetime": + err = unpopulate(val, "MaxAgentLifetime", &s.MaxAgentLifetime) + delete(rawMsg, key) + case "resourcePredictions": + err = unpopulate(val, "ResourcePredictions", &s.ResourcePredictions) + delete(rawMsg, key) + case "resourcePredictionsProfile": + s.ResourcePredictionsProfile, err = unmarshalResourcePredictionsProfileClassification(val) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type StatelessAgentProfile. +func (s StatelessAgentProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["kind"] = "Stateless" + populate(objectMap, "resourcePredictions", s.ResourcePredictions) + populate(objectMap, "resourcePredictionsProfile", s.ResourcePredictionsProfile) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StatelessAgentProfile. +func (s *StatelessAgentProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &s.Kind) + delete(rawMsg, key) + case "resourcePredictions": + err = unpopulate(val, "ResourcePredictions", &s.ResourcePredictions) + delete(rawMsg, key) + case "resourcePredictionsProfile": + s.ResourcePredictionsProfile, err = unmarshalResourcePredictionsProfileClassification(val) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type StorageProfile. +func (s StorageProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dataDisks", s.DataDisks) + populate(objectMap, "osDiskStorageAccountType", s.OSDiskStorageAccountType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StorageProfile. +func (s *StorageProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "dataDisks": + err = unpopulate(val, "DataDisks", &s.DataDisks) + delete(rawMsg, key) + case "osDiskStorageAccountType": + err = unpopulate(val, "OSDiskStorageAccountType", &s.OSDiskStorageAccountType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateTime[datetime.RFC3339](objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateTime[datetime.RFC3339](val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateTime[datetime.RFC3339](val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserAssignedIdentity. +func (u UserAssignedIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clientId", u.ClientID) + populate(objectMap, "principalId", u.PrincipalID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserAssignedIdentity. +func (u *UserAssignedIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "clientId": + err = unpopulate(val, "ClientID", &u.ClientID) + delete(rawMsg, key) + case "principalId": + err = unpopulate(val, "PrincipalID", &u.PrincipalID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VmssFabricProfile. +func (v VmssFabricProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "images", v.Images) + objectMap["kind"] = "Vmss" + populate(objectMap, "networkProfile", v.NetworkProfile) + populate(objectMap, "osProfile", v.OSProfile) + populate(objectMap, "sku", v.SKU) + populate(objectMap, "storageProfile", v.StorageProfile) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VmssFabricProfile. +func (v *VmssFabricProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "images": + err = unpopulate(val, "Images", &v.Images) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &v.Kind) + delete(rawMsg, key) + case "networkProfile": + err = unpopulate(val, "NetworkProfile", &v.NetworkProfile) + delete(rawMsg, key) + case "osProfile": + err = unpopulate(val, "OSProfile", &v.OSProfile) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &v.SKU) + delete(rawMsg, key) + case "storageProfile": + err = unpopulate(val, "StorageProfile", &v.StorageProfile) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/local/armdevopsinfrastructure/zz_operations_client.go b/test/local/armdevopsinfrastructure/zz_operations_client.go new file mode 100644 index 000000000000..34ab01436875 --- /dev/null +++ b/test/local/armdevopsinfrastructure/zz_operations_client.go @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdevopsinfrastructure + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +// +// Generated from API version 2026-04-17-preview +type OperationsClient struct { + internal *arm.Client +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*OperationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OperationsClient{ + internal: cl, + } + return client, nil +} + +// NewListPager - List the operations for the provider +// - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ + More: func(page OperationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OperationsClientListResponse) (OperationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OperationsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return OperationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, _ *OperationsClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.DevOpsInfrastructure/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260417Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsClientListResponse, error) { + result := OperationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armdevopsinfrastructure/zz_options.go b/test/local/armdevopsinfrastructure/zz_options.go new file mode 100644 index 000000000000..e5581f03d331 --- /dev/null +++ b/test/local/armdevopsinfrastructure/zz_options.go @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdevopsinfrastructure + +// ImageVersionsClientListByImageOptions contains the optional parameters for the ImageVersionsClient.NewListByImagePager +// method. +type ImageVersionsClientListByImageOptions struct { + // placeholder for future optional parameters +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} + +// PoolsClientBeginCreateOrUpdateOptions contains the optional parameters for the PoolsClient.BeginCreateOrUpdate method. +type PoolsClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// PoolsClientBeginDeleteOptions contains the optional parameters for the PoolsClient.BeginDelete method. +type PoolsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// PoolsClientBeginUpdateOptions contains the optional parameters for the PoolsClient.BeginUpdate method. +type PoolsClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// PoolsClientCheckNameAvailabilityOptions contains the optional parameters for the PoolsClient.CheckNameAvailability method. +type PoolsClientCheckNameAvailabilityOptions struct { + // placeholder for future optional parameters +} + +// PoolsClientDeleteResourcesOptions contains the optional parameters for the PoolsClient.DeleteResources method. +type PoolsClientDeleteResourcesOptions struct { + // placeholder for future optional parameters +} + +// PoolsClientGetOptions contains the optional parameters for the PoolsClient.Get method. +type PoolsClientGetOptions struct { + // placeholder for future optional parameters +} + +// PoolsClientListByResourceGroupOptions contains the optional parameters for the PoolsClient.NewListByResourceGroupPager +// method. +type PoolsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// PoolsClientListBySubscriptionOptions contains the optional parameters for the PoolsClient.NewListBySubscriptionPager method. +type PoolsClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// ResourceDetailsClientListByPoolOptions contains the optional parameters for the ResourceDetailsClient.NewListByPoolPager +// method. +type ResourceDetailsClientListByPoolOptions struct { + // placeholder for future optional parameters +} + +// SKUClientListByLocationOptions contains the optional parameters for the SKUClient.NewListByLocationPager method. +type SKUClientListByLocationOptions struct { + // placeholder for future optional parameters +} + +// SubscriptionUsagesClientUsagesOptions contains the optional parameters for the SubscriptionUsagesClient.NewUsagesPager +// method. +type SubscriptionUsagesClientUsagesOptions struct { + // placeholder for future optional parameters +} diff --git a/test/local/armdevopsinfrastructure/zz_polymorphic_helpers.go b/test/local/armdevopsinfrastructure/zz_polymorphic_helpers.go new file mode 100644 index 000000000000..3332b62e1472 --- /dev/null +++ b/test/local/armdevopsinfrastructure/zz_polymorphic_helpers.go @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdevopsinfrastructure + +import "encoding/json" + +func unmarshalAgentProfileClassification(rawMsg json.RawMessage) (AgentProfileClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b AgentProfileClassification + switch m["kind"] { + case "Stateful": + b = &Stateful{} + case "Stateless": + b = &StatelessAgentProfile{} + default: + b = &AgentProfile{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} + +func unmarshalFabricProfileClassification(rawMsg json.RawMessage) (FabricProfileClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b FabricProfileClassification + switch m["kind"] { + case "Vmss": + b = &VmssFabricProfile{} + default: + b = &FabricProfile{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} + +func unmarshalOrganizationProfileClassification(rawMsg json.RawMessage) (OrganizationProfileClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b OrganizationProfileClassification + switch m["kind"] { + case "AzureDevOps": + b = &AzureDevOpsOrganizationProfile{} + case "GitHub": + b = &GitHubOrganizationProfile{} + default: + b = &OrganizationProfile{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} + +func unmarshalResourcePredictionsProfileClassification(rawMsg json.RawMessage) (ResourcePredictionsProfileClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b ResourcePredictionsProfileClassification + switch m["kind"] { + case string(ResourcePredictionsProfileTypeAutomatic): + b = &AutomaticResourcePredictionsProfile{} + case string(ResourcePredictionsProfileTypeManual): + b = &ManualResourcePredictionsProfile{} + default: + b = &ResourcePredictionsProfile{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} diff --git a/test/local/armdevopsinfrastructure/zz_pools_client.go b/test/local/armdevopsinfrastructure/zz_pools_client.go new file mode 100644 index 000000000000..a04f45a3169d --- /dev/null +++ b/test/local/armdevopsinfrastructure/zz_pools_client.go @@ -0,0 +1,553 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdevopsinfrastructure + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// PoolsClient contains the methods for the Pools group. +// Don't use this type directly, use NewPoolsClient() instead. +// +// Generated from API version 2026-04-17-preview +type PoolsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewPoolsClient creates a new instance of PoolsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewPoolsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*PoolsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &PoolsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CheckNameAvailability - Checks that the pool name is valid and is not already in use. +// If the operation fails it returns an *azcore.ResponseError type. +// - body - The CheckAvailability request +// - options - PoolsClientCheckNameAvailabilityOptions contains the optional parameters for the PoolsClient.CheckNameAvailability +// method. +func (client *PoolsClient) CheckNameAvailability(ctx context.Context, body CheckNameAvailability, options *PoolsClientCheckNameAvailabilityOptions) (PoolsClientCheckNameAvailabilityResponse, error) { + var err error + const operationName = "PoolsClient.CheckNameAvailability" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.checkNameAvailabilityCreateRequest(ctx, body, options) + if err != nil { + return PoolsClientCheckNameAvailabilityResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PoolsClientCheckNameAvailabilityResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PoolsClientCheckNameAvailabilityResponse{}, err + } + resp, err := client.checkNameAvailabilityHandleResponse(httpResp) + return resp, err +} + +// checkNameAvailabilityCreateRequest creates the CheckNameAvailability request. +func (client *PoolsClient) checkNameAvailabilityCreateRequest(ctx context.Context, body CheckNameAvailability, _ *PoolsClientCheckNameAvailabilityOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.DevOpsInfrastructure/checkNameAvailability" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260417Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// checkNameAvailabilityHandleResponse handles the CheckNameAvailability response. +func (client *PoolsClient) checkNameAvailabilityHandleResponse(resp *http.Response) (PoolsClientCheckNameAvailabilityResponse, error) { + result := PoolsClientCheckNameAvailabilityResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CheckNameAvailabilityResult); err != nil { + return PoolsClientCheckNameAvailabilityResponse{}, err + } + return result, nil +} + +// BeginCreateOrUpdate - Create a Pool +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - poolName - Name of the pool. It needs to be globally unique. +// - resource - Resource create parameters. +// - options - PoolsClientBeginCreateOrUpdateOptions contains the optional parameters for the PoolsClient.BeginCreateOrUpdate +// method. +func (client *PoolsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, poolName string, resource Pool, options *PoolsClientBeginCreateOrUpdateOptions) (*runtime.Poller[PoolsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, poolName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PoolsClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PoolsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create a Pool +// If the operation fails it returns an *azcore.ResponseError type. +func (client *PoolsClient) createOrUpdate(ctx context.Context, resourceGroupName string, poolName string, resource Pool, options *PoolsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "PoolsClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, poolName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *PoolsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, poolName string, resource Pool, _ *PoolsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevOpsInfrastructure/pools/{poolName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if poolName == "" { + return nil, errors.New("parameter poolName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolName}", url.PathEscape(poolName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260417Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a Pool +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - poolName - Name of the pool. It needs to be globally unique. +// - options - PoolsClientBeginDeleteOptions contains the optional parameters for the PoolsClient.BeginDelete method. +func (client *PoolsClient) BeginDelete(ctx context.Context, resourceGroupName string, poolName string, options *PoolsClientBeginDeleteOptions) (*runtime.Poller[PoolsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, poolName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PoolsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PoolsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a Pool +// If the operation fails it returns an *azcore.ResponseError type. +func (client *PoolsClient) deleteOperation(ctx context.Context, resourceGroupName string, poolName string, options *PoolsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "PoolsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, poolName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *PoolsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, poolName string, _ *PoolsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevOpsInfrastructure/pools/{poolName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if poolName == "" { + return nil, errors.New("parameter poolName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolName}", url.PathEscape(poolName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260417Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// DeleteResources - A synchronous resource action. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - poolName - Name of the pool. It needs to be globally unique. +// - body - The content of the action request +// - options - PoolsClientDeleteResourcesOptions contains the optional parameters for the PoolsClient.DeleteResources method. +func (client *PoolsClient) DeleteResources(ctx context.Context, resourceGroupName string, poolName string, body DeleteResourcesDetails, options *PoolsClientDeleteResourcesOptions) (PoolsClientDeleteResourcesResponse, error) { + var err error + const operationName = "PoolsClient.DeleteResources" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteResourcesCreateRequest(ctx, resourceGroupName, poolName, body, options) + if err != nil { + return PoolsClientDeleteResourcesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PoolsClientDeleteResourcesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PoolsClientDeleteResourcesResponse{}, err + } + return PoolsClientDeleteResourcesResponse{}, nil +} + +// deleteResourcesCreateRequest creates the DeleteResources request. +func (client *PoolsClient) deleteResourcesCreateRequest(ctx context.Context, resourceGroupName string, poolName string, body DeleteResourcesDetails, _ *PoolsClientDeleteResourcesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevOpsInfrastructure/pools/{poolName}/resources" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if poolName == "" { + return nil, errors.New("parameter poolName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolName}", url.PathEscape(poolName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260417Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// Get - Get a Pool +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - poolName - Name of the pool. It needs to be globally unique. +// - options - PoolsClientGetOptions contains the optional parameters for the PoolsClient.Get method. +func (client *PoolsClient) Get(ctx context.Context, resourceGroupName string, poolName string, options *PoolsClientGetOptions) (PoolsClientGetResponse, error) { + var err error + const operationName = "PoolsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, poolName, options) + if err != nil { + return PoolsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PoolsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PoolsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *PoolsClient) getCreateRequest(ctx context.Context, resourceGroupName string, poolName string, _ *PoolsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevOpsInfrastructure/pools/{poolName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if poolName == "" { + return nil, errors.New("parameter poolName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolName}", url.PathEscape(poolName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260417Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *PoolsClient) getHandleResponse(resp *http.Response) (PoolsClientGetResponse, error) { + result := PoolsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Pool); err != nil { + return PoolsClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - List Pool resources by resource group +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - PoolsClientListByResourceGroupOptions contains the optional parameters for the PoolsClient.NewListByResourceGroupPager +// method. +func (client *PoolsClient) NewListByResourceGroupPager(resourceGroupName string, options *PoolsClientListByResourceGroupOptions) *runtime.Pager[PoolsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[PoolsClientListByResourceGroupResponse]{ + More: func(page PoolsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PoolsClientListByResourceGroupResponse) (PoolsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PoolsClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return PoolsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *PoolsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *PoolsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevOpsInfrastructure/pools" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260417Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *PoolsClient) listByResourceGroupHandleResponse(resp *http.Response) (PoolsClientListByResourceGroupResponse, error) { + result := PoolsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PoolListResult); err != nil { + return PoolsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - List Pool resources by subscription ID +// - options - PoolsClientListBySubscriptionOptions contains the optional parameters for the PoolsClient.NewListBySubscriptionPager +// method. +func (client *PoolsClient) NewListBySubscriptionPager(options *PoolsClientListBySubscriptionOptions) *runtime.Pager[PoolsClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[PoolsClientListBySubscriptionResponse]{ + More: func(page PoolsClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PoolsClientListBySubscriptionResponse) (PoolsClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PoolsClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return PoolsClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *PoolsClient) listBySubscriptionCreateRequest(ctx context.Context, _ *PoolsClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.DevOpsInfrastructure/pools" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260417Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *PoolsClient) listBySubscriptionHandleResponse(resp *http.Response) (PoolsClientListBySubscriptionResponse, error) { + result := PoolsClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PoolListResult); err != nil { + return PoolsClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update a Pool +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - poolName - Name of the pool. It needs to be globally unique. +// - properties - The resource properties to be updated. +// - options - PoolsClientBeginUpdateOptions contains the optional parameters for the PoolsClient.BeginUpdate method. +func (client *PoolsClient) BeginUpdate(ctx context.Context, resourceGroupName string, poolName string, properties PoolUpdate, options *PoolsClientBeginUpdateOptions) (*runtime.Poller[PoolsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, poolName, properties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PoolsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PoolsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a Pool +// If the operation fails it returns an *azcore.ResponseError type. +func (client *PoolsClient) update(ctx context.Context, resourceGroupName string, poolName string, properties PoolUpdate, options *PoolsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "PoolsClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, poolName, properties, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *PoolsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, poolName string, properties PoolUpdate, _ *PoolsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevOpsInfrastructure/pools/{poolName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if poolName == "" { + return nil, errors.New("parameter poolName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolName}", url.PathEscape(poolName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260417Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armdevopsinfrastructure/zz_resourcedetails_client.go b/test/local/armdevopsinfrastructure/zz_resourcedetails_client.go new file mode 100644 index 000000000000..c32afd31787a --- /dev/null +++ b/test/local/armdevopsinfrastructure/zz_resourcedetails_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdevopsinfrastructure + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ResourceDetailsClient contains the methods for the ResourceDetails group. +// Don't use this type directly, use NewResourceDetailsClient() instead. +// +// Generated from API version 2026-04-17-preview +type ResourceDetailsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewResourceDetailsClient creates a new instance of ResourceDetailsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewResourceDetailsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ResourceDetailsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ResourceDetailsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListByPoolPager - List ResourceDetailsObject resources by Pool +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - poolName - Name of the pool. It needs to be globally unique. +// - options - ResourceDetailsClientListByPoolOptions contains the optional parameters for the ResourceDetailsClient.NewListByPoolPager +// method. +func (client *ResourceDetailsClient) NewListByPoolPager(resourceGroupName string, poolName string, options *ResourceDetailsClientListByPoolOptions) *runtime.Pager[ResourceDetailsClientListByPoolResponse] { + return runtime.NewPager(runtime.PagingHandler[ResourceDetailsClientListByPoolResponse]{ + More: func(page ResourceDetailsClientListByPoolResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ResourceDetailsClientListByPoolResponse) (ResourceDetailsClientListByPoolResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ResourceDetailsClient.NewListByPoolPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByPoolCreateRequest(ctx, resourceGroupName, poolName, options) + }, nil) + if err != nil { + return ResourceDetailsClientListByPoolResponse{}, err + } + return client.listByPoolHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByPoolCreateRequest creates the ListByPool request. +func (client *ResourceDetailsClient) listByPoolCreateRequest(ctx context.Context, resourceGroupName string, poolName string, _ *ResourceDetailsClientListByPoolOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevOpsInfrastructure/pools/{poolName}/resources" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if poolName == "" { + return nil, errors.New("parameter poolName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{poolName}", url.PathEscape(poolName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260417Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByPoolHandleResponse handles the ListByPool response. +func (client *ResourceDetailsClient) listByPoolHandleResponse(resp *http.Response) (ResourceDetailsClientListByPoolResponse, error) { + result := ResourceDetailsClientListByPoolResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ResourceDetailsObjectListResult); err != nil { + return ResourceDetailsClientListByPoolResponse{}, err + } + return result, nil +} diff --git a/test/local/armdevopsinfrastructure/zz_responses.go b/test/local/armdevopsinfrastructure/zz_responses.go new file mode 100644 index 000000000000..eea131e1cb2c --- /dev/null +++ b/test/local/armdevopsinfrastructure/zz_responses.go @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdevopsinfrastructure + +// ImageVersionsClientListByImageResponse contains the response from method ImageVersionsClient.NewListByImagePager. +type ImageVersionsClientListByImageResponse struct { + // The response of a ImageVersion list operation. + ImageVersionListResult +} + +// OperationsClientListResponse contains the response from method OperationsClient.NewListPager. +type OperationsClientListResponse struct { + // A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. + OperationListResult +} + +// PoolsClientCheckNameAvailabilityResponse contains the response from method PoolsClient.CheckNameAvailability. +type PoolsClientCheckNameAvailabilityResponse struct { + // The CheckNameAvailability operation response. + CheckNameAvailabilityResult +} + +// PoolsClientCreateOrUpdateResponse contains the response from method PoolsClient.BeginCreateOrUpdate. +type PoolsClientCreateOrUpdateResponse struct { + // Concrete tracked resource types can be created by aliasing this type using a specific property type. + Pool +} + +// PoolsClientDeleteResourcesResponse contains the response from method PoolsClient.DeleteResources. +type PoolsClientDeleteResourcesResponse struct { + // placeholder for future response values +} + +// PoolsClientDeleteResponse contains the response from method PoolsClient.BeginDelete. +type PoolsClientDeleteResponse struct { + // placeholder for future response values +} + +// PoolsClientGetResponse contains the response from method PoolsClient.Get. +type PoolsClientGetResponse struct { + // Concrete tracked resource types can be created by aliasing this type using a specific property type. + Pool +} + +// PoolsClientListByResourceGroupResponse contains the response from method PoolsClient.NewListByResourceGroupPager. +type PoolsClientListByResourceGroupResponse struct { + // The response of a Pool list operation. + PoolListResult +} + +// PoolsClientListBySubscriptionResponse contains the response from method PoolsClient.NewListBySubscriptionPager. +type PoolsClientListBySubscriptionResponse struct { + // The response of a Pool list operation. + PoolListResult +} + +// PoolsClientUpdateResponse contains the response from method PoolsClient.BeginUpdate. +type PoolsClientUpdateResponse struct { + // Concrete tracked resource types can be created by aliasing this type using a specific property type. + Pool +} + +// ResourceDetailsClientListByPoolResponse contains the response from method ResourceDetailsClient.NewListByPoolPager. +type ResourceDetailsClientListByPoolResponse struct { + // The response of a ResourceDetailsObject list operation. + ResourceDetailsObjectListResult +} + +// SKUClientListByLocationResponse contains the response from method SKUClient.NewListByLocationPager. +type SKUClientListByLocationResponse struct { + // The response of a ResourceSku list operation. + ResourceSKUListResult +} + +// SubscriptionUsagesClientUsagesResponse contains the response from method SubscriptionUsagesClient.NewUsagesPager. +type SubscriptionUsagesClientUsagesResponse struct { + // Paged collection of Quota items + PagedQuota +} diff --git a/test/local/armdevopsinfrastructure/zz_sku_client.go b/test/local/armdevopsinfrastructure/zz_sku_client.go new file mode 100644 index 000000000000..02afcd787614 --- /dev/null +++ b/test/local/armdevopsinfrastructure/zz_sku_client.go @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdevopsinfrastructure + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// SKUClient contains the methods for the SKU group. +// Don't use this type directly, use NewSKUClient() instead. +// +// Generated from API version 2026-04-17-preview +type SKUClient struct { + internal *arm.Client + subscriptionID string +} + +// NewSKUClient creates a new instance of SKUClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewSKUClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SKUClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SKUClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListByLocationPager - List ResourceSku resources by subscription ID +// - locationName - Name of the location. +// - options - SKUClientListByLocationOptions contains the optional parameters for the SKUClient.NewListByLocationPager method. +func (client *SKUClient) NewListByLocationPager(locationName string, options *SKUClientListByLocationOptions) *runtime.Pager[SKUClientListByLocationResponse] { + return runtime.NewPager(runtime.PagingHandler[SKUClientListByLocationResponse]{ + More: func(page SKUClientListByLocationResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SKUClientListByLocationResponse) (SKUClientListByLocationResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SKUClient.NewListByLocationPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByLocationCreateRequest(ctx, locationName, options) + }, nil) + if err != nil { + return SKUClientListByLocationResponse{}, err + } + return client.listByLocationHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByLocationCreateRequest creates the ListByLocation request. +func (client *SKUClient) listByLocationCreateRequest(ctx context.Context, locationName string, _ *SKUClientListByLocationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.DevOpsInfrastructure/locations/{locationName}/skus" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if locationName == "" { + return nil, errors.New("parameter locationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{locationName}", url.PathEscape(locationName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260417Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByLocationHandleResponse handles the ListByLocation response. +func (client *SKUClient) listByLocationHandleResponse(resp *http.Response) (SKUClientListByLocationResponse, error) { + result := SKUClientListByLocationResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ResourceSKUListResult); err != nil { + return SKUClientListByLocationResponse{}, err + } + return result, nil +} diff --git a/test/local/armdevopsinfrastructure/zz_subscriptionusages_client.go b/test/local/armdevopsinfrastructure/zz_subscriptionusages_client.go new file mode 100644 index 000000000000..ac248ad4e5cd --- /dev/null +++ b/test/local/armdevopsinfrastructure/zz_subscriptionusages_client.go @@ -0,0 +1,100 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armdevopsinfrastructure + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// SubscriptionUsagesClient contains the methods for the SubscriptionUsages group. +// Don't use this type directly, use NewSubscriptionUsagesClient() instead. +// +// Generated from API version 2026-04-17-preview +type SubscriptionUsagesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewSubscriptionUsagesClient creates a new instance of SubscriptionUsagesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewSubscriptionUsagesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SubscriptionUsagesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SubscriptionUsagesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewUsagesPager - List Quota resources by subscription ID +// - location - The name of the Azure region. +// - options - SubscriptionUsagesClientUsagesOptions contains the optional parameters for the SubscriptionUsagesClient.NewUsagesPager +// method. +func (client *SubscriptionUsagesClient) NewUsagesPager(location string, options *SubscriptionUsagesClientUsagesOptions) *runtime.Pager[SubscriptionUsagesClientUsagesResponse] { + return runtime.NewPager(runtime.PagingHandler[SubscriptionUsagesClientUsagesResponse]{ + More: func(page SubscriptionUsagesClientUsagesResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SubscriptionUsagesClientUsagesResponse) (SubscriptionUsagesClientUsagesResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SubscriptionUsagesClient.NewUsagesPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.usagesCreateRequest(ctx, location, options) + }, nil) + if err != nil { + return SubscriptionUsagesClientUsagesResponse{}, err + } + return client.usagesHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// usagesCreateRequest creates the Usages request. +func (client *SubscriptionUsagesClient) usagesCreateRequest(ctx context.Context, location string, _ *SubscriptionUsagesClientUsagesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.DevOpsInfrastructure/locations/{location}/usages" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260417Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// usagesHandleResponse handles the Usages response. +func (client *SubscriptionUsagesClient) usagesHandleResponse(resp *http.Response) (SubscriptionUsagesClientUsagesResponse, error) { + result := SubscriptionUsagesClientUsagesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PagedQuota); err != nil { + return SubscriptionUsagesClientUsagesResponse{}, err + } + return result, nil +} diff --git a/test/local/armdevopsinfrastructure/zz_version.go b/test/local/armdevopsinfrastructure/zz_version.go new file mode 100644 index 000000000000..7adafd5932df --- /dev/null +++ b/test/local/armdevopsinfrastructure/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package armdevopsinfrastructure + +const ( + moduleName = "armdevopsinfrastructure" + moduleVersion = "v0.1.0" +) diff --git a/test/local/armhardwaresecuritymodules/LICENSE.txt b/test/local/armhardwaresecuritymodules/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/local/armhardwaresecuritymodules/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/local/armhardwaresecuritymodules/fake/zz_cloudhsmclusterbackupstatus_server.go b/test/local/armhardwaresecuritymodules/fake/zz_cloudhsmclusterbackupstatus_server.go new file mode 100644 index 000000000000..2ac41b94516a --- /dev/null +++ b/test/local/armhardwaresecuritymodules/fake/zz_cloudhsmclusterbackupstatus_server.go @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armhardwaresecuritymodules" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// CloudHsmClusterBackupStatusServer is a fake server for instances of the armhardwaresecuritymodules.CloudHsmClusterBackupStatusClient type. +type CloudHsmClusterBackupStatusServer struct { + // Get is the fake for method CloudHsmClusterBackupStatusClient.Get + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + Get func(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, jobID string, options *armhardwaresecuritymodules.CloudHsmClusterBackupStatusClientGetOptions) (resp azfake.Responder[armhardwaresecuritymodules.CloudHsmClusterBackupStatusClientGetResponse], errResp azfake.ErrorResponder) +} + +// NewCloudHsmClusterBackupStatusServerTransport creates a new instance of CloudHsmClusterBackupStatusServerTransport with the provided implementation. +// The returned CloudHsmClusterBackupStatusServerTransport instance is connected to an instance of armhardwaresecuritymodules.CloudHsmClusterBackupStatusClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewCloudHsmClusterBackupStatusServerTransport(srv *CloudHsmClusterBackupStatusServer) *CloudHsmClusterBackupStatusServerTransport { + return &CloudHsmClusterBackupStatusServerTransport{srv: srv} +} + +// CloudHsmClusterBackupStatusServerTransport connects instances of armhardwaresecuritymodules.CloudHsmClusterBackupStatusClient to instances of CloudHsmClusterBackupStatusServer. +// Don't use this type directly, use NewCloudHsmClusterBackupStatusServerTransport instead. +type CloudHsmClusterBackupStatusServerTransport struct { + srv *CloudHsmClusterBackupStatusServer +} + +// Do implements the policy.Transporter interface for CloudHsmClusterBackupStatusServerTransport. +func (c *CloudHsmClusterBackupStatusServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *CloudHsmClusterBackupStatusServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if cloudHsmClusterBackupStatusServerTransportInterceptor != nil { + res.resp, res.err, intercepted = cloudHsmClusterBackupStatusServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "CloudHsmClusterBackupStatusClient.Get": + res.resp, res.err = c.dispatchGet(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *CloudHsmClusterBackupStatusServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if c.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HardwareSecurityModules/cloudHsmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/backupOperationStatus/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudHsmClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudHsmClusterName")]) + if err != nil { + return nil, err + } + jobIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("jobId")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.Get(req.Context(), resourceGroupNameParam, cloudHsmClusterNameParam, jobIDParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BackupResult, req) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).Location; val != nil { + resp.Header.Set("Location", *val) + } + if val := server.GetResponse(respr).RequestID; val != nil { + resp.Header.Set("x-ms-request-id", *val) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to CloudHsmClusterBackupStatusServerTransport +var cloudHsmClusterBackupStatusServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armhardwaresecuritymodules/fake/zz_cloudhsmclusterprivateendpointconnections_server.go b/test/local/armhardwaresecuritymodules/fake/zz_cloudhsmclusterprivateendpointconnections_server.go new file mode 100644 index 000000000000..81a250e3de94 --- /dev/null +++ b/test/local/armhardwaresecuritymodules/fake/zz_cloudhsmclusterprivateendpointconnections_server.go @@ -0,0 +1,226 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armhardwaresecuritymodules" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// CloudHsmClusterPrivateEndpointConnectionsServer is a fake server for instances of the armhardwaresecuritymodules.CloudHsmClusterPrivateEndpointConnectionsClient type. +type CloudHsmClusterPrivateEndpointConnectionsServer struct { + // Create is the fake for method CloudHsmClusterPrivateEndpointConnectionsClient.Create + // HTTP status codes to indicate success: http.StatusOK + Create func(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, peConnectionName string, properties armhardwaresecuritymodules.PrivateEndpointConnection, options *armhardwaresecuritymodules.CloudHsmClusterPrivateEndpointConnectionsClientCreateOptions) (resp azfake.Responder[armhardwaresecuritymodules.CloudHsmClusterPrivateEndpointConnectionsClientCreateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method CloudHsmClusterPrivateEndpointConnectionsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, peConnectionName string, options *armhardwaresecuritymodules.CloudHsmClusterPrivateEndpointConnectionsClientBeginDeleteOptions) (resp azfake.PollerResponder[armhardwaresecuritymodules.CloudHsmClusterPrivateEndpointConnectionsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method CloudHsmClusterPrivateEndpointConnectionsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, peConnectionName string, options *armhardwaresecuritymodules.CloudHsmClusterPrivateEndpointConnectionsClientGetOptions) (resp azfake.Responder[armhardwaresecuritymodules.CloudHsmClusterPrivateEndpointConnectionsClientGetResponse], errResp azfake.ErrorResponder) +} + +// NewCloudHsmClusterPrivateEndpointConnectionsServerTransport creates a new instance of CloudHsmClusterPrivateEndpointConnectionsServerTransport with the provided implementation. +// The returned CloudHsmClusterPrivateEndpointConnectionsServerTransport instance is connected to an instance of armhardwaresecuritymodules.CloudHsmClusterPrivateEndpointConnectionsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewCloudHsmClusterPrivateEndpointConnectionsServerTransport(srv *CloudHsmClusterPrivateEndpointConnectionsServer) *CloudHsmClusterPrivateEndpointConnectionsServerTransport { + return &CloudHsmClusterPrivateEndpointConnectionsServerTransport{ + srv: srv, + beginDelete: newTracker[azfake.PollerResponder[armhardwaresecuritymodules.CloudHsmClusterPrivateEndpointConnectionsClientDeleteResponse]](), + } +} + +// CloudHsmClusterPrivateEndpointConnectionsServerTransport connects instances of armhardwaresecuritymodules.CloudHsmClusterPrivateEndpointConnectionsClient to instances of CloudHsmClusterPrivateEndpointConnectionsServer. +// Don't use this type directly, use NewCloudHsmClusterPrivateEndpointConnectionsServerTransport instead. +type CloudHsmClusterPrivateEndpointConnectionsServerTransport struct { + srv *CloudHsmClusterPrivateEndpointConnectionsServer + beginDelete *tracker[azfake.PollerResponder[armhardwaresecuritymodules.CloudHsmClusterPrivateEndpointConnectionsClientDeleteResponse]] +} + +// Do implements the policy.Transporter interface for CloudHsmClusterPrivateEndpointConnectionsServerTransport. +func (c *CloudHsmClusterPrivateEndpointConnectionsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *CloudHsmClusterPrivateEndpointConnectionsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if cloudHsmClusterPrivateEndpointConnectionsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = cloudHsmClusterPrivateEndpointConnectionsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "CloudHsmClusterPrivateEndpointConnectionsClient.Create": + res.resp, res.err = c.dispatchCreate(req) + case "CloudHsmClusterPrivateEndpointConnectionsClient.BeginDelete": + res.resp, res.err = c.dispatchBeginDelete(req) + case "CloudHsmClusterPrivateEndpointConnectionsClient.Get": + res.resp, res.err = c.dispatchGet(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *CloudHsmClusterPrivateEndpointConnectionsServerTransport) dispatchCreate(req *http.Request) (*http.Response, error) { + if c.srv.Create == nil { + return nil, &nonRetriableError{errors.New("fake for method Create not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HardwareSecurityModules/cloudHsmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/privateEndpointConnections/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armhardwaresecuritymodules.PrivateEndpointConnection](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudHsmClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudHsmClusterName")]) + if err != nil { + return nil, err + } + peConnectionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("peConnectionName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.Create(req.Context(), resourceGroupNameParam, cloudHsmClusterNameParam, peConnectionNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).PrivateEndpointConnection, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *CloudHsmClusterPrivateEndpointConnectionsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if c.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := c.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HardwareSecurityModules/cloudHsmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/privateEndpointConnections/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudHsmClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudHsmClusterName")]) + if err != nil { + return nil, err + } + peConnectionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("peConnectionName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginDelete(req.Context(), resourceGroupNameParam, cloudHsmClusterNameParam, peConnectionNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + c.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + c.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + c.beginDelete.remove(req) + } + + return resp, nil +} + +func (c *CloudHsmClusterPrivateEndpointConnectionsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if c.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HardwareSecurityModules/cloudHsmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/privateEndpointConnections/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudHsmClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudHsmClusterName")]) + if err != nil { + return nil, err + } + peConnectionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("peConnectionName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.Get(req.Context(), resourceGroupNameParam, cloudHsmClusterNameParam, peConnectionNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).PrivateEndpointConnection, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to CloudHsmClusterPrivateEndpointConnectionsServerTransport +var cloudHsmClusterPrivateEndpointConnectionsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armhardwaresecuritymodules/fake/zz_cloudhsmclusterprivatelinkresources_server.go b/test/local/armhardwaresecuritymodules/fake/zz_cloudhsmclusterprivatelinkresources_server.go new file mode 100644 index 000000000000..44573009389e --- /dev/null +++ b/test/local/armhardwaresecuritymodules/fake/zz_cloudhsmclusterprivatelinkresources_server.go @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armhardwaresecuritymodules" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// CloudHsmClusterPrivateLinkResourcesServer is a fake server for instances of the armhardwaresecuritymodules.CloudHsmClusterPrivateLinkResourcesClient type. +type CloudHsmClusterPrivateLinkResourcesServer struct { + // NewListByCloudHsmClusterPager is the fake for method CloudHsmClusterPrivateLinkResourcesClient.NewListByCloudHsmClusterPager + // HTTP status codes to indicate success: http.StatusOK + NewListByCloudHsmClusterPager func(resourceGroupName string, cloudHsmClusterName string, options *armhardwaresecuritymodules.CloudHsmClusterPrivateLinkResourcesClientListByCloudHsmClusterOptions) (resp azfake.PagerResponder[armhardwaresecuritymodules.CloudHsmClusterPrivateLinkResourcesClientListByCloudHsmClusterResponse]) +} + +// NewCloudHsmClusterPrivateLinkResourcesServerTransport creates a new instance of CloudHsmClusterPrivateLinkResourcesServerTransport with the provided implementation. +// The returned CloudHsmClusterPrivateLinkResourcesServerTransport instance is connected to an instance of armhardwaresecuritymodules.CloudHsmClusterPrivateLinkResourcesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewCloudHsmClusterPrivateLinkResourcesServerTransport(srv *CloudHsmClusterPrivateLinkResourcesServer) *CloudHsmClusterPrivateLinkResourcesServerTransport { + return &CloudHsmClusterPrivateLinkResourcesServerTransport{ + srv: srv, + newListByCloudHsmClusterPager: newTracker[azfake.PagerResponder[armhardwaresecuritymodules.CloudHsmClusterPrivateLinkResourcesClientListByCloudHsmClusterResponse]](), + } +} + +// CloudHsmClusterPrivateLinkResourcesServerTransport connects instances of armhardwaresecuritymodules.CloudHsmClusterPrivateLinkResourcesClient to instances of CloudHsmClusterPrivateLinkResourcesServer. +// Don't use this type directly, use NewCloudHsmClusterPrivateLinkResourcesServerTransport instead. +type CloudHsmClusterPrivateLinkResourcesServerTransport struct { + srv *CloudHsmClusterPrivateLinkResourcesServer + newListByCloudHsmClusterPager *tracker[azfake.PagerResponder[armhardwaresecuritymodules.CloudHsmClusterPrivateLinkResourcesClientListByCloudHsmClusterResponse]] +} + +// Do implements the policy.Transporter interface for CloudHsmClusterPrivateLinkResourcesServerTransport. +func (c *CloudHsmClusterPrivateLinkResourcesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *CloudHsmClusterPrivateLinkResourcesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if cloudHsmClusterPrivateLinkResourcesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = cloudHsmClusterPrivateLinkResourcesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "CloudHsmClusterPrivateLinkResourcesClient.NewListByCloudHsmClusterPager": + res.resp, res.err = c.dispatchNewListByCloudHsmClusterPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *CloudHsmClusterPrivateLinkResourcesServerTransport) dispatchNewListByCloudHsmClusterPager(req *http.Request) (*http.Response, error) { + if c.srv.NewListByCloudHsmClusterPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByCloudHsmClusterPager not implemented")} + } + newListByCloudHsmClusterPager := c.newListByCloudHsmClusterPager.get(req) + if newListByCloudHsmClusterPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HardwareSecurityModules/cloudHsmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/privateLinkResources` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudHsmClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudHsmClusterName")]) + if err != nil { + return nil, err + } + resp := c.srv.NewListByCloudHsmClusterPager(resourceGroupNameParam, cloudHsmClusterNameParam, nil) + newListByCloudHsmClusterPager = &resp + c.newListByCloudHsmClusterPager.add(req, newListByCloudHsmClusterPager) + server.PagerResponderInjectNextLinks(newListByCloudHsmClusterPager, req, func(page *armhardwaresecuritymodules.CloudHsmClusterPrivateLinkResourcesClientListByCloudHsmClusterResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByCloudHsmClusterPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + c.newListByCloudHsmClusterPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByCloudHsmClusterPager) { + c.newListByCloudHsmClusterPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to CloudHsmClusterPrivateLinkResourcesServerTransport +var cloudHsmClusterPrivateLinkResourcesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armhardwaresecuritymodules/fake/zz_cloudhsmclusterrestorestatus_server.go b/test/local/armhardwaresecuritymodules/fake/zz_cloudhsmclusterrestorestatus_server.go new file mode 100644 index 000000000000..35e3b8b50619 --- /dev/null +++ b/test/local/armhardwaresecuritymodules/fake/zz_cloudhsmclusterrestorestatus_server.go @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armhardwaresecuritymodules" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// CloudHsmClusterRestoreStatusServer is a fake server for instances of the armhardwaresecuritymodules.CloudHsmClusterRestoreStatusClient type. +type CloudHsmClusterRestoreStatusServer struct { + // Get is the fake for method CloudHsmClusterRestoreStatusClient.Get + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + Get func(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, jobID string, options *armhardwaresecuritymodules.CloudHsmClusterRestoreStatusClientGetOptions) (resp azfake.Responder[armhardwaresecuritymodules.CloudHsmClusterRestoreStatusClientGetResponse], errResp azfake.ErrorResponder) +} + +// NewCloudHsmClusterRestoreStatusServerTransport creates a new instance of CloudHsmClusterRestoreStatusServerTransport with the provided implementation. +// The returned CloudHsmClusterRestoreStatusServerTransport instance is connected to an instance of armhardwaresecuritymodules.CloudHsmClusterRestoreStatusClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewCloudHsmClusterRestoreStatusServerTransport(srv *CloudHsmClusterRestoreStatusServer) *CloudHsmClusterRestoreStatusServerTransport { + return &CloudHsmClusterRestoreStatusServerTransport{srv: srv} +} + +// CloudHsmClusterRestoreStatusServerTransport connects instances of armhardwaresecuritymodules.CloudHsmClusterRestoreStatusClient to instances of CloudHsmClusterRestoreStatusServer. +// Don't use this type directly, use NewCloudHsmClusterRestoreStatusServerTransport instead. +type CloudHsmClusterRestoreStatusServerTransport struct { + srv *CloudHsmClusterRestoreStatusServer +} + +// Do implements the policy.Transporter interface for CloudHsmClusterRestoreStatusServerTransport. +func (c *CloudHsmClusterRestoreStatusServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *CloudHsmClusterRestoreStatusServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if cloudHsmClusterRestoreStatusServerTransportInterceptor != nil { + res.resp, res.err, intercepted = cloudHsmClusterRestoreStatusServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "CloudHsmClusterRestoreStatusClient.Get": + res.resp, res.err = c.dispatchGet(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *CloudHsmClusterRestoreStatusServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if c.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HardwareSecurityModules/cloudHsmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/restoreOperationStatus/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudHsmClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudHsmClusterName")]) + if err != nil { + return nil, err + } + jobIDParam, err := url.PathUnescape(matches[regex.SubexpIndex("jobId")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.Get(req.Context(), resourceGroupNameParam, cloudHsmClusterNameParam, jobIDParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RestoreResult, req) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).Location; val != nil { + resp.Header.Set("Location", *val) + } + if val := server.GetResponse(respr).RequestID; val != nil { + resp.Header.Set("x-ms-request-id", *val) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to CloudHsmClusterRestoreStatusServerTransport +var cloudHsmClusterRestoreStatusServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armhardwaresecuritymodules/fake/zz_cloudhsmclusters_server.go b/test/local/armhardwaresecuritymodules/fake/zz_cloudhsmclusters_server.go new file mode 100644 index 000000000000..debab827cae8 --- /dev/null +++ b/test/local/armhardwaresecuritymodules/fake/zz_cloudhsmclusters_server.go @@ -0,0 +1,629 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armhardwaresecuritymodules" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "reflect" + "regexp" + "slices" +) + +// CloudHsmClustersServer is a fake server for instances of the armhardwaresecuritymodules.CloudHsmClustersClient type. +type CloudHsmClustersServer struct { + // BeginBackup is the fake for method CloudHsmClustersClient.BeginBackup + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginBackup func(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, options *armhardwaresecuritymodules.CloudHsmClustersClientBeginBackupOptions) (resp azfake.PollerResponder[armhardwaresecuritymodules.CloudHsmClustersClientBackupResponse], errResp azfake.ErrorResponder) + + // BeginCreateOrUpdate is the fake for method CloudHsmClustersClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, body armhardwaresecuritymodules.CloudHsmCluster, options *armhardwaresecuritymodules.CloudHsmClustersClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armhardwaresecuritymodules.CloudHsmClustersClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method CloudHsmClustersClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, options *armhardwaresecuritymodules.CloudHsmClustersClientBeginDeleteOptions) (resp azfake.PollerResponder[armhardwaresecuritymodules.CloudHsmClustersClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method CloudHsmClustersClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, options *armhardwaresecuritymodules.CloudHsmClustersClientGetOptions) (resp azfake.Responder[armhardwaresecuritymodules.CloudHsmClustersClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method CloudHsmClustersClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armhardwaresecuritymodules.CloudHsmClustersClientListByResourceGroupOptions) (resp azfake.PagerResponder[armhardwaresecuritymodules.CloudHsmClustersClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method CloudHsmClustersClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armhardwaresecuritymodules.CloudHsmClustersClientListBySubscriptionOptions) (resp azfake.PagerResponder[armhardwaresecuritymodules.CloudHsmClustersClientListBySubscriptionResponse]) + + // BeginRestore is the fake for method CloudHsmClustersClient.BeginRestore + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginRestore func(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, restoreRequestProperties armhardwaresecuritymodules.RestoreRequestProperties, options *armhardwaresecuritymodules.CloudHsmClustersClientBeginRestoreOptions) (resp azfake.PollerResponder[armhardwaresecuritymodules.CloudHsmClustersClientRestoreResponse], errResp azfake.ErrorResponder) + + // BeginUpdate is the fake for method CloudHsmClustersClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, body armhardwaresecuritymodules.CloudHsmClusterPatchParameters, options *armhardwaresecuritymodules.CloudHsmClustersClientBeginUpdateOptions) (resp azfake.PollerResponder[armhardwaresecuritymodules.CloudHsmClustersClientUpdateResponse], errResp azfake.ErrorResponder) + + // BeginValidateBackupProperties is the fake for method CloudHsmClustersClient.BeginValidateBackupProperties + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginValidateBackupProperties func(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, options *armhardwaresecuritymodules.CloudHsmClustersClientBeginValidateBackupPropertiesOptions) (resp azfake.PollerResponder[armhardwaresecuritymodules.CloudHsmClustersClientValidateBackupPropertiesResponse], errResp azfake.ErrorResponder) + + // BeginValidateRestoreProperties is the fake for method CloudHsmClustersClient.BeginValidateRestoreProperties + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginValidateRestoreProperties func(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, options *armhardwaresecuritymodules.CloudHsmClustersClientBeginValidateRestorePropertiesOptions) (resp azfake.PollerResponder[armhardwaresecuritymodules.CloudHsmClustersClientValidateRestorePropertiesResponse], errResp azfake.ErrorResponder) +} + +// NewCloudHsmClustersServerTransport creates a new instance of CloudHsmClustersServerTransport with the provided implementation. +// The returned CloudHsmClustersServerTransport instance is connected to an instance of armhardwaresecuritymodules.CloudHsmClustersClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewCloudHsmClustersServerTransport(srv *CloudHsmClustersServer) *CloudHsmClustersServerTransport { + return &CloudHsmClustersServerTransport{ + srv: srv, + beginBackup: newTracker[azfake.PollerResponder[armhardwaresecuritymodules.CloudHsmClustersClientBackupResponse]](), + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armhardwaresecuritymodules.CloudHsmClustersClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armhardwaresecuritymodules.CloudHsmClustersClientDeleteResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armhardwaresecuritymodules.CloudHsmClustersClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armhardwaresecuritymodules.CloudHsmClustersClientListBySubscriptionResponse]](), + beginRestore: newTracker[azfake.PollerResponder[armhardwaresecuritymodules.CloudHsmClustersClientRestoreResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armhardwaresecuritymodules.CloudHsmClustersClientUpdateResponse]](), + beginValidateBackupProperties: newTracker[azfake.PollerResponder[armhardwaresecuritymodules.CloudHsmClustersClientValidateBackupPropertiesResponse]](), + beginValidateRestoreProperties: newTracker[azfake.PollerResponder[armhardwaresecuritymodules.CloudHsmClustersClientValidateRestorePropertiesResponse]](), + } +} + +// CloudHsmClustersServerTransport connects instances of armhardwaresecuritymodules.CloudHsmClustersClient to instances of CloudHsmClustersServer. +// Don't use this type directly, use NewCloudHsmClustersServerTransport instead. +type CloudHsmClustersServerTransport struct { + srv *CloudHsmClustersServer + beginBackup *tracker[azfake.PollerResponder[armhardwaresecuritymodules.CloudHsmClustersClientBackupResponse]] + beginCreateOrUpdate *tracker[azfake.PollerResponder[armhardwaresecuritymodules.CloudHsmClustersClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armhardwaresecuritymodules.CloudHsmClustersClientDeleteResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armhardwaresecuritymodules.CloudHsmClustersClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armhardwaresecuritymodules.CloudHsmClustersClientListBySubscriptionResponse]] + beginRestore *tracker[azfake.PollerResponder[armhardwaresecuritymodules.CloudHsmClustersClientRestoreResponse]] + beginUpdate *tracker[azfake.PollerResponder[armhardwaresecuritymodules.CloudHsmClustersClientUpdateResponse]] + beginValidateBackupProperties *tracker[azfake.PollerResponder[armhardwaresecuritymodules.CloudHsmClustersClientValidateBackupPropertiesResponse]] + beginValidateRestoreProperties *tracker[azfake.PollerResponder[armhardwaresecuritymodules.CloudHsmClustersClientValidateRestorePropertiesResponse]] +} + +// Do implements the policy.Transporter interface for CloudHsmClustersServerTransport. +func (c *CloudHsmClustersServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *CloudHsmClustersServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if cloudHsmClustersServerTransportInterceptor != nil { + res.resp, res.err, intercepted = cloudHsmClustersServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "CloudHsmClustersClient.BeginBackup": + res.resp, res.err = c.dispatchBeginBackup(req) + case "CloudHsmClustersClient.BeginCreateOrUpdate": + res.resp, res.err = c.dispatchBeginCreateOrUpdate(req) + case "CloudHsmClustersClient.BeginDelete": + res.resp, res.err = c.dispatchBeginDelete(req) + case "CloudHsmClustersClient.Get": + res.resp, res.err = c.dispatchGet(req) + case "CloudHsmClustersClient.NewListByResourceGroupPager": + res.resp, res.err = c.dispatchNewListByResourceGroupPager(req) + case "CloudHsmClustersClient.NewListBySubscriptionPager": + res.resp, res.err = c.dispatchNewListBySubscriptionPager(req) + case "CloudHsmClustersClient.BeginRestore": + res.resp, res.err = c.dispatchBeginRestore(req) + case "CloudHsmClustersClient.BeginUpdate": + res.resp, res.err = c.dispatchBeginUpdate(req) + case "CloudHsmClustersClient.BeginValidateBackupProperties": + res.resp, res.err = c.dispatchBeginValidateBackupProperties(req) + case "CloudHsmClustersClient.BeginValidateRestoreProperties": + res.resp, res.err = c.dispatchBeginValidateRestoreProperties(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *CloudHsmClustersServerTransport) dispatchBeginBackup(req *http.Request) (*http.Response, error) { + if c.srv.BeginBackup == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginBackup not implemented")} + } + beginBackup := c.beginBackup.get(req) + if beginBackup == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HardwareSecurityModules/cloudHsmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/backup` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armhardwaresecuritymodules.BackupRequestProperties](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudHsmClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudHsmClusterName")]) + if err != nil { + return nil, err + } + var options *armhardwaresecuritymodules.CloudHsmClustersClientBeginBackupOptions + if !reflect.ValueOf(body).IsZero() { + options = &armhardwaresecuritymodules.CloudHsmClustersClientBeginBackupOptions{ + BackupRequestProperties: &body, + } + } + respr, errRespr := c.srv.BeginBackup(req.Context(), resourceGroupNameParam, cloudHsmClusterNameParam, options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginBackup = &respr + c.beginBackup.add(req, beginBackup) + } + + resp, err := server.PollerResponderNext(beginBackup, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + c.beginBackup.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginBackup) { + c.beginBackup.remove(req) + } + + return resp, nil +} + +func (c *CloudHsmClustersServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if c.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := c.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HardwareSecurityModules/cloudHsmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armhardwaresecuritymodules.CloudHsmCluster](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudHsmClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudHsmClusterName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, cloudHsmClusterNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + c.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + c.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + c.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (c *CloudHsmClustersServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if c.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := c.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HardwareSecurityModules/cloudHsmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudHsmClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudHsmClusterName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginDelete(req.Context(), resourceGroupNameParam, cloudHsmClusterNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + c.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + c.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + c.beginDelete.remove(req) + } + + return resp, nil +} + +func (c *CloudHsmClustersServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if c.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HardwareSecurityModules/cloudHsmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudHsmClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudHsmClusterName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.Get(req.Context(), resourceGroupNameParam, cloudHsmClusterNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CloudHsmCluster, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *CloudHsmClustersServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if c.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := c.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HardwareSecurityModules/cloudHsmClusters` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + skiptokenParam := getOptional(qp.Get("$skiptoken")) + var options *armhardwaresecuritymodules.CloudHsmClustersClientListByResourceGroupOptions + if skiptokenParam != nil { + options = &armhardwaresecuritymodules.CloudHsmClustersClientListByResourceGroupOptions{ + Skiptoken: skiptokenParam, + } + } + resp := c.srv.NewListByResourceGroupPager(resourceGroupNameParam, options) + newListByResourceGroupPager = &resp + c.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armhardwaresecuritymodules.CloudHsmClustersClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + c.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + c.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (c *CloudHsmClustersServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if c.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := c.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HardwareSecurityModules/cloudHsmClusters` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + skiptokenParam := getOptional(qp.Get("$skiptoken")) + var options *armhardwaresecuritymodules.CloudHsmClustersClientListBySubscriptionOptions + if skiptokenParam != nil { + options = &armhardwaresecuritymodules.CloudHsmClustersClientListBySubscriptionOptions{ + Skiptoken: skiptokenParam, + } + } + resp := c.srv.NewListBySubscriptionPager(options) + newListBySubscriptionPager = &resp + c.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armhardwaresecuritymodules.CloudHsmClustersClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + c.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + c.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (c *CloudHsmClustersServerTransport) dispatchBeginRestore(req *http.Request) (*http.Response, error) { + if c.srv.BeginRestore == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginRestore not implemented")} + } + beginRestore := c.beginRestore.get(req) + if beginRestore == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HardwareSecurityModules/cloudHsmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/restore` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armhardwaresecuritymodules.RestoreRequestProperties](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudHsmClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudHsmClusterName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginRestore(req.Context(), resourceGroupNameParam, cloudHsmClusterNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginRestore = &respr + c.beginRestore.add(req, beginRestore) + } + + resp, err := server.PollerResponderNext(beginRestore, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + c.beginRestore.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginRestore) { + c.beginRestore.remove(req) + } + + return resp, nil +} + +func (c *CloudHsmClustersServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if c.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := c.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HardwareSecurityModules/cloudHsmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armhardwaresecuritymodules.CloudHsmClusterPatchParameters](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudHsmClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudHsmClusterName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginUpdate(req.Context(), resourceGroupNameParam, cloudHsmClusterNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + c.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + c.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + c.beginUpdate.remove(req) + } + + return resp, nil +} + +func (c *CloudHsmClustersServerTransport) dispatchBeginValidateBackupProperties(req *http.Request) (*http.Response, error) { + if c.srv.BeginValidateBackupProperties == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginValidateBackupProperties not implemented")} + } + beginValidateBackupProperties := c.beginValidateBackupProperties.get(req) + if beginValidateBackupProperties == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HardwareSecurityModules/cloudHsmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/validateBackupProperties` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armhardwaresecuritymodules.BackupRequestProperties](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudHsmClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudHsmClusterName")]) + if err != nil { + return nil, err + } + var options *armhardwaresecuritymodules.CloudHsmClustersClientBeginValidateBackupPropertiesOptions + if !reflect.ValueOf(body).IsZero() { + options = &armhardwaresecuritymodules.CloudHsmClustersClientBeginValidateBackupPropertiesOptions{ + BackupRequestProperties: &body, + } + } + respr, errRespr := c.srv.BeginValidateBackupProperties(req.Context(), resourceGroupNameParam, cloudHsmClusterNameParam, options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginValidateBackupProperties = &respr + c.beginValidateBackupProperties.add(req, beginValidateBackupProperties) + } + + resp, err := server.PollerResponderNext(beginValidateBackupProperties, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + c.beginValidateBackupProperties.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginValidateBackupProperties) { + c.beginValidateBackupProperties.remove(req) + } + + return resp, nil +} + +func (c *CloudHsmClustersServerTransport) dispatchBeginValidateRestoreProperties(req *http.Request) (*http.Response, error) { + if c.srv.BeginValidateRestoreProperties == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginValidateRestoreProperties not implemented")} + } + beginValidateRestoreProperties := c.beginValidateRestoreProperties.get(req) + if beginValidateRestoreProperties == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HardwareSecurityModules/cloudHsmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/validateRestoreProperties` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armhardwaresecuritymodules.RestoreRequestProperties](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudHsmClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudHsmClusterName")]) + if err != nil { + return nil, err + } + var options *armhardwaresecuritymodules.CloudHsmClustersClientBeginValidateRestorePropertiesOptions + if !reflect.ValueOf(body).IsZero() { + options = &armhardwaresecuritymodules.CloudHsmClustersClientBeginValidateRestorePropertiesOptions{ + RestoreRequestProperties: &body, + } + } + respr, errRespr := c.srv.BeginValidateRestoreProperties(req.Context(), resourceGroupNameParam, cloudHsmClusterNameParam, options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginValidateRestoreProperties = &respr + c.beginValidateRestoreProperties.add(req, beginValidateRestoreProperties) + } + + resp, err := server.PollerResponderNext(beginValidateRestoreProperties, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + c.beginValidateRestoreProperties.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginValidateRestoreProperties) { + c.beginValidateRestoreProperties.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to CloudHsmClustersServerTransport +var cloudHsmClustersServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armhardwaresecuritymodules/fake/zz_dedicatedhsm_server.go b/test/local/armhardwaresecuritymodules/fake/zz_dedicatedhsm_server.go new file mode 100644 index 000000000000..078959060ce3 --- /dev/null +++ b/test/local/armhardwaresecuritymodules/fake/zz_dedicatedhsm_server.go @@ -0,0 +1,454 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armhardwaresecuritymodules" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" + "strconv" +) + +// DedicatedHsmServer is a fake server for instances of the armhardwaresecuritymodules.DedicatedHsmClient type. +type DedicatedHsmServer struct { + // BeginCreateOrUpdate is the fake for method DedicatedHsmClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, name string, parameters armhardwaresecuritymodules.DedicatedHsm, options *armhardwaresecuritymodules.DedicatedHsmClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armhardwaresecuritymodules.DedicatedHsmClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method DedicatedHsmClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, name string, options *armhardwaresecuritymodules.DedicatedHsmClientBeginDeleteOptions) (resp azfake.PollerResponder[armhardwaresecuritymodules.DedicatedHsmClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method DedicatedHsmClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, name string, options *armhardwaresecuritymodules.DedicatedHsmClientGetOptions) (resp azfake.Responder[armhardwaresecuritymodules.DedicatedHsmClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method DedicatedHsmClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armhardwaresecuritymodules.DedicatedHsmClientListByResourceGroupOptions) (resp azfake.PagerResponder[armhardwaresecuritymodules.DedicatedHsmClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method DedicatedHsmClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armhardwaresecuritymodules.DedicatedHsmClientListBySubscriptionOptions) (resp azfake.PagerResponder[armhardwaresecuritymodules.DedicatedHsmClientListBySubscriptionResponse]) + + // NewListOutboundNetworkDependenciesEndpointsPager is the fake for method DedicatedHsmClient.NewListOutboundNetworkDependenciesEndpointsPager + // HTTP status codes to indicate success: http.StatusOK + NewListOutboundNetworkDependenciesEndpointsPager func(resourceGroupName string, name string, options *armhardwaresecuritymodules.DedicatedHsmClientListOutboundNetworkDependenciesEndpointsOptions) (resp azfake.PagerResponder[armhardwaresecuritymodules.DedicatedHsmClientListOutboundNetworkDependenciesEndpointsResponse]) + + // BeginUpdate is the fake for method DedicatedHsmClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, name string, parameters armhardwaresecuritymodules.DedicatedHsmPatchParameters, options *armhardwaresecuritymodules.DedicatedHsmClientBeginUpdateOptions) (resp azfake.PollerResponder[armhardwaresecuritymodules.DedicatedHsmClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewDedicatedHsmServerTransport creates a new instance of DedicatedHsmServerTransport with the provided implementation. +// The returned DedicatedHsmServerTransport instance is connected to an instance of armhardwaresecuritymodules.DedicatedHsmClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDedicatedHsmServerTransport(srv *DedicatedHsmServer) *DedicatedHsmServerTransport { + return &DedicatedHsmServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armhardwaresecuritymodules.DedicatedHsmClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armhardwaresecuritymodules.DedicatedHsmClientDeleteResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armhardwaresecuritymodules.DedicatedHsmClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armhardwaresecuritymodules.DedicatedHsmClientListBySubscriptionResponse]](), + newListOutboundNetworkDependenciesEndpointsPager: newTracker[azfake.PagerResponder[armhardwaresecuritymodules.DedicatedHsmClientListOutboundNetworkDependenciesEndpointsResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armhardwaresecuritymodules.DedicatedHsmClientUpdateResponse]](), + } +} + +// DedicatedHsmServerTransport connects instances of armhardwaresecuritymodules.DedicatedHsmClient to instances of DedicatedHsmServer. +// Don't use this type directly, use NewDedicatedHsmServerTransport instead. +type DedicatedHsmServerTransport struct { + srv *DedicatedHsmServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armhardwaresecuritymodules.DedicatedHsmClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armhardwaresecuritymodules.DedicatedHsmClientDeleteResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armhardwaresecuritymodules.DedicatedHsmClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armhardwaresecuritymodules.DedicatedHsmClientListBySubscriptionResponse]] + newListOutboundNetworkDependenciesEndpointsPager *tracker[azfake.PagerResponder[armhardwaresecuritymodules.DedicatedHsmClientListOutboundNetworkDependenciesEndpointsResponse]] + beginUpdate *tracker[azfake.PollerResponder[armhardwaresecuritymodules.DedicatedHsmClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for DedicatedHsmServerTransport. +func (d *DedicatedHsmServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DedicatedHsmServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if dedicatedHsmServerTransportInterceptor != nil { + res.resp, res.err, intercepted = dedicatedHsmServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DedicatedHsmClient.BeginCreateOrUpdate": + res.resp, res.err = d.dispatchBeginCreateOrUpdate(req) + case "DedicatedHsmClient.BeginDelete": + res.resp, res.err = d.dispatchBeginDelete(req) + case "DedicatedHsmClient.Get": + res.resp, res.err = d.dispatchGet(req) + case "DedicatedHsmClient.NewListByResourceGroupPager": + res.resp, res.err = d.dispatchNewListByResourceGroupPager(req) + case "DedicatedHsmClient.NewListBySubscriptionPager": + res.resp, res.err = d.dispatchNewListBySubscriptionPager(req) + case "DedicatedHsmClient.NewListOutboundNetworkDependenciesEndpointsPager": + res.resp, res.err = d.dispatchNewListOutboundNetworkDependenciesEndpointsPager(req) + case "DedicatedHsmClient.BeginUpdate": + res.resp, res.err = d.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DedicatedHsmServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if d.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := d.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HardwareSecurityModules/dedicatedHSMs/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armhardwaresecuritymodules.DedicatedHsm](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("name")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, nameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + d.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + d.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + d.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (d *DedicatedHsmServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if d.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := d.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HardwareSecurityModules/dedicatedHSMs/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("name")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.BeginDelete(req.Context(), resourceGroupNameParam, nameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + d.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + d.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + d.beginDelete.remove(req) + } + + return resp, nil +} + +func (d *DedicatedHsmServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HardwareSecurityModules/dedicatedHSMs/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("name")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Get(req.Context(), resourceGroupNameParam, nameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DedicatedHsm, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DedicatedHsmServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if d.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := d.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HardwareSecurityModules/dedicatedHSMs` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + topParam, err := parseOptional(qp.Get("$top"), func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + var options *armhardwaresecuritymodules.DedicatedHsmClientListByResourceGroupOptions + if topParam != nil { + options = &armhardwaresecuritymodules.DedicatedHsmClientListByResourceGroupOptions{ + Top: topParam, + } + } + resp := d.srv.NewListByResourceGroupPager(resourceGroupNameParam, options) + newListByResourceGroupPager = &resp + d.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armhardwaresecuritymodules.DedicatedHsmClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + d.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + d.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (d *DedicatedHsmServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if d.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := d.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HardwareSecurityModules/dedicatedHSMs` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + topParam, err := parseOptional(qp.Get("$top"), func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + var options *armhardwaresecuritymodules.DedicatedHsmClientListBySubscriptionOptions + if topParam != nil { + options = &armhardwaresecuritymodules.DedicatedHsmClientListBySubscriptionOptions{ + Top: topParam, + } + } + resp := d.srv.NewListBySubscriptionPager(options) + newListBySubscriptionPager = &resp + d.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armhardwaresecuritymodules.DedicatedHsmClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + d.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + d.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (d *DedicatedHsmServerTransport) dispatchNewListOutboundNetworkDependenciesEndpointsPager(req *http.Request) (*http.Response, error) { + if d.srv.NewListOutboundNetworkDependenciesEndpointsPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListOutboundNetworkDependenciesEndpointsPager not implemented")} + } + newListOutboundNetworkDependenciesEndpointsPager := d.newListOutboundNetworkDependenciesEndpointsPager.get(req) + if newListOutboundNetworkDependenciesEndpointsPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HardwareSecurityModules/dedicatedHSMs/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/outboundNetworkDependenciesEndpoints` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("name")]) + if err != nil { + return nil, err + } + resp := d.srv.NewListOutboundNetworkDependenciesEndpointsPager(resourceGroupNameParam, nameParam, nil) + newListOutboundNetworkDependenciesEndpointsPager = &resp + d.newListOutboundNetworkDependenciesEndpointsPager.add(req, newListOutboundNetworkDependenciesEndpointsPager) + server.PagerResponderInjectNextLinks(newListOutboundNetworkDependenciesEndpointsPager, req, func(page *armhardwaresecuritymodules.DedicatedHsmClientListOutboundNetworkDependenciesEndpointsResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListOutboundNetworkDependenciesEndpointsPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + d.newListOutboundNetworkDependenciesEndpointsPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListOutboundNetworkDependenciesEndpointsPager) { + d.newListOutboundNetworkDependenciesEndpointsPager.remove(req) + } + return resp, nil +} + +func (d *DedicatedHsmServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if d.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := d.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HardwareSecurityModules/dedicatedHSMs/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armhardwaresecuritymodules.DedicatedHsmPatchParameters](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("name")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.BeginUpdate(req.Context(), resourceGroupNameParam, nameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + d.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + d.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + d.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to DedicatedHsmServerTransport +var dedicatedHsmServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armhardwaresecuritymodules/fake/zz_internal.go b/test/local/armhardwaresecuritymodules/fake/zz_internal.go new file mode 100644 index 000000000000..504fffe54caa --- /dev/null +++ b/test/local/armhardwaresecuritymodules/fake/zz_internal.go @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "reflect" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getOptional[T any](v T) *T { + if reflect.ValueOf(v).IsZero() { + return nil + } + return &v +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func parseOptional[T any](v string, parse func(v string) (T, error)) (*T, error) { + if v == "" { + return nil, nil + } + t, err := parse(v) + if err != nil { + return nil, err + } + return &t, nil +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/local/armhardwaresecuritymodules/fake/zz_operations_server.go b/test/local/armhardwaresecuritymodules/fake/zz_operations_server.go new file mode 100644 index 000000000000..74790d17843a --- /dev/null +++ b/test/local/armhardwaresecuritymodules/fake/zz_operations_server.go @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armhardwaresecuritymodules" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "slices" +) + +// OperationsServer is a fake server for instances of the armhardwaresecuritymodules.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armhardwaresecuritymodules.OperationsClientListOptions) (resp azfake.PagerResponder[armhardwaresecuritymodules.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of armhardwaresecuritymodules.OperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOperationsServerTransport(srv *OperationsServer) *OperationsServerTransport { + return &OperationsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armhardwaresecuritymodules.OperationsClientListResponse]](), + } +} + +// OperationsServerTransport connects instances of armhardwaresecuritymodules.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[armhardwaresecuritymodules.OperationsClientListResponse]] +} + +// Do implements the policy.Transporter interface for OperationsServerTransport. +func (o *OperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if operationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = operationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OperationsClient.NewListPager": + res.resp, res.err = o.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OperationsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := o.newListPager.get(req) + if newListPager == nil { + resp := o.srv.NewListPager(nil) + newListPager = &resp + o.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armhardwaresecuritymodules.OperationsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + o.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + o.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OperationsServerTransport +var operationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armhardwaresecuritymodules/fake/zz_privateendpointconnections_server.go b/test/local/armhardwaresecuritymodules/fake/zz_privateendpointconnections_server.go new file mode 100644 index 000000000000..6d7b36b02614 --- /dev/null +++ b/test/local/armhardwaresecuritymodules/fake/zz_privateendpointconnections_server.go @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armhardwaresecuritymodules" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// PrivateEndpointConnectionsServer is a fake server for instances of the armhardwaresecuritymodules.PrivateEndpointConnectionsClient type. +type PrivateEndpointConnectionsServer struct { + // NewListByCloudHsmClusterPager is the fake for method PrivateEndpointConnectionsClient.NewListByCloudHsmClusterPager + // HTTP status codes to indicate success: http.StatusOK + NewListByCloudHsmClusterPager func(resourceGroupName string, cloudHsmClusterName string, options *armhardwaresecuritymodules.PrivateEndpointConnectionsClientListByCloudHsmClusterOptions) (resp azfake.PagerResponder[armhardwaresecuritymodules.PrivateEndpointConnectionsClientListByCloudHsmClusterResponse]) +} + +// NewPrivateEndpointConnectionsServerTransport creates a new instance of PrivateEndpointConnectionsServerTransport with the provided implementation. +// The returned PrivateEndpointConnectionsServerTransport instance is connected to an instance of armhardwaresecuritymodules.PrivateEndpointConnectionsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewPrivateEndpointConnectionsServerTransport(srv *PrivateEndpointConnectionsServer) *PrivateEndpointConnectionsServerTransport { + return &PrivateEndpointConnectionsServerTransport{ + srv: srv, + newListByCloudHsmClusterPager: newTracker[azfake.PagerResponder[armhardwaresecuritymodules.PrivateEndpointConnectionsClientListByCloudHsmClusterResponse]](), + } +} + +// PrivateEndpointConnectionsServerTransport connects instances of armhardwaresecuritymodules.PrivateEndpointConnectionsClient to instances of PrivateEndpointConnectionsServer. +// Don't use this type directly, use NewPrivateEndpointConnectionsServerTransport instead. +type PrivateEndpointConnectionsServerTransport struct { + srv *PrivateEndpointConnectionsServer + newListByCloudHsmClusterPager *tracker[azfake.PagerResponder[armhardwaresecuritymodules.PrivateEndpointConnectionsClientListByCloudHsmClusterResponse]] +} + +// Do implements the policy.Transporter interface for PrivateEndpointConnectionsServerTransport. +func (p *PrivateEndpointConnectionsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return p.dispatchToMethodFake(req, method) +} + +func (p *PrivateEndpointConnectionsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if privateEndpointConnectionsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = privateEndpointConnectionsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "PrivateEndpointConnectionsClient.NewListByCloudHsmClusterPager": + res.resp, res.err = p.dispatchNewListByCloudHsmClusterPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (p *PrivateEndpointConnectionsServerTransport) dispatchNewListByCloudHsmClusterPager(req *http.Request) (*http.Response, error) { + if p.srv.NewListByCloudHsmClusterPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByCloudHsmClusterPager not implemented")} + } + newListByCloudHsmClusterPager := p.newListByCloudHsmClusterPager.get(req) + if newListByCloudHsmClusterPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HardwareSecurityModules/cloudHsmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/privateEndpointConnections` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudHsmClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudHsmClusterName")]) + if err != nil { + return nil, err + } + resp := p.srv.NewListByCloudHsmClusterPager(resourceGroupNameParam, cloudHsmClusterNameParam, nil) + newListByCloudHsmClusterPager = &resp + p.newListByCloudHsmClusterPager.add(req, newListByCloudHsmClusterPager) + server.PagerResponderInjectNextLinks(newListByCloudHsmClusterPager, req, func(page *armhardwaresecuritymodules.PrivateEndpointConnectionsClientListByCloudHsmClusterResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByCloudHsmClusterPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newListByCloudHsmClusterPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByCloudHsmClusterPager) { + p.newListByCloudHsmClusterPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to PrivateEndpointConnectionsServerTransport +var privateEndpointConnectionsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armhardwaresecuritymodules/fake/zz_server_factory.go b/test/local/armhardwaresecuritymodules/fake/zz_server_factory.go new file mode 100644 index 000000000000..f997afeb2904 --- /dev/null +++ b/test/local/armhardwaresecuritymodules/fake/zz_server_factory.go @@ -0,0 +1,125 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armhardwaresecuritymodules.ClientFactory type. +type ServerFactory struct { + // CloudHsmClusterBackupStatusServer contains the fakes for client CloudHsmClusterBackupStatusClient + CloudHsmClusterBackupStatusServer CloudHsmClusterBackupStatusServer + + // CloudHsmClusterPrivateEndpointConnectionsServer contains the fakes for client CloudHsmClusterPrivateEndpointConnectionsClient + CloudHsmClusterPrivateEndpointConnectionsServer CloudHsmClusterPrivateEndpointConnectionsServer + + // CloudHsmClusterPrivateLinkResourcesServer contains the fakes for client CloudHsmClusterPrivateLinkResourcesClient + CloudHsmClusterPrivateLinkResourcesServer CloudHsmClusterPrivateLinkResourcesServer + + // CloudHsmClusterRestoreStatusServer contains the fakes for client CloudHsmClusterRestoreStatusClient + CloudHsmClusterRestoreStatusServer CloudHsmClusterRestoreStatusServer + + // CloudHsmClustersServer contains the fakes for client CloudHsmClustersClient + CloudHsmClustersServer CloudHsmClustersServer + + // DedicatedHsmServer contains the fakes for client DedicatedHsmClient + DedicatedHsmServer DedicatedHsmServer + + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer + + // PrivateEndpointConnectionsServer contains the fakes for client PrivateEndpointConnectionsClient + PrivateEndpointConnectionsServer PrivateEndpointConnectionsServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armhardwaresecuritymodules.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of armhardwaresecuritymodules.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trCloudHsmClusterBackupStatusServer *CloudHsmClusterBackupStatusServerTransport + trCloudHsmClusterPrivateEndpointConnectionsServer *CloudHsmClusterPrivateEndpointConnectionsServerTransport + trCloudHsmClusterPrivateLinkResourcesServer *CloudHsmClusterPrivateLinkResourcesServerTransport + trCloudHsmClusterRestoreStatusServer *CloudHsmClusterRestoreStatusServerTransport + trCloudHsmClustersServer *CloudHsmClustersServerTransport + trDedicatedHsmServer *DedicatedHsmServerTransport + trOperationsServer *OperationsServerTransport + trPrivateEndpointConnectionsServer *PrivateEndpointConnectionsServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "CloudHsmClusterBackupStatusClient": + initServer(&s.trMu, &s.trCloudHsmClusterBackupStatusServer, func() *CloudHsmClusterBackupStatusServerTransport { + return NewCloudHsmClusterBackupStatusServerTransport(&s.srv.CloudHsmClusterBackupStatusServer) + }) + resp, err = s.trCloudHsmClusterBackupStatusServer.Do(req) + case "CloudHsmClusterPrivateEndpointConnectionsClient": + initServer(&s.trMu, &s.trCloudHsmClusterPrivateEndpointConnectionsServer, func() *CloudHsmClusterPrivateEndpointConnectionsServerTransport { + return NewCloudHsmClusterPrivateEndpointConnectionsServerTransport(&s.srv.CloudHsmClusterPrivateEndpointConnectionsServer) + }) + resp, err = s.trCloudHsmClusterPrivateEndpointConnectionsServer.Do(req) + case "CloudHsmClusterPrivateLinkResourcesClient": + initServer(&s.trMu, &s.trCloudHsmClusterPrivateLinkResourcesServer, func() *CloudHsmClusterPrivateLinkResourcesServerTransport { + return NewCloudHsmClusterPrivateLinkResourcesServerTransport(&s.srv.CloudHsmClusterPrivateLinkResourcesServer) + }) + resp, err = s.trCloudHsmClusterPrivateLinkResourcesServer.Do(req) + case "CloudHsmClusterRestoreStatusClient": + initServer(&s.trMu, &s.trCloudHsmClusterRestoreStatusServer, func() *CloudHsmClusterRestoreStatusServerTransport { + return NewCloudHsmClusterRestoreStatusServerTransport(&s.srv.CloudHsmClusterRestoreStatusServer) + }) + resp, err = s.trCloudHsmClusterRestoreStatusServer.Do(req) + case "CloudHsmClustersClient": + initServer(&s.trMu, &s.trCloudHsmClustersServer, func() *CloudHsmClustersServerTransport { + return NewCloudHsmClustersServerTransport(&s.srv.CloudHsmClustersServer) + }) + resp, err = s.trCloudHsmClustersServer.Do(req) + case "DedicatedHsmClient": + initServer(&s.trMu, &s.trDedicatedHsmServer, func() *DedicatedHsmServerTransport { return NewDedicatedHsmServerTransport(&s.srv.DedicatedHsmServer) }) + resp, err = s.trDedicatedHsmServer.Do(req) + case "OperationsClient": + initServer(&s.trMu, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + resp, err = s.trOperationsServer.Do(req) + case "PrivateEndpointConnectionsClient": + initServer(&s.trMu, &s.trPrivateEndpointConnectionsServer, func() *PrivateEndpointConnectionsServerTransport { + return NewPrivateEndpointConnectionsServerTransport(&s.srv.PrivateEndpointConnectionsServer) + }) + resp, err = s.trPrivateEndpointConnectionsServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} diff --git a/test/local/armhardwaresecuritymodules/go.mod b/test/local/armhardwaresecuritymodules/go.mod new file mode 100644 index 000000000000..f5b67416dc76 --- /dev/null +++ b/test/local/armhardwaresecuritymodules/go.mod @@ -0,0 +1,11 @@ +module armhardwaresecuritymodules + +go 1.25.0 + +require github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect +) diff --git a/test/local/armhardwaresecuritymodules/go.sum b/test/local/armhardwaresecuritymodules/go.sum new file mode 100644 index 000000000000..3fdb64caf441 --- /dev/null +++ b/test/local/armhardwaresecuritymodules/go.sum @@ -0,0 +1,16 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/local/armhardwaresecuritymodules/testdata/_metadata.json b/test/local/armhardwaresecuritymodules/testdata/_metadata.json new file mode 100644 index 000000000000..5b41667385f9 --- /dev/null +++ b/test/local/armhardwaresecuritymodules/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Microsoft.HardwareSecurityModules": "2025-03-31" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/local/armhardwaresecuritymodules/zz_client_factory.go b/test/local/armhardwaresecuritymodules/zz_client_factory.go new file mode 100644 index 000000000000..9c15bf2f580c --- /dev/null +++ b/test/local/armhardwaresecuritymodules/zz_client_factory.go @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armhardwaresecuritymodules + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + subscriptionID string + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, + internal: internal, + }, nil +} + +// NewCloudHsmClusterBackupStatusClient creates a new instance of CloudHsmClusterBackupStatusClient. +func (c *ClientFactory) NewCloudHsmClusterBackupStatusClient() *CloudHsmClusterBackupStatusClient { + return &CloudHsmClusterBackupStatusClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewCloudHsmClusterPrivateEndpointConnectionsClient creates a new instance of CloudHsmClusterPrivateEndpointConnectionsClient. +func (c *ClientFactory) NewCloudHsmClusterPrivateEndpointConnectionsClient() *CloudHsmClusterPrivateEndpointConnectionsClient { + return &CloudHsmClusterPrivateEndpointConnectionsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewCloudHsmClusterPrivateLinkResourcesClient creates a new instance of CloudHsmClusterPrivateLinkResourcesClient. +func (c *ClientFactory) NewCloudHsmClusterPrivateLinkResourcesClient() *CloudHsmClusterPrivateLinkResourcesClient { + return &CloudHsmClusterPrivateLinkResourcesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewCloudHsmClusterRestoreStatusClient creates a new instance of CloudHsmClusterRestoreStatusClient. +func (c *ClientFactory) NewCloudHsmClusterRestoreStatusClient() *CloudHsmClusterRestoreStatusClient { + return &CloudHsmClusterRestoreStatusClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewCloudHsmClustersClient creates a new instance of CloudHsmClustersClient. +func (c *ClientFactory) NewCloudHsmClustersClient() *CloudHsmClustersClient { + return &CloudHsmClustersClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewDedicatedHsmClient creates a new instance of DedicatedHsmClient. +func (c *ClientFactory) NewDedicatedHsmClient() *DedicatedHsmClient { + return &DedicatedHsmClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: c.internal, + } +} + +// NewPrivateEndpointConnectionsClient creates a new instance of PrivateEndpointConnectionsClient. +func (c *ClientFactory) NewPrivateEndpointConnectionsClient() *PrivateEndpointConnectionsClient { + return &PrivateEndpointConnectionsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} diff --git a/test/local/armhardwaresecuritymodules/zz_cloudhsmclusterbackupstatus_client.go b/test/local/armhardwaresecuritymodules/zz_cloudhsmclusterbackupstatus_client.go new file mode 100644 index 000000000000..eaef7f8faff0 --- /dev/null +++ b/test/local/armhardwaresecuritymodules/zz_cloudhsmclusterbackupstatus_client.go @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armhardwaresecuritymodules + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// CloudHsmClusterBackupStatusClient contains the methods for the CloudHsmClusterBackupStatus group. +// Don't use this type directly, use NewCloudHsmClusterBackupStatusClient() instead. +// +// Generated from API version 2025-03-31 +type CloudHsmClusterBackupStatusClient struct { + internal *arm.Client + subscriptionID string +} + +// NewCloudHsmClusterBackupStatusClient creates a new instance of CloudHsmClusterBackupStatusClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewCloudHsmClusterBackupStatusClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CloudHsmClusterBackupStatusClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CloudHsmClusterBackupStatusClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Gets the backup operation status of the specified Cloud HSM Cluster +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudHsmClusterName - The name of the Cloud HSM Cluster within the specified resource group. Cloud HSM Cluster names must +// be between 3 and 23 characters in length. +// - jobID - Identifier for the backup operation +// - options - CloudHsmClusterBackupStatusClientGetOptions contains the optional parameters for the CloudHsmClusterBackupStatusClient.Get +// method. +func (client *CloudHsmClusterBackupStatusClient) Get(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, jobID string, options *CloudHsmClusterBackupStatusClientGetOptions) (CloudHsmClusterBackupStatusClientGetResponse, error) { + var err error + const operationName = "CloudHsmClusterBackupStatusClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, cloudHsmClusterName, jobID, options) + if err != nil { + return CloudHsmClusterBackupStatusClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CloudHsmClusterBackupStatusClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return CloudHsmClusterBackupStatusClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *CloudHsmClusterBackupStatusClient) getCreateRequest(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, jobID string, _ *CloudHsmClusterBackupStatusClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HardwareSecurityModules/cloudHsmClusters/{cloudHsmClusterName}/backupOperationStatus/{jobId}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudHsmClusterName == "" { + return nil, errors.New("parameter cloudHsmClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudHsmClusterName}", url.PathEscape(cloudHsmClusterName)) + if jobID == "" { + return nil, errors.New("parameter jobID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobId}", url.PathEscape(jobID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250331) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *CloudHsmClusterBackupStatusClient) getHandleResponse(resp *http.Response) (CloudHsmClusterBackupStatusClientGetResponse, error) { + result := CloudHsmClusterBackupStatusClientGetResponse{} + if val := resp.Header.Get("Location"); val != "" { + result.Location = &val + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.BackupResult); err != nil { + return CloudHsmClusterBackupStatusClientGetResponse{}, err + } + return result, nil +} diff --git a/test/local/armhardwaresecuritymodules/zz_cloudhsmclusterprivateendpointconnections_client.go b/test/local/armhardwaresecuritymodules/zz_cloudhsmclusterprivateendpointconnections_client.go new file mode 100644 index 000000000000..3c16511fe1c8 --- /dev/null +++ b/test/local/armhardwaresecuritymodules/zz_cloudhsmclusterprivateendpointconnections_client.go @@ -0,0 +1,263 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armhardwaresecuritymodules + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// CloudHsmClusterPrivateEndpointConnectionsClient contains the methods for the CloudHsmClusterPrivateEndpointConnections +// group. +// Don't use this type directly, use NewCloudHsmClusterPrivateEndpointConnectionsClient() instead. +// +// Generated from API version 2025-03-31 +type CloudHsmClusterPrivateEndpointConnectionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewCloudHsmClusterPrivateEndpointConnectionsClient creates a new instance of CloudHsmClusterPrivateEndpointConnectionsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewCloudHsmClusterPrivateEndpointConnectionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CloudHsmClusterPrivateEndpointConnectionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CloudHsmClusterPrivateEndpointConnectionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Create - Creates or updates the private endpoint connection for the Cloud Hsm Cluster. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudHsmClusterName - The name of the Cloud HSM Cluster within the specified resource group. Cloud HSM Cluster names must +// be between 3 and 23 characters in length. +// - peConnectionName - Name of the private endpoint connection associated with the Cloud HSM Cluster. +// - properties - Parameters of the PrivateEndpointConnection +// - options - CloudHsmClusterPrivateEndpointConnectionsClientCreateOptions contains the optional parameters for the CloudHsmClusterPrivateEndpointConnectionsClient.Create +// method. +func (client *CloudHsmClusterPrivateEndpointConnectionsClient) Create(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, peConnectionName string, properties PrivateEndpointConnection, options *CloudHsmClusterPrivateEndpointConnectionsClientCreateOptions) (CloudHsmClusterPrivateEndpointConnectionsClientCreateResponse, error) { + var err error + const operationName = "CloudHsmClusterPrivateEndpointConnectionsClient.Create" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, cloudHsmClusterName, peConnectionName, properties, options) + if err != nil { + return CloudHsmClusterPrivateEndpointConnectionsClientCreateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CloudHsmClusterPrivateEndpointConnectionsClientCreateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CloudHsmClusterPrivateEndpointConnectionsClientCreateResponse{}, err + } + resp, err := client.createHandleResponse(httpResp) + return resp, err +} + +// createCreateRequest creates the Create request. +func (client *CloudHsmClusterPrivateEndpointConnectionsClient) createCreateRequest(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, peConnectionName string, properties PrivateEndpointConnection, _ *CloudHsmClusterPrivateEndpointConnectionsClientCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HardwareSecurityModules/cloudHsmClusters/{cloudHsmClusterName}/privateEndpointConnections/{peConnectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudHsmClusterName == "" { + return nil, errors.New("parameter cloudHsmClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudHsmClusterName}", url.PathEscape(cloudHsmClusterName)) + if peConnectionName == "" { + return nil, errors.New("parameter peConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peConnectionName}", url.PathEscape(peConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250331) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} + +// createHandleResponse handles the Create response. +func (client *CloudHsmClusterPrivateEndpointConnectionsClient) createHandleResponse(resp *http.Response) (CloudHsmClusterPrivateEndpointConnectionsClientCreateResponse, error) { + result := CloudHsmClusterPrivateEndpointConnectionsClientCreateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnection); err != nil { + return CloudHsmClusterPrivateEndpointConnectionsClientCreateResponse{}, err + } + return result, nil +} + +// BeginDelete - Deletes the private endpoint connection for the Cloud Hsm Cluster. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudHsmClusterName - The name of the Cloud HSM Cluster within the specified resource group. Cloud HSM Cluster names must +// be between 3 and 23 characters in length. +// - peConnectionName - Name of the private endpoint connection associated with the Cloud HSM Cluster. +// - options - CloudHsmClusterPrivateEndpointConnectionsClientBeginDeleteOptions contains the optional parameters for the CloudHsmClusterPrivateEndpointConnectionsClient.BeginDelete +// method. +func (client *CloudHsmClusterPrivateEndpointConnectionsClient) BeginDelete(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, peConnectionName string, options *CloudHsmClusterPrivateEndpointConnectionsClientBeginDeleteOptions) (*runtime.Poller[CloudHsmClusterPrivateEndpointConnectionsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, cloudHsmClusterName, peConnectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudHsmClusterPrivateEndpointConnectionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudHsmClusterPrivateEndpointConnectionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the private endpoint connection for the Cloud Hsm Cluster. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CloudHsmClusterPrivateEndpointConnectionsClient) deleteOperation(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, peConnectionName string, options *CloudHsmClusterPrivateEndpointConnectionsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "CloudHsmClusterPrivateEndpointConnectionsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, cloudHsmClusterName, peConnectionName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *CloudHsmClusterPrivateEndpointConnectionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, peConnectionName string, _ *CloudHsmClusterPrivateEndpointConnectionsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HardwareSecurityModules/cloudHsmClusters/{cloudHsmClusterName}/privateEndpointConnections/{peConnectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudHsmClusterName == "" { + return nil, errors.New("parameter cloudHsmClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudHsmClusterName}", url.PathEscape(cloudHsmClusterName)) + if peConnectionName == "" { + return nil, errors.New("parameter peConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peConnectionName}", url.PathEscape(peConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250331) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Gets the private endpoint connection for the Cloud Hsm Cluster. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudHsmClusterName - The name of the Cloud HSM Cluster within the specified resource group. Cloud HSM Cluster names must +// be between 3 and 23 characters in length. +// - peConnectionName - Name of the private endpoint connection associated with the Cloud HSM Cluster. +// - options - CloudHsmClusterPrivateEndpointConnectionsClientGetOptions contains the optional parameters for the CloudHsmClusterPrivateEndpointConnectionsClient.Get +// method. +func (client *CloudHsmClusterPrivateEndpointConnectionsClient) Get(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, peConnectionName string, options *CloudHsmClusterPrivateEndpointConnectionsClientGetOptions) (CloudHsmClusterPrivateEndpointConnectionsClientGetResponse, error) { + var err error + const operationName = "CloudHsmClusterPrivateEndpointConnectionsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, cloudHsmClusterName, peConnectionName, options) + if err != nil { + return CloudHsmClusterPrivateEndpointConnectionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CloudHsmClusterPrivateEndpointConnectionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CloudHsmClusterPrivateEndpointConnectionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *CloudHsmClusterPrivateEndpointConnectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, peConnectionName string, _ *CloudHsmClusterPrivateEndpointConnectionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HardwareSecurityModules/cloudHsmClusters/{cloudHsmClusterName}/privateEndpointConnections/{peConnectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudHsmClusterName == "" { + return nil, errors.New("parameter cloudHsmClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudHsmClusterName}", url.PathEscape(cloudHsmClusterName)) + if peConnectionName == "" { + return nil, errors.New("parameter peConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peConnectionName}", url.PathEscape(peConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250331) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *CloudHsmClusterPrivateEndpointConnectionsClient) getHandleResponse(resp *http.Response) (CloudHsmClusterPrivateEndpointConnectionsClientGetResponse, error) { + result := CloudHsmClusterPrivateEndpointConnectionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnection); err != nil { + return CloudHsmClusterPrivateEndpointConnectionsClientGetResponse{}, err + } + return result, nil +} diff --git a/test/local/armhardwaresecuritymodules/zz_cloudhsmclusterprivatelinkresources_client.go b/test/local/armhardwaresecuritymodules/zz_cloudhsmclusterprivatelinkresources_client.go new file mode 100644 index 000000000000..15c06e0f4795 --- /dev/null +++ b/test/local/armhardwaresecuritymodules/zz_cloudhsmclusterprivatelinkresources_client.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armhardwaresecuritymodules + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// CloudHsmClusterPrivateLinkResourcesClient contains the methods for the CloudHsmClusterPrivateLinkResources group. +// Don't use this type directly, use NewCloudHsmClusterPrivateLinkResourcesClient() instead. +// +// Generated from API version 2025-03-31 +type CloudHsmClusterPrivateLinkResourcesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewCloudHsmClusterPrivateLinkResourcesClient creates a new instance of CloudHsmClusterPrivateLinkResourcesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewCloudHsmClusterPrivateLinkResourcesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CloudHsmClusterPrivateLinkResourcesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CloudHsmClusterPrivateLinkResourcesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListByCloudHsmClusterPager - Gets the private link resources supported for the Cloud Hsm Cluster. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudHsmClusterName - The name of the Cloud HSM Cluster within the specified resource group. Cloud HSM Cluster names must +// be between 3 and 23 characters in length. +// - options - CloudHsmClusterPrivateLinkResourcesClientListByCloudHsmClusterOptions contains the optional parameters for the +// CloudHsmClusterPrivateLinkResourcesClient.NewListByCloudHsmClusterPager method. +func (client *CloudHsmClusterPrivateLinkResourcesClient) NewListByCloudHsmClusterPager(resourceGroupName string, cloudHsmClusterName string, options *CloudHsmClusterPrivateLinkResourcesClientListByCloudHsmClusterOptions) *runtime.Pager[CloudHsmClusterPrivateLinkResourcesClientListByCloudHsmClusterResponse] { + return runtime.NewPager(runtime.PagingHandler[CloudHsmClusterPrivateLinkResourcesClientListByCloudHsmClusterResponse]{ + More: func(page CloudHsmClusterPrivateLinkResourcesClientListByCloudHsmClusterResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CloudHsmClusterPrivateLinkResourcesClientListByCloudHsmClusterResponse) (CloudHsmClusterPrivateLinkResourcesClientListByCloudHsmClusterResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CloudHsmClusterPrivateLinkResourcesClient.NewListByCloudHsmClusterPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByCloudHsmClusterCreateRequest(ctx, resourceGroupName, cloudHsmClusterName, options) + }, nil) + if err != nil { + return CloudHsmClusterPrivateLinkResourcesClientListByCloudHsmClusterResponse{}, err + } + return client.listByCloudHsmClusterHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByCloudHsmClusterCreateRequest creates the ListByCloudHsmCluster request. +func (client *CloudHsmClusterPrivateLinkResourcesClient) listByCloudHsmClusterCreateRequest(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, _ *CloudHsmClusterPrivateLinkResourcesClientListByCloudHsmClusterOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HardwareSecurityModules/cloudHsmClusters/{cloudHsmClusterName}/privateLinkResources" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudHsmClusterName == "" { + return nil, errors.New("parameter cloudHsmClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudHsmClusterName}", url.PathEscape(cloudHsmClusterName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250331) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByCloudHsmClusterHandleResponse handles the ListByCloudHsmCluster response. +func (client *CloudHsmClusterPrivateLinkResourcesClient) listByCloudHsmClusterHandleResponse(resp *http.Response) (CloudHsmClusterPrivateLinkResourcesClientListByCloudHsmClusterResponse, error) { + result := CloudHsmClusterPrivateLinkResourcesClientListByCloudHsmClusterResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateLinkResourceListResult); err != nil { + return CloudHsmClusterPrivateLinkResourcesClientListByCloudHsmClusterResponse{}, err + } + return result, nil +} diff --git a/test/local/armhardwaresecuritymodules/zz_cloudhsmclusterrestorestatus_client.go b/test/local/armhardwaresecuritymodules/zz_cloudhsmclusterrestorestatus_client.go new file mode 100644 index 000000000000..278a7bb24e2f --- /dev/null +++ b/test/local/armhardwaresecuritymodules/zz_cloudhsmclusterrestorestatus_client.go @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armhardwaresecuritymodules + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// CloudHsmClusterRestoreStatusClient contains the methods for the CloudHsmClusterRestoreStatus group. +// Don't use this type directly, use NewCloudHsmClusterRestoreStatusClient() instead. +// +// Generated from API version 2025-03-31 +type CloudHsmClusterRestoreStatusClient struct { + internal *arm.Client + subscriptionID string +} + +// NewCloudHsmClusterRestoreStatusClient creates a new instance of CloudHsmClusterRestoreStatusClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewCloudHsmClusterRestoreStatusClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CloudHsmClusterRestoreStatusClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CloudHsmClusterRestoreStatusClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Gets the restore operation status of the specified Cloud HSM Cluster +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudHsmClusterName - The name of the Cloud HSM Cluster within the specified resource group. Cloud HSM Cluster names must +// be between 3 and 23 characters in length. +// - jobID - Identifier for the restore operation +// - options - CloudHsmClusterRestoreStatusClientGetOptions contains the optional parameters for the CloudHsmClusterRestoreStatusClient.Get +// method. +func (client *CloudHsmClusterRestoreStatusClient) Get(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, jobID string, options *CloudHsmClusterRestoreStatusClientGetOptions) (CloudHsmClusterRestoreStatusClientGetResponse, error) { + var err error + const operationName = "CloudHsmClusterRestoreStatusClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, cloudHsmClusterName, jobID, options) + if err != nil { + return CloudHsmClusterRestoreStatusClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CloudHsmClusterRestoreStatusClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return CloudHsmClusterRestoreStatusClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *CloudHsmClusterRestoreStatusClient) getCreateRequest(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, jobID string, _ *CloudHsmClusterRestoreStatusClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HardwareSecurityModules/cloudHsmClusters/{cloudHsmClusterName}/restoreOperationStatus/{jobId}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudHsmClusterName == "" { + return nil, errors.New("parameter cloudHsmClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudHsmClusterName}", url.PathEscape(cloudHsmClusterName)) + if jobID == "" { + return nil, errors.New("parameter jobID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobId}", url.PathEscape(jobID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250331) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *CloudHsmClusterRestoreStatusClient) getHandleResponse(resp *http.Response) (CloudHsmClusterRestoreStatusClientGetResponse, error) { + result := CloudHsmClusterRestoreStatusClientGetResponse{} + if val := resp.Header.Get("Location"); val != "" { + result.Location = &val + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.RestoreResult); err != nil { + return CloudHsmClusterRestoreStatusClientGetResponse{}, err + } + return result, nil +} diff --git a/test/local/armhardwaresecuritymodules/zz_cloudhsmclusters_client.go b/test/local/armhardwaresecuritymodules/zz_cloudhsmclusters_client.go new file mode 100644 index 000000000000..3a078de82253 --- /dev/null +++ b/test/local/armhardwaresecuritymodules/zz_cloudhsmclusters_client.go @@ -0,0 +1,772 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armhardwaresecuritymodules + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// CloudHsmClustersClient contains the methods for the CloudHsmClusters group. +// Don't use this type directly, use NewCloudHsmClustersClient() instead. +// +// Generated from API version 2025-03-31 +type CloudHsmClustersClient struct { + internal *arm.Client + subscriptionID string +} + +// NewCloudHsmClustersClient creates a new instance of CloudHsmClustersClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewCloudHsmClustersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CloudHsmClustersClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CloudHsmClustersClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginBackup - Create a backup of the Cloud HSM Cluster in the specified subscription +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudHsmClusterName - The name of the Cloud HSM Cluster within the specified resource group. Cloud HSM Cluster names must +// be between 3 and 23 characters in length. +// - options - CloudHsmClustersClientBeginBackupOptions contains the optional parameters for the CloudHsmClustersClient.BeginBackup +// method. +func (client *CloudHsmClustersClient) BeginBackup(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, options *CloudHsmClustersClientBeginBackupOptions) (*runtime.Poller[CloudHsmClustersClientBackupResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.backup(ctx, resourceGroupName, cloudHsmClusterName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudHsmClustersClientBackupResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudHsmClustersClientBackupResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Backup - Create a backup of the Cloud HSM Cluster in the specified subscription +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CloudHsmClustersClient) backup(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, options *CloudHsmClustersClientBeginBackupOptions) (*http.Response, error) { + var err error + const operationName = "CloudHsmClustersClient.BeginBackup" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.backupCreateRequest(ctx, resourceGroupName, cloudHsmClusterName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// backupCreateRequest creates the Backup request. +func (client *CloudHsmClustersClient) backupCreateRequest(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, options *CloudHsmClustersClientBeginBackupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HardwareSecurityModules/cloudHsmClusters/{cloudHsmClusterName}/backup" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudHsmClusterName == "" { + return nil, errors.New("parameter cloudHsmClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudHsmClusterName}", url.PathEscape(cloudHsmClusterName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250331) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.BackupRequestProperties != nil { + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, *options.BackupRequestProperties); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// BeginCreateOrUpdate - Create or Update a Cloud HSM Cluster in the specified subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudHsmClusterName - The name of the Cloud HSM Cluster within the specified resource group. Cloud HSM Cluster names must +// be between 3 and 23 characters in length. +// - body - Parameters to create Cloud HSM Cluster +// - options - CloudHsmClustersClientBeginCreateOrUpdateOptions contains the optional parameters for the CloudHsmClustersClient.BeginCreateOrUpdate +// method. +func (client *CloudHsmClustersClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, body CloudHsmCluster, options *CloudHsmClustersClientBeginCreateOrUpdateOptions) (*runtime.Poller[CloudHsmClustersClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, cloudHsmClusterName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudHsmClustersClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaOriginalURI, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudHsmClustersClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create or Update a Cloud HSM Cluster in the specified subscription. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CloudHsmClustersClient) createOrUpdate(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, body CloudHsmCluster, options *CloudHsmClustersClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "CloudHsmClustersClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, cloudHsmClusterName, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *CloudHsmClustersClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, body CloudHsmCluster, _ *CloudHsmClustersClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HardwareSecurityModules/cloudHsmClusters/{cloudHsmClusterName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudHsmClusterName == "" { + return nil, errors.New("parameter cloudHsmClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudHsmClusterName}", url.PathEscape(cloudHsmClusterName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250331) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes the specified Cloud HSM Cluster +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudHsmClusterName - The name of the Cloud HSM Cluster within the specified resource group. Cloud HSM Cluster names must +// be between 3 and 23 characters in length. +// - options - CloudHsmClustersClientBeginDeleteOptions contains the optional parameters for the CloudHsmClustersClient.BeginDelete +// method. +func (client *CloudHsmClustersClient) BeginDelete(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, options *CloudHsmClustersClientBeginDeleteOptions) (*runtime.Poller[CloudHsmClustersClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, cloudHsmClusterName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudHsmClustersClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudHsmClustersClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified Cloud HSM Cluster +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CloudHsmClustersClient) deleteOperation(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, options *CloudHsmClustersClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "CloudHsmClustersClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, cloudHsmClusterName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *CloudHsmClustersClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, _ *CloudHsmClustersClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HardwareSecurityModules/cloudHsmClusters/{cloudHsmClusterName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudHsmClusterName == "" { + return nil, errors.New("parameter cloudHsmClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudHsmClusterName}", url.PathEscape(cloudHsmClusterName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250331) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Gets the specified Cloud HSM Cluster +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudHsmClusterName - The name of the Cloud HSM Cluster within the specified resource group. Cloud HSM Cluster names must +// be between 3 and 23 characters in length. +// - options - CloudHsmClustersClientGetOptions contains the optional parameters for the CloudHsmClustersClient.Get method. +func (client *CloudHsmClustersClient) Get(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, options *CloudHsmClustersClientGetOptions) (CloudHsmClustersClientGetResponse, error) { + var err error + const operationName = "CloudHsmClustersClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, cloudHsmClusterName, options) + if err != nil { + return CloudHsmClustersClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CloudHsmClustersClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CloudHsmClustersClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *CloudHsmClustersClient) getCreateRequest(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, _ *CloudHsmClustersClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HardwareSecurityModules/cloudHsmClusters/{cloudHsmClusterName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudHsmClusterName == "" { + return nil, errors.New("parameter cloudHsmClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudHsmClusterName}", url.PathEscape(cloudHsmClusterName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250331) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *CloudHsmClustersClient) getHandleResponse(resp *http.Response) (CloudHsmClustersClientGetResponse, error) { + result := CloudHsmClustersClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CloudHsmCluster); err != nil { + return CloudHsmClustersClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - The List operation gets information about the Cloud HSM Clusters associated with the subscription +// and within the specified resource group. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - CloudHsmClustersClientListByResourceGroupOptions contains the optional parameters for the CloudHsmClustersClient.NewListByResourceGroupPager +// method. +func (client *CloudHsmClustersClient) NewListByResourceGroupPager(resourceGroupName string, options *CloudHsmClustersClientListByResourceGroupOptions) *runtime.Pager[CloudHsmClustersClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[CloudHsmClustersClientListByResourceGroupResponse]{ + More: func(page CloudHsmClustersClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CloudHsmClustersClientListByResourceGroupResponse) (CloudHsmClustersClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CloudHsmClustersClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return CloudHsmClustersClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *CloudHsmClustersClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *CloudHsmClustersClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HardwareSecurityModules/cloudHsmClusters" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Skiptoken != nil { + reqQP.Set("$skiptoken", *options.Skiptoken) + } + reqQP.Set("api-version", version20250331) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *CloudHsmClustersClient) listByResourceGroupHandleResponse(resp *http.Response) (CloudHsmClustersClientListByResourceGroupResponse, error) { + result := CloudHsmClustersClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CloudHsmClusterListResult); err != nil { + return CloudHsmClustersClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - The List operation gets information about the Cloud HSM Clusters associated with the subscription. +// - options - CloudHsmClustersClientListBySubscriptionOptions contains the optional parameters for the CloudHsmClustersClient.NewListBySubscriptionPager +// method. +func (client *CloudHsmClustersClient) NewListBySubscriptionPager(options *CloudHsmClustersClientListBySubscriptionOptions) *runtime.Pager[CloudHsmClustersClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[CloudHsmClustersClientListBySubscriptionResponse]{ + More: func(page CloudHsmClustersClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CloudHsmClustersClientListBySubscriptionResponse) (CloudHsmClustersClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CloudHsmClustersClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return CloudHsmClustersClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *CloudHsmClustersClient) listBySubscriptionCreateRequest(ctx context.Context, options *CloudHsmClustersClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.HardwareSecurityModules/cloudHsmClusters" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Skiptoken != nil { + reqQP.Set("$skiptoken", *options.Skiptoken) + } + reqQP.Set("api-version", version20250331) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *CloudHsmClustersClient) listBySubscriptionHandleResponse(resp *http.Response) (CloudHsmClustersClientListBySubscriptionResponse, error) { + result := CloudHsmClustersClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CloudHsmClusterListResult); err != nil { + return CloudHsmClustersClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// BeginRestore - Restores all key materials of a specified Cloud HSM Cluster +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudHsmClusterName - The name of the Cloud HSM Cluster within the specified resource group. Cloud HSM Cluster names must +// be between 3 and 23 characters in length. +// - restoreRequestProperties - Restore Operation Required properties +// - options - CloudHsmClustersClientBeginRestoreOptions contains the optional parameters for the CloudHsmClustersClient.BeginRestore +// method. +func (client *CloudHsmClustersClient) BeginRestore(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, restoreRequestProperties RestoreRequestProperties, options *CloudHsmClustersClientBeginRestoreOptions) (*runtime.Poller[CloudHsmClustersClientRestoreResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.restore(ctx, resourceGroupName, cloudHsmClusterName, restoreRequestProperties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudHsmClustersClientRestoreResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudHsmClustersClientRestoreResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Restore - Restores all key materials of a specified Cloud HSM Cluster +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CloudHsmClustersClient) restore(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, restoreRequestProperties RestoreRequestProperties, options *CloudHsmClustersClientBeginRestoreOptions) (*http.Response, error) { + var err error + const operationName = "CloudHsmClustersClient.BeginRestore" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.restoreCreateRequest(ctx, resourceGroupName, cloudHsmClusterName, restoreRequestProperties, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// restoreCreateRequest creates the Restore request. +func (client *CloudHsmClustersClient) restoreCreateRequest(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, restoreRequestProperties RestoreRequestProperties, _ *CloudHsmClustersClientBeginRestoreOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HardwareSecurityModules/cloudHsmClusters/{cloudHsmClusterName}/restore" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudHsmClusterName == "" { + return nil, errors.New("parameter cloudHsmClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudHsmClusterName}", url.PathEscape(cloudHsmClusterName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250331) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, restoreRequestProperties); err != nil { + return nil, err + } + return req, nil +} + +// BeginUpdate - Update a Cloud HSM Cluster in the specified subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudHsmClusterName - The name of the Cloud HSM Cluster within the specified resource group. Cloud HSM Cluster names must +// be between 3 and 23 characters in length. +// - body - Parameters to create Cloud HSM Cluster +// - options - CloudHsmClustersClientBeginUpdateOptions contains the optional parameters for the CloudHsmClustersClient.BeginUpdate +// method. +func (client *CloudHsmClustersClient) BeginUpdate(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, body CloudHsmClusterPatchParameters, options *CloudHsmClustersClientBeginUpdateOptions) (*runtime.Poller[CloudHsmClustersClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, cloudHsmClusterName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudHsmClustersClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudHsmClustersClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a Cloud HSM Cluster in the specified subscription. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CloudHsmClustersClient) update(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, body CloudHsmClusterPatchParameters, options *CloudHsmClustersClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "CloudHsmClustersClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, cloudHsmClusterName, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *CloudHsmClustersClient) updateCreateRequest(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, body CloudHsmClusterPatchParameters, _ *CloudHsmClustersClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HardwareSecurityModules/cloudHsmClusters/{cloudHsmClusterName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudHsmClusterName == "" { + return nil, errors.New("parameter cloudHsmClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudHsmClusterName}", url.PathEscape(cloudHsmClusterName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250331) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// BeginValidateBackupProperties - Pre Backup operation to validate whether the customer can perform a backup on the Cloud +// HSM Cluster resource in the specified subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudHsmClusterName - The name of the Cloud HSM Cluster within the specified resource group. Cloud HSM Cluster names must +// be between 3 and 23 characters in length. +// - options - CloudHsmClustersClientBeginValidateBackupPropertiesOptions contains the optional parameters for the CloudHsmClustersClient.BeginValidateBackupProperties +// method. +func (client *CloudHsmClustersClient) BeginValidateBackupProperties(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, options *CloudHsmClustersClientBeginValidateBackupPropertiesOptions) (*runtime.Poller[CloudHsmClustersClientValidateBackupPropertiesResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.validateBackupProperties(ctx, resourceGroupName, cloudHsmClusterName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudHsmClustersClientValidateBackupPropertiesResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudHsmClustersClientValidateBackupPropertiesResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ValidateBackupProperties - Pre Backup operation to validate whether the customer can perform a backup on the Cloud HSM +// Cluster resource in the specified subscription. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CloudHsmClustersClient) validateBackupProperties(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, options *CloudHsmClustersClientBeginValidateBackupPropertiesOptions) (*http.Response, error) { + var err error + const operationName = "CloudHsmClustersClient.BeginValidateBackupProperties" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.validateBackupPropertiesCreateRequest(ctx, resourceGroupName, cloudHsmClusterName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// validateBackupPropertiesCreateRequest creates the ValidateBackupProperties request. +func (client *CloudHsmClustersClient) validateBackupPropertiesCreateRequest(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, options *CloudHsmClustersClientBeginValidateBackupPropertiesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HardwareSecurityModules/cloudHsmClusters/{cloudHsmClusterName}/validateBackupProperties" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudHsmClusterName == "" { + return nil, errors.New("parameter cloudHsmClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudHsmClusterName}", url.PathEscape(cloudHsmClusterName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250331) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.BackupRequestProperties != nil { + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, *options.BackupRequestProperties); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// BeginValidateRestoreProperties - Queued validating pre restore operation +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudHsmClusterName - The name of the Cloud HSM Cluster within the specified resource group. Cloud HSM Cluster names must +// be between 3 and 23 characters in length. +// - options - CloudHsmClustersClientBeginValidateRestorePropertiesOptions contains the optional parameters for the CloudHsmClustersClient.BeginValidateRestoreProperties +// method. +func (client *CloudHsmClustersClient) BeginValidateRestoreProperties(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, options *CloudHsmClustersClientBeginValidateRestorePropertiesOptions) (*runtime.Poller[CloudHsmClustersClientValidateRestorePropertiesResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.validateRestoreProperties(ctx, resourceGroupName, cloudHsmClusterName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudHsmClustersClientValidateRestorePropertiesResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudHsmClustersClientValidateRestorePropertiesResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ValidateRestoreProperties - Queued validating pre restore operation +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CloudHsmClustersClient) validateRestoreProperties(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, options *CloudHsmClustersClientBeginValidateRestorePropertiesOptions) (*http.Response, error) { + var err error + const operationName = "CloudHsmClustersClient.BeginValidateRestoreProperties" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.validateRestorePropertiesCreateRequest(ctx, resourceGroupName, cloudHsmClusterName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// validateRestorePropertiesCreateRequest creates the ValidateRestoreProperties request. +func (client *CloudHsmClustersClient) validateRestorePropertiesCreateRequest(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, options *CloudHsmClustersClientBeginValidateRestorePropertiesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HardwareSecurityModules/cloudHsmClusters/{cloudHsmClusterName}/validateRestoreProperties" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudHsmClusterName == "" { + return nil, errors.New("parameter cloudHsmClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudHsmClusterName}", url.PathEscape(cloudHsmClusterName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250331) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.RestoreRequestProperties != nil { + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, *options.RestoreRequestProperties); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} diff --git a/test/local/armhardwaresecuritymodules/zz_constants.go b/test/local/armhardwaresecuritymodules/zz_constants.go new file mode 100644 index 000000000000..7810690b69f4 --- /dev/null +++ b/test/local/armhardwaresecuritymodules/zz_constants.go @@ -0,0 +1,343 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armhardwaresecuritymodules + +const ( + version20250331 string = "2025-03-31" +) + +// ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +type ActionType string + +const ( + // ActionTypeInternal - Actions are for internal-only APIs. + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// ActivationState - State of security domain activation +type ActivationState string + +const ( + ActivationStateActive ActivationState = "Active" + ActivationStateFailed ActivationState = "Failed" + ActivationStateNotActivated ActivationState = "NotActivated" + ActivationStateNotDefined ActivationState = "NotDefined" + ActivationStateUnknown ActivationState = "Unknown" +) + +// PossibleActivationStateValues returns the possible values for the ActivationState const type. +func PossibleActivationStateValues() []ActivationState { + return []ActivationState{ + ActivationStateActive, + ActivationStateFailed, + ActivationStateNotActivated, + ActivationStateNotDefined, + ActivationStateUnknown, + } +} + +// AutoGeneratedDomainNameLabelScope - The Cloud HSM Cluster's auto-generated Domain Name Label Scope +type AutoGeneratedDomainNameLabelScope string + +const ( + AutoGeneratedDomainNameLabelScopeNoReuse AutoGeneratedDomainNameLabelScope = "NoReuse" + AutoGeneratedDomainNameLabelScopeResourceGroupReuse AutoGeneratedDomainNameLabelScope = "ResourceGroupReuse" + AutoGeneratedDomainNameLabelScopeSubscriptionReuse AutoGeneratedDomainNameLabelScope = "SubscriptionReuse" + AutoGeneratedDomainNameLabelScopeTenantReuse AutoGeneratedDomainNameLabelScope = "TenantReuse" +) + +// PossibleAutoGeneratedDomainNameLabelScopeValues returns the possible values for the AutoGeneratedDomainNameLabelScope const type. +func PossibleAutoGeneratedDomainNameLabelScopeValues() []AutoGeneratedDomainNameLabelScope { + return []AutoGeneratedDomainNameLabelScope{ + AutoGeneratedDomainNameLabelScopeNoReuse, + AutoGeneratedDomainNameLabelScopeResourceGroupReuse, + AutoGeneratedDomainNameLabelScopeSubscriptionReuse, + AutoGeneratedDomainNameLabelScopeTenantReuse, + } +} + +// BackupRestoreOperationStatus - Status of the backup/restore operation +type BackupRestoreOperationStatus string + +const ( + BackupRestoreOperationStatusCancelled BackupRestoreOperationStatus = "Cancelled" + BackupRestoreOperationStatusFailed BackupRestoreOperationStatus = "Failed" + BackupRestoreOperationStatusInProgress BackupRestoreOperationStatus = "InProgress" + BackupRestoreOperationStatusSucceeded BackupRestoreOperationStatus = "Succeeded" +) + +// PossibleBackupRestoreOperationStatusValues returns the possible values for the BackupRestoreOperationStatus const type. +func PossibleBackupRestoreOperationStatusValues() []BackupRestoreOperationStatus { + return []BackupRestoreOperationStatus{ + BackupRestoreOperationStatusCancelled, + BackupRestoreOperationStatusFailed, + BackupRestoreOperationStatusInProgress, + BackupRestoreOperationStatusSucceeded, + } +} + +// CloudHsmClusterSKUFamily - Sku family of the Cloud HSM Cluster +type CloudHsmClusterSKUFamily string + +const ( + CloudHsmClusterSKUFamilyB CloudHsmClusterSKUFamily = "B" +) + +// PossibleCloudHsmClusterSKUFamilyValues returns the possible values for the CloudHsmClusterSKUFamily const type. +func PossibleCloudHsmClusterSKUFamilyValues() []CloudHsmClusterSKUFamily { + return []CloudHsmClusterSKUFamily{ + CloudHsmClusterSKUFamilyB, + } +} + +// CloudHsmClusterSKUName - Sku name of the Cloud HSM Cluster +type CloudHsmClusterSKUName string + +const ( + CloudHsmClusterSKUNameStandardB1 CloudHsmClusterSKUName = "Standard_B1" + CloudHsmClusterSKUNameStandardB10 CloudHsmClusterSKUName = "Standard B10" +) + +// PossibleCloudHsmClusterSKUNameValues returns the possible values for the CloudHsmClusterSKUName const type. +func PossibleCloudHsmClusterSKUNameValues() []CloudHsmClusterSKUName { + return []CloudHsmClusterSKUName{ + CloudHsmClusterSKUNameStandardB1, + CloudHsmClusterSKUNameStandardB10, + } +} + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// JSONWebKeyType - Provisioning state. +type JSONWebKeyType string + +const ( + // JSONWebKeyTypeAllocating - A device is currently being allocated for the dedicated HSM resource. + JSONWebKeyTypeAllocating JSONWebKeyType = "Allocating" + // JSONWebKeyTypeCheckingQuota - Validating the subscription has sufficient quota to allocate a dedicated HSM device. + JSONWebKeyTypeCheckingQuota JSONWebKeyType = "CheckingQuota" + // JSONWebKeyTypeConnecting - The dedicated HSM is being connected to the virtual network. + JSONWebKeyTypeConnecting JSONWebKeyType = "Connecting" + // JSONWebKeyTypeDeleting - The dedicated HSM is currently being deleted. + JSONWebKeyTypeDeleting JSONWebKeyType = "Deleting" + // JSONWebKeyTypeFailed - Provisioning of the dedicated HSM has failed. + JSONWebKeyTypeFailed JSONWebKeyType = "Failed" + // JSONWebKeyTypeProvisioning - The dedicated HSM is currently being provisioned. + JSONWebKeyTypeProvisioning JSONWebKeyType = "Provisioning" + // JSONWebKeyTypeSucceeded - The dedicated HSM has been fully provisioned. + JSONWebKeyTypeSucceeded JSONWebKeyType = "Succeeded" +) + +// PossibleJSONWebKeyTypeValues returns the possible values for the JSONWebKeyType const type. +func PossibleJSONWebKeyTypeValues() []JSONWebKeyType { + return []JSONWebKeyType{ + JSONWebKeyTypeAllocating, + JSONWebKeyTypeCheckingQuota, + JSONWebKeyTypeConnecting, + JSONWebKeyTypeDeleting, + JSONWebKeyTypeFailed, + JSONWebKeyTypeProvisioning, + JSONWebKeyTypeSucceeded, + } +} + +// ManagedServiceIdentityType - Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). +type ManagedServiceIdentityType string + +const ( + // ManagedServiceIdentityTypeNone - No managed identity. + ManagedServiceIdentityTypeNone ManagedServiceIdentityType = "None" + // ManagedServiceIdentityTypeSystemAssigned - System assigned managed identity. + ManagedServiceIdentityTypeSystemAssigned ManagedServiceIdentityType = "SystemAssigned" + // ManagedServiceIdentityTypeSystemAssignedUserAssigned - System and user assigned managed identity. + ManagedServiceIdentityTypeSystemAssignedUserAssigned ManagedServiceIdentityType = "SystemAssigned,UserAssigned" + // ManagedServiceIdentityTypeUserAssigned - User assigned managed identity. + ManagedServiceIdentityTypeUserAssigned ManagedServiceIdentityType = "UserAssigned" +) + +// PossibleManagedServiceIdentityTypeValues returns the possible values for the ManagedServiceIdentityType const type. +func PossibleManagedServiceIdentityTypeValues() []ManagedServiceIdentityType { + return []ManagedServiceIdentityType{ + ManagedServiceIdentityTypeNone, + ManagedServiceIdentityTypeSystemAssigned, + ManagedServiceIdentityTypeSystemAssignedUserAssigned, + ManagedServiceIdentityTypeUserAssigned, + } +} + +// Origin - The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default +// value is "user,system" +type Origin string + +const ( + // OriginSystem - Indicates the operation is initiated by a system. + OriginSystem Origin = "system" + // OriginUser - Indicates the operation is initiated by a user. + OriginUser Origin = "user" + // OriginUserSystem - Indicates the operation is initiated by a user or system. + OriginUserSystem Origin = "user,system" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginSystem, + OriginUser, + OriginUserSystem, + } +} + +// PrivateEndpointConnectionProvisioningState - The current provisioning state. +type PrivateEndpointConnectionProvisioningState string + +const ( + PrivateEndpointConnectionProvisioningStateCanceled PrivateEndpointConnectionProvisioningState = "Canceled" + PrivateEndpointConnectionProvisioningStateCreating PrivateEndpointConnectionProvisioningState = "Creating" + PrivateEndpointConnectionProvisioningStateDeleting PrivateEndpointConnectionProvisioningState = "Deleting" + PrivateEndpointConnectionProvisioningStateFailed PrivateEndpointConnectionProvisioningState = "Failed" + PrivateEndpointConnectionProvisioningStateInternalError PrivateEndpointConnectionProvisioningState = "InternalError" + PrivateEndpointConnectionProvisioningStateSucceeded PrivateEndpointConnectionProvisioningState = "Succeeded" + PrivateEndpointConnectionProvisioningStateUpdating PrivateEndpointConnectionProvisioningState = "Updating" +) + +// PossiblePrivateEndpointConnectionProvisioningStateValues returns the possible values for the PrivateEndpointConnectionProvisioningState const type. +func PossiblePrivateEndpointConnectionProvisioningStateValues() []PrivateEndpointConnectionProvisioningState { + return []PrivateEndpointConnectionProvisioningState{ + PrivateEndpointConnectionProvisioningStateCanceled, + PrivateEndpointConnectionProvisioningStateCreating, + PrivateEndpointConnectionProvisioningStateDeleting, + PrivateEndpointConnectionProvisioningStateFailed, + PrivateEndpointConnectionProvisioningStateInternalError, + PrivateEndpointConnectionProvisioningStateSucceeded, + PrivateEndpointConnectionProvisioningStateUpdating, + } +} + +// PrivateEndpointServiceConnectionStatus - The private endpoint connection status. +type PrivateEndpointServiceConnectionStatus string + +const ( + // PrivateEndpointServiceConnectionStatusApproved - Connection approved + PrivateEndpointServiceConnectionStatusApproved PrivateEndpointServiceConnectionStatus = "Approved" + // PrivateEndpointServiceConnectionStatusPending - Connection waiting for approval or rejection + PrivateEndpointServiceConnectionStatusPending PrivateEndpointServiceConnectionStatus = "Pending" + // PrivateEndpointServiceConnectionStatusRejected - Connection Rejected + PrivateEndpointServiceConnectionStatusRejected PrivateEndpointServiceConnectionStatus = "Rejected" +) + +// PossiblePrivateEndpointServiceConnectionStatusValues returns the possible values for the PrivateEndpointServiceConnectionStatus const type. +func PossiblePrivateEndpointServiceConnectionStatusValues() []PrivateEndpointServiceConnectionStatus { + return []PrivateEndpointServiceConnectionStatus{ + PrivateEndpointServiceConnectionStatusApproved, + PrivateEndpointServiceConnectionStatusPending, + PrivateEndpointServiceConnectionStatusRejected, + } +} + +// ProvisioningState - The Cloud HSM Cluster's provisioningState +type ProvisioningState string + +const ( + ProvisioningStateCanceled ProvisioningState = "Canceled" + ProvisioningStateDeleting ProvisioningState = "Deleting" + ProvisioningStateFailed ProvisioningState = "Failed" + ProvisioningStateProvisioning ProvisioningState = "Provisioning" + ProvisioningStateSucceeded ProvisioningState = "Succeeded" + ProvisioningStateUpdating ProvisioningState = "Updating" +) + +// PossibleProvisioningStateValues returns the possible values for the ProvisioningState const type. +func PossibleProvisioningStateValues() []ProvisioningState { + return []ProvisioningState{ + ProvisioningStateCanceled, + ProvisioningStateDeleting, + ProvisioningStateFailed, + ProvisioningStateProvisioning, + ProvisioningStateSucceeded, + ProvisioningStateUpdating, + } +} + +// PublicNetworkAccess - The Cloud HSM Cluster public network access +type PublicNetworkAccess string + +const ( + PublicNetworkAccessDisabled PublicNetworkAccess = "Disabled" +) + +// PossiblePublicNetworkAccessValues returns the possible values for the PublicNetworkAccess const type. +func PossiblePublicNetworkAccessValues() []PublicNetworkAccess { + return []PublicNetworkAccess{ + PublicNetworkAccessDisabled, + } +} + +// SKUName - SKU of the dedicated HSM +type SKUName string + +const ( + // SKUNamePayShield10KLMK1CPS250 - The dedicated HSM is a payShield 10K, model PS10-D, 10Gb Ethernet Hardware Platform device + // with 1 local master key which supports up to 250 calls per second. + SKUNamePayShield10KLMK1CPS250 SKUName = "payShield10K_LMK1_CPS250" + // SKUNamePayShield10KLMK1CPS2500 - The dedicated HSM is a payShield 10K, model PS10-D, 10Gb Ethernet Hardware Platform device + // with 1 local master key which supports up to 2500 calls per second. + SKUNamePayShield10KLMK1CPS2500 SKUName = "payShield10K_LMK1_CPS2500" + // SKUNamePayShield10KLMK1CPS60 - The dedicated HSM is a payShield 10K, model PS10-D, 10Gb Ethernet Hardware Platform device + // with 1 local master key which supports up to 60 calls per second. + SKUNamePayShield10KLMK1CPS60 SKUName = "payShield10K_LMK1_CPS60" + // SKUNamePayShield10KLMK2CPS250 - The dedicated HSM is a payShield 10K, model PS10-D, 10Gb Ethernet Hardware Platform device + // with 2 local master keys which supports up to 250 calls per second. + SKUNamePayShield10KLMK2CPS250 SKUName = "payShield10K_LMK2_CPS250" + // SKUNamePayShield10KLMK2CPS2500 - The dedicated HSM is a payShield 10K, model PS10-D, 10Gb Ethernet Hardware Platform device + // with 2 local master keys which supports up to 2500 calls per second. + SKUNamePayShield10KLMK2CPS2500 SKUName = "payShield10K_LMK2_CPS2500" + // SKUNamePayShield10KLMK2CPS60 - The dedicated HSM is a payShield 10K, model PS10-D, 10Gb Ethernet Hardware Platform device + // with 2 local master keys which supports up to 60 calls per second. + SKUNamePayShield10KLMK2CPS60 SKUName = "payShield10K_LMK2_CPS60" + // SKUNameSafeNetLunaNetworkHSMA790 - The dedicated HSM is a Safenet Luna Network HSM A790 device. + SKUNameSafeNetLunaNetworkHSMA790 SKUName = "SafeNet Luna Network HSM A790" +) + +// PossibleSKUNameValues returns the possible values for the SKUName const type. +func PossibleSKUNameValues() []SKUName { + return []SKUName{ + SKUNamePayShield10KLMK1CPS250, + SKUNamePayShield10KLMK1CPS2500, + SKUNamePayShield10KLMK1CPS60, + SKUNamePayShield10KLMK2CPS250, + SKUNamePayShield10KLMK2CPS2500, + SKUNamePayShield10KLMK2CPS60, + SKUNameSafeNetLunaNetworkHSMA790, + } +} diff --git a/test/local/armhardwaresecuritymodules/zz_dedicatedhsm_client.go b/test/local/armhardwaresecuritymodules/zz_dedicatedhsm_client.go new file mode 100644 index 000000000000..0194eb3a58d2 --- /dev/null +++ b/test/local/armhardwaresecuritymodules/zz_dedicatedhsm_client.go @@ -0,0 +1,512 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armhardwaresecuritymodules + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" +) + +// DedicatedHsmClient contains the methods for the DedicatedHsm group. +// Don't use this type directly, use NewDedicatedHsmClient() instead. +// +// Generated from API version 2025-03-31 +type DedicatedHsmClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDedicatedHsmClient creates a new instance of DedicatedHsmClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewDedicatedHsmClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DedicatedHsmClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DedicatedHsmClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create or Update a dedicated HSM in the specified subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - name - Name of the dedicated Hsm +// - parameters - Parameters to create or update the dedicated hsm +// - options - DedicatedHsmClientBeginCreateOrUpdateOptions contains the optional parameters for the DedicatedHsmClient.BeginCreateOrUpdate +// method. +func (client *DedicatedHsmClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, name string, parameters DedicatedHsm, options *DedicatedHsmClientBeginCreateOrUpdateOptions) (*runtime.Poller[DedicatedHsmClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, name, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DedicatedHsmClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DedicatedHsmClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create or Update a dedicated HSM in the specified subscription. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *DedicatedHsmClient) createOrUpdate(ctx context.Context, resourceGroupName string, name string, parameters DedicatedHsm, options *DedicatedHsmClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "DedicatedHsmClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, name, parameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *DedicatedHsmClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, name string, parameters DedicatedHsm, _ *DedicatedHsmClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HardwareSecurityModules/dedicatedHSMs/{name}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250331) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes the specified Azure Dedicated HSM. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - name - Name of the dedicated Hsm +// - options - DedicatedHsmClientBeginDeleteOptions contains the optional parameters for the DedicatedHsmClient.BeginDelete +// method. +func (client *DedicatedHsmClient) BeginDelete(ctx context.Context, resourceGroupName string, name string, options *DedicatedHsmClientBeginDeleteOptions) (*runtime.Poller[DedicatedHsmClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, name, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DedicatedHsmClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DedicatedHsmClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes the specified Azure Dedicated HSM. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *DedicatedHsmClient) deleteOperation(ctx context.Context, resourceGroupName string, name string, options *DedicatedHsmClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "DedicatedHsmClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, name, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *DedicatedHsmClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, name string, _ *DedicatedHsmClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HardwareSecurityModules/dedicatedHSMs/{name}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250331) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Gets the specified Azure dedicated HSM. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - name - Name of the dedicated Hsm +// - options - DedicatedHsmClientGetOptions contains the optional parameters for the DedicatedHsmClient.Get method. +func (client *DedicatedHsmClient) Get(ctx context.Context, resourceGroupName string, name string, options *DedicatedHsmClientGetOptions) (DedicatedHsmClientGetResponse, error) { + var err error + const operationName = "DedicatedHsmClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, name, options) + if err != nil { + return DedicatedHsmClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DedicatedHsmClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DedicatedHsmClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DedicatedHsmClient) getCreateRequest(ctx context.Context, resourceGroupName string, name string, _ *DedicatedHsmClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HardwareSecurityModules/dedicatedHSMs/{name}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250331) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DedicatedHsmClient) getHandleResponse(resp *http.Response) (DedicatedHsmClientGetResponse, error) { + result := DedicatedHsmClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DedicatedHsm); err != nil { + return DedicatedHsmClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - The List operation gets information about the dedicated HSMs associated with the subscription +// and within the specified resource group. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - DedicatedHsmClientListByResourceGroupOptions contains the optional parameters for the DedicatedHsmClient.NewListByResourceGroupPager +// method. +func (client *DedicatedHsmClient) NewListByResourceGroupPager(resourceGroupName string, options *DedicatedHsmClientListByResourceGroupOptions) *runtime.Pager[DedicatedHsmClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[DedicatedHsmClientListByResourceGroupResponse]{ + More: func(page DedicatedHsmClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DedicatedHsmClientListByResourceGroupResponse) (DedicatedHsmClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DedicatedHsmClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return DedicatedHsmClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *DedicatedHsmClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *DedicatedHsmClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HardwareSecurityModules/dedicatedHSMs" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + reqQP.Set("api-version", version20250331) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *DedicatedHsmClient) listByResourceGroupHandleResponse(resp *http.Response) (DedicatedHsmClientListByResourceGroupResponse, error) { + result := DedicatedHsmClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DedicatedHsmListResult); err != nil { + return DedicatedHsmClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - The List operation gets information about the dedicated HSMs associated with the subscription. +// - options - DedicatedHsmClientListBySubscriptionOptions contains the optional parameters for the DedicatedHsmClient.NewListBySubscriptionPager +// method. +func (client *DedicatedHsmClient) NewListBySubscriptionPager(options *DedicatedHsmClientListBySubscriptionOptions) *runtime.Pager[DedicatedHsmClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[DedicatedHsmClientListBySubscriptionResponse]{ + More: func(page DedicatedHsmClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DedicatedHsmClientListBySubscriptionResponse) (DedicatedHsmClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DedicatedHsmClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return DedicatedHsmClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *DedicatedHsmClient) listBySubscriptionCreateRequest(ctx context.Context, options *DedicatedHsmClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.HardwareSecurityModules/dedicatedHSMs" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + reqQP.Set("api-version", version20250331) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *DedicatedHsmClient) listBySubscriptionHandleResponse(resp *http.Response) (DedicatedHsmClientListBySubscriptionResponse, error) { + result := DedicatedHsmClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DedicatedHsmListResult); err != nil { + return DedicatedHsmClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// NewListOutboundNetworkDependenciesEndpointsPager - Gets a list of egress endpoints (network endpoints of all outbound dependencies) +// in the specified dedicated hsm resource. The operation returns properties of each egress endpoint. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - name - Name of the dedicated Hsm +// - options - DedicatedHsmClientListOutboundNetworkDependenciesEndpointsOptions contains the optional parameters for the DedicatedHsmClient.NewListOutboundNetworkDependenciesEndpointsPager +// method. +func (client *DedicatedHsmClient) NewListOutboundNetworkDependenciesEndpointsPager(resourceGroupName string, name string, options *DedicatedHsmClientListOutboundNetworkDependenciesEndpointsOptions) *runtime.Pager[DedicatedHsmClientListOutboundNetworkDependenciesEndpointsResponse] { + return runtime.NewPager(runtime.PagingHandler[DedicatedHsmClientListOutboundNetworkDependenciesEndpointsResponse]{ + More: func(page DedicatedHsmClientListOutboundNetworkDependenciesEndpointsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DedicatedHsmClientListOutboundNetworkDependenciesEndpointsResponse) (DedicatedHsmClientListOutboundNetworkDependenciesEndpointsResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DedicatedHsmClient.NewListOutboundNetworkDependenciesEndpointsPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listOutboundNetworkDependenciesEndpointsCreateRequest(ctx, resourceGroupName, name, options) + }, nil) + if err != nil { + return DedicatedHsmClientListOutboundNetworkDependenciesEndpointsResponse{}, err + } + return client.listOutboundNetworkDependenciesEndpointsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listOutboundNetworkDependenciesEndpointsCreateRequest creates the ListOutboundNetworkDependenciesEndpoints request. +func (client *DedicatedHsmClient) listOutboundNetworkDependenciesEndpointsCreateRequest(ctx context.Context, resourceGroupName string, name string, _ *DedicatedHsmClientListOutboundNetworkDependenciesEndpointsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HardwareSecurityModules/dedicatedHSMs/{name}/outboundNetworkDependenciesEndpoints" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250331) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listOutboundNetworkDependenciesEndpointsHandleResponse handles the ListOutboundNetworkDependenciesEndpoints response. +func (client *DedicatedHsmClient) listOutboundNetworkDependenciesEndpointsHandleResponse(resp *http.Response) (DedicatedHsmClientListOutboundNetworkDependenciesEndpointsResponse, error) { + result := DedicatedHsmClientListOutboundNetworkDependenciesEndpointsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OutboundEnvironmentEndpointCollection); err != nil { + return DedicatedHsmClientListOutboundNetworkDependenciesEndpointsResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update a dedicated HSM in the specified subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - name - Name of the dedicated Hsm +// - parameters - Parameters to patch the dedicated HSM +// - options - DedicatedHsmClientBeginUpdateOptions contains the optional parameters for the DedicatedHsmClient.BeginUpdate +// method. +func (client *DedicatedHsmClient) BeginUpdate(ctx context.Context, resourceGroupName string, name string, parameters DedicatedHsmPatchParameters, options *DedicatedHsmClientBeginUpdateOptions) (*runtime.Poller[DedicatedHsmClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, name, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DedicatedHsmClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DedicatedHsmClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a dedicated HSM in the specified subscription. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *DedicatedHsmClient) update(ctx context.Context, resourceGroupName string, name string, parameters DedicatedHsmPatchParameters, options *DedicatedHsmClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "DedicatedHsmClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, name, parameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *DedicatedHsmClient) updateCreateRequest(ctx context.Context, resourceGroupName string, name string, parameters DedicatedHsmPatchParameters, _ *DedicatedHsmClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HardwareSecurityModules/dedicatedHSMs/{name}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250331) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armhardwaresecuritymodules/zz_models.go b/test/local/armhardwaresecuritymodules/zz_models.go new file mode 100644 index 000000000000..7d411c885042 --- /dev/null +++ b/test/local/armhardwaresecuritymodules/zz_models.go @@ -0,0 +1,547 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armhardwaresecuritymodules + +import "time" + +// APIEntityReference - The API entity reference. +type APIEntityReference struct { + // The Azure resource id in the form of /subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroupName}/... + ResourceID *string +} + +// BackupRequestProperties - Backup properties +type BackupRequestProperties struct { + // REQUIRED; The Azure blob storage container Uri which contains the backup + AzureStorageBlobContainerURI *string + + // The SAS token pointing to an Azure blob storage container. This property is reserved for Azure Backup Service. + Token *string +} + +// BackupRestoreBaseResultProperties - Backup and Restore operation common properties +type BackupRestoreBaseResultProperties struct { + // Error encountered, if any, during the backup/restore operation. + Error *ErrorDetail + + // Identifier for the backup/restore operation. + JobID *string + + // The status details of backup/restore operation + StatusDetails *string + + // READ-ONLY; The end time of the backup/restore operation in UTC + EndTime *time.Time + + // READ-ONLY; The start time of the backup/restore operation in UTC + StartTime *time.Time + + // READ-ONLY; Status of the backup/restore operation + Status *BackupRestoreOperationStatus +} + +// BackupResult - Backup operation Result +type BackupResult struct { + // Properties of the Cloud HSM Cluster + Properties *BackupResultProperties +} + +// BackupResultProperties - Properties of the Cloud HSM Cluster +type BackupResultProperties struct { + // The Azure blob storage container Uri which contains the backup + AzureStorageBlobContainerURI *string + + // The ID of the backup. + BackupID *string + + // Error encountered, if any, during the backup/restore operation. + Error *ErrorDetail + + // Identifier for the backup/restore operation. + JobID *string + + // The status details of backup/restore operation + StatusDetails *string + + // READ-ONLY; The end time of the backup/restore operation in UTC + EndTime *time.Time + + // READ-ONLY; The start time of the backup/restore operation in UTC + StartTime *time.Time + + // READ-ONLY; Status of the backup/restore operation + Status *BackupRestoreOperationStatus +} + +// CloudHsmCluster - Resource information with extended details. +type CloudHsmCluster struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // Managed service identity (system assigned and/or user assigned identities) + Identity *ManagedServiceIdentity + + // Properties of the Cloud HSM Cluster + Properties *CloudHsmClusterProperties + + // SKU details + SKU *CloudHsmClusterSKU + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// CloudHsmClusterListResult - The response of a CloudHsmCluster list operation. +type CloudHsmClusterListResult struct { + // REQUIRED; The CloudHsmCluster items on this page + Value []*CloudHsmCluster + + // The link to the next page of items + NextLink *string +} + +// CloudHsmClusterPatchParameters - Patchable properties of the Cloud HSM Cluster +type CloudHsmClusterPatchParameters struct { + // Managed service identity (system assigned and/or user assigned identities) + Identity *ManagedServiceIdentity + + // The Cloud HSM Cluster's tags + Tags map[string]*string +} + +// CloudHsmClusterProperties - Properties of a Cloud HSM Cluster. +type CloudHsmClusterProperties struct { + // The Cloud HSM Cluster's auto-generated Domain Name Label Scope + AutoGeneratedDomainNameLabelScope *AutoGeneratedDomainNameLabelScope + + // The Cloud HSM Cluster public network access + PublicNetworkAccess *PublicNetworkAccess + + // READ-ONLY; State of security domain activation + ActivationState *ActivationState + + // READ-ONLY; An array of Cloud HSM Cluster's HSMs + Hsms []*CloudHsmProperties + + // READ-ONLY; List of private endpoint connection resources + PrivateEndpointConnections []*PrivateEndpointConnection + + // READ-ONLY; The Cloud HSM Cluster's provisioningState + ProvisioningState *ProvisioningState + + // READ-ONLY; Cloud HSM Cluster status message + StatusMessage *string +} + +// CloudHsmClusterSKU - Cloud Hsm Cluster SKU information +type CloudHsmClusterSKU struct { + // REQUIRED; Sku family of the Cloud HSM Cluster + Family *CloudHsmClusterSKUFamily + + // REQUIRED; Sku name of the Cloud HSM Cluster + Name *CloudHsmClusterSKUName + + // Sku capacity + Capacity *int32 +} + +// CloudHsmProperties - The Cloud HSM Properties +type CloudHsmProperties struct { + // FQDN of the Cloud HSM + Fqdn *string + + // The Cloud HSM State. Values are: Deploying, ConfiguringSlb, Starting, Starting, Failed, Failed, Deleting, DeletingSlbEntry, + // InitialProvisioning, Updating + State *string + + // The Cloud HSM State message + StateMessage *string +} + +// DedicatedHsm - Resource information with extended details. +type DedicatedHsm struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // REQUIRED; Properties of the dedicated HSM + Properties *DedicatedHsmProperties + + // REQUIRED; SKU details + SKU *SKU + + // Resource tags. + Tags map[string]*string + + // The availability zones. + Zones []*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// DedicatedHsmListResult - The response of a DedicatedHsm list operation. +type DedicatedHsmListResult struct { + // REQUIRED; The DedicatedHsm items on this page + Value []*DedicatedHsm + + // The link to the next page of items + NextLink *string +} + +// DedicatedHsmPatchParameters - Patchable properties of the dedicated HSM +type DedicatedHsmPatchParameters struct { + // Resource tags + Tags map[string]*string +} + +// DedicatedHsmProperties - Properties of the dedicated hsm +type DedicatedHsmProperties struct { + // Specifies the management network interfaces of the dedicated hsm. + ManagementNetworkProfile *NetworkProfile + + // Specifies the network interfaces of the dedicated hsm. + NetworkProfile *NetworkProfile + + // This field will be used when RP does not support Availability zones. + StampID *string + + // READ-ONLY; Provisioning state. + ProvisioningState *JSONWebKeyType + + // READ-ONLY; Resource Status Message. + StatusMessage *string +} + +// EndpointDependency - A domain name that dedicated hsm services are reaching at. +type EndpointDependency struct { + // The domain name of the dependency. + DomainName *string + + // The Ports and Protocols used when connecting to domainName. + EndpointDetails []*EndpointDetail +} + +// EndpointDetail - Connect information from the dedicated hsm service to a single endpoint. +type EndpointDetail struct { + // Description of the detail + Description *string + + // An IP Address that Domain Name currently resolves to. + IPAddress *string + + // The port an endpoint is connected to. + Port *int32 + + // The protocol used for connection + Protocol *string +} + +// ErrorAdditionalInfo - The resource management error additional info. +type ErrorAdditionalInfo struct { + // READ-ONLY; The additional info. + Info any + + // READ-ONLY; The additional info type. + Type *string +} + +// ErrorDetail - The error detail. +type ErrorDetail struct { + // READ-ONLY; The error additional info. + AdditionalInfo []*ErrorAdditionalInfo + + // READ-ONLY; The error code. + Code *string + + // READ-ONLY; The error details. + Details []*ErrorDetail + + // READ-ONLY; The error message. + Message *string + + // READ-ONLY; The error target. + Target *string +} + +// ManagedServiceIdentity - Managed service identity (system assigned and/or user assigned identities) +type ManagedServiceIdentity struct { + // REQUIRED; The type of managed identity assigned to this resource. + Type *ManagedServiceIdentityType + + // The identities assigned to this resource by the user. + UserAssignedIdentities map[string]*UserAssignedIdentity + + // READ-ONLY; The service principal ID of the system assigned identity. This property will only be provided for a system assigned + // identity. + PrincipalID *string + + // READ-ONLY; The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + TenantID *string +} + +// NetworkInterface - The network interface definition. +type NetworkInterface struct { + // Private Ip address of the interface + PrivateIPAddress *string + + // READ-ONLY; The Azure resource id in the form of /subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroupName}/... + ResourceID *string +} + +// NetworkProfile - The network profile definition. +type NetworkProfile struct { + // Specifies the list of resource Ids for the network interfaces associated with the dedicated HSM. + NetworkInterfaces []*NetworkInterface + + // Specifies the identifier of the subnet. + Subnet *APIEntityReference +} + +// Operation - REST API Operation +// +// Details of a REST API operation, returned from the Resource Provider Operations API +type Operation struct { + // Localized display information for this particular operation. + Display *OperationDisplay + + // READ-ONLY; Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + ActionType *ActionType + + // READ-ONLY; Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure + // Resource Manager/control-plane operations. + IsDataAction *bool + + // READ-ONLY; The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + // "Microsoft.Compute/virtualMachines/capture/action" + Name *string + + // READ-ONLY; The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default + // value is "user,system" + Origin *Origin +} + +// OperationDisplay - Localized display information for an operation. +type OperationDisplay struct { + // READ-ONLY; The short, localized friendly description of the operation; suitable for tool tips and detailed views. + Description *string + + // READ-ONLY; The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual + // Machine", "Restart Virtual Machine". + Operation *string + + // READ-ONLY; The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft + // Compute". + Provider *string + + // READ-ONLY; The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job + // Schedule Collections". + Resource *string +} + +// OperationListResult - A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to +// get the next set of results. +type OperationListResult struct { + // REQUIRED; The Operation items on this page + Value []*Operation + + // The link to the next page of items + NextLink *string +} + +// OutboundEnvironmentEndpoint - Egress endpoints which dedicated hsm service connects to for common purpose. +type OutboundEnvironmentEndpoint struct { + // The category of endpoints accessed by the dedicated hsm service, e.g. azure-resource-management, apiserver, etc. + Category *string + + // The endpoints that dedicated hsm service connects to + Endpoints []*EndpointDependency +} + +// OutboundEnvironmentEndpointCollection - Collection of OutboundEnvironmentEndpoint +type OutboundEnvironmentEndpointCollection struct { + // REQUIRED; The OutboundEnvironmentEndpoint items on this page + Value []*OutboundEnvironmentEndpoint + + // The link to the next page of items + NextLink *string +} + +// PrivateEndpoint - The private endpoint resource. +type PrivateEndpoint struct { + // READ-ONLY; The resource identifier of the private endpoint + ID *string +} + +// PrivateEndpointConnection - The private endpoint connection resource. +type PrivateEndpointConnection struct { + // Modified whenever there is a change in the state of private endpoint connection. + Etag *string + + // Resource properties. + Properties *PrivateEndpointConnectionProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// PrivateEndpointConnectionListResult - The response of a PrivateEndpointConnection list operation. +type PrivateEndpointConnectionListResult struct { + // REQUIRED; The PrivateEndpointConnection items on this page + Value []*PrivateEndpointConnection + + // The link to the next page of items + NextLink *string +} + +// PrivateEndpointConnectionProperties - Properties of the private endpoint connection. +type PrivateEndpointConnectionProperties struct { + // REQUIRED; A collection of information about the state of the connection between service consumer and provider. + PrivateLinkServiceConnectionState *PrivateLinkServiceConnectionState + + // The private endpoint resource. + PrivateEndpoint *PrivateEndpoint + + // READ-ONLY; The group ids for the private endpoint resource. + GroupIDs []*string + + // READ-ONLY; The provisioning state of the private endpoint connection resource. + ProvisioningState *PrivateEndpointConnectionProvisioningState +} + +// PrivateLinkResource - A private link resource. +type PrivateLinkResource struct { + // Resource properties. + Properties *PrivateLinkResourceProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// PrivateLinkResourceListResult - A list of private link resources. +type PrivateLinkResourceListResult struct { + // Array of private link resources + Value []*PrivateLinkResource + + // READ-ONLY; URL to get the next set of operation list results (if there are any). + NextLink *string +} + +// PrivateLinkResourceProperties - Properties of a private link resource. +type PrivateLinkResourceProperties struct { + // The private link resource private link DNS zone name. + RequiredZoneNames []*string + + // READ-ONLY; The private link resource group id. + GroupID *string + + // READ-ONLY; The private link resource required member names. + RequiredMembers []*string +} + +// PrivateLinkServiceConnectionState - A collection of information about the state of the connection between service consumer +// and provider. +type PrivateLinkServiceConnectionState struct { + // A message indicating if changes on the service provider require any updates on the consumer. + ActionsRequired *string + + // The reason for approval/rejection of the connection. + Description *string + + // Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. + Status *PrivateEndpointServiceConnectionStatus +} + +// RestoreRequestProperties - Cloud Hsm Cluster restore information +type RestoreRequestProperties struct { + // REQUIRED; The Azure blob storage container Uri which contains the backup + AzureStorageBlobContainerURI *string + + // REQUIRED; An autogenerated unique string ID for labeling the backup. It contains both a UUID and a date timestamp. + BackupID *string + + // The SAS token pointing to an Azure blob storage container. This property is reserved for Azure Backup Service. + Token *string +} + +// RestoreResult - Restore operation properties +type RestoreResult struct { + // Backup and Restore operation common properties + Properties *BackupRestoreBaseResultProperties +} + +// SKU of the dedicated HSM +type SKU struct { + // SKU of the dedicated HSM + Name *SKUName +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time + + // The identity that created the resource. + CreatedBy *string + + // The type of identity that created the resource. + CreatedByType *CreatedByType + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time + + // The identity that last modified the resource. + LastModifiedBy *string + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType +} + +// UserAssignedIdentity - User assigned identity properties +type UserAssignedIdentity struct { + // READ-ONLY; The client ID of the assigned identity. + ClientID *string + + // READ-ONLY; The principal ID of the assigned identity. + PrincipalID *string +} diff --git a/test/local/armhardwaresecuritymodules/zz_models_serde.go b/test/local/armhardwaresecuritymodules/zz_models_serde.go new file mode 100644 index 000000000000..c741ad187a33 --- /dev/null +++ b/test/local/armhardwaresecuritymodules/zz_models_serde.go @@ -0,0 +1,1536 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armhardwaresecuritymodules + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type APIEntityReference. +func (a APIEntityReference) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "resourceId", a.ResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APIEntityReference. +func (a *APIEntityReference) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "resourceId": + err = unpopulate(val, "ResourceID", &a.ResourceID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BackupRequestProperties. +func (b BackupRequestProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "azureStorageBlobContainerUri", b.AzureStorageBlobContainerURI) + populate(objectMap, "token", b.Token) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BackupRequestProperties. +func (b *BackupRequestProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "azureStorageBlobContainerUri": + err = unpopulate(val, "AzureStorageBlobContainerURI", &b.AzureStorageBlobContainerURI) + delete(rawMsg, key) + case "token": + err = unpopulate(val, "Token", &b.Token) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BackupRestoreBaseResultProperties. +func (b BackupRestoreBaseResultProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "endTime", b.EndTime) + populate(objectMap, "error", b.Error) + populate(objectMap, "jobId", b.JobID) + populateTime[datetime.RFC3339](objectMap, "startTime", b.StartTime) + populate(objectMap, "status", b.Status) + populate(objectMap, "statusDetails", b.StatusDetails) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BackupRestoreBaseResultProperties. +func (b *BackupRestoreBaseResultProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "endTime": + err = unpopulateTime[datetime.RFC3339](val, "EndTime", &b.EndTime) + delete(rawMsg, key) + case "error": + err = unpopulate(val, "Error", &b.Error) + delete(rawMsg, key) + case "jobId": + err = unpopulate(val, "JobID", &b.JobID) + delete(rawMsg, key) + case "startTime": + err = unpopulateTime[datetime.RFC3339](val, "StartTime", &b.StartTime) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &b.Status) + delete(rawMsg, key) + case "statusDetails": + err = unpopulate(val, "StatusDetails", &b.StatusDetails) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BackupResult. +func (b BackupResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", b.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BackupResult. +func (b *BackupResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &b.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BackupResultProperties. +func (b BackupResultProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "azureStorageBlobContainerUri", b.AzureStorageBlobContainerURI) + populate(objectMap, "backupId", b.BackupID) + populateTime[datetime.RFC3339](objectMap, "endTime", b.EndTime) + populate(objectMap, "error", b.Error) + populate(objectMap, "jobId", b.JobID) + populateTime[datetime.RFC3339](objectMap, "startTime", b.StartTime) + populate(objectMap, "status", b.Status) + populate(objectMap, "statusDetails", b.StatusDetails) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BackupResultProperties. +func (b *BackupResultProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "azureStorageBlobContainerUri": + err = unpopulate(val, "AzureStorageBlobContainerURI", &b.AzureStorageBlobContainerURI) + delete(rawMsg, key) + case "backupId": + err = unpopulate(val, "BackupID", &b.BackupID) + delete(rawMsg, key) + case "endTime": + err = unpopulateTime[datetime.RFC3339](val, "EndTime", &b.EndTime) + delete(rawMsg, key) + case "error": + err = unpopulate(val, "Error", &b.Error) + delete(rawMsg, key) + case "jobId": + err = unpopulate(val, "JobID", &b.JobID) + delete(rawMsg, key) + case "startTime": + err = unpopulateTime[datetime.RFC3339](val, "StartTime", &b.StartTime) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &b.Status) + delete(rawMsg, key) + case "statusDetails": + err = unpopulate(val, "StatusDetails", &b.StatusDetails) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CloudHsmCluster. +func (c CloudHsmCluster) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", c.ID) + populate(objectMap, "identity", c.Identity) + populate(objectMap, "location", c.Location) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "sku", c.SKU) + populate(objectMap, "systemData", c.SystemData) + populate(objectMap, "tags", c.Tags) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudHsmCluster. +func (c *CloudHsmCluster) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &c.Identity) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &c.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &c.SKU) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &c.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &c.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CloudHsmClusterListResult. +func (c CloudHsmClusterListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", c.NextLink) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudHsmClusterListResult. +func (c *CloudHsmClusterListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &c.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &c.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CloudHsmClusterPatchParameters. +func (c CloudHsmClusterPatchParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identity", c.Identity) + populate(objectMap, "tags", c.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudHsmClusterPatchParameters. +func (c *CloudHsmClusterPatchParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "identity": + err = unpopulate(val, "Identity", &c.Identity) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &c.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CloudHsmClusterProperties. +func (c CloudHsmClusterProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "activationState", c.ActivationState) + populate(objectMap, "autoGeneratedDomainNameLabelScope", c.AutoGeneratedDomainNameLabelScope) + populate(objectMap, "hsms", c.Hsms) + populate(objectMap, "privateEndpointConnections", c.PrivateEndpointConnections) + populate(objectMap, "provisioningState", c.ProvisioningState) + populate(objectMap, "publicNetworkAccess", c.PublicNetworkAccess) + populate(objectMap, "statusMessage", c.StatusMessage) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudHsmClusterProperties. +func (c *CloudHsmClusterProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "activationState": + err = unpopulate(val, "ActivationState", &c.ActivationState) + delete(rawMsg, key) + case "autoGeneratedDomainNameLabelScope": + err = unpopulate(val, "AutoGeneratedDomainNameLabelScope", &c.AutoGeneratedDomainNameLabelScope) + delete(rawMsg, key) + case "hsms": + err = unpopulate(val, "Hsms", &c.Hsms) + delete(rawMsg, key) + case "privateEndpointConnections": + err = unpopulate(val, "PrivateEndpointConnections", &c.PrivateEndpointConnections) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &c.ProvisioningState) + delete(rawMsg, key) + case "publicNetworkAccess": + err = unpopulate(val, "PublicNetworkAccess", &c.PublicNetworkAccess) + delete(rawMsg, key) + case "statusMessage": + err = unpopulate(val, "StatusMessage", &c.StatusMessage) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CloudHsmClusterSKU. +func (c CloudHsmClusterSKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "capacity", c.Capacity) + populate(objectMap, "family", c.Family) + populate(objectMap, "name", c.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudHsmClusterSKU. +func (c *CloudHsmClusterSKU) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "capacity": + err = unpopulate(val, "Capacity", &c.Capacity) + delete(rawMsg, key) + case "family": + err = unpopulate(val, "Family", &c.Family) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CloudHsmProperties. +func (c CloudHsmProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "fqdn", c.Fqdn) + populate(objectMap, "state", c.State) + populate(objectMap, "stateMessage", c.StateMessage) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudHsmProperties. +func (c *CloudHsmProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "fqdn": + err = unpopulate(val, "Fqdn", &c.Fqdn) + delete(rawMsg, key) + case "state": + err = unpopulate(val, "State", &c.State) + delete(rawMsg, key) + case "stateMessage": + err = unpopulate(val, "StateMessage", &c.StateMessage) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DedicatedHsm. +func (d DedicatedHsm) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", d.ID) + populate(objectMap, "location", d.Location) + populate(objectMap, "name", d.Name) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "sku", d.SKU) + populate(objectMap, "systemData", d.SystemData) + populate(objectMap, "tags", d.Tags) + populate(objectMap, "type", d.Type) + populate(objectMap, "zones", d.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DedicatedHsm. +func (d *DedicatedHsm) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &d.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &d.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &d.SKU) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &d.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &d.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &d.Type) + delete(rawMsg, key) + case "zones": + err = unpopulate(val, "Zones", &d.Zones) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DedicatedHsmListResult. +func (d DedicatedHsmListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", d.NextLink) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DedicatedHsmListResult. +func (d *DedicatedHsmListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &d.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &d.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DedicatedHsmPatchParameters. +func (d DedicatedHsmPatchParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "tags", d.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DedicatedHsmPatchParameters. +func (d *DedicatedHsmPatchParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "tags": + err = unpopulate(val, "Tags", &d.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DedicatedHsmProperties. +func (d DedicatedHsmProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "managementNetworkProfile", d.ManagementNetworkProfile) + populate(objectMap, "networkProfile", d.NetworkProfile) + populate(objectMap, "provisioningState", d.ProvisioningState) + populate(objectMap, "stampId", d.StampID) + populate(objectMap, "statusMessage", d.StatusMessage) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DedicatedHsmProperties. +func (d *DedicatedHsmProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "managementNetworkProfile": + err = unpopulate(val, "ManagementNetworkProfile", &d.ManagementNetworkProfile) + delete(rawMsg, key) + case "networkProfile": + err = unpopulate(val, "NetworkProfile", &d.NetworkProfile) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &d.ProvisioningState) + delete(rawMsg, key) + case "stampId": + err = unpopulate(val, "StampID", &d.StampID) + delete(rawMsg, key) + case "statusMessage": + err = unpopulate(val, "StatusMessage", &d.StatusMessage) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EndpointDependency. +func (e EndpointDependency) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "domainName", e.DomainName) + populate(objectMap, "endpointDetails", e.EndpointDetails) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EndpointDependency. +func (e *EndpointDependency) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "domainName": + err = unpopulate(val, "DomainName", &e.DomainName) + delete(rawMsg, key) + case "endpointDetails": + err = unpopulate(val, "EndpointDetails", &e.EndpointDetails) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EndpointDetail. +func (e EndpointDetail) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", e.Description) + populate(objectMap, "ipAddress", e.IPAddress) + populate(objectMap, "port", e.Port) + populate(objectMap, "protocol", e.Protocol) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EndpointDetail. +func (e *EndpointDetail) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &e.Description) + delete(rawMsg, key) + case "ipAddress": + err = unpopulate(val, "IPAddress", &e.IPAddress) + delete(rawMsg, key) + case "port": + err = unpopulate(val, "Port", &e.Port) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &e.Protocol) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ErrorAdditionalInfo. +func (e ErrorAdditionalInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateAny(objectMap, "info", e.Info) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ErrorAdditionalInfo. +func (e *ErrorAdditionalInfo) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "info": + err = unpopulate(val, "Info", &e.Info) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &e.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ErrorDetail. +func (e ErrorDetail) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "additionalInfo", e.AdditionalInfo) + populate(objectMap, "code", e.Code) + populate(objectMap, "details", e.Details) + populate(objectMap, "message", e.Message) + populate(objectMap, "target", e.Target) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ErrorDetail. +func (e *ErrorDetail) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "additionalInfo": + err = unpopulate(val, "AdditionalInfo", &e.AdditionalInfo) + delete(rawMsg, key) + case "code": + err = unpopulate(val, "Code", &e.Code) + delete(rawMsg, key) + case "details": + err = unpopulate(val, "Details", &e.Details) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &e.Message) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &e.Target) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedServiceIdentity. +func (m ManagedServiceIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "principalId", m.PrincipalID) + populate(objectMap, "tenantId", m.TenantID) + populate(objectMap, "type", m.Type) + populate(objectMap, "userAssignedIdentities", m.UserAssignedIdentities) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedServiceIdentity. +func (m *ManagedServiceIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "principalId": + err = unpopulate(val, "PrincipalID", &m.PrincipalID) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &m.TenantID) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + case "userAssignedIdentities": + err = unpopulate(val, "UserAssignedIdentities", &m.UserAssignedIdentities) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkInterface. +func (n NetworkInterface) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "privateIpAddress", n.PrivateIPAddress) + populate(objectMap, "resourceId", n.ResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkInterface. +func (n *NetworkInterface) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "privateIpAddress": + err = unpopulate(val, "PrivateIPAddress", &n.PrivateIPAddress) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &n.ResourceID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkProfile. +func (n NetworkProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "networkInterfaces", n.NetworkInterfaces) + populate(objectMap, "subnet", n.Subnet) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkProfile. +func (n *NetworkProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "networkInterfaces": + err = unpopulate(val, "NetworkInterfaces", &n.NetworkInterfaces) + delete(rawMsg, key) + case "subnet": + err = unpopulate(val, "Subnet", &n.Subnet) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Operation. +func (o Operation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionType", o.ActionType) + populate(objectMap, "display", o.Display) + populate(objectMap, "isDataAction", o.IsDataAction) + populate(objectMap, "name", o.Name) + populate(objectMap, "origin", o.Origin) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Operation. +func (o *Operation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionType": + err = unpopulate(val, "ActionType", &o.ActionType) + delete(rawMsg, key) + case "display": + err = unpopulate(val, "Display", &o.Display) + delete(rawMsg, key) + case "isDataAction": + err = unpopulate(val, "IsDataAction", &o.IsDataAction) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "origin": + err = unpopulate(val, "Origin", &o.Origin) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationDisplay. +func (o OperationDisplay) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", o.Description) + populate(objectMap, "operation", o.Operation) + populate(objectMap, "provider", o.Provider) + populate(objectMap, "resource", o.Resource) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationDisplay. +func (o *OperationDisplay) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &o.Description) + delete(rawMsg, key) + case "operation": + err = unpopulate(val, "Operation", &o.Operation) + delete(rawMsg, key) + case "provider": + err = unpopulate(val, "Provider", &o.Provider) + delete(rawMsg, key) + case "resource": + err = unpopulate(val, "Resource", &o.Resource) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationListResult. +func (o *OperationListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &o.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OutboundEnvironmentEndpoint. +func (o OutboundEnvironmentEndpoint) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "category", o.Category) + populate(objectMap, "endpoints", o.Endpoints) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OutboundEnvironmentEndpoint. +func (o *OutboundEnvironmentEndpoint) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "category": + err = unpopulate(val, "Category", &o.Category) + delete(rawMsg, key) + case "endpoints": + err = unpopulate(val, "Endpoints", &o.Endpoints) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OutboundEnvironmentEndpointCollection. +func (o OutboundEnvironmentEndpointCollection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OutboundEnvironmentEndpointCollection. +func (o *OutboundEnvironmentEndpointCollection) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &o.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpoint. +func (p PrivateEndpoint) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", p.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpoint. +func (p *PrivateEndpoint) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnection. +func (p PrivateEndpointConnection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "etag", p.Etag) + populate(objectMap, "id", p.ID) + populate(objectMap, "name", p.Name) + populate(objectMap, "properties", p.Properties) + populate(objectMap, "systemData", p.SystemData) + populate(objectMap, "type", p.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpointConnection. +func (p *PrivateEndpointConnection) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, "Etag", &p.Etag) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &p.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &p.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &p.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnectionListResult. +func (p PrivateEndpointConnectionListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", p.NextLink) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpointConnectionListResult. +func (p *PrivateEndpointConnectionListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &p.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnectionProperties. +func (p PrivateEndpointConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "groupIds", p.GroupIDs) + populate(objectMap, "privateEndpoint", p.PrivateEndpoint) + populate(objectMap, "privateLinkServiceConnectionState", p.PrivateLinkServiceConnectionState) + populate(objectMap, "provisioningState", p.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpointConnectionProperties. +func (p *PrivateEndpointConnectionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "groupIds": + err = unpopulate(val, "GroupIDs", &p.GroupIDs) + delete(rawMsg, key) + case "privateEndpoint": + err = unpopulate(val, "PrivateEndpoint", &p.PrivateEndpoint) + delete(rawMsg, key) + case "privateLinkServiceConnectionState": + err = unpopulate(val, "PrivateLinkServiceConnectionState", &p.PrivateLinkServiceConnectionState) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResource. +func (p PrivateLinkResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", p.ID) + populate(objectMap, "name", p.Name) + populate(objectMap, "properties", p.Properties) + populate(objectMap, "systemData", p.SystemData) + populate(objectMap, "type", p.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkResource. +func (p *PrivateLinkResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &p.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &p.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &p.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResourceListResult. +func (p PrivateLinkResourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", p.NextLink) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkResourceListResult. +func (p *PrivateLinkResourceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &p.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResourceProperties. +func (p PrivateLinkResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "groupId", p.GroupID) + populate(objectMap, "requiredMembers", p.RequiredMembers) + populate(objectMap, "requiredZoneNames", p.RequiredZoneNames) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkResourceProperties. +func (p *PrivateLinkResourceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "groupId": + err = unpopulate(val, "GroupID", &p.GroupID) + delete(rawMsg, key) + case "requiredMembers": + err = unpopulate(val, "RequiredMembers", &p.RequiredMembers) + delete(rawMsg, key) + case "requiredZoneNames": + err = unpopulate(val, "RequiredZoneNames", &p.RequiredZoneNames) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkServiceConnectionState. +func (p PrivateLinkServiceConnectionState) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionsRequired", p.ActionsRequired) + populate(objectMap, "description", p.Description) + populate(objectMap, "status", p.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkServiceConnectionState. +func (p *PrivateLinkServiceConnectionState) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionsRequired": + err = unpopulate(val, "ActionsRequired", &p.ActionsRequired) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &p.Description) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &p.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RestoreRequestProperties. +func (r RestoreRequestProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "azureStorageBlobContainerUri", r.AzureStorageBlobContainerURI) + populate(objectMap, "backupId", r.BackupID) + populate(objectMap, "token", r.Token) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RestoreRequestProperties. +func (r *RestoreRequestProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "azureStorageBlobContainerUri": + err = unpopulate(val, "AzureStorageBlobContainerURI", &r.AzureStorageBlobContainerURI) + delete(rawMsg, key) + case "backupId": + err = unpopulate(val, "BackupID", &r.BackupID) + delete(rawMsg, key) + case "token": + err = unpopulate(val, "Token", &r.Token) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RestoreResult. +func (r RestoreResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", r.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RestoreResult. +func (r *RestoreResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &r.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SKU. +func (s SKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", s.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SKU. +func (s *SKU) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateTime[datetime.RFC3339](objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateTime[datetime.RFC3339](val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateTime[datetime.RFC3339](val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserAssignedIdentity. +func (u UserAssignedIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clientId", u.ClientID) + populate(objectMap, "principalId", u.PrincipalID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserAssignedIdentity. +func (u *UserAssignedIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "clientId": + err = unpopulate(val, "ClientID", &u.ClientID) + delete(rawMsg, key) + case "principalId": + err = unpopulate(val, "PrincipalID", &u.PrincipalID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func populateAny(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/local/armhardwaresecuritymodules/zz_operations_client.go b/test/local/armhardwaresecuritymodules/zz_operations_client.go new file mode 100644 index 000000000000..08a26a3b9185 --- /dev/null +++ b/test/local/armhardwaresecuritymodules/zz_operations_client.go @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armhardwaresecuritymodules + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +// +// Generated from API version 2025-03-31 +type OperationsClient struct { + internal *arm.Client +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*OperationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OperationsClient{ + internal: cl, + } + return client, nil +} + +// NewListPager - List the operations for the provider +// - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ + More: func(page OperationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OperationsClientListResponse) (OperationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OperationsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return OperationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, _ *OperationsClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.HardwareSecurityModules/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250331) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsClientListResponse, error) { + result := OperationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armhardwaresecuritymodules/zz_options.go b/test/local/armhardwaresecuritymodules/zz_options.go new file mode 100644 index 000000000000..9f9d1a0cb27a --- /dev/null +++ b/test/local/armhardwaresecuritymodules/zz_options.go @@ -0,0 +1,171 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armhardwaresecuritymodules + +// CloudHsmClusterBackupStatusClientGetOptions contains the optional parameters for the CloudHsmClusterBackupStatusClient.Get +// method. +type CloudHsmClusterBackupStatusClientGetOptions struct { + // placeholder for future optional parameters +} + +// CloudHsmClusterPrivateEndpointConnectionsClientBeginDeleteOptions contains the optional parameters for the CloudHsmClusterPrivateEndpointConnectionsClient.BeginDelete +// method. +type CloudHsmClusterPrivateEndpointConnectionsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CloudHsmClusterPrivateEndpointConnectionsClientCreateOptions contains the optional parameters for the CloudHsmClusterPrivateEndpointConnectionsClient.Create +// method. +type CloudHsmClusterPrivateEndpointConnectionsClientCreateOptions struct { + // placeholder for future optional parameters +} + +// CloudHsmClusterPrivateEndpointConnectionsClientGetOptions contains the optional parameters for the CloudHsmClusterPrivateEndpointConnectionsClient.Get +// method. +type CloudHsmClusterPrivateEndpointConnectionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// CloudHsmClusterPrivateLinkResourcesClientListByCloudHsmClusterOptions contains the optional parameters for the CloudHsmClusterPrivateLinkResourcesClient.NewListByCloudHsmClusterPager +// method. +type CloudHsmClusterPrivateLinkResourcesClientListByCloudHsmClusterOptions struct { + // placeholder for future optional parameters +} + +// CloudHsmClusterRestoreStatusClientGetOptions contains the optional parameters for the CloudHsmClusterRestoreStatusClient.Get +// method. +type CloudHsmClusterRestoreStatusClientGetOptions struct { + // placeholder for future optional parameters +} + +// CloudHsmClustersClientBeginBackupOptions contains the optional parameters for the CloudHsmClustersClient.BeginBackup method. +type CloudHsmClustersClientBeginBackupOptions struct { + // Azure storage Resource Uri + BackupRequestProperties *BackupRequestProperties + + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CloudHsmClustersClientBeginCreateOrUpdateOptions contains the optional parameters for the CloudHsmClustersClient.BeginCreateOrUpdate +// method. +type CloudHsmClustersClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CloudHsmClustersClientBeginDeleteOptions contains the optional parameters for the CloudHsmClustersClient.BeginDelete method. +type CloudHsmClustersClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CloudHsmClustersClientBeginRestoreOptions contains the optional parameters for the CloudHsmClustersClient.BeginRestore +// method. +type CloudHsmClustersClientBeginRestoreOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CloudHsmClustersClientBeginUpdateOptions contains the optional parameters for the CloudHsmClustersClient.BeginUpdate method. +type CloudHsmClustersClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CloudHsmClustersClientBeginValidateBackupPropertiesOptions contains the optional parameters for the CloudHsmClustersClient.BeginValidateBackupProperties +// method. +type CloudHsmClustersClientBeginValidateBackupPropertiesOptions struct { + // Backup Operation Required properties + BackupRequestProperties *BackupRequestProperties + + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CloudHsmClustersClientBeginValidateRestorePropertiesOptions contains the optional parameters for the CloudHsmClustersClient.BeginValidateRestoreProperties +// method. +type CloudHsmClustersClientBeginValidateRestorePropertiesOptions struct { + // Optional Parameters to validate prior performing a restore operation. + RestoreRequestProperties *RestoreRequestProperties + + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CloudHsmClustersClientGetOptions contains the optional parameters for the CloudHsmClustersClient.Get method. +type CloudHsmClustersClientGetOptions struct { + // placeholder for future optional parameters +} + +// CloudHsmClustersClientListByResourceGroupOptions contains the optional parameters for the CloudHsmClustersClient.NewListByResourceGroupPager +// method. +type CloudHsmClustersClientListByResourceGroupOptions struct { + // The page-continuation token to use with a paged version of this API + Skiptoken *string +} + +// CloudHsmClustersClientListBySubscriptionOptions contains the optional parameters for the CloudHsmClustersClient.NewListBySubscriptionPager +// method. +type CloudHsmClustersClientListBySubscriptionOptions struct { + // The page-continuation token to use with a paged version of this API + Skiptoken *string +} + +// DedicatedHsmClientBeginCreateOrUpdateOptions contains the optional parameters for the DedicatedHsmClient.BeginCreateOrUpdate +// method. +type DedicatedHsmClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// DedicatedHsmClientBeginDeleteOptions contains the optional parameters for the DedicatedHsmClient.BeginDelete method. +type DedicatedHsmClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// DedicatedHsmClientBeginUpdateOptions contains the optional parameters for the DedicatedHsmClient.BeginUpdate method. +type DedicatedHsmClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// DedicatedHsmClientGetOptions contains the optional parameters for the DedicatedHsmClient.Get method. +type DedicatedHsmClientGetOptions struct { + // placeholder for future optional parameters +} + +// DedicatedHsmClientListByResourceGroupOptions contains the optional parameters for the DedicatedHsmClient.NewListByResourceGroupPager +// method. +type DedicatedHsmClientListByResourceGroupOptions struct { + // Maximum number of results to return. + Top *int32 +} + +// DedicatedHsmClientListBySubscriptionOptions contains the optional parameters for the DedicatedHsmClient.NewListBySubscriptionPager +// method. +type DedicatedHsmClientListBySubscriptionOptions struct { + // Maximum number of results to return. + Top *int32 +} + +// DedicatedHsmClientListOutboundNetworkDependenciesEndpointsOptions contains the optional parameters for the DedicatedHsmClient.NewListOutboundNetworkDependenciesEndpointsPager +// method. +type DedicatedHsmClientListOutboundNetworkDependenciesEndpointsOptions struct { + // placeholder for future optional parameters +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointConnectionsClientListByCloudHsmClusterOptions contains the optional parameters for the PrivateEndpointConnectionsClient.NewListByCloudHsmClusterPager +// method. +type PrivateEndpointConnectionsClientListByCloudHsmClusterOptions struct { + // placeholder for future optional parameters +} diff --git a/test/local/armhardwaresecuritymodules/zz_privateendpointconnections_client.go b/test/local/armhardwaresecuritymodules/zz_privateendpointconnections_client.go new file mode 100644 index 000000000000..ee3a8c1dc1e2 --- /dev/null +++ b/test/local/armhardwaresecuritymodules/zz_privateendpointconnections_client.go @@ -0,0 +1,107 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armhardwaresecuritymodules + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// PrivateEndpointConnectionsClient contains the methods for the PrivateEndpointConnections group. +// Don't use this type directly, use NewPrivateEndpointConnectionsClient() instead. +// +// Generated from API version 2025-03-31 +type PrivateEndpointConnectionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewPrivateEndpointConnectionsClient creates a new instance of PrivateEndpointConnectionsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewPrivateEndpointConnectionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*PrivateEndpointConnectionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &PrivateEndpointConnectionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListByCloudHsmClusterPager - The List operation gets information about the private endpoint connections associated with +// the Cloud HSM Cluster +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudHsmClusterName - The name of the Cloud HSM Cluster within the specified resource group. Cloud HSM Cluster names must +// be between 3 and 23 characters in length. +// - options - PrivateEndpointConnectionsClientListByCloudHsmClusterOptions contains the optional parameters for the PrivateEndpointConnectionsClient.NewListByCloudHsmClusterPager +// method. +func (client *PrivateEndpointConnectionsClient) NewListByCloudHsmClusterPager(resourceGroupName string, cloudHsmClusterName string, options *PrivateEndpointConnectionsClientListByCloudHsmClusterOptions) *runtime.Pager[PrivateEndpointConnectionsClientListByCloudHsmClusterResponse] { + return runtime.NewPager(runtime.PagingHandler[PrivateEndpointConnectionsClientListByCloudHsmClusterResponse]{ + More: func(page PrivateEndpointConnectionsClientListByCloudHsmClusterResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PrivateEndpointConnectionsClientListByCloudHsmClusterResponse) (PrivateEndpointConnectionsClientListByCloudHsmClusterResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PrivateEndpointConnectionsClient.NewListByCloudHsmClusterPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByCloudHsmClusterCreateRequest(ctx, resourceGroupName, cloudHsmClusterName, options) + }, nil) + if err != nil { + return PrivateEndpointConnectionsClientListByCloudHsmClusterResponse{}, err + } + return client.listByCloudHsmClusterHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByCloudHsmClusterCreateRequest creates the ListByCloudHsmCluster request. +func (client *PrivateEndpointConnectionsClient) listByCloudHsmClusterCreateRequest(ctx context.Context, resourceGroupName string, cloudHsmClusterName string, _ *PrivateEndpointConnectionsClientListByCloudHsmClusterOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HardwareSecurityModules/cloudHsmClusters/{cloudHsmClusterName}/privateEndpointConnections" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudHsmClusterName == "" { + return nil, errors.New("parameter cloudHsmClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudHsmClusterName}", url.PathEscape(cloudHsmClusterName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250331) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByCloudHsmClusterHandleResponse handles the ListByCloudHsmCluster response. +func (client *PrivateEndpointConnectionsClient) listByCloudHsmClusterHandleResponse(resp *http.Response) (PrivateEndpointConnectionsClientListByCloudHsmClusterResponse, error) { + result := PrivateEndpointConnectionsClientListByCloudHsmClusterResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnectionListResult); err != nil { + return PrivateEndpointConnectionsClientListByCloudHsmClusterResponse{}, err + } + return result, nil +} diff --git a/test/local/armhardwaresecuritymodules/zz_responses.go b/test/local/armhardwaresecuritymodules/zz_responses.go new file mode 100644 index 000000000000..8fa767d7acf6 --- /dev/null +++ b/test/local/armhardwaresecuritymodules/zz_responses.go @@ -0,0 +1,164 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armhardwaresecuritymodules + +// CloudHsmClusterBackupStatusClientGetResponse contains the response from method CloudHsmClusterBackupStatusClient.Get. +type CloudHsmClusterBackupStatusClientGetResponse struct { + // Backup operation Result + BackupResult + + // The Location header contains the URL where the status of the long running operation can be checked. + Location *string + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string +} + +// CloudHsmClusterPrivateEndpointConnectionsClientCreateResponse contains the response from method CloudHsmClusterPrivateEndpointConnectionsClient.Create. +type CloudHsmClusterPrivateEndpointConnectionsClientCreateResponse struct { + // The private endpoint connection resource. + PrivateEndpointConnection +} + +// CloudHsmClusterPrivateEndpointConnectionsClientDeleteResponse contains the response from method CloudHsmClusterPrivateEndpointConnectionsClient.BeginDelete. +type CloudHsmClusterPrivateEndpointConnectionsClientDeleteResponse struct { + // placeholder for future response values +} + +// CloudHsmClusterPrivateEndpointConnectionsClientGetResponse contains the response from method CloudHsmClusterPrivateEndpointConnectionsClient.Get. +type CloudHsmClusterPrivateEndpointConnectionsClientGetResponse struct { + // The private endpoint connection resource. + PrivateEndpointConnection +} + +// CloudHsmClusterPrivateLinkResourcesClientListByCloudHsmClusterResponse contains the response from method CloudHsmClusterPrivateLinkResourcesClient.NewListByCloudHsmClusterPager. +type CloudHsmClusterPrivateLinkResourcesClientListByCloudHsmClusterResponse struct { + // A list of private link resources. + PrivateLinkResourceListResult +} + +// CloudHsmClusterRestoreStatusClientGetResponse contains the response from method CloudHsmClusterRestoreStatusClient.Get. +type CloudHsmClusterRestoreStatusClientGetResponse struct { + // Restore operation properties + RestoreResult + + // The Location header contains the URL where the status of the long running operation can be checked. + Location *string + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string +} + +// CloudHsmClustersClientBackupResponse contains the response from method CloudHsmClustersClient.BeginBackup. +type CloudHsmClustersClientBackupResponse struct { + // Backup operation Result + BackupResult +} + +// CloudHsmClustersClientCreateOrUpdateResponse contains the response from method CloudHsmClustersClient.BeginCreateOrUpdate. +type CloudHsmClustersClientCreateOrUpdateResponse struct { + // Resource information with extended details. + CloudHsmCluster +} + +// CloudHsmClustersClientDeleteResponse contains the response from method CloudHsmClustersClient.BeginDelete. +type CloudHsmClustersClientDeleteResponse struct { + // placeholder for future response values +} + +// CloudHsmClustersClientGetResponse contains the response from method CloudHsmClustersClient.Get. +type CloudHsmClustersClientGetResponse struct { + // Resource information with extended details. + CloudHsmCluster +} + +// CloudHsmClustersClientListByResourceGroupResponse contains the response from method CloudHsmClustersClient.NewListByResourceGroupPager. +type CloudHsmClustersClientListByResourceGroupResponse struct { + // The response of a CloudHsmCluster list operation. + CloudHsmClusterListResult +} + +// CloudHsmClustersClientListBySubscriptionResponse contains the response from method CloudHsmClustersClient.NewListBySubscriptionPager. +type CloudHsmClustersClientListBySubscriptionResponse struct { + // The response of a CloudHsmCluster list operation. + CloudHsmClusterListResult +} + +// CloudHsmClustersClientRestoreResponse contains the response from method CloudHsmClustersClient.BeginRestore. +type CloudHsmClustersClientRestoreResponse struct { + // Restore operation properties + RestoreResult +} + +// CloudHsmClustersClientUpdateResponse contains the response from method CloudHsmClustersClient.BeginUpdate. +type CloudHsmClustersClientUpdateResponse struct { + // Resource information with extended details. + CloudHsmCluster +} + +// CloudHsmClustersClientValidateBackupPropertiesResponse contains the response from method CloudHsmClustersClient.BeginValidateBackupProperties. +type CloudHsmClustersClientValidateBackupPropertiesResponse struct { + // Backup operation Result + BackupResult +} + +// CloudHsmClustersClientValidateRestorePropertiesResponse contains the response from method CloudHsmClustersClient.BeginValidateRestoreProperties. +type CloudHsmClustersClientValidateRestorePropertiesResponse struct { + // Restore operation properties + RestoreResult +} + +// DedicatedHsmClientCreateOrUpdateResponse contains the response from method DedicatedHsmClient.BeginCreateOrUpdate. +type DedicatedHsmClientCreateOrUpdateResponse struct { + // Resource information with extended details. + DedicatedHsm +} + +// DedicatedHsmClientDeleteResponse contains the response from method DedicatedHsmClient.BeginDelete. +type DedicatedHsmClientDeleteResponse struct { + // placeholder for future response values +} + +// DedicatedHsmClientGetResponse contains the response from method DedicatedHsmClient.Get. +type DedicatedHsmClientGetResponse struct { + // Resource information with extended details. + DedicatedHsm +} + +// DedicatedHsmClientListByResourceGroupResponse contains the response from method DedicatedHsmClient.NewListByResourceGroupPager. +type DedicatedHsmClientListByResourceGroupResponse struct { + // The response of a DedicatedHsm list operation. + DedicatedHsmListResult +} + +// DedicatedHsmClientListBySubscriptionResponse contains the response from method DedicatedHsmClient.NewListBySubscriptionPager. +type DedicatedHsmClientListBySubscriptionResponse struct { + // The response of a DedicatedHsm list operation. + DedicatedHsmListResult +} + +// DedicatedHsmClientListOutboundNetworkDependenciesEndpointsResponse contains the response from method DedicatedHsmClient.NewListOutboundNetworkDependenciesEndpointsPager. +type DedicatedHsmClientListOutboundNetworkDependenciesEndpointsResponse struct { + // Collection of OutboundEnvironmentEndpoint + OutboundEnvironmentEndpointCollection +} + +// DedicatedHsmClientUpdateResponse contains the response from method DedicatedHsmClient.BeginUpdate. +type DedicatedHsmClientUpdateResponse struct { + // Resource information with extended details. + DedicatedHsm +} + +// OperationsClientListResponse contains the response from method OperationsClient.NewListPager. +type OperationsClientListResponse struct { + // A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. + OperationListResult +} + +// PrivateEndpointConnectionsClientListByCloudHsmClusterResponse contains the response from method PrivateEndpointConnectionsClient.NewListByCloudHsmClusterPager. +type PrivateEndpointConnectionsClientListByCloudHsmClusterResponse struct { + // The response of a PrivateEndpointConnection list operation. + PrivateEndpointConnectionListResult +} diff --git a/test/local/armhardwaresecuritymodules/zz_version.go b/test/local/armhardwaresecuritymodules/zz_version.go new file mode 100644 index 000000000000..cedeed72f398 --- /dev/null +++ b/test/local/armhardwaresecuritymodules/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package armhardwaresecuritymodules + +const ( + moduleName = "armhardwaresecuritymodules" + moduleVersion = "v0.1.0" +) diff --git a/test/local/armhealthbot/LICENSE.txt b/test/local/armhealthbot/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/local/armhealthbot/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/local/armhealthbot/fake/zz_bots_server.go b/test/local/armhealthbot/fake/zz_bots_server.go new file mode 100644 index 000000000000..6bf2e231d265 --- /dev/null +++ b/test/local/armhealthbot/fake/zz_bots_server.go @@ -0,0 +1,448 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armhealthbot" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// BotsServer is a fake server for instances of the armhealthbot.BotsClient type. +type BotsServer struct { + // BeginCreate is the fake for method BotsClient.BeginCreate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreate func(ctx context.Context, resourceGroupName string, botName string, parameters armhealthbot.HealthBot, options *armhealthbot.BotsClientBeginCreateOptions) (resp azfake.PollerResponder[armhealthbot.BotsClientCreateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method BotsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, botName string, options *armhealthbot.BotsClientBeginDeleteOptions) (resp azfake.PollerResponder[armhealthbot.BotsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method BotsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, botName string, options *armhealthbot.BotsClientGetOptions) (resp azfake.Responder[armhealthbot.BotsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method BotsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armhealthbot.BotsClientListOptions) (resp azfake.PagerResponder[armhealthbot.BotsClientListResponse]) + + // NewListByResourceGroupPager is the fake for method BotsClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armhealthbot.BotsClientListByResourceGroupOptions) (resp azfake.PagerResponder[armhealthbot.BotsClientListByResourceGroupResponse]) + + // ListSecrets is the fake for method BotsClient.ListSecrets + // HTTP status codes to indicate success: http.StatusOK + ListSecrets func(ctx context.Context, resourceGroupName string, botName string, options *armhealthbot.BotsClientListSecretsOptions) (resp azfake.Responder[armhealthbot.BotsClientListSecretsResponse], errResp azfake.ErrorResponder) + + // RegenerateAPIJwtSecret is the fake for method BotsClient.RegenerateAPIJwtSecret + // HTTP status codes to indicate success: http.StatusOK + RegenerateAPIJwtSecret func(ctx context.Context, resourceGroupName string, botName string, options *armhealthbot.BotsClientRegenerateAPIJwtSecretOptions) (resp azfake.Responder[armhealthbot.BotsClientRegenerateAPIJwtSecretResponse], errResp azfake.ErrorResponder) + + // BeginUpdate is the fake for method BotsClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginUpdate func(ctx context.Context, resourceGroupName string, botName string, parameters armhealthbot.UpdateParameters, options *armhealthbot.BotsClientBeginUpdateOptions) (resp azfake.PollerResponder[armhealthbot.BotsClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewBotsServerTransport creates a new instance of BotsServerTransport with the provided implementation. +// The returned BotsServerTransport instance is connected to an instance of armhealthbot.BotsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewBotsServerTransport(srv *BotsServer) *BotsServerTransport { + return &BotsServerTransport{ + srv: srv, + beginCreate: newTracker[azfake.PollerResponder[armhealthbot.BotsClientCreateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armhealthbot.BotsClientDeleteResponse]](), + newListPager: newTracker[azfake.PagerResponder[armhealthbot.BotsClientListResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armhealthbot.BotsClientListByResourceGroupResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armhealthbot.BotsClientUpdateResponse]](), + } +} + +// BotsServerTransport connects instances of armhealthbot.BotsClient to instances of BotsServer. +// Don't use this type directly, use NewBotsServerTransport instead. +type BotsServerTransport struct { + srv *BotsServer + beginCreate *tracker[azfake.PollerResponder[armhealthbot.BotsClientCreateResponse]] + beginDelete *tracker[azfake.PollerResponder[armhealthbot.BotsClientDeleteResponse]] + newListPager *tracker[azfake.PagerResponder[armhealthbot.BotsClientListResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armhealthbot.BotsClientListByResourceGroupResponse]] + beginUpdate *tracker[azfake.PollerResponder[armhealthbot.BotsClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for BotsServerTransport. +func (b *BotsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return b.dispatchToMethodFake(req, method) +} + +func (b *BotsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if botsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = botsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "BotsClient.BeginCreate": + res.resp, res.err = b.dispatchBeginCreate(req) + case "BotsClient.BeginDelete": + res.resp, res.err = b.dispatchBeginDelete(req) + case "BotsClient.Get": + res.resp, res.err = b.dispatchGet(req) + case "BotsClient.NewListPager": + res.resp, res.err = b.dispatchNewListPager(req) + case "BotsClient.NewListByResourceGroupPager": + res.resp, res.err = b.dispatchNewListByResourceGroupPager(req) + case "BotsClient.ListSecrets": + res.resp, res.err = b.dispatchListSecrets(req) + case "BotsClient.RegenerateAPIJwtSecret": + res.resp, res.err = b.dispatchRegenerateAPIJwtSecret(req) + case "BotsClient.BeginUpdate": + res.resp, res.err = b.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (b *BotsServerTransport) dispatchBeginCreate(req *http.Request) (*http.Response, error) { + if b.srv.BeginCreate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreate not implemented")} + } + beginCreate := b.beginCreate.get(req) + if beginCreate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HealthBot/healthBots/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armhealthbot.HealthBot](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + botNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("botName")]) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.BeginCreate(req.Context(), resourceGroupNameParam, botNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreate = &respr + b.beginCreate.add(req, beginCreate) + } + + resp, err := server.PollerResponderNext(beginCreate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + b.beginCreate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreate) { + b.beginCreate.remove(req) + } + + return resp, nil +} + +func (b *BotsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if b.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := b.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HealthBot/healthBots/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + botNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("botName")]) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.BeginDelete(req.Context(), resourceGroupNameParam, botNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + b.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + b.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + b.beginDelete.remove(req) + } + + return resp, nil +} + +func (b *BotsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if b.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HealthBot/healthBots/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + botNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("botName")]) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.Get(req.Context(), resourceGroupNameParam, botNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).HealthBot, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BotsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if b.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := b.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HealthBot/healthBots` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := b.srv.NewListPager(nil) + newListPager = &resp + b.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armhealthbot.BotsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + b.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + b.newListPager.remove(req) + } + return resp, nil +} + +func (b *BotsServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if b.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := b.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HealthBot/healthBots` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := b.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + b.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armhealthbot.BotsClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + b.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + b.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (b *BotsServerTransport) dispatchListSecrets(req *http.Request) (*http.Response, error) { + if b.srv.ListSecrets == nil { + return nil, &nonRetriableError{errors.New("fake for method ListSecrets not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HealthBot/healthBots/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/listSecrets` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + botNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("botName")]) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.ListSecrets(req.Context(), resourceGroupNameParam, botNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeysResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BotsServerTransport) dispatchRegenerateAPIJwtSecret(req *http.Request) (*http.Response, error) { + if b.srv.RegenerateAPIJwtSecret == nil { + return nil, &nonRetriableError{errors.New("fake for method RegenerateAPIJwtSecret not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HealthBot/healthBots/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/regenerateApiJwtSecret` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + botNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("botName")]) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.RegenerateAPIJwtSecret(req.Context(), resourceGroupNameParam, botNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Key, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BotsServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if b.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := b.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.HealthBot/healthBots/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armhealthbot.UpdateParameters](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + botNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("botName")]) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.BeginUpdate(req.Context(), resourceGroupNameParam, botNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + b.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + b.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + b.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to BotsServerTransport +var botsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armhealthbot/fake/zz_internal.go b/test/local/armhealthbot/fake/zz_internal.go new file mode 100644 index 000000000000..590b4d743e97 --- /dev/null +++ b/test/local/armhealthbot/fake/zz_internal.go @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/local/armhealthbot/fake/zz_operations_server.go b/test/local/armhealthbot/fake/zz_operations_server.go new file mode 100644 index 000000000000..60cd3bbeefa1 --- /dev/null +++ b/test/local/armhealthbot/fake/zz_operations_server.go @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armhealthbot" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "slices" +) + +// OperationsServer is a fake server for instances of the armhealthbot.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armhealthbot.OperationsClientListOptions) (resp azfake.PagerResponder[armhealthbot.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of armhealthbot.OperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOperationsServerTransport(srv *OperationsServer) *OperationsServerTransport { + return &OperationsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armhealthbot.OperationsClientListResponse]](), + } +} + +// OperationsServerTransport connects instances of armhealthbot.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[armhealthbot.OperationsClientListResponse]] +} + +// Do implements the policy.Transporter interface for OperationsServerTransport. +func (o *OperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if operationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = operationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OperationsClient.NewListPager": + res.resp, res.err = o.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OperationsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := o.newListPager.get(req) + if newListPager == nil { + resp := o.srv.NewListPager(nil) + newListPager = &resp + o.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armhealthbot.OperationsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + o.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + o.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OperationsServerTransport +var operationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armhealthbot/fake/zz_server_factory.go b/test/local/armhealthbot/fake/zz_server_factory.go new file mode 100644 index 000000000000..7dfd02309c19 --- /dev/null +++ b/test/local/armhealthbot/fake/zz_server_factory.go @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armhealthbot.ClientFactory type. +type ServerFactory struct { + // BotsServer contains the fakes for client BotsClient + BotsServer BotsServer + + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armhealthbot.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of armhealthbot.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trBotsServer *BotsServerTransport + trOperationsServer *OperationsServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "BotsClient": + initServer(&s.trMu, &s.trBotsServer, func() *BotsServerTransport { return NewBotsServerTransport(&s.srv.BotsServer) }) + resp, err = s.trBotsServer.Do(req) + case "OperationsClient": + initServer(&s.trMu, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + resp, err = s.trOperationsServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} diff --git a/test/local/armhealthbot/go.mod b/test/local/armhealthbot/go.mod new file mode 100644 index 000000000000..254a0fc974f4 --- /dev/null +++ b/test/local/armhealthbot/go.mod @@ -0,0 +1,11 @@ +module armhealthbot + +go 1.25.0 + +require github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect +) diff --git a/test/local/armhealthbot/go.sum b/test/local/armhealthbot/go.sum new file mode 100644 index 000000000000..3fdb64caf441 --- /dev/null +++ b/test/local/armhealthbot/go.sum @@ -0,0 +1,16 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/local/armhealthbot/testdata/_metadata.json b/test/local/armhealthbot/testdata/_metadata.json new file mode 100644 index 000000000000..861a911cb7c5 --- /dev/null +++ b/test/local/armhealthbot/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Microsoft.HealthBot": "2025-11-01" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/local/armhealthbot/zz_bots_client.go b/test/local/armhealthbot/zz_bots_client.go new file mode 100644 index 000000000000..3b0ea19a3187 --- /dev/null +++ b/test/local/armhealthbot/zz_bots_client.go @@ -0,0 +1,561 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armhealthbot + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// BotsClient contains the methods for the Bots group. +// Don't use this type directly, use NewBotsClient() instead. +// +// Generated from API version 2025-11-01 +type BotsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewBotsClient creates a new instance of BotsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewBotsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*BotsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &BotsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreate - Create a new Azure Health Bot. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - botName - The name of the Bot resource. +// - parameters - The parameters to provide for the created Azure Health Bot. +// - options - BotsClientBeginCreateOptions contains the optional parameters for the BotsClient.BeginCreate method. +func (client *BotsClient) BeginCreate(ctx context.Context, resourceGroupName string, botName string, parameters HealthBot, options *BotsClientBeginCreateOptions) (*runtime.Poller[BotsClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, resourceGroupName, botName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[BotsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[BotsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Create a new Azure Health Bot. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *BotsClient) create(ctx context.Context, resourceGroupName string, botName string, parameters HealthBot, options *BotsClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "BotsClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, botName, parameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *BotsClient) createCreateRequest(ctx context.Context, resourceGroupName string, botName string, parameters HealthBot, _ *BotsClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HealthBot/healthBots/{botName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if botName == "" { + return nil, errors.New("parameter botName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{botName}", url.PathEscape(botName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a HealthBot. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - botName - The name of the Bot resource. +// - options - BotsClientBeginDeleteOptions contains the optional parameters for the BotsClient.BeginDelete method. +func (client *BotsClient) BeginDelete(ctx context.Context, resourceGroupName string, botName string, options *BotsClientBeginDeleteOptions) (*runtime.Poller[BotsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, botName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[BotsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[BotsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a HealthBot. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *BotsClient) deleteOperation(ctx context.Context, resourceGroupName string, botName string, options *BotsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "BotsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, botName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *BotsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, botName string, _ *BotsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HealthBot/healthBots/{botName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if botName == "" { + return nil, errors.New("parameter botName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{botName}", url.PathEscape(botName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a HealthBot. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - botName - The name of the Bot resource. +// - options - BotsClientGetOptions contains the optional parameters for the BotsClient.Get method. +func (client *BotsClient) Get(ctx context.Context, resourceGroupName string, botName string, options *BotsClientGetOptions) (BotsClientGetResponse, error) { + var err error + const operationName = "BotsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, botName, options) + if err != nil { + return BotsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BotsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BotsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *BotsClient) getCreateRequest(ctx context.Context, resourceGroupName string, botName string, _ *BotsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HealthBot/healthBots/{botName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if botName == "" { + return nil, errors.New("parameter botName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{botName}", url.PathEscape(botName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *BotsClient) getHandleResponse(resp *http.Response) (BotsClientGetResponse, error) { + result := BotsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.HealthBot); err != nil { + return BotsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - Returns all the resources of a particular type belonging to a subscription. +// - options - BotsClientListOptions contains the optional parameters for the BotsClient.NewListPager method. +func (client *BotsClient) NewListPager(options *BotsClientListOptions) *runtime.Pager[BotsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[BotsClientListResponse]{ + More: func(page BotsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *BotsClientListResponse) (BotsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "BotsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return BotsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *BotsClient) listCreateRequest(ctx context.Context, _ *BotsClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.HealthBot/healthBots" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *BotsClient) listHandleResponse(resp *http.Response) (BotsClientListResponse, error) { + result := BotsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BotResponseList); err != nil { + return BotsClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Returns all the resources of a particular type belonging to a resource group +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - BotsClientListByResourceGroupOptions contains the optional parameters for the BotsClient.NewListByResourceGroupPager +// method. +func (client *BotsClient) NewListByResourceGroupPager(resourceGroupName string, options *BotsClientListByResourceGroupOptions) *runtime.Pager[BotsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[BotsClientListByResourceGroupResponse]{ + More: func(page BotsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *BotsClientListByResourceGroupResponse) (BotsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "BotsClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return BotsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *BotsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *BotsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HealthBot/healthBots" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *BotsClient) listByResourceGroupHandleResponse(resp *http.Response) (BotsClientListByResourceGroupResponse, error) { + result := BotsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BotResponseList); err != nil { + return BotsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// ListSecrets - List all secrets of a HealthBot. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - botName - The name of the Bot resource. +// - options - BotsClientListSecretsOptions contains the optional parameters for the BotsClient.ListSecrets method. +func (client *BotsClient) ListSecrets(ctx context.Context, resourceGroupName string, botName string, options *BotsClientListSecretsOptions) (BotsClientListSecretsResponse, error) { + var err error + const operationName = "BotsClient.ListSecrets" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listSecretsCreateRequest(ctx, resourceGroupName, botName, options) + if err != nil { + return BotsClientListSecretsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BotsClientListSecretsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BotsClientListSecretsResponse{}, err + } + resp, err := client.listSecretsHandleResponse(httpResp) + return resp, err +} + +// listSecretsCreateRequest creates the ListSecrets request. +func (client *BotsClient) listSecretsCreateRequest(ctx context.Context, resourceGroupName string, botName string, _ *BotsClientListSecretsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HealthBot/healthBots/{botName}/listSecrets" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if botName == "" { + return nil, errors.New("parameter botName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{botName}", url.PathEscape(botName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listSecretsHandleResponse handles the ListSecrets response. +func (client *BotsClient) listSecretsHandleResponse(resp *http.Response) (BotsClientListSecretsResponse, error) { + result := BotsClientListSecretsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeysResponse); err != nil { + return BotsClientListSecretsResponse{}, err + } + return result, nil +} + +// RegenerateAPIJwtSecret - Regenerate the API JWT Secret of a HealthBot. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - botName - The name of the Bot resource. +// - options - BotsClientRegenerateAPIJwtSecretOptions contains the optional parameters for the BotsClient.RegenerateAPIJwtSecret +// method. +func (client *BotsClient) RegenerateAPIJwtSecret(ctx context.Context, resourceGroupName string, botName string, options *BotsClientRegenerateAPIJwtSecretOptions) (BotsClientRegenerateAPIJwtSecretResponse, error) { + var err error + const operationName = "BotsClient.RegenerateAPIJwtSecret" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.regenerateAPIJwtSecretCreateRequest(ctx, resourceGroupName, botName, options) + if err != nil { + return BotsClientRegenerateAPIJwtSecretResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BotsClientRegenerateAPIJwtSecretResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BotsClientRegenerateAPIJwtSecretResponse{}, err + } + resp, err := client.regenerateAPIJwtSecretHandleResponse(httpResp) + return resp, err +} + +// regenerateAPIJwtSecretCreateRequest creates the RegenerateAPIJwtSecret request. +func (client *BotsClient) regenerateAPIJwtSecretCreateRequest(ctx context.Context, resourceGroupName string, botName string, _ *BotsClientRegenerateAPIJwtSecretOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HealthBot/healthBots/{botName}/regenerateApiJwtSecret" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if botName == "" { + return nil, errors.New("parameter botName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{botName}", url.PathEscape(botName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// regenerateAPIJwtSecretHandleResponse handles the RegenerateAPIJwtSecret response. +func (client *BotsClient) regenerateAPIJwtSecretHandleResponse(resp *http.Response) (BotsClientRegenerateAPIJwtSecretResponse, error) { + result := BotsClientRegenerateAPIJwtSecretResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Key); err != nil { + return BotsClientRegenerateAPIJwtSecretResponse{}, err + } + return result, nil +} + +// BeginUpdate - Patch a HealthBot. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - botName - The name of the Bot resource. +// - parameters - The parameters to provide for the required Azure Health Bot. +// - options - BotsClientBeginUpdateOptions contains the optional parameters for the BotsClient.BeginUpdate method. +func (client *BotsClient) BeginUpdate(ctx context.Context, resourceGroupName string, botName string, parameters UpdateParameters, options *BotsClientBeginUpdateOptions) (*runtime.Poller[BotsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, botName, parameters, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[BotsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[BotsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Patch a HealthBot. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *BotsClient) update(ctx context.Context, resourceGroupName string, botName string, parameters UpdateParameters, options *BotsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "BotsClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, botName, parameters, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *BotsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, botName string, parameters UpdateParameters, _ *BotsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HealthBot/healthBots/{botName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if botName == "" { + return nil, errors.New("parameter botName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{botName}", url.PathEscape(botName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armhealthbot/zz_client_factory.go b/test/local/armhealthbot/zz_client_factory.go new file mode 100644 index 000000000000..9e7938c5e779 --- /dev/null +++ b/test/local/armhealthbot/zz_client_factory.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armhealthbot + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + subscriptionID string + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, + internal: internal, + }, nil +} + +// NewBotsClient creates a new instance of BotsClient. +func (c *ClientFactory) NewBotsClient() *BotsClient { + return &BotsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: c.internal, + } +} diff --git a/test/local/armhealthbot/zz_constants.go b/test/local/armhealthbot/zz_constants.go new file mode 100644 index 000000000000..f8d6ada7484c --- /dev/null +++ b/test/local/armhealthbot/zz_constants.go @@ -0,0 +1,74 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armhealthbot + +const ( + version20251101 string = "2025-11-01" +) + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// ResourceIdentityType - The identity type. The type 'SystemAssigned, UserAssigned' includes both an implicitly created identity +// and a set of user assigned identities. The type 'None' will remove any identities from the Azure Health Bot +type ResourceIdentityType string + +const ( + ResourceIdentityTypeNone ResourceIdentityType = "None" + ResourceIdentityTypeSystemAssigned ResourceIdentityType = "SystemAssigned" + ResourceIdentityTypeSystemAssignedUserAssigned ResourceIdentityType = "SystemAssigned, UserAssigned" + ResourceIdentityTypeUserAssigned ResourceIdentityType = "UserAssigned" +) + +// PossibleResourceIdentityTypeValues returns the possible values for the ResourceIdentityType const type. +func PossibleResourceIdentityTypeValues() []ResourceIdentityType { + return []ResourceIdentityType{ + ResourceIdentityTypeNone, + ResourceIdentityTypeSystemAssigned, + ResourceIdentityTypeSystemAssignedUserAssigned, + ResourceIdentityTypeUserAssigned, + } +} + +// SKUName - The name of the Azure Health Bot SKU +type SKUName string + +const ( + SKUNameC0 SKUName = "C0" + SKUNameC1 SKUName = "C1" + SKUNameF0 SKUName = "F0" + SKUNamePES SKUName = "PES" +) + +// PossibleSKUNameValues returns the possible values for the SKUName const type. +func PossibleSKUNameValues() []SKUName { + return []SKUName{ + SKUNameC0, + SKUNameC1, + SKUNameF0, + SKUNamePES, + } +} diff --git a/test/local/armhealthbot/zz_models.go b/test/local/armhealthbot/zz_models.go new file mode 100644 index 000000000000..fc16ea1272e7 --- /dev/null +++ b/test/local/armhealthbot/zz_models.go @@ -0,0 +1,206 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armhealthbot + +import "time" + +// AvailableOperations - Available operations of the service. +type AvailableOperations struct { + // REQUIRED; Collection of available operation details. + Value []*OperationDetail + + // URL client should use to fetch the next page (per server side paging). + // It's null for now, added for future use. + NextLink *string +} + +// BotResponseList - The list of Azure Health Bot operation response. +type BotResponseList struct { + // READ-ONLY; The HealthBot items on this page + Value []*HealthBot + + // The link to the next page of items + NextLink *string +} + +// HealthBot - Azure Health Bot resource definition +type HealthBot struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // REQUIRED; SKU of the Azure Health Bot. + SKU *SKU + + // The identity of the Azure Health Bot. + Identity *Identity + + // The set of properties specific to Azure Health Bot resource. + Properties *Properties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// Identity for the resource. +type Identity struct { + // The identity type. The type 'SystemAssigned, UserAssigned' includes both an implicitly created identity and a set of user + // assigned identities. The type 'None' will remove any identities from the Azure Health Bot + Type *ResourceIdentityType + + // The list of user identities associated with the resource. The user identity dictionary key references will be ARM resource + // ids in the form: + // '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. + UserAssignedIdentities map[string]*UserAssignedIdentity + + // READ-ONLY; The principal ID of resource identity. This property will only be provided for a system assigned identity. + PrincipalID *string + + // READ-ONLY; The tenant ID of resource. This property will only be provided for a system assigned identity. + TenantID *string +} + +// Key - An entry of HealthBotKeysResponse +type Key struct { + // The name of the key. + KeyName *string + + // The value of the key. + Value *string +} + +// KeyVaultProperties - Properties of the key vault. +type KeyVaultProperties struct { + // REQUIRED; The name of the key vault key. + KeyName *string + + // REQUIRED; The Uri of the key vault. + KeyVaultURI *string + + // The version of the key vault key. + KeyVersion *string + + // The user assigned identity (ARM resource id) that has access to the key. + UserIdentity *string +} + +// KeysResponse - Health Bot Keys Response. +type KeysResponse struct { + // Array of Azure Health Bot Secrets. + Secrets []*Key +} + +// OperationDetail - Operation detail payload +type OperationDetail struct { + // Display of the operation + Display *OperationDisplay + + // Indicates whether the operation is a data action + IsDataAction *bool + + // Name of the operation + Name *string + + // Origin of the operation + Origin *string + + // Additional properties. + Properties any +} + +// OperationDisplay - Operation display payload +type OperationDisplay struct { + // Localized friendly description for the operation + Description *string + + // Localized friendly name for the operation + Operation *string + + // Resource provider of the operation + Provider *string + + // Resource of the operation + Resource *string +} + +// Properties - The properties of a Azure Health Bot. The Health Bot Service is a cloud platform that empowers developers +// in Healthcare organizations to build and deploy their compliant, AI-powered virtual health assistants and health bots, +// that help them improve processes and reduce costs. +type Properties struct { + // KeyVault properties for the resource encryption. + KeyVaultProperties *KeyVaultProperties + + // READ-ONLY; The access control method for the Azure Health Bot resource. + AccessControlMethod *string + + // READ-ONLY; The link. + BotManagementPortalLink *string + + // READ-ONLY; The provisioning state of the Azure Health Bot resource. + ProvisioningState *string +} + +// SKU - The resource model definition representing SKU +type SKU struct { + // REQUIRED; The name of the Azure Health Bot SKU + Name *SKUName +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time + + // The identity that created the resource. + CreatedBy *string + + // The type of identity that created the resource. + CreatedByType *CreatedByType + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time + + // The identity that last modified the resource. + LastModifiedBy *string + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType +} + +// UpdateParameters - Parameters for updating a Azure Health Bot. +type UpdateParameters struct { + // The identity of the Azure Health Bot. + Identity *Identity + Location *string + + // Properties of Azure Health Bot. + Properties *Properties + + // SKU of the Azure Health Bot. + SKU *SKU + + // Tags for a Azure Health Bot. + Tags map[string]*string +} + +// UserAssignedIdentity - The details of the user assigned managed identity used by the Video Analyzer resource. +type UserAssignedIdentity struct { + // READ-ONLY; The client ID of user assigned identity. + ClientID *string + + // READ-ONLY; The principal ID of user assigned identity. + PrincipalID *string +} diff --git a/test/local/armhealthbot/zz_models_serde.go b/test/local/armhealthbot/zz_models_serde.go new file mode 100644 index 000000000000..b4c99e236945 --- /dev/null +++ b/test/local/armhealthbot/zz_models_serde.go @@ -0,0 +1,598 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armhealthbot + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type AvailableOperations. +func (a AvailableOperations) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AvailableOperations. +func (a *AvailableOperations) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &a.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BotResponseList. +func (b BotResponseList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", b.NextLink) + populate(objectMap, "value", b.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BotResponseList. +func (b *BotResponseList) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &b.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &b.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HealthBot. +func (h HealthBot) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", h.ID) + populate(objectMap, "identity", h.Identity) + populate(objectMap, "location", h.Location) + populate(objectMap, "name", h.Name) + populate(objectMap, "properties", h.Properties) + populate(objectMap, "sku", h.SKU) + populate(objectMap, "systemData", h.SystemData) + populate(objectMap, "tags", h.Tags) + populate(objectMap, "type", h.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HealthBot. +func (h *HealthBot) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &h.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &h.Identity) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &h.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &h.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &h.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &h.SKU) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &h.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &h.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &h.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Identity. +func (i Identity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "principalId", i.PrincipalID) + populate(objectMap, "tenantId", i.TenantID) + populate(objectMap, "type", i.Type) + populate(objectMap, "userAssignedIdentities", i.UserAssignedIdentities) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Identity. +func (i *Identity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "principalId": + err = unpopulate(val, "PrincipalID", &i.PrincipalID) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &i.TenantID) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &i.Type) + delete(rawMsg, key) + case "userAssignedIdentities": + err = unpopulate(val, "UserAssignedIdentities", &i.UserAssignedIdentities) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Key. +func (k Key) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "keyName", k.KeyName) + populate(objectMap, "value", k.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Key. +func (k *Key) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "keyName": + err = unpopulate(val, "KeyName", &k.KeyName) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &k.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyVaultProperties. +func (k KeyVaultProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "keyName", k.KeyName) + populate(objectMap, "keyVaultUri", k.KeyVaultURI) + populate(objectMap, "keyVersion", k.KeyVersion) + populate(objectMap, "userIdentity", k.UserIdentity) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyVaultProperties. +func (k *KeyVaultProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "keyName": + err = unpopulate(val, "KeyName", &k.KeyName) + delete(rawMsg, key) + case "keyVaultUri": + err = unpopulate(val, "KeyVaultURI", &k.KeyVaultURI) + delete(rawMsg, key) + case "keyVersion": + err = unpopulate(val, "KeyVersion", &k.KeyVersion) + delete(rawMsg, key) + case "userIdentity": + err = unpopulate(val, "UserIdentity", &k.UserIdentity) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeysResponse. +func (k KeysResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "secrets", k.Secrets) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeysResponse. +func (k *KeysResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "secrets": + err = unpopulate(val, "Secrets", &k.Secrets) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationDetail. +func (o OperationDetail) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "display", o.Display) + populate(objectMap, "isDataAction", o.IsDataAction) + populate(objectMap, "name", o.Name) + populate(objectMap, "origin", o.Origin) + populateAny(objectMap, "properties", o.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationDetail. +func (o *OperationDetail) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "display": + err = unpopulate(val, "Display", &o.Display) + delete(rawMsg, key) + case "isDataAction": + err = unpopulate(val, "IsDataAction", &o.IsDataAction) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "origin": + err = unpopulate(val, "Origin", &o.Origin) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &o.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationDisplay. +func (o OperationDisplay) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", o.Description) + populate(objectMap, "operation", o.Operation) + populate(objectMap, "provider", o.Provider) + populate(objectMap, "resource", o.Resource) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationDisplay. +func (o *OperationDisplay) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &o.Description) + delete(rawMsg, key) + case "operation": + err = unpopulate(val, "Operation", &o.Operation) + delete(rawMsg, key) + case "provider": + err = unpopulate(val, "Provider", &o.Provider) + delete(rawMsg, key) + case "resource": + err = unpopulate(val, "Resource", &o.Resource) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Properties. +func (p Properties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "accessControlMethod", p.AccessControlMethod) + populate(objectMap, "botManagementPortalLink", p.BotManagementPortalLink) + populate(objectMap, "keyVaultProperties", p.KeyVaultProperties) + populate(objectMap, "provisioningState", p.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Properties. +func (p *Properties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "accessControlMethod": + err = unpopulate(val, "AccessControlMethod", &p.AccessControlMethod) + delete(rawMsg, key) + case "botManagementPortalLink": + err = unpopulate(val, "BotManagementPortalLink", &p.BotManagementPortalLink) + delete(rawMsg, key) + case "keyVaultProperties": + err = unpopulate(val, "KeyVaultProperties", &p.KeyVaultProperties) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SKU. +func (s SKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", s.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SKU. +func (s *SKU) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateTime[datetime.RFC3339](objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateTime[datetime.RFC3339](val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateTime[datetime.RFC3339](val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UpdateParameters. +func (u UpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identity", u.Identity) + populate(objectMap, "location", u.Location) + populate(objectMap, "properties", u.Properties) + populate(objectMap, "sku", u.SKU) + populate(objectMap, "tags", u.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UpdateParameters. +func (u *UpdateParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "identity": + err = unpopulate(val, "Identity", &u.Identity) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &u.Location) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &u.Properties) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &u.SKU) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &u.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserAssignedIdentity. +func (u UserAssignedIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clientId", u.ClientID) + populate(objectMap, "principalId", u.PrincipalID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserAssignedIdentity. +func (u *UserAssignedIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "clientId": + err = unpopulate(val, "ClientID", &u.ClientID) + delete(rawMsg, key) + case "principalId": + err = unpopulate(val, "PrincipalID", &u.PrincipalID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func populateAny(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/local/armhealthbot/zz_operations_client.go b/test/local/armhealthbot/zz_operations_client.go new file mode 100644 index 000000000000..4f617bcd60ce --- /dev/null +++ b/test/local/armhealthbot/zz_operations_client.go @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armhealthbot + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// OperationsClient - This is the interface that implements the standard Azure Resource Manager operation that returns +// all supported RP operations. You should have exactly one declaration for each +// Azure Resource Manager service. It implements +// GET "/providers/Microsoft.ContosoProviderHub/operations" +// Don't use this type directly, use NewOperationsClient() instead. +// +// Generated from API version 2025-11-01 +type OperationsClient struct { + internal *arm.Client +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*OperationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OperationsClient{ + internal: cl, + } + return client, nil +} + +// NewListPager - Lists all the available Azure Health Bot operations. +// - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ + More: func(page OperationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OperationsClientListResponse) (OperationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OperationsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return OperationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, _ *OperationsClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.HealthBot/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20251101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsClientListResponse, error) { + result := OperationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AvailableOperations); err != nil { + return OperationsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armhealthbot/zz_options.go b/test/local/armhealthbot/zz_options.go new file mode 100644 index 000000000000..bcec8b0dc20e --- /dev/null +++ b/test/local/armhealthbot/zz_options.go @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armhealthbot + +// BotsClientBeginCreateOptions contains the optional parameters for the BotsClient.BeginCreate method. +type BotsClientBeginCreateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// BotsClientBeginDeleteOptions contains the optional parameters for the BotsClient.BeginDelete method. +type BotsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// BotsClientBeginUpdateOptions contains the optional parameters for the BotsClient.BeginUpdate method. +type BotsClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// BotsClientGetOptions contains the optional parameters for the BotsClient.Get method. +type BotsClientGetOptions struct { + // placeholder for future optional parameters +} + +// BotsClientListByResourceGroupOptions contains the optional parameters for the BotsClient.NewListByResourceGroupPager method. +type BotsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// BotsClientListOptions contains the optional parameters for the BotsClient.NewListPager method. +type BotsClientListOptions struct { + // placeholder for future optional parameters +} + +// BotsClientListSecretsOptions contains the optional parameters for the BotsClient.ListSecrets method. +type BotsClientListSecretsOptions struct { + // placeholder for future optional parameters +} + +// BotsClientRegenerateAPIJwtSecretOptions contains the optional parameters for the BotsClient.RegenerateAPIJwtSecret method. +type BotsClientRegenerateAPIJwtSecretOptions struct { + // placeholder for future optional parameters +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} diff --git a/test/local/armhealthbot/zz_responses.go b/test/local/armhealthbot/zz_responses.go new file mode 100644 index 000000000000..b1de8a98ea0f --- /dev/null +++ b/test/local/armhealthbot/zz_responses.go @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armhealthbot + +// BotsClientCreateResponse contains the response from method BotsClient.BeginCreate. +type BotsClientCreateResponse struct { + // Azure Health Bot resource definition + HealthBot +} + +// BotsClientDeleteResponse contains the response from method BotsClient.BeginDelete. +type BotsClientDeleteResponse struct { + // placeholder for future response values +} + +// BotsClientGetResponse contains the response from method BotsClient.Get. +type BotsClientGetResponse struct { + // Azure Health Bot resource definition + HealthBot +} + +// BotsClientListByResourceGroupResponse contains the response from method BotsClient.NewListByResourceGroupPager. +type BotsClientListByResourceGroupResponse struct { + // The list of Azure Health Bot operation response. + BotResponseList +} + +// BotsClientListResponse contains the response from method BotsClient.NewListPager. +type BotsClientListResponse struct { + // The list of Azure Health Bot operation response. + BotResponseList +} + +// BotsClientListSecretsResponse contains the response from method BotsClient.ListSecrets. +type BotsClientListSecretsResponse struct { + // Health Bot Keys Response. + KeysResponse +} + +// BotsClientRegenerateAPIJwtSecretResponse contains the response from method BotsClient.RegenerateAPIJwtSecret. +type BotsClientRegenerateAPIJwtSecretResponse struct { + // An entry of HealthBotKeysResponse + Key +} + +// BotsClientUpdateResponse contains the response from method BotsClient.BeginUpdate. +type BotsClientUpdateResponse struct { + // Azure Health Bot resource definition + HealthBot +} + +// OperationsClientListResponse contains the response from method OperationsClient.NewListPager. +type OperationsClientListResponse struct { + // Available operations of the service. + AvailableOperations +} diff --git a/test/local/armhealthbot/zz_version.go b/test/local/armhealthbot/zz_version.go new file mode 100644 index 000000000000..be029ae1bdd7 --- /dev/null +++ b/test/local/armhealthbot/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package armhealthbot + +const ( + moduleName = "armhealthbot" + moduleVersion = "v0.1.0" +) diff --git a/test/local/armlargeinstance/LICENSE.txt b/test/local/armlargeinstance/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/local/armlargeinstance/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/local/armlargeinstance/fake/zz_azurelargestorageinstance_server.go b/test/local/armlargeinstance/fake/zz_azurelargestorageinstance_server.go new file mode 100644 index 000000000000..6c4dca5f33ca --- /dev/null +++ b/test/local/armlargeinstance/fake/zz_azurelargestorageinstance_server.go @@ -0,0 +1,331 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armlargeinstance" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// AzureLargeStorageInstanceServer is a fake server for instances of the armlargeinstance.AzureLargeStorageInstanceClient type. +type AzureLargeStorageInstanceServer struct { + // Create is the fake for method AzureLargeStorageInstanceClient.Create + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + Create func(ctx context.Context, resourceGroupName string, azureLargeStorageInstanceName string, resource armlargeinstance.AzureLargeStorageInstance, options *armlargeinstance.AzureLargeStorageInstanceClientCreateOptions) (resp azfake.Responder[armlargeinstance.AzureLargeStorageInstanceClientCreateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method AzureLargeStorageInstanceClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceGroupName string, azureLargeStorageInstanceName string, options *armlargeinstance.AzureLargeStorageInstanceClientDeleteOptions) (resp azfake.Responder[armlargeinstance.AzureLargeStorageInstanceClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method AzureLargeStorageInstanceClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, azureLargeStorageInstanceName string, options *armlargeinstance.AzureLargeStorageInstanceClientGetOptions) (resp azfake.Responder[armlargeinstance.AzureLargeStorageInstanceClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method AzureLargeStorageInstanceClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armlargeinstance.AzureLargeStorageInstanceClientListByResourceGroupOptions) (resp azfake.PagerResponder[armlargeinstance.AzureLargeStorageInstanceClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method AzureLargeStorageInstanceClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armlargeinstance.AzureLargeStorageInstanceClientListBySubscriptionOptions) (resp azfake.PagerResponder[armlargeinstance.AzureLargeStorageInstanceClientListBySubscriptionResponse]) + + // Update is the fake for method AzureLargeStorageInstanceClient.Update + // HTTP status codes to indicate success: http.StatusOK + Update func(ctx context.Context, resourceGroupName string, azureLargeStorageInstanceName string, properties armlargeinstance.AzureLargeStorageInstanceTagsUpdate, options *armlargeinstance.AzureLargeStorageInstanceClientUpdateOptions) (resp azfake.Responder[armlargeinstance.AzureLargeStorageInstanceClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewAzureLargeStorageInstanceServerTransport creates a new instance of AzureLargeStorageInstanceServerTransport with the provided implementation. +// The returned AzureLargeStorageInstanceServerTransport instance is connected to an instance of armlargeinstance.AzureLargeStorageInstanceClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAzureLargeStorageInstanceServerTransport(srv *AzureLargeStorageInstanceServer) *AzureLargeStorageInstanceServerTransport { + return &AzureLargeStorageInstanceServerTransport{ + srv: srv, + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armlargeinstance.AzureLargeStorageInstanceClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armlargeinstance.AzureLargeStorageInstanceClientListBySubscriptionResponse]](), + } +} + +// AzureLargeStorageInstanceServerTransport connects instances of armlargeinstance.AzureLargeStorageInstanceClient to instances of AzureLargeStorageInstanceServer. +// Don't use this type directly, use NewAzureLargeStorageInstanceServerTransport instead. +type AzureLargeStorageInstanceServerTransport struct { + srv *AzureLargeStorageInstanceServer + newListByResourceGroupPager *tracker[azfake.PagerResponder[armlargeinstance.AzureLargeStorageInstanceClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armlargeinstance.AzureLargeStorageInstanceClientListBySubscriptionResponse]] +} + +// Do implements the policy.Transporter interface for AzureLargeStorageInstanceServerTransport. +func (a *AzureLargeStorageInstanceServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *AzureLargeStorageInstanceServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if azureLargeStorageInstanceServerTransportInterceptor != nil { + res.resp, res.err, intercepted = azureLargeStorageInstanceServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "AzureLargeStorageInstanceClient.Create": + res.resp, res.err = a.dispatchCreate(req) + case "AzureLargeStorageInstanceClient.Delete": + res.resp, res.err = a.dispatchDelete(req) + case "AzureLargeStorageInstanceClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "AzureLargeStorageInstanceClient.NewListByResourceGroupPager": + res.resp, res.err = a.dispatchNewListByResourceGroupPager(req) + case "AzureLargeStorageInstanceClient.NewListBySubscriptionPager": + res.resp, res.err = a.dispatchNewListBySubscriptionPager(req) + case "AzureLargeStorageInstanceClient.Update": + res.resp, res.err = a.dispatchUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *AzureLargeStorageInstanceServerTransport) dispatchCreate(req *http.Request) (*http.Response, error) { + if a.srv.Create == nil { + return nil, &nonRetriableError{errors.New("fake for method Create not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AzureLargeInstance/azureLargeStorageInstances/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armlargeinstance.AzureLargeStorageInstance](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + azureLargeStorageInstanceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("azureLargeStorageInstanceName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Create(req.Context(), resourceGroupNameParam, azureLargeStorageInstanceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).AzureLargeStorageInstance, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AzureLargeStorageInstanceServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if a.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AzureLargeInstance/azureLargeStorageInstances/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + azureLargeStorageInstanceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("azureLargeStorageInstanceName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Delete(req.Context(), resourceGroupNameParam, azureLargeStorageInstanceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AzureLargeStorageInstanceServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AzureLargeInstance/azureLargeStorageInstances/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + azureLargeStorageInstanceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("azureLargeStorageInstanceName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Get(req.Context(), resourceGroupNameParam, azureLargeStorageInstanceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).AzureLargeStorageInstance, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AzureLargeStorageInstanceServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if a.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := a.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AzureLargeInstance/azureLargeStorageInstances` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := a.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + a.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armlargeinstance.AzureLargeStorageInstanceClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + a.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (a *AzureLargeStorageInstanceServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if a.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := a.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AzureLargeInstance/azureLargeStorageInstances` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := a.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + a.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armlargeinstance.AzureLargeStorageInstanceClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + a.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (a *AzureLargeStorageInstanceServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) { + if a.srv.Update == nil { + return nil, &nonRetriableError{errors.New("fake for method Update not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AzureLargeInstance/azureLargeStorageInstances/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armlargeinstance.AzureLargeStorageInstanceTagsUpdate](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + azureLargeStorageInstanceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("azureLargeStorageInstanceName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Update(req.Context(), resourceGroupNameParam, azureLargeStorageInstanceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).AzureLargeStorageInstance, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to AzureLargeStorageInstanceServerTransport +var azureLargeStorageInstanceServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armlargeinstance/fake/zz_internal.go b/test/local/armlargeinstance/fake/zz_internal.go new file mode 100644 index 000000000000..590b4d743e97 --- /dev/null +++ b/test/local/armlargeinstance/fake/zz_internal.go @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/local/armlargeinstance/fake/zz_operations_server.go b/test/local/armlargeinstance/fake/zz_operations_server.go new file mode 100644 index 000000000000..6c40d0fc4598 --- /dev/null +++ b/test/local/armlargeinstance/fake/zz_operations_server.go @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armlargeinstance" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "slices" +) + +// OperationsServer is a fake server for instances of the armlargeinstance.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armlargeinstance.OperationsClientListOptions) (resp azfake.PagerResponder[armlargeinstance.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of armlargeinstance.OperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOperationsServerTransport(srv *OperationsServer) *OperationsServerTransport { + return &OperationsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armlargeinstance.OperationsClientListResponse]](), + } +} + +// OperationsServerTransport connects instances of armlargeinstance.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[armlargeinstance.OperationsClientListResponse]] +} + +// Do implements the policy.Transporter interface for OperationsServerTransport. +func (o *OperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if operationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = operationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OperationsClient.NewListPager": + res.resp, res.err = o.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OperationsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := o.newListPager.get(req) + if newListPager == nil { + resp := o.srv.NewListPager(nil) + newListPager = &resp + o.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armlargeinstance.OperationsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + o.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + o.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OperationsServerTransport +var operationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armlargeinstance/fake/zz_server.go b/test/local/armlargeinstance/fake/zz_server.go new file mode 100644 index 000000000000..ccc1a641c22e --- /dev/null +++ b/test/local/armlargeinstance/fake/zz_server.go @@ -0,0 +1,498 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armlargeinstance" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "reflect" + "regexp" + "slices" +) + +// Server is a fake server for instances of the armlargeinstance.Client type. +type Server struct { + // Create is the fake for method Client.Create + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + Create func(ctx context.Context, resourceGroupName string, azureLargeInstanceName string, resource armlargeinstance.AzureLargeInstance, options *armlargeinstance.ClientCreateOptions) (resp azfake.Responder[armlargeinstance.ClientCreateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method Client.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceGroupName string, azureLargeInstanceName string, options *armlargeinstance.ClientDeleteOptions) (resp azfake.Responder[armlargeinstance.ClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method Client.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, azureLargeInstanceName string, options *armlargeinstance.ClientGetOptions) (resp azfake.Responder[armlargeinstance.ClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method Client.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armlargeinstance.ClientListByResourceGroupOptions) (resp azfake.PagerResponder[armlargeinstance.ClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method Client.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armlargeinstance.ClientListBySubscriptionOptions) (resp azfake.PagerResponder[armlargeinstance.ClientListBySubscriptionResponse]) + + // BeginRestart is the fake for method Client.BeginRestart + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginRestart func(ctx context.Context, resourceGroupName string, azureLargeInstanceName string, options *armlargeinstance.ClientBeginRestartOptions) (resp azfake.PollerResponder[armlargeinstance.ClientRestartResponse], errResp azfake.ErrorResponder) + + // BeginShutdown is the fake for method Client.BeginShutdown + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginShutdown func(ctx context.Context, resourceGroupName string, azureLargeInstanceName string, options *armlargeinstance.ClientBeginShutdownOptions) (resp azfake.PollerResponder[armlargeinstance.ClientShutdownResponse], errResp azfake.ErrorResponder) + + // BeginStart is the fake for method Client.BeginStart + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginStart func(ctx context.Context, resourceGroupName string, azureLargeInstanceName string, options *armlargeinstance.ClientBeginStartOptions) (resp azfake.PollerResponder[armlargeinstance.ClientStartResponse], errResp azfake.ErrorResponder) + + // Update is the fake for method Client.Update + // HTTP status codes to indicate success: http.StatusOK + Update func(ctx context.Context, resourceGroupName string, azureLargeInstanceName string, properties armlargeinstance.TagsUpdate, options *armlargeinstance.ClientUpdateOptions) (resp azfake.Responder[armlargeinstance.ClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewServerTransport creates a new instance of ServerTransport with the provided implementation. +// The returned ServerTransport instance is connected to an instance of armlargeinstance.Client via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerTransport(srv *Server) *ServerTransport { + return &ServerTransport{ + srv: srv, + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armlargeinstance.ClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armlargeinstance.ClientListBySubscriptionResponse]](), + beginRestart: newTracker[azfake.PollerResponder[armlargeinstance.ClientRestartResponse]](), + beginShutdown: newTracker[azfake.PollerResponder[armlargeinstance.ClientShutdownResponse]](), + beginStart: newTracker[azfake.PollerResponder[armlargeinstance.ClientStartResponse]](), + } +} + +// ServerTransport connects instances of armlargeinstance.Client to instances of Server. +// Don't use this type directly, use NewServerTransport instead. +type ServerTransport struct { + srv *Server + newListByResourceGroupPager *tracker[azfake.PagerResponder[armlargeinstance.ClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armlargeinstance.ClientListBySubscriptionResponse]] + beginRestart *tracker[azfake.PollerResponder[armlargeinstance.ClientRestartResponse]] + beginShutdown *tracker[azfake.PollerResponder[armlargeinstance.ClientShutdownResponse]] + beginStart *tracker[azfake.PollerResponder[armlargeinstance.ClientStartResponse]] +} + +// Do implements the policy.Transporter interface for ServerTransport. +func (s *ServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if serverTransportInterceptor != nil { + res.resp, res.err, intercepted = serverTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "Client.Create": + res.resp, res.err = s.dispatchCreate(req) + case "Client.Delete": + res.resp, res.err = s.dispatchDelete(req) + case "Client.Get": + res.resp, res.err = s.dispatchGet(req) + case "Client.NewListByResourceGroupPager": + res.resp, res.err = s.dispatchNewListByResourceGroupPager(req) + case "Client.NewListBySubscriptionPager": + res.resp, res.err = s.dispatchNewListBySubscriptionPager(req) + case "Client.BeginRestart": + res.resp, res.err = s.dispatchBeginRestart(req) + case "Client.BeginShutdown": + res.resp, res.err = s.dispatchBeginShutdown(req) + case "Client.BeginStart": + res.resp, res.err = s.dispatchBeginStart(req) + case "Client.Update": + res.resp, res.err = s.dispatchUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ServerTransport) dispatchCreate(req *http.Request) (*http.Response, error) { + if s.srv.Create == nil { + return nil, &nonRetriableError{errors.New("fake for method Create not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AzureLargeInstance/azureLargeInstances/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armlargeinstance.AzureLargeInstance](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + azureLargeInstanceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("azureLargeInstanceName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Create(req.Context(), resourceGroupNameParam, azureLargeInstanceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).AzureLargeInstance, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if s.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AzureLargeInstance/azureLargeInstances/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + azureLargeInstanceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("azureLargeInstanceName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Delete(req.Context(), resourceGroupNameParam, azureLargeInstanceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if s.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AzureLargeInstance/azureLargeInstances/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + azureLargeInstanceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("azureLargeInstanceName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Get(req.Context(), resourceGroupNameParam, azureLargeInstanceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).AzureLargeInstance, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if s.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := s.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AzureLargeInstance/azureLargeInstances` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := s.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + s.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armlargeinstance.ClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + s.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + s.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (s *ServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if s.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := s.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AzureLargeInstance/azureLargeInstances` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := s.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + s.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armlargeinstance.ClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + s.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + s.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (s *ServerTransport) dispatchBeginRestart(req *http.Request) (*http.Response, error) { + if s.srv.BeginRestart == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginRestart not implemented")} + } + beginRestart := s.beginRestart.get(req) + if beginRestart == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AzureLargeInstance/azureLargeInstances/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/restart` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armlargeinstance.ForceState](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + azureLargeInstanceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("azureLargeInstanceName")]) + if err != nil { + return nil, err + } + var options *armlargeinstance.ClientBeginRestartOptions + if !reflect.ValueOf(body).IsZero() { + options = &armlargeinstance.ClientBeginRestartOptions{ + ForceParameter: &body, + } + } + respr, errRespr := s.srv.BeginRestart(req.Context(), resourceGroupNameParam, azureLargeInstanceNameParam, options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginRestart = &respr + s.beginRestart.add(req, beginRestart) + } + + resp, err := server.PollerResponderNext(beginRestart, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + s.beginRestart.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginRestart) { + s.beginRestart.remove(req) + } + + return resp, nil +} + +func (s *ServerTransport) dispatchBeginShutdown(req *http.Request) (*http.Response, error) { + if s.srv.BeginShutdown == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginShutdown not implemented")} + } + beginShutdown := s.beginShutdown.get(req) + if beginShutdown == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AzureLargeInstance/azureLargeInstances/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/shutdown` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + azureLargeInstanceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("azureLargeInstanceName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.BeginShutdown(req.Context(), resourceGroupNameParam, azureLargeInstanceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginShutdown = &respr + s.beginShutdown.add(req, beginShutdown) + } + + resp, err := server.PollerResponderNext(beginShutdown, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + s.beginShutdown.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginShutdown) { + s.beginShutdown.remove(req) + } + + return resp, nil +} + +func (s *ServerTransport) dispatchBeginStart(req *http.Request) (*http.Response, error) { + if s.srv.BeginStart == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginStart not implemented")} + } + beginStart := s.beginStart.get(req) + if beginStart == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AzureLargeInstance/azureLargeInstances/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/start` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + azureLargeInstanceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("azureLargeInstanceName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.BeginStart(req.Context(), resourceGroupNameParam, azureLargeInstanceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginStart = &respr + s.beginStart.add(req, beginStart) + } + + resp, err := server.PollerResponderNext(beginStart, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + s.beginStart.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginStart) { + s.beginStart.remove(req) + } + + return resp, nil +} + +func (s *ServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) { + if s.srv.Update == nil { + return nil, &nonRetriableError{errors.New("fake for method Update not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.AzureLargeInstance/azureLargeInstances/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armlargeinstance.TagsUpdate](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + azureLargeInstanceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("azureLargeInstanceName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Update(req.Context(), resourceGroupNameParam, azureLargeInstanceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).AzureLargeInstance, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ServerTransport +var serverTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armlargeinstance/fake/zz_server_factory.go b/test/local/armlargeinstance/fake/zz_server_factory.go new file mode 100644 index 000000000000..f2030a13269d --- /dev/null +++ b/test/local/armlargeinstance/fake/zz_server_factory.go @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armlargeinstance.ClientFactory type. +type ServerFactory struct { + // AzureLargeStorageInstanceServer contains the fakes for client AzureLargeStorageInstanceClient + AzureLargeStorageInstanceServer AzureLargeStorageInstanceServer + + // Server contains the fakes for client Client + Server Server + + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armlargeinstance.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of armlargeinstance.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trAzureLargeStorageInstanceServer *AzureLargeStorageInstanceServerTransport + trServer *ServerTransport + trOperationsServer *OperationsServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "AzureLargeStorageInstanceClient": + initServer(&s.trMu, &s.trAzureLargeStorageInstanceServer, func() *AzureLargeStorageInstanceServerTransport { + return NewAzureLargeStorageInstanceServerTransport(&s.srv.AzureLargeStorageInstanceServer) + }) + resp, err = s.trAzureLargeStorageInstanceServer.Do(req) + case "Client": + initServer(&s.trMu, &s.trServer, func() *ServerTransport { return NewServerTransport(&s.srv.Server) }) + resp, err = s.trServer.Do(req) + case "OperationsClient": + initServer(&s.trMu, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + resp, err = s.trOperationsServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} diff --git a/test/local/armlargeinstance/go.mod b/test/local/armlargeinstance/go.mod new file mode 100644 index 000000000000..e02667563e37 --- /dev/null +++ b/test/local/armlargeinstance/go.mod @@ -0,0 +1,11 @@ +module armlargeinstance + +go 1.25.0 + +require github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect +) diff --git a/test/local/armlargeinstance/go.sum b/test/local/armlargeinstance/go.sum new file mode 100644 index 000000000000..3fdb64caf441 --- /dev/null +++ b/test/local/armlargeinstance/go.sum @@ -0,0 +1,16 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/local/armlargeinstance/testdata/_metadata.json b/test/local/armlargeinstance/testdata/_metadata.json new file mode 100644 index 000000000000..4af0b56e86c9 --- /dev/null +++ b/test/local/armlargeinstance/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Microsoft.AzureLargeInstance": "2024-08-01-preview" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/local/armlargeinstance/zz_azurelargestorageinstance_client.go b/test/local/armlargeinstance/zz_azurelargestorageinstance_client.go new file mode 100644 index 000000000000..85998f67c3c3 --- /dev/null +++ b/test/local/armlargeinstance/zz_azurelargestorageinstance_client.go @@ -0,0 +1,411 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armlargeinstance + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// AzureLargeStorageInstanceClient contains the methods for the AzureLargeStorageInstance group. +// Don't use this type directly, use NewAzureLargeStorageInstanceClient() instead. +// +// Generated from API version 2024-08-01-preview +type AzureLargeStorageInstanceClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAzureLargeStorageInstanceClient creates a new instance of AzureLargeStorageInstanceClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewAzureLargeStorageInstanceClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AzureLargeStorageInstanceClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AzureLargeStorageInstanceClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Create - Creates an Azure Large Storage Instance for the specified subscription, +// resource group, and instance name. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - azureLargeStorageInstanceName - Name of the AzureLargeStorageInstance. +// - resource - Resource create parameters. +// - options - AzureLargeStorageInstanceClientCreateOptions contains the optional parameters for the AzureLargeStorageInstanceClient.Create +// method. +func (client *AzureLargeStorageInstanceClient) Create(ctx context.Context, resourceGroupName string, azureLargeStorageInstanceName string, resource AzureLargeStorageInstance, options *AzureLargeStorageInstanceClientCreateOptions) (AzureLargeStorageInstanceClientCreateResponse, error) { + var err error + const operationName = "AzureLargeStorageInstanceClient.Create" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, azureLargeStorageInstanceName, resource, options) + if err != nil { + return AzureLargeStorageInstanceClientCreateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AzureLargeStorageInstanceClientCreateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return AzureLargeStorageInstanceClientCreateResponse{}, err + } + resp, err := client.createHandleResponse(httpResp) + return resp, err +} + +// createCreateRequest creates the Create request. +func (client *AzureLargeStorageInstanceClient) createCreateRequest(ctx context.Context, resourceGroupName string, azureLargeStorageInstanceName string, resource AzureLargeStorageInstance, _ *AzureLargeStorageInstanceClientCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureLargeInstance/azureLargeStorageInstances/{azureLargeStorageInstanceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if azureLargeStorageInstanceName == "" { + return nil, errors.New("parameter azureLargeStorageInstanceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{azureLargeStorageInstanceName}", url.PathEscape(azureLargeStorageInstanceName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240801Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// createHandleResponse handles the Create response. +func (client *AzureLargeStorageInstanceClient) createHandleResponse(resp *http.Response) (AzureLargeStorageInstanceClientCreateResponse, error) { + result := AzureLargeStorageInstanceClientCreateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AzureLargeStorageInstance); err != nil { + return AzureLargeStorageInstanceClientCreateResponse{}, err + } + return result, nil +} + +// Delete - Deletes an Azure Large Storage Instance for the specified subscription, +// resource group, and instance name. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - azureLargeStorageInstanceName - Name of the AzureLargeStorageInstance. +// - options - AzureLargeStorageInstanceClientDeleteOptions contains the optional parameters for the AzureLargeStorageInstanceClient.Delete +// method. +func (client *AzureLargeStorageInstanceClient) Delete(ctx context.Context, resourceGroupName string, azureLargeStorageInstanceName string, options *AzureLargeStorageInstanceClientDeleteOptions) (AzureLargeStorageInstanceClientDeleteResponse, error) { + var err error + const operationName = "AzureLargeStorageInstanceClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, azureLargeStorageInstanceName, options) + if err != nil { + return AzureLargeStorageInstanceClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AzureLargeStorageInstanceClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return AzureLargeStorageInstanceClientDeleteResponse{}, err + } + return AzureLargeStorageInstanceClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *AzureLargeStorageInstanceClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, azureLargeStorageInstanceName string, _ *AzureLargeStorageInstanceClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureLargeInstance/azureLargeStorageInstances/{azureLargeStorageInstanceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if azureLargeStorageInstanceName == "" { + return nil, errors.New("parameter azureLargeStorageInstanceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{azureLargeStorageInstanceName}", url.PathEscape(azureLargeStorageInstanceName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240801Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Gets an Azure Large Storage instance for the specified subscription, resource +// group, and instance name. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - azureLargeStorageInstanceName - Name of the AzureLargeStorageInstance. +// - options - AzureLargeStorageInstanceClientGetOptions contains the optional parameters for the AzureLargeStorageInstanceClient.Get +// method. +func (client *AzureLargeStorageInstanceClient) Get(ctx context.Context, resourceGroupName string, azureLargeStorageInstanceName string, options *AzureLargeStorageInstanceClientGetOptions) (AzureLargeStorageInstanceClientGetResponse, error) { + var err error + const operationName = "AzureLargeStorageInstanceClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, azureLargeStorageInstanceName, options) + if err != nil { + return AzureLargeStorageInstanceClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AzureLargeStorageInstanceClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AzureLargeStorageInstanceClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *AzureLargeStorageInstanceClient) getCreateRequest(ctx context.Context, resourceGroupName string, azureLargeStorageInstanceName string, _ *AzureLargeStorageInstanceClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureLargeInstance/azureLargeStorageInstances/{azureLargeStorageInstanceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if azureLargeStorageInstanceName == "" { + return nil, errors.New("parameter azureLargeStorageInstanceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{azureLargeStorageInstanceName}", url.PathEscape(azureLargeStorageInstanceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240801Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *AzureLargeStorageInstanceClient) getHandleResponse(resp *http.Response) (AzureLargeStorageInstanceClientGetResponse, error) { + result := AzureLargeStorageInstanceClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AzureLargeStorageInstance); err != nil { + return AzureLargeStorageInstanceClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Gets a list of AzureLargeStorageInstances in the specified subscription and +// resource group. The operations returns various properties of each Azure +// LargeStorage instance. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - AzureLargeStorageInstanceClientListByResourceGroupOptions contains the optional parameters for the AzureLargeStorageInstanceClient.NewListByResourceGroupPager +// method. +func (client *AzureLargeStorageInstanceClient) NewListByResourceGroupPager(resourceGroupName string, options *AzureLargeStorageInstanceClientListByResourceGroupOptions) *runtime.Pager[AzureLargeStorageInstanceClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[AzureLargeStorageInstanceClientListByResourceGroupResponse]{ + More: func(page AzureLargeStorageInstanceClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AzureLargeStorageInstanceClientListByResourceGroupResponse) (AzureLargeStorageInstanceClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AzureLargeStorageInstanceClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return AzureLargeStorageInstanceClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *AzureLargeStorageInstanceClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *AzureLargeStorageInstanceClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureLargeInstance/azureLargeStorageInstances" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240801Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *AzureLargeStorageInstanceClient) listByResourceGroupHandleResponse(resp *http.Response) (AzureLargeStorageInstanceClientListByResourceGroupResponse, error) { + result := AzureLargeStorageInstanceClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AzureLargeStorageInstanceListResult); err != nil { + return AzureLargeStorageInstanceClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - Gets a list of AzureLargeStorageInstances in the specified subscription. The +// operations returns various properties of each Azure LargeStorage instance. +// - options - AzureLargeStorageInstanceClientListBySubscriptionOptions contains the optional parameters for the AzureLargeStorageInstanceClient.NewListBySubscriptionPager +// method. +func (client *AzureLargeStorageInstanceClient) NewListBySubscriptionPager(options *AzureLargeStorageInstanceClientListBySubscriptionOptions) *runtime.Pager[AzureLargeStorageInstanceClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[AzureLargeStorageInstanceClientListBySubscriptionResponse]{ + More: func(page AzureLargeStorageInstanceClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AzureLargeStorageInstanceClientListBySubscriptionResponse) (AzureLargeStorageInstanceClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AzureLargeStorageInstanceClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return AzureLargeStorageInstanceClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *AzureLargeStorageInstanceClient) listBySubscriptionCreateRequest(ctx context.Context, _ *AzureLargeStorageInstanceClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.AzureLargeInstance/azureLargeStorageInstances" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240801Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *AzureLargeStorageInstanceClient) listBySubscriptionHandleResponse(resp *http.Response) (AzureLargeStorageInstanceClientListBySubscriptionResponse, error) { + result := AzureLargeStorageInstanceClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AzureLargeStorageInstanceListResult); err != nil { + return AzureLargeStorageInstanceClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// Update - Patches the Tags field of a Azure Large Storage Instance for the specified +// subscription, resource group, and instance name. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - azureLargeStorageInstanceName - Name of the AzureLargeStorageInstance. +// - properties - The resource properties to be updated. +// - options - AzureLargeStorageInstanceClientUpdateOptions contains the optional parameters for the AzureLargeStorageInstanceClient.Update +// method. +func (client *AzureLargeStorageInstanceClient) Update(ctx context.Context, resourceGroupName string, azureLargeStorageInstanceName string, properties AzureLargeStorageInstanceTagsUpdate, options *AzureLargeStorageInstanceClientUpdateOptions) (AzureLargeStorageInstanceClientUpdateResponse, error) { + var err error + const operationName = "AzureLargeStorageInstanceClient.Update" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, azureLargeStorageInstanceName, properties, options) + if err != nil { + return AzureLargeStorageInstanceClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AzureLargeStorageInstanceClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AzureLargeStorageInstanceClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *AzureLargeStorageInstanceClient) updateCreateRequest(ctx context.Context, resourceGroupName string, azureLargeStorageInstanceName string, properties AzureLargeStorageInstanceTagsUpdate, _ *AzureLargeStorageInstanceClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureLargeInstance/azureLargeStorageInstances/{azureLargeStorageInstanceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if azureLargeStorageInstanceName == "" { + return nil, errors.New("parameter azureLargeStorageInstanceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{azureLargeStorageInstanceName}", url.PathEscape(azureLargeStorageInstanceName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240801Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *AzureLargeStorageInstanceClient) updateHandleResponse(resp *http.Response) (AzureLargeStorageInstanceClientUpdateResponse, error) { + result := AzureLargeStorageInstanceClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AzureLargeStorageInstance); err != nil { + return AzureLargeStorageInstanceClientUpdateResponse{}, err + } + return result, nil +} diff --git a/test/local/armlargeinstance/zz_client.go b/test/local/armlargeinstance/zz_client.go new file mode 100644 index 000000000000..1195a108b3c7 --- /dev/null +++ b/test/local/armlargeinstance/zz_client.go @@ -0,0 +1,625 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armlargeinstance + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// Client contains the methods for the service. +// Don't use this type directly, use NewClient() instead. +// +// Generated from API version 2024-08-01-preview +type Client struct { + internal *arm.Client + subscriptionID string +} + +// NewClient creates a new instance of Client with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*Client, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &Client{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Create - Creates an Azure Large Instance for the specified subscription, +// resource group, and instance name. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - azureLargeInstanceName - Name of the AzureLargeInstance. +// - resource - Resource create parameters. +// - options - ClientCreateOptions contains the optional parameters for the Client.Create method. +func (client *Client) Create(ctx context.Context, resourceGroupName string, azureLargeInstanceName string, resource AzureLargeInstance, options *ClientCreateOptions) (ClientCreateResponse, error) { + var err error + const operationName = "Client.Create" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, azureLargeInstanceName, resource, options) + if err != nil { + return ClientCreateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientCreateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return ClientCreateResponse{}, err + } + resp, err := client.createHandleResponse(httpResp) + return resp, err +} + +// createCreateRequest creates the Create request. +func (client *Client) createCreateRequest(ctx context.Context, resourceGroupName string, azureLargeInstanceName string, resource AzureLargeInstance, _ *ClientCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureLargeInstance/azureLargeInstances/{azureLargeInstanceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if azureLargeInstanceName == "" { + return nil, errors.New("parameter azureLargeInstanceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{azureLargeInstanceName}", url.PathEscape(azureLargeInstanceName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240801Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// createHandleResponse handles the Create response. +func (client *Client) createHandleResponse(resp *http.Response) (ClientCreateResponse, error) { + result := ClientCreateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AzureLargeInstance); err != nil { + return ClientCreateResponse{}, err + } + return result, nil +} + +// Delete - Deletes an Azure Large Instance for the specified subscription, resource group, +// and instance name. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - azureLargeInstanceName - Name of the AzureLargeInstance. +// - options - ClientDeleteOptions contains the optional parameters for the Client.Delete method. +func (client *Client) Delete(ctx context.Context, resourceGroupName string, azureLargeInstanceName string, options *ClientDeleteOptions) (ClientDeleteResponse, error) { + var err error + const operationName = "Client.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, azureLargeInstanceName, options) + if err != nil { + return ClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ClientDeleteResponse{}, err + } + return ClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *Client) deleteCreateRequest(ctx context.Context, resourceGroupName string, azureLargeInstanceName string, _ *ClientDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureLargeInstance/azureLargeInstances/{azureLargeInstanceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if azureLargeInstanceName == "" { + return nil, errors.New("parameter azureLargeInstanceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{azureLargeInstanceName}", url.PathEscape(azureLargeInstanceName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240801Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Gets an Azure Large Instance for the specified subscription, resource group, +// and instance name. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - azureLargeInstanceName - Name of the AzureLargeInstance. +// - options - ClientGetOptions contains the optional parameters for the Client.Get method. +func (client *Client) Get(ctx context.Context, resourceGroupName string, azureLargeInstanceName string, options *ClientGetOptions) (ClientGetResponse, error) { + var err error + const operationName = "Client.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, azureLargeInstanceName, options) + if err != nil { + return ClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *Client) getCreateRequest(ctx context.Context, resourceGroupName string, azureLargeInstanceName string, _ *ClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureLargeInstance/azureLargeInstances/{azureLargeInstanceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if azureLargeInstanceName == "" { + return nil, errors.New("parameter azureLargeInstanceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{azureLargeInstanceName}", url.PathEscape(azureLargeInstanceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240801Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *Client) getHandleResponse(resp *http.Response) (ClientGetResponse, error) { + result := ClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AzureLargeInstance); err != nil { + return ClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - Gets a list of Azure Large Instances in the specified subscription and resource +// group. The operations returns various properties of each Azure Large Instance. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - ClientListByResourceGroupOptions contains the optional parameters for the Client.NewListByResourceGroupPager +// method. +func (client *Client) NewListByResourceGroupPager(resourceGroupName string, options *ClientListByResourceGroupOptions) *runtime.Pager[ClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[ClientListByResourceGroupResponse]{ + More: func(page ClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ClientListByResourceGroupResponse) (ClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "Client.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return ClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *Client) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *ClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureLargeInstance/azureLargeInstances" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240801Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *Client) listByResourceGroupHandleResponse(resp *http.Response) (ClientListByResourceGroupResponse, error) { + result := ClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListResult); err != nil { + return ClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - Gets a list of Azure Large Instances in the specified subscription. The +// operations returns various properties of each Azure Large Instance. +// - options - ClientListBySubscriptionOptions contains the optional parameters for the Client.NewListBySubscriptionPager method. +func (client *Client) NewListBySubscriptionPager(options *ClientListBySubscriptionOptions) *runtime.Pager[ClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[ClientListBySubscriptionResponse]{ + More: func(page ClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ClientListBySubscriptionResponse) (ClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "Client.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return ClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *Client) listBySubscriptionCreateRequest(ctx context.Context, _ *ClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.AzureLargeInstance/azureLargeInstances" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240801Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *Client) listBySubscriptionHandleResponse(resp *http.Response) (ClientListBySubscriptionResponse, error) { + result := ClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListResult); err != nil { + return ClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// BeginRestart - The operation to restart an Azure Large Instance (only for compute instances) +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - azureLargeInstanceName - Name of the AzureLargeInstance. +// - options - ClientBeginRestartOptions contains the optional parameters for the Client.BeginRestart method. +func (client *Client) BeginRestart(ctx context.Context, resourceGroupName string, azureLargeInstanceName string, options *ClientBeginRestartOptions) (*runtime.Poller[ClientRestartResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.restart(ctx, resourceGroupName, azureLargeInstanceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ClientRestartResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ClientRestartResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Restart - The operation to restart an Azure Large Instance (only for compute instances) +// If the operation fails it returns an *azcore.ResponseError type. +func (client *Client) restart(ctx context.Context, resourceGroupName string, azureLargeInstanceName string, options *ClientBeginRestartOptions) (*http.Response, error) { + var err error + const operationName = "Client.BeginRestart" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.restartCreateRequest(ctx, resourceGroupName, azureLargeInstanceName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// restartCreateRequest creates the Restart request. +func (client *Client) restartCreateRequest(ctx context.Context, resourceGroupName string, azureLargeInstanceName string, options *ClientBeginRestartOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureLargeInstance/azureLargeInstances/{azureLargeInstanceName}/restart" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if azureLargeInstanceName == "" { + return nil, errors.New("parameter azureLargeInstanceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{azureLargeInstanceName}", url.PathEscape(azureLargeInstanceName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240801Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.ForceParameter != nil { + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, *options.ForceParameter); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// BeginShutdown - The operation to shutdown an Azure Large Instance (only for compute instances) +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - azureLargeInstanceName - Name of the AzureLargeInstance. +// - options - ClientBeginShutdownOptions contains the optional parameters for the Client.BeginShutdown method. +func (client *Client) BeginShutdown(ctx context.Context, resourceGroupName string, azureLargeInstanceName string, options *ClientBeginShutdownOptions) (*runtime.Poller[ClientShutdownResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.shutdown(ctx, resourceGroupName, azureLargeInstanceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ClientShutdownResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ClientShutdownResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Shutdown - The operation to shutdown an Azure Large Instance (only for compute instances) +// If the operation fails it returns an *azcore.ResponseError type. +func (client *Client) shutdown(ctx context.Context, resourceGroupName string, azureLargeInstanceName string, options *ClientBeginShutdownOptions) (*http.Response, error) { + var err error + const operationName = "Client.BeginShutdown" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.shutdownCreateRequest(ctx, resourceGroupName, azureLargeInstanceName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// shutdownCreateRequest creates the Shutdown request. +func (client *Client) shutdownCreateRequest(ctx context.Context, resourceGroupName string, azureLargeInstanceName string, _ *ClientBeginShutdownOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureLargeInstance/azureLargeInstances/{azureLargeInstanceName}/shutdown" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if azureLargeInstanceName == "" { + return nil, errors.New("parameter azureLargeInstanceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{azureLargeInstanceName}", url.PathEscape(azureLargeInstanceName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240801Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginStart - The operation to start an Azure Large Instance (only for compute instances) +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - azureLargeInstanceName - Name of the AzureLargeInstance. +// - options - ClientBeginStartOptions contains the optional parameters for the Client.BeginStart method. +func (client *Client) BeginStart(ctx context.Context, resourceGroupName string, azureLargeInstanceName string, options *ClientBeginStartOptions) (*runtime.Poller[ClientStartResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.start(ctx, resourceGroupName, azureLargeInstanceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ClientStartResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ClientStartResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Start - The operation to start an Azure Large Instance (only for compute instances) +// If the operation fails it returns an *azcore.ResponseError type. +func (client *Client) start(ctx context.Context, resourceGroupName string, azureLargeInstanceName string, options *ClientBeginStartOptions) (*http.Response, error) { + var err error + const operationName = "Client.BeginStart" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.startCreateRequest(ctx, resourceGroupName, azureLargeInstanceName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// startCreateRequest creates the Start request. +func (client *Client) startCreateRequest(ctx context.Context, resourceGroupName string, azureLargeInstanceName string, _ *ClientBeginStartOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureLargeInstance/azureLargeInstances/{azureLargeInstanceName}/start" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if azureLargeInstanceName == "" { + return nil, errors.New("parameter azureLargeInstanceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{azureLargeInstanceName}", url.PathEscape(azureLargeInstanceName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240801Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// Update - Patches the Tags field of an Azure Large Instance for the specified +// subscription, resource group, and instance name. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - azureLargeInstanceName - Name of the AzureLargeInstance. +// - properties - The resource properties to be updated. +// - options - ClientUpdateOptions contains the optional parameters for the Client.Update method. +func (client *Client) Update(ctx context.Context, resourceGroupName string, azureLargeInstanceName string, properties TagsUpdate, options *ClientUpdateOptions) (ClientUpdateResponse, error) { + var err error + const operationName = "Client.Update" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, azureLargeInstanceName, properties, options) + if err != nil { + return ClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *Client) updateCreateRequest(ctx context.Context, resourceGroupName string, azureLargeInstanceName string, properties TagsUpdate, _ *ClientUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AzureLargeInstance/azureLargeInstances/{azureLargeInstanceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if azureLargeInstanceName == "" { + return nil, errors.New("parameter azureLargeInstanceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{azureLargeInstanceName}", url.PathEscape(azureLargeInstanceName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240801Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *Client) updateHandleResponse(resp *http.Response) (ClientUpdateResponse, error) { + result := ClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AzureLargeInstance); err != nil { + return ClientUpdateResponse{}, err + } + return result, nil +} diff --git a/test/local/armlargeinstance/zz_client_factory.go b/test/local/armlargeinstance/zz_client_factory.go new file mode 100644 index 000000000000..5bb02cfee372 --- /dev/null +++ b/test/local/armlargeinstance/zz_client_factory.go @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armlargeinstance + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + subscriptionID string + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, + internal: internal, + }, nil +} + +// NewAzureLargeStorageInstanceClient creates a new instance of AzureLargeStorageInstanceClient. +func (c *ClientFactory) NewAzureLargeStorageInstanceClient() *AzureLargeStorageInstanceClient { + return &AzureLargeStorageInstanceClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewClient creates a new instance of Client. +func (c *ClientFactory) NewClient() *Client { + return &Client{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: c.internal, + } +} diff --git a/test/local/armlargeinstance/zz_constants.go b/test/local/armlargeinstance/zz_constants.go new file mode 100644 index 000000000000..b89dcf6dc38c --- /dev/null +++ b/test/local/armlargeinstance/zz_constants.go @@ -0,0 +1,419 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armlargeinstance + +const ( + version20240801Preview string = "2024-08-01-preview" +) + +// ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +type ActionType string + +const ( + // ActionTypeInternal - Actions are for internal-only APIs. + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// ForcePowerState - Enum of two possible values to determine if the ALI instance restart operation should forcefully terminate +// and halt any existing processes that may be running on the server or not. +type ForcePowerState string + +const ( + // ForcePowerStateActive - Active means that the restart operation will terminate and halt existing processes that may be + // running on the server + ForcePowerStateActive ForcePowerState = "active" + // ForcePowerStateInactive - Inactive means that the restart operation will not terminate and halt existing processes that + // may be running on the server + ForcePowerStateInactive ForcePowerState = "inactive" +) + +// PossibleForcePowerStateValues returns the possible values for the ForcePowerState const type. +func PossibleForcePowerStateValues() []ForcePowerState { + return []ForcePowerState{ + ForcePowerStateActive, + ForcePowerStateInactive, + } +} + +// HardwareTypeNamesEnum - Enum of the hardware options (vendor and/or their product name) for an Azure Large Instance +type HardwareTypeNamesEnum string + +const ( + // HardwareTypeNamesEnumCiscoUCS - Hardware type of UCS from vendor Cisco + HardwareTypeNamesEnumCiscoUCS HardwareTypeNamesEnum = "Cisco_UCS" + // HardwareTypeNamesEnumHPE - Hardware type of HPE from vendor Hewlett Packard Enterprise + HardwareTypeNamesEnumHPE HardwareTypeNamesEnum = "HPE" + // HardwareTypeNamesEnumSDFLEX - Hardware type of SDFLEX + HardwareTypeNamesEnumSDFLEX HardwareTypeNamesEnum = "SDFLEX" +) + +// PossibleHardwareTypeNamesEnumValues returns the possible values for the HardwareTypeNamesEnum const type. +func PossibleHardwareTypeNamesEnumValues() []HardwareTypeNamesEnum { + return []HardwareTypeNamesEnum{ + HardwareTypeNamesEnumCiscoUCS, + HardwareTypeNamesEnumHPE, + HardwareTypeNamesEnumSDFLEX, + } +} + +// ManagedServiceIdentityType - Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). +type ManagedServiceIdentityType string + +const ( + // ManagedServiceIdentityTypeNone - No managed identity. + ManagedServiceIdentityTypeNone ManagedServiceIdentityType = "None" + // ManagedServiceIdentityTypeSystemAssigned - System assigned managed identity. + ManagedServiceIdentityTypeSystemAssigned ManagedServiceIdentityType = "SystemAssigned" + // ManagedServiceIdentityTypeSystemAssignedUserAssigned - System and user assigned managed identity. + ManagedServiceIdentityTypeSystemAssignedUserAssigned ManagedServiceIdentityType = "SystemAssigned,UserAssigned" + // ManagedServiceIdentityTypeUserAssigned - User assigned managed identity. + ManagedServiceIdentityTypeUserAssigned ManagedServiceIdentityType = "UserAssigned" +) + +// PossibleManagedServiceIdentityTypeValues returns the possible values for the ManagedServiceIdentityType const type. +func PossibleManagedServiceIdentityTypeValues() []ManagedServiceIdentityType { + return []ManagedServiceIdentityType{ + ManagedServiceIdentityTypeNone, + ManagedServiceIdentityTypeSystemAssigned, + ManagedServiceIdentityTypeSystemAssignedUserAssigned, + ManagedServiceIdentityTypeUserAssigned, + } +} + +// Origin - The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default +// value is "user,system" +type Origin string + +const ( + // OriginSystem - Indicates the operation is initiated by a system. + OriginSystem Origin = "system" + // OriginUser - Indicates the operation is initiated by a user. + OriginUser Origin = "user" + // OriginUserSystem - Indicates the operation is initiated by a user or system. + OriginUserSystem Origin = "user,system" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginSystem, + OriginUser, + OriginUserSystem, + } +} + +// PowerStateEnum - Power states that an Azure Large Instance can be in +type PowerStateEnum string + +const ( + // PowerStateEnumRestarting - Restarting means that the Azure Large Instance resource is restarting. + PowerStateEnumRestarting PowerStateEnum = "restarting" + // PowerStateEnumStarted - Started means that the Azure Large Instance resource has been powered on. + PowerStateEnumStarted PowerStateEnum = "started" + // PowerStateEnumStarting - Starting means that the Azure Large Instance resource is turning on. + PowerStateEnumStarting PowerStateEnum = "starting" + // PowerStateEnumStopped - Stopped means that the Azure Large Instance resource has shut down. + PowerStateEnumStopped PowerStateEnum = "stopped" + // PowerStateEnumStopping - Stopping means that the Azure Large Instance resource is shutting down. + PowerStateEnumStopping PowerStateEnum = "stopping" + // PowerStateEnumUnknown - Unknown means that the state of the Azure Large Instance is unknown. + PowerStateEnumUnknown PowerStateEnum = "unknown" +) + +// PossiblePowerStateEnumValues returns the possible values for the PowerStateEnum const type. +func PossiblePowerStateEnumValues() []PowerStateEnum { + return []PowerStateEnum{ + PowerStateEnumRestarting, + PowerStateEnumStarted, + PowerStateEnumStarting, + PowerStateEnumStopped, + PowerStateEnumStopping, + PowerStateEnumUnknown, + } +} + +// ProvisioningState - An enum of possible operation states for an AzureLargeStorageInstances +type ProvisioningState string + +const ( + // ProvisioningStateAccepted - Accepted means ARM resource has been accepted. + ProvisioningStateAccepted ProvisioningState = "Accepted" + // ProvisioningStateCanceled - Cancelled means resource operation has been cancelled + ProvisioningStateCanceled ProvisioningState = "Canceled" + // ProvisioningStateCreating - Creating means ARM resource is being created. + ProvisioningStateCreating ProvisioningState = "Creating" + // ProvisioningStateDeleting - Deleting means resource is in the process of being deleted + ProvisioningStateDeleting ProvisioningState = "Deleting" + // ProvisioningStateFailed - Failed means resource is in failed state + ProvisioningStateFailed ProvisioningState = "Failed" + // ProvisioningStateMigrating - Migrating means resource is being migrated from one subscription or resource group to another + ProvisioningStateMigrating ProvisioningState = "Migrating" + // ProvisioningStateSucceeded - Succeeded means resource creation succeeded during last create/update + ProvisioningStateSucceeded ProvisioningState = "Succeeded" + // ProvisioningStateUpdating - Updating means an existing ARM resource is being updated + ProvisioningStateUpdating ProvisioningState = "Updating" +) + +// PossibleProvisioningStateValues returns the possible values for the ProvisioningState const type. +func PossibleProvisioningStateValues() []ProvisioningState { + return []ProvisioningState{ + ProvisioningStateAccepted, + ProvisioningStateCanceled, + ProvisioningStateCreating, + ProvisioningStateDeleting, + ProvisioningStateFailed, + ProvisioningStateMigrating, + ProvisioningStateSucceeded, + ProvisioningStateUpdating, + } +} + +// ProvisioningStatesEnum - Provisioning states that an Azure Large Instance can be in +type ProvisioningStatesEnum string + +const ( + // ProvisioningStatesEnumAccepted - Accepted means Azure Large Instance resource provisioning has been accepted. + ProvisioningStatesEnumAccepted ProvisioningStatesEnum = "Accepted" + // ProvisioningStatesEnumCanceled - Cancelled Azure Large Instance resource operation has been cancelled + ProvisioningStatesEnumCanceled ProvisioningStatesEnum = "Canceled" + // ProvisioningStatesEnumCreating - Creating means Azure Large Instance resource is being created. + ProvisioningStatesEnumCreating ProvisioningStatesEnum = "Creating" + // ProvisioningStatesEnumDeleting - Deleting means Azure Large Instance resource is in the process of being deleted + ProvisioningStatesEnumDeleting ProvisioningStatesEnum = "Deleting" + // ProvisioningStatesEnumFailed - Failed means Azure Large Instance resource is in failed state + ProvisioningStatesEnumFailed ProvisioningStatesEnum = "Failed" + // ProvisioningStatesEnumMigrating - Migrating means Azure Large Instance resource is being migrated from one subscription + // or resource group to another + ProvisioningStatesEnumMigrating ProvisioningStatesEnum = "Migrating" + // ProvisioningStatesEnumSucceeded - Succeeded means Azure Large Instance resource creation succeeded during last create/update + ProvisioningStatesEnumSucceeded ProvisioningStatesEnum = "Succeeded" + // ProvisioningStatesEnumUpdating - Updating means an existing Azure Large Instance resource is being updated + ProvisioningStatesEnumUpdating ProvisioningStatesEnum = "Updating" +) + +// PossibleProvisioningStatesEnumValues returns the possible values for the ProvisioningStatesEnum const type. +func PossibleProvisioningStatesEnumValues() []ProvisioningStatesEnum { + return []ProvisioningStatesEnum{ + ProvisioningStatesEnumAccepted, + ProvisioningStatesEnumCanceled, + ProvisioningStatesEnumCreating, + ProvisioningStatesEnumDeleting, + ProvisioningStatesEnumFailed, + ProvisioningStatesEnumMigrating, + ProvisioningStatesEnumSucceeded, + ProvisioningStatesEnumUpdating, + } +} + +// SizeNamesEnum - Enum of available model types (each of which have their own storage / memory sizes) for an Azure Large +// Instance type. See https://learn.microsoft.com/azure/sap/large-instances/hana-available-skus +type SizeNamesEnum string + +const ( + // SizeNamesEnumS112 - No longer offered or used. + SizeNamesEnumS112 SizeNamesEnum = "S112" + // SizeNamesEnumS144 - Type I class SKU that can't be purchased anymore + SizeNamesEnumS144 SizeNamesEnum = "S144" + // SizeNamesEnumS144M - Type I class SKU that can't be purchased anymore + SizeNamesEnumS144M SizeNamesEnum = "S144m" + // SizeNamesEnumS192 - Type I class SKU that can't be purchased anymore + SizeNamesEnumS192 SizeNamesEnum = "S192" + // SizeNamesEnumS192M - Type I class SKU that can't be purchased anymore + SizeNamesEnumS192M SizeNamesEnum = "S192m" + // SizeNamesEnumS192Xm - Type I class SKU that can't be purchased anymore + SizeNamesEnumS192Xm SizeNamesEnum = "S192xm" + // SizeNamesEnumS224 - 4 sockets, 224 CPU threads, 112 CPU cores, 3 TB total memory, 3 TB DRAM, 6.3 TB storage, Cisco_UCS + // hardware type + SizeNamesEnumS224 SizeNamesEnum = "S224" + // SizeNamesEnumS224M - 4 sockets, 224 CPU threads, 112 CPU cores, 6 TB total memory, 6 TB DRAM, 10.5 TB storage, Cisco_UCS + // hardware type + SizeNamesEnumS224M SizeNamesEnum = "S224m" + // SizeNamesEnumS224Om - 4 sockets, 224 CPU threads, 112 CPU cores, 6 TB total memory, 3 TB DRAM, 3 TB memory optane, 10.5 + // TB storage, Cisco_UCS hardware type + SizeNamesEnumS224Om SizeNamesEnum = "S224om" + // SizeNamesEnumS224Oo - 4 sockets, 224 CPU threads, 112 CPU cores, 4.5 TB total memory, 1.5 TB DRAM, 3 TB memory optane, + // 8.4 TB storage, Cisco_UCS hardware type + SizeNamesEnumS224Oo SizeNamesEnum = "S224oo" + // SizeNamesEnumS224Oom - 4 sockets, 224 CPU threads, 112 CPU cores, 9 TB total memory, 3 TB DRAM, 6 TB memory optane, 14.8 + // TB storage, Cisco_UCS hardware type + SizeNamesEnumS224Oom SizeNamesEnum = "S224oom" + // SizeNamesEnumS224Ooo - 4 sockets, 224 CPU threads, 112 CPU cores, 7.5TB total memory, 1.5 TB DRAM, 6 TB memory optane, + // 12.7 TB storage, Cisco_UCS hardware type + SizeNamesEnumS224Ooo SizeNamesEnum = "S224ooo" + // SizeNamesEnumS224Se - 4 sockets, 448 CPU threads, 6 TB total memory, SDFLEX hardware type + SizeNamesEnumS224Se SizeNamesEnum = "S224se" + // SizeNamesEnumS384 - 8 sockets, 384 CPU threads, 192 CPU cores, 4 TB total memory, 4 TB DRAM, 16 TB storage, HPEMc990x hardware + // type + SizeNamesEnumS384 SizeNamesEnum = "S384" + // SizeNamesEnumS384M - 8 sockets, 384 CPU threads, 192 CPU cores, 6 TB total memory, 6 TB DRAM, 18 TB storage, HPEMc990x + // hardware type + SizeNamesEnumS384M SizeNamesEnum = "S384m" + // SizeNamesEnumS384Xm - 8 sockets, 384 CPU threads, 192 CPU cores, 8 TB total memory, 8 TB DRAM, 22 TB storage, HPEMc990x + // hardware type + SizeNamesEnumS384Xm SizeNamesEnum = "S384xm" + // SizeNamesEnumS384Xxm - 8 sockets, 384 CPU threads, 12 TB total memory, HPEMc990x hardware type + SizeNamesEnumS384Xxm SizeNamesEnum = "S384xxm" + // SizeNamesEnumS448 - 8 sockets, 448 CPU threads, 224 CPU cores, 6 TB total memory, 6 TB DRAM, 10.5 TB storage, SDFLEX hardware + // type + SizeNamesEnumS448 SizeNamesEnum = "S448" + // SizeNamesEnumS448M - 8 sockets, 448 CPU threads, 224 CPU cores, 12 TB total memory, 12 TB DRAM, 18.9 TB storage, SDFLEX + // hardware type + SizeNamesEnumS448M SizeNamesEnum = "S448m" + // SizeNamesEnumS448Om - 8 sockets, 448 CPU threads, 224 CPU cores, 12 TB total memory, 6 TB DRAM, 6 TB memory optane, 18.9 + // TB storage, SDFLEX hardware type + SizeNamesEnumS448Om SizeNamesEnum = "S448om" + // SizeNamesEnumS448Oo - 8 sockets, 448 CPU threads, 224 CPU cores, 9 TB total memory, 3 TB DRAM, 6 TB memory optane, 14.8 + // TB storage, SDFLEX hardware type + SizeNamesEnumS448Oo SizeNamesEnum = "S448oo" + // SizeNamesEnumS448Oom - 8 sockets, 448 CPU threads, 224 CPU cores, 18 TB total memory, 6 TB DRAM, 12 memory optane, 27.4 + // TB storage, SDFLEX hardware type + SizeNamesEnumS448Oom SizeNamesEnum = "S448oom" + // SizeNamesEnumS448Ooo - 8 sockets, 448 CPU threads, 224 CPU cores, 15 TB total memory, 3 TB DRAM, 12 memory optane, 23.2 + // TB storage, SDFLEX hardware type + SizeNamesEnumS448Ooo SizeNamesEnum = "S448ooo" + // SizeNamesEnumS448Se - 8 sockets, 448 CPU threads, 12 TB total memory, SDFLEX hardware type + SizeNamesEnumS448Se SizeNamesEnum = "S448se" + // SizeNamesEnumS576M - 12 sockets, 576 CPU threads, 288 CPU cores, 12 TB total memory, 12 TB DRAM, 28 TB storage, HPEMc990x + // hardware type + SizeNamesEnumS576M SizeNamesEnum = "S576m" + // SizeNamesEnumS576Xm - 12 sockets, 576 CPU threads, 288 CPU cores, 18 TB total memory, HPEMc990x hardware type + SizeNamesEnumS576Xm SizeNamesEnum = "S576xm" + // SizeNamesEnumS672 - 12 sockets, 672 CPU threads, 336 CPU cores, 9 TB total memory, 9 TB DRAM, 14.7 TB storage, SDFLEX hardware + // type + SizeNamesEnumS672 SizeNamesEnum = "S672" + // SizeNamesEnumS672M - 12 sockets, 672 CPU threads, 336 CPU cores, 18 TB total memory, 18 TB DRAM, 27.4 TB storage, SDFLEX + // hardware type + SizeNamesEnumS672M SizeNamesEnum = "S672m" + // SizeNamesEnumS672Om - 12 sockets, 672 CPU threads, 336 CPU cores, 18 TB total memory, 9 TB DRAM, 9 TB memory optane, 27.4 + // TB storage, SDFLEX hardware type + SizeNamesEnumS672Om SizeNamesEnum = "S672om" + // SizeNamesEnumS672Oo - 12 sockets, 672 CPU threads, 336 CPU cores, 13.5 TB total memory, 4.5 TB DRAM, 9 TB memory optane, + // 21.1 TB storage, SDFLEX hardware type + SizeNamesEnumS672Oo SizeNamesEnum = "S672oo" + // SizeNamesEnumS672Oom - 12 sockets, 672 CPU threads, 336 CPU cores, 27 TB total memory, 9 TB DRAM, 18 TB memory optane, + // 40 TB storage, SDFLEX hardware type + SizeNamesEnumS672Oom SizeNamesEnum = "S672oom" + // SizeNamesEnumS672Ooo - 12 sockets, 672 CPU threads, 336 CPU cores, 22.5 TB total memory, 4.5 TB DRAM, 18 TB memory optane, + // 33.7 TB storage, SDFLEX hardware type + SizeNamesEnumS672Ooo SizeNamesEnum = "S672ooo" + // SizeNamesEnumS72 - Type I class SKU that can't be purchased anymore + SizeNamesEnumS72 SizeNamesEnum = "S72" + // SizeNamesEnumS72M - Type I class SKU that can't be purchased anymore + SizeNamesEnumS72M SizeNamesEnum = "S72m" + // SizeNamesEnumS768 - No longer offered or used. + SizeNamesEnumS768 SizeNamesEnum = "S768" + // SizeNamesEnumS768M - 16 sockets, 768 CPU threads, 384 CPU cores, 16 TB total memory, 16 TB DRAM, 36 TB storage, HPEMc990x + // hardware type + SizeNamesEnumS768M SizeNamesEnum = "S768m" + // SizeNamesEnumS768Xm - 16 sockets, 768 CPU threads, 384 CPU cores, 24 TB total memory, 24 TB DRAM, 56 TB storage, HPEMc990x + // hardware type + SizeNamesEnumS768Xm SizeNamesEnum = "S768xm" + // SizeNamesEnumS896 - 16 sockets, 896 CPU threads, 448 CPU cores, 12 TB total memory, 12 TB DRAM, 18.9 TB storage, SDFLEX + // hardware type + SizeNamesEnumS896 SizeNamesEnum = "S896" + // SizeNamesEnumS896M - 16 sockets, 896 CPU threads, 448 CPU cores, 24 TB total memory, 24 TB DRAM, 35.8 TB storage, SDFLEX + // hardware type + SizeNamesEnumS896M SizeNamesEnum = "S896m" + // SizeNamesEnumS896Om - 16 sockets, 896 CPU threads, 448 CPU cores, 24 TB total memory, 12 TB DRAM, 12 TB memory optane, + // 35.8 TB storage, SDFLEX hardware type + SizeNamesEnumS896Om SizeNamesEnum = "S896om" + // SizeNamesEnumS896Oo - 16 sockets, 896 CPU threads, 448 CPU cores, 18 TB total memory, 6 TB DRAM, 12 TB memory optane, 27.4 + // TB storage, SDFLEX hardware type + SizeNamesEnumS896Oo SizeNamesEnum = "S896oo" + // SizeNamesEnumS896Oom - 16 sockets, 896 CPU threads, 448 CPU cores, 36 TB total memory, 12 TB DRAM, 24 TB memory optane, + // 52.7 TB storage, SDFLEX hardware type + SizeNamesEnumS896Oom SizeNamesEnum = "S896oom" + // SizeNamesEnumS896Ooo - 16 sockets, 896 CPU threads, 448 CPU cores, 30 TB total memory, 6 TB DRAM, 24 TB memory optane, + // 44.3 TB storage, SDFLEX hardware type + SizeNamesEnumS896Ooo SizeNamesEnum = "S896ooo" + // SizeNamesEnumS96 - 2 sockets, 96 CPU threads, 48 CPU cores, 768 GB total memory, 768 GB DRAM, 3.0 TB storage, Cisco_UCS + // hardware type + SizeNamesEnumS96 SizeNamesEnum = "S96" + // SizeNamesEnumS960M - 20 sockets, 960 CPU threads, 480 CPU cores, 20 TB total memory, 20 TB DRAM, 46 TB storage, HPEMc990x + // hardware type + SizeNamesEnumS960M SizeNamesEnum = "S960m" +) + +// PossibleSizeNamesEnumValues returns the possible values for the SizeNamesEnum const type. +func PossibleSizeNamesEnumValues() []SizeNamesEnum { + return []SizeNamesEnum{ + SizeNamesEnumS112, + SizeNamesEnumS144, + SizeNamesEnumS144M, + SizeNamesEnumS192, + SizeNamesEnumS192M, + SizeNamesEnumS192Xm, + SizeNamesEnumS224, + SizeNamesEnumS224M, + SizeNamesEnumS224Om, + SizeNamesEnumS224Oo, + SizeNamesEnumS224Oom, + SizeNamesEnumS224Ooo, + SizeNamesEnumS224Se, + SizeNamesEnumS384, + SizeNamesEnumS384M, + SizeNamesEnumS384Xm, + SizeNamesEnumS384Xxm, + SizeNamesEnumS448, + SizeNamesEnumS448M, + SizeNamesEnumS448Om, + SizeNamesEnumS448Oo, + SizeNamesEnumS448Oom, + SizeNamesEnumS448Ooo, + SizeNamesEnumS448Se, + SizeNamesEnumS576M, + SizeNamesEnumS576Xm, + SizeNamesEnumS672, + SizeNamesEnumS672M, + SizeNamesEnumS672Om, + SizeNamesEnumS672Oo, + SizeNamesEnumS672Oom, + SizeNamesEnumS672Ooo, + SizeNamesEnumS72, + SizeNamesEnumS72M, + SizeNamesEnumS768, + SizeNamesEnumS768M, + SizeNamesEnumS768Xm, + SizeNamesEnumS896, + SizeNamesEnumS896M, + SizeNamesEnumS896Om, + SizeNamesEnumS896Oo, + SizeNamesEnumS896Oom, + SizeNamesEnumS896Ooo, + SizeNamesEnumS96, + SizeNamesEnumS960M, + } +} diff --git a/test/local/armlargeinstance/zz_models.go b/test/local/armlargeinstance/zz_models.go new file mode 100644 index 000000000000..1accbd2c9126 --- /dev/null +++ b/test/local/armlargeinstance/zz_models.go @@ -0,0 +1,389 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armlargeinstance + +import "time" + +// AzureLargeInstance - Azure Large Instance info on Azure (ARM properties and AzureLargeInstance +// properties) +type AzureLargeInstance struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *Properties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// AzureLargeStorageInstance info on Azure (ARM properties and +// AzureLargeStorageInstance properties) +type AzureLargeStorageInstance struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The managed service identities assigned to this resource. + Identity *ManagedServiceIdentity + + // The resource-specific properties for this resource. + Properties *AzureLargeStorageInstanceProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// AzureLargeStorageInstanceListResult - The response of a AzureLargeStorageInstance list operation. +type AzureLargeStorageInstanceListResult struct { + // REQUIRED; The AzureLargeStorageInstance items on this page + Value []*AzureLargeStorageInstance + + // The link to the next page of items + NextLink *string +} + +// AzureLargeStorageInstanceProperties - Describes the properties of an AzureLargeStorageInstance. +type AzureLargeStorageInstanceProperties struct { + // Specifies the AzureLargeStorageInstance unique ID. + AzureLargeStorageInstanceUniqueIdentifier *string + + // Specifies the storage properties for the AzureLargeStorage instance. + StorageProperties *StorageProperties +} + +// AzureLargeStorageInstanceTagsUpdate - The type used for updating tags in AzureLargeStorageInstance resources. +type AzureLargeStorageInstanceTagsUpdate struct { + // The managed service identities assigned to this resource. + Identity *ManagedServiceIdentity + + // Resource tags. + Tags map[string]*string +} + +// Disk - Specifies the disk information fo the Azure Large Instance +type Disk struct { + // Specifies the size of an empty data disk in gigabytes. + DiskSizeGB *int32 + + // The disk name. + Name *string + + // READ-ONLY; Specifies the logical unit number of the data disk. This value is used to + // identify data disks within the VM and therefore must be unique for each data + // disk attached to a VM. + Lun *int32 +} + +// ErrorAdditionalInfo - The resource management error additional info. +type ErrorAdditionalInfo struct { + // READ-ONLY; The additional info. + Info any + + // READ-ONLY; The additional info type. + Type *string +} + +// ErrorDetail - The error detail. +type ErrorDetail struct { + // READ-ONLY; The error additional info. + AdditionalInfo []*ErrorAdditionalInfo + + // READ-ONLY; The error code. + Code *string + + // READ-ONLY; The error details. + Details []*ErrorDetail + + // READ-ONLY; The error message. + Message *string + + // READ-ONLY; The error target. + Target *string +} + +// ForceState - The active state empowers the server with the ability to forcefully terminate +// and halt any existing processes that may be running on the server +type ForceState struct { + // Whether to force restart by shutting all processes. + ForceState *ForcePowerState +} + +// HardwareProfile - Specifies the hardware settings for the Azure Large Instance. +type HardwareProfile struct { + // Specifies the Azure Large Instance SKU. + AzureLargeInstanceSize *SizeNamesEnum + + // Name of the hardware type (vendor and/or their product name) + HardwareType *HardwareTypeNamesEnum +} + +// IPAddress - Specifies the IP address of the network interface. +type IPAddress struct { + // Specifies the IP address of the network interface. + IPAddress *string +} + +// ListResult - The response of a AzureLargeInstance list operation. +type ListResult struct { + // REQUIRED; The AzureLargeInstance items on this page + Value []*AzureLargeInstance + + // The link to the next page of items + NextLink *string +} + +// ManagedServiceIdentity - Managed service identity (system assigned and/or user assigned identities) +type ManagedServiceIdentity struct { + // REQUIRED; The type of managed identity assigned to this resource. + Type *ManagedServiceIdentityType + + // The identities assigned to this resource by the user. + UserAssignedIdentities map[string]*UserAssignedIdentity + + // READ-ONLY; The service principal ID of the system assigned identity. This property will only be provided for a system assigned + // identity. + PrincipalID *string + + // READ-ONLY; The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + TenantID *string +} + +// NetworkProfile - Specifies the network settings for the Azure Large Instance disks. +type NetworkProfile struct { + // Specifies the circuit id for connecting to express route. + CircuitID *string + + // Specifies the network interfaces for the Azure Large Instance. + NetworkInterfaces []*IPAddress +} + +// Operation - REST API Operation +// +// Details of a REST API operation, returned from the Resource Provider Operations API +type Operation struct { + // Localized display information for this particular operation. + Display *OperationDisplay + + // READ-ONLY; Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + ActionType *ActionType + + // READ-ONLY; Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure + // Resource Manager/control-plane operations. + IsDataAction *bool + + // READ-ONLY; The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + // "Microsoft.Compute/virtualMachines/capture/action" + Name *string + + // READ-ONLY; The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default + // value is "user,system" + Origin *Origin +} + +// OperationDisplay - Localized display information for an operation. +type OperationDisplay struct { + // READ-ONLY; The short, localized friendly description of the operation; suitable for tool tips and detailed views. + Description *string + + // READ-ONLY; The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual + // Machine", "Restart Virtual Machine". + Operation *string + + // READ-ONLY; The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft + // Compute". + Provider *string + + // READ-ONLY; The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job + // Schedule Collections". + Resource *string +} + +// OperationListResult - A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to +// get the next set of results. +type OperationListResult struct { + // REQUIRED; The Operation items on this page + Value []*Operation + + // The link to the next page of items + NextLink *string +} + +// OperationStatusResult - The current status of an async operation. +type OperationStatusResult struct { + // REQUIRED; Operation status. + Status *string + + // The end time of the operation. + EndTime *time.Time + + // If present, details of the operation error. + Error *ErrorDetail + + // Fully qualified ID for the async operation. + ID *string + + // Name of the async operation. + Name *string + + // The operations list. + Operations []*OperationStatusResult + + // Percent of the operation that is complete. + PercentComplete *float64 + + // The start time of the operation. + StartTime *time.Time + + // READ-ONLY; Fully qualified ID of the resource against which the original async operation was started. + ResourceID *string +} + +// OsProfile - Specifies the operating system settings for the Azure Large Instance. +type OsProfile struct { + // Specifies the host OS name of the Azure Large Instance. + ComputerName *string + + // This property allows you to specify the type of the OS. + OSType *string + + // Specifies the SSH public key used to access the operating system. + SSHPublicKey *string + + // Specifies version of operating system. + Version *string +} + +// Properties - Describes the properties of an Azure Large Instance. +type Properties struct { + // Specifies the Azure Large Instance unique ID. + AzureLargeInstanceID *string + + // Specifies the hardware settings for the Azure Large Instance. + HardwareProfile *HardwareProfile + + // Hardware revision of an Azure Large Instance + HwRevision *string + + // Specifies the network settings for the Azure Large Instance. + NetworkProfile *NetworkProfile + + // Specifies the operating system settings for the Azure Large Instance. + OSProfile *OsProfile + + // Resource power state + PowerState *PowerStateEnum + + // Resource proximity placement group + ProximityPlacementGroup *string + + // Specifies the storage settings for the Azure Large Instance disks. + StorageProfile *StorageProfile + + // READ-ONLY; State of provisioning of the AzureLargeInstance + ProvisioningState *ProvisioningStatesEnum +} + +// StorageBillingProperties - Describes the billing related details of the AzureLargeStorageInstance. +type StorageBillingProperties struct { + // the billing mode for the storage instance + BillingMode *string + + // the SKU type that is provisioned + SKU *string +} + +// StorageProfile - Specifies the storage settings for the Azure Large Instance disks. +type StorageProfile struct { + // IP Address to connect to storage. + NfsIPAddress *string + + // Specifies information about the operating system disk used by Azure Large + // Instance. + OSDisks []*Disk +} + +// StorageProperties - described the storage properties of the azure large storage instance +type StorageProperties struct { + // the kind of storage instance + Generation *string + + // the hardware type of the storage instance + HardwareType *HardwareTypeNamesEnum + + // the offering type for which the resource is getting provisioned + OfferingType *string + + // State of provisioning of the AzureLargeStorageInstance + ProvisioningState *ProvisioningState + + // the billing related information for the resource + StorageBillingProperties *StorageBillingProperties + + // the storage protocol for which the resource is getting provisioned + StorageType *string + + // the workload for which the resource is getting provisioned + WorkloadType *string +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time + + // The identity that created the resource. + CreatedBy *string + + // The type of identity that created the resource. + CreatedByType *CreatedByType + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time + + // The identity that last modified the resource. + LastModifiedBy *string + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType +} + +// TagsUpdate - The type used for updating tags in AzureLargeInstance resources. +type TagsUpdate struct { + // Resource tags. + Tags map[string]*string +} + +// UserAssignedIdentity - User assigned identity properties +type UserAssignedIdentity struct { + // READ-ONLY; The client ID of the assigned identity. + ClientID *string + + // READ-ONLY; The principal ID of the assigned identity. + PrincipalID *string +} diff --git a/test/local/armlargeinstance/zz_models_serde.go b/test/local/armlargeinstance/zz_models_serde.go new file mode 100644 index 000000000000..57bda6d74a11 --- /dev/null +++ b/test/local/armlargeinstance/zz_models_serde.go @@ -0,0 +1,1054 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armlargeinstance + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type AzureLargeInstance. +func (a AzureLargeInstance) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "location", a.Location) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "tags", a.Tags) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureLargeInstance. +func (a *AzureLargeInstance) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &a.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &a.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &a.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AzureLargeStorageInstance. +func (a AzureLargeStorageInstance) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "identity", a.Identity) + populate(objectMap, "location", a.Location) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "tags", a.Tags) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureLargeStorageInstance. +func (a *AzureLargeStorageInstance) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &a.Identity) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &a.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &a.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &a.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AzureLargeStorageInstanceListResult. +func (a AzureLargeStorageInstanceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureLargeStorageInstanceListResult. +func (a *AzureLargeStorageInstanceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &a.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AzureLargeStorageInstanceProperties. +func (a AzureLargeStorageInstanceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "azureLargeStorageInstanceUniqueIdentifier", a.AzureLargeStorageInstanceUniqueIdentifier) + populate(objectMap, "storageProperties", a.StorageProperties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureLargeStorageInstanceProperties. +func (a *AzureLargeStorageInstanceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "azureLargeStorageInstanceUniqueIdentifier": + err = unpopulate(val, "AzureLargeStorageInstanceUniqueIdentifier", &a.AzureLargeStorageInstanceUniqueIdentifier) + delete(rawMsg, key) + case "storageProperties": + err = unpopulate(val, "StorageProperties", &a.StorageProperties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AzureLargeStorageInstanceTagsUpdate. +func (a AzureLargeStorageInstanceTagsUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identity", a.Identity) + populate(objectMap, "tags", a.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureLargeStorageInstanceTagsUpdate. +func (a *AzureLargeStorageInstanceTagsUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "identity": + err = unpopulate(val, "Identity", &a.Identity) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &a.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Disk. +func (d Disk) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "diskSizeGB", d.DiskSizeGB) + populate(objectMap, "lun", d.Lun) + populate(objectMap, "name", d.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Disk. +func (d *Disk) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "diskSizeGB": + err = unpopulate(val, "DiskSizeGB", &d.DiskSizeGB) + delete(rawMsg, key) + case "lun": + err = unpopulate(val, "Lun", &d.Lun) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ErrorAdditionalInfo. +func (e ErrorAdditionalInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateAny(objectMap, "info", e.Info) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ErrorAdditionalInfo. +func (e *ErrorAdditionalInfo) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "info": + err = unpopulate(val, "Info", &e.Info) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &e.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ErrorDetail. +func (e ErrorDetail) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "additionalInfo", e.AdditionalInfo) + populate(objectMap, "code", e.Code) + populate(objectMap, "details", e.Details) + populate(objectMap, "message", e.Message) + populate(objectMap, "target", e.Target) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ErrorDetail. +func (e *ErrorDetail) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "additionalInfo": + err = unpopulate(val, "AdditionalInfo", &e.AdditionalInfo) + delete(rawMsg, key) + case "code": + err = unpopulate(val, "Code", &e.Code) + delete(rawMsg, key) + case "details": + err = unpopulate(val, "Details", &e.Details) + delete(rawMsg, key) + case "message": + err = unpopulate(val, "Message", &e.Message) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "Target", &e.Target) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ForceState. +func (f ForceState) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "forceState", f.ForceState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ForceState. +func (f *ForceState) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "forceState": + err = unpopulate(val, "ForceState", &f.ForceState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HardwareProfile. +func (h HardwareProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "azureLargeInstanceSize", h.AzureLargeInstanceSize) + populate(objectMap, "hardwareType", h.HardwareType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HardwareProfile. +func (h *HardwareProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "azureLargeInstanceSize": + err = unpopulate(val, "AzureLargeInstanceSize", &h.AzureLargeInstanceSize) + delete(rawMsg, key) + case "hardwareType": + err = unpopulate(val, "HardwareType", &h.HardwareType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type IPAddress. +func (i IPAddress) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "ipAddress", i.IPAddress) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IPAddress. +func (i *IPAddress) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "ipAddress": + err = unpopulate(val, "IPAddress", &i.IPAddress) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ListResult. +func (l ListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", l.NextLink) + populate(objectMap, "value", l.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ListResult. +func (l *ListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &l.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &l.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedServiceIdentity. +func (m ManagedServiceIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "principalId", m.PrincipalID) + populate(objectMap, "tenantId", m.TenantID) + populate(objectMap, "type", m.Type) + populate(objectMap, "userAssignedIdentities", m.UserAssignedIdentities) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedServiceIdentity. +func (m *ManagedServiceIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "principalId": + err = unpopulate(val, "PrincipalID", &m.PrincipalID) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &m.TenantID) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + case "userAssignedIdentities": + err = unpopulate(val, "UserAssignedIdentities", &m.UserAssignedIdentities) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkProfile. +func (n NetworkProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "circuitId", n.CircuitID) + populate(objectMap, "networkInterfaces", n.NetworkInterfaces) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkProfile. +func (n *NetworkProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "circuitId": + err = unpopulate(val, "CircuitID", &n.CircuitID) + delete(rawMsg, key) + case "networkInterfaces": + err = unpopulate(val, "NetworkInterfaces", &n.NetworkInterfaces) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Operation. +func (o Operation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionType", o.ActionType) + populate(objectMap, "display", o.Display) + populate(objectMap, "isDataAction", o.IsDataAction) + populate(objectMap, "name", o.Name) + populate(objectMap, "origin", o.Origin) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Operation. +func (o *Operation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionType": + err = unpopulate(val, "ActionType", &o.ActionType) + delete(rawMsg, key) + case "display": + err = unpopulate(val, "Display", &o.Display) + delete(rawMsg, key) + case "isDataAction": + err = unpopulate(val, "IsDataAction", &o.IsDataAction) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "origin": + err = unpopulate(val, "Origin", &o.Origin) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationDisplay. +func (o OperationDisplay) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", o.Description) + populate(objectMap, "operation", o.Operation) + populate(objectMap, "provider", o.Provider) + populate(objectMap, "resource", o.Resource) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationDisplay. +func (o *OperationDisplay) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &o.Description) + delete(rawMsg, key) + case "operation": + err = unpopulate(val, "Operation", &o.Operation) + delete(rawMsg, key) + case "provider": + err = unpopulate(val, "Provider", &o.Provider) + delete(rawMsg, key) + case "resource": + err = unpopulate(val, "Resource", &o.Resource) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationListResult. +func (o *OperationListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &o.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationStatusResult. +func (o OperationStatusResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "endTime", o.EndTime) + populate(objectMap, "error", o.Error) + populate(objectMap, "id", o.ID) + populate(objectMap, "name", o.Name) + populate(objectMap, "operations", o.Operations) + populate(objectMap, "percentComplete", o.PercentComplete) + populate(objectMap, "resourceId", o.ResourceID) + populateTime[datetime.RFC3339](objectMap, "startTime", o.StartTime) + populate(objectMap, "status", o.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationStatusResult. +func (o *OperationStatusResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "endTime": + err = unpopulateTime[datetime.RFC3339](val, "EndTime", &o.EndTime) + delete(rawMsg, key) + case "error": + err = unpopulate(val, "Error", &o.Error) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &o.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "operations": + err = unpopulate(val, "Operations", &o.Operations) + delete(rawMsg, key) + case "percentComplete": + err = unpopulate(val, "PercentComplete", &o.PercentComplete) + delete(rawMsg, key) + case "resourceId": + err = unpopulate(val, "ResourceID", &o.ResourceID) + delete(rawMsg, key) + case "startTime": + err = unpopulateTime[datetime.RFC3339](val, "StartTime", &o.StartTime) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &o.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OsProfile. +func (o OsProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "computerName", o.ComputerName) + populate(objectMap, "osType", o.OSType) + populate(objectMap, "sshPublicKey", o.SSHPublicKey) + populate(objectMap, "version", o.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OsProfile. +func (o *OsProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "computerName": + err = unpopulate(val, "ComputerName", &o.ComputerName) + delete(rawMsg, key) + case "osType": + err = unpopulate(val, "OSType", &o.OSType) + delete(rawMsg, key) + case "sshPublicKey": + err = unpopulate(val, "SSHPublicKey", &o.SSHPublicKey) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &o.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Properties. +func (p Properties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "azureLargeInstanceId", p.AzureLargeInstanceID) + populate(objectMap, "hardwareProfile", p.HardwareProfile) + populate(objectMap, "hwRevision", p.HwRevision) + populate(objectMap, "networkProfile", p.NetworkProfile) + populate(objectMap, "osProfile", p.OSProfile) + populate(objectMap, "powerState", p.PowerState) + populate(objectMap, "provisioningState", p.ProvisioningState) + populate(objectMap, "proximityPlacementGroup", p.ProximityPlacementGroup) + populate(objectMap, "storageProfile", p.StorageProfile) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Properties. +func (p *Properties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "azureLargeInstanceId": + err = unpopulate(val, "AzureLargeInstanceID", &p.AzureLargeInstanceID) + delete(rawMsg, key) + case "hardwareProfile": + err = unpopulate(val, "HardwareProfile", &p.HardwareProfile) + delete(rawMsg, key) + case "hwRevision": + err = unpopulate(val, "HwRevision", &p.HwRevision) + delete(rawMsg, key) + case "networkProfile": + err = unpopulate(val, "NetworkProfile", &p.NetworkProfile) + delete(rawMsg, key) + case "osProfile": + err = unpopulate(val, "OSProfile", &p.OSProfile) + delete(rawMsg, key) + case "powerState": + err = unpopulate(val, "PowerState", &p.PowerState) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + case "proximityPlacementGroup": + err = unpopulate(val, "ProximityPlacementGroup", &p.ProximityPlacementGroup) + delete(rawMsg, key) + case "storageProfile": + err = unpopulate(val, "StorageProfile", &p.StorageProfile) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type StorageBillingProperties. +func (s StorageBillingProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "billingMode", s.BillingMode) + populate(objectMap, "sku", s.SKU) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StorageBillingProperties. +func (s *StorageBillingProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "billingMode": + err = unpopulate(val, "BillingMode", &s.BillingMode) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, "SKU", &s.SKU) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type StorageProfile. +func (s StorageProfile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nfsIpAddress", s.NfsIPAddress) + populate(objectMap, "osDisks", s.OSDisks) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StorageProfile. +func (s *StorageProfile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nfsIpAddress": + err = unpopulate(val, "NfsIPAddress", &s.NfsIPAddress) + delete(rawMsg, key) + case "osDisks": + err = unpopulate(val, "OSDisks", &s.OSDisks) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type StorageProperties. +func (s StorageProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "generation", s.Generation) + populate(objectMap, "hardwareType", s.HardwareType) + populate(objectMap, "offeringType", s.OfferingType) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "storageBillingProperties", s.StorageBillingProperties) + populate(objectMap, "storageType", s.StorageType) + populate(objectMap, "workloadType", s.WorkloadType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StorageProperties. +func (s *StorageProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "generation": + err = unpopulate(val, "Generation", &s.Generation) + delete(rawMsg, key) + case "hardwareType": + err = unpopulate(val, "HardwareType", &s.HardwareType) + delete(rawMsg, key) + case "offeringType": + err = unpopulate(val, "OfferingType", &s.OfferingType) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &s.ProvisioningState) + delete(rawMsg, key) + case "storageBillingProperties": + err = unpopulate(val, "StorageBillingProperties", &s.StorageBillingProperties) + delete(rawMsg, key) + case "storageType": + err = unpopulate(val, "StorageType", &s.StorageType) + delete(rawMsg, key) + case "workloadType": + err = unpopulate(val, "WorkloadType", &s.WorkloadType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateTime[datetime.RFC3339](objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateTime[datetime.RFC3339](val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateTime[datetime.RFC3339](val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TagsUpdate. +func (t TagsUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "tags", t.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TagsUpdate. +func (t *TagsUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "tags": + err = unpopulate(val, "Tags", &t.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserAssignedIdentity. +func (u UserAssignedIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clientId", u.ClientID) + populate(objectMap, "principalId", u.PrincipalID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserAssignedIdentity. +func (u *UserAssignedIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "clientId": + err = unpopulate(val, "ClientID", &u.ClientID) + delete(rawMsg, key) + case "principalId": + err = unpopulate(val, "PrincipalID", &u.PrincipalID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func populateAny(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/local/armlargeinstance/zz_operations_client.go b/test/local/armlargeinstance/zz_operations_client.go new file mode 100644 index 000000000000..5944ad79ef4a --- /dev/null +++ b/test/local/armlargeinstance/zz_operations_client.go @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armlargeinstance + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +// +// Generated from API version 2024-08-01-preview +type OperationsClient struct { + internal *arm.Client +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*OperationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OperationsClient{ + internal: cl, + } + return client, nil +} + +// NewListPager - List the operations for the provider +// - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ + More: func(page OperationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OperationsClientListResponse) (OperationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OperationsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return OperationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, _ *OperationsClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.AzureLargeInstance/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240801Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsClientListResponse, error) { + result := OperationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armlargeinstance/zz_options.go b/test/local/armlargeinstance/zz_options.go new file mode 100644 index 000000000000..91e68062a43f --- /dev/null +++ b/test/local/armlargeinstance/zz_options.go @@ -0,0 +1,98 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armlargeinstance + +// AzureLargeStorageInstanceClientCreateOptions contains the optional parameters for the AzureLargeStorageInstanceClient.Create +// method. +type AzureLargeStorageInstanceClientCreateOptions struct { + // placeholder for future optional parameters +} + +// AzureLargeStorageInstanceClientDeleteOptions contains the optional parameters for the AzureLargeStorageInstanceClient.Delete +// method. +type AzureLargeStorageInstanceClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// AzureLargeStorageInstanceClientGetOptions contains the optional parameters for the AzureLargeStorageInstanceClient.Get +// method. +type AzureLargeStorageInstanceClientGetOptions struct { + // placeholder for future optional parameters +} + +// AzureLargeStorageInstanceClientListByResourceGroupOptions contains the optional parameters for the AzureLargeStorageInstanceClient.NewListByResourceGroupPager +// method. +type AzureLargeStorageInstanceClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// AzureLargeStorageInstanceClientListBySubscriptionOptions contains the optional parameters for the AzureLargeStorageInstanceClient.NewListBySubscriptionPager +// method. +type AzureLargeStorageInstanceClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// AzureLargeStorageInstanceClientUpdateOptions contains the optional parameters for the AzureLargeStorageInstanceClient.Update +// method. +type AzureLargeStorageInstanceClientUpdateOptions struct { + // placeholder for future optional parameters +} + +// ClientBeginRestartOptions contains the optional parameters for the Client.BeginRestart method. +type ClientBeginRestartOptions struct { + // When set to 'active', this parameter empowers the server with the ability to forcefully terminate and halt any existing + // processes that may be running on the server + ForceParameter *ForceState + + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ClientBeginShutdownOptions contains the optional parameters for the Client.BeginShutdown method. +type ClientBeginShutdownOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ClientBeginStartOptions contains the optional parameters for the Client.BeginStart method. +type ClientBeginStartOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ClientCreateOptions contains the optional parameters for the Client.Create method. +type ClientCreateOptions struct { + // placeholder for future optional parameters +} + +// ClientDeleteOptions contains the optional parameters for the Client.Delete method. +type ClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// ClientGetOptions contains the optional parameters for the Client.Get method. +type ClientGetOptions struct { + // placeholder for future optional parameters +} + +// ClientListByResourceGroupOptions contains the optional parameters for the Client.NewListByResourceGroupPager method. +type ClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// ClientListBySubscriptionOptions contains the optional parameters for the Client.NewListBySubscriptionPager method. +type ClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// ClientUpdateOptions contains the optional parameters for the Client.Update method. +type ClientUpdateOptions struct { + // placeholder for future optional parameters +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} diff --git a/test/local/armlargeinstance/zz_responses.go b/test/local/armlargeinstance/zz_responses.go new file mode 100644 index 000000000000..7bed58cea312 --- /dev/null +++ b/test/local/armlargeinstance/zz_responses.go @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armlargeinstance + +// AzureLargeStorageInstanceClientCreateResponse contains the response from method AzureLargeStorageInstanceClient.Create. +type AzureLargeStorageInstanceClientCreateResponse struct { + // AzureLargeStorageInstance info on Azure (ARM properties and + // AzureLargeStorageInstance properties) + AzureLargeStorageInstance +} + +// AzureLargeStorageInstanceClientDeleteResponse contains the response from method AzureLargeStorageInstanceClient.Delete. +type AzureLargeStorageInstanceClientDeleteResponse struct { + // placeholder for future response values +} + +// AzureLargeStorageInstanceClientGetResponse contains the response from method AzureLargeStorageInstanceClient.Get. +type AzureLargeStorageInstanceClientGetResponse struct { + // AzureLargeStorageInstance info on Azure (ARM properties and + // AzureLargeStorageInstance properties) + AzureLargeStorageInstance +} + +// AzureLargeStorageInstanceClientListByResourceGroupResponse contains the response from method AzureLargeStorageInstanceClient.NewListByResourceGroupPager. +type AzureLargeStorageInstanceClientListByResourceGroupResponse struct { + // The response of a AzureLargeStorageInstance list operation. + AzureLargeStorageInstanceListResult +} + +// AzureLargeStorageInstanceClientListBySubscriptionResponse contains the response from method AzureLargeStorageInstanceClient.NewListBySubscriptionPager. +type AzureLargeStorageInstanceClientListBySubscriptionResponse struct { + // The response of a AzureLargeStorageInstance list operation. + AzureLargeStorageInstanceListResult +} + +// AzureLargeStorageInstanceClientUpdateResponse contains the response from method AzureLargeStorageInstanceClient.Update. +type AzureLargeStorageInstanceClientUpdateResponse struct { + // AzureLargeStorageInstance info on Azure (ARM properties and + // AzureLargeStorageInstance properties) + AzureLargeStorageInstance +} + +// ClientCreateResponse contains the response from method Client.Create. +type ClientCreateResponse struct { + // Azure Large Instance info on Azure (ARM properties and AzureLargeInstance + // properties) + AzureLargeInstance +} + +// ClientDeleteResponse contains the response from method Client.Delete. +type ClientDeleteResponse struct { + // placeholder for future response values +} + +// ClientGetResponse contains the response from method Client.Get. +type ClientGetResponse struct { + // Azure Large Instance info on Azure (ARM properties and AzureLargeInstance + // properties) + AzureLargeInstance +} + +// ClientListByResourceGroupResponse contains the response from method Client.NewListByResourceGroupPager. +type ClientListByResourceGroupResponse struct { + // The response of a AzureLargeInstance list operation. + ListResult +} + +// ClientListBySubscriptionResponse contains the response from method Client.NewListBySubscriptionPager. +type ClientListBySubscriptionResponse struct { + // The response of a AzureLargeInstance list operation. + ListResult +} + +// ClientRestartResponse contains the response from method Client.BeginRestart. +type ClientRestartResponse struct { + // placeholder for future response values +} + +// ClientShutdownResponse contains the response from method Client.BeginShutdown. +type ClientShutdownResponse struct { + // The current status of an async operation. + OperationStatusResult +} + +// ClientStartResponse contains the response from method Client.BeginStart. +type ClientStartResponse struct { + // The current status of an async operation. + OperationStatusResult +} + +// ClientUpdateResponse contains the response from method Client.Update. +type ClientUpdateResponse struct { + // Azure Large Instance info on Azure (ARM properties and AzureLargeInstance + // properties) + AzureLargeInstance +} + +// OperationsClientListResponse contains the response from method OperationsClient.NewListPager. +type OperationsClientListResponse struct { + // A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. + OperationListResult +} diff --git a/test/local/armlargeinstance/zz_version.go b/test/local/armlargeinstance/zz_version.go new file mode 100644 index 000000000000..c644cdd70767 --- /dev/null +++ b/test/local/armlargeinstance/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package armlargeinstance + +const ( + moduleName = "armlargeinstance" + moduleVersion = "v0.1.0" +) diff --git a/test/local/armloadtestservice/LICENSE.txt b/test/local/armloadtestservice/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/local/armloadtestservice/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/local/armloadtestservice/fake/zz_internal.go b/test/local/armloadtestservice/fake/zz_internal.go new file mode 100644 index 000000000000..590b4d743e97 --- /dev/null +++ b/test/local/armloadtestservice/fake/zz_internal.go @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/local/armloadtestservice/fake/zz_loadtestmappings_server.go b/test/local/armloadtestservice/fake/zz_loadtestmappings_server.go new file mode 100644 index 000000000000..deba5ebf1a76 --- /dev/null +++ b/test/local/armloadtestservice/fake/zz_loadtestmappings_server.go @@ -0,0 +1,290 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armloadtestservice" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// LoadTestMappingsServer is a fake server for instances of the armloadtestservice.LoadTestMappingsClient type. +type LoadTestMappingsServer struct { + // CreateOrUpdate is the fake for method LoadTestMappingsClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceURI string, loadTestMappingName string, resource armloadtestservice.LoadTestMappingResource, options *armloadtestservice.LoadTestMappingsClientCreateOrUpdateOptions) (resp azfake.Responder[armloadtestservice.LoadTestMappingsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method LoadTestMappingsClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceURI string, loadTestMappingName string, options *armloadtestservice.LoadTestMappingsClientDeleteOptions) (resp azfake.Responder[armloadtestservice.LoadTestMappingsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method LoadTestMappingsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceURI string, loadTestMappingName string, options *armloadtestservice.LoadTestMappingsClientGetOptions) (resp azfake.Responder[armloadtestservice.LoadTestMappingsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method LoadTestMappingsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceURI string, options *armloadtestservice.LoadTestMappingsClientListOptions) (resp azfake.PagerResponder[armloadtestservice.LoadTestMappingsClientListResponse]) + + // Update is the fake for method LoadTestMappingsClient.Update + // HTTP status codes to indicate success: http.StatusOK + Update func(ctx context.Context, resourceURI string, loadTestMappingName string, properties armloadtestservice.LoadTestMappingResourceUpdate, options *armloadtestservice.LoadTestMappingsClientUpdateOptions) (resp azfake.Responder[armloadtestservice.LoadTestMappingsClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewLoadTestMappingsServerTransport creates a new instance of LoadTestMappingsServerTransport with the provided implementation. +// The returned LoadTestMappingsServerTransport instance is connected to an instance of armloadtestservice.LoadTestMappingsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewLoadTestMappingsServerTransport(srv *LoadTestMappingsServer) *LoadTestMappingsServerTransport { + return &LoadTestMappingsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armloadtestservice.LoadTestMappingsClientListResponse]](), + } +} + +// LoadTestMappingsServerTransport connects instances of armloadtestservice.LoadTestMappingsClient to instances of LoadTestMappingsServer. +// Don't use this type directly, use NewLoadTestMappingsServerTransport instead. +type LoadTestMappingsServerTransport struct { + srv *LoadTestMappingsServer + newListPager *tracker[azfake.PagerResponder[armloadtestservice.LoadTestMappingsClientListResponse]] +} + +// Do implements the policy.Transporter interface for LoadTestMappingsServerTransport. +func (l *LoadTestMappingsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return l.dispatchToMethodFake(req, method) +} + +func (l *LoadTestMappingsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if loadTestMappingsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = loadTestMappingsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "LoadTestMappingsClient.CreateOrUpdate": + res.resp, res.err = l.dispatchCreateOrUpdate(req) + case "LoadTestMappingsClient.Delete": + res.resp, res.err = l.dispatchDelete(req) + case "LoadTestMappingsClient.Get": + res.resp, res.err = l.dispatchGet(req) + case "LoadTestMappingsClient.NewListPager": + res.resp, res.err = l.dispatchNewListPager(req) + case "LoadTestMappingsClient.Update": + res.resp, res.err = l.dispatchUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (l *LoadTestMappingsServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if l.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.LoadTestService/loadTestMappings/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armloadtestservice.LoadTestMappingResource](req) + if err != nil { + return nil, err + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + loadTestMappingNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("loadTestMappingName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.CreateOrUpdate(req.Context(), resourceURIParam, loadTestMappingNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).LoadTestMappingResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (l *LoadTestMappingsServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if l.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.LoadTestService/loadTestMappings/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + loadTestMappingNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("loadTestMappingName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.Delete(req.Context(), resourceURIParam, loadTestMappingNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (l *LoadTestMappingsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if l.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.LoadTestService/loadTestMappings/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + loadTestMappingNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("loadTestMappingName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.Get(req.Context(), resourceURIParam, loadTestMappingNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).LoadTestMappingResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (l *LoadTestMappingsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if l.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := l.newListPager.get(req) + if newListPager == nil { + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.LoadTestService/loadTestMappings` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + resp := l.srv.NewListPager(resourceURIParam, nil) + newListPager = &resp + l.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armloadtestservice.LoadTestMappingsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + l.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + l.newListPager.remove(req) + } + return resp, nil +} + +func (l *LoadTestMappingsServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) { + if l.srv.Update == nil { + return nil, &nonRetriableError{errors.New("fake for method Update not implemented")} + } + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.LoadTestService/loadTestMappings/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armloadtestservice.LoadTestMappingResourceUpdate](req) + if err != nil { + return nil, err + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + loadTestMappingNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("loadTestMappingName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.Update(req.Context(), resourceURIParam, loadTestMappingNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).LoadTestMappingResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to LoadTestMappingsServerTransport +var loadTestMappingsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armloadtestservice/fake/zz_loadtestprofilemappings_server.go b/test/local/armloadtestservice/fake/zz_loadtestprofilemappings_server.go new file mode 100644 index 000000000000..c262338a6259 --- /dev/null +++ b/test/local/armloadtestservice/fake/zz_loadtestprofilemappings_server.go @@ -0,0 +1,290 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armloadtestservice" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// LoadTestProfileMappingsServer is a fake server for instances of the armloadtestservice.LoadTestProfileMappingsClient type. +type LoadTestProfileMappingsServer struct { + // CreateOrUpdate is the fake for method LoadTestProfileMappingsClient.CreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + CreateOrUpdate func(ctx context.Context, resourceURI string, loadTestProfileMappingName string, resource armloadtestservice.LoadTestProfileMappingResource, options *armloadtestservice.LoadTestProfileMappingsClientCreateOrUpdateOptions) (resp azfake.Responder[armloadtestservice.LoadTestProfileMappingsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // Delete is the fake for method LoadTestProfileMappingsClient.Delete + // HTTP status codes to indicate success: http.StatusOK, http.StatusNoContent + Delete func(ctx context.Context, resourceURI string, loadTestProfileMappingName string, options *armloadtestservice.LoadTestProfileMappingsClientDeleteOptions) (resp azfake.Responder[armloadtestservice.LoadTestProfileMappingsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method LoadTestProfileMappingsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceURI string, loadTestProfileMappingName string, options *armloadtestservice.LoadTestProfileMappingsClientGetOptions) (resp azfake.Responder[armloadtestservice.LoadTestProfileMappingsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method LoadTestProfileMappingsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(resourceURI string, options *armloadtestservice.LoadTestProfileMappingsClientListOptions) (resp azfake.PagerResponder[armloadtestservice.LoadTestProfileMappingsClientListResponse]) + + // Update is the fake for method LoadTestProfileMappingsClient.Update + // HTTP status codes to indicate success: http.StatusOK + Update func(ctx context.Context, resourceURI string, loadTestProfileMappingName string, properties armloadtestservice.LoadTestProfileMappingResourceUpdate, options *armloadtestservice.LoadTestProfileMappingsClientUpdateOptions) (resp azfake.Responder[armloadtestservice.LoadTestProfileMappingsClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewLoadTestProfileMappingsServerTransport creates a new instance of LoadTestProfileMappingsServerTransport with the provided implementation. +// The returned LoadTestProfileMappingsServerTransport instance is connected to an instance of armloadtestservice.LoadTestProfileMappingsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewLoadTestProfileMappingsServerTransport(srv *LoadTestProfileMappingsServer) *LoadTestProfileMappingsServerTransport { + return &LoadTestProfileMappingsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armloadtestservice.LoadTestProfileMappingsClientListResponse]](), + } +} + +// LoadTestProfileMappingsServerTransport connects instances of armloadtestservice.LoadTestProfileMappingsClient to instances of LoadTestProfileMappingsServer. +// Don't use this type directly, use NewLoadTestProfileMappingsServerTransport instead. +type LoadTestProfileMappingsServerTransport struct { + srv *LoadTestProfileMappingsServer + newListPager *tracker[azfake.PagerResponder[armloadtestservice.LoadTestProfileMappingsClientListResponse]] +} + +// Do implements the policy.Transporter interface for LoadTestProfileMappingsServerTransport. +func (l *LoadTestProfileMappingsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return l.dispatchToMethodFake(req, method) +} + +func (l *LoadTestProfileMappingsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if loadTestProfileMappingsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = loadTestProfileMappingsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "LoadTestProfileMappingsClient.CreateOrUpdate": + res.resp, res.err = l.dispatchCreateOrUpdate(req) + case "LoadTestProfileMappingsClient.Delete": + res.resp, res.err = l.dispatchDelete(req) + case "LoadTestProfileMappingsClient.Get": + res.resp, res.err = l.dispatchGet(req) + case "LoadTestProfileMappingsClient.NewListPager": + res.resp, res.err = l.dispatchNewListPager(req) + case "LoadTestProfileMappingsClient.Update": + res.resp, res.err = l.dispatchUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (l *LoadTestProfileMappingsServerTransport) dispatchCreateOrUpdate(req *http.Request) (*http.Response, error) { + if l.srv.CreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateOrUpdate not implemented")} + } + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.LoadTestService/loadTestProfileMappings/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armloadtestservice.LoadTestProfileMappingResource](req) + if err != nil { + return nil, err + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + loadTestProfileMappingNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("loadTestProfileMappingName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.CreateOrUpdate(req.Context(), resourceURIParam, loadTestProfileMappingNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).LoadTestProfileMappingResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (l *LoadTestProfileMappingsServerTransport) dispatchDelete(req *http.Request) (*http.Response, error) { + if l.srv.Delete == nil { + return nil, &nonRetriableError{errors.New("fake for method Delete not implemented")} + } + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.LoadTestService/loadTestProfileMappings/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + loadTestProfileMappingNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("loadTestProfileMappingName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.Delete(req.Context(), resourceURIParam, loadTestProfileMappingNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (l *LoadTestProfileMappingsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if l.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.LoadTestService/loadTestProfileMappings/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + loadTestProfileMappingNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("loadTestProfileMappingName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.Get(req.Context(), resourceURIParam, loadTestProfileMappingNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).LoadTestProfileMappingResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (l *LoadTestProfileMappingsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if l.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := l.newListPager.get(req) + if newListPager == nil { + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.LoadTestService/loadTestProfileMappings` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + resp := l.srv.NewListPager(resourceURIParam, nil) + newListPager = &resp + l.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armloadtestservice.LoadTestProfileMappingsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + l.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + l.newListPager.remove(req) + } + return resp, nil +} + +func (l *LoadTestProfileMappingsServerTransport) dispatchUpdate(req *http.Request) (*http.Response, error) { + if l.srv.Update == nil { + return nil, &nonRetriableError{errors.New("fake for method Update not implemented")} + } + const regexStr = `/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.LoadTestService/loadTestProfileMappings/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armloadtestservice.LoadTestProfileMappingResourceUpdate](req) + if err != nil { + return nil, err + } + resourceURIParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceUri")]) + if err != nil { + return nil, err + } + loadTestProfileMappingNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("loadTestProfileMappingName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.Update(req.Context(), resourceURIParam, loadTestProfileMappingNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).LoadTestProfileMappingResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to LoadTestProfileMappingsServerTransport +var loadTestProfileMappingsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armloadtestservice/fake/zz_loadtests_server.go b/test/local/armloadtestservice/fake/zz_loadtests_server.go new file mode 100644 index 000000000000..ee62e5c0ed96 --- /dev/null +++ b/test/local/armloadtestservice/fake/zz_loadtests_server.go @@ -0,0 +1,419 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armloadtestservice" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// LoadTestsServer is a fake server for instances of the armloadtestservice.LoadTestsClient type. +type LoadTestsServer struct { + // BeginCreateOrUpdate is the fake for method LoadTestsClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, loadTestName string, resource armloadtestservice.LoadTestResource, options *armloadtestservice.LoadTestsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armloadtestservice.LoadTestsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method LoadTestsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, loadTestName string, options *armloadtestservice.LoadTestsClientBeginDeleteOptions) (resp azfake.PollerResponder[armloadtestservice.LoadTestsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method LoadTestsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, loadTestName string, options *armloadtestservice.LoadTestsClientGetOptions) (resp azfake.Responder[armloadtestservice.LoadTestsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method LoadTestsClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armloadtestservice.LoadTestsClientListByResourceGroupOptions) (resp azfake.PagerResponder[armloadtestservice.LoadTestsClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method LoadTestsClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armloadtestservice.LoadTestsClientListBySubscriptionOptions) (resp azfake.PagerResponder[armloadtestservice.LoadTestsClientListBySubscriptionResponse]) + + // NewOutboundNetworkDependenciesEndpointsPager is the fake for method LoadTestsClient.NewOutboundNetworkDependenciesEndpointsPager + // HTTP status codes to indicate success: http.StatusOK + NewOutboundNetworkDependenciesEndpointsPager func(resourceGroupName string, loadTestName string, options *armloadtestservice.LoadTestsClientOutboundNetworkDependenciesEndpointsOptions) (resp azfake.PagerResponder[armloadtestservice.LoadTestsClientOutboundNetworkDependenciesEndpointsResponse]) + + // BeginUpdate is the fake for method LoadTestsClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, loadTestName string, properties armloadtestservice.LoadTestResourceUpdate, options *armloadtestservice.LoadTestsClientBeginUpdateOptions) (resp azfake.PollerResponder[armloadtestservice.LoadTestsClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewLoadTestsServerTransport creates a new instance of LoadTestsServerTransport with the provided implementation. +// The returned LoadTestsServerTransport instance is connected to an instance of armloadtestservice.LoadTestsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewLoadTestsServerTransport(srv *LoadTestsServer) *LoadTestsServerTransport { + return &LoadTestsServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armloadtestservice.LoadTestsClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armloadtestservice.LoadTestsClientDeleteResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armloadtestservice.LoadTestsClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armloadtestservice.LoadTestsClientListBySubscriptionResponse]](), + newOutboundNetworkDependenciesEndpointsPager: newTracker[azfake.PagerResponder[armloadtestservice.LoadTestsClientOutboundNetworkDependenciesEndpointsResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armloadtestservice.LoadTestsClientUpdateResponse]](), + } +} + +// LoadTestsServerTransport connects instances of armloadtestservice.LoadTestsClient to instances of LoadTestsServer. +// Don't use this type directly, use NewLoadTestsServerTransport instead. +type LoadTestsServerTransport struct { + srv *LoadTestsServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armloadtestservice.LoadTestsClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armloadtestservice.LoadTestsClientDeleteResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armloadtestservice.LoadTestsClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armloadtestservice.LoadTestsClientListBySubscriptionResponse]] + newOutboundNetworkDependenciesEndpointsPager *tracker[azfake.PagerResponder[armloadtestservice.LoadTestsClientOutboundNetworkDependenciesEndpointsResponse]] + beginUpdate *tracker[azfake.PollerResponder[armloadtestservice.LoadTestsClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for LoadTestsServerTransport. +func (l *LoadTestsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return l.dispatchToMethodFake(req, method) +} + +func (l *LoadTestsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if loadTestsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = loadTestsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "LoadTestsClient.BeginCreateOrUpdate": + res.resp, res.err = l.dispatchBeginCreateOrUpdate(req) + case "LoadTestsClient.BeginDelete": + res.resp, res.err = l.dispatchBeginDelete(req) + case "LoadTestsClient.Get": + res.resp, res.err = l.dispatchGet(req) + case "LoadTestsClient.NewListByResourceGroupPager": + res.resp, res.err = l.dispatchNewListByResourceGroupPager(req) + case "LoadTestsClient.NewListBySubscriptionPager": + res.resp, res.err = l.dispatchNewListBySubscriptionPager(req) + case "LoadTestsClient.NewOutboundNetworkDependenciesEndpointsPager": + res.resp, res.err = l.dispatchNewOutboundNetworkDependenciesEndpointsPager(req) + case "LoadTestsClient.BeginUpdate": + res.resp, res.err = l.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (l *LoadTestsServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if l.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := l.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.LoadTestService/loadTests/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armloadtestservice.LoadTestResource](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + loadTestNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("loadTestName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, loadTestNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + l.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + l.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + l.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (l *LoadTestsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if l.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := l.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.LoadTestService/loadTests/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + loadTestNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("loadTestName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.BeginDelete(req.Context(), resourceGroupNameParam, loadTestNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + l.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + l.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + l.beginDelete.remove(req) + } + + return resp, nil +} + +func (l *LoadTestsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if l.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.LoadTestService/loadTests/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + loadTestNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("loadTestName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.Get(req.Context(), resourceGroupNameParam, loadTestNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).LoadTestResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (l *LoadTestsServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if l.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := l.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.LoadTestService/loadTests` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := l.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + l.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armloadtestservice.LoadTestsClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + l.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + l.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (l *LoadTestsServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if l.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := l.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.LoadTestService/loadTests` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := l.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + l.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armloadtestservice.LoadTestsClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + l.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + l.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (l *LoadTestsServerTransport) dispatchNewOutboundNetworkDependenciesEndpointsPager(req *http.Request) (*http.Response, error) { + if l.srv.NewOutboundNetworkDependenciesEndpointsPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewOutboundNetworkDependenciesEndpointsPager not implemented")} + } + newOutboundNetworkDependenciesEndpointsPager := l.newOutboundNetworkDependenciesEndpointsPager.get(req) + if newOutboundNetworkDependenciesEndpointsPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.LoadTestService/loadTests/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/outboundNetworkDependenciesEndpoints` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + loadTestNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("loadTestName")]) + if err != nil { + return nil, err + } + resp := l.srv.NewOutboundNetworkDependenciesEndpointsPager(resourceGroupNameParam, loadTestNameParam, nil) + newOutboundNetworkDependenciesEndpointsPager = &resp + l.newOutboundNetworkDependenciesEndpointsPager.add(req, newOutboundNetworkDependenciesEndpointsPager) + server.PagerResponderInjectNextLinks(newOutboundNetworkDependenciesEndpointsPager, req, func(page *armloadtestservice.LoadTestsClientOutboundNetworkDependenciesEndpointsResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newOutboundNetworkDependenciesEndpointsPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + l.newOutboundNetworkDependenciesEndpointsPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newOutboundNetworkDependenciesEndpointsPager) { + l.newOutboundNetworkDependenciesEndpointsPager.remove(req) + } + return resp, nil +} + +func (l *LoadTestsServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if l.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := l.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.LoadTestService/loadTests/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armloadtestservice.LoadTestResourceUpdate](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + loadTestNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("loadTestName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.BeginUpdate(req.Context(), resourceGroupNameParam, loadTestNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + l.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + l.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + l.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to LoadTestsServerTransport +var loadTestsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armloadtestservice/fake/zz_loadtestsmaxmonthlyvirtualuserhourslimitsresource_server.go b/test/local/armloadtestservice/fake/zz_loadtestsmaxmonthlyvirtualuserhourslimitsresource_server.go new file mode 100644 index 000000000000..5516d8f935e0 --- /dev/null +++ b/test/local/armloadtestservice/fake/zz_loadtestsmaxmonthlyvirtualuserhourslimitsresource_server.go @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armloadtestservice" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServer is a fake server for instances of the armloadtestservice.LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient type. +type LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServer struct { + // Get is the fake for method LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, loadTestName string, options *armloadtestservice.LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientGetOptions) (resp azfake.Responder[armloadtestservice.LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientGetResponse], errResp azfake.ErrorResponder) + + // Set is the fake for method LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient.Set + // HTTP status codes to indicate success: http.StatusOK + Set func(ctx context.Context, resourceGroupName string, loadTestName string, body armloadtestservice.MaxMonthlyVirtualUserHoursLimitRequest, options *armloadtestservice.LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientSetOptions) (resp azfake.Responder[armloadtestservice.LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientSetResponse], errResp azfake.ErrorResponder) +} + +// NewLoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServerTransport creates a new instance of LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServerTransport with the provided implementation. +// The returned LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServerTransport instance is connected to an instance of armloadtestservice.LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewLoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServerTransport(srv *LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServer) *LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServerTransport { + return &LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServerTransport{srv: srv} +} + +// LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServerTransport connects instances of armloadtestservice.LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient to instances of LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServer. +// Don't use this type directly, use NewLoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServerTransport instead. +type LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServerTransport struct { + srv *LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServer +} + +// Do implements the policy.Transporter interface for LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServerTransport. +func (l *LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return l.dispatchToMethodFake(req, method) +} + +func (l *LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if loadTestsMaxMonthlyVirtualUserHoursLimitsResourceServerTransportInterceptor != nil { + res.resp, res.err, intercepted = loadTestsMaxMonthlyVirtualUserHoursLimitsResourceServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient.Get": + res.resp, res.err = l.dispatchGet(req) + case "LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient.Set": + res.resp, res.err = l.dispatchSet(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (l *LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if l.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.LoadTestService/loadTests/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/limits/maxMonthlyVirtualUserHours` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + loadTestNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("loadTestName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.Get(req.Context(), resourceGroupNameParam, loadTestNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).MaxMonthlyVirtualUserHoursResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (l *LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServerTransport) dispatchSet(req *http.Request) (*http.Response, error) { + if l.srv.Set == nil { + return nil, &nonRetriableError{errors.New("fake for method Set not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.LoadTestService/loadTests/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/limits/maxMonthlyVirtualUserHours/set` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armloadtestservice.MaxMonthlyVirtualUserHoursLimitRequest](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + loadTestNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("loadTestName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.Set(req.Context(), resourceGroupNameParam, loadTestNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).MaxMonthlyVirtualUserHoursResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServerTransport +var loadTestsMaxMonthlyVirtualUserHoursLimitsResourceServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armloadtestservice/fake/zz_operations_server.go b/test/local/armloadtestservice/fake/zz_operations_server.go new file mode 100644 index 000000000000..d875f2d9a9d5 --- /dev/null +++ b/test/local/armloadtestservice/fake/zz_operations_server.go @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armloadtestservice" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "slices" +) + +// OperationsServer is a fake server for instances of the armloadtestservice.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armloadtestservice.OperationsClientListOptions) (resp azfake.PagerResponder[armloadtestservice.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of armloadtestservice.OperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOperationsServerTransport(srv *OperationsServer) *OperationsServerTransport { + return &OperationsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armloadtestservice.OperationsClientListResponse]](), + } +} + +// OperationsServerTransport connects instances of armloadtestservice.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[armloadtestservice.OperationsClientListResponse]] +} + +// Do implements the policy.Transporter interface for OperationsServerTransport. +func (o *OperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if operationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = operationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OperationsClient.NewListPager": + res.resp, res.err = o.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OperationsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := o.newListPager.get(req) + if newListPager == nil { + resp := o.srv.NewListPager(nil) + newListPager = &resp + o.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armloadtestservice.OperationsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + o.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + o.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OperationsServerTransport +var operationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armloadtestservice/fake/zz_quotas_server.go b/test/local/armloadtestservice/fake/zz_quotas_server.go new file mode 100644 index 000000000000..e4921618e6ab --- /dev/null +++ b/test/local/armloadtestservice/fake/zz_quotas_server.go @@ -0,0 +1,208 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armloadtestservice" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// QuotasServer is a fake server for instances of the armloadtestservice.QuotasClient type. +type QuotasServer struct { + // CheckAvailability is the fake for method QuotasClient.CheckAvailability + // HTTP status codes to indicate success: http.StatusOK + CheckAvailability func(ctx context.Context, location string, quotaBucketName string, quotaBucketRequest armloadtestservice.QuotaBucketRequest, options *armloadtestservice.QuotasClientCheckAvailabilityOptions) (resp azfake.Responder[armloadtestservice.QuotasClientCheckAvailabilityResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method QuotasClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, location string, quotaBucketName string, options *armloadtestservice.QuotasClientGetOptions) (resp azfake.Responder[armloadtestservice.QuotasClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method QuotasClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(location string, options *armloadtestservice.QuotasClientListOptions) (resp azfake.PagerResponder[armloadtestservice.QuotasClientListResponse]) +} + +// NewQuotasServerTransport creates a new instance of QuotasServerTransport with the provided implementation. +// The returned QuotasServerTransport instance is connected to an instance of armloadtestservice.QuotasClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewQuotasServerTransport(srv *QuotasServer) *QuotasServerTransport { + return &QuotasServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armloadtestservice.QuotasClientListResponse]](), + } +} + +// QuotasServerTransport connects instances of armloadtestservice.QuotasClient to instances of QuotasServer. +// Don't use this type directly, use NewQuotasServerTransport instead. +type QuotasServerTransport struct { + srv *QuotasServer + newListPager *tracker[azfake.PagerResponder[armloadtestservice.QuotasClientListResponse]] +} + +// Do implements the policy.Transporter interface for QuotasServerTransport. +func (q *QuotasServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return q.dispatchToMethodFake(req, method) +} + +func (q *QuotasServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if quotasServerTransportInterceptor != nil { + res.resp, res.err, intercepted = quotasServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "QuotasClient.CheckAvailability": + res.resp, res.err = q.dispatchCheckAvailability(req) + case "QuotasClient.Get": + res.resp, res.err = q.dispatchGet(req) + case "QuotasClient.NewListPager": + res.resp, res.err = q.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (q *QuotasServerTransport) dispatchCheckAvailability(req *http.Request) (*http.Response, error) { + if q.srv.CheckAvailability == nil { + return nil, &nonRetriableError{errors.New("fake for method CheckAvailability not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.LoadTestService/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/quotas/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/checkAvailability` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armloadtestservice.QuotaBucketRequest](req) + if err != nil { + return nil, err + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + quotaBucketNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("quotaBucketName")]) + if err != nil { + return nil, err + } + respr, errRespr := q.srv.CheckAvailability(req.Context(), locationParam, quotaBucketNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CheckQuotaAvailabilityResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (q *QuotasServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if q.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.LoadTestService/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/quotas/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + quotaBucketNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("quotaBucketName")]) + if err != nil { + return nil, err + } + respr, errRespr := q.srv.Get(req.Context(), locationParam, quotaBucketNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).QuotaResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (q *QuotasServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if q.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := q.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.LoadTestService/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/quotas` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + resp := q.srv.NewListPager(locationParam, nil) + newListPager = &resp + q.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armloadtestservice.QuotasClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + q.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + q.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to QuotasServerTransport +var quotasServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armloadtestservice/fake/zz_server_factory.go b/test/local/armloadtestservice/fake/zz_server_factory.go new file mode 100644 index 000000000000..8804f0af68d4 --- /dev/null +++ b/test/local/armloadtestservice/fake/zz_server_factory.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armloadtestservice.ClientFactory type. +type ServerFactory struct { + // LoadTestMappingsServer contains the fakes for client LoadTestMappingsClient + LoadTestMappingsServer LoadTestMappingsServer + + // LoadTestProfileMappingsServer contains the fakes for client LoadTestProfileMappingsClient + LoadTestProfileMappingsServer LoadTestProfileMappingsServer + + // LoadTestsServer contains the fakes for client LoadTestsClient + LoadTestsServer LoadTestsServer + + // LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServer contains the fakes for client LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient + LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServer LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServer + + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer + + // QuotasServer contains the fakes for client QuotasClient + QuotasServer QuotasServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armloadtestservice.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of armloadtestservice.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trLoadTestMappingsServer *LoadTestMappingsServerTransport + trLoadTestProfileMappingsServer *LoadTestProfileMappingsServerTransport + trLoadTestsServer *LoadTestsServerTransport + trLoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServer *LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServerTransport + trOperationsServer *OperationsServerTransport + trQuotasServer *QuotasServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "LoadTestMappingsClient": + initServer(&s.trMu, &s.trLoadTestMappingsServer, func() *LoadTestMappingsServerTransport { + return NewLoadTestMappingsServerTransport(&s.srv.LoadTestMappingsServer) + }) + resp, err = s.trLoadTestMappingsServer.Do(req) + case "LoadTestProfileMappingsClient": + initServer(&s.trMu, &s.trLoadTestProfileMappingsServer, func() *LoadTestProfileMappingsServerTransport { + return NewLoadTestProfileMappingsServerTransport(&s.srv.LoadTestProfileMappingsServer) + }) + resp, err = s.trLoadTestProfileMappingsServer.Do(req) + case "LoadTestsClient": + initServer(&s.trMu, &s.trLoadTestsServer, func() *LoadTestsServerTransport { return NewLoadTestsServerTransport(&s.srv.LoadTestsServer) }) + resp, err = s.trLoadTestsServer.Do(req) + case "LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient": + initServer(&s.trMu, &s.trLoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServer, func() *LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServerTransport { + return NewLoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServerTransport(&s.srv.LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServer) + }) + resp, err = s.trLoadTestsMaxMonthlyVirtualUserHoursLimitsResourceServer.Do(req) + case "OperationsClient": + initServer(&s.trMu, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + resp, err = s.trOperationsServer.Do(req) + case "QuotasClient": + initServer(&s.trMu, &s.trQuotasServer, func() *QuotasServerTransport { return NewQuotasServerTransport(&s.srv.QuotasServer) }) + resp, err = s.trQuotasServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} diff --git a/test/local/armloadtestservice/go.mod b/test/local/armloadtestservice/go.mod new file mode 100644 index 000000000000..68de8a2c6f4c --- /dev/null +++ b/test/local/armloadtestservice/go.mod @@ -0,0 +1,11 @@ +module armloadtestservice + +go 1.25.0 + +require github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect +) diff --git a/test/local/armloadtestservice/go.sum b/test/local/armloadtestservice/go.sum new file mode 100644 index 000000000000..3fdb64caf441 --- /dev/null +++ b/test/local/armloadtestservice/go.sum @@ -0,0 +1,16 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/local/armloadtestservice/testdata/_metadata.json b/test/local/armloadtestservice/testdata/_metadata.json new file mode 100644 index 000000000000..2608bc7da8be --- /dev/null +++ b/test/local/armloadtestservice/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Microsoft.LoadTestService": "2024-12-01-preview" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/local/armloadtestservice/zz_client_factory.go b/test/local/armloadtestservice/zz_client_factory.go new file mode 100644 index 000000000000..6482624b4ef7 --- /dev/null +++ b/test/local/armloadtestservice/zz_client_factory.go @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armloadtestservice + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + internal: internal, + }, nil +} + +// NewLoadTestMappingsClient creates a new instance of LoadTestMappingsClient. +func (c *ClientFactory) NewLoadTestMappingsClient() *LoadTestMappingsClient { + return &LoadTestMappingsClient{ + internal: c.internal, + } +} + +// NewLoadTestProfileMappingsClient creates a new instance of LoadTestProfileMappingsClient. +func (c *ClientFactory) NewLoadTestProfileMappingsClient() *LoadTestProfileMappingsClient { + return &LoadTestProfileMappingsClient{ + internal: c.internal, + } +} + +// NewLoadTestsClient creates a new instance of LoadTestsClient. +func (c *ClientFactory) NewLoadTestsClient(subscriptionID string) *LoadTestsClient { + return &LoadTestsClient{ + subscriptionID: subscriptionID, + internal: c.internal, + } +} + +// NewLoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient creates a new instance of LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient. +func (c *ClientFactory) NewLoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient(subscriptionID string) *LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient { + return &LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient{ + subscriptionID: subscriptionID, + internal: c.internal, + } +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: c.internal, + } +} + +// NewQuotasClient creates a new instance of QuotasClient. +func (c *ClientFactory) NewQuotasClient(subscriptionID string) *QuotasClient { + return &QuotasClient{ + subscriptionID: subscriptionID, + internal: c.internal, + } +} diff --git a/test/local/armloadtestservice/zz_constants.go b/test/local/armloadtestservice/zz_constants.go new file mode 100644 index 000000000000..4cc23c3ecfc7 --- /dev/null +++ b/test/local/armloadtestservice/zz_constants.go @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armloadtestservice + +const ( + version20241201Preview string = "2024-12-01-preview" +) + +// ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +type ActionType string + +const ( + // ActionTypeInternal - Actions are for internal-only APIs. + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// ManagedServiceIdentityType - Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). +type ManagedServiceIdentityType string + +const ( + // ManagedServiceIdentityTypeNone - No managed identity. + ManagedServiceIdentityTypeNone ManagedServiceIdentityType = "None" + // ManagedServiceIdentityTypeSystemAssigned - System assigned managed identity. + ManagedServiceIdentityTypeSystemAssigned ManagedServiceIdentityType = "SystemAssigned" + // ManagedServiceIdentityTypeSystemAssignedUserAssigned - System and user assigned managed identity. + ManagedServiceIdentityTypeSystemAssignedUserAssigned ManagedServiceIdentityType = "SystemAssigned,UserAssigned" + // ManagedServiceIdentityTypeUserAssigned - User assigned managed identity. + ManagedServiceIdentityTypeUserAssigned ManagedServiceIdentityType = "UserAssigned" +) + +// PossibleManagedServiceIdentityTypeValues returns the possible values for the ManagedServiceIdentityType const type. +func PossibleManagedServiceIdentityTypeValues() []ManagedServiceIdentityType { + return []ManagedServiceIdentityType{ + ManagedServiceIdentityTypeNone, + ManagedServiceIdentityTypeSystemAssigned, + ManagedServiceIdentityTypeSystemAssignedUserAssigned, + ManagedServiceIdentityTypeUserAssigned, + } +} + +// Origin - The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default +// value is "user,system" +type Origin string + +const ( + // OriginSystem - Indicates the operation is initiated by a system. + OriginSystem Origin = "system" + // OriginUser - Indicates the operation is initiated by a user. + OriginUser Origin = "user" + // OriginUserSystem - Indicates the operation is initiated by a user or system. + OriginUserSystem Origin = "user,system" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginSystem, + OriginUser, + OriginUserSystem, + } +} + +// ResourceState - Resources provisioning states. +type ResourceState string + +const ( + // ResourceStateCanceled - Resource creation was canceled. + ResourceStateCanceled ResourceState = "Canceled" + // ResourceStateDeleted - Deleted state. + ResourceStateDeleted ResourceState = "Deleted" + // ResourceStateFailed - Resource creation failed. + ResourceStateFailed ResourceState = "Failed" + // ResourceStateSucceeded - Resource has been created. + ResourceStateSucceeded ResourceState = "Succeeded" +) + +// PossibleResourceStateValues returns the possible values for the ResourceState const type. +func PossibleResourceStateValues() []ResourceState { + return []ResourceState{ + ResourceStateCanceled, + ResourceStateDeleted, + ResourceStateFailed, + ResourceStateSucceeded, + } +} + +// Type - Managed identity type to use for accessing encryption key Url. +type Type string + +const ( + // TypeSystemAssigned - System assigned identity. + TypeSystemAssigned Type = "SystemAssigned" + // TypeUserAssigned - User assigned identity. + TypeUserAssigned Type = "UserAssigned" +) + +// PossibleTypeValues returns the possible values for the Type const type. +func PossibleTypeValues() []Type { + return []Type{ + TypeSystemAssigned, + TypeUserAssigned, + } +} diff --git a/test/local/armloadtestservice/zz_loadtestmappings_client.go b/test/local/armloadtestservice/zz_loadtestmappings_client.go new file mode 100644 index 000000000000..c910b6d298b5 --- /dev/null +++ b/test/local/armloadtestservice/zz_loadtestmappings_client.go @@ -0,0 +1,325 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armloadtestservice + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// LoadTestMappingsClient contains the methods for the LoadTestMappings group. +// Don't use this type directly, use NewLoadTestMappingsClient() instead. +// +// Generated from API version 2024-12-01-preview +type LoadTestMappingsClient struct { + internal *arm.Client +} + +// NewLoadTestMappingsClient creates a new instance of LoadTestMappingsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewLoadTestMappingsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*LoadTestMappingsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &LoadTestMappingsClient{ + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Create a LoadTestMappingResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - loadTestMappingName - Load Test Mapping name +// - resource - Resource create parameters. +// - options - LoadTestMappingsClientCreateOrUpdateOptions contains the optional parameters for the LoadTestMappingsClient.CreateOrUpdate +// method. +func (client *LoadTestMappingsClient) CreateOrUpdate(ctx context.Context, resourceURI string, loadTestMappingName string, resource LoadTestMappingResource, options *LoadTestMappingsClientCreateOrUpdateOptions) (LoadTestMappingsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "LoadTestMappingsClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceURI, loadTestMappingName, resource, options) + if err != nil { + return LoadTestMappingsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LoadTestMappingsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return LoadTestMappingsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *LoadTestMappingsClient) createOrUpdateCreateRequest(ctx context.Context, resourceURI string, loadTestMappingName string, resource LoadTestMappingResource, _ *LoadTestMappingsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.LoadTestService/loadTestMappings/{loadTestMappingName}" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + if loadTestMappingName == "" { + return nil, errors.New("parameter loadTestMappingName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadTestMappingName}", url.PathEscape(loadTestMappingName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20241201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *LoadTestMappingsClient) createOrUpdateHandleResponse(resp *http.Response) (LoadTestMappingsClientCreateOrUpdateResponse, error) { + result := LoadTestMappingsClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LoadTestMappingResource); err != nil { + return LoadTestMappingsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Delete a LoadTestMappingResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - loadTestMappingName - Load Test Mapping name +// - options - LoadTestMappingsClientDeleteOptions contains the optional parameters for the LoadTestMappingsClient.Delete method. +func (client *LoadTestMappingsClient) Delete(ctx context.Context, resourceURI string, loadTestMappingName string, options *LoadTestMappingsClientDeleteOptions) (LoadTestMappingsClientDeleteResponse, error) { + var err error + const operationName = "LoadTestMappingsClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceURI, loadTestMappingName, options) + if err != nil { + return LoadTestMappingsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LoadTestMappingsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return LoadTestMappingsClientDeleteResponse{}, err + } + return LoadTestMappingsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *LoadTestMappingsClient) deleteCreateRequest(ctx context.Context, resourceURI string, loadTestMappingName string, _ *LoadTestMappingsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.LoadTestService/loadTestMappings/{loadTestMappingName}" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + if loadTestMappingName == "" { + return nil, errors.New("parameter loadTestMappingName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadTestMappingName}", url.PathEscape(loadTestMappingName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20241201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a LoadTestMappingResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - loadTestMappingName - Load Test Mapping name +// - options - LoadTestMappingsClientGetOptions contains the optional parameters for the LoadTestMappingsClient.Get method. +func (client *LoadTestMappingsClient) Get(ctx context.Context, resourceURI string, loadTestMappingName string, options *LoadTestMappingsClientGetOptions) (LoadTestMappingsClientGetResponse, error) { + var err error + const operationName = "LoadTestMappingsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceURI, loadTestMappingName, options) + if err != nil { + return LoadTestMappingsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LoadTestMappingsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return LoadTestMappingsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *LoadTestMappingsClient) getCreateRequest(ctx context.Context, resourceURI string, loadTestMappingName string, _ *LoadTestMappingsClientGetOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.LoadTestService/loadTestMappings/{loadTestMappingName}" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + if loadTestMappingName == "" { + return nil, errors.New("parameter loadTestMappingName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadTestMappingName}", url.PathEscape(loadTestMappingName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20241201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *LoadTestMappingsClient) getHandleResponse(resp *http.Response) (LoadTestMappingsClientGetResponse, error) { + result := LoadTestMappingsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LoadTestMappingResource); err != nil { + return LoadTestMappingsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List LoadTestMappingResource resources by parent +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - options - LoadTestMappingsClientListOptions contains the optional parameters for the LoadTestMappingsClient.NewListPager +// method. +func (client *LoadTestMappingsClient) NewListPager(resourceURI string, options *LoadTestMappingsClientListOptions) *runtime.Pager[LoadTestMappingsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[LoadTestMappingsClientListResponse]{ + More: func(page LoadTestMappingsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *LoadTestMappingsClientListResponse) (LoadTestMappingsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "LoadTestMappingsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceURI, options) + }, nil) + if err != nil { + return LoadTestMappingsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *LoadTestMappingsClient) listCreateRequest(ctx context.Context, resourceURI string, _ *LoadTestMappingsClientListOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.LoadTestService/loadTestMappings" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20241201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *LoadTestMappingsClient) listHandleResponse(resp *http.Response) (LoadTestMappingsClientListResponse, error) { + result := LoadTestMappingsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LoadTestMappingResourceListResult); err != nil { + return LoadTestMappingsClientListResponse{}, err + } + return result, nil +} + +// Update - Update a LoadTestMappingResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - loadTestMappingName - Load Test Mapping name +// - properties - The resource properties to be updated. +// - options - LoadTestMappingsClientUpdateOptions contains the optional parameters for the LoadTestMappingsClient.Update method. +func (client *LoadTestMappingsClient) Update(ctx context.Context, resourceURI string, loadTestMappingName string, properties LoadTestMappingResourceUpdate, options *LoadTestMappingsClientUpdateOptions) (LoadTestMappingsClientUpdateResponse, error) { + var err error + const operationName = "LoadTestMappingsClient.Update" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceURI, loadTestMappingName, properties, options) + if err != nil { + return LoadTestMappingsClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LoadTestMappingsClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return LoadTestMappingsClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *LoadTestMappingsClient) updateCreateRequest(ctx context.Context, resourceURI string, loadTestMappingName string, properties LoadTestMappingResourceUpdate, _ *LoadTestMappingsClientUpdateOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.LoadTestService/loadTestMappings/{loadTestMappingName}" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + if loadTestMappingName == "" { + return nil, errors.New("parameter loadTestMappingName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadTestMappingName}", url.PathEscape(loadTestMappingName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20241201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *LoadTestMappingsClient) updateHandleResponse(resp *http.Response) (LoadTestMappingsClientUpdateResponse, error) { + result := LoadTestMappingsClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LoadTestMappingResource); err != nil { + return LoadTestMappingsClientUpdateResponse{}, err + } + return result, nil +} diff --git a/test/local/armloadtestservice/zz_loadtestprofilemappings_client.go b/test/local/armloadtestservice/zz_loadtestprofilemappings_client.go new file mode 100644 index 000000000000..ab4893e08959 --- /dev/null +++ b/test/local/armloadtestservice/zz_loadtestprofilemappings_client.go @@ -0,0 +1,328 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armloadtestservice + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// LoadTestProfileMappingsClient contains the methods for the LoadTestProfileMappings group. +// Don't use this type directly, use NewLoadTestProfileMappingsClient() instead. +// +// Generated from API version 2024-12-01-preview +type LoadTestProfileMappingsClient struct { + internal *arm.Client +} + +// NewLoadTestProfileMappingsClient creates a new instance of LoadTestProfileMappingsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewLoadTestProfileMappingsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*LoadTestProfileMappingsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &LoadTestProfileMappingsClient{ + internal: cl, + } + return client, nil +} + +// CreateOrUpdate - Create a LoadTestProfileMappingResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - loadTestProfileMappingName - Load Test Profile Mapping name +// - resource - Resource create parameters. +// - options - LoadTestProfileMappingsClientCreateOrUpdateOptions contains the optional parameters for the LoadTestProfileMappingsClient.CreateOrUpdate +// method. +func (client *LoadTestProfileMappingsClient) CreateOrUpdate(ctx context.Context, resourceURI string, loadTestProfileMappingName string, resource LoadTestProfileMappingResource, options *LoadTestProfileMappingsClientCreateOrUpdateOptions) (LoadTestProfileMappingsClientCreateOrUpdateResponse, error) { + var err error + const operationName = "LoadTestProfileMappingsClient.CreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceURI, loadTestProfileMappingName, resource, options) + if err != nil { + return LoadTestProfileMappingsClientCreateOrUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LoadTestProfileMappingsClientCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return LoadTestProfileMappingsClientCreateOrUpdateResponse{}, err + } + resp, err := client.createOrUpdateHandleResponse(httpResp) + return resp, err +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *LoadTestProfileMappingsClient) createOrUpdateCreateRequest(ctx context.Context, resourceURI string, loadTestProfileMappingName string, resource LoadTestProfileMappingResource, _ *LoadTestProfileMappingsClientCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.LoadTestService/loadTestProfileMappings/{loadTestProfileMappingName}" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + if loadTestProfileMappingName == "" { + return nil, errors.New("parameter loadTestProfileMappingName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadTestProfileMappingName}", url.PathEscape(loadTestProfileMappingName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20241201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *LoadTestProfileMappingsClient) createOrUpdateHandleResponse(resp *http.Response) (LoadTestProfileMappingsClientCreateOrUpdateResponse, error) { + result := LoadTestProfileMappingsClientCreateOrUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LoadTestProfileMappingResource); err != nil { + return LoadTestProfileMappingsClientCreateOrUpdateResponse{}, err + } + return result, nil +} + +// Delete - Delete a LoadTestProfileMappingResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - loadTestProfileMappingName - Load Test Profile Mapping name +// - options - LoadTestProfileMappingsClientDeleteOptions contains the optional parameters for the LoadTestProfileMappingsClient.Delete +// method. +func (client *LoadTestProfileMappingsClient) Delete(ctx context.Context, resourceURI string, loadTestProfileMappingName string, options *LoadTestProfileMappingsClientDeleteOptions) (LoadTestProfileMappingsClientDeleteResponse, error) { + var err error + const operationName = "LoadTestProfileMappingsClient.Delete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceURI, loadTestProfileMappingName, options) + if err != nil { + return LoadTestProfileMappingsClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LoadTestProfileMappingsClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return LoadTestProfileMappingsClientDeleteResponse{}, err + } + return LoadTestProfileMappingsClientDeleteResponse{}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *LoadTestProfileMappingsClient) deleteCreateRequest(ctx context.Context, resourceURI string, loadTestProfileMappingName string, _ *LoadTestProfileMappingsClientDeleteOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.LoadTestService/loadTestProfileMappings/{loadTestProfileMappingName}" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + if loadTestProfileMappingName == "" { + return nil, errors.New("parameter loadTestProfileMappingName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadTestProfileMappingName}", url.PathEscape(loadTestProfileMappingName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20241201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a LoadTestProfileMappingResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - loadTestProfileMappingName - Load Test Profile Mapping name +// - options - LoadTestProfileMappingsClientGetOptions contains the optional parameters for the LoadTestProfileMappingsClient.Get +// method. +func (client *LoadTestProfileMappingsClient) Get(ctx context.Context, resourceURI string, loadTestProfileMappingName string, options *LoadTestProfileMappingsClientGetOptions) (LoadTestProfileMappingsClientGetResponse, error) { + var err error + const operationName = "LoadTestProfileMappingsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceURI, loadTestProfileMappingName, options) + if err != nil { + return LoadTestProfileMappingsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LoadTestProfileMappingsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return LoadTestProfileMappingsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *LoadTestProfileMappingsClient) getCreateRequest(ctx context.Context, resourceURI string, loadTestProfileMappingName string, _ *LoadTestProfileMappingsClientGetOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.LoadTestService/loadTestProfileMappings/{loadTestProfileMappingName}" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + if loadTestProfileMappingName == "" { + return nil, errors.New("parameter loadTestProfileMappingName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadTestProfileMappingName}", url.PathEscape(loadTestProfileMappingName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20241201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *LoadTestProfileMappingsClient) getHandleResponse(resp *http.Response) (LoadTestProfileMappingsClientGetResponse, error) { + result := LoadTestProfileMappingsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LoadTestProfileMappingResource); err != nil { + return LoadTestProfileMappingsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List LoadTestProfileMappingResource resources by parent +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - options - LoadTestProfileMappingsClientListOptions contains the optional parameters for the LoadTestProfileMappingsClient.NewListPager +// method. +func (client *LoadTestProfileMappingsClient) NewListPager(resourceURI string, options *LoadTestProfileMappingsClientListOptions) *runtime.Pager[LoadTestProfileMappingsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[LoadTestProfileMappingsClientListResponse]{ + More: func(page LoadTestProfileMappingsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *LoadTestProfileMappingsClientListResponse) (LoadTestProfileMappingsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "LoadTestProfileMappingsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceURI, options) + }, nil) + if err != nil { + return LoadTestProfileMappingsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *LoadTestProfileMappingsClient) listCreateRequest(ctx context.Context, resourceURI string, _ *LoadTestProfileMappingsClientListOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.LoadTestService/loadTestProfileMappings" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20241201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *LoadTestProfileMappingsClient) listHandleResponse(resp *http.Response) (LoadTestProfileMappingsClientListResponse, error) { + result := LoadTestProfileMappingsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LoadTestProfileMappingResourceListResult); err != nil { + return LoadTestProfileMappingsClientListResponse{}, err + } + return result, nil +} + +// Update - Update a LoadTestProfileMappingResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceURI - The fully qualified Azure Resource manager identifier of the resource. +// - loadTestProfileMappingName - Load Test Profile Mapping name +// - properties - The resource properties to be updated. +// - options - LoadTestProfileMappingsClientUpdateOptions contains the optional parameters for the LoadTestProfileMappingsClient.Update +// method. +func (client *LoadTestProfileMappingsClient) Update(ctx context.Context, resourceURI string, loadTestProfileMappingName string, properties LoadTestProfileMappingResourceUpdate, options *LoadTestProfileMappingsClientUpdateOptions) (LoadTestProfileMappingsClientUpdateResponse, error) { + var err error + const operationName = "LoadTestProfileMappingsClient.Update" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceURI, loadTestProfileMappingName, properties, options) + if err != nil { + return LoadTestProfileMappingsClientUpdateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LoadTestProfileMappingsClientUpdateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return LoadTestProfileMappingsClientUpdateResponse{}, err + } + resp, err := client.updateHandleResponse(httpResp) + return resp, err +} + +// updateCreateRequest creates the Update request. +func (client *LoadTestProfileMappingsClient) updateCreateRequest(ctx context.Context, resourceURI string, loadTestProfileMappingName string, properties LoadTestProfileMappingResourceUpdate, _ *LoadTestProfileMappingsClientUpdateOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.LoadTestService/loadTestProfileMappings/{loadTestProfileMappingName}" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + if loadTestProfileMappingName == "" { + return nil, errors.New("parameter loadTestProfileMappingName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadTestProfileMappingName}", url.PathEscape(loadTestProfileMappingName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20241201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *LoadTestProfileMappingsClient) updateHandleResponse(resp *http.Response) (LoadTestProfileMappingsClientUpdateResponse, error) { + result := LoadTestProfileMappingsClientUpdateResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LoadTestProfileMappingResource); err != nil { + return LoadTestProfileMappingsClientUpdateResponse{}, err + } + return result, nil +} diff --git a/test/local/armloadtestservice/zz_loadtests_client.go b/test/local/armloadtestservice/zz_loadtests_client.go new file mode 100644 index 000000000000..19b91610e36c --- /dev/null +++ b/test/local/armloadtestservice/zz_loadtests_client.go @@ -0,0 +1,502 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armloadtestservice + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// LoadTestsClient contains the methods for the LoadTests group. +// Don't use this type directly, use NewLoadTestsClient() instead. +// +// Generated from API version 2024-12-01-preview +type LoadTestsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewLoadTestsClient creates a new instance of LoadTestsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewLoadTestsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*LoadTestsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &LoadTestsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create a LoadTestResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - loadTestName - Load Test name +// - resource - Resource create parameters. +// - options - LoadTestsClientBeginCreateOrUpdateOptions contains the optional parameters for the LoadTestsClient.BeginCreateOrUpdate +// method. +func (client *LoadTestsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, loadTestName string, resource LoadTestResource, options *LoadTestsClientBeginCreateOrUpdateOptions) (*runtime.Poller[LoadTestsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, loadTestName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[LoadTestsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[LoadTestsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create a LoadTestResource +// If the operation fails it returns an *azcore.ResponseError type. +func (client *LoadTestsClient) createOrUpdate(ctx context.Context, resourceGroupName string, loadTestName string, resource LoadTestResource, options *LoadTestsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "LoadTestsClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, loadTestName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *LoadTestsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, loadTestName string, resource LoadTestResource, _ *LoadTestsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LoadTestService/loadTests/{loadTestName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadTestName == "" { + return nil, errors.New("parameter loadTestName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadTestName}", url.PathEscape(loadTestName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20241201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a LoadTestResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - loadTestName - Load Test name +// - options - LoadTestsClientBeginDeleteOptions contains the optional parameters for the LoadTestsClient.BeginDelete method. +func (client *LoadTestsClient) BeginDelete(ctx context.Context, resourceGroupName string, loadTestName string, options *LoadTestsClientBeginDeleteOptions) (*runtime.Poller[LoadTestsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, loadTestName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[LoadTestsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[LoadTestsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a LoadTestResource +// If the operation fails it returns an *azcore.ResponseError type. +func (client *LoadTestsClient) deleteOperation(ctx context.Context, resourceGroupName string, loadTestName string, options *LoadTestsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "LoadTestsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, loadTestName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *LoadTestsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, loadTestName string, _ *LoadTestsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LoadTestService/loadTests/{loadTestName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadTestName == "" { + return nil, errors.New("parameter loadTestName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadTestName}", url.PathEscape(loadTestName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20241201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a LoadTestResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - loadTestName - Load Test name +// - options - LoadTestsClientGetOptions contains the optional parameters for the LoadTestsClient.Get method. +func (client *LoadTestsClient) Get(ctx context.Context, resourceGroupName string, loadTestName string, options *LoadTestsClientGetOptions) (LoadTestsClientGetResponse, error) { + var err error + const operationName = "LoadTestsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, loadTestName, options) + if err != nil { + return LoadTestsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LoadTestsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return LoadTestsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *LoadTestsClient) getCreateRequest(ctx context.Context, resourceGroupName string, loadTestName string, _ *LoadTestsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LoadTestService/loadTests/{loadTestName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadTestName == "" { + return nil, errors.New("parameter loadTestName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadTestName}", url.PathEscape(loadTestName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20241201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *LoadTestsClient) getHandleResponse(resp *http.Response) (LoadTestsClientGetResponse, error) { + result := LoadTestsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LoadTestResource); err != nil { + return LoadTestsClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - List LoadTestResource resources by resource group +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - LoadTestsClientListByResourceGroupOptions contains the optional parameters for the LoadTestsClient.NewListByResourceGroupPager +// method. +func (client *LoadTestsClient) NewListByResourceGroupPager(resourceGroupName string, options *LoadTestsClientListByResourceGroupOptions) *runtime.Pager[LoadTestsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[LoadTestsClientListByResourceGroupResponse]{ + More: func(page LoadTestsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *LoadTestsClientListByResourceGroupResponse) (LoadTestsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "LoadTestsClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return LoadTestsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *LoadTestsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *LoadTestsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LoadTestService/loadTests" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20241201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *LoadTestsClient) listByResourceGroupHandleResponse(resp *http.Response) (LoadTestsClientListByResourceGroupResponse, error) { + result := LoadTestsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LoadTestResourceListResult); err != nil { + return LoadTestsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - List LoadTestResource resources by subscription ID +// - options - LoadTestsClientListBySubscriptionOptions contains the optional parameters for the LoadTestsClient.NewListBySubscriptionPager +// method. +func (client *LoadTestsClient) NewListBySubscriptionPager(options *LoadTestsClientListBySubscriptionOptions) *runtime.Pager[LoadTestsClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[LoadTestsClientListBySubscriptionResponse]{ + More: func(page LoadTestsClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *LoadTestsClientListBySubscriptionResponse) (LoadTestsClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "LoadTestsClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return LoadTestsClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *LoadTestsClient) listBySubscriptionCreateRequest(ctx context.Context, _ *LoadTestsClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.LoadTestService/loadTests" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20241201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *LoadTestsClient) listBySubscriptionHandleResponse(resp *http.Response) (LoadTestsClientListBySubscriptionResponse, error) { + result := LoadTestsClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.LoadTestResourceListResult); err != nil { + return LoadTestsClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// NewOutboundNetworkDependenciesEndpointsPager - Lists the endpoints that agents may call as part of load testing. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - loadTestName - Load Test name +// - options - LoadTestsClientOutboundNetworkDependenciesEndpointsOptions contains the optional parameters for the LoadTestsClient.NewOutboundNetworkDependenciesEndpointsPager +// method. +func (client *LoadTestsClient) NewOutboundNetworkDependenciesEndpointsPager(resourceGroupName string, loadTestName string, options *LoadTestsClientOutboundNetworkDependenciesEndpointsOptions) *runtime.Pager[LoadTestsClientOutboundNetworkDependenciesEndpointsResponse] { + return runtime.NewPager(runtime.PagingHandler[LoadTestsClientOutboundNetworkDependenciesEndpointsResponse]{ + More: func(page LoadTestsClientOutboundNetworkDependenciesEndpointsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *LoadTestsClientOutboundNetworkDependenciesEndpointsResponse) (LoadTestsClientOutboundNetworkDependenciesEndpointsResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "LoadTestsClient.NewOutboundNetworkDependenciesEndpointsPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.outboundNetworkDependenciesEndpointsCreateRequest(ctx, resourceGroupName, loadTestName, options) + }, nil) + if err != nil { + return LoadTestsClientOutboundNetworkDependenciesEndpointsResponse{}, err + } + return client.outboundNetworkDependenciesEndpointsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// outboundNetworkDependenciesEndpointsCreateRequest creates the OutboundNetworkDependenciesEndpoints request. +func (client *LoadTestsClient) outboundNetworkDependenciesEndpointsCreateRequest(ctx context.Context, resourceGroupName string, loadTestName string, _ *LoadTestsClientOutboundNetworkDependenciesEndpointsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LoadTestService/loadTests/{loadTestName}/outboundNetworkDependenciesEndpoints" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadTestName == "" { + return nil, errors.New("parameter loadTestName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadTestName}", url.PathEscape(loadTestName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20241201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// outboundNetworkDependenciesEndpointsHandleResponse handles the OutboundNetworkDependenciesEndpoints response. +func (client *LoadTestsClient) outboundNetworkDependenciesEndpointsHandleResponse(resp *http.Response) (LoadTestsClientOutboundNetworkDependenciesEndpointsResponse, error) { + result := LoadTestsClientOutboundNetworkDependenciesEndpointsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PagedOutboundEnvironmentEndpoint); err != nil { + return LoadTestsClientOutboundNetworkDependenciesEndpointsResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update a LoadTestResource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - loadTestName - Load Test name +// - properties - The resource properties to be updated. +// - options - LoadTestsClientBeginUpdateOptions contains the optional parameters for the LoadTestsClient.BeginUpdate method. +func (client *LoadTestsClient) BeginUpdate(ctx context.Context, resourceGroupName string, loadTestName string, properties LoadTestResourceUpdate, options *LoadTestsClientBeginUpdateOptions) (*runtime.Poller[LoadTestsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, loadTestName, properties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[LoadTestsClientUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaLocation, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[LoadTestsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a LoadTestResource +// If the operation fails it returns an *azcore.ResponseError type. +func (client *LoadTestsClient) update(ctx context.Context, resourceGroupName string, loadTestName string, properties LoadTestResourceUpdate, options *LoadTestsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "LoadTestsClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, loadTestName, properties, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *LoadTestsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, loadTestName string, properties LoadTestResourceUpdate, _ *LoadTestsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LoadTestService/loadTests/{loadTestName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadTestName == "" { + return nil, errors.New("parameter loadTestName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadTestName}", url.PathEscape(loadTestName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20241201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armloadtestservice/zz_loadtestsmaxmonthlyvirtualuserhourslimitsresource_client.go b/test/local/armloadtestservice/zz_loadtestsmaxmonthlyvirtualuserhourslimitsresource_client.go new file mode 100644 index 000000000000..94fb42795723 --- /dev/null +++ b/test/local/armloadtestservice/zz_loadtestsmaxmonthlyvirtualuserhourslimitsresource_client.go @@ -0,0 +1,174 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armloadtestservice + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient contains the methods for the LoadTestsMaxMonthlyVirtualUserHoursLimitsResource +// group. +// Don't use this type directly, use NewLoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient() instead. +// +// Generated from API version 2024-12-01-preview +type LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient struct { + internal *arm.Client + subscriptionID string +} + +// NewLoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient creates a new instance of LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewLoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get the limit of max monthly virtual user hours for the load testing resource. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - loadTestName - Load Test name +// - options - LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientGetOptions contains the optional parameters for the LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient.Get +// method. +func (client *LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient) Get(ctx context.Context, resourceGroupName string, loadTestName string, options *LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientGetOptions) (LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientGetResponse, error) { + var err error + const operationName = "LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, loadTestName, options) + if err != nil { + return LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient) getCreateRequest(ctx context.Context, resourceGroupName string, loadTestName string, _ *LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LoadTestService/loadTests/{loadTestName}/limits/maxMonthlyVirtualUserHours" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadTestName == "" { + return nil, errors.New("parameter loadTestName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadTestName}", url.PathEscape(loadTestName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20241201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient) getHandleResponse(resp *http.Response) (LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientGetResponse, error) { + result := LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.MaxMonthlyVirtualUserHoursResource); err != nil { + return LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientGetResponse{}, err + } + return result, nil +} + +// Set - Set the limit of max monthly virtual user hours for the load testing resource. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - loadTestName - Load Test name +// - body - The content of the action request +// - options - LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientSetOptions contains the optional parameters for the LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient.Set +// method. +func (client *LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient) Set(ctx context.Context, resourceGroupName string, loadTestName string, body MaxMonthlyVirtualUserHoursLimitRequest, options *LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientSetOptions) (LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientSetResponse, error) { + var err error + const operationName = "LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient.Set" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.setCreateRequest(ctx, resourceGroupName, loadTestName, body, options) + if err != nil { + return LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientSetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientSetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientSetResponse{}, err + } + resp, err := client.setHandleResponse(httpResp) + return resp, err +} + +// setCreateRequest creates the Set request. +func (client *LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient) setCreateRequest(ctx context.Context, resourceGroupName string, loadTestName string, body MaxMonthlyVirtualUserHoursLimitRequest, _ *LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientSetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.LoadTestService/loadTests/{loadTestName}/limits/maxMonthlyVirtualUserHours/set" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if loadTestName == "" { + return nil, errors.New("parameter loadTestName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{loadTestName}", url.PathEscape(loadTestName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20241201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// setHandleResponse handles the Set response. +func (client *LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient) setHandleResponse(resp *http.Response) (LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientSetResponse, error) { + result := LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientSetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.MaxMonthlyVirtualUserHoursResource); err != nil { + return LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientSetResponse{}, err + } + return result, nil +} diff --git a/test/local/armloadtestservice/zz_models.go b/test/local/armloadtestservice/zz_models.go new file mode 100644 index 000000000000..4694fa133f88 --- /dev/null +++ b/test/local/armloadtestservice/zz_models.go @@ -0,0 +1,480 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armloadtestservice + +import "time" + +// CheckQuotaAvailabilityResponse - Check quota availability response object. +type CheckQuotaAvailabilityResponse struct { + // Check quota availability response properties. + Properties *CheckQuotaAvailabilityResponseProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string + + // READ-ONLY; The name of the resource. + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData +} + +// CheckQuotaAvailabilityResponseProperties - Check quota availability response properties. +type CheckQuotaAvailabilityResponseProperties struct { + // Message indicating additional details to add to quota support request. + AvailabilityStatus *string + + // True/False indicating whether the quota request be granted based on availability. + IsAvailable *bool +} + +// EncryptionProperties - Key and identity details for Customer Managed Key encryption of load test resource. +type EncryptionProperties struct { + // All identity configuration for Customer-managed key settings defining which identity should be used to auth to Key Vault. + Identity *EncryptionPropertiesIdentity + + // key encryption key Url, versioned. Ex: https://contosovault.vault.azure.net/keys/contosokek/562a4bb76b524a1493a6afe8e536ee78 + // or https://contosovault.vault.azure.net/keys/contosokek. + KeyURL *string +} + +// EncryptionPropertiesIdentity - All identity configuration for Customer-managed key settings defining which identity should +// be used to auth to Key Vault. +type EncryptionPropertiesIdentity struct { + // User assigned identity to use for accessing key encryption key Url. Ex: /subscriptions/a0a0a0a0-bbbb-cccd-dddd-e1e1e1e1e1e1/resourceGroups//providers/Microsoft.ManagedIdentity/userAssignedIdentities/myId. + ResourceID *string + + // Managed identity type to use for accessing encryption key Url. + Type *Type +} + +// EndpointDependency - A domain name and connection details used to access a dependency. +type EndpointDependency struct { + // READ-ONLY; The domain name of the dependency. Domain names may be fully qualified or may contain a * wildcard. + DomainName *string + + // READ-ONLY; Human-readable supplemental information about the dependency and when it is applicable. + Description *string + + // READ-ONLY; The list of connection details for this endpoint. + EndpointDetails []*EndpointDetail +} + +// EndpointDetail - Details about the connection between the Batch service and the endpoint. +type EndpointDetail struct { + // READ-ONLY; The port an endpoint is connected to. + Port *int32 +} + +// LoadTestMappingProperties - Azure LoadTest mapping resource properties. +type LoadTestMappingProperties struct { + // Mapped Azure Load Test resource Id. + AzureLoadTestingResourceID *string + + // Mapped source resource Id. + SourceResourceID *string + + // Mapped Azure Load Test resource test-id. + TestID *string +} + +// LoadTestMappingResource - LoadTest mapping resource details +type LoadTestMappingResource struct { + // The resource-specific properties for this resource. + Properties *LoadTestMappingProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// LoadTestMappingResourceListResult - The response of a LoadTestMappingResource list operation. +type LoadTestMappingResourceListResult struct { + // REQUIRED; The LoadTestMappingResource items on this page + Value []*LoadTestMappingResource + + // The link to the next page of items + NextLink *string +} + +// LoadTestMappingResourceUpdate - The type used for update operations of the LoadTestMappingResource. +type LoadTestMappingResourceUpdate struct { + // The resource-specific properties for this resource. + Properties *LoadTestMappingResourceUpdateProperties +} + +// LoadTestMappingResourceUpdateProperties - The updatable properties of the LoadTestMappingResource. +type LoadTestMappingResourceUpdateProperties struct { + // Mapped Azure Load Test resource Id. + AzureLoadTestingResourceID *string + + // Mapped source resource Id. + SourceResourceID *string + + // Mapped Azure Load Test resource test-id. + TestID *string +} + +// LoadTestProfileMappingProperties - Azure LoadTest profile mapping resource properties. +type LoadTestProfileMappingProperties struct { + // Mapped Azure Load Test resource Id. + AzureLoadTestingResourceID *string + + // Mapped source resource Id. + SourceResourceID *string + + // Mapped Azure Load Test resource test-profile-id. + TestProfileID *string +} + +// LoadTestProfileMappingResource - LoadTest profile mapping resource details +type LoadTestProfileMappingResource struct { + // The resource-specific properties for this resource. + Properties *LoadTestProfileMappingProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// LoadTestProfileMappingResourceListResult - The response of a LoadTestProfileMappingResource list operation. +type LoadTestProfileMappingResourceListResult struct { + // REQUIRED; The LoadTestProfileMappingResource items on this page + Value []*LoadTestProfileMappingResource + + // The link to the next page of items + NextLink *string +} + +// LoadTestProfileMappingResourceUpdate - The type used for update operations of the LoadTestProfileMappingResource. +type LoadTestProfileMappingResourceUpdate struct { + // The resource-specific properties for this resource. + Properties *LoadTestProfileMappingResourceUpdateProperties +} + +// LoadTestProfileMappingResourceUpdateProperties - The updatable properties of the LoadTestProfileMappingResource. +type LoadTestProfileMappingResourceUpdateProperties struct { + // Mapped Azure Load Test resource Id. + AzureLoadTestingResourceID *string + + // Mapped source resource Id. + SourceResourceID *string + + // Mapped Azure Load Test resource test-profile-id. + TestProfileID *string +} + +// LoadTestProperties - LoadTest resource properties. +type LoadTestProperties struct { + // Description of the resource. + Description *string + + // CMK Encryption property. + Encryption *EncryptionProperties + + // READ-ONLY; Resource data plane URI. + DataPlaneURI *string + + // READ-ONLY; Resource provisioning state. + ProvisioningState *ResourceState +} + +// LoadTestResource - LoadTest details. +type LoadTestResource struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The managed service identities assigned to this resource. + Identity *ManagedServiceIdentity + + // The resource-specific properties for this resource. + Properties *LoadTestProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// LoadTestResourceListResult - The response of a LoadTestResource list operation. +type LoadTestResourceListResult struct { + // REQUIRED; The LoadTestResource items on this page + Value []*LoadTestResource + + // The link to the next page of items + NextLink *string +} + +// LoadTestResourceUpdate - The type used for update operations of the LoadTestResource. +type LoadTestResourceUpdate struct { + // The managed service identities assigned to this resource. + Identity *ManagedServiceIdentity + + // The resource-specific properties for this resource. + Properties *LoadTestResourceUpdateProperties + + // Resource tags. + Tags map[string]*string +} + +// LoadTestResourceUpdateProperties - The updatable properties of the LoadTestResource. +type LoadTestResourceUpdateProperties struct { + // Description of the resource. + Description *string + + // CMK Encryption property. + Encryption *EncryptionProperties +} + +// ManagedServiceIdentity - Managed service identity (system assigned and/or user assigned identities) +type ManagedServiceIdentity struct { + // REQUIRED; The type of managed identity assigned to this resource. + Type *ManagedServiceIdentityType + + // The identities assigned to this resource by the user. + UserAssignedIdentities map[string]*UserAssignedIdentity + + // READ-ONLY; The service principal ID of the system assigned identity. This property will only be provided for a system assigned + // identity. + PrincipalID *string + + // READ-ONLY; The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + TenantID *string +} + +// MaxMonthlyVirtualUserHoursLimitRequest - Max monthly virtual usage hours limit request payload. +type MaxMonthlyVirtualUserHoursLimitRequest struct { + // The new maxMonthlyVirtualUserHours limit, with -1 indicating that there is no limit. + Limit *int32 +} + +// MaxMonthlyVirtualUserHoursResource - Max monthly virtual usage hours resource. +type MaxMonthlyVirtualUserHoursResource struct { + // The resource-specific properties for this resource. + Properties *MaxMonthlyVirtualUserHoursResourceProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// MaxMonthlyVirtualUserHoursResourceProperties - Max monthly virtual usage hours resource limit properties. +type MaxMonthlyVirtualUserHoursResourceProperties struct { + // READ-ONLY; Current limit value, with -1 indicating that there is no limit. + Limit *int32 + + // READ-ONLY; Resource provisioning state. + ProvisioningState *ResourceState + + // READ-ONLY; Current usage value. + Usage *int32 +} + +// Operation - REST API Operation +// +// Details of a REST API operation, returned from the Resource Provider Operations API +type Operation struct { + // Localized display information for this particular operation. + Display *OperationDisplay + + // READ-ONLY; Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + ActionType *ActionType + + // READ-ONLY; Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure + // Resource Manager/control-plane operations. + IsDataAction *bool + + // READ-ONLY; The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + // "Microsoft.Compute/virtualMachines/capture/action" + Name *string + + // READ-ONLY; The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default + // value is "user,system" + Origin *Origin +} + +// OperationDisplay - Localized display information for an operation. +type OperationDisplay struct { + // READ-ONLY; The short, localized friendly description of the operation; suitable for tool tips and detailed views. + Description *string + + // READ-ONLY; The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual + // Machine", "Restart Virtual Machine". + Operation *string + + // READ-ONLY; The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft + // Compute". + Provider *string + + // READ-ONLY; The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job + // Schedule Collections". + Resource *string +} + +// OperationListResult - A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to +// get the next set of results. +type OperationListResult struct { + // REQUIRED; The Operation items on this page + Value []*Operation + + // The link to the next page of items + NextLink *string +} + +// OutboundEnvironmentEndpoint - A collection of related endpoints from the same service for which the Batch service requires +// outbound access. +type OutboundEnvironmentEndpoint struct { + // READ-ONLY; The type of service that Azure Load Testing connects to. + Category *string + + // READ-ONLY; The endpoints for this service to which the Batch service makes outbound calls. + Endpoints []*EndpointDependency +} + +// PagedOutboundEnvironmentEndpoint - Values returned by the List operation. +type PagedOutboundEnvironmentEndpoint struct { + // REQUIRED; The OutboundEnvironmentEndpoint items on this page + Value []*OutboundEnvironmentEndpoint + + // The link to the next page of items + NextLink *string +} + +// QuotaBucketRequest - Request object of new quota for a quota bucket. +type QuotaBucketRequest struct { + // Request object of new quota for a quota bucket. + Properties *QuotaBucketRequestProperties +} + +// QuotaBucketRequestProperties - New quota request request properties. +type QuotaBucketRequestProperties struct { + // Current quota limit of the quota bucket. + CurrentQuota *int32 + + // Current quota usage of the quota bucket. + CurrentUsage *int32 + + // Dimensions for new quota request. + Dimensions *QuotaBucketRequestPropertiesDimensions + + // New quota limit of the quota bucket. + NewQuota *int32 +} + +// QuotaBucketRequestPropertiesDimensions - Dimensions for new quota request. +type QuotaBucketRequestPropertiesDimensions struct { + // Location dimension for new quota request of the quota bucket. + Location *string + + // Subscription Id dimension for new quota request of the quota bucket. + SubscriptionID *string +} + +// QuotaResource - Quota bucket details object. +type QuotaResource struct { + // The resource-specific properties for this resource. + Properties *QuotaResourceProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// QuotaResourceListResult - The response of a QuotaResource list operation. +type QuotaResourceListResult struct { + // REQUIRED; The QuotaResource items on this page + Value []*QuotaResource + + // The link to the next page of items + NextLink *string +} + +// QuotaResourceProperties - Quota bucket resource properties. +type QuotaResourceProperties struct { + // Current quota limit of the quota bucket. + Limit *int32 + + // Current quota usage of the quota bucket. + Usage *int32 + + // READ-ONLY; Resource provisioning state. + ProvisioningState *ResourceState +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time + + // The identity that created the resource. + CreatedBy *string + + // The type of identity that created the resource. + CreatedByType *CreatedByType + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time + + // The identity that last modified the resource. + LastModifiedBy *string + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType +} + +// UserAssignedIdentity - User assigned identity properties +type UserAssignedIdentity struct { + // READ-ONLY; The client ID of the assigned identity. + ClientID *string + + // READ-ONLY; The principal ID of the assigned identity. + PrincipalID *string +} diff --git a/test/local/armloadtestservice/zz_models_serde.go b/test/local/armloadtestservice/zz_models_serde.go new file mode 100644 index 000000000000..bb19e0ac47ff --- /dev/null +++ b/test/local/armloadtestservice/zz_models_serde.go @@ -0,0 +1,1396 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armloadtestservice + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type CheckQuotaAvailabilityResponse. +func (c CheckQuotaAvailabilityResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", c.ID) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "systemData", c.SystemData) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CheckQuotaAvailabilityResponse. +func (c *CheckQuotaAvailabilityResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &c.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CheckQuotaAvailabilityResponseProperties. +func (c CheckQuotaAvailabilityResponseProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "availabilityStatus", c.AvailabilityStatus) + populate(objectMap, "isAvailable", c.IsAvailable) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CheckQuotaAvailabilityResponseProperties. +func (c *CheckQuotaAvailabilityResponseProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "availabilityStatus": + err = unpopulate(val, "AvailabilityStatus", &c.AvailabilityStatus) + delete(rawMsg, key) + case "isAvailable": + err = unpopulate(val, "IsAvailable", &c.IsAvailable) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EncryptionProperties. +func (e EncryptionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identity", e.Identity) + populate(objectMap, "keyUrl", e.KeyURL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EncryptionProperties. +func (e *EncryptionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "identity": + err = unpopulate(val, "Identity", &e.Identity) + delete(rawMsg, key) + case "keyUrl": + err = unpopulate(val, "KeyURL", &e.KeyURL) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EncryptionPropertiesIdentity. +func (e EncryptionPropertiesIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "resourceId", e.ResourceID) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EncryptionPropertiesIdentity. +func (e *EncryptionPropertiesIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "resourceId": + err = unpopulate(val, "ResourceID", &e.ResourceID) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &e.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EndpointDependency. +func (e EndpointDependency) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", e.Description) + populate(objectMap, "domainName", e.DomainName) + populate(objectMap, "endpointDetails", e.EndpointDetails) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EndpointDependency. +func (e *EndpointDependency) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &e.Description) + delete(rawMsg, key) + case "domainName": + err = unpopulate(val, "DomainName", &e.DomainName) + delete(rawMsg, key) + case "endpointDetails": + err = unpopulate(val, "EndpointDetails", &e.EndpointDetails) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EndpointDetail. +func (e EndpointDetail) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "port", e.Port) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EndpointDetail. +func (e *EndpointDetail) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "port": + err = unpopulate(val, "Port", &e.Port) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LoadTestMappingProperties. +func (l LoadTestMappingProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "azureLoadTestingResourceId", l.AzureLoadTestingResourceID) + populate(objectMap, "sourceResourceId", l.SourceResourceID) + populate(objectMap, "testId", l.TestID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadTestMappingProperties. +func (l *LoadTestMappingProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "azureLoadTestingResourceId": + err = unpopulate(val, "AzureLoadTestingResourceID", &l.AzureLoadTestingResourceID) + delete(rawMsg, key) + case "sourceResourceId": + err = unpopulate(val, "SourceResourceID", &l.SourceResourceID) + delete(rawMsg, key) + case "testId": + err = unpopulate(val, "TestID", &l.TestID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LoadTestMappingResource. +func (l LoadTestMappingResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", l.ID) + populate(objectMap, "name", l.Name) + populate(objectMap, "properties", l.Properties) + populate(objectMap, "systemData", l.SystemData) + populate(objectMap, "type", l.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadTestMappingResource. +func (l *LoadTestMappingResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &l.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &l.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &l.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &l.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &l.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LoadTestMappingResourceListResult. +func (l LoadTestMappingResourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", l.NextLink) + populate(objectMap, "value", l.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadTestMappingResourceListResult. +func (l *LoadTestMappingResourceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &l.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &l.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LoadTestMappingResourceUpdate. +func (l LoadTestMappingResourceUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", l.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadTestMappingResourceUpdate. +func (l *LoadTestMappingResourceUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &l.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LoadTestMappingResourceUpdateProperties. +func (l LoadTestMappingResourceUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "azureLoadTestingResourceId", l.AzureLoadTestingResourceID) + populate(objectMap, "sourceResourceId", l.SourceResourceID) + populate(objectMap, "testId", l.TestID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadTestMappingResourceUpdateProperties. +func (l *LoadTestMappingResourceUpdateProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "azureLoadTestingResourceId": + err = unpopulate(val, "AzureLoadTestingResourceID", &l.AzureLoadTestingResourceID) + delete(rawMsg, key) + case "sourceResourceId": + err = unpopulate(val, "SourceResourceID", &l.SourceResourceID) + delete(rawMsg, key) + case "testId": + err = unpopulate(val, "TestID", &l.TestID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LoadTestProfileMappingProperties. +func (l LoadTestProfileMappingProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "azureLoadTestingResourceId", l.AzureLoadTestingResourceID) + populate(objectMap, "sourceResourceId", l.SourceResourceID) + populate(objectMap, "testProfileId", l.TestProfileID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadTestProfileMappingProperties. +func (l *LoadTestProfileMappingProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "azureLoadTestingResourceId": + err = unpopulate(val, "AzureLoadTestingResourceID", &l.AzureLoadTestingResourceID) + delete(rawMsg, key) + case "sourceResourceId": + err = unpopulate(val, "SourceResourceID", &l.SourceResourceID) + delete(rawMsg, key) + case "testProfileId": + err = unpopulate(val, "TestProfileID", &l.TestProfileID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LoadTestProfileMappingResource. +func (l LoadTestProfileMappingResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", l.ID) + populate(objectMap, "name", l.Name) + populate(objectMap, "properties", l.Properties) + populate(objectMap, "systemData", l.SystemData) + populate(objectMap, "type", l.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadTestProfileMappingResource. +func (l *LoadTestProfileMappingResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &l.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &l.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &l.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &l.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &l.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LoadTestProfileMappingResourceListResult. +func (l LoadTestProfileMappingResourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", l.NextLink) + populate(objectMap, "value", l.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadTestProfileMappingResourceListResult. +func (l *LoadTestProfileMappingResourceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &l.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &l.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LoadTestProfileMappingResourceUpdate. +func (l LoadTestProfileMappingResourceUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", l.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadTestProfileMappingResourceUpdate. +func (l *LoadTestProfileMappingResourceUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &l.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LoadTestProfileMappingResourceUpdateProperties. +func (l LoadTestProfileMappingResourceUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "azureLoadTestingResourceId", l.AzureLoadTestingResourceID) + populate(objectMap, "sourceResourceId", l.SourceResourceID) + populate(objectMap, "testProfileId", l.TestProfileID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadTestProfileMappingResourceUpdateProperties. +func (l *LoadTestProfileMappingResourceUpdateProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "azureLoadTestingResourceId": + err = unpopulate(val, "AzureLoadTestingResourceID", &l.AzureLoadTestingResourceID) + delete(rawMsg, key) + case "sourceResourceId": + err = unpopulate(val, "SourceResourceID", &l.SourceResourceID) + delete(rawMsg, key) + case "testProfileId": + err = unpopulate(val, "TestProfileID", &l.TestProfileID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LoadTestProperties. +func (l LoadTestProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dataPlaneURI", l.DataPlaneURI) + populate(objectMap, "description", l.Description) + populate(objectMap, "encryption", l.Encryption) + populate(objectMap, "provisioningState", l.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadTestProperties. +func (l *LoadTestProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "dataPlaneURI": + err = unpopulate(val, "DataPlaneURI", &l.DataPlaneURI) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &l.Description) + delete(rawMsg, key) + case "encryption": + err = unpopulate(val, "Encryption", &l.Encryption) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &l.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LoadTestResource. +func (l LoadTestResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", l.ID) + populate(objectMap, "identity", l.Identity) + populate(objectMap, "location", l.Location) + populate(objectMap, "name", l.Name) + populate(objectMap, "properties", l.Properties) + populate(objectMap, "systemData", l.SystemData) + populate(objectMap, "tags", l.Tags) + populate(objectMap, "type", l.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadTestResource. +func (l *LoadTestResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &l.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &l.Identity) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &l.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &l.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &l.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &l.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &l.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &l.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LoadTestResourceListResult. +func (l LoadTestResourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", l.NextLink) + populate(objectMap, "value", l.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadTestResourceListResult. +func (l *LoadTestResourceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &l.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &l.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LoadTestResourceUpdate. +func (l LoadTestResourceUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identity", l.Identity) + populate(objectMap, "properties", l.Properties) + populate(objectMap, "tags", l.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadTestResourceUpdate. +func (l *LoadTestResourceUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "identity": + err = unpopulate(val, "Identity", &l.Identity) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &l.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &l.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LoadTestResourceUpdateProperties. +func (l LoadTestResourceUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", l.Description) + populate(objectMap, "encryption", l.Encryption) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LoadTestResourceUpdateProperties. +func (l *LoadTestResourceUpdateProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &l.Description) + delete(rawMsg, key) + case "encryption": + err = unpopulate(val, "Encryption", &l.Encryption) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedServiceIdentity. +func (m ManagedServiceIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "principalId", m.PrincipalID) + populate(objectMap, "tenantId", m.TenantID) + populate(objectMap, "type", m.Type) + populate(objectMap, "userAssignedIdentities", m.UserAssignedIdentities) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedServiceIdentity. +func (m *ManagedServiceIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "principalId": + err = unpopulate(val, "PrincipalID", &m.PrincipalID) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &m.TenantID) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + case "userAssignedIdentities": + err = unpopulate(val, "UserAssignedIdentities", &m.UserAssignedIdentities) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MaxMonthlyVirtualUserHoursLimitRequest. +func (m MaxMonthlyVirtualUserHoursLimitRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "limit", m.Limit) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MaxMonthlyVirtualUserHoursLimitRequest. +func (m *MaxMonthlyVirtualUserHoursLimitRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "limit": + err = unpopulate(val, "Limit", &m.Limit) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MaxMonthlyVirtualUserHoursResource. +func (m MaxMonthlyVirtualUserHoursResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", m.ID) + populate(objectMap, "name", m.Name) + populate(objectMap, "properties", m.Properties) + populate(objectMap, "systemData", m.SystemData) + populate(objectMap, "type", m.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MaxMonthlyVirtualUserHoursResource. +func (m *MaxMonthlyVirtualUserHoursResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &m.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &m.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &m.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &m.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MaxMonthlyVirtualUserHoursResourceProperties. +func (m MaxMonthlyVirtualUserHoursResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "limit", m.Limit) + populate(objectMap, "provisioningState", m.ProvisioningState) + populate(objectMap, "usage", m.Usage) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MaxMonthlyVirtualUserHoursResourceProperties. +func (m *MaxMonthlyVirtualUserHoursResourceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "limit": + err = unpopulate(val, "Limit", &m.Limit) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &m.ProvisioningState) + delete(rawMsg, key) + case "usage": + err = unpopulate(val, "Usage", &m.Usage) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Operation. +func (o Operation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionType", o.ActionType) + populate(objectMap, "display", o.Display) + populate(objectMap, "isDataAction", o.IsDataAction) + populate(objectMap, "name", o.Name) + populate(objectMap, "origin", o.Origin) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Operation. +func (o *Operation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionType": + err = unpopulate(val, "ActionType", &o.ActionType) + delete(rawMsg, key) + case "display": + err = unpopulate(val, "Display", &o.Display) + delete(rawMsg, key) + case "isDataAction": + err = unpopulate(val, "IsDataAction", &o.IsDataAction) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "origin": + err = unpopulate(val, "Origin", &o.Origin) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationDisplay. +func (o OperationDisplay) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", o.Description) + populate(objectMap, "operation", o.Operation) + populate(objectMap, "provider", o.Provider) + populate(objectMap, "resource", o.Resource) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationDisplay. +func (o *OperationDisplay) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &o.Description) + delete(rawMsg, key) + case "operation": + err = unpopulate(val, "Operation", &o.Operation) + delete(rawMsg, key) + case "provider": + err = unpopulate(val, "Provider", &o.Provider) + delete(rawMsg, key) + case "resource": + err = unpopulate(val, "Resource", &o.Resource) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationListResult. +func (o *OperationListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &o.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OutboundEnvironmentEndpoint. +func (o OutboundEnvironmentEndpoint) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "category", o.Category) + populate(objectMap, "endpoints", o.Endpoints) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OutboundEnvironmentEndpoint. +func (o *OutboundEnvironmentEndpoint) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "category": + err = unpopulate(val, "Category", &o.Category) + delete(rawMsg, key) + case "endpoints": + err = unpopulate(val, "Endpoints", &o.Endpoints) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PagedOutboundEnvironmentEndpoint. +func (p PagedOutboundEnvironmentEndpoint) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", p.NextLink) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PagedOutboundEnvironmentEndpoint. +func (p *PagedOutboundEnvironmentEndpoint) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &p.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type QuotaBucketRequest. +func (q QuotaBucketRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", q.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type QuotaBucketRequest. +func (q *QuotaBucketRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &q.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type QuotaBucketRequestProperties. +func (q QuotaBucketRequestProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "currentQuota", q.CurrentQuota) + populate(objectMap, "currentUsage", q.CurrentUsage) + populate(objectMap, "dimensions", q.Dimensions) + populate(objectMap, "newQuota", q.NewQuota) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type QuotaBucketRequestProperties. +func (q *QuotaBucketRequestProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "currentQuota": + err = unpopulate(val, "CurrentQuota", &q.CurrentQuota) + delete(rawMsg, key) + case "currentUsage": + err = unpopulate(val, "CurrentUsage", &q.CurrentUsage) + delete(rawMsg, key) + case "dimensions": + err = unpopulate(val, "Dimensions", &q.Dimensions) + delete(rawMsg, key) + case "newQuota": + err = unpopulate(val, "NewQuota", &q.NewQuota) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type QuotaBucketRequestPropertiesDimensions. +func (q QuotaBucketRequestPropertiesDimensions) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "location", q.Location) + populate(objectMap, "subscriptionId", q.SubscriptionID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type QuotaBucketRequestPropertiesDimensions. +func (q *QuotaBucketRequestPropertiesDimensions) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "location": + err = unpopulate(val, "Location", &q.Location) + delete(rawMsg, key) + case "subscriptionId": + err = unpopulate(val, "SubscriptionID", &q.SubscriptionID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type QuotaResource. +func (q QuotaResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", q.ID) + populate(objectMap, "name", q.Name) + populate(objectMap, "properties", q.Properties) + populate(objectMap, "systemData", q.SystemData) + populate(objectMap, "type", q.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type QuotaResource. +func (q *QuotaResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &q.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &q.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &q.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &q.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &q.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type QuotaResourceListResult. +func (q QuotaResourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", q.NextLink) + populate(objectMap, "value", q.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type QuotaResourceListResult. +func (q *QuotaResourceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &q.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &q.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type QuotaResourceProperties. +func (q QuotaResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "limit", q.Limit) + populate(objectMap, "provisioningState", q.ProvisioningState) + populate(objectMap, "usage", q.Usage) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type QuotaResourceProperties. +func (q *QuotaResourceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "limit": + err = unpopulate(val, "Limit", &q.Limit) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &q.ProvisioningState) + delete(rawMsg, key) + case "usage": + err = unpopulate(val, "Usage", &q.Usage) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", q, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateTime[datetime.RFC3339](objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateTime[datetime.RFC3339](val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateTime[datetime.RFC3339](val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserAssignedIdentity. +func (u UserAssignedIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clientId", u.ClientID) + populate(objectMap, "principalId", u.PrincipalID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserAssignedIdentity. +func (u *UserAssignedIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "clientId": + err = unpopulate(val, "ClientID", &u.ClientID) + delete(rawMsg, key) + case "principalId": + err = unpopulate(val, "PrincipalID", &u.PrincipalID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/local/armloadtestservice/zz_operations_client.go b/test/local/armloadtestservice/zz_operations_client.go new file mode 100644 index 000000000000..32110c79f249 --- /dev/null +++ b/test/local/armloadtestservice/zz_operations_client.go @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armloadtestservice + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +// +// Generated from API version 2024-12-01-preview +type OperationsClient struct { + internal *arm.Client +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*OperationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OperationsClient{ + internal: cl, + } + return client, nil +} + +// NewListPager - List the operations for the provider +// - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ + More: func(page OperationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OperationsClientListResponse) (OperationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OperationsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return OperationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, _ *OperationsClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.LoadTestService/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20241201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsClientListResponse, error) { + result := OperationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armloadtestservice/zz_options.go b/test/local/armloadtestservice/zz_options.go new file mode 100644 index 000000000000..44c3fab9e0fc --- /dev/null +++ b/test/local/armloadtestservice/zz_options.go @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armloadtestservice + +// LoadTestMappingsClientCreateOrUpdateOptions contains the optional parameters for the LoadTestMappingsClient.CreateOrUpdate +// method. +type LoadTestMappingsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// LoadTestMappingsClientDeleteOptions contains the optional parameters for the LoadTestMappingsClient.Delete method. +type LoadTestMappingsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// LoadTestMappingsClientGetOptions contains the optional parameters for the LoadTestMappingsClient.Get method. +type LoadTestMappingsClientGetOptions struct { + // placeholder for future optional parameters +} + +// LoadTestMappingsClientListOptions contains the optional parameters for the LoadTestMappingsClient.NewListPager method. +type LoadTestMappingsClientListOptions struct { + // placeholder for future optional parameters +} + +// LoadTestMappingsClientUpdateOptions contains the optional parameters for the LoadTestMappingsClient.Update method. +type LoadTestMappingsClientUpdateOptions struct { + // placeholder for future optional parameters +} + +// LoadTestProfileMappingsClientCreateOrUpdateOptions contains the optional parameters for the LoadTestProfileMappingsClient.CreateOrUpdate +// method. +type LoadTestProfileMappingsClientCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// LoadTestProfileMappingsClientDeleteOptions contains the optional parameters for the LoadTestProfileMappingsClient.Delete +// method. +type LoadTestProfileMappingsClientDeleteOptions struct { + // placeholder for future optional parameters +} + +// LoadTestProfileMappingsClientGetOptions contains the optional parameters for the LoadTestProfileMappingsClient.Get method. +type LoadTestProfileMappingsClientGetOptions struct { + // placeholder for future optional parameters +} + +// LoadTestProfileMappingsClientListOptions contains the optional parameters for the LoadTestProfileMappingsClient.NewListPager +// method. +type LoadTestProfileMappingsClientListOptions struct { + // placeholder for future optional parameters +} + +// LoadTestProfileMappingsClientUpdateOptions contains the optional parameters for the LoadTestProfileMappingsClient.Update +// method. +type LoadTestProfileMappingsClientUpdateOptions struct { + // placeholder for future optional parameters +} + +// LoadTestsClientBeginCreateOrUpdateOptions contains the optional parameters for the LoadTestsClient.BeginCreateOrUpdate +// method. +type LoadTestsClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// LoadTestsClientBeginDeleteOptions contains the optional parameters for the LoadTestsClient.BeginDelete method. +type LoadTestsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// LoadTestsClientBeginUpdateOptions contains the optional parameters for the LoadTestsClient.BeginUpdate method. +type LoadTestsClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// LoadTestsClientGetOptions contains the optional parameters for the LoadTestsClient.Get method. +type LoadTestsClientGetOptions struct { + // placeholder for future optional parameters +} + +// LoadTestsClientListByResourceGroupOptions contains the optional parameters for the LoadTestsClient.NewListByResourceGroupPager +// method. +type LoadTestsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// LoadTestsClientListBySubscriptionOptions contains the optional parameters for the LoadTestsClient.NewListBySubscriptionPager +// method. +type LoadTestsClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// LoadTestsClientOutboundNetworkDependenciesEndpointsOptions contains the optional parameters for the LoadTestsClient.NewOutboundNetworkDependenciesEndpointsPager +// method. +type LoadTestsClientOutboundNetworkDependenciesEndpointsOptions struct { + // placeholder for future optional parameters +} + +// LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientGetOptions contains the optional parameters for the LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient.Get +// method. +type LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientGetOptions struct { + // placeholder for future optional parameters +} + +// LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientSetOptions contains the optional parameters for the LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient.Set +// method. +type LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientSetOptions struct { + // placeholder for future optional parameters +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} + +// QuotasClientCheckAvailabilityOptions contains the optional parameters for the QuotasClient.CheckAvailability method. +type QuotasClientCheckAvailabilityOptions struct { + // placeholder for future optional parameters +} + +// QuotasClientGetOptions contains the optional parameters for the QuotasClient.Get method. +type QuotasClientGetOptions struct { + // placeholder for future optional parameters +} + +// QuotasClientListOptions contains the optional parameters for the QuotasClient.NewListPager method. +type QuotasClientListOptions struct { + // placeholder for future optional parameters +} diff --git a/test/local/armloadtestservice/zz_quotas_client.go b/test/local/armloadtestservice/zz_quotas_client.go new file mode 100644 index 000000000000..a61256872807 --- /dev/null +++ b/test/local/armloadtestservice/zz_quotas_client.go @@ -0,0 +1,229 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armloadtestservice + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// QuotasClient contains the methods for the Quotas group. +// Don't use this type directly, use NewQuotasClient() instead. +// +// Generated from API version 2024-12-01-preview +type QuotasClient struct { + internal *arm.Client + subscriptionID string +} + +// NewQuotasClient creates a new instance of QuotasClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewQuotasClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*QuotasClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &QuotasClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CheckAvailability - Check Quota Availability on quota bucket per region per subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// - location - The name of the Azure region. +// - quotaBucketName - The quota name. +// - quotaBucketRequest - The content of the action request +// - options - QuotasClientCheckAvailabilityOptions contains the optional parameters for the QuotasClient.CheckAvailability +// method. +func (client *QuotasClient) CheckAvailability(ctx context.Context, location string, quotaBucketName string, quotaBucketRequest QuotaBucketRequest, options *QuotasClientCheckAvailabilityOptions) (QuotasClientCheckAvailabilityResponse, error) { + var err error + const operationName = "QuotasClient.CheckAvailability" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.checkAvailabilityCreateRequest(ctx, location, quotaBucketName, quotaBucketRequest, options) + if err != nil { + return QuotasClientCheckAvailabilityResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return QuotasClientCheckAvailabilityResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return QuotasClientCheckAvailabilityResponse{}, err + } + resp, err := client.checkAvailabilityHandleResponse(httpResp) + return resp, err +} + +// checkAvailabilityCreateRequest creates the CheckAvailability request. +func (client *QuotasClient) checkAvailabilityCreateRequest(ctx context.Context, location string, quotaBucketName string, quotaBucketRequest QuotaBucketRequest, _ *QuotasClientCheckAvailabilityOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.LoadTestService/locations/{location}/quotas/{quotaBucketName}/checkAvailability" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if quotaBucketName == "" { + return nil, errors.New("parameter quotaBucketName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{quotaBucketName}", url.PathEscape(quotaBucketName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20241201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, quotaBucketRequest); err != nil { + return nil, err + } + return req, nil +} + +// checkAvailabilityHandleResponse handles the CheckAvailability response. +func (client *QuotasClient) checkAvailabilityHandleResponse(resp *http.Response) (QuotasClientCheckAvailabilityResponse, error) { + result := QuotasClientCheckAvailabilityResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CheckQuotaAvailabilityResponse); err != nil { + return QuotasClientCheckAvailabilityResponse{}, err + } + return result, nil +} + +// Get - Get the available quota for a quota bucket per region per subscription. +// If the operation fails it returns an *azcore.ResponseError type. +// - location - The name of the Azure region. +// - quotaBucketName - The quota name. +// - options - QuotasClientGetOptions contains the optional parameters for the QuotasClient.Get method. +func (client *QuotasClient) Get(ctx context.Context, location string, quotaBucketName string, options *QuotasClientGetOptions) (QuotasClientGetResponse, error) { + var err error + const operationName = "QuotasClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, location, quotaBucketName, options) + if err != nil { + return QuotasClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return QuotasClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return QuotasClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *QuotasClient) getCreateRequest(ctx context.Context, location string, quotaBucketName string, _ *QuotasClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.LoadTestService/locations/{location}/quotas/{quotaBucketName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if quotaBucketName == "" { + return nil, errors.New("parameter quotaBucketName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{quotaBucketName}", url.PathEscape(quotaBucketName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20241201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *QuotasClient) getHandleResponse(resp *http.Response) (QuotasClientGetResponse, error) { + result := QuotasClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.QuotaResource); err != nil { + return QuotasClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List quotas for a given subscription Id. +// - location - The name of the Azure region. +// - options - QuotasClientListOptions contains the optional parameters for the QuotasClient.NewListPager method. +func (client *QuotasClient) NewListPager(location string, options *QuotasClientListOptions) *runtime.Pager[QuotasClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[QuotasClientListResponse]{ + More: func(page QuotasClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *QuotasClientListResponse) (QuotasClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "QuotasClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, location, options) + }, nil) + if err != nil { + return QuotasClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *QuotasClient) listCreateRequest(ctx context.Context, location string, _ *QuotasClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.LoadTestService/locations/{location}/quotas" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20241201Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *QuotasClient) listHandleResponse(resp *http.Response) (QuotasClientListResponse, error) { + result := QuotasClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.QuotaResourceListResult); err != nil { + return QuotasClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armloadtestservice/zz_responses.go b/test/local/armloadtestservice/zz_responses.go new file mode 100644 index 000000000000..fdafc41f9f48 --- /dev/null +++ b/test/local/armloadtestservice/zz_responses.go @@ -0,0 +1,140 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armloadtestservice + +// LoadTestMappingsClientCreateOrUpdateResponse contains the response from method LoadTestMappingsClient.CreateOrUpdate. +type LoadTestMappingsClientCreateOrUpdateResponse struct { + // LoadTest mapping resource details + LoadTestMappingResource +} + +// LoadTestMappingsClientDeleteResponse contains the response from method LoadTestMappingsClient.Delete. +type LoadTestMappingsClientDeleteResponse struct { + // placeholder for future response values +} + +// LoadTestMappingsClientGetResponse contains the response from method LoadTestMappingsClient.Get. +type LoadTestMappingsClientGetResponse struct { + // LoadTest mapping resource details + LoadTestMappingResource +} + +// LoadTestMappingsClientListResponse contains the response from method LoadTestMappingsClient.NewListPager. +type LoadTestMappingsClientListResponse struct { + // The response of a LoadTestMappingResource list operation. + LoadTestMappingResourceListResult +} + +// LoadTestMappingsClientUpdateResponse contains the response from method LoadTestMappingsClient.Update. +type LoadTestMappingsClientUpdateResponse struct { + // LoadTest mapping resource details + LoadTestMappingResource +} + +// LoadTestProfileMappingsClientCreateOrUpdateResponse contains the response from method LoadTestProfileMappingsClient.CreateOrUpdate. +type LoadTestProfileMappingsClientCreateOrUpdateResponse struct { + // LoadTest profile mapping resource details + LoadTestProfileMappingResource +} + +// LoadTestProfileMappingsClientDeleteResponse contains the response from method LoadTestProfileMappingsClient.Delete. +type LoadTestProfileMappingsClientDeleteResponse struct { + // placeholder for future response values +} + +// LoadTestProfileMappingsClientGetResponse contains the response from method LoadTestProfileMappingsClient.Get. +type LoadTestProfileMappingsClientGetResponse struct { + // LoadTest profile mapping resource details + LoadTestProfileMappingResource +} + +// LoadTestProfileMappingsClientListResponse contains the response from method LoadTestProfileMappingsClient.NewListPager. +type LoadTestProfileMappingsClientListResponse struct { + // The response of a LoadTestProfileMappingResource list operation. + LoadTestProfileMappingResourceListResult +} + +// LoadTestProfileMappingsClientUpdateResponse contains the response from method LoadTestProfileMappingsClient.Update. +type LoadTestProfileMappingsClientUpdateResponse struct { + // LoadTest profile mapping resource details + LoadTestProfileMappingResource +} + +// LoadTestsClientCreateOrUpdateResponse contains the response from method LoadTestsClient.BeginCreateOrUpdate. +type LoadTestsClientCreateOrUpdateResponse struct { + // LoadTest details. + LoadTestResource +} + +// LoadTestsClientDeleteResponse contains the response from method LoadTestsClient.BeginDelete. +type LoadTestsClientDeleteResponse struct { + // placeholder for future response values +} + +// LoadTestsClientGetResponse contains the response from method LoadTestsClient.Get. +type LoadTestsClientGetResponse struct { + // LoadTest details. + LoadTestResource +} + +// LoadTestsClientListByResourceGroupResponse contains the response from method LoadTestsClient.NewListByResourceGroupPager. +type LoadTestsClientListByResourceGroupResponse struct { + // The response of a LoadTestResource list operation. + LoadTestResourceListResult +} + +// LoadTestsClientListBySubscriptionResponse contains the response from method LoadTestsClient.NewListBySubscriptionPager. +type LoadTestsClientListBySubscriptionResponse struct { + // The response of a LoadTestResource list operation. + LoadTestResourceListResult +} + +// LoadTestsClientOutboundNetworkDependenciesEndpointsResponse contains the response from method LoadTestsClient.NewOutboundNetworkDependenciesEndpointsPager. +type LoadTestsClientOutboundNetworkDependenciesEndpointsResponse struct { + // Values returned by the List operation. + PagedOutboundEnvironmentEndpoint +} + +// LoadTestsClientUpdateResponse contains the response from method LoadTestsClient.BeginUpdate. +type LoadTestsClientUpdateResponse struct { + // LoadTest details. + LoadTestResource +} + +// LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientGetResponse contains the response from method LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient.Get. +type LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientGetResponse struct { + // Max monthly virtual usage hours resource. + MaxMonthlyVirtualUserHoursResource +} + +// LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientSetResponse contains the response from method LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClient.Set. +type LoadTestsMaxMonthlyVirtualUserHoursLimitsResourceClientSetResponse struct { + // Max monthly virtual usage hours resource. + MaxMonthlyVirtualUserHoursResource +} + +// OperationsClientListResponse contains the response from method OperationsClient.NewListPager. +type OperationsClientListResponse struct { + // A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. + OperationListResult +} + +// QuotasClientCheckAvailabilityResponse contains the response from method QuotasClient.CheckAvailability. +type QuotasClientCheckAvailabilityResponse struct { + // Check quota availability response object. + CheckQuotaAvailabilityResponse +} + +// QuotasClientGetResponse contains the response from method QuotasClient.Get. +type QuotasClientGetResponse struct { + // Quota bucket details object. + QuotaResource +} + +// QuotasClientListResponse contains the response from method QuotasClient.NewListPager. +type QuotasClientListResponse struct { + // The response of a QuotaResource list operation. + QuotaResourceListResult +} diff --git a/test/local/armloadtestservice/zz_version.go b/test/local/armloadtestservice/zz_version.go new file mode 100644 index 000000000000..d88f354c5a8c --- /dev/null +++ b/test/local/armloadtestservice/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package armloadtestservice + +const ( + moduleName = "armloadtestservice" + moduleVersion = "v0.1.0" +) diff --git a/test/local/armmongocluster/LICENSE.txt b/test/local/armmongocluster/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/local/armmongocluster/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/local/armmongocluster/fake/zz_firewallrules_server.go b/test/local/armmongocluster/fake/zz_firewallrules_server.go new file mode 100644 index 000000000000..ba5328960371 --- /dev/null +++ b/test/local/armmongocluster/fake/zz_firewallrules_server.go @@ -0,0 +1,289 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armmongocluster" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// FirewallRulesServer is a fake server for instances of the armmongocluster.FirewallRulesClient type. +type FirewallRulesServer struct { + // BeginCreateOrUpdate is the fake for method FirewallRulesClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated, http.StatusAccepted + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, mongoClusterName string, firewallRuleName string, resource armmongocluster.FirewallRule, options *armmongocluster.FirewallRulesClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armmongocluster.FirewallRulesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method FirewallRulesClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, mongoClusterName string, firewallRuleName string, options *armmongocluster.FirewallRulesClientBeginDeleteOptions) (resp azfake.PollerResponder[armmongocluster.FirewallRulesClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method FirewallRulesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, mongoClusterName string, firewallRuleName string, options *armmongocluster.FirewallRulesClientGetOptions) (resp azfake.Responder[armmongocluster.FirewallRulesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByMongoClusterPager is the fake for method FirewallRulesClient.NewListByMongoClusterPager + // HTTP status codes to indicate success: http.StatusOK + NewListByMongoClusterPager func(resourceGroupName string, mongoClusterName string, options *armmongocluster.FirewallRulesClientListByMongoClusterOptions) (resp azfake.PagerResponder[armmongocluster.FirewallRulesClientListByMongoClusterResponse]) +} + +// NewFirewallRulesServerTransport creates a new instance of FirewallRulesServerTransport with the provided implementation. +// The returned FirewallRulesServerTransport instance is connected to an instance of armmongocluster.FirewallRulesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewFirewallRulesServerTransport(srv *FirewallRulesServer) *FirewallRulesServerTransport { + return &FirewallRulesServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armmongocluster.FirewallRulesClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armmongocluster.FirewallRulesClientDeleteResponse]](), + newListByMongoClusterPager: newTracker[azfake.PagerResponder[armmongocluster.FirewallRulesClientListByMongoClusterResponse]](), + } +} + +// FirewallRulesServerTransport connects instances of armmongocluster.FirewallRulesClient to instances of FirewallRulesServer. +// Don't use this type directly, use NewFirewallRulesServerTransport instead. +type FirewallRulesServerTransport struct { + srv *FirewallRulesServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armmongocluster.FirewallRulesClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armmongocluster.FirewallRulesClientDeleteResponse]] + newListByMongoClusterPager *tracker[azfake.PagerResponder[armmongocluster.FirewallRulesClientListByMongoClusterResponse]] +} + +// Do implements the policy.Transporter interface for FirewallRulesServerTransport. +func (f *FirewallRulesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return f.dispatchToMethodFake(req, method) +} + +func (f *FirewallRulesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if firewallRulesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = firewallRulesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "FirewallRulesClient.BeginCreateOrUpdate": + res.resp, res.err = f.dispatchBeginCreateOrUpdate(req) + case "FirewallRulesClient.BeginDelete": + res.resp, res.err = f.dispatchBeginDelete(req) + case "FirewallRulesClient.Get": + res.resp, res.err = f.dispatchGet(req) + case "FirewallRulesClient.NewListByMongoClusterPager": + res.resp, res.err = f.dispatchNewListByMongoClusterPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (f *FirewallRulesServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if f.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := f.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/mongoClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/firewallRules/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armmongocluster.FirewallRule](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + mongoClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("mongoClusterName")]) + if err != nil { + return nil, err + } + firewallRuleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("firewallRuleName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, mongoClusterNameParam, firewallRuleNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + f.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated, http.StatusAccepted}, resp.StatusCode) { + f.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + f.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (f *FirewallRulesServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if f.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := f.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/mongoClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/firewallRules/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + mongoClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("mongoClusterName")]) + if err != nil { + return nil, err + } + firewallRuleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("firewallRuleName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.BeginDelete(req.Context(), resourceGroupNameParam, mongoClusterNameParam, firewallRuleNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + f.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + f.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + f.beginDelete.remove(req) + } + + return resp, nil +} + +func (f *FirewallRulesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if f.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/mongoClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/firewallRules/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + mongoClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("mongoClusterName")]) + if err != nil { + return nil, err + } + firewallRuleNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("firewallRuleName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.Get(req.Context(), resourceGroupNameParam, mongoClusterNameParam, firewallRuleNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).FirewallRule, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (f *FirewallRulesServerTransport) dispatchNewListByMongoClusterPager(req *http.Request) (*http.Response, error) { + if f.srv.NewListByMongoClusterPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByMongoClusterPager not implemented")} + } + newListByMongoClusterPager := f.newListByMongoClusterPager.get(req) + if newListByMongoClusterPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/mongoClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/firewallRules` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + mongoClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("mongoClusterName")]) + if err != nil { + return nil, err + } + resp := f.srv.NewListByMongoClusterPager(resourceGroupNameParam, mongoClusterNameParam, nil) + newListByMongoClusterPager = &resp + f.newListByMongoClusterPager.add(req, newListByMongoClusterPager) + server.PagerResponderInjectNextLinks(newListByMongoClusterPager, req, func(page *armmongocluster.FirewallRulesClientListByMongoClusterResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByMongoClusterPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + f.newListByMongoClusterPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByMongoClusterPager) { + f.newListByMongoClusterPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to FirewallRulesServerTransport +var firewallRulesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armmongocluster/fake/zz_internal.go b/test/local/armmongocluster/fake/zz_internal.go new file mode 100644 index 000000000000..590b4d743e97 --- /dev/null +++ b/test/local/armmongocluster/fake/zz_internal.go @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/local/armmongocluster/fake/zz_mongoclusters_server.go b/test/local/armmongocluster/fake/zz_mongoclusters_server.go new file mode 100644 index 000000000000..867a1efd22c0 --- /dev/null +++ b/test/local/armmongocluster/fake/zz_mongoclusters_server.go @@ -0,0 +1,504 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armmongocluster" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// MongoClustersServer is a fake server for instances of the armmongocluster.MongoClustersClient type. +type MongoClustersServer struct { + // CheckNameAvailability is the fake for method MongoClustersClient.CheckNameAvailability + // HTTP status codes to indicate success: http.StatusOK + CheckNameAvailability func(ctx context.Context, location string, body armmongocluster.CheckNameAvailabilityRequest, options *armmongocluster.MongoClustersClientCheckNameAvailabilityOptions) (resp azfake.Responder[armmongocluster.MongoClustersClientCheckNameAvailabilityResponse], errResp azfake.ErrorResponder) + + // BeginCreateOrUpdate is the fake for method MongoClustersClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, mongoClusterName string, resource armmongocluster.MongoCluster, options *armmongocluster.MongoClustersClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armmongocluster.MongoClustersClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method MongoClustersClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, mongoClusterName string, options *armmongocluster.MongoClustersClientBeginDeleteOptions) (resp azfake.PollerResponder[armmongocluster.MongoClustersClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method MongoClustersClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, mongoClusterName string, options *armmongocluster.MongoClustersClientGetOptions) (resp azfake.Responder[armmongocluster.MongoClustersClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method MongoClustersClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armmongocluster.MongoClustersClientListOptions) (resp azfake.PagerResponder[armmongocluster.MongoClustersClientListResponse]) + + // NewListByResourceGroupPager is the fake for method MongoClustersClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armmongocluster.MongoClustersClientListByResourceGroupOptions) (resp azfake.PagerResponder[armmongocluster.MongoClustersClientListByResourceGroupResponse]) + + // ListConnectionStrings is the fake for method MongoClustersClient.ListConnectionStrings + // HTTP status codes to indicate success: http.StatusOK + ListConnectionStrings func(ctx context.Context, resourceGroupName string, mongoClusterName string, options *armmongocluster.MongoClustersClientListConnectionStringsOptions) (resp azfake.Responder[armmongocluster.MongoClustersClientListConnectionStringsResponse], errResp azfake.ErrorResponder) + + // BeginPromote is the fake for method MongoClustersClient.BeginPromote + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginPromote func(ctx context.Context, resourceGroupName string, mongoClusterName string, body armmongocluster.PromoteReplicaRequest, options *armmongocluster.MongoClustersClientBeginPromoteOptions) (resp azfake.PollerResponder[armmongocluster.MongoClustersClientPromoteResponse], errResp azfake.ErrorResponder) + + // BeginUpdate is the fake for method MongoClustersClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, mongoClusterName string, properties armmongocluster.Update, options *armmongocluster.MongoClustersClientBeginUpdateOptions) (resp azfake.PollerResponder[armmongocluster.MongoClustersClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewMongoClustersServerTransport creates a new instance of MongoClustersServerTransport with the provided implementation. +// The returned MongoClustersServerTransport instance is connected to an instance of armmongocluster.MongoClustersClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewMongoClustersServerTransport(srv *MongoClustersServer) *MongoClustersServerTransport { + return &MongoClustersServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armmongocluster.MongoClustersClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armmongocluster.MongoClustersClientDeleteResponse]](), + newListPager: newTracker[azfake.PagerResponder[armmongocluster.MongoClustersClientListResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armmongocluster.MongoClustersClientListByResourceGroupResponse]](), + beginPromote: newTracker[azfake.PollerResponder[armmongocluster.MongoClustersClientPromoteResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armmongocluster.MongoClustersClientUpdateResponse]](), + } +} + +// MongoClustersServerTransport connects instances of armmongocluster.MongoClustersClient to instances of MongoClustersServer. +// Don't use this type directly, use NewMongoClustersServerTransport instead. +type MongoClustersServerTransport struct { + srv *MongoClustersServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armmongocluster.MongoClustersClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armmongocluster.MongoClustersClientDeleteResponse]] + newListPager *tracker[azfake.PagerResponder[armmongocluster.MongoClustersClientListResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armmongocluster.MongoClustersClientListByResourceGroupResponse]] + beginPromote *tracker[azfake.PollerResponder[armmongocluster.MongoClustersClientPromoteResponse]] + beginUpdate *tracker[azfake.PollerResponder[armmongocluster.MongoClustersClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for MongoClustersServerTransport. +func (m *MongoClustersServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToMethodFake(req, method) +} + +func (m *MongoClustersServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if mongoClustersServerTransportInterceptor != nil { + res.resp, res.err, intercepted = mongoClustersServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "MongoClustersClient.CheckNameAvailability": + res.resp, res.err = m.dispatchCheckNameAvailability(req) + case "MongoClustersClient.BeginCreateOrUpdate": + res.resp, res.err = m.dispatchBeginCreateOrUpdate(req) + case "MongoClustersClient.BeginDelete": + res.resp, res.err = m.dispatchBeginDelete(req) + case "MongoClustersClient.Get": + res.resp, res.err = m.dispatchGet(req) + case "MongoClustersClient.NewListPager": + res.resp, res.err = m.dispatchNewListPager(req) + case "MongoClustersClient.NewListByResourceGroupPager": + res.resp, res.err = m.dispatchNewListByResourceGroupPager(req) + case "MongoClustersClient.ListConnectionStrings": + res.resp, res.err = m.dispatchListConnectionStrings(req) + case "MongoClustersClient.BeginPromote": + res.resp, res.err = m.dispatchBeginPromote(req) + case "MongoClustersClient.BeginUpdate": + res.resp, res.err = m.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *MongoClustersServerTransport) dispatchCheckNameAvailability(req *http.Request) (*http.Response, error) { + if m.srv.CheckNameAvailability == nil { + return nil, &nonRetriableError{errors.New("fake for method CheckNameAvailability not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/checkMongoClusterNameAvailability` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armmongocluster.CheckNameAvailabilityRequest](req) + if err != nil { + return nil, err + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.CheckNameAvailability(req.Context(), locationParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CheckNameAvailabilityResponse, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *MongoClustersServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if m.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := m.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/mongoClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armmongocluster.MongoCluster](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + mongoClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("mongoClusterName")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, mongoClusterNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + m.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + m.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + m.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (m *MongoClustersServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if m.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := m.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/mongoClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + mongoClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("mongoClusterName")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.BeginDelete(req.Context(), resourceGroupNameParam, mongoClusterNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + m.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + m.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + m.beginDelete.remove(req) + } + + return resp, nil +} + +func (m *MongoClustersServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if m.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/mongoClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + mongoClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("mongoClusterName")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.Get(req.Context(), resourceGroupNameParam, mongoClusterNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).MongoCluster, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *MongoClustersServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if m.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := m.newListPager.get(req) + if newListPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/mongoClusters` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := m.srv.NewListPager(nil) + newListPager = &resp + m.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armmongocluster.MongoClustersClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + m.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + m.newListPager.remove(req) + } + return resp, nil +} + +func (m *MongoClustersServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if m.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := m.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/mongoClusters` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := m.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + m.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armmongocluster.MongoClustersClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + m.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + m.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (m *MongoClustersServerTransport) dispatchListConnectionStrings(req *http.Request) (*http.Response, error) { + if m.srv.ListConnectionStrings == nil { + return nil, &nonRetriableError{errors.New("fake for method ListConnectionStrings not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/mongoClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/listConnectionStrings` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + mongoClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("mongoClusterName")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.ListConnectionStrings(req.Context(), resourceGroupNameParam, mongoClusterNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ListConnectionStringsResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *MongoClustersServerTransport) dispatchBeginPromote(req *http.Request) (*http.Response, error) { + if m.srv.BeginPromote == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginPromote not implemented")} + } + beginPromote := m.beginPromote.get(req) + if beginPromote == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/mongoClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/promote` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armmongocluster.PromoteReplicaRequest](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + mongoClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("mongoClusterName")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.BeginPromote(req.Context(), resourceGroupNameParam, mongoClusterNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginPromote = &respr + m.beginPromote.add(req, beginPromote) + } + + resp, err := server.PollerResponderNext(beginPromote, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + m.beginPromote.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginPromote) { + m.beginPromote.remove(req) + } + + return resp, nil +} + +func (m *MongoClustersServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if m.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := m.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/mongoClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armmongocluster.Update](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + mongoClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("mongoClusterName")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.BeginUpdate(req.Context(), resourceGroupNameParam, mongoClusterNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + m.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + m.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + m.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to MongoClustersServerTransport +var mongoClustersServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armmongocluster/fake/zz_operations_server.go b/test/local/armmongocluster/fake/zz_operations_server.go new file mode 100644 index 000000000000..aa2c216ffc70 --- /dev/null +++ b/test/local/armmongocluster/fake/zz_operations_server.go @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armmongocluster" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "slices" +) + +// OperationsServer is a fake server for instances of the armmongocluster.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armmongocluster.OperationsClientListOptions) (resp azfake.PagerResponder[armmongocluster.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of armmongocluster.OperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOperationsServerTransport(srv *OperationsServer) *OperationsServerTransport { + return &OperationsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armmongocluster.OperationsClientListResponse]](), + } +} + +// OperationsServerTransport connects instances of armmongocluster.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[armmongocluster.OperationsClientListResponse]] +} + +// Do implements the policy.Transporter interface for OperationsServerTransport. +func (o *OperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if operationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = operationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OperationsClient.NewListPager": + res.resp, res.err = o.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OperationsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := o.newListPager.get(req) + if newListPager == nil { + resp := o.srv.NewListPager(nil) + newListPager = &resp + o.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armmongocluster.OperationsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + o.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + o.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OperationsServerTransport +var operationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armmongocluster/fake/zz_privateendpointconnections_server.go b/test/local/armmongocluster/fake/zz_privateendpointconnections_server.go new file mode 100644 index 000000000000..87eba32819d0 --- /dev/null +++ b/test/local/armmongocluster/fake/zz_privateendpointconnections_server.go @@ -0,0 +1,289 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armmongocluster" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// PrivateEndpointConnectionsServer is a fake server for instances of the armmongocluster.PrivateEndpointConnectionsClient type. +type PrivateEndpointConnectionsServer struct { + // BeginCreate is the fake for method PrivateEndpointConnectionsClient.BeginCreate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated, http.StatusAccepted + BeginCreate func(ctx context.Context, resourceGroupName string, mongoClusterName string, privateEndpointConnectionName string, resource armmongocluster.PrivateEndpointConnectionResource, options *armmongocluster.PrivateEndpointConnectionsClientBeginCreateOptions) (resp azfake.PollerResponder[armmongocluster.PrivateEndpointConnectionsClientCreateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method PrivateEndpointConnectionsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, mongoClusterName string, privateEndpointConnectionName string, options *armmongocluster.PrivateEndpointConnectionsClientBeginDeleteOptions) (resp azfake.PollerResponder[armmongocluster.PrivateEndpointConnectionsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method PrivateEndpointConnectionsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, mongoClusterName string, privateEndpointConnectionName string, options *armmongocluster.PrivateEndpointConnectionsClientGetOptions) (resp azfake.Responder[armmongocluster.PrivateEndpointConnectionsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByMongoClusterPager is the fake for method PrivateEndpointConnectionsClient.NewListByMongoClusterPager + // HTTP status codes to indicate success: http.StatusOK + NewListByMongoClusterPager func(resourceGroupName string, mongoClusterName string, options *armmongocluster.PrivateEndpointConnectionsClientListByMongoClusterOptions) (resp azfake.PagerResponder[armmongocluster.PrivateEndpointConnectionsClientListByMongoClusterResponse]) +} + +// NewPrivateEndpointConnectionsServerTransport creates a new instance of PrivateEndpointConnectionsServerTransport with the provided implementation. +// The returned PrivateEndpointConnectionsServerTransport instance is connected to an instance of armmongocluster.PrivateEndpointConnectionsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewPrivateEndpointConnectionsServerTransport(srv *PrivateEndpointConnectionsServer) *PrivateEndpointConnectionsServerTransport { + return &PrivateEndpointConnectionsServerTransport{ + srv: srv, + beginCreate: newTracker[azfake.PollerResponder[armmongocluster.PrivateEndpointConnectionsClientCreateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armmongocluster.PrivateEndpointConnectionsClientDeleteResponse]](), + newListByMongoClusterPager: newTracker[azfake.PagerResponder[armmongocluster.PrivateEndpointConnectionsClientListByMongoClusterResponse]](), + } +} + +// PrivateEndpointConnectionsServerTransport connects instances of armmongocluster.PrivateEndpointConnectionsClient to instances of PrivateEndpointConnectionsServer. +// Don't use this type directly, use NewPrivateEndpointConnectionsServerTransport instead. +type PrivateEndpointConnectionsServerTransport struct { + srv *PrivateEndpointConnectionsServer + beginCreate *tracker[azfake.PollerResponder[armmongocluster.PrivateEndpointConnectionsClientCreateResponse]] + beginDelete *tracker[azfake.PollerResponder[armmongocluster.PrivateEndpointConnectionsClientDeleteResponse]] + newListByMongoClusterPager *tracker[azfake.PagerResponder[armmongocluster.PrivateEndpointConnectionsClientListByMongoClusterResponse]] +} + +// Do implements the policy.Transporter interface for PrivateEndpointConnectionsServerTransport. +func (p *PrivateEndpointConnectionsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return p.dispatchToMethodFake(req, method) +} + +func (p *PrivateEndpointConnectionsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if privateEndpointConnectionsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = privateEndpointConnectionsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "PrivateEndpointConnectionsClient.BeginCreate": + res.resp, res.err = p.dispatchBeginCreate(req) + case "PrivateEndpointConnectionsClient.BeginDelete": + res.resp, res.err = p.dispatchBeginDelete(req) + case "PrivateEndpointConnectionsClient.Get": + res.resp, res.err = p.dispatchGet(req) + case "PrivateEndpointConnectionsClient.NewListByMongoClusterPager": + res.resp, res.err = p.dispatchNewListByMongoClusterPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (p *PrivateEndpointConnectionsServerTransport) dispatchBeginCreate(req *http.Request) (*http.Response, error) { + if p.srv.BeginCreate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreate not implemented")} + } + beginCreate := p.beginCreate.get(req) + if beginCreate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/mongoClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/privateEndpointConnections/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armmongocluster.PrivateEndpointConnectionResource](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + mongoClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("mongoClusterName")]) + if err != nil { + return nil, err + } + privateEndpointConnectionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("privateEndpointConnectionName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.BeginCreate(req.Context(), resourceGroupNameParam, mongoClusterNameParam, privateEndpointConnectionNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreate = &respr + p.beginCreate.add(req, beginCreate) + } + + resp, err := server.PollerResponderNext(beginCreate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated, http.StatusAccepted}, resp.StatusCode) { + p.beginCreate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreate) { + p.beginCreate.remove(req) + } + + return resp, nil +} + +func (p *PrivateEndpointConnectionsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if p.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := p.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/mongoClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/privateEndpointConnections/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + mongoClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("mongoClusterName")]) + if err != nil { + return nil, err + } + privateEndpointConnectionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("privateEndpointConnectionName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.BeginDelete(req.Context(), resourceGroupNameParam, mongoClusterNameParam, privateEndpointConnectionNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + p.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + p.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + p.beginDelete.remove(req) + } + + return resp, nil +} + +func (p *PrivateEndpointConnectionsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if p.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/mongoClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/privateEndpointConnections/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + mongoClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("mongoClusterName")]) + if err != nil { + return nil, err + } + privateEndpointConnectionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("privateEndpointConnectionName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.Get(req.Context(), resourceGroupNameParam, mongoClusterNameParam, privateEndpointConnectionNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).PrivateEndpointConnectionResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (p *PrivateEndpointConnectionsServerTransport) dispatchNewListByMongoClusterPager(req *http.Request) (*http.Response, error) { + if p.srv.NewListByMongoClusterPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByMongoClusterPager not implemented")} + } + newListByMongoClusterPager := p.newListByMongoClusterPager.get(req) + if newListByMongoClusterPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/mongoClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/privateEndpointConnections` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + mongoClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("mongoClusterName")]) + if err != nil { + return nil, err + } + resp := p.srv.NewListByMongoClusterPager(resourceGroupNameParam, mongoClusterNameParam, nil) + newListByMongoClusterPager = &resp + p.newListByMongoClusterPager.add(req, newListByMongoClusterPager) + server.PagerResponderInjectNextLinks(newListByMongoClusterPager, req, func(page *armmongocluster.PrivateEndpointConnectionsClientListByMongoClusterResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByMongoClusterPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newListByMongoClusterPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByMongoClusterPager) { + p.newListByMongoClusterPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to PrivateEndpointConnectionsServerTransport +var privateEndpointConnectionsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armmongocluster/fake/zz_privatelinks_server.go b/test/local/armmongocluster/fake/zz_privatelinks_server.go new file mode 100644 index 000000000000..dd1eb1117ada --- /dev/null +++ b/test/local/armmongocluster/fake/zz_privatelinks_server.go @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armmongocluster" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// PrivateLinksServer is a fake server for instances of the armmongocluster.PrivateLinksClient type. +type PrivateLinksServer struct { + // NewListByMongoClusterPager is the fake for method PrivateLinksClient.NewListByMongoClusterPager + // HTTP status codes to indicate success: http.StatusOK + NewListByMongoClusterPager func(resourceGroupName string, mongoClusterName string, options *armmongocluster.PrivateLinksClientListByMongoClusterOptions) (resp azfake.PagerResponder[armmongocluster.PrivateLinksClientListByMongoClusterResponse]) +} + +// NewPrivateLinksServerTransport creates a new instance of PrivateLinksServerTransport with the provided implementation. +// The returned PrivateLinksServerTransport instance is connected to an instance of armmongocluster.PrivateLinksClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewPrivateLinksServerTransport(srv *PrivateLinksServer) *PrivateLinksServerTransport { + return &PrivateLinksServerTransport{ + srv: srv, + newListByMongoClusterPager: newTracker[azfake.PagerResponder[armmongocluster.PrivateLinksClientListByMongoClusterResponse]](), + } +} + +// PrivateLinksServerTransport connects instances of armmongocluster.PrivateLinksClient to instances of PrivateLinksServer. +// Don't use this type directly, use NewPrivateLinksServerTransport instead. +type PrivateLinksServerTransport struct { + srv *PrivateLinksServer + newListByMongoClusterPager *tracker[azfake.PagerResponder[armmongocluster.PrivateLinksClientListByMongoClusterResponse]] +} + +// Do implements the policy.Transporter interface for PrivateLinksServerTransport. +func (p *PrivateLinksServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return p.dispatchToMethodFake(req, method) +} + +func (p *PrivateLinksServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if privateLinksServerTransportInterceptor != nil { + res.resp, res.err, intercepted = privateLinksServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "PrivateLinksClient.NewListByMongoClusterPager": + res.resp, res.err = p.dispatchNewListByMongoClusterPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (p *PrivateLinksServerTransport) dispatchNewListByMongoClusterPager(req *http.Request) (*http.Response, error) { + if p.srv.NewListByMongoClusterPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByMongoClusterPager not implemented")} + } + newListByMongoClusterPager := p.newListByMongoClusterPager.get(req) + if newListByMongoClusterPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/mongoClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/privateLinkResources` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + mongoClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("mongoClusterName")]) + if err != nil { + return nil, err + } + resp := p.srv.NewListByMongoClusterPager(resourceGroupNameParam, mongoClusterNameParam, nil) + newListByMongoClusterPager = &resp + p.newListByMongoClusterPager.add(req, newListByMongoClusterPager) + server.PagerResponderInjectNextLinks(newListByMongoClusterPager, req, func(page *armmongocluster.PrivateLinksClientListByMongoClusterResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByMongoClusterPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + p.newListByMongoClusterPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByMongoClusterPager) { + p.newListByMongoClusterPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to PrivateLinksServerTransport +var privateLinksServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armmongocluster/fake/zz_replicas_server.go b/test/local/armmongocluster/fake/zz_replicas_server.go new file mode 100644 index 000000000000..def91b00f751 --- /dev/null +++ b/test/local/armmongocluster/fake/zz_replicas_server.go @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armmongocluster" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// ReplicasServer is a fake server for instances of the armmongocluster.ReplicasClient type. +type ReplicasServer struct { + // NewListByParentPager is the fake for method ReplicasClient.NewListByParentPager + // HTTP status codes to indicate success: http.StatusOK + NewListByParentPager func(resourceGroupName string, mongoClusterName string, options *armmongocluster.ReplicasClientListByParentOptions) (resp azfake.PagerResponder[armmongocluster.ReplicasClientListByParentResponse]) +} + +// NewReplicasServerTransport creates a new instance of ReplicasServerTransport with the provided implementation. +// The returned ReplicasServerTransport instance is connected to an instance of armmongocluster.ReplicasClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewReplicasServerTransport(srv *ReplicasServer) *ReplicasServerTransport { + return &ReplicasServerTransport{ + srv: srv, + newListByParentPager: newTracker[azfake.PagerResponder[armmongocluster.ReplicasClientListByParentResponse]](), + } +} + +// ReplicasServerTransport connects instances of armmongocluster.ReplicasClient to instances of ReplicasServer. +// Don't use this type directly, use NewReplicasServerTransport instead. +type ReplicasServerTransport struct { + srv *ReplicasServer + newListByParentPager *tracker[azfake.PagerResponder[armmongocluster.ReplicasClientListByParentResponse]] +} + +// Do implements the policy.Transporter interface for ReplicasServerTransport. +func (r *ReplicasServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return r.dispatchToMethodFake(req, method) +} + +func (r *ReplicasServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if replicasServerTransportInterceptor != nil { + res.resp, res.err, intercepted = replicasServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ReplicasClient.NewListByParentPager": + res.resp, res.err = r.dispatchNewListByParentPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (r *ReplicasServerTransport) dispatchNewListByParentPager(req *http.Request) (*http.Response, error) { + if r.srv.NewListByParentPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByParentPager not implemented")} + } + newListByParentPager := r.newListByParentPager.get(req) + if newListByParentPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/mongoClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/replicas` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + mongoClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("mongoClusterName")]) + if err != nil { + return nil, err + } + resp := r.srv.NewListByParentPager(resourceGroupNameParam, mongoClusterNameParam, nil) + newListByParentPager = &resp + r.newListByParentPager.add(req, newListByParentPager) + server.PagerResponderInjectNextLinks(newListByParentPager, req, func(page *armmongocluster.ReplicasClientListByParentResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByParentPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + r.newListByParentPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByParentPager) { + r.newListByParentPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ReplicasServerTransport +var replicasServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armmongocluster/fake/zz_server_factory.go b/test/local/armmongocluster/fake/zz_server_factory.go new file mode 100644 index 000000000000..2eb240159ffe --- /dev/null +++ b/test/local/armmongocluster/fake/zz_server_factory.go @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armmongocluster.ClientFactory type. +type ServerFactory struct { + // FirewallRulesServer contains the fakes for client FirewallRulesClient + FirewallRulesServer FirewallRulesServer + + // MongoClustersServer contains the fakes for client MongoClustersClient + MongoClustersServer MongoClustersServer + + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer + + // PrivateEndpointConnectionsServer contains the fakes for client PrivateEndpointConnectionsClient + PrivateEndpointConnectionsServer PrivateEndpointConnectionsServer + + // PrivateLinksServer contains the fakes for client PrivateLinksClient + PrivateLinksServer PrivateLinksServer + + // ReplicasServer contains the fakes for client ReplicasClient + ReplicasServer ReplicasServer + + // UsersServer contains the fakes for client UsersClient + UsersServer UsersServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armmongocluster.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of armmongocluster.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trFirewallRulesServer *FirewallRulesServerTransport + trMongoClustersServer *MongoClustersServerTransport + trOperationsServer *OperationsServerTransport + trPrivateEndpointConnectionsServer *PrivateEndpointConnectionsServerTransport + trPrivateLinksServer *PrivateLinksServerTransport + trReplicasServer *ReplicasServerTransport + trUsersServer *UsersServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "FirewallRulesClient": + initServer(&s.trMu, &s.trFirewallRulesServer, func() *FirewallRulesServerTransport { + return NewFirewallRulesServerTransport(&s.srv.FirewallRulesServer) + }) + resp, err = s.trFirewallRulesServer.Do(req) + case "MongoClustersClient": + initServer(&s.trMu, &s.trMongoClustersServer, func() *MongoClustersServerTransport { + return NewMongoClustersServerTransport(&s.srv.MongoClustersServer) + }) + resp, err = s.trMongoClustersServer.Do(req) + case "OperationsClient": + initServer(&s.trMu, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + resp, err = s.trOperationsServer.Do(req) + case "PrivateEndpointConnectionsClient": + initServer(&s.trMu, &s.trPrivateEndpointConnectionsServer, func() *PrivateEndpointConnectionsServerTransport { + return NewPrivateEndpointConnectionsServerTransport(&s.srv.PrivateEndpointConnectionsServer) + }) + resp, err = s.trPrivateEndpointConnectionsServer.Do(req) + case "PrivateLinksClient": + initServer(&s.trMu, &s.trPrivateLinksServer, func() *PrivateLinksServerTransport { return NewPrivateLinksServerTransport(&s.srv.PrivateLinksServer) }) + resp, err = s.trPrivateLinksServer.Do(req) + case "ReplicasClient": + initServer(&s.trMu, &s.trReplicasServer, func() *ReplicasServerTransport { return NewReplicasServerTransport(&s.srv.ReplicasServer) }) + resp, err = s.trReplicasServer.Do(req) + case "UsersClient": + initServer(&s.trMu, &s.trUsersServer, func() *UsersServerTransport { return NewUsersServerTransport(&s.srv.UsersServer) }) + resp, err = s.trUsersServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} diff --git a/test/local/armmongocluster/fake/zz_users_server.go b/test/local/armmongocluster/fake/zz_users_server.go new file mode 100644 index 000000000000..b09eeade2efa --- /dev/null +++ b/test/local/armmongocluster/fake/zz_users_server.go @@ -0,0 +1,289 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armmongocluster" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// UsersServer is a fake server for instances of the armmongocluster.UsersClient type. +type UsersServer struct { + // BeginCreateOrUpdate is the fake for method UsersClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, mongoClusterName string, userName string, resource armmongocluster.User, options *armmongocluster.UsersClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armmongocluster.UsersClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method UsersClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, mongoClusterName string, userName string, options *armmongocluster.UsersClientBeginDeleteOptions) (resp azfake.PollerResponder[armmongocluster.UsersClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method UsersClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, mongoClusterName string, userName string, options *armmongocluster.UsersClientGetOptions) (resp azfake.Responder[armmongocluster.UsersClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByMongoClusterPager is the fake for method UsersClient.NewListByMongoClusterPager + // HTTP status codes to indicate success: http.StatusOK + NewListByMongoClusterPager func(resourceGroupName string, mongoClusterName string, options *armmongocluster.UsersClientListByMongoClusterOptions) (resp azfake.PagerResponder[armmongocluster.UsersClientListByMongoClusterResponse]) +} + +// NewUsersServerTransport creates a new instance of UsersServerTransport with the provided implementation. +// The returned UsersServerTransport instance is connected to an instance of armmongocluster.UsersClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewUsersServerTransport(srv *UsersServer) *UsersServerTransport { + return &UsersServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armmongocluster.UsersClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armmongocluster.UsersClientDeleteResponse]](), + newListByMongoClusterPager: newTracker[azfake.PagerResponder[armmongocluster.UsersClientListByMongoClusterResponse]](), + } +} + +// UsersServerTransport connects instances of armmongocluster.UsersClient to instances of UsersServer. +// Don't use this type directly, use NewUsersServerTransport instead. +type UsersServerTransport struct { + srv *UsersServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armmongocluster.UsersClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armmongocluster.UsersClientDeleteResponse]] + newListByMongoClusterPager *tracker[azfake.PagerResponder[armmongocluster.UsersClientListByMongoClusterResponse]] +} + +// Do implements the policy.Transporter interface for UsersServerTransport. +func (u *UsersServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return u.dispatchToMethodFake(req, method) +} + +func (u *UsersServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if usersServerTransportInterceptor != nil { + res.resp, res.err, intercepted = usersServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "UsersClient.BeginCreateOrUpdate": + res.resp, res.err = u.dispatchBeginCreateOrUpdate(req) + case "UsersClient.BeginDelete": + res.resp, res.err = u.dispatchBeginDelete(req) + case "UsersClient.Get": + res.resp, res.err = u.dispatchGet(req) + case "UsersClient.NewListByMongoClusterPager": + res.resp, res.err = u.dispatchNewListByMongoClusterPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (u *UsersServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if u.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := u.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/mongoClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/users/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armmongocluster.User](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + mongoClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("mongoClusterName")]) + if err != nil { + return nil, err + } + userNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("userName")]) + if err != nil { + return nil, err + } + respr, errRespr := u.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, mongoClusterNameParam, userNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + u.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + u.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + u.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (u *UsersServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if u.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := u.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/mongoClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/users/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + mongoClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("mongoClusterName")]) + if err != nil { + return nil, err + } + userNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("userName")]) + if err != nil { + return nil, err + } + respr, errRespr := u.srv.BeginDelete(req.Context(), resourceGroupNameParam, mongoClusterNameParam, userNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + u.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + u.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + u.beginDelete.remove(req) + } + + return resp, nil +} + +func (u *UsersServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if u.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/mongoClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/users/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + mongoClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("mongoClusterName")]) + if err != nil { + return nil, err + } + userNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("userName")]) + if err != nil { + return nil, err + } + respr, errRespr := u.srv.Get(req.Context(), resourceGroupNameParam, mongoClusterNameParam, userNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).User, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (u *UsersServerTransport) dispatchNewListByMongoClusterPager(req *http.Request) (*http.Response, error) { + if u.srv.NewListByMongoClusterPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByMongoClusterPager not implemented")} + } + newListByMongoClusterPager := u.newListByMongoClusterPager.get(req) + if newListByMongoClusterPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.DocumentDB/mongoClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/users` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + mongoClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("mongoClusterName")]) + if err != nil { + return nil, err + } + resp := u.srv.NewListByMongoClusterPager(resourceGroupNameParam, mongoClusterNameParam, nil) + newListByMongoClusterPager = &resp + u.newListByMongoClusterPager.add(req, newListByMongoClusterPager) + server.PagerResponderInjectNextLinks(newListByMongoClusterPager, req, func(page *armmongocluster.UsersClientListByMongoClusterResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByMongoClusterPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + u.newListByMongoClusterPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByMongoClusterPager) { + u.newListByMongoClusterPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to UsersServerTransport +var usersServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armmongocluster/go.mod b/test/local/armmongocluster/go.mod new file mode 100644 index 000000000000..d9f34ca9c413 --- /dev/null +++ b/test/local/armmongocluster/go.mod @@ -0,0 +1,11 @@ +module armmongocluster + +go 1.25.0 + +require github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect +) diff --git a/test/local/armmongocluster/go.sum b/test/local/armmongocluster/go.sum new file mode 100644 index 000000000000..3fdb64caf441 --- /dev/null +++ b/test/local/armmongocluster/go.sum @@ -0,0 +1,16 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/local/armmongocluster/testdata/_metadata.json b/test/local/armmongocluster/testdata/_metadata.json new file mode 100644 index 000000000000..c7f52f85daa4 --- /dev/null +++ b/test/local/armmongocluster/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Microsoft.DocumentDB": "2026-06-01" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/local/armmongocluster/zz_client_factory.go b/test/local/armmongocluster/zz_client_factory.go new file mode 100644 index 000000000000..579b7cda06ff --- /dev/null +++ b/test/local/armmongocluster/zz_client_factory.go @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmongocluster + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + subscriptionID string + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, + internal: internal, + }, nil +} + +// NewFirewallRulesClient creates a new instance of FirewallRulesClient. +func (c *ClientFactory) NewFirewallRulesClient() *FirewallRulesClient { + return &FirewallRulesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewMongoClustersClient creates a new instance of MongoClustersClient. +func (c *ClientFactory) NewMongoClustersClient() *MongoClustersClient { + return &MongoClustersClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: c.internal, + } +} + +// NewPrivateEndpointConnectionsClient creates a new instance of PrivateEndpointConnectionsClient. +func (c *ClientFactory) NewPrivateEndpointConnectionsClient() *PrivateEndpointConnectionsClient { + return &PrivateEndpointConnectionsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewPrivateLinksClient creates a new instance of PrivateLinksClient. +func (c *ClientFactory) NewPrivateLinksClient() *PrivateLinksClient { + return &PrivateLinksClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewReplicasClient creates a new instance of ReplicasClient. +func (c *ClientFactory) NewReplicasClient() *ReplicasClient { + return &ReplicasClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewUsersClient creates a new instance of UsersClient. +func (c *ClientFactory) NewUsersClient() *UsersClient { + return &UsersClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} diff --git a/test/local/armmongocluster/zz_constants.go b/test/local/armmongocluster/zz_constants.go new file mode 100644 index 000000000000..99244bc5ec6c --- /dev/null +++ b/test/local/armmongocluster/zz_constants.go @@ -0,0 +1,523 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmongocluster + +const ( + version20260601 string = "2026-06-01" +) + +// ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +type ActionType string + +const ( + // ActionTypeInternal - Actions are for internal-only APIs. + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// AuthenticationMode - The authentication modes supporting on the Mongo cluster. +type AuthenticationMode string + +const ( + // AuthenticationModeMicrosoftEntraID - Microsoft Entra ID authentication mode using Entra users assigned to the cluster and + // auth mechanism 'MONGODB-OIDC'. + AuthenticationModeMicrosoftEntraID AuthenticationMode = "MicrosoftEntraID" + // AuthenticationModeNativeAuth - Native mongo authentication mode using username and password with auth mechanism 'SCRAM-SHA-256'. + AuthenticationModeNativeAuth AuthenticationMode = "NativeAuth" +) + +// PossibleAuthenticationModeValues returns the possible values for the AuthenticationMode const type. +func PossibleAuthenticationModeValues() []AuthenticationMode { + return []AuthenticationMode{ + AuthenticationModeMicrosoftEntraID, + AuthenticationModeNativeAuth, + } +} + +// CheckNameAvailabilityReason - Possible reasons for a name not being available. +type CheckNameAvailabilityReason string + +const ( + // CheckNameAvailabilityReasonAlreadyExists - Name already exists. + CheckNameAvailabilityReasonAlreadyExists CheckNameAvailabilityReason = "AlreadyExists" + // CheckNameAvailabilityReasonInvalid - Name is invalid. + CheckNameAvailabilityReasonInvalid CheckNameAvailabilityReason = "Invalid" +) + +// PossibleCheckNameAvailabilityReasonValues returns the possible values for the CheckNameAvailabilityReason const type. +func PossibleCheckNameAvailabilityReasonValues() []CheckNameAvailabilityReason { + return []CheckNameAvailabilityReason{ + CheckNameAvailabilityReasonAlreadyExists, + CheckNameAvailabilityReasonInvalid, + } +} + +// CreateMode - The mode that the Mongo Cluster is created with. +type CreateMode string + +const ( + // CreateModeDefault - Create a new mongo cluster. + CreateModeDefault CreateMode = "Default" + // CreateModeGeoReplica - Create a replica cluster in distinct geographic region from the source cluster. + CreateModeGeoReplica CreateMode = "GeoReplica" + // CreateModePointInTimeRestore - Create a mongo cluster from a restore point-in-time. + CreateModePointInTimeRestore CreateMode = "PointInTimeRestore" + // CreateModeReplica - Create a replica cluster in the same geographic region as the source cluster. + CreateModeReplica CreateMode = "Replica" +) + +// PossibleCreateModeValues returns the possible values for the CreateMode const type. +func PossibleCreateModeValues() []CreateMode { + return []CreateMode{ + CreateModeDefault, + CreateModeGeoReplica, + CreateModePointInTimeRestore, + CreateModeReplica, + } +} + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// DataAPIMode - The mode to apply to the Mongo Data API. +type DataAPIMode string + +const ( + // DataAPIModeDisabled - Mongo Data API is disabled for the cluster. + DataAPIModeDisabled DataAPIMode = "Disabled" + // DataAPIModeEnabled - Mongo Data API is enabled for the cluster. + DataAPIModeEnabled DataAPIMode = "Enabled" +) + +// PossibleDataAPIModeValues returns the possible values for the DataAPIMode const type. +func PossibleDataAPIModeValues() []DataAPIMode { + return []DataAPIMode{ + DataAPIModeDisabled, + DataAPIModeEnabled, + } +} + +// EntraPrincipalType - Microsoft Entra ID principal types available for a Mongo user. +type EntraPrincipalType string + +const ( + // EntraPrincipalTypeServicePrincipal - Entra service principal type. + EntraPrincipalTypeServicePrincipal EntraPrincipalType = "servicePrincipal" + // EntraPrincipalTypeUser - Entra user type. + EntraPrincipalTypeUser EntraPrincipalType = "user" +) + +// PossibleEntraPrincipalTypeValues returns the possible values for the EntraPrincipalType const type. +func PossibleEntraPrincipalTypeValues() []EntraPrincipalType { + return []EntraPrincipalType{ + EntraPrincipalTypeServicePrincipal, + EntraPrincipalTypeUser, + } +} + +// HighAvailabilityMode - The high availability modes for a cluster. +type HighAvailabilityMode string + +const ( + // HighAvailabilityModeDisabled - High availability mode is disabled. This mode is can see availability impact during faults + // or maintenance and is not recommended for production. + HighAvailabilityModeDisabled HighAvailabilityMode = "Disabled" + // HighAvailabilityModeSameZone - High availability mode is enabled, where each server in a shard is placed in the same availability + // zone. + HighAvailabilityModeSameZone HighAvailabilityMode = "SameZone" + // HighAvailabilityModeZoneRedundantPreferred - High availability mode is enabled and preferences ZoneRedundant if availability + // zones capacity is available in the region, otherwise falls-back to provisioning with SameZone. + HighAvailabilityModeZoneRedundantPreferred HighAvailabilityMode = "ZoneRedundantPreferred" +) + +// PossibleHighAvailabilityModeValues returns the possible values for the HighAvailabilityMode const type. +func PossibleHighAvailabilityModeValues() []HighAvailabilityMode { + return []HighAvailabilityMode{ + HighAvailabilityModeDisabled, + HighAvailabilityModeSameZone, + HighAvailabilityModeZoneRedundantPreferred, + } +} + +// IdentityProviderType - Identity provider types that a a user identity can belong to. +type IdentityProviderType string + +const ( + // IdentityProviderTypeMicrosoftEntraID - Microsoft Entra ID provider. + IdentityProviderTypeMicrosoftEntraID IdentityProviderType = "MicrosoftEntraID" +) + +// PossibleIdentityProviderTypeValues returns the possible values for the IdentityProviderType const type. +func PossibleIdentityProviderTypeValues() []IdentityProviderType { + return []IdentityProviderType{ + IdentityProviderTypeMicrosoftEntraID, + } +} + +// KeyEncryptionKeyIdentityType - The type of identity for key encryption key. +type KeyEncryptionKeyIdentityType string + +const ( + // KeyEncryptionKeyIdentityTypeUserAssignedIdentity - User assigned identity. + KeyEncryptionKeyIdentityTypeUserAssignedIdentity KeyEncryptionKeyIdentityType = "UserAssignedIdentity" +) + +// PossibleKeyEncryptionKeyIdentityTypeValues returns the possible values for the KeyEncryptionKeyIdentityType const type. +func PossibleKeyEncryptionKeyIdentityTypeValues() []KeyEncryptionKeyIdentityType { + return []KeyEncryptionKeyIdentityType{ + KeyEncryptionKeyIdentityTypeUserAssignedIdentity, + } +} + +// ManagedServiceIdentityType - Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). +type ManagedServiceIdentityType string + +const ( + // ManagedServiceIdentityTypeNone - No managed identity. + ManagedServiceIdentityTypeNone ManagedServiceIdentityType = "None" + // ManagedServiceIdentityTypeSystemAssigned - System assigned managed identity. + ManagedServiceIdentityTypeSystemAssigned ManagedServiceIdentityType = "SystemAssigned" + // ManagedServiceIdentityTypeSystemAssignedUserAssigned - System and user assigned managed identity. + ManagedServiceIdentityTypeSystemAssignedUserAssigned ManagedServiceIdentityType = "SystemAssigned,UserAssigned" + // ManagedServiceIdentityTypeUserAssigned - User assigned managed identity. + ManagedServiceIdentityTypeUserAssigned ManagedServiceIdentityType = "UserAssigned" +) + +// PossibleManagedServiceIdentityTypeValues returns the possible values for the ManagedServiceIdentityType const type. +func PossibleManagedServiceIdentityTypeValues() []ManagedServiceIdentityType { + return []ManagedServiceIdentityType{ + ManagedServiceIdentityTypeNone, + ManagedServiceIdentityTypeSystemAssigned, + ManagedServiceIdentityTypeSystemAssignedUserAssigned, + ManagedServiceIdentityTypeUserAssigned, + } +} + +// NetworkBypassMode - The network bypass mode for the Mongo cluster. +type NetworkBypassMode string + +const ( + // NetworkBypassModeAzureCosmosDB - Allows Azure Cosmos DB service to bypass network restrictions. + NetworkBypassModeAzureCosmosDB NetworkBypassMode = "AzureCosmosDB" + // NetworkBypassModeNone - No network bypass is enabled. + NetworkBypassModeNone NetworkBypassMode = "None" +) + +// PossibleNetworkBypassModeValues returns the possible values for the NetworkBypassMode const type. +func PossibleNetworkBypassModeValues() []NetworkBypassMode { + return []NetworkBypassMode{ + NetworkBypassModeAzureCosmosDB, + NetworkBypassModeNone, + } +} + +// Origin - The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default +// value is "user,system" +type Origin string + +const ( + // OriginSystem - Indicates the operation is initiated by a system. + OriginSystem Origin = "system" + // OriginUser - Indicates the operation is initiated by a user. + OriginUser Origin = "user" + // OriginUserSystem - Indicates the operation is initiated by a user or system. + OriginUserSystem Origin = "user,system" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginSystem, + OriginUser, + OriginUserSystem, + } +} + +// PreviewFeature - Preview features that can be enabled on a mongo cluster. +type PreviewFeature string + +const ( + // PreviewFeatureGeoReplicas - Enables geo replicas preview feature. The feature must be set at create-time on new cluster + // to enable linking a geo-replica cluster to it. + PreviewFeatureGeoReplicas PreviewFeature = "GeoReplicas" +) + +// PossiblePreviewFeatureValues returns the possible values for the PreviewFeature const type. +func PossiblePreviewFeatureValues() []PreviewFeature { + return []PreviewFeature{ + PreviewFeatureGeoReplicas, + } +} + +// PrivateEndpointConnectionProvisioningState - The current provisioning state. +type PrivateEndpointConnectionProvisioningState string + +const ( + // PrivateEndpointConnectionProvisioningStateCreating - Connection is being created + PrivateEndpointConnectionProvisioningStateCreating PrivateEndpointConnectionProvisioningState = "Creating" + // PrivateEndpointConnectionProvisioningStateDeleting - Connection is being deleted + PrivateEndpointConnectionProvisioningStateDeleting PrivateEndpointConnectionProvisioningState = "Deleting" + // PrivateEndpointConnectionProvisioningStateFailed - Connection provisioning has failed + PrivateEndpointConnectionProvisioningStateFailed PrivateEndpointConnectionProvisioningState = "Failed" + // PrivateEndpointConnectionProvisioningStateSucceeded - Connection has been provisioned + PrivateEndpointConnectionProvisioningStateSucceeded PrivateEndpointConnectionProvisioningState = "Succeeded" +) + +// PossiblePrivateEndpointConnectionProvisioningStateValues returns the possible values for the PrivateEndpointConnectionProvisioningState const type. +func PossiblePrivateEndpointConnectionProvisioningStateValues() []PrivateEndpointConnectionProvisioningState { + return []PrivateEndpointConnectionProvisioningState{ + PrivateEndpointConnectionProvisioningStateCreating, + PrivateEndpointConnectionProvisioningStateDeleting, + PrivateEndpointConnectionProvisioningStateFailed, + PrivateEndpointConnectionProvisioningStateSucceeded, + } +} + +// PrivateEndpointServiceConnectionStatus - The private endpoint connection status. +type PrivateEndpointServiceConnectionStatus string + +const ( + // PrivateEndpointServiceConnectionStatusApproved - Connection approved + PrivateEndpointServiceConnectionStatusApproved PrivateEndpointServiceConnectionStatus = "Approved" + // PrivateEndpointServiceConnectionStatusPending - Connection waiting for approval or rejection + PrivateEndpointServiceConnectionStatusPending PrivateEndpointServiceConnectionStatus = "Pending" + // PrivateEndpointServiceConnectionStatusRejected - Connection Rejected + PrivateEndpointServiceConnectionStatusRejected PrivateEndpointServiceConnectionStatus = "Rejected" +) + +// PossiblePrivateEndpointServiceConnectionStatusValues returns the possible values for the PrivateEndpointServiceConnectionStatus const type. +func PossiblePrivateEndpointServiceConnectionStatusValues() []PrivateEndpointServiceConnectionStatus { + return []PrivateEndpointServiceConnectionStatus{ + PrivateEndpointServiceConnectionStatusApproved, + PrivateEndpointServiceConnectionStatusPending, + PrivateEndpointServiceConnectionStatusRejected, + } +} + +// PromoteMode - The mode to apply to a promote operation. +type PromoteMode string + +const ( + // PromoteModeSwitchover - Promotion will switch the current replica cluster to the primary role and the original primary + // will be switched to a replica role, maintaining the replication link. + PromoteModeSwitchover PromoteMode = "Switchover" +) + +// PossiblePromoteModeValues returns the possible values for the PromoteMode const type. +func PossiblePromoteModeValues() []PromoteMode { + return []PromoteMode{ + PromoteModeSwitchover, + } +} + +// PromoteOption - The option to apply to a promote operation. +type PromoteOption string + +const ( + // PromoteOptionForced - Promote option forces the promotion without waiting for the replica to be caught up to the primary. + // This can result in data-loss so should only be used during disaster recovery scenarios. + PromoteOptionForced PromoteOption = "Forced" +) + +// PossiblePromoteOptionValues returns the possible values for the PromoteOption const type. +func PossiblePromoteOptionValues() []PromoteOption { + return []PromoteOption{ + PromoteOptionForced, + } +} + +// ProvisioningState - The provisioning state of the last accepted operation. +type ProvisioningState string + +const ( + // ProvisioningStateCanceled - Resource creation was canceled. + ProvisioningStateCanceled ProvisioningState = "Canceled" + // ProvisioningStateDropping - A drop operation is in-progress on the resource. + ProvisioningStateDropping ProvisioningState = "Dropping" + // ProvisioningStateFailed - Resource creation failed. + ProvisioningStateFailed ProvisioningState = "Failed" + // ProvisioningStateInProgress - An operation is in-progress on the resource. + ProvisioningStateInProgress ProvisioningState = "InProgress" + // ProvisioningStateSucceeded - Resource has been created. + ProvisioningStateSucceeded ProvisioningState = "Succeeded" + // ProvisioningStateUpdating - An update operation is in-progress on the resource. + ProvisioningStateUpdating ProvisioningState = "Updating" +) + +// PossibleProvisioningStateValues returns the possible values for the ProvisioningState const type. +func PossibleProvisioningStateValues() []ProvisioningState { + return []ProvisioningState{ + ProvisioningStateCanceled, + ProvisioningStateDropping, + ProvisioningStateFailed, + ProvisioningStateInProgress, + ProvisioningStateSucceeded, + ProvisioningStateUpdating, + } +} + +// PublicNetworkAccess - Whether or not public endpoint access is allowed for this Mongo cluster. Value is optional and default +// value is 'Enabled' +type PublicNetworkAccess string + +const ( + // PublicNetworkAccessDisabled - If set, the private endpoints are the exclusive access method. + PublicNetworkAccessDisabled PublicNetworkAccess = "Disabled" + // PublicNetworkAccessEnabled - If set, mongo cluster can be accessed through private and public methods. + PublicNetworkAccessEnabled PublicNetworkAccess = "Enabled" +) + +// PossiblePublicNetworkAccessValues returns the possible values for the PublicNetworkAccess const type. +func PossiblePublicNetworkAccessValues() []PublicNetworkAccess { + return []PublicNetworkAccess{ + PublicNetworkAccessDisabled, + PublicNetworkAccessEnabled, + } +} + +// ReplicationRole - Replication role of the mongo cluster. +type ReplicationRole string + +const ( + // ReplicationRoleAsyncReplica - The cluster is a local asynchronous replica. + ReplicationRoleAsyncReplica ReplicationRole = "AsyncReplica" + // ReplicationRoleGeoAsyncReplica - The cluster is a geo-asynchronous replica. + ReplicationRoleGeoAsyncReplica ReplicationRole = "GeoAsyncReplica" + // ReplicationRolePrimary - The cluster is a primary replica. + ReplicationRolePrimary ReplicationRole = "Primary" +) + +// PossibleReplicationRoleValues returns the possible values for the ReplicationRole const type. +func PossibleReplicationRoleValues() []ReplicationRole { + return []ReplicationRole{ + ReplicationRoleAsyncReplica, + ReplicationRoleGeoAsyncReplica, + ReplicationRolePrimary, + } +} + +// ReplicationState - The state of the replication link between the replica and source cluster. +type ReplicationState string + +const ( + // ReplicationStateActive - Replication link is active. + ReplicationStateActive ReplicationState = "Active" + // ReplicationStateBroken - Replication link is broken and the replica may need to be recreated. + ReplicationStateBroken ReplicationState = "Broken" + // ReplicationStateCatchup - Replica is catching-up with the primary. This can occur after the replica is created or after + // a promotion is triggered. + ReplicationStateCatchup ReplicationState = "Catchup" + // ReplicationStateProvisioning - Replica and replication link to the primary is being created. + ReplicationStateProvisioning ReplicationState = "Provisioning" + // ReplicationStateReconfiguring - Replication link is re-configuring due to a promotion event. + ReplicationStateReconfiguring ReplicationState = "Reconfiguring" + // ReplicationStateUpdating - Replication link is being updated due to a change on the replica or an upgrade. + ReplicationStateUpdating ReplicationState = "Updating" +) + +// PossibleReplicationStateValues returns the possible values for the ReplicationState const type. +func PossibleReplicationStateValues() []ReplicationState { + return []ReplicationState{ + ReplicationStateActive, + ReplicationStateBroken, + ReplicationStateCatchup, + ReplicationStateProvisioning, + ReplicationStateReconfiguring, + ReplicationStateUpdating, + } +} + +// Status - The status of the Mongo cluster resource. +type Status string + +const ( + // StatusDropping - The mongo cluster resource is being dropped. + StatusDropping Status = "Dropping" + // StatusProvisioning - The mongo cluster resource is being provisioned. + StatusProvisioning Status = "Provisioning" + // StatusReady - The mongo cluster resource is ready for use. + StatusReady Status = "Ready" + // StatusStarting - The mongo cluster resource is being started. + StatusStarting Status = "Starting" + // StatusStopped - The mongo cluster resource is stopped. + StatusStopped Status = "Stopped" + // StatusStopping - The mongo cluster resource is being stopped. + StatusStopping Status = "Stopping" + // StatusUpdating - The mongo cluster resource is being updated. + StatusUpdating Status = "Updating" +) + +// PossibleStatusValues returns the possible values for the Status const type. +func PossibleStatusValues() []Status { + return []Status{ + StatusDropping, + StatusProvisioning, + StatusReady, + StatusStarting, + StatusStopped, + StatusStopping, + StatusUpdating, + } +} + +// StorageType - The type of storage that a mongo cluster can be provisioned with. +type StorageType string + +const ( + // StorageTypePremiumSSD - Premium SSD for high performance workloads. + StorageTypePremiumSSD StorageType = "PremiumSSD" + // StorageTypePremiumSSDv2 - Premium SSD v2 for very IO-intensive workloads. This is a preview option and has additional limitations. + StorageTypePremiumSSDv2 StorageType = "PremiumSSDv2" +) + +// PossibleStorageTypeValues returns the possible values for the StorageType const type. +func PossibleStorageTypeValues() []StorageType { + return []StorageType{ + StorageTypePremiumSSD, + StorageTypePremiumSSDv2, + } +} + +// UserRole - Built-in database role that can be assigned to a user. +type UserRole string + +const ( + // UserRoleRoot - Root role permissions on the target scope. + UserRoleRoot UserRole = "root" +) + +// PossibleUserRoleValues returns the possible values for the UserRole const type. +func PossibleUserRoleValues() []UserRole { + return []UserRole{ + UserRoleRoot, + } +} diff --git a/test/local/armmongocluster/zz_firewallrules_client.go b/test/local/armmongocluster/zz_firewallrules_client.go new file mode 100644 index 000000000000..18076351b8cb --- /dev/null +++ b/test/local/armmongocluster/zz_firewallrules_client.go @@ -0,0 +1,331 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmongocluster + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// FirewallRulesClient contains the methods for the FirewallRules group. +// Don't use this type directly, use NewFirewallRulesClient() instead. +// +// Generated from API version 2026-06-01 +type FirewallRulesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewFirewallRulesClient creates a new instance of FirewallRulesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewFirewallRulesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*FirewallRulesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &FirewallRulesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates a new firewall rule or updates an existing firewall rule on a mongo cluster. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - mongoClusterName - The name of the mongo cluster. +// - firewallRuleName - The name of the mongo cluster firewall rule. +// - resource - Resource create parameters. +// - options - FirewallRulesClientBeginCreateOrUpdateOptions contains the optional parameters for the FirewallRulesClient.BeginCreateOrUpdate +// method. +func (client *FirewallRulesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, mongoClusterName string, firewallRuleName string, resource FirewallRule, options *FirewallRulesClientBeginCreateOrUpdateOptions) (*runtime.Poller[FirewallRulesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, mongoClusterName, firewallRuleName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FirewallRulesClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FirewallRulesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates a new firewall rule or updates an existing firewall rule on a mongo cluster. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *FirewallRulesClient) createOrUpdate(ctx context.Context, resourceGroupName string, mongoClusterName string, firewallRuleName string, resource FirewallRule, options *FirewallRulesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "FirewallRulesClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, mongoClusterName, firewallRuleName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *FirewallRulesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, mongoClusterName string, firewallRuleName string, resource FirewallRule, _ *FirewallRulesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}/firewallRules/{firewallRuleName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if mongoClusterName == "" { + return nil, errors.New("parameter mongoClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{mongoClusterName}", url.PathEscape(mongoClusterName)) + if firewallRuleName == "" { + return nil, errors.New("parameter firewallRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{firewallRuleName}", url.PathEscape(firewallRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260601) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a mongo cluster firewall rule. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - mongoClusterName - The name of the mongo cluster. +// - firewallRuleName - The name of the mongo cluster firewall rule. +// - options - FirewallRulesClientBeginDeleteOptions contains the optional parameters for the FirewallRulesClient.BeginDelete +// method. +func (client *FirewallRulesClient) BeginDelete(ctx context.Context, resourceGroupName string, mongoClusterName string, firewallRuleName string, options *FirewallRulesClientBeginDeleteOptions) (*runtime.Poller[FirewallRulesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, mongoClusterName, firewallRuleName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[FirewallRulesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[FirewallRulesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a mongo cluster firewall rule. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *FirewallRulesClient) deleteOperation(ctx context.Context, resourceGroupName string, mongoClusterName string, firewallRuleName string, options *FirewallRulesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "FirewallRulesClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, mongoClusterName, firewallRuleName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *FirewallRulesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, mongoClusterName string, firewallRuleName string, _ *FirewallRulesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}/firewallRules/{firewallRuleName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if mongoClusterName == "" { + return nil, errors.New("parameter mongoClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{mongoClusterName}", url.PathEscape(mongoClusterName)) + if firewallRuleName == "" { + return nil, errors.New("parameter firewallRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{firewallRuleName}", url.PathEscape(firewallRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260601) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Gets information about a mongo cluster firewall rule. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - mongoClusterName - The name of the mongo cluster. +// - firewallRuleName - The name of the mongo cluster firewall rule. +// - options - FirewallRulesClientGetOptions contains the optional parameters for the FirewallRulesClient.Get method. +func (client *FirewallRulesClient) Get(ctx context.Context, resourceGroupName string, mongoClusterName string, firewallRuleName string, options *FirewallRulesClientGetOptions) (FirewallRulesClientGetResponse, error) { + var err error + const operationName = "FirewallRulesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, mongoClusterName, firewallRuleName, options) + if err != nil { + return FirewallRulesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FirewallRulesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FirewallRulesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *FirewallRulesClient) getCreateRequest(ctx context.Context, resourceGroupName string, mongoClusterName string, firewallRuleName string, _ *FirewallRulesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}/firewallRules/{firewallRuleName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if mongoClusterName == "" { + return nil, errors.New("parameter mongoClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{mongoClusterName}", url.PathEscape(mongoClusterName)) + if firewallRuleName == "" { + return nil, errors.New("parameter firewallRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{firewallRuleName}", url.PathEscape(firewallRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260601) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *FirewallRulesClient) getHandleResponse(resp *http.Response) (FirewallRulesClientGetResponse, error) { + result := FirewallRulesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FirewallRule); err != nil { + return FirewallRulesClientGetResponse{}, err + } + return result, nil +} + +// NewListByMongoClusterPager - List all the firewall rules in a given mongo cluster. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - mongoClusterName - The name of the mongo cluster. +// - options - FirewallRulesClientListByMongoClusterOptions contains the optional parameters for the FirewallRulesClient.NewListByMongoClusterPager +// method. +func (client *FirewallRulesClient) NewListByMongoClusterPager(resourceGroupName string, mongoClusterName string, options *FirewallRulesClientListByMongoClusterOptions) *runtime.Pager[FirewallRulesClientListByMongoClusterResponse] { + return runtime.NewPager(runtime.PagingHandler[FirewallRulesClientListByMongoClusterResponse]{ + More: func(page FirewallRulesClientListByMongoClusterResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *FirewallRulesClientListByMongoClusterResponse) (FirewallRulesClientListByMongoClusterResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "FirewallRulesClient.NewListByMongoClusterPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByMongoClusterCreateRequest(ctx, resourceGroupName, mongoClusterName, options) + }, nil) + if err != nil { + return FirewallRulesClientListByMongoClusterResponse{}, err + } + return client.listByMongoClusterHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByMongoClusterCreateRequest creates the ListByMongoCluster request. +func (client *FirewallRulesClient) listByMongoClusterCreateRequest(ctx context.Context, resourceGroupName string, mongoClusterName string, _ *FirewallRulesClientListByMongoClusterOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}/firewallRules" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if mongoClusterName == "" { + return nil, errors.New("parameter mongoClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{mongoClusterName}", url.PathEscape(mongoClusterName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260601) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByMongoClusterHandleResponse handles the ListByMongoCluster response. +func (client *FirewallRulesClient) listByMongoClusterHandleResponse(resp *http.Response) (FirewallRulesClientListByMongoClusterResponse, error) { + result := FirewallRulesClientListByMongoClusterResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FirewallRuleListResult); err != nil { + return FirewallRulesClientListByMongoClusterResponse{}, err + } + return result, nil +} diff --git a/test/local/armmongocluster/zz_interfaces.go b/test/local/armmongocluster/zz_interfaces.go new file mode 100644 index 000000000000..53ad1029f3ce --- /dev/null +++ b/test/local/armmongocluster/zz_interfaces.go @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmongocluster + +// IdentityProviderClassification provides polymorphic access to related types. +// Call the interface's GetIdentityProvider() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *EntraIdentityProvider, *IdentityProvider +type IdentityProviderClassification interface { + // GetIdentityProvider returns the IdentityProvider content of the underlying type. + GetIdentityProvider() *IdentityProvider +} diff --git a/test/local/armmongocluster/zz_models.go b/test/local/armmongocluster/zz_models.go new file mode 100644 index 000000000000..7187f671b218 --- /dev/null +++ b/test/local/armmongocluster/zz_models.go @@ -0,0 +1,688 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmongocluster + +import "time" + +// AdministratorProperties - The local administrator login properties. +type AdministratorProperties struct { + // The administrator password. + Password *string + + // The administrator user name. + UserName *string +} + +// AuthConfigProperties - The authentication configuration for the Mongo cluster. +type AuthConfigProperties struct { + // Allowed authentication modes for data access on the cluster. + AllowedModes []*AuthenticationMode +} + +// BackupProperties - The backup properties of the cluster. This includes the earliest restore time and retention settings. +type BackupProperties struct { + // READ-ONLY; Earliest restore timestamp in UTC ISO8601 format. + EarliestRestoreTime *string +} + +// CheckNameAvailabilityRequest - The check availability request body. +type CheckNameAvailabilityRequest struct { + // The name of the resource for which availability needs to be checked. + Name *string + + // The resource type. + Type *string +} + +// CheckNameAvailabilityResponse - The check availability result. +type CheckNameAvailabilityResponse struct { + // Detailed reason why the given name is not available. + Message *string + + // Indicates if the resource name is available. + NameAvailable *bool + + // The reason why the given name is not available. + Reason *CheckNameAvailabilityReason +} + +// ComputeProperties - The compute properties of the cluster. This includes the virtual-cores/memory and scaling options applied +// to servers in the cluster. +type ComputeProperties struct { + // The compute tier to assign to the cluster, where each tier maps to a virtual-core and memory size. Example values: 'M30', + // 'M40'. + Tier *string +} + +// ConnectionString - Connection string for the mongo cluster +type ConnectionString struct { + // READ-ONLY; Value of the connection string + ConnectionString *string + + // READ-ONLY; Description of the connection string + Description *string + + // READ-ONLY; Name of the connection string. + Name *string +} + +// CustomerManagedKeyEncryptionProperties - Customer managed key encryption settings. +type CustomerManagedKeyEncryptionProperties struct { + // The identity used to access the key encryption key. + KeyEncryptionKeyIdentity *KeyEncryptionKeyIdentity + + // The URI of the key vault key used for encryption. + KeyEncryptionKeyURL *string +} + +// DataAPIProperties - Data API properties. +type DataAPIProperties struct { + // The mode to indicate whether the Mongo Data API is enabled for a cluster. + Mode *DataAPIMode +} + +// DatabaseRole - Database role definition that is assigned to a user. +type DatabaseRole struct { + // REQUIRED; Database scope that the role is assigned to. + Db *string + + // REQUIRED; The role that is assigned to the user on the database scope. + Role *UserRole +} + +// EncryptionProperties - The encryption configuration for the mongo cluster. +type EncryptionProperties struct { + // Customer managed key encryption settings. + CustomerManagedKeyEncryption *CustomerManagedKeyEncryptionProperties +} + +// EntraIdentityProvider - Defines a Microsoft Entra ID Mongo user. +type EntraIdentityProvider struct { + // REQUIRED; The Entra identity properties for the user. + Properties *EntraIdentityProviderProperties + + // CONSTANT; The type of identity provider that the user belongs to. + // Field has constant value IdentityProviderTypeMicrosoftEntraID, any specified value is ignored. + Type *IdentityProviderType +} + +// GetIdentityProvider implements the IdentityProviderClassification interface for type EntraIdentityProvider. +func (e *EntraIdentityProvider) GetIdentityProvider() *IdentityProvider { + return &IdentityProvider{ + Type: e.Type, + } +} + +// EntraIdentityProviderProperties - Microsoft Entra ID provider properties. +type EntraIdentityProviderProperties struct { + // REQUIRED; The principal type of the user. + PrincipalType *EntraPrincipalType +} + +// FirewallRule - Represents a mongo cluster firewall rule. +type FirewallRule struct { + // The resource-specific properties for this resource. + Properties *FirewallRuleProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// FirewallRuleListResult - The response of a FirewallRule list operation. +type FirewallRuleListResult struct { + // REQUIRED; The FirewallRule items on this page + Value []*FirewallRule + + // The link to the next page of items + NextLink *string +} + +// FirewallRuleProperties - The properties of a mongo cluster firewall rule. +type FirewallRuleProperties struct { + // REQUIRED; The end IP address of the mongo cluster firewall rule. Must be IPv4 format. + EndIPAddress *string + + // REQUIRED; The start IP address of the mongo cluster firewall rule. Must be IPv4 format. + StartIPAddress *string + + // READ-ONLY; The provisioning state of the firewall rule. + ProvisioningState *ProvisioningState +} + +// HighAvailabilityProperties - The high availability properties of the cluster. +type HighAvailabilityProperties struct { + // The target high availability mode requested for the cluster. + TargetMode *HighAvailabilityMode +} + +// IdentityProvider - Defines a user's identity provider definition. +type IdentityProvider struct { + // REQUIRED; The type of identity provider that the user belongs to. + Type *IdentityProviderType +} + +// GetIdentityProvider implements the IdentityProviderClassification interface for type IdentityProvider. +func (i *IdentityProvider) GetIdentityProvider() *IdentityProvider { return i } + +// KeyEncryptionKeyIdentity - The identity used for key encryption key. +type KeyEncryptionKeyIdentity struct { + // The type of identity. Only 'UserAssignedIdentity' is supported. + IdentityType *KeyEncryptionKeyIdentityType + + // The user assigned identity resource id. + UserAssignedIdentityResourceID *string +} + +// ListConnectionStringsResult - The connection strings for the given mongo cluster. +type ListConnectionStringsResult struct { + // READ-ONLY; An array that contains the connection strings for a mongo cluster. + ConnectionStrings []*ConnectionString +} + +// ListResult - The response of a MongoCluster list operation. +type ListResult struct { + // REQUIRED; The MongoCluster items on this page + Value []*MongoCluster + + // The link to the next page of items + NextLink *string +} + +// ManagedServiceIdentity - Managed service identity (system assigned and/or user assigned identities) +type ManagedServiceIdentity struct { + // REQUIRED; The type of managed identity assigned to this resource. + Type *ManagedServiceIdentityType + + // The identities assigned to this resource by the user. + UserAssignedIdentities map[string]*UserAssignedIdentity + + // READ-ONLY; The service principal ID of the system assigned identity. This property will only be provided for a system assigned + // identity. + PrincipalID *string + + // READ-ONLY; The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + TenantID *string +} + +// MongoCluster - Represents a mongo cluster resource. +type MongoCluster struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The managed service identities assigned to this resource. + Identity *ManagedServiceIdentity + + // The resource-specific properties for this resource. + Properties *Properties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// Operation - REST API Operation +// +// Details of a REST API operation, returned from the Resource Provider Operations API +type Operation struct { + // Localized display information for this particular operation. + Display *OperationDisplay + + // READ-ONLY; Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + ActionType *ActionType + + // READ-ONLY; Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure + // Resource Manager/control-plane operations. + IsDataAction *bool + + // READ-ONLY; The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + // "Microsoft.Compute/virtualMachines/capture/action" + Name *string + + // READ-ONLY; The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default + // value is "user,system" + Origin *Origin +} + +// OperationDisplay - Localized display information for an operation. +type OperationDisplay struct { + // READ-ONLY; The short, localized friendly description of the operation; suitable for tool tips and detailed views. + Description *string + + // READ-ONLY; The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual + // Machine", "Restart Virtual Machine". + Operation *string + + // READ-ONLY; The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft + // Compute". + Provider *string + + // READ-ONLY; The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job + // Schedule Collections". + Resource *string +} + +// OperationListResult - A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to +// get the next set of results. +type OperationListResult struct { + // REQUIRED; The Operation items on this page + Value []*Operation + + // The link to the next page of items + NextLink *string +} + +// PrivateEndpoint - The private endpoint resource. +type PrivateEndpoint struct { + // READ-ONLY; The resource identifier of the private endpoint + ID *string +} + +// PrivateEndpointConnection - The private endpoint connection resource +type PrivateEndpointConnection struct { + // The private endpoint connection properties + Properties *PrivateEndpointConnectionProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// PrivateEndpointConnectionProperties - Properties of the private endpoint connection. +type PrivateEndpointConnectionProperties struct { + // REQUIRED; A collection of information about the state of the connection between service consumer and provider. + PrivateLinkServiceConnectionState *PrivateLinkServiceConnectionState + + // The private endpoint resource. + PrivateEndpoint *PrivateEndpoint + + // READ-ONLY; The group ids for the private endpoint resource. + GroupIDs []*string + + // READ-ONLY; The provisioning state of the private endpoint connection resource. + ProvisioningState *PrivateEndpointConnectionProvisioningState +} + +// PrivateEndpointConnectionResource - Concrete proxy resource types can be created by aliasing this type using a specific +// property type. +type PrivateEndpointConnectionResource struct { + // The resource-specific properties for this resource. + Properties *PrivateEndpointConnectionProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// PrivateEndpointConnectionResourceListResult - The response of a PrivateEndpointConnectionResource list operation. +type PrivateEndpointConnectionResourceListResult struct { + // REQUIRED; The PrivateEndpointConnectionResource items on this page + Value []*PrivateEndpointConnectionResource + + // The link to the next page of items + NextLink *string +} + +// PrivateLinkResource - Concrete proxy resource types can be created by aliasing this type using a specific property type. +type PrivateLinkResource struct { + // The resource-specific properties for this resource. + Properties *PrivateLinkResourceProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// PrivateLinkResourceListResult - The response of a PrivateLinkResource list operation. +type PrivateLinkResourceListResult struct { + // REQUIRED; The PrivateLinkResource items on this page + Value []*PrivateLinkResource + + // The link to the next page of items + NextLink *string +} + +// PrivateLinkResourceProperties - Properties of a private link resource. +type PrivateLinkResourceProperties struct { + // The private link resource private link DNS zone name. + RequiredZoneNames []*string + + // READ-ONLY; The private link resource group id. + GroupID *string + + // READ-ONLY; The private link resource required member names. + RequiredMembers []*string +} + +// PrivateLinkServiceConnectionState - A collection of information about the state of the connection between service consumer +// and provider. +type PrivateLinkServiceConnectionState struct { + // A message indicating if changes on the service provider require any updates on the consumer. + ActionsRequired *string + + // The reason for approval/rejection of the connection. + Description *string + + // Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. + Status *PrivateEndpointServiceConnectionStatus +} + +// PromoteReplicaRequest - Promote replica request properties. +type PromoteReplicaRequest struct { + // REQUIRED; The promote option to apply to the operation. + PromoteOption *PromoteOption + + // The mode to apply to the promote operation. Value is optional and default value is 'Switchover'. + Mode *PromoteMode +} + +// Properties - The properties of a mongo cluster. +type Properties struct { + // The local administrator properties for the mongo cluster. + Administrator *AdministratorProperties + + // The authentication configuration for the cluster. + AuthConfig *AuthConfigProperties + + // The backup properties of the mongo cluster. + Backup *BackupProperties + + // The compute properties of the mongo cluster. + Compute *ComputeProperties + + // The mode to create a mongo cluster. + CreateMode *CreateMode + + // The Data API properties of the mongo cluster. + DataAPI *DataAPIProperties + + // The encryption configuration for the cluster. Depends on identity being configured. + Encryption *EncryptionProperties + + // The high availability properties of the mongo cluster. + HighAvailability *HighAvailabilityProperties + + // The network bypass mode for the cluster. Setting to 'AzureCosmosDB' allows Azure Cosmos DB service to bypass network restrictions. + NetworkBypassMode *NetworkBypassMode + + // List of private endpoint connections. + PreviewFeatures []*PreviewFeature + + // Whether or not public endpoint access is allowed for this mongo cluster. + PublicNetworkAccess *PublicNetworkAccess + + // The parameters to create a replica mongo cluster. + ReplicaParameters *ReplicaParameters + + // The parameters to create a point-in-time restore mongo cluster. + RestoreParameters *RestoreParameters + + // The Mongo DB server version. Defaults to the latest available version if not specified. + ServerVersion *string + + // The sharding properties of the mongo cluster. + Sharding *ShardingProperties + + // The storage properties of the mongo cluster. + Storage *StorageProperties + + // READ-ONLY; The status of the mongo cluster. + ClusterStatus *Status + + // READ-ONLY; The default mongo connection string for the cluster. + ConnectionString *string + + // READ-ONLY; The infrastructure version the cluster is provisioned on. + InfrastructureVersion *string + + // READ-ONLY; List of private endpoint connections. + PrivateEndpointConnections []*PrivateEndpointConnection + + // READ-ONLY; The provisioning state of the mongo cluster. + ProvisioningState *ProvisioningState + + // READ-ONLY; The replication properties for the mongo cluster + Replica *ReplicationProperties +} + +// Replica - Represents a mongo cluster replica. +type Replica struct { + // The resource-specific properties for this resource. + Properties *Properties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ReplicaListResult - The response of a Replica list operation. +type ReplicaListResult struct { + // REQUIRED; The Replica items on this page + Value []*Replica + + // The link to the next page of items + NextLink *string +} + +// ReplicaParameters - Parameters used for replica operations. +type ReplicaParameters struct { + // REQUIRED; The location of the source cluster + SourceLocation *string + + // REQUIRED; The id of the replication source cluster. + SourceResourceID *string +} + +// ReplicationProperties - Replica properties of the mongo cluster. +type ReplicationProperties struct { + // READ-ONLY; The replication link state of the replica cluster. + ReplicationState *ReplicationState + + // READ-ONLY; The replication role of the cluster + Role *ReplicationRole + + // READ-ONLY; The resource id the source cluster for the replica cluster. + SourceResourceID *string +} + +// RestoreParameters - Parameters used for restore operations +type RestoreParameters struct { + // UTC point in time to restore a mongo cluster + PointInTimeUTC *time.Time + + // Resource ID to locate the source cluster to restore + SourceResourceID *string +} + +// ShardingProperties - The sharding properties of the cluster. This includes the shard count and scaling options for the +// cluster. +type ShardingProperties struct { + // Number of shards to provision on the cluster. + ShardCount *int32 +} + +// StorageProperties - The storage properties of the cluster. This includes the data storage size and scaling applied to servers +// in the cluster. +type StorageProperties struct { + // The size of the data disk assigned to each server. + SizeGb *int64 + + // The type of storage to provision the cluster servers with. + Type *StorageType +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time + + // The identity that created the resource. + CreatedBy *string + + // The type of identity that created the resource. + CreatedByType *CreatedByType + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time + + // The identity that last modified the resource. + LastModifiedBy *string + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType +} + +// Update - The type used for update operations of the MongoCluster. +type Update struct { + // The managed service identities assigned to this resource. + Identity *ManagedServiceIdentity + + // The resource-specific properties for this resource. + Properties *UpdateProperties + + // Resource tags. + Tags map[string]*string +} + +// UpdateProperties - The updatable properties of the MongoCluster. +type UpdateProperties struct { + // The local administrator properties for the mongo cluster. + Administrator *AdministratorProperties + + // The authentication configuration for the cluster. + AuthConfig *AuthConfigProperties + + // The backup properties of the mongo cluster. + Backup *BackupProperties + + // The compute properties of the mongo cluster. + Compute *ComputeProperties + + // The Data API properties of the mongo cluster. + DataAPI *DataAPIProperties + + // The encryption configuration for the cluster. Depends on identity being configured. + Encryption *EncryptionProperties + + // The high availability properties of the mongo cluster. + HighAvailability *HighAvailabilityProperties + + // The network bypass mode for the cluster. Setting to 'AzureCosmosDB' allows Azure Cosmos DB service to bypass network restrictions. + NetworkBypassMode *NetworkBypassMode + + // List of private endpoint connections. + PreviewFeatures []*PreviewFeature + + // Whether or not public endpoint access is allowed for this mongo cluster. + PublicNetworkAccess *PublicNetworkAccess + + // The Mongo DB server version. Defaults to the latest available version if not specified. + ServerVersion *string + + // The sharding properties of the mongo cluster. + Sharding *ShardingProperties + + // The storage properties of the mongo cluster. + Storage *StorageProperties +} + +// User - Represents a Mongo cluster user. +type User struct { + // The resource-specific properties for this resource. + Properties *UserProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// UserAssignedIdentity - User assigned identity properties +type UserAssignedIdentity struct { + // READ-ONLY; The client ID of the assigned identity. + ClientID *string + + // READ-ONLY; The principal ID of the assigned identity. + PrincipalID *string +} + +// UserListResult - The response of a User list operation. +type UserListResult struct { + // REQUIRED; The User items on this page + Value []*User + + // The link to the next page of items + NextLink *string +} + +// UserProperties - Definition of Mongo user resource on a cluster. +type UserProperties struct { + // The user's identity provider definition. + IdentityProvider IdentityProviderClassification + + // Database roles that are assigned to the user. + Roles []*DatabaseRole + + // READ-ONLY; The provisioning state of the user. + ProvisioningState *ProvisioningState +} diff --git a/test/local/armmongocluster/zz_models_serde.go b/test/local/armmongocluster/zz_models_serde.go new file mode 100644 index 000000000000..91b10b38822d --- /dev/null +++ b/test/local/armmongocluster/zz_models_serde.go @@ -0,0 +1,1903 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmongocluster + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type AdministratorProperties. +func (a AdministratorProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "password", a.Password) + populate(objectMap, "userName", a.UserName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AdministratorProperties. +func (a *AdministratorProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "password": + err = unpopulate(val, "Password", &a.Password) + delete(rawMsg, key) + case "userName": + err = unpopulate(val, "UserName", &a.UserName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AuthConfigProperties. +func (a AuthConfigProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allowedModes", a.AllowedModes) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AuthConfigProperties. +func (a *AuthConfigProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "allowedModes": + err = unpopulate(val, "AllowedModes", &a.AllowedModes) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BackupProperties. +func (b BackupProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "earliestRestoreTime", b.EarliestRestoreTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BackupProperties. +func (b *BackupProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "earliestRestoreTime": + err = unpopulate(val, "EarliestRestoreTime", &b.EarliestRestoreTime) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CheckNameAvailabilityRequest. +func (c CheckNameAvailabilityRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", c.Name) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CheckNameAvailabilityRequest. +func (c *CheckNameAvailabilityRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CheckNameAvailabilityResponse. +func (c CheckNameAvailabilityResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "message", c.Message) + populate(objectMap, "nameAvailable", c.NameAvailable) + populate(objectMap, "reason", c.Reason) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CheckNameAvailabilityResponse. +func (c *CheckNameAvailabilityResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "message": + err = unpopulate(val, "Message", &c.Message) + delete(rawMsg, key) + case "nameAvailable": + err = unpopulate(val, "NameAvailable", &c.NameAvailable) + delete(rawMsg, key) + case "reason": + err = unpopulate(val, "Reason", &c.Reason) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ComputeProperties. +func (c ComputeProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "tier", c.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ComputeProperties. +func (c *ComputeProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "tier": + err = unpopulate(val, "Tier", &c.Tier) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConnectionString. +func (c ConnectionString) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "connectionString", c.ConnectionString) + populate(objectMap, "description", c.Description) + populate(objectMap, "name", c.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionString. +func (c *ConnectionString) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "connectionString": + err = unpopulate(val, "ConnectionString", &c.ConnectionString) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &c.Description) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CustomerManagedKeyEncryptionProperties. +func (c CustomerManagedKeyEncryptionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "keyEncryptionKeyIdentity", c.KeyEncryptionKeyIdentity) + populate(objectMap, "keyEncryptionKeyUrl", c.KeyEncryptionKeyURL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CustomerManagedKeyEncryptionProperties. +func (c *CustomerManagedKeyEncryptionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "keyEncryptionKeyIdentity": + err = unpopulate(val, "KeyEncryptionKeyIdentity", &c.KeyEncryptionKeyIdentity) + delete(rawMsg, key) + case "keyEncryptionKeyUrl": + err = unpopulate(val, "KeyEncryptionKeyURL", &c.KeyEncryptionKeyURL) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DataAPIProperties. +func (d DataAPIProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "mode", d.Mode) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DataAPIProperties. +func (d *DataAPIProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "mode": + err = unpopulate(val, "Mode", &d.Mode) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DatabaseRole. +func (d DatabaseRole) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "db", d.Db) + populate(objectMap, "role", d.Role) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DatabaseRole. +func (d *DatabaseRole) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "db": + err = unpopulate(val, "Db", &d.Db) + delete(rawMsg, key) + case "role": + err = unpopulate(val, "Role", &d.Role) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EncryptionProperties. +func (e EncryptionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "customerManagedKeyEncryption", e.CustomerManagedKeyEncryption) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EncryptionProperties. +func (e *EncryptionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "customerManagedKeyEncryption": + err = unpopulate(val, "CustomerManagedKeyEncryption", &e.CustomerManagedKeyEncryption) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EntraIdentityProvider. +func (e EntraIdentityProvider) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", e.Properties) + objectMap["type"] = IdentityProviderTypeMicrosoftEntraID + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EntraIdentityProvider. +func (e *EntraIdentityProvider) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &e.Properties) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &e.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EntraIdentityProviderProperties. +func (e EntraIdentityProviderProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "principalType", e.PrincipalType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EntraIdentityProviderProperties. +func (e *EntraIdentityProviderProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "principalType": + err = unpopulate(val, "PrincipalType", &e.PrincipalType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FirewallRule. +func (f FirewallRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", f.ID) + populate(objectMap, "name", f.Name) + populate(objectMap, "properties", f.Properties) + populate(objectMap, "systemData", f.SystemData) + populate(objectMap, "type", f.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallRule. +func (f *FirewallRule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &f.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &f.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &f.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &f.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &f.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FirewallRuleListResult. +func (f FirewallRuleListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", f.NextLink) + populate(objectMap, "value", f.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallRuleListResult. +func (f *FirewallRuleListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &f.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &f.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FirewallRuleProperties. +func (f FirewallRuleProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "endIpAddress", f.EndIPAddress) + populate(objectMap, "provisioningState", f.ProvisioningState) + populate(objectMap, "startIpAddress", f.StartIPAddress) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FirewallRuleProperties. +func (f *FirewallRuleProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "endIpAddress": + err = unpopulate(val, "EndIPAddress", &f.EndIPAddress) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &f.ProvisioningState) + delete(rawMsg, key) + case "startIpAddress": + err = unpopulate(val, "StartIPAddress", &f.StartIPAddress) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type HighAvailabilityProperties. +func (h HighAvailabilityProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "targetMode", h.TargetMode) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HighAvailabilityProperties. +func (h *HighAvailabilityProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "targetMode": + err = unpopulate(val, "TargetMode", &h.TargetMode) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", h, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type IdentityProvider. +func (i IdentityProvider) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "type", i.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IdentityProvider. +func (i *IdentityProvider) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "type": + err = unpopulate(val, "Type", &i.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyEncryptionKeyIdentity. +func (k KeyEncryptionKeyIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identityType", k.IdentityType) + populate(objectMap, "userAssignedIdentityResourceId", k.UserAssignedIdentityResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyEncryptionKeyIdentity. +func (k *KeyEncryptionKeyIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "identityType": + err = unpopulate(val, "IdentityType", &k.IdentityType) + delete(rawMsg, key) + case "userAssignedIdentityResourceId": + err = unpopulate(val, "UserAssignedIdentityResourceID", &k.UserAssignedIdentityResourceID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ListConnectionStringsResult. +func (l ListConnectionStringsResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "connectionStrings", l.ConnectionStrings) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ListConnectionStringsResult. +func (l *ListConnectionStringsResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "connectionStrings": + err = unpopulate(val, "ConnectionStrings", &l.ConnectionStrings) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ListResult. +func (l ListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", l.NextLink) + populate(objectMap, "value", l.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ListResult. +func (l *ListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &l.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &l.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedServiceIdentity. +func (m ManagedServiceIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "principalId", m.PrincipalID) + populate(objectMap, "tenantId", m.TenantID) + populate(objectMap, "type", m.Type) + populate(objectMap, "userAssignedIdentities", m.UserAssignedIdentities) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedServiceIdentity. +func (m *ManagedServiceIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "principalId": + err = unpopulate(val, "PrincipalID", &m.PrincipalID) + delete(rawMsg, key) + case "tenantId": + err = unpopulate(val, "TenantID", &m.TenantID) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + case "userAssignedIdentities": + err = unpopulate(val, "UserAssignedIdentities", &m.UserAssignedIdentities) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MongoCluster. +func (m MongoCluster) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", m.ID) + populate(objectMap, "identity", m.Identity) + populate(objectMap, "location", m.Location) + populate(objectMap, "name", m.Name) + populate(objectMap, "properties", m.Properties) + populate(objectMap, "systemData", m.SystemData) + populate(objectMap, "tags", m.Tags) + populate(objectMap, "type", m.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MongoCluster. +func (m *MongoCluster) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &m.ID) + delete(rawMsg, key) + case "identity": + err = unpopulate(val, "Identity", &m.Identity) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &m.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &m.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &m.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &m.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &m.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Operation. +func (o Operation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionType", o.ActionType) + populate(objectMap, "display", o.Display) + populate(objectMap, "isDataAction", o.IsDataAction) + populate(objectMap, "name", o.Name) + populate(objectMap, "origin", o.Origin) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Operation. +func (o *Operation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionType": + err = unpopulate(val, "ActionType", &o.ActionType) + delete(rawMsg, key) + case "display": + err = unpopulate(val, "Display", &o.Display) + delete(rawMsg, key) + case "isDataAction": + err = unpopulate(val, "IsDataAction", &o.IsDataAction) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "origin": + err = unpopulate(val, "Origin", &o.Origin) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationDisplay. +func (o OperationDisplay) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", o.Description) + populate(objectMap, "operation", o.Operation) + populate(objectMap, "provider", o.Provider) + populate(objectMap, "resource", o.Resource) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationDisplay. +func (o *OperationDisplay) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &o.Description) + delete(rawMsg, key) + case "operation": + err = unpopulate(val, "Operation", &o.Operation) + delete(rawMsg, key) + case "provider": + err = unpopulate(val, "Provider", &o.Provider) + delete(rawMsg, key) + case "resource": + err = unpopulate(val, "Resource", &o.Resource) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationListResult. +func (o *OperationListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &o.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpoint. +func (p PrivateEndpoint) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", p.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpoint. +func (p *PrivateEndpoint) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnection. +func (p PrivateEndpointConnection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", p.ID) + populate(objectMap, "name", p.Name) + populate(objectMap, "properties", p.Properties) + populate(objectMap, "systemData", p.SystemData) + populate(objectMap, "type", p.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpointConnection. +func (p *PrivateEndpointConnection) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &p.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &p.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &p.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnectionProperties. +func (p PrivateEndpointConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "groupIds", p.GroupIDs) + populate(objectMap, "privateEndpoint", p.PrivateEndpoint) + populate(objectMap, "privateLinkServiceConnectionState", p.PrivateLinkServiceConnectionState) + populate(objectMap, "provisioningState", p.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpointConnectionProperties. +func (p *PrivateEndpointConnectionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "groupIds": + err = unpopulate(val, "GroupIDs", &p.GroupIDs) + delete(rawMsg, key) + case "privateEndpoint": + err = unpopulate(val, "PrivateEndpoint", &p.PrivateEndpoint) + delete(rawMsg, key) + case "privateLinkServiceConnectionState": + err = unpopulate(val, "PrivateLinkServiceConnectionState", &p.PrivateLinkServiceConnectionState) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnectionResource. +func (p PrivateEndpointConnectionResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", p.ID) + populate(objectMap, "name", p.Name) + populate(objectMap, "properties", p.Properties) + populate(objectMap, "systemData", p.SystemData) + populate(objectMap, "type", p.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpointConnectionResource. +func (p *PrivateEndpointConnectionResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &p.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &p.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &p.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnectionResourceListResult. +func (p PrivateEndpointConnectionResourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", p.NextLink) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateEndpointConnectionResourceListResult. +func (p *PrivateEndpointConnectionResourceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &p.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResource. +func (p PrivateLinkResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", p.ID) + populate(objectMap, "name", p.Name) + populate(objectMap, "properties", p.Properties) + populate(objectMap, "systemData", p.SystemData) + populate(objectMap, "type", p.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkResource. +func (p *PrivateLinkResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &p.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &p.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &p.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResourceListResult. +func (p PrivateLinkResourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", p.NextLink) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkResourceListResult. +func (p *PrivateLinkResourceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &p.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResourceProperties. +func (p PrivateLinkResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "groupId", p.GroupID) + populate(objectMap, "requiredMembers", p.RequiredMembers) + populate(objectMap, "requiredZoneNames", p.RequiredZoneNames) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkResourceProperties. +func (p *PrivateLinkResourceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "groupId": + err = unpopulate(val, "GroupID", &p.GroupID) + delete(rawMsg, key) + case "requiredMembers": + err = unpopulate(val, "RequiredMembers", &p.RequiredMembers) + delete(rawMsg, key) + case "requiredZoneNames": + err = unpopulate(val, "RequiredZoneNames", &p.RequiredZoneNames) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkServiceConnectionState. +func (p PrivateLinkServiceConnectionState) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionsRequired", p.ActionsRequired) + populate(objectMap, "description", p.Description) + populate(objectMap, "status", p.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateLinkServiceConnectionState. +func (p *PrivateLinkServiceConnectionState) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionsRequired": + err = unpopulate(val, "ActionsRequired", &p.ActionsRequired) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &p.Description) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &p.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PromoteReplicaRequest. +func (p PromoteReplicaRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "mode", p.Mode) + populate(objectMap, "promoteOption", p.PromoteOption) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PromoteReplicaRequest. +func (p *PromoteReplicaRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "mode": + err = unpopulate(val, "Mode", &p.Mode) + delete(rawMsg, key) + case "promoteOption": + err = unpopulate(val, "PromoteOption", &p.PromoteOption) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Properties. +func (p Properties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "administrator", p.Administrator) + populate(objectMap, "authConfig", p.AuthConfig) + populate(objectMap, "backup", p.Backup) + populate(objectMap, "clusterStatus", p.ClusterStatus) + populate(objectMap, "compute", p.Compute) + populate(objectMap, "connectionString", p.ConnectionString) + populate(objectMap, "createMode", p.CreateMode) + populate(objectMap, "dataApi", p.DataAPI) + populate(objectMap, "encryption", p.Encryption) + populate(objectMap, "highAvailability", p.HighAvailability) + populate(objectMap, "infrastructureVersion", p.InfrastructureVersion) + populate(objectMap, "networkBypassMode", p.NetworkBypassMode) + populate(objectMap, "previewFeatures", p.PreviewFeatures) + populate(objectMap, "privateEndpointConnections", p.PrivateEndpointConnections) + populate(objectMap, "provisioningState", p.ProvisioningState) + populate(objectMap, "publicNetworkAccess", p.PublicNetworkAccess) + populate(objectMap, "replica", p.Replica) + populate(objectMap, "replicaParameters", p.ReplicaParameters) + populate(objectMap, "restoreParameters", p.RestoreParameters) + populate(objectMap, "serverVersion", p.ServerVersion) + populate(objectMap, "sharding", p.Sharding) + populate(objectMap, "storage", p.Storage) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Properties. +func (p *Properties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "administrator": + err = unpopulate(val, "Administrator", &p.Administrator) + delete(rawMsg, key) + case "authConfig": + err = unpopulate(val, "AuthConfig", &p.AuthConfig) + delete(rawMsg, key) + case "backup": + err = unpopulate(val, "Backup", &p.Backup) + delete(rawMsg, key) + case "clusterStatus": + err = unpopulate(val, "ClusterStatus", &p.ClusterStatus) + delete(rawMsg, key) + case "compute": + err = unpopulate(val, "Compute", &p.Compute) + delete(rawMsg, key) + case "connectionString": + err = unpopulate(val, "ConnectionString", &p.ConnectionString) + delete(rawMsg, key) + case "createMode": + err = unpopulate(val, "CreateMode", &p.CreateMode) + delete(rawMsg, key) + case "dataApi": + err = unpopulate(val, "DataAPI", &p.DataAPI) + delete(rawMsg, key) + case "encryption": + err = unpopulate(val, "Encryption", &p.Encryption) + delete(rawMsg, key) + case "highAvailability": + err = unpopulate(val, "HighAvailability", &p.HighAvailability) + delete(rawMsg, key) + case "infrastructureVersion": + err = unpopulate(val, "InfrastructureVersion", &p.InfrastructureVersion) + delete(rawMsg, key) + case "networkBypassMode": + err = unpopulate(val, "NetworkBypassMode", &p.NetworkBypassMode) + delete(rawMsg, key) + case "previewFeatures": + err = unpopulate(val, "PreviewFeatures", &p.PreviewFeatures) + delete(rawMsg, key) + case "privateEndpointConnections": + err = unpopulate(val, "PrivateEndpointConnections", &p.PrivateEndpointConnections) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + case "publicNetworkAccess": + err = unpopulate(val, "PublicNetworkAccess", &p.PublicNetworkAccess) + delete(rawMsg, key) + case "replica": + err = unpopulate(val, "Replica", &p.Replica) + delete(rawMsg, key) + case "replicaParameters": + err = unpopulate(val, "ReplicaParameters", &p.ReplicaParameters) + delete(rawMsg, key) + case "restoreParameters": + err = unpopulate(val, "RestoreParameters", &p.RestoreParameters) + delete(rawMsg, key) + case "serverVersion": + err = unpopulate(val, "ServerVersion", &p.ServerVersion) + delete(rawMsg, key) + case "sharding": + err = unpopulate(val, "Sharding", &p.Sharding) + delete(rawMsg, key) + case "storage": + err = unpopulate(val, "Storage", &p.Storage) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Replica. +func (r Replica) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "systemData", r.SystemData) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Replica. +func (r *Replica) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &r.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &r.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ReplicaListResult. +func (r ReplicaListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", r.NextLink) + populate(objectMap, "value", r.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ReplicaListResult. +func (r *ReplicaListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &r.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &r.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ReplicaParameters. +func (r ReplicaParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "sourceLocation", r.SourceLocation) + populate(objectMap, "sourceResourceId", r.SourceResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ReplicaParameters. +func (r *ReplicaParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "sourceLocation": + err = unpopulate(val, "SourceLocation", &r.SourceLocation) + delete(rawMsg, key) + case "sourceResourceId": + err = unpopulate(val, "SourceResourceID", &r.SourceResourceID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ReplicationProperties. +func (r ReplicationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "replicationState", r.ReplicationState) + populate(objectMap, "role", r.Role) + populate(objectMap, "sourceResourceId", r.SourceResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ReplicationProperties. +func (r *ReplicationProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "replicationState": + err = unpopulate(val, "ReplicationState", &r.ReplicationState) + delete(rawMsg, key) + case "role": + err = unpopulate(val, "Role", &r.Role) + delete(rawMsg, key) + case "sourceResourceId": + err = unpopulate(val, "SourceResourceID", &r.SourceResourceID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RestoreParameters. +func (r RestoreParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "pointInTimeUTC", r.PointInTimeUTC) + populate(objectMap, "sourceResourceId", r.SourceResourceID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RestoreParameters. +func (r *RestoreParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "pointInTimeUTC": + err = unpopulateTime[datetime.RFC3339](val, "PointInTimeUTC", &r.PointInTimeUTC) + delete(rawMsg, key) + case "sourceResourceId": + err = unpopulate(val, "SourceResourceID", &r.SourceResourceID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ShardingProperties. +func (s ShardingProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "shardCount", s.ShardCount) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ShardingProperties. +func (s *ShardingProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "shardCount": + err = unpopulate(val, "ShardCount", &s.ShardCount) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type StorageProperties. +func (s StorageProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "sizeGb", s.SizeGb) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StorageProperties. +func (s *StorageProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "sizeGb": + err = unpopulate(val, "SizeGb", &s.SizeGb) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateTime[datetime.RFC3339](objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateTime[datetime.RFC3339](val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateTime[datetime.RFC3339](val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Update. +func (u Update) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identity", u.Identity) + populate(objectMap, "properties", u.Properties) + populate(objectMap, "tags", u.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Update. +func (u *Update) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "identity": + err = unpopulate(val, "Identity", &u.Identity) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &u.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &u.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UpdateProperties. +func (u UpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "administrator", u.Administrator) + populate(objectMap, "authConfig", u.AuthConfig) + populate(objectMap, "backup", u.Backup) + populate(objectMap, "compute", u.Compute) + populate(objectMap, "dataApi", u.DataAPI) + populate(objectMap, "encryption", u.Encryption) + populate(objectMap, "highAvailability", u.HighAvailability) + populate(objectMap, "networkBypassMode", u.NetworkBypassMode) + populate(objectMap, "previewFeatures", u.PreviewFeatures) + populate(objectMap, "publicNetworkAccess", u.PublicNetworkAccess) + populate(objectMap, "serverVersion", u.ServerVersion) + populate(objectMap, "sharding", u.Sharding) + populate(objectMap, "storage", u.Storage) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UpdateProperties. +func (u *UpdateProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "administrator": + err = unpopulate(val, "Administrator", &u.Administrator) + delete(rawMsg, key) + case "authConfig": + err = unpopulate(val, "AuthConfig", &u.AuthConfig) + delete(rawMsg, key) + case "backup": + err = unpopulate(val, "Backup", &u.Backup) + delete(rawMsg, key) + case "compute": + err = unpopulate(val, "Compute", &u.Compute) + delete(rawMsg, key) + case "dataApi": + err = unpopulate(val, "DataAPI", &u.DataAPI) + delete(rawMsg, key) + case "encryption": + err = unpopulate(val, "Encryption", &u.Encryption) + delete(rawMsg, key) + case "highAvailability": + err = unpopulate(val, "HighAvailability", &u.HighAvailability) + delete(rawMsg, key) + case "networkBypassMode": + err = unpopulate(val, "NetworkBypassMode", &u.NetworkBypassMode) + delete(rawMsg, key) + case "previewFeatures": + err = unpopulate(val, "PreviewFeatures", &u.PreviewFeatures) + delete(rawMsg, key) + case "publicNetworkAccess": + err = unpopulate(val, "PublicNetworkAccess", &u.PublicNetworkAccess) + delete(rawMsg, key) + case "serverVersion": + err = unpopulate(val, "ServerVersion", &u.ServerVersion) + delete(rawMsg, key) + case "sharding": + err = unpopulate(val, "Sharding", &u.Sharding) + delete(rawMsg, key) + case "storage": + err = unpopulate(val, "Storage", &u.Storage) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type User. +func (u User) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", u.ID) + populate(objectMap, "name", u.Name) + populate(objectMap, "properties", u.Properties) + populate(objectMap, "systemData", u.SystemData) + populate(objectMap, "type", u.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type User. +func (u *User) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &u.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &u.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &u.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &u.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &u.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserAssignedIdentity. +func (u UserAssignedIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clientId", u.ClientID) + populate(objectMap, "principalId", u.PrincipalID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserAssignedIdentity. +func (u *UserAssignedIdentity) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "clientId": + err = unpopulate(val, "ClientID", &u.ClientID) + delete(rawMsg, key) + case "principalId": + err = unpopulate(val, "PrincipalID", &u.PrincipalID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserListResult. +func (u UserListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", u.NextLink) + populate(objectMap, "value", u.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserListResult. +func (u *UserListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &u.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &u.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UserProperties. +func (u UserProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "identityProvider", u.IdentityProvider) + populate(objectMap, "provisioningState", u.ProvisioningState) + populate(objectMap, "roles", u.Roles) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UserProperties. +func (u *UserProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "identityProvider": + u.IdentityProvider, err = unmarshalIdentityProviderClassification(val) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &u.ProvisioningState) + delete(rawMsg, key) + case "roles": + err = unpopulate(val, "Roles", &u.Roles) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/local/armmongocluster/zz_mongoclusters_client.go b/test/local/armmongocluster/zz_mongoclusters_client.go new file mode 100644 index 000000000000..8e5d93870013 --- /dev/null +++ b/test/local/armmongocluster/zz_mongoclusters_client.go @@ -0,0 +1,646 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmongocluster + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// MongoClustersClient contains the methods for the MongoClusters group. +// Don't use this type directly, use NewMongoClustersClient() instead. +// +// Generated from API version 2026-06-01 +type MongoClustersClient struct { + internal *arm.Client + subscriptionID string +} + +// NewMongoClustersClient creates a new instance of MongoClustersClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewMongoClustersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*MongoClustersClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &MongoClustersClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// CheckNameAvailability - Check if mongo cluster name is available for use. +// If the operation fails it returns an *azcore.ResponseError type. +// - location - The name of the Azure region. +// - body - The CheckAvailability request +// - options - MongoClustersClientCheckNameAvailabilityOptions contains the optional parameters for the MongoClustersClient.CheckNameAvailability +// method. +func (client *MongoClustersClient) CheckNameAvailability(ctx context.Context, location string, body CheckNameAvailabilityRequest, options *MongoClustersClientCheckNameAvailabilityOptions) (MongoClustersClientCheckNameAvailabilityResponse, error) { + var err error + const operationName = "MongoClustersClient.CheckNameAvailability" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.checkNameAvailabilityCreateRequest(ctx, location, body, options) + if err != nil { + return MongoClustersClientCheckNameAvailabilityResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MongoClustersClientCheckNameAvailabilityResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return MongoClustersClientCheckNameAvailabilityResponse{}, err + } + resp, err := client.checkNameAvailabilityHandleResponse(httpResp) + return resp, err +} + +// checkNameAvailabilityCreateRequest creates the CheckNameAvailability request. +func (client *MongoClustersClient) checkNameAvailabilityCreateRequest(ctx context.Context, location string, body CheckNameAvailabilityRequest, _ *MongoClustersClientCheckNameAvailabilityOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/locations/{location}/checkMongoClusterNameAvailability" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260601) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// checkNameAvailabilityHandleResponse handles the CheckNameAvailability response. +func (client *MongoClustersClient) checkNameAvailabilityHandleResponse(resp *http.Response) (MongoClustersClientCheckNameAvailabilityResponse, error) { + result := MongoClustersClientCheckNameAvailabilityResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CheckNameAvailabilityResponse); err != nil { + return MongoClustersClientCheckNameAvailabilityResponse{}, err + } + return result, nil +} + +// BeginCreateOrUpdate - Create or update a mongo cluster. Update overwrites all properties for the resource. To only modify +// some of the properties, use PATCH. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - mongoClusterName - The name of the mongo cluster. +// - resource - Resource create parameters. +// - options - MongoClustersClientBeginCreateOrUpdateOptions contains the optional parameters for the MongoClustersClient.BeginCreateOrUpdate +// method. +func (client *MongoClustersClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, mongoClusterName string, resource MongoCluster, options *MongoClustersClientBeginCreateOrUpdateOptions) (*runtime.Poller[MongoClustersClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, mongoClusterName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[MongoClustersClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[MongoClustersClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create or update a mongo cluster. Update overwrites all properties for the resource. To only modify some +// of the properties, use PATCH. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *MongoClustersClient) createOrUpdate(ctx context.Context, resourceGroupName string, mongoClusterName string, resource MongoCluster, options *MongoClustersClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "MongoClustersClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, mongoClusterName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *MongoClustersClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, mongoClusterName string, resource MongoCluster, _ *MongoClustersClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if mongoClusterName == "" { + return nil, errors.New("parameter mongoClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{mongoClusterName}", url.PathEscape(mongoClusterName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260601) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a mongo cluster. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - mongoClusterName - The name of the mongo cluster. +// - options - MongoClustersClientBeginDeleteOptions contains the optional parameters for the MongoClustersClient.BeginDelete +// method. +func (client *MongoClustersClient) BeginDelete(ctx context.Context, resourceGroupName string, mongoClusterName string, options *MongoClustersClientBeginDeleteOptions) (*runtime.Poller[MongoClustersClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, mongoClusterName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[MongoClustersClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[MongoClustersClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a mongo cluster. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *MongoClustersClient) deleteOperation(ctx context.Context, resourceGroupName string, mongoClusterName string, options *MongoClustersClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "MongoClustersClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, mongoClusterName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *MongoClustersClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, mongoClusterName string, _ *MongoClustersClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if mongoClusterName == "" { + return nil, errors.New("parameter mongoClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{mongoClusterName}", url.PathEscape(mongoClusterName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260601) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Gets information about a mongo cluster. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - mongoClusterName - The name of the mongo cluster. +// - options - MongoClustersClientGetOptions contains the optional parameters for the MongoClustersClient.Get method. +func (client *MongoClustersClient) Get(ctx context.Context, resourceGroupName string, mongoClusterName string, options *MongoClustersClientGetOptions) (MongoClustersClientGetResponse, error) { + var err error + const operationName = "MongoClustersClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, mongoClusterName, options) + if err != nil { + return MongoClustersClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MongoClustersClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return MongoClustersClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *MongoClustersClient) getCreateRequest(ctx context.Context, resourceGroupName string, mongoClusterName string, _ *MongoClustersClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if mongoClusterName == "" { + return nil, errors.New("parameter mongoClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{mongoClusterName}", url.PathEscape(mongoClusterName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260601) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *MongoClustersClient) getHandleResponse(resp *http.Response) (MongoClustersClientGetResponse, error) { + result := MongoClustersClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.MongoCluster); err != nil { + return MongoClustersClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List all the mongo clusters in a given subscription. +// - options - MongoClustersClientListOptions contains the optional parameters for the MongoClustersClient.NewListPager method. +func (client *MongoClustersClient) NewListPager(options *MongoClustersClientListOptions) *runtime.Pager[MongoClustersClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[MongoClustersClientListResponse]{ + More: func(page MongoClustersClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *MongoClustersClientListResponse) (MongoClustersClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "MongoClustersClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return MongoClustersClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *MongoClustersClient) listCreateRequest(ctx context.Context, _ *MongoClustersClientListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.DocumentDB/mongoClusters" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260601) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *MongoClustersClient) listHandleResponse(resp *http.Response) (MongoClustersClientListResponse, error) { + result := MongoClustersClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListResult); err != nil { + return MongoClustersClientListResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - List all the mongo clusters in a given resource group. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - MongoClustersClientListByResourceGroupOptions contains the optional parameters for the MongoClustersClient.NewListByResourceGroupPager +// method. +func (client *MongoClustersClient) NewListByResourceGroupPager(resourceGroupName string, options *MongoClustersClientListByResourceGroupOptions) *runtime.Pager[MongoClustersClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[MongoClustersClientListByResourceGroupResponse]{ + More: func(page MongoClustersClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *MongoClustersClientListByResourceGroupResponse) (MongoClustersClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "MongoClustersClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return MongoClustersClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *MongoClustersClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *MongoClustersClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260601) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *MongoClustersClient) listByResourceGroupHandleResponse(resp *http.Response) (MongoClustersClientListByResourceGroupResponse, error) { + result := MongoClustersClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListResult); err != nil { + return MongoClustersClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// ListConnectionStrings - List mongo cluster connection strings. This includes the default connection string using SCRAM-SHA-256, +// as well as other connection strings supported by the cluster. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - mongoClusterName - The name of the mongo cluster. +// - options - MongoClustersClientListConnectionStringsOptions contains the optional parameters for the MongoClustersClient.ListConnectionStrings +// method. +func (client *MongoClustersClient) ListConnectionStrings(ctx context.Context, resourceGroupName string, mongoClusterName string, options *MongoClustersClientListConnectionStringsOptions) (MongoClustersClientListConnectionStringsResponse, error) { + var err error + const operationName = "MongoClustersClient.ListConnectionStrings" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listConnectionStringsCreateRequest(ctx, resourceGroupName, mongoClusterName, options) + if err != nil { + return MongoClustersClientListConnectionStringsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MongoClustersClientListConnectionStringsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return MongoClustersClientListConnectionStringsResponse{}, err + } + resp, err := client.listConnectionStringsHandleResponse(httpResp) + return resp, err +} + +// listConnectionStringsCreateRequest creates the ListConnectionStrings request. +func (client *MongoClustersClient) listConnectionStringsCreateRequest(ctx context.Context, resourceGroupName string, mongoClusterName string, _ *MongoClustersClientListConnectionStringsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}/listConnectionStrings" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if mongoClusterName == "" { + return nil, errors.New("parameter mongoClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{mongoClusterName}", url.PathEscape(mongoClusterName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260601) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listConnectionStringsHandleResponse handles the ListConnectionStrings response. +func (client *MongoClustersClient) listConnectionStringsHandleResponse(resp *http.Response) (MongoClustersClientListConnectionStringsResponse, error) { + result := MongoClustersClientListConnectionStringsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ListConnectionStringsResult); err != nil { + return MongoClustersClientListConnectionStringsResponse{}, err + } + return result, nil +} + +// BeginPromote - Promotes a replica mongo cluster to a primary role. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - mongoClusterName - The name of the mongo cluster. +// - body - The content of the action request +// - options - MongoClustersClientBeginPromoteOptions contains the optional parameters for the MongoClustersClient.BeginPromote +// method. +func (client *MongoClustersClient) BeginPromote(ctx context.Context, resourceGroupName string, mongoClusterName string, body PromoteReplicaRequest, options *MongoClustersClientBeginPromoteOptions) (*runtime.Poller[MongoClustersClientPromoteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.promote(ctx, resourceGroupName, mongoClusterName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[MongoClustersClientPromoteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[MongoClustersClientPromoteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Promote - Promotes a replica mongo cluster to a primary role. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *MongoClustersClient) promote(ctx context.Context, resourceGroupName string, mongoClusterName string, body PromoteReplicaRequest, options *MongoClustersClientBeginPromoteOptions) (*http.Response, error) { + var err error + const operationName = "MongoClustersClient.BeginPromote" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.promoteCreateRequest(ctx, resourceGroupName, mongoClusterName, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// promoteCreateRequest creates the Promote request. +func (client *MongoClustersClient) promoteCreateRequest(ctx context.Context, resourceGroupName string, mongoClusterName string, body PromoteReplicaRequest, _ *MongoClustersClientBeginPromoteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}/promote" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if mongoClusterName == "" { + return nil, errors.New("parameter mongoClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{mongoClusterName}", url.PathEscape(mongoClusterName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260601) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// BeginUpdate - Updates an existing mongo cluster. The request body can contain one to many of the properties present in +// the normal mongo cluster definition. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - mongoClusterName - The name of the mongo cluster. +// - properties - The resource properties to be updated. +// - options - MongoClustersClientBeginUpdateOptions contains the optional parameters for the MongoClustersClient.BeginUpdate +// method. +func (client *MongoClustersClient) BeginUpdate(ctx context.Context, resourceGroupName string, mongoClusterName string, properties Update, options *MongoClustersClientBeginUpdateOptions) (*runtime.Poller[MongoClustersClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, mongoClusterName, properties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[MongoClustersClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[MongoClustersClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Updates an existing mongo cluster. The request body can contain one to many of the properties present in the normal +// mongo cluster definition. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *MongoClustersClient) update(ctx context.Context, resourceGroupName string, mongoClusterName string, properties Update, options *MongoClustersClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "MongoClustersClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, mongoClusterName, properties, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *MongoClustersClient) updateCreateRequest(ctx context.Context, resourceGroupName string, mongoClusterName string, properties Update, _ *MongoClustersClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if mongoClusterName == "" { + return nil, errors.New("parameter mongoClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{mongoClusterName}", url.PathEscape(mongoClusterName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260601) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armmongocluster/zz_operations_client.go b/test/local/armmongocluster/zz_operations_client.go new file mode 100644 index 000000000000..444d64569c13 --- /dev/null +++ b/test/local/armmongocluster/zz_operations_client.go @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmongocluster + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +// +// Generated from API version 2026-06-01 +type OperationsClient struct { + internal *arm.Client +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*OperationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OperationsClient{ + internal: cl, + } + return client, nil +} + +// NewListPager - List the operations for the provider +// - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ + More: func(page OperationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OperationsClientListResponse) (OperationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OperationsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return OperationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, _ *OperationsClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.DocumentDB/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260601) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsClientListResponse, error) { + result := OperationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armmongocluster/zz_options.go b/test/local/armmongocluster/zz_options.go new file mode 100644 index 000000000000..a050e68aed3c --- /dev/null +++ b/test/local/armmongocluster/zz_options.go @@ -0,0 +1,146 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmongocluster + +// FirewallRulesClientBeginCreateOrUpdateOptions contains the optional parameters for the FirewallRulesClient.BeginCreateOrUpdate +// method. +type FirewallRulesClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// FirewallRulesClientBeginDeleteOptions contains the optional parameters for the FirewallRulesClient.BeginDelete method. +type FirewallRulesClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// FirewallRulesClientGetOptions contains the optional parameters for the FirewallRulesClient.Get method. +type FirewallRulesClientGetOptions struct { + // placeholder for future optional parameters +} + +// FirewallRulesClientListByMongoClusterOptions contains the optional parameters for the FirewallRulesClient.NewListByMongoClusterPager +// method. +type FirewallRulesClientListByMongoClusterOptions struct { + // placeholder for future optional parameters +} + +// MongoClustersClientBeginCreateOrUpdateOptions contains the optional parameters for the MongoClustersClient.BeginCreateOrUpdate +// method. +type MongoClustersClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// MongoClustersClientBeginDeleteOptions contains the optional parameters for the MongoClustersClient.BeginDelete method. +type MongoClustersClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// MongoClustersClientBeginPromoteOptions contains the optional parameters for the MongoClustersClient.BeginPromote method. +type MongoClustersClientBeginPromoteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// MongoClustersClientBeginUpdateOptions contains the optional parameters for the MongoClustersClient.BeginUpdate method. +type MongoClustersClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// MongoClustersClientCheckNameAvailabilityOptions contains the optional parameters for the MongoClustersClient.CheckNameAvailability +// method. +type MongoClustersClientCheckNameAvailabilityOptions struct { + // placeholder for future optional parameters +} + +// MongoClustersClientGetOptions contains the optional parameters for the MongoClustersClient.Get method. +type MongoClustersClientGetOptions struct { + // placeholder for future optional parameters +} + +// MongoClustersClientListByResourceGroupOptions contains the optional parameters for the MongoClustersClient.NewListByResourceGroupPager +// method. +type MongoClustersClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// MongoClustersClientListConnectionStringsOptions contains the optional parameters for the MongoClustersClient.ListConnectionStrings +// method. +type MongoClustersClientListConnectionStringsOptions struct { + // placeholder for future optional parameters +} + +// MongoClustersClientListOptions contains the optional parameters for the MongoClustersClient.NewListPager method. +type MongoClustersClientListOptions struct { + // placeholder for future optional parameters +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointConnectionsClientBeginCreateOptions contains the optional parameters for the PrivateEndpointConnectionsClient.BeginCreate +// method. +type PrivateEndpointConnectionsClientBeginCreateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// PrivateEndpointConnectionsClientBeginDeleteOptions contains the optional parameters for the PrivateEndpointConnectionsClient.BeginDelete +// method. +type PrivateEndpointConnectionsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// PrivateEndpointConnectionsClientGetOptions contains the optional parameters for the PrivateEndpointConnectionsClient.Get +// method. +type PrivateEndpointConnectionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointConnectionsClientListByMongoClusterOptions contains the optional parameters for the PrivateEndpointConnectionsClient.NewListByMongoClusterPager +// method. +type PrivateEndpointConnectionsClientListByMongoClusterOptions struct { + // placeholder for future optional parameters +} + +// PrivateLinksClientListByMongoClusterOptions contains the optional parameters for the PrivateLinksClient.NewListByMongoClusterPager +// method. +type PrivateLinksClientListByMongoClusterOptions struct { + // placeholder for future optional parameters +} + +// ReplicasClientListByParentOptions contains the optional parameters for the ReplicasClient.NewListByParentPager method. +type ReplicasClientListByParentOptions struct { + // placeholder for future optional parameters +} + +// UsersClientBeginCreateOrUpdateOptions contains the optional parameters for the UsersClient.BeginCreateOrUpdate method. +type UsersClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// UsersClientBeginDeleteOptions contains the optional parameters for the UsersClient.BeginDelete method. +type UsersClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// UsersClientGetOptions contains the optional parameters for the UsersClient.Get method. +type UsersClientGetOptions struct { + // placeholder for future optional parameters +} + +// UsersClientListByMongoClusterOptions contains the optional parameters for the UsersClient.NewListByMongoClusterPager method. +type UsersClientListByMongoClusterOptions struct { + // placeholder for future optional parameters +} diff --git a/test/local/armmongocluster/zz_polymorphic_helpers.go b/test/local/armmongocluster/zz_polymorphic_helpers.go new file mode 100644 index 000000000000..bb52fc0ed6ea --- /dev/null +++ b/test/local/armmongocluster/zz_polymorphic_helpers.go @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmongocluster + +import "encoding/json" + +func unmarshalIdentityProviderClassification(rawMsg json.RawMessage) (IdentityProviderClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b IdentityProviderClassification + switch m["type"] { + case string(IdentityProviderTypeMicrosoftEntraID): + b = &EntraIdentityProvider{} + default: + b = &IdentityProvider{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} diff --git a/test/local/armmongocluster/zz_privateendpointconnections_client.go b/test/local/armmongocluster/zz_privateendpointconnections_client.go new file mode 100644 index 000000000000..8e7f82a1065a --- /dev/null +++ b/test/local/armmongocluster/zz_privateendpointconnections_client.go @@ -0,0 +1,332 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmongocluster + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// PrivateEndpointConnectionsClient contains the methods for the PrivateEndpointConnections group. +// Don't use this type directly, use NewPrivateEndpointConnectionsClient() instead. +// +// Generated from API version 2026-06-01 +type PrivateEndpointConnectionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewPrivateEndpointConnectionsClient creates a new instance of PrivateEndpointConnectionsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewPrivateEndpointConnectionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*PrivateEndpointConnectionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &PrivateEndpointConnectionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreate - Create a Private endpoint connection +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - mongoClusterName - The name of the mongo cluster. +// - privateEndpointConnectionName - The name of the private endpoint connection associated with the Azure resource. +// - resource - Resource create parameters. +// - options - PrivateEndpointConnectionsClientBeginCreateOptions contains the optional parameters for the PrivateEndpointConnectionsClient.BeginCreate +// method. +func (client *PrivateEndpointConnectionsClient) BeginCreate(ctx context.Context, resourceGroupName string, mongoClusterName string, privateEndpointConnectionName string, resource PrivateEndpointConnectionResource, options *PrivateEndpointConnectionsClientBeginCreateOptions) (*runtime.Poller[PrivateEndpointConnectionsClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, resourceGroupName, mongoClusterName, privateEndpointConnectionName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PrivateEndpointConnectionsClientCreateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PrivateEndpointConnectionsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Create a Private endpoint connection +// If the operation fails it returns an *azcore.ResponseError type. +func (client *PrivateEndpointConnectionsClient) create(ctx context.Context, resourceGroupName string, mongoClusterName string, privateEndpointConnectionName string, resource PrivateEndpointConnectionResource, options *PrivateEndpointConnectionsClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "PrivateEndpointConnectionsClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, mongoClusterName, privateEndpointConnectionName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *PrivateEndpointConnectionsClient) createCreateRequest(ctx context.Context, resourceGroupName string, mongoClusterName string, privateEndpointConnectionName string, resource PrivateEndpointConnectionResource, _ *PrivateEndpointConnectionsClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}/privateEndpointConnections/{privateEndpointConnectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if mongoClusterName == "" { + return nil, errors.New("parameter mongoClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{mongoClusterName}", url.PathEscape(mongoClusterName)) + if privateEndpointConnectionName == "" { + return nil, errors.New("parameter privateEndpointConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260601) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete the private endpoint connection +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - mongoClusterName - The name of the mongo cluster. +// - privateEndpointConnectionName - The name of the private endpoint connection associated with the Azure resource. +// - options - PrivateEndpointConnectionsClientBeginDeleteOptions contains the optional parameters for the PrivateEndpointConnectionsClient.BeginDelete +// method. +func (client *PrivateEndpointConnectionsClient) BeginDelete(ctx context.Context, resourceGroupName string, mongoClusterName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsClientBeginDeleteOptions) (*runtime.Poller[PrivateEndpointConnectionsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, mongoClusterName, privateEndpointConnectionName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[PrivateEndpointConnectionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[PrivateEndpointConnectionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete the private endpoint connection +// If the operation fails it returns an *azcore.ResponseError type. +func (client *PrivateEndpointConnectionsClient) deleteOperation(ctx context.Context, resourceGroupName string, mongoClusterName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "PrivateEndpointConnectionsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, mongoClusterName, privateEndpointConnectionName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *PrivateEndpointConnectionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, mongoClusterName string, privateEndpointConnectionName string, _ *PrivateEndpointConnectionsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}/privateEndpointConnections/{privateEndpointConnectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if mongoClusterName == "" { + return nil, errors.New("parameter mongoClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{mongoClusterName}", url.PathEscape(mongoClusterName)) + if privateEndpointConnectionName == "" { + return nil, errors.New("parameter privateEndpointConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260601) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a specific private connection +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - mongoClusterName - The name of the mongo cluster. +// - privateEndpointConnectionName - The name of the private endpoint connection associated with the Azure resource. +// - options - PrivateEndpointConnectionsClientGetOptions contains the optional parameters for the PrivateEndpointConnectionsClient.Get +// method. +func (client *PrivateEndpointConnectionsClient) Get(ctx context.Context, resourceGroupName string, mongoClusterName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsClientGetOptions) (PrivateEndpointConnectionsClientGetResponse, error) { + var err error + const operationName = "PrivateEndpointConnectionsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, mongoClusterName, privateEndpointConnectionName, options) + if err != nil { + return PrivateEndpointConnectionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PrivateEndpointConnectionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PrivateEndpointConnectionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *PrivateEndpointConnectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, mongoClusterName string, privateEndpointConnectionName string, _ *PrivateEndpointConnectionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}/privateEndpointConnections/{privateEndpointConnectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if mongoClusterName == "" { + return nil, errors.New("parameter mongoClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{mongoClusterName}", url.PathEscape(mongoClusterName)) + if privateEndpointConnectionName == "" { + return nil, errors.New("parameter privateEndpointConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260601) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *PrivateEndpointConnectionsClient) getHandleResponse(resp *http.Response) (PrivateEndpointConnectionsClientGetResponse, error) { + result := PrivateEndpointConnectionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnectionResource); err != nil { + return PrivateEndpointConnectionsClientGetResponse{}, err + } + return result, nil +} + +// NewListByMongoClusterPager - List existing private connections +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - mongoClusterName - The name of the mongo cluster. +// - options - PrivateEndpointConnectionsClientListByMongoClusterOptions contains the optional parameters for the PrivateEndpointConnectionsClient.NewListByMongoClusterPager +// method. +func (client *PrivateEndpointConnectionsClient) NewListByMongoClusterPager(resourceGroupName string, mongoClusterName string, options *PrivateEndpointConnectionsClientListByMongoClusterOptions) *runtime.Pager[PrivateEndpointConnectionsClientListByMongoClusterResponse] { + return runtime.NewPager(runtime.PagingHandler[PrivateEndpointConnectionsClientListByMongoClusterResponse]{ + More: func(page PrivateEndpointConnectionsClientListByMongoClusterResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PrivateEndpointConnectionsClientListByMongoClusterResponse) (PrivateEndpointConnectionsClientListByMongoClusterResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PrivateEndpointConnectionsClient.NewListByMongoClusterPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByMongoClusterCreateRequest(ctx, resourceGroupName, mongoClusterName, options) + }, nil) + if err != nil { + return PrivateEndpointConnectionsClientListByMongoClusterResponse{}, err + } + return client.listByMongoClusterHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByMongoClusterCreateRequest creates the ListByMongoCluster request. +func (client *PrivateEndpointConnectionsClient) listByMongoClusterCreateRequest(ctx context.Context, resourceGroupName string, mongoClusterName string, _ *PrivateEndpointConnectionsClientListByMongoClusterOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}/privateEndpointConnections" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if mongoClusterName == "" { + return nil, errors.New("parameter mongoClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{mongoClusterName}", url.PathEscape(mongoClusterName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260601) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByMongoClusterHandleResponse handles the ListByMongoCluster response. +func (client *PrivateEndpointConnectionsClient) listByMongoClusterHandleResponse(resp *http.Response) (PrivateEndpointConnectionsClientListByMongoClusterResponse, error) { + result := PrivateEndpointConnectionsClientListByMongoClusterResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnectionResourceListResult); err != nil { + return PrivateEndpointConnectionsClientListByMongoClusterResponse{}, err + } + return result, nil +} diff --git a/test/local/armmongocluster/zz_privatelinks_client.go b/test/local/armmongocluster/zz_privatelinks_client.go new file mode 100644 index 000000000000..0003b606ef32 --- /dev/null +++ b/test/local/armmongocluster/zz_privatelinks_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmongocluster + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// PrivateLinksClient contains the methods for the PrivateLinks group. +// Don't use this type directly, use NewPrivateLinksClient() instead. +// +// Generated from API version 2026-06-01 +type PrivateLinksClient struct { + internal *arm.Client + subscriptionID string +} + +// NewPrivateLinksClient creates a new instance of PrivateLinksClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewPrivateLinksClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*PrivateLinksClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &PrivateLinksClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListByMongoClusterPager - list private links on the given resource +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - mongoClusterName - The name of the mongo cluster. +// - options - PrivateLinksClientListByMongoClusterOptions contains the optional parameters for the PrivateLinksClient.NewListByMongoClusterPager +// method. +func (client *PrivateLinksClient) NewListByMongoClusterPager(resourceGroupName string, mongoClusterName string, options *PrivateLinksClientListByMongoClusterOptions) *runtime.Pager[PrivateLinksClientListByMongoClusterResponse] { + return runtime.NewPager(runtime.PagingHandler[PrivateLinksClientListByMongoClusterResponse]{ + More: func(page PrivateLinksClientListByMongoClusterResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *PrivateLinksClientListByMongoClusterResponse) (PrivateLinksClientListByMongoClusterResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "PrivateLinksClient.NewListByMongoClusterPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByMongoClusterCreateRequest(ctx, resourceGroupName, mongoClusterName, options) + }, nil) + if err != nil { + return PrivateLinksClientListByMongoClusterResponse{}, err + } + return client.listByMongoClusterHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByMongoClusterCreateRequest creates the ListByMongoCluster request. +func (client *PrivateLinksClient) listByMongoClusterCreateRequest(ctx context.Context, resourceGroupName string, mongoClusterName string, _ *PrivateLinksClientListByMongoClusterOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}/privateLinkResources" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if mongoClusterName == "" { + return nil, errors.New("parameter mongoClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{mongoClusterName}", url.PathEscape(mongoClusterName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260601) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByMongoClusterHandleResponse handles the ListByMongoCluster response. +func (client *PrivateLinksClient) listByMongoClusterHandleResponse(resp *http.Response) (PrivateLinksClientListByMongoClusterResponse, error) { + result := PrivateLinksClientListByMongoClusterResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateLinkResourceListResult); err != nil { + return PrivateLinksClientListByMongoClusterResponse{}, err + } + return result, nil +} diff --git a/test/local/armmongocluster/zz_replicas_client.go b/test/local/armmongocluster/zz_replicas_client.go new file mode 100644 index 000000000000..a92381f2ba16 --- /dev/null +++ b/test/local/armmongocluster/zz_replicas_client.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmongocluster + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ReplicasClient contains the methods for the Replicas group. +// Don't use this type directly, use NewReplicasClient() instead. +// +// Generated from API version 2026-06-01 +type ReplicasClient struct { + internal *arm.Client + subscriptionID string +} + +// NewReplicasClient creates a new instance of ReplicasClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewReplicasClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ReplicasClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ReplicasClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NewListByParentPager - List all the replicas for the mongo cluster. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - mongoClusterName - The name of the mongo cluster. +// - options - ReplicasClientListByParentOptions contains the optional parameters for the ReplicasClient.NewListByParentPager +// method. +func (client *ReplicasClient) NewListByParentPager(resourceGroupName string, mongoClusterName string, options *ReplicasClientListByParentOptions) *runtime.Pager[ReplicasClientListByParentResponse] { + return runtime.NewPager(runtime.PagingHandler[ReplicasClientListByParentResponse]{ + More: func(page ReplicasClientListByParentResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ReplicasClientListByParentResponse) (ReplicasClientListByParentResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ReplicasClient.NewListByParentPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByParentCreateRequest(ctx, resourceGroupName, mongoClusterName, options) + }, nil) + if err != nil { + return ReplicasClientListByParentResponse{}, err + } + return client.listByParentHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByParentCreateRequest creates the ListByParent request. +func (client *ReplicasClient) listByParentCreateRequest(ctx context.Context, resourceGroupName string, mongoClusterName string, _ *ReplicasClientListByParentOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}/replicas" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if mongoClusterName == "" { + return nil, errors.New("parameter mongoClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{mongoClusterName}", url.PathEscape(mongoClusterName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260601) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByParentHandleResponse handles the ListByParent response. +func (client *ReplicasClient) listByParentHandleResponse(resp *http.Response) (ReplicasClientListByParentResponse, error) { + result := ReplicasClientListByParentResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ReplicaListResult); err != nil { + return ReplicasClientListByParentResponse{}, err + } + return result, nil +} diff --git a/test/local/armmongocluster/zz_responses.go b/test/local/armmongocluster/zz_responses.go new file mode 100644 index 000000000000..424f84d3fd24 --- /dev/null +++ b/test/local/armmongocluster/zz_responses.go @@ -0,0 +1,144 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmongocluster + +// FirewallRulesClientCreateOrUpdateResponse contains the response from method FirewallRulesClient.BeginCreateOrUpdate. +type FirewallRulesClientCreateOrUpdateResponse struct { + // Represents a mongo cluster firewall rule. + FirewallRule +} + +// FirewallRulesClientDeleteResponse contains the response from method FirewallRulesClient.BeginDelete. +type FirewallRulesClientDeleteResponse struct { + // placeholder for future response values +} + +// FirewallRulesClientGetResponse contains the response from method FirewallRulesClient.Get. +type FirewallRulesClientGetResponse struct { + // Represents a mongo cluster firewall rule. + FirewallRule +} + +// FirewallRulesClientListByMongoClusterResponse contains the response from method FirewallRulesClient.NewListByMongoClusterPager. +type FirewallRulesClientListByMongoClusterResponse struct { + // The response of a FirewallRule list operation. + FirewallRuleListResult +} + +// MongoClustersClientCheckNameAvailabilityResponse contains the response from method MongoClustersClient.CheckNameAvailability. +type MongoClustersClientCheckNameAvailabilityResponse struct { + // The check availability result. + CheckNameAvailabilityResponse +} + +// MongoClustersClientCreateOrUpdateResponse contains the response from method MongoClustersClient.BeginCreateOrUpdate. +type MongoClustersClientCreateOrUpdateResponse struct { + // Represents a mongo cluster resource. + MongoCluster +} + +// MongoClustersClientDeleteResponse contains the response from method MongoClustersClient.BeginDelete. +type MongoClustersClientDeleteResponse struct { + // placeholder for future response values +} + +// MongoClustersClientGetResponse contains the response from method MongoClustersClient.Get. +type MongoClustersClientGetResponse struct { + // Represents a mongo cluster resource. + MongoCluster +} + +// MongoClustersClientListByResourceGroupResponse contains the response from method MongoClustersClient.NewListByResourceGroupPager. +type MongoClustersClientListByResourceGroupResponse struct { + // The response of a MongoCluster list operation. + ListResult +} + +// MongoClustersClientListConnectionStringsResponse contains the response from method MongoClustersClient.ListConnectionStrings. +type MongoClustersClientListConnectionStringsResponse struct { + // The connection strings for the given mongo cluster. + ListConnectionStringsResult +} + +// MongoClustersClientListResponse contains the response from method MongoClustersClient.NewListPager. +type MongoClustersClientListResponse struct { + // The response of a MongoCluster list operation. + ListResult +} + +// MongoClustersClientPromoteResponse contains the response from method MongoClustersClient.BeginPromote. +type MongoClustersClientPromoteResponse struct { + // placeholder for future response values +} + +// MongoClustersClientUpdateResponse contains the response from method MongoClustersClient.BeginUpdate. +type MongoClustersClientUpdateResponse struct { + // Represents a mongo cluster resource. + MongoCluster +} + +// OperationsClientListResponse contains the response from method OperationsClient.NewListPager. +type OperationsClientListResponse struct { + // A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. + OperationListResult +} + +// PrivateEndpointConnectionsClientCreateResponse contains the response from method PrivateEndpointConnectionsClient.BeginCreate. +type PrivateEndpointConnectionsClientCreateResponse struct { + // Concrete proxy resource types can be created by aliasing this type using a specific property type. + PrivateEndpointConnectionResource +} + +// PrivateEndpointConnectionsClientDeleteResponse contains the response from method PrivateEndpointConnectionsClient.BeginDelete. +type PrivateEndpointConnectionsClientDeleteResponse struct { + // placeholder for future response values +} + +// PrivateEndpointConnectionsClientGetResponse contains the response from method PrivateEndpointConnectionsClient.Get. +type PrivateEndpointConnectionsClientGetResponse struct { + // Concrete proxy resource types can be created by aliasing this type using a specific property type. + PrivateEndpointConnectionResource +} + +// PrivateEndpointConnectionsClientListByMongoClusterResponse contains the response from method PrivateEndpointConnectionsClient.NewListByMongoClusterPager. +type PrivateEndpointConnectionsClientListByMongoClusterResponse struct { + // The response of a PrivateEndpointConnectionResource list operation. + PrivateEndpointConnectionResourceListResult +} + +// PrivateLinksClientListByMongoClusterResponse contains the response from method PrivateLinksClient.NewListByMongoClusterPager. +type PrivateLinksClientListByMongoClusterResponse struct { + // The response of a PrivateLinkResource list operation. + PrivateLinkResourceListResult +} + +// ReplicasClientListByParentResponse contains the response from method ReplicasClient.NewListByParentPager. +type ReplicasClientListByParentResponse struct { + // The response of a Replica list operation. + ReplicaListResult +} + +// UsersClientCreateOrUpdateResponse contains the response from method UsersClient.BeginCreateOrUpdate. +type UsersClientCreateOrUpdateResponse struct { + // Represents a Mongo cluster user. + User +} + +// UsersClientDeleteResponse contains the response from method UsersClient.BeginDelete. +type UsersClientDeleteResponse struct { + // placeholder for future response values +} + +// UsersClientGetResponse contains the response from method UsersClient.Get. +type UsersClientGetResponse struct { + // Represents a Mongo cluster user. + User +} + +// UsersClientListByMongoClusterResponse contains the response from method UsersClient.NewListByMongoClusterPager. +type UsersClientListByMongoClusterResponse struct { + // The response of a User list operation. + UserListResult +} diff --git a/test/local/armmongocluster/zz_users_client.go b/test/local/armmongocluster/zz_users_client.go new file mode 100644 index 000000000000..9ea07cbc2433 --- /dev/null +++ b/test/local/armmongocluster/zz_users_client.go @@ -0,0 +1,330 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armmongocluster + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// UsersClient contains the methods for the Users group. +// Don't use this type directly, use NewUsersClient() instead. +// +// Generated from API version 2026-06-01 +type UsersClient struct { + internal *arm.Client + subscriptionID string +} + +// NewUsersClient creates a new instance of UsersClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewUsersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*UsersClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &UsersClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Creates a new user or updates an existing user on a mongo cluster. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - mongoClusterName - The name of the mongo cluster. +// - userName - The name of the mongo cluster user. +// - resource - Resource create parameters. +// - options - UsersClientBeginCreateOrUpdateOptions contains the optional parameters for the UsersClient.BeginCreateOrUpdate +// method. +func (client *UsersClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, mongoClusterName string, userName string, resource User, options *UsersClientBeginCreateOrUpdateOptions) (*runtime.Poller[UsersClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, mongoClusterName, userName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[UsersClientCreateOrUpdateResponse]{ + FinalStateVia: runtime.FinalStateViaAzureAsyncOp, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[UsersClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Creates a new user or updates an existing user on a mongo cluster. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *UsersClient) createOrUpdate(ctx context.Context, resourceGroupName string, mongoClusterName string, userName string, resource User, options *UsersClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "UsersClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, mongoClusterName, userName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *UsersClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, mongoClusterName string, userName string, resource User, _ *UsersClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}/users/{userName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if mongoClusterName == "" { + return nil, errors.New("parameter mongoClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{mongoClusterName}", url.PathEscape(mongoClusterName)) + if userName == "" { + return nil, errors.New("parameter userName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{userName}", url.PathEscape(userName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260601) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Deletes a mongo cluster user. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - mongoClusterName - The name of the mongo cluster. +// - userName - The name of the mongo cluster user. +// - options - UsersClientBeginDeleteOptions contains the optional parameters for the UsersClient.BeginDelete method. +func (client *UsersClient) BeginDelete(ctx context.Context, resourceGroupName string, mongoClusterName string, userName string, options *UsersClientBeginDeleteOptions) (*runtime.Poller[UsersClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, mongoClusterName, userName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[UsersClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[UsersClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Deletes a mongo cluster user. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *UsersClient) deleteOperation(ctx context.Context, resourceGroupName string, mongoClusterName string, userName string, options *UsersClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "UsersClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, mongoClusterName, userName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *UsersClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, mongoClusterName string, userName string, _ *UsersClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}/users/{userName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if mongoClusterName == "" { + return nil, errors.New("parameter mongoClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{mongoClusterName}", url.PathEscape(mongoClusterName)) + if userName == "" { + return nil, errors.New("parameter userName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{userName}", url.PathEscape(userName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260601) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Gets the defintion of a Mongo cluster user. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - mongoClusterName - The name of the mongo cluster. +// - userName - The name of the mongo cluster user. +// - options - UsersClientGetOptions contains the optional parameters for the UsersClient.Get method. +func (client *UsersClient) Get(ctx context.Context, resourceGroupName string, mongoClusterName string, userName string, options *UsersClientGetOptions) (UsersClientGetResponse, error) { + var err error + const operationName = "UsersClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, mongoClusterName, userName, options) + if err != nil { + return UsersClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return UsersClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return UsersClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *UsersClient) getCreateRequest(ctx context.Context, resourceGroupName string, mongoClusterName string, userName string, _ *UsersClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}/users/{userName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if mongoClusterName == "" { + return nil, errors.New("parameter mongoClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{mongoClusterName}", url.PathEscape(mongoClusterName)) + if userName == "" { + return nil, errors.New("parameter userName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{userName}", url.PathEscape(userName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260601) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *UsersClient) getHandleResponse(resp *http.Response) (UsersClientGetResponse, error) { + result := UsersClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.User); err != nil { + return UsersClientGetResponse{}, err + } + return result, nil +} + +// NewListByMongoClusterPager - List all the users on a mongo cluster. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - mongoClusterName - The name of the mongo cluster. +// - options - UsersClientListByMongoClusterOptions contains the optional parameters for the UsersClient.NewListByMongoClusterPager +// method. +func (client *UsersClient) NewListByMongoClusterPager(resourceGroupName string, mongoClusterName string, options *UsersClientListByMongoClusterOptions) *runtime.Pager[UsersClientListByMongoClusterResponse] { + return runtime.NewPager(runtime.PagingHandler[UsersClientListByMongoClusterResponse]{ + More: func(page UsersClientListByMongoClusterResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *UsersClientListByMongoClusterResponse) (UsersClientListByMongoClusterResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "UsersClient.NewListByMongoClusterPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByMongoClusterCreateRequest(ctx, resourceGroupName, mongoClusterName, options) + }, nil) + if err != nil { + return UsersClientListByMongoClusterResponse{}, err + } + return client.listByMongoClusterHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByMongoClusterCreateRequest creates the ListByMongoCluster request. +func (client *UsersClient) listByMongoClusterCreateRequest(ctx context.Context, resourceGroupName string, mongoClusterName string, _ *UsersClientListByMongoClusterOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/mongoClusters/{mongoClusterName}/users" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if mongoClusterName == "" { + return nil, errors.New("parameter mongoClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{mongoClusterName}", url.PathEscape(mongoClusterName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260601) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByMongoClusterHandleResponse handles the ListByMongoCluster response. +func (client *UsersClient) listByMongoClusterHandleResponse(resp *http.Response) (UsersClientListByMongoClusterResponse, error) { + result := UsersClientListByMongoClusterResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.UserListResult); err != nil { + return UsersClientListByMongoClusterResponse{}, err + } + return result, nil +} diff --git a/test/local/armmongocluster/zz_version.go b/test/local/armmongocluster/zz_version.go new file mode 100644 index 000000000000..6edc74e6394e --- /dev/null +++ b/test/local/armmongocluster/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package armmongocluster + +const ( + moduleName = "armmongocluster" + moduleVersion = "v0.1.0" +) diff --git a/test/local/armoracledatabase/LICENSE.txt b/test/local/armoracledatabase/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/local/armoracledatabase/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/local/armoracledatabase/fake/zz_autonomousdatabasebackups_server.go b/test/local/armoracledatabase/fake/zz_autonomousdatabasebackups_server.go new file mode 100644 index 000000000000..07cc9f335836 --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_autonomousdatabasebackups_server.go @@ -0,0 +1,349 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armoracledatabase/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// AutonomousDatabaseBackupsServer is a fake server for instances of the armoracledatabase.AutonomousDatabaseBackupsClient type. +type AutonomousDatabaseBackupsServer struct { + // BeginCreateOrUpdate is the fake for method AutonomousDatabaseBackupsClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, autonomousdatabasename string, adbbackupid string, resource armoracledatabase.AutonomousDatabaseBackup, options *armoracledatabase.AutonomousDatabaseBackupsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armoracledatabase.AutonomousDatabaseBackupsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method AutonomousDatabaseBackupsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, autonomousdatabasename string, adbbackupid string, options *armoracledatabase.AutonomousDatabaseBackupsClientBeginDeleteOptions) (resp azfake.PollerResponder[armoracledatabase.AutonomousDatabaseBackupsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method AutonomousDatabaseBackupsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, autonomousdatabasename string, adbbackupid string, options *armoracledatabase.AutonomousDatabaseBackupsClientGetOptions) (resp azfake.Responder[armoracledatabase.AutonomousDatabaseBackupsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByAutonomousDatabasePager is the fake for method AutonomousDatabaseBackupsClient.NewListByAutonomousDatabasePager + // HTTP status codes to indicate success: http.StatusOK + NewListByAutonomousDatabasePager func(resourceGroupName string, autonomousdatabasename string, options *armoracledatabase.AutonomousDatabaseBackupsClientListByAutonomousDatabaseOptions) (resp azfake.PagerResponder[armoracledatabase.AutonomousDatabaseBackupsClientListByAutonomousDatabaseResponse]) + + // BeginUpdate is the fake for method AutonomousDatabaseBackupsClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, autonomousdatabasename string, adbbackupid string, properties armoracledatabase.AutonomousDatabaseBackupUpdate, options *armoracledatabase.AutonomousDatabaseBackupsClientBeginUpdateOptions) (resp azfake.PollerResponder[armoracledatabase.AutonomousDatabaseBackupsClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewAutonomousDatabaseBackupsServerTransport creates a new instance of AutonomousDatabaseBackupsServerTransport with the provided implementation. +// The returned AutonomousDatabaseBackupsServerTransport instance is connected to an instance of armoracledatabase.AutonomousDatabaseBackupsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAutonomousDatabaseBackupsServerTransport(srv *AutonomousDatabaseBackupsServer) *AutonomousDatabaseBackupsServerTransport { + return &AutonomousDatabaseBackupsServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armoracledatabase.AutonomousDatabaseBackupsClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armoracledatabase.AutonomousDatabaseBackupsClientDeleteResponse]](), + newListByAutonomousDatabasePager: newTracker[azfake.PagerResponder[armoracledatabase.AutonomousDatabaseBackupsClientListByAutonomousDatabaseResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armoracledatabase.AutonomousDatabaseBackupsClientUpdateResponse]](), + } +} + +// AutonomousDatabaseBackupsServerTransport connects instances of armoracledatabase.AutonomousDatabaseBackupsClient to instances of AutonomousDatabaseBackupsServer. +// Don't use this type directly, use NewAutonomousDatabaseBackupsServerTransport instead. +type AutonomousDatabaseBackupsServerTransport struct { + srv *AutonomousDatabaseBackupsServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armoracledatabase.AutonomousDatabaseBackupsClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armoracledatabase.AutonomousDatabaseBackupsClientDeleteResponse]] + newListByAutonomousDatabasePager *tracker[azfake.PagerResponder[armoracledatabase.AutonomousDatabaseBackupsClientListByAutonomousDatabaseResponse]] + beginUpdate *tracker[azfake.PollerResponder[armoracledatabase.AutonomousDatabaseBackupsClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for AutonomousDatabaseBackupsServerTransport. +func (a *AutonomousDatabaseBackupsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *AutonomousDatabaseBackupsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if autonomousDatabaseBackupsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = autonomousDatabaseBackupsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "AutonomousDatabaseBackupsClient.BeginCreateOrUpdate": + res.resp, res.err = a.dispatchBeginCreateOrUpdate(req) + case "AutonomousDatabaseBackupsClient.BeginDelete": + res.resp, res.err = a.dispatchBeginDelete(req) + case "AutonomousDatabaseBackupsClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "AutonomousDatabaseBackupsClient.NewListByAutonomousDatabasePager": + res.resp, res.err = a.dispatchNewListByAutonomousDatabasePager(req) + case "AutonomousDatabaseBackupsClient.BeginUpdate": + res.resp, res.err = a.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *AutonomousDatabaseBackupsServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if a.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := a.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/autonomousDatabases/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/autonomousDatabaseBackups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.AutonomousDatabaseBackup](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + autonomousdatabasenameParam, err := url.PathUnescape(matches[regex.SubexpIndex("autonomousdatabasename")]) + if err != nil { + return nil, err + } + adbbackupidParam, err := url.PathUnescape(matches[regex.SubexpIndex("adbbackupid")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, autonomousdatabasenameParam, adbbackupidParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + a.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + a.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + a.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (a *AutonomousDatabaseBackupsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if a.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := a.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/autonomousDatabases/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/autonomousDatabaseBackups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + autonomousdatabasenameParam, err := url.PathUnescape(matches[regex.SubexpIndex("autonomousdatabasename")]) + if err != nil { + return nil, err + } + adbbackupidParam, err := url.PathUnescape(matches[regex.SubexpIndex("adbbackupid")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginDelete(req.Context(), resourceGroupNameParam, autonomousdatabasenameParam, adbbackupidParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + a.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + a.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + a.beginDelete.remove(req) + } + + return resp, nil +} + +func (a *AutonomousDatabaseBackupsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/autonomousDatabases/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/autonomousDatabaseBackups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + autonomousdatabasenameParam, err := url.PathUnescape(matches[regex.SubexpIndex("autonomousdatabasename")]) + if err != nil { + return nil, err + } + adbbackupidParam, err := url.PathUnescape(matches[regex.SubexpIndex("adbbackupid")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Get(req.Context(), resourceGroupNameParam, autonomousdatabasenameParam, adbbackupidParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).AutonomousDatabaseBackup, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AutonomousDatabaseBackupsServerTransport) dispatchNewListByAutonomousDatabasePager(req *http.Request) (*http.Response, error) { + if a.srv.NewListByAutonomousDatabasePager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByAutonomousDatabasePager not implemented")} + } + newListByAutonomousDatabasePager := a.newListByAutonomousDatabasePager.get(req) + if newListByAutonomousDatabasePager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/autonomousDatabases/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/autonomousDatabaseBackups` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + autonomousdatabasenameParam, err := url.PathUnescape(matches[regex.SubexpIndex("autonomousdatabasename")]) + if err != nil { + return nil, err + } + resp := a.srv.NewListByAutonomousDatabasePager(resourceGroupNameParam, autonomousdatabasenameParam, nil) + newListByAutonomousDatabasePager = &resp + a.newListByAutonomousDatabasePager.add(req, newListByAutonomousDatabasePager) + server.PagerResponderInjectNextLinks(newListByAutonomousDatabasePager, req, func(page *armoracledatabase.AutonomousDatabaseBackupsClientListByAutonomousDatabaseResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByAutonomousDatabasePager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListByAutonomousDatabasePager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByAutonomousDatabasePager) { + a.newListByAutonomousDatabasePager.remove(req) + } + return resp, nil +} + +func (a *AutonomousDatabaseBackupsServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if a.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := a.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/autonomousDatabases/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/autonomousDatabaseBackups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.AutonomousDatabaseBackupUpdate](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + autonomousdatabasenameParam, err := url.PathUnescape(matches[regex.SubexpIndex("autonomousdatabasename")]) + if err != nil { + return nil, err + } + adbbackupidParam, err := url.PathUnescape(matches[regex.SubexpIndex("adbbackupid")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginUpdate(req.Context(), resourceGroupNameParam, autonomousdatabasenameParam, adbbackupidParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + a.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + a.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + a.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to AutonomousDatabaseBackupsServerTransport +var autonomousDatabaseBackupsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armoracledatabase/fake/zz_autonomousdatabasecharactersets_server.go b/test/local/armoracledatabase/fake/zz_autonomousdatabasecharactersets_server.go new file mode 100644 index 000000000000..f773daf04aca --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_autonomousdatabasecharactersets_server.go @@ -0,0 +1,165 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armoracledatabase/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// AutonomousDatabaseCharacterSetsServer is a fake server for instances of the armoracledatabase.AutonomousDatabaseCharacterSetsClient type. +type AutonomousDatabaseCharacterSetsServer struct { + // Get is the fake for method AutonomousDatabaseCharacterSetsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, location string, adbscharsetname string, options *armoracledatabase.AutonomousDatabaseCharacterSetsClientGetOptions) (resp azfake.Responder[armoracledatabase.AutonomousDatabaseCharacterSetsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByLocationPager is the fake for method AutonomousDatabaseCharacterSetsClient.NewListByLocationPager + // HTTP status codes to indicate success: http.StatusOK + NewListByLocationPager func(location string, options *armoracledatabase.AutonomousDatabaseCharacterSetsClientListByLocationOptions) (resp azfake.PagerResponder[armoracledatabase.AutonomousDatabaseCharacterSetsClientListByLocationResponse]) +} + +// NewAutonomousDatabaseCharacterSetsServerTransport creates a new instance of AutonomousDatabaseCharacterSetsServerTransport with the provided implementation. +// The returned AutonomousDatabaseCharacterSetsServerTransport instance is connected to an instance of armoracledatabase.AutonomousDatabaseCharacterSetsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAutonomousDatabaseCharacterSetsServerTransport(srv *AutonomousDatabaseCharacterSetsServer) *AutonomousDatabaseCharacterSetsServerTransport { + return &AutonomousDatabaseCharacterSetsServerTransport{ + srv: srv, + newListByLocationPager: newTracker[azfake.PagerResponder[armoracledatabase.AutonomousDatabaseCharacterSetsClientListByLocationResponse]](), + } +} + +// AutonomousDatabaseCharacterSetsServerTransport connects instances of armoracledatabase.AutonomousDatabaseCharacterSetsClient to instances of AutonomousDatabaseCharacterSetsServer. +// Don't use this type directly, use NewAutonomousDatabaseCharacterSetsServerTransport instead. +type AutonomousDatabaseCharacterSetsServerTransport struct { + srv *AutonomousDatabaseCharacterSetsServer + newListByLocationPager *tracker[azfake.PagerResponder[armoracledatabase.AutonomousDatabaseCharacterSetsClientListByLocationResponse]] +} + +// Do implements the policy.Transporter interface for AutonomousDatabaseCharacterSetsServerTransport. +func (a *AutonomousDatabaseCharacterSetsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *AutonomousDatabaseCharacterSetsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if autonomousDatabaseCharacterSetsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = autonomousDatabaseCharacterSetsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "AutonomousDatabaseCharacterSetsClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "AutonomousDatabaseCharacterSetsClient.NewListByLocationPager": + res.resp, res.err = a.dispatchNewListByLocationPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *AutonomousDatabaseCharacterSetsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/autonomousDatabaseCharacterSets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + adbscharsetnameParam, err := url.PathUnescape(matches[regex.SubexpIndex("adbscharsetname")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Get(req.Context(), locationParam, adbscharsetnameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).AutonomousDatabaseCharacterSet, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AutonomousDatabaseCharacterSetsServerTransport) dispatchNewListByLocationPager(req *http.Request) (*http.Response, error) { + if a.srv.NewListByLocationPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByLocationPager not implemented")} + } + newListByLocationPager := a.newListByLocationPager.get(req) + if newListByLocationPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/autonomousDatabaseCharacterSets` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + resp := a.srv.NewListByLocationPager(locationParam, nil) + newListByLocationPager = &resp + a.newListByLocationPager.add(req, newListByLocationPager) + server.PagerResponderInjectNextLinks(newListByLocationPager, req, func(page *armoracledatabase.AutonomousDatabaseCharacterSetsClientListByLocationResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByLocationPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListByLocationPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByLocationPager) { + a.newListByLocationPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to AutonomousDatabaseCharacterSetsServerTransport +var autonomousDatabaseCharacterSetsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armoracledatabase/fake/zz_autonomousdatabasenationalcharactersets_server.go b/test/local/armoracledatabase/fake/zz_autonomousdatabasenationalcharactersets_server.go new file mode 100644 index 000000000000..54bc0fad86c4 --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_autonomousdatabasenationalcharactersets_server.go @@ -0,0 +1,165 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armoracledatabase/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// AutonomousDatabaseNationalCharacterSetsServer is a fake server for instances of the armoracledatabase.AutonomousDatabaseNationalCharacterSetsClient type. +type AutonomousDatabaseNationalCharacterSetsServer struct { + // Get is the fake for method AutonomousDatabaseNationalCharacterSetsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, location string, adbsncharsetname string, options *armoracledatabase.AutonomousDatabaseNationalCharacterSetsClientGetOptions) (resp azfake.Responder[armoracledatabase.AutonomousDatabaseNationalCharacterSetsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByLocationPager is the fake for method AutonomousDatabaseNationalCharacterSetsClient.NewListByLocationPager + // HTTP status codes to indicate success: http.StatusOK + NewListByLocationPager func(location string, options *armoracledatabase.AutonomousDatabaseNationalCharacterSetsClientListByLocationOptions) (resp azfake.PagerResponder[armoracledatabase.AutonomousDatabaseNationalCharacterSetsClientListByLocationResponse]) +} + +// NewAutonomousDatabaseNationalCharacterSetsServerTransport creates a new instance of AutonomousDatabaseNationalCharacterSetsServerTransport with the provided implementation. +// The returned AutonomousDatabaseNationalCharacterSetsServerTransport instance is connected to an instance of armoracledatabase.AutonomousDatabaseNationalCharacterSetsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAutonomousDatabaseNationalCharacterSetsServerTransport(srv *AutonomousDatabaseNationalCharacterSetsServer) *AutonomousDatabaseNationalCharacterSetsServerTransport { + return &AutonomousDatabaseNationalCharacterSetsServerTransport{ + srv: srv, + newListByLocationPager: newTracker[azfake.PagerResponder[armoracledatabase.AutonomousDatabaseNationalCharacterSetsClientListByLocationResponse]](), + } +} + +// AutonomousDatabaseNationalCharacterSetsServerTransport connects instances of armoracledatabase.AutonomousDatabaseNationalCharacterSetsClient to instances of AutonomousDatabaseNationalCharacterSetsServer. +// Don't use this type directly, use NewAutonomousDatabaseNationalCharacterSetsServerTransport instead. +type AutonomousDatabaseNationalCharacterSetsServerTransport struct { + srv *AutonomousDatabaseNationalCharacterSetsServer + newListByLocationPager *tracker[azfake.PagerResponder[armoracledatabase.AutonomousDatabaseNationalCharacterSetsClientListByLocationResponse]] +} + +// Do implements the policy.Transporter interface for AutonomousDatabaseNationalCharacterSetsServerTransport. +func (a *AutonomousDatabaseNationalCharacterSetsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *AutonomousDatabaseNationalCharacterSetsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if autonomousDatabaseNationalCharacterSetsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = autonomousDatabaseNationalCharacterSetsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "AutonomousDatabaseNationalCharacterSetsClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "AutonomousDatabaseNationalCharacterSetsClient.NewListByLocationPager": + res.resp, res.err = a.dispatchNewListByLocationPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *AutonomousDatabaseNationalCharacterSetsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/autonomousDatabaseNationalCharacterSets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + adbsncharsetnameParam, err := url.PathUnescape(matches[regex.SubexpIndex("adbsncharsetname")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Get(req.Context(), locationParam, adbsncharsetnameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).AutonomousDatabaseNationalCharacterSet, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AutonomousDatabaseNationalCharacterSetsServerTransport) dispatchNewListByLocationPager(req *http.Request) (*http.Response, error) { + if a.srv.NewListByLocationPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByLocationPager not implemented")} + } + newListByLocationPager := a.newListByLocationPager.get(req) + if newListByLocationPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/autonomousDatabaseNationalCharacterSets` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + resp := a.srv.NewListByLocationPager(locationParam, nil) + newListByLocationPager = &resp + a.newListByLocationPager.add(req, newListByLocationPager) + server.PagerResponderInjectNextLinks(newListByLocationPager, req, func(page *armoracledatabase.AutonomousDatabaseNationalCharacterSetsClientListByLocationResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByLocationPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListByLocationPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByLocationPager) { + a.newListByLocationPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to AutonomousDatabaseNationalCharacterSetsServerTransport +var autonomousDatabaseNationalCharacterSetsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armoracledatabase/fake/zz_autonomousdatabases_server.go b/test/local/armoracledatabase/fake/zz_autonomousdatabases_server.go new file mode 100644 index 000000000000..91000a7eb40a --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_autonomousdatabases_server.go @@ -0,0 +1,745 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armoracledatabase/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// AutonomousDatabasesServer is a fake server for instances of the armoracledatabase.AutonomousDatabasesClient type. +type AutonomousDatabasesServer struct { + // BeginAction is the fake for method AutonomousDatabasesClient.BeginAction + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginAction func(ctx context.Context, resourceGroupName string, autonomousdatabasename string, body armoracledatabase.AutonomousDatabaseLifecycleAction, options *armoracledatabase.AutonomousDatabasesClientBeginActionOptions) (resp azfake.PollerResponder[armoracledatabase.AutonomousDatabasesClientActionResponse], errResp azfake.ErrorResponder) + + // BeginChangeDisasterRecoveryConfiguration is the fake for method AutonomousDatabasesClient.BeginChangeDisasterRecoveryConfiguration + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginChangeDisasterRecoveryConfiguration func(ctx context.Context, resourceGroupName string, autonomousdatabasename string, body armoracledatabase.DisasterRecoveryConfigurationDetails, options *armoracledatabase.AutonomousDatabasesClientBeginChangeDisasterRecoveryConfigurationOptions) (resp azfake.PollerResponder[armoracledatabase.AutonomousDatabasesClientChangeDisasterRecoveryConfigurationResponse], errResp azfake.ErrorResponder) + + // BeginCreateOrUpdate is the fake for method AutonomousDatabasesClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, autonomousdatabasename string, resource armoracledatabase.AutonomousDatabase, options *armoracledatabase.AutonomousDatabasesClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armoracledatabase.AutonomousDatabasesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method AutonomousDatabasesClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, autonomousdatabasename string, options *armoracledatabase.AutonomousDatabasesClientBeginDeleteOptions) (resp azfake.PollerResponder[armoracledatabase.AutonomousDatabasesClientDeleteResponse], errResp azfake.ErrorResponder) + + // BeginFailover is the fake for method AutonomousDatabasesClient.BeginFailover + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginFailover func(ctx context.Context, resourceGroupName string, autonomousdatabasename string, body armoracledatabase.PeerDbDetails, options *armoracledatabase.AutonomousDatabasesClientBeginFailoverOptions) (resp azfake.PollerResponder[armoracledatabase.AutonomousDatabasesClientFailoverResponse], errResp azfake.ErrorResponder) + + // GenerateWallet is the fake for method AutonomousDatabasesClient.GenerateWallet + // HTTP status codes to indicate success: http.StatusOK + GenerateWallet func(ctx context.Context, resourceGroupName string, autonomousdatabasename string, body armoracledatabase.GenerateAutonomousDatabaseWalletDetails, options *armoracledatabase.AutonomousDatabasesClientGenerateWalletOptions) (resp azfake.Responder[armoracledatabase.AutonomousDatabasesClientGenerateWalletResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method AutonomousDatabasesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, autonomousdatabasename string, options *armoracledatabase.AutonomousDatabasesClientGetOptions) (resp azfake.Responder[armoracledatabase.AutonomousDatabasesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method AutonomousDatabasesClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armoracledatabase.AutonomousDatabasesClientListByResourceGroupOptions) (resp azfake.PagerResponder[armoracledatabase.AutonomousDatabasesClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method AutonomousDatabasesClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armoracledatabase.AutonomousDatabasesClientListBySubscriptionOptions) (resp azfake.PagerResponder[armoracledatabase.AutonomousDatabasesClientListBySubscriptionResponse]) + + // BeginRestore is the fake for method AutonomousDatabasesClient.BeginRestore + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginRestore func(ctx context.Context, resourceGroupName string, autonomousdatabasename string, body armoracledatabase.RestoreAutonomousDatabaseDetails, options *armoracledatabase.AutonomousDatabasesClientBeginRestoreOptions) (resp azfake.PollerResponder[armoracledatabase.AutonomousDatabasesClientRestoreResponse], errResp azfake.ErrorResponder) + + // BeginShrink is the fake for method AutonomousDatabasesClient.BeginShrink + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginShrink func(ctx context.Context, resourceGroupName string, autonomousdatabasename string, options *armoracledatabase.AutonomousDatabasesClientBeginShrinkOptions) (resp azfake.PollerResponder[armoracledatabase.AutonomousDatabasesClientShrinkResponse], errResp azfake.ErrorResponder) + + // BeginSwitchover is the fake for method AutonomousDatabasesClient.BeginSwitchover + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginSwitchover func(ctx context.Context, resourceGroupName string, autonomousdatabasename string, body armoracledatabase.PeerDbDetails, options *armoracledatabase.AutonomousDatabasesClientBeginSwitchoverOptions) (resp azfake.PollerResponder[armoracledatabase.AutonomousDatabasesClientSwitchoverResponse], errResp azfake.ErrorResponder) + + // BeginUpdate is the fake for method AutonomousDatabasesClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, autonomousdatabasename string, properties armoracledatabase.AutonomousDatabaseUpdate, options *armoracledatabase.AutonomousDatabasesClientBeginUpdateOptions) (resp azfake.PollerResponder[armoracledatabase.AutonomousDatabasesClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewAutonomousDatabasesServerTransport creates a new instance of AutonomousDatabasesServerTransport with the provided implementation. +// The returned AutonomousDatabasesServerTransport instance is connected to an instance of armoracledatabase.AutonomousDatabasesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAutonomousDatabasesServerTransport(srv *AutonomousDatabasesServer) *AutonomousDatabasesServerTransport { + return &AutonomousDatabasesServerTransport{ + srv: srv, + beginAction: newTracker[azfake.PollerResponder[armoracledatabase.AutonomousDatabasesClientActionResponse]](), + beginChangeDisasterRecoveryConfiguration: newTracker[azfake.PollerResponder[armoracledatabase.AutonomousDatabasesClientChangeDisasterRecoveryConfigurationResponse]](), + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armoracledatabase.AutonomousDatabasesClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armoracledatabase.AutonomousDatabasesClientDeleteResponse]](), + beginFailover: newTracker[azfake.PollerResponder[armoracledatabase.AutonomousDatabasesClientFailoverResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armoracledatabase.AutonomousDatabasesClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armoracledatabase.AutonomousDatabasesClientListBySubscriptionResponse]](), + beginRestore: newTracker[azfake.PollerResponder[armoracledatabase.AutonomousDatabasesClientRestoreResponse]](), + beginShrink: newTracker[azfake.PollerResponder[armoracledatabase.AutonomousDatabasesClientShrinkResponse]](), + beginSwitchover: newTracker[azfake.PollerResponder[armoracledatabase.AutonomousDatabasesClientSwitchoverResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armoracledatabase.AutonomousDatabasesClientUpdateResponse]](), + } +} + +// AutonomousDatabasesServerTransport connects instances of armoracledatabase.AutonomousDatabasesClient to instances of AutonomousDatabasesServer. +// Don't use this type directly, use NewAutonomousDatabasesServerTransport instead. +type AutonomousDatabasesServerTransport struct { + srv *AutonomousDatabasesServer + beginAction *tracker[azfake.PollerResponder[armoracledatabase.AutonomousDatabasesClientActionResponse]] + beginChangeDisasterRecoveryConfiguration *tracker[azfake.PollerResponder[armoracledatabase.AutonomousDatabasesClientChangeDisasterRecoveryConfigurationResponse]] + beginCreateOrUpdate *tracker[azfake.PollerResponder[armoracledatabase.AutonomousDatabasesClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armoracledatabase.AutonomousDatabasesClientDeleteResponse]] + beginFailover *tracker[azfake.PollerResponder[armoracledatabase.AutonomousDatabasesClientFailoverResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armoracledatabase.AutonomousDatabasesClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armoracledatabase.AutonomousDatabasesClientListBySubscriptionResponse]] + beginRestore *tracker[azfake.PollerResponder[armoracledatabase.AutonomousDatabasesClientRestoreResponse]] + beginShrink *tracker[azfake.PollerResponder[armoracledatabase.AutonomousDatabasesClientShrinkResponse]] + beginSwitchover *tracker[azfake.PollerResponder[armoracledatabase.AutonomousDatabasesClientSwitchoverResponse]] + beginUpdate *tracker[azfake.PollerResponder[armoracledatabase.AutonomousDatabasesClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for AutonomousDatabasesServerTransport. +func (a *AutonomousDatabasesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *AutonomousDatabasesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if autonomousDatabasesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = autonomousDatabasesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "AutonomousDatabasesClient.BeginAction": + res.resp, res.err = a.dispatchBeginAction(req) + case "AutonomousDatabasesClient.BeginChangeDisasterRecoveryConfiguration": + res.resp, res.err = a.dispatchBeginChangeDisasterRecoveryConfiguration(req) + case "AutonomousDatabasesClient.BeginCreateOrUpdate": + res.resp, res.err = a.dispatchBeginCreateOrUpdate(req) + case "AutonomousDatabasesClient.BeginDelete": + res.resp, res.err = a.dispatchBeginDelete(req) + case "AutonomousDatabasesClient.BeginFailover": + res.resp, res.err = a.dispatchBeginFailover(req) + case "AutonomousDatabasesClient.GenerateWallet": + res.resp, res.err = a.dispatchGenerateWallet(req) + case "AutonomousDatabasesClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "AutonomousDatabasesClient.NewListByResourceGroupPager": + res.resp, res.err = a.dispatchNewListByResourceGroupPager(req) + case "AutonomousDatabasesClient.NewListBySubscriptionPager": + res.resp, res.err = a.dispatchNewListBySubscriptionPager(req) + case "AutonomousDatabasesClient.BeginRestore": + res.resp, res.err = a.dispatchBeginRestore(req) + case "AutonomousDatabasesClient.BeginShrink": + res.resp, res.err = a.dispatchBeginShrink(req) + case "AutonomousDatabasesClient.BeginSwitchover": + res.resp, res.err = a.dispatchBeginSwitchover(req) + case "AutonomousDatabasesClient.BeginUpdate": + res.resp, res.err = a.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *AutonomousDatabasesServerTransport) dispatchBeginAction(req *http.Request) (*http.Response, error) { + if a.srv.BeginAction == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginAction not implemented")} + } + beginAction := a.beginAction.get(req) + if beginAction == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/autonomousDatabases/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/action` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.AutonomousDatabaseLifecycleAction](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + autonomousdatabasenameParam, err := url.PathUnescape(matches[regex.SubexpIndex("autonomousdatabasename")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginAction(req.Context(), resourceGroupNameParam, autonomousdatabasenameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginAction = &respr + a.beginAction.add(req, beginAction) + } + + resp, err := server.PollerResponderNext(beginAction, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + a.beginAction.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginAction) { + a.beginAction.remove(req) + } + + return resp, nil +} + +func (a *AutonomousDatabasesServerTransport) dispatchBeginChangeDisasterRecoveryConfiguration(req *http.Request) (*http.Response, error) { + if a.srv.BeginChangeDisasterRecoveryConfiguration == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginChangeDisasterRecoveryConfiguration not implemented")} + } + beginChangeDisasterRecoveryConfiguration := a.beginChangeDisasterRecoveryConfiguration.get(req) + if beginChangeDisasterRecoveryConfiguration == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/autonomousDatabases/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/changeDisasterRecoveryConfiguration` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.DisasterRecoveryConfigurationDetails](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + autonomousdatabasenameParam, err := url.PathUnescape(matches[regex.SubexpIndex("autonomousdatabasename")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginChangeDisasterRecoveryConfiguration(req.Context(), resourceGroupNameParam, autonomousdatabasenameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginChangeDisasterRecoveryConfiguration = &respr + a.beginChangeDisasterRecoveryConfiguration.add(req, beginChangeDisasterRecoveryConfiguration) + } + + resp, err := server.PollerResponderNext(beginChangeDisasterRecoveryConfiguration, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + a.beginChangeDisasterRecoveryConfiguration.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginChangeDisasterRecoveryConfiguration) { + a.beginChangeDisasterRecoveryConfiguration.remove(req) + } + + return resp, nil +} + +func (a *AutonomousDatabasesServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if a.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := a.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/autonomousDatabases/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.AutonomousDatabase](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + autonomousdatabasenameParam, err := url.PathUnescape(matches[regex.SubexpIndex("autonomousdatabasename")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, autonomousdatabasenameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + a.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + a.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + a.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (a *AutonomousDatabasesServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if a.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := a.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/autonomousDatabases/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + autonomousdatabasenameParam, err := url.PathUnescape(matches[regex.SubexpIndex("autonomousdatabasename")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginDelete(req.Context(), resourceGroupNameParam, autonomousdatabasenameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + a.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + a.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + a.beginDelete.remove(req) + } + + return resp, nil +} + +func (a *AutonomousDatabasesServerTransport) dispatchBeginFailover(req *http.Request) (*http.Response, error) { + if a.srv.BeginFailover == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginFailover not implemented")} + } + beginFailover := a.beginFailover.get(req) + if beginFailover == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/autonomousDatabases/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/failover` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.PeerDbDetails](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + autonomousdatabasenameParam, err := url.PathUnescape(matches[regex.SubexpIndex("autonomousdatabasename")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginFailover(req.Context(), resourceGroupNameParam, autonomousdatabasenameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginFailover = &respr + a.beginFailover.add(req, beginFailover) + } + + resp, err := server.PollerResponderNext(beginFailover, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + a.beginFailover.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginFailover) { + a.beginFailover.remove(req) + } + + return resp, nil +} + +func (a *AutonomousDatabasesServerTransport) dispatchGenerateWallet(req *http.Request) (*http.Response, error) { + if a.srv.GenerateWallet == nil { + return nil, &nonRetriableError{errors.New("fake for method GenerateWallet not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/autonomousDatabases/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/generateWallet` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.GenerateAutonomousDatabaseWalletDetails](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + autonomousdatabasenameParam, err := url.PathUnescape(matches[regex.SubexpIndex("autonomousdatabasename")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.GenerateWallet(req.Context(), resourceGroupNameParam, autonomousdatabasenameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).AutonomousDatabaseWalletFile, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AutonomousDatabasesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/autonomousDatabases/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + autonomousdatabasenameParam, err := url.PathUnescape(matches[regex.SubexpIndex("autonomousdatabasename")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Get(req.Context(), resourceGroupNameParam, autonomousdatabasenameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).AutonomousDatabase, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AutonomousDatabasesServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if a.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := a.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/autonomousDatabases` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := a.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + a.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armoracledatabase.AutonomousDatabasesClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + a.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (a *AutonomousDatabasesServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if a.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := a.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/autonomousDatabases` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := a.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + a.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armoracledatabase.AutonomousDatabasesClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + a.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (a *AutonomousDatabasesServerTransport) dispatchBeginRestore(req *http.Request) (*http.Response, error) { + if a.srv.BeginRestore == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginRestore not implemented")} + } + beginRestore := a.beginRestore.get(req) + if beginRestore == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/autonomousDatabases/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/restore` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.RestoreAutonomousDatabaseDetails](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + autonomousdatabasenameParam, err := url.PathUnescape(matches[regex.SubexpIndex("autonomousdatabasename")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginRestore(req.Context(), resourceGroupNameParam, autonomousdatabasenameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginRestore = &respr + a.beginRestore.add(req, beginRestore) + } + + resp, err := server.PollerResponderNext(beginRestore, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + a.beginRestore.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginRestore) { + a.beginRestore.remove(req) + } + + return resp, nil +} + +func (a *AutonomousDatabasesServerTransport) dispatchBeginShrink(req *http.Request) (*http.Response, error) { + if a.srv.BeginShrink == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginShrink not implemented")} + } + beginShrink := a.beginShrink.get(req) + if beginShrink == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/autonomousDatabases/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/shrink` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + autonomousdatabasenameParam, err := url.PathUnescape(matches[regex.SubexpIndex("autonomousdatabasename")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginShrink(req.Context(), resourceGroupNameParam, autonomousdatabasenameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginShrink = &respr + a.beginShrink.add(req, beginShrink) + } + + resp, err := server.PollerResponderNext(beginShrink, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + a.beginShrink.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginShrink) { + a.beginShrink.remove(req) + } + + return resp, nil +} + +func (a *AutonomousDatabasesServerTransport) dispatchBeginSwitchover(req *http.Request) (*http.Response, error) { + if a.srv.BeginSwitchover == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginSwitchover not implemented")} + } + beginSwitchover := a.beginSwitchover.get(req) + if beginSwitchover == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/autonomousDatabases/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/switchover` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.PeerDbDetails](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + autonomousdatabasenameParam, err := url.PathUnescape(matches[regex.SubexpIndex("autonomousdatabasename")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginSwitchover(req.Context(), resourceGroupNameParam, autonomousdatabasenameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginSwitchover = &respr + a.beginSwitchover.add(req, beginSwitchover) + } + + resp, err := server.PollerResponderNext(beginSwitchover, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + a.beginSwitchover.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginSwitchover) { + a.beginSwitchover.remove(req) + } + + return resp, nil +} + +func (a *AutonomousDatabasesServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if a.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := a.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/autonomousDatabases/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.AutonomousDatabaseUpdate](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + autonomousdatabasenameParam, err := url.PathUnescape(matches[regex.SubexpIndex("autonomousdatabasename")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.BeginUpdate(req.Context(), resourceGroupNameParam, autonomousdatabasenameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + a.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + a.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + a.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to AutonomousDatabasesServerTransport +var autonomousDatabasesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armoracledatabase/fake/zz_autonomousdatabaseversions_server.go b/test/local/armoracledatabase/fake/zz_autonomousdatabaseversions_server.go new file mode 100644 index 000000000000..baf4e1a32128 --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_autonomousdatabaseversions_server.go @@ -0,0 +1,165 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armoracledatabase/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// AutonomousDatabaseVersionsServer is a fake server for instances of the armoracledatabase.AutonomousDatabaseVersionsClient type. +type AutonomousDatabaseVersionsServer struct { + // Get is the fake for method AutonomousDatabaseVersionsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, location string, autonomousdbversionsname string, options *armoracledatabase.AutonomousDatabaseVersionsClientGetOptions) (resp azfake.Responder[armoracledatabase.AutonomousDatabaseVersionsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByLocationPager is the fake for method AutonomousDatabaseVersionsClient.NewListByLocationPager + // HTTP status codes to indicate success: http.StatusOK + NewListByLocationPager func(location string, options *armoracledatabase.AutonomousDatabaseVersionsClientListByLocationOptions) (resp azfake.PagerResponder[armoracledatabase.AutonomousDatabaseVersionsClientListByLocationResponse]) +} + +// NewAutonomousDatabaseVersionsServerTransport creates a new instance of AutonomousDatabaseVersionsServerTransport with the provided implementation. +// The returned AutonomousDatabaseVersionsServerTransport instance is connected to an instance of armoracledatabase.AutonomousDatabaseVersionsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAutonomousDatabaseVersionsServerTransport(srv *AutonomousDatabaseVersionsServer) *AutonomousDatabaseVersionsServerTransport { + return &AutonomousDatabaseVersionsServerTransport{ + srv: srv, + newListByLocationPager: newTracker[azfake.PagerResponder[armoracledatabase.AutonomousDatabaseVersionsClientListByLocationResponse]](), + } +} + +// AutonomousDatabaseVersionsServerTransport connects instances of armoracledatabase.AutonomousDatabaseVersionsClient to instances of AutonomousDatabaseVersionsServer. +// Don't use this type directly, use NewAutonomousDatabaseVersionsServerTransport instead. +type AutonomousDatabaseVersionsServerTransport struct { + srv *AutonomousDatabaseVersionsServer + newListByLocationPager *tracker[azfake.PagerResponder[armoracledatabase.AutonomousDatabaseVersionsClientListByLocationResponse]] +} + +// Do implements the policy.Transporter interface for AutonomousDatabaseVersionsServerTransport. +func (a *AutonomousDatabaseVersionsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *AutonomousDatabaseVersionsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if autonomousDatabaseVersionsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = autonomousDatabaseVersionsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "AutonomousDatabaseVersionsClient.Get": + res.resp, res.err = a.dispatchGet(req) + case "AutonomousDatabaseVersionsClient.NewListByLocationPager": + res.resp, res.err = a.dispatchNewListByLocationPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *AutonomousDatabaseVersionsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/autonomousDbVersions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + autonomousdbversionsnameParam, err := url.PathUnescape(matches[regex.SubexpIndex("autonomousdbversionsname")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Get(req.Context(), locationParam, autonomousdbversionsnameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).AutonomousDbVersion, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (a *AutonomousDatabaseVersionsServerTransport) dispatchNewListByLocationPager(req *http.Request) (*http.Response, error) { + if a.srv.NewListByLocationPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByLocationPager not implemented")} + } + newListByLocationPager := a.newListByLocationPager.get(req) + if newListByLocationPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/autonomousDbVersions` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + resp := a.srv.NewListByLocationPager(locationParam, nil) + newListByLocationPager = &resp + a.newListByLocationPager.add(req, newListByLocationPager) + server.PagerResponderInjectNextLinks(newListByLocationPager, req, func(page *armoracledatabase.AutonomousDatabaseVersionsClientListByLocationResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByLocationPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + a.newListByLocationPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByLocationPager) { + a.newListByLocationPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to AutonomousDatabaseVersionsServerTransport +var autonomousDatabaseVersionsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armoracledatabase/fake/zz_cloudexadatainfrastructures_server.go b/test/local/armoracledatabase/fake/zz_cloudexadatainfrastructures_server.go new file mode 100644 index 000000000000..1c4a1efd52bc --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_cloudexadatainfrastructures_server.go @@ -0,0 +1,478 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armoracledatabase/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// CloudExadataInfrastructuresServer is a fake server for instances of the armoracledatabase.CloudExadataInfrastructuresClient type. +type CloudExadataInfrastructuresServer struct { + // BeginAddStorageCapacity is the fake for method CloudExadataInfrastructuresClient.BeginAddStorageCapacity + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginAddStorageCapacity func(ctx context.Context, resourceGroupName string, cloudexadatainfrastructurename string, options *armoracledatabase.CloudExadataInfrastructuresClientBeginAddStorageCapacityOptions) (resp azfake.PollerResponder[armoracledatabase.CloudExadataInfrastructuresClientAddStorageCapacityResponse], errResp azfake.ErrorResponder) + + // BeginConfigureExascale is the fake for method CloudExadataInfrastructuresClient.BeginConfigureExascale + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginConfigureExascale func(ctx context.Context, resourceGroupName string, cloudexadatainfrastructurename string, body armoracledatabase.ConfigureExascaleCloudExadataInfrastructureDetails, options *armoracledatabase.CloudExadataInfrastructuresClientBeginConfigureExascaleOptions) (resp azfake.PollerResponder[armoracledatabase.CloudExadataInfrastructuresClientConfigureExascaleResponse], errResp azfake.ErrorResponder) + + // BeginCreateOrUpdate is the fake for method CloudExadataInfrastructuresClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, cloudexadatainfrastructurename string, resource armoracledatabase.CloudExadataInfrastructure, options *armoracledatabase.CloudExadataInfrastructuresClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armoracledatabase.CloudExadataInfrastructuresClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method CloudExadataInfrastructuresClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, cloudexadatainfrastructurename string, options *armoracledatabase.CloudExadataInfrastructuresClientBeginDeleteOptions) (resp azfake.PollerResponder[armoracledatabase.CloudExadataInfrastructuresClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method CloudExadataInfrastructuresClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, cloudexadatainfrastructurename string, options *armoracledatabase.CloudExadataInfrastructuresClientGetOptions) (resp azfake.Responder[armoracledatabase.CloudExadataInfrastructuresClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method CloudExadataInfrastructuresClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armoracledatabase.CloudExadataInfrastructuresClientListByResourceGroupOptions) (resp azfake.PagerResponder[armoracledatabase.CloudExadataInfrastructuresClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method CloudExadataInfrastructuresClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armoracledatabase.CloudExadataInfrastructuresClientListBySubscriptionOptions) (resp azfake.PagerResponder[armoracledatabase.CloudExadataInfrastructuresClientListBySubscriptionResponse]) + + // BeginUpdate is the fake for method CloudExadataInfrastructuresClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, cloudexadatainfrastructurename string, properties armoracledatabase.CloudExadataInfrastructureUpdate, options *armoracledatabase.CloudExadataInfrastructuresClientBeginUpdateOptions) (resp azfake.PollerResponder[armoracledatabase.CloudExadataInfrastructuresClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewCloudExadataInfrastructuresServerTransport creates a new instance of CloudExadataInfrastructuresServerTransport with the provided implementation. +// The returned CloudExadataInfrastructuresServerTransport instance is connected to an instance of armoracledatabase.CloudExadataInfrastructuresClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewCloudExadataInfrastructuresServerTransport(srv *CloudExadataInfrastructuresServer) *CloudExadataInfrastructuresServerTransport { + return &CloudExadataInfrastructuresServerTransport{ + srv: srv, + beginAddStorageCapacity: newTracker[azfake.PollerResponder[armoracledatabase.CloudExadataInfrastructuresClientAddStorageCapacityResponse]](), + beginConfigureExascale: newTracker[azfake.PollerResponder[armoracledatabase.CloudExadataInfrastructuresClientConfigureExascaleResponse]](), + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armoracledatabase.CloudExadataInfrastructuresClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armoracledatabase.CloudExadataInfrastructuresClientDeleteResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armoracledatabase.CloudExadataInfrastructuresClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armoracledatabase.CloudExadataInfrastructuresClientListBySubscriptionResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armoracledatabase.CloudExadataInfrastructuresClientUpdateResponse]](), + } +} + +// CloudExadataInfrastructuresServerTransport connects instances of armoracledatabase.CloudExadataInfrastructuresClient to instances of CloudExadataInfrastructuresServer. +// Don't use this type directly, use NewCloudExadataInfrastructuresServerTransport instead. +type CloudExadataInfrastructuresServerTransport struct { + srv *CloudExadataInfrastructuresServer + beginAddStorageCapacity *tracker[azfake.PollerResponder[armoracledatabase.CloudExadataInfrastructuresClientAddStorageCapacityResponse]] + beginConfigureExascale *tracker[azfake.PollerResponder[armoracledatabase.CloudExadataInfrastructuresClientConfigureExascaleResponse]] + beginCreateOrUpdate *tracker[azfake.PollerResponder[armoracledatabase.CloudExadataInfrastructuresClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armoracledatabase.CloudExadataInfrastructuresClientDeleteResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armoracledatabase.CloudExadataInfrastructuresClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armoracledatabase.CloudExadataInfrastructuresClientListBySubscriptionResponse]] + beginUpdate *tracker[azfake.PollerResponder[armoracledatabase.CloudExadataInfrastructuresClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for CloudExadataInfrastructuresServerTransport. +func (c *CloudExadataInfrastructuresServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *CloudExadataInfrastructuresServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if cloudExadataInfrastructuresServerTransportInterceptor != nil { + res.resp, res.err, intercepted = cloudExadataInfrastructuresServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "CloudExadataInfrastructuresClient.BeginAddStorageCapacity": + res.resp, res.err = c.dispatchBeginAddStorageCapacity(req) + case "CloudExadataInfrastructuresClient.BeginConfigureExascale": + res.resp, res.err = c.dispatchBeginConfigureExascale(req) + case "CloudExadataInfrastructuresClient.BeginCreateOrUpdate": + res.resp, res.err = c.dispatchBeginCreateOrUpdate(req) + case "CloudExadataInfrastructuresClient.BeginDelete": + res.resp, res.err = c.dispatchBeginDelete(req) + case "CloudExadataInfrastructuresClient.Get": + res.resp, res.err = c.dispatchGet(req) + case "CloudExadataInfrastructuresClient.NewListByResourceGroupPager": + res.resp, res.err = c.dispatchNewListByResourceGroupPager(req) + case "CloudExadataInfrastructuresClient.NewListBySubscriptionPager": + res.resp, res.err = c.dispatchNewListBySubscriptionPager(req) + case "CloudExadataInfrastructuresClient.BeginUpdate": + res.resp, res.err = c.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *CloudExadataInfrastructuresServerTransport) dispatchBeginAddStorageCapacity(req *http.Request) (*http.Response, error) { + if c.srv.BeginAddStorageCapacity == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginAddStorageCapacity not implemented")} + } + beginAddStorageCapacity := c.beginAddStorageCapacity.get(req) + if beginAddStorageCapacity == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudExadataInfrastructures/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/addStorageCapacity` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudexadatainfrastructurenameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudexadatainfrastructurename")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginAddStorageCapacity(req.Context(), resourceGroupNameParam, cloudexadatainfrastructurenameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginAddStorageCapacity = &respr + c.beginAddStorageCapacity.add(req, beginAddStorageCapacity) + } + + resp, err := server.PollerResponderNext(beginAddStorageCapacity, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + c.beginAddStorageCapacity.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginAddStorageCapacity) { + c.beginAddStorageCapacity.remove(req) + } + + return resp, nil +} + +func (c *CloudExadataInfrastructuresServerTransport) dispatchBeginConfigureExascale(req *http.Request) (*http.Response, error) { + if c.srv.BeginConfigureExascale == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginConfigureExascale not implemented")} + } + beginConfigureExascale := c.beginConfigureExascale.get(req) + if beginConfigureExascale == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudExadataInfrastructures/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/configureExascale` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.ConfigureExascaleCloudExadataInfrastructureDetails](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudexadatainfrastructurenameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudexadatainfrastructurename")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginConfigureExascale(req.Context(), resourceGroupNameParam, cloudexadatainfrastructurenameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginConfigureExascale = &respr + c.beginConfigureExascale.add(req, beginConfigureExascale) + } + + resp, err := server.PollerResponderNext(beginConfigureExascale, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + c.beginConfigureExascale.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginConfigureExascale) { + c.beginConfigureExascale.remove(req) + } + + return resp, nil +} + +func (c *CloudExadataInfrastructuresServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if c.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := c.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudExadataInfrastructures/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.CloudExadataInfrastructure](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudexadatainfrastructurenameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudexadatainfrastructurename")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, cloudexadatainfrastructurenameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + c.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + c.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + c.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (c *CloudExadataInfrastructuresServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if c.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := c.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudExadataInfrastructures/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudexadatainfrastructurenameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudexadatainfrastructurename")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginDelete(req.Context(), resourceGroupNameParam, cloudexadatainfrastructurenameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + c.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + c.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + c.beginDelete.remove(req) + } + + return resp, nil +} + +func (c *CloudExadataInfrastructuresServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if c.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudExadataInfrastructures/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudexadatainfrastructurenameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudexadatainfrastructurename")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.Get(req.Context(), resourceGroupNameParam, cloudexadatainfrastructurenameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CloudExadataInfrastructure, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *CloudExadataInfrastructuresServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if c.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := c.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudExadataInfrastructures` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := c.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + c.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armoracledatabase.CloudExadataInfrastructuresClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + c.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + c.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (c *CloudExadataInfrastructuresServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if c.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := c.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudExadataInfrastructures` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := c.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + c.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armoracledatabase.CloudExadataInfrastructuresClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + c.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + c.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (c *CloudExadataInfrastructuresServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if c.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := c.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudExadataInfrastructures/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.CloudExadataInfrastructureUpdate](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudexadatainfrastructurenameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudexadatainfrastructurename")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginUpdate(req.Context(), resourceGroupNameParam, cloudexadatainfrastructurenameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + c.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + c.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + c.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to CloudExadataInfrastructuresServerTransport +var cloudExadataInfrastructuresServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armoracledatabase/fake/zz_cloudvmclusters_server.go b/test/local/armoracledatabase/fake/zz_cloudvmclusters_server.go new file mode 100644 index 000000000000..e16acf228ec6 --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_cloudvmclusters_server.go @@ -0,0 +1,525 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armoracledatabase/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// CloudVMClustersServer is a fake server for instances of the armoracledatabase.CloudVMClustersClient type. +type CloudVMClustersServer struct { + // BeginAddVMs is the fake for method CloudVMClustersClient.BeginAddVMs + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginAddVMs func(ctx context.Context, resourceGroupName string, cloudvmclustername string, body armoracledatabase.AddRemoveDbNode, options *armoracledatabase.CloudVMClustersClientBeginAddVMsOptions) (resp azfake.PollerResponder[armoracledatabase.CloudVMClustersClientAddVMsResponse], errResp azfake.ErrorResponder) + + // BeginCreateOrUpdate is the fake for method CloudVMClustersClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, cloudvmclustername string, resource armoracledatabase.CloudVMCluster, options *armoracledatabase.CloudVMClustersClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armoracledatabase.CloudVMClustersClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method CloudVMClustersClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, cloudvmclustername string, options *armoracledatabase.CloudVMClustersClientBeginDeleteOptions) (resp azfake.PollerResponder[armoracledatabase.CloudVMClustersClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method CloudVMClustersClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, cloudvmclustername string, options *armoracledatabase.CloudVMClustersClientGetOptions) (resp azfake.Responder[armoracledatabase.CloudVMClustersClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method CloudVMClustersClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armoracledatabase.CloudVMClustersClientListByResourceGroupOptions) (resp azfake.PagerResponder[armoracledatabase.CloudVMClustersClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method CloudVMClustersClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armoracledatabase.CloudVMClustersClientListBySubscriptionOptions) (resp azfake.PagerResponder[armoracledatabase.CloudVMClustersClientListBySubscriptionResponse]) + + // ListPrivateIPAddresses is the fake for method CloudVMClustersClient.ListPrivateIPAddresses + // HTTP status codes to indicate success: http.StatusOK + ListPrivateIPAddresses func(ctx context.Context, resourceGroupName string, cloudvmclustername string, body armoracledatabase.PrivateIPAddressesFilter, options *armoracledatabase.CloudVMClustersClientListPrivateIPAddressesOptions) (resp azfake.Responder[armoracledatabase.CloudVMClustersClientListPrivateIPAddressesResponse], errResp azfake.ErrorResponder) + + // BeginRemoveVMs is the fake for method CloudVMClustersClient.BeginRemoveVMs + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginRemoveVMs func(ctx context.Context, resourceGroupName string, cloudvmclustername string, body armoracledatabase.AddRemoveDbNode, options *armoracledatabase.CloudVMClustersClientBeginRemoveVMsOptions) (resp azfake.PollerResponder[armoracledatabase.CloudVMClustersClientRemoveVMsResponse], errResp azfake.ErrorResponder) + + // BeginUpdate is the fake for method CloudVMClustersClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, cloudvmclustername string, properties armoracledatabase.CloudVMClusterUpdate, options *armoracledatabase.CloudVMClustersClientBeginUpdateOptions) (resp azfake.PollerResponder[armoracledatabase.CloudVMClustersClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewCloudVMClustersServerTransport creates a new instance of CloudVMClustersServerTransport with the provided implementation. +// The returned CloudVMClustersServerTransport instance is connected to an instance of armoracledatabase.CloudVMClustersClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewCloudVMClustersServerTransport(srv *CloudVMClustersServer) *CloudVMClustersServerTransport { + return &CloudVMClustersServerTransport{ + srv: srv, + beginAddVMs: newTracker[azfake.PollerResponder[armoracledatabase.CloudVMClustersClientAddVMsResponse]](), + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armoracledatabase.CloudVMClustersClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armoracledatabase.CloudVMClustersClientDeleteResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armoracledatabase.CloudVMClustersClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armoracledatabase.CloudVMClustersClientListBySubscriptionResponse]](), + beginRemoveVMs: newTracker[azfake.PollerResponder[armoracledatabase.CloudVMClustersClientRemoveVMsResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armoracledatabase.CloudVMClustersClientUpdateResponse]](), + } +} + +// CloudVMClustersServerTransport connects instances of armoracledatabase.CloudVMClustersClient to instances of CloudVMClustersServer. +// Don't use this type directly, use NewCloudVMClustersServerTransport instead. +type CloudVMClustersServerTransport struct { + srv *CloudVMClustersServer + beginAddVMs *tracker[azfake.PollerResponder[armoracledatabase.CloudVMClustersClientAddVMsResponse]] + beginCreateOrUpdate *tracker[azfake.PollerResponder[armoracledatabase.CloudVMClustersClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armoracledatabase.CloudVMClustersClientDeleteResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armoracledatabase.CloudVMClustersClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armoracledatabase.CloudVMClustersClientListBySubscriptionResponse]] + beginRemoveVMs *tracker[azfake.PollerResponder[armoracledatabase.CloudVMClustersClientRemoveVMsResponse]] + beginUpdate *tracker[azfake.PollerResponder[armoracledatabase.CloudVMClustersClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for CloudVMClustersServerTransport. +func (c *CloudVMClustersServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *CloudVMClustersServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if cloudVMClustersServerTransportInterceptor != nil { + res.resp, res.err, intercepted = cloudVMClustersServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "CloudVMClustersClient.BeginAddVMs": + res.resp, res.err = c.dispatchBeginAddVMs(req) + case "CloudVMClustersClient.BeginCreateOrUpdate": + res.resp, res.err = c.dispatchBeginCreateOrUpdate(req) + case "CloudVMClustersClient.BeginDelete": + res.resp, res.err = c.dispatchBeginDelete(req) + case "CloudVMClustersClient.Get": + res.resp, res.err = c.dispatchGet(req) + case "CloudVMClustersClient.NewListByResourceGroupPager": + res.resp, res.err = c.dispatchNewListByResourceGroupPager(req) + case "CloudVMClustersClient.NewListBySubscriptionPager": + res.resp, res.err = c.dispatchNewListBySubscriptionPager(req) + case "CloudVMClustersClient.ListPrivateIPAddresses": + res.resp, res.err = c.dispatchListPrivateIPAddresses(req) + case "CloudVMClustersClient.BeginRemoveVMs": + res.resp, res.err = c.dispatchBeginRemoveVMs(req) + case "CloudVMClustersClient.BeginUpdate": + res.resp, res.err = c.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *CloudVMClustersServerTransport) dispatchBeginAddVMs(req *http.Request) (*http.Response, error) { + if c.srv.BeginAddVMs == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginAddVMs not implemented")} + } + beginAddVMs := c.beginAddVMs.get(req) + if beginAddVMs == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudVmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/addVms` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.AddRemoveDbNode](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudvmclusternameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudvmclustername")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginAddVMs(req.Context(), resourceGroupNameParam, cloudvmclusternameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginAddVMs = &respr + c.beginAddVMs.add(req, beginAddVMs) + } + + resp, err := server.PollerResponderNext(beginAddVMs, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + c.beginAddVMs.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginAddVMs) { + c.beginAddVMs.remove(req) + } + + return resp, nil +} + +func (c *CloudVMClustersServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if c.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := c.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudVmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.CloudVMCluster](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudvmclusternameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudvmclustername")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, cloudvmclusternameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + c.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + c.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + c.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (c *CloudVMClustersServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if c.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := c.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudVmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudvmclusternameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudvmclustername")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginDelete(req.Context(), resourceGroupNameParam, cloudvmclusternameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + c.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + c.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + c.beginDelete.remove(req) + } + + return resp, nil +} + +func (c *CloudVMClustersServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if c.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudVmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudvmclusternameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudvmclustername")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.Get(req.Context(), resourceGroupNameParam, cloudvmclusternameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).CloudVMCluster, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *CloudVMClustersServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if c.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := c.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudVmClusters` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := c.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + c.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armoracledatabase.CloudVMClustersClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + c.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + c.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (c *CloudVMClustersServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if c.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := c.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudVmClusters` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := c.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + c.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armoracledatabase.CloudVMClustersClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + c.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + c.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (c *CloudVMClustersServerTransport) dispatchListPrivateIPAddresses(req *http.Request) (*http.Response, error) { + if c.srv.ListPrivateIPAddresses == nil { + return nil, &nonRetriableError{errors.New("fake for method ListPrivateIPAddresses not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudVmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/listPrivateIpAddresses` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.PrivateIPAddressesFilter](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudvmclusternameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudvmclustername")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.ListPrivateIPAddresses(req.Context(), resourceGroupNameParam, cloudvmclusternameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).PrivateIPAddressPropertiesArray, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *CloudVMClustersServerTransport) dispatchBeginRemoveVMs(req *http.Request) (*http.Response, error) { + if c.srv.BeginRemoveVMs == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginRemoveVMs not implemented")} + } + beginRemoveVMs := c.beginRemoveVMs.get(req) + if beginRemoveVMs == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudVmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/removeVms` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.AddRemoveDbNode](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudvmclusternameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudvmclustername")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginRemoveVMs(req.Context(), resourceGroupNameParam, cloudvmclusternameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginRemoveVMs = &respr + c.beginRemoveVMs.add(req, beginRemoveVMs) + } + + resp, err := server.PollerResponderNext(beginRemoveVMs, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + c.beginRemoveVMs.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginRemoveVMs) { + c.beginRemoveVMs.remove(req) + } + + return resp, nil +} + +func (c *CloudVMClustersServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if c.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := c.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudVmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.CloudVMClusterUpdate](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudvmclusternameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudvmclustername")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.BeginUpdate(req.Context(), resourceGroupNameParam, cloudvmclusternameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + c.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + c.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + c.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to CloudVMClustersServerTransport +var cloudVMClustersServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armoracledatabase/fake/zz_dbnodes_server.go b/test/local/armoracledatabase/fake/zz_dbnodes_server.go new file mode 100644 index 000000000000..3c4aa4938154 --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_dbnodes_server.go @@ -0,0 +1,233 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armoracledatabase/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// DbNodesServer is a fake server for instances of the armoracledatabase.DbNodesClient type. +type DbNodesServer struct { + // BeginAction is the fake for method DbNodesClient.BeginAction + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginAction func(ctx context.Context, resourceGroupName string, cloudvmclustername string, dbnodeocid string, body armoracledatabase.DbNodeAction, options *armoracledatabase.DbNodesClientBeginActionOptions) (resp azfake.PollerResponder[armoracledatabase.DbNodesClientActionResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method DbNodesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, cloudvmclustername string, dbnodeocid string, options *armoracledatabase.DbNodesClientGetOptions) (resp azfake.Responder[armoracledatabase.DbNodesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByCloudVMClusterPager is the fake for method DbNodesClient.NewListByCloudVMClusterPager + // HTTP status codes to indicate success: http.StatusOK + NewListByCloudVMClusterPager func(resourceGroupName string, cloudvmclustername string, options *armoracledatabase.DbNodesClientListByCloudVMClusterOptions) (resp azfake.PagerResponder[armoracledatabase.DbNodesClientListByCloudVMClusterResponse]) +} + +// NewDbNodesServerTransport creates a new instance of DbNodesServerTransport with the provided implementation. +// The returned DbNodesServerTransport instance is connected to an instance of armoracledatabase.DbNodesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDbNodesServerTransport(srv *DbNodesServer) *DbNodesServerTransport { + return &DbNodesServerTransport{ + srv: srv, + beginAction: newTracker[azfake.PollerResponder[armoracledatabase.DbNodesClientActionResponse]](), + newListByCloudVMClusterPager: newTracker[azfake.PagerResponder[armoracledatabase.DbNodesClientListByCloudVMClusterResponse]](), + } +} + +// DbNodesServerTransport connects instances of armoracledatabase.DbNodesClient to instances of DbNodesServer. +// Don't use this type directly, use NewDbNodesServerTransport instead. +type DbNodesServerTransport struct { + srv *DbNodesServer + beginAction *tracker[azfake.PollerResponder[armoracledatabase.DbNodesClientActionResponse]] + newListByCloudVMClusterPager *tracker[azfake.PagerResponder[armoracledatabase.DbNodesClientListByCloudVMClusterResponse]] +} + +// Do implements the policy.Transporter interface for DbNodesServerTransport. +func (d *DbNodesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DbNodesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if dbNodesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = dbNodesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DbNodesClient.BeginAction": + res.resp, res.err = d.dispatchBeginAction(req) + case "DbNodesClient.Get": + res.resp, res.err = d.dispatchGet(req) + case "DbNodesClient.NewListByCloudVMClusterPager": + res.resp, res.err = d.dispatchNewListByCloudVMClusterPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DbNodesServerTransport) dispatchBeginAction(req *http.Request) (*http.Response, error) { + if d.srv.BeginAction == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginAction not implemented")} + } + beginAction := d.beginAction.get(req) + if beginAction == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudVmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/dbNodes/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/action` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.DbNodeAction](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudvmclusternameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudvmclustername")]) + if err != nil { + return nil, err + } + dbnodeocidParam, err := url.PathUnescape(matches[regex.SubexpIndex("dbnodeocid")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.BeginAction(req.Context(), resourceGroupNameParam, cloudvmclusternameParam, dbnodeocidParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginAction = &respr + d.beginAction.add(req, beginAction) + } + + resp, err := server.PollerResponderNext(beginAction, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + d.beginAction.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginAction) { + d.beginAction.remove(req) + } + + return resp, nil +} + +func (d *DbNodesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudVmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/dbNodes/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudvmclusternameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudvmclustername")]) + if err != nil { + return nil, err + } + dbnodeocidParam, err := url.PathUnescape(matches[regex.SubexpIndex("dbnodeocid")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Get(req.Context(), resourceGroupNameParam, cloudvmclusternameParam, dbnodeocidParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DbNode, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DbNodesServerTransport) dispatchNewListByCloudVMClusterPager(req *http.Request) (*http.Response, error) { + if d.srv.NewListByCloudVMClusterPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByCloudVMClusterPager not implemented")} + } + newListByCloudVMClusterPager := d.newListByCloudVMClusterPager.get(req) + if newListByCloudVMClusterPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudVmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/dbNodes` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudvmclusternameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudvmclustername")]) + if err != nil { + return nil, err + } + resp := d.srv.NewListByCloudVMClusterPager(resourceGroupNameParam, cloudvmclusternameParam, nil) + newListByCloudVMClusterPager = &resp + d.newListByCloudVMClusterPager.add(req, newListByCloudVMClusterPager) + server.PagerResponderInjectNextLinks(newListByCloudVMClusterPager, req, func(page *armoracledatabase.DbNodesClientListByCloudVMClusterResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByCloudVMClusterPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + d.newListByCloudVMClusterPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByCloudVMClusterPager) { + d.newListByCloudVMClusterPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DbNodesServerTransport +var dbNodesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armoracledatabase/fake/zz_dbservers_server.go b/test/local/armoracledatabase/fake/zz_dbservers_server.go new file mode 100644 index 000000000000..783dbe8056a8 --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_dbservers_server.go @@ -0,0 +1,173 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armoracledatabase/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// DbServersServer is a fake server for instances of the armoracledatabase.DbServersClient type. +type DbServersServer struct { + // Get is the fake for method DbServersClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, cloudexadatainfrastructurename string, dbserverocid string, options *armoracledatabase.DbServersClientGetOptions) (resp azfake.Responder[armoracledatabase.DbServersClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByCloudExadataInfrastructurePager is the fake for method DbServersClient.NewListByCloudExadataInfrastructurePager + // HTTP status codes to indicate success: http.StatusOK + NewListByCloudExadataInfrastructurePager func(resourceGroupName string, cloudexadatainfrastructurename string, options *armoracledatabase.DbServersClientListByCloudExadataInfrastructureOptions) (resp azfake.PagerResponder[armoracledatabase.DbServersClientListByCloudExadataInfrastructureResponse]) +} + +// NewDbServersServerTransport creates a new instance of DbServersServerTransport with the provided implementation. +// The returned DbServersServerTransport instance is connected to an instance of armoracledatabase.DbServersClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDbServersServerTransport(srv *DbServersServer) *DbServersServerTransport { + return &DbServersServerTransport{ + srv: srv, + newListByCloudExadataInfrastructurePager: newTracker[azfake.PagerResponder[armoracledatabase.DbServersClientListByCloudExadataInfrastructureResponse]](), + } +} + +// DbServersServerTransport connects instances of armoracledatabase.DbServersClient to instances of DbServersServer. +// Don't use this type directly, use NewDbServersServerTransport instead. +type DbServersServerTransport struct { + srv *DbServersServer + newListByCloudExadataInfrastructurePager *tracker[azfake.PagerResponder[armoracledatabase.DbServersClientListByCloudExadataInfrastructureResponse]] +} + +// Do implements the policy.Transporter interface for DbServersServerTransport. +func (d *DbServersServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DbServersServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if dbServersServerTransportInterceptor != nil { + res.resp, res.err, intercepted = dbServersServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DbServersClient.Get": + res.resp, res.err = d.dispatchGet(req) + case "DbServersClient.NewListByCloudExadataInfrastructurePager": + res.resp, res.err = d.dispatchNewListByCloudExadataInfrastructurePager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DbServersServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudExadataInfrastructures/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/dbServers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudexadatainfrastructurenameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudexadatainfrastructurename")]) + if err != nil { + return nil, err + } + dbserverocidParam, err := url.PathUnescape(matches[regex.SubexpIndex("dbserverocid")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Get(req.Context(), resourceGroupNameParam, cloudexadatainfrastructurenameParam, dbserverocidParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DbServer, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DbServersServerTransport) dispatchNewListByCloudExadataInfrastructurePager(req *http.Request) (*http.Response, error) { + if d.srv.NewListByCloudExadataInfrastructurePager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByCloudExadataInfrastructurePager not implemented")} + } + newListByCloudExadataInfrastructurePager := d.newListByCloudExadataInfrastructurePager.get(req) + if newListByCloudExadataInfrastructurePager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudExadataInfrastructures/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/dbServers` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudexadatainfrastructurenameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudexadatainfrastructurename")]) + if err != nil { + return nil, err + } + resp := d.srv.NewListByCloudExadataInfrastructurePager(resourceGroupNameParam, cloudexadatainfrastructurenameParam, nil) + newListByCloudExadataInfrastructurePager = &resp + d.newListByCloudExadataInfrastructurePager.add(req, newListByCloudExadataInfrastructurePager) + server.PagerResponderInjectNextLinks(newListByCloudExadataInfrastructurePager, req, func(page *armoracledatabase.DbServersClientListByCloudExadataInfrastructureResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByCloudExadataInfrastructurePager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + d.newListByCloudExadataInfrastructurePager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByCloudExadataInfrastructurePager) { + d.newListByCloudExadataInfrastructurePager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DbServersServerTransport +var dbServersServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armoracledatabase/fake/zz_dbsystems_server.go b/test/local/armoracledatabase/fake/zz_dbsystems_server.go new file mode 100644 index 000000000000..86eb8c695dab --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_dbsystems_server.go @@ -0,0 +1,370 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armoracledatabase/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// DbSystemsServer is a fake server for instances of the armoracledatabase.DbSystemsClient type. +type DbSystemsServer struct { + // BeginCreateOrUpdate is the fake for method DbSystemsClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, dbSystemName string, resource armoracledatabase.DbSystem, options *armoracledatabase.DbSystemsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armoracledatabase.DbSystemsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method DbSystemsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, dbSystemName string, options *armoracledatabase.DbSystemsClientBeginDeleteOptions) (resp azfake.PollerResponder[armoracledatabase.DbSystemsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method DbSystemsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, dbSystemName string, options *armoracledatabase.DbSystemsClientGetOptions) (resp azfake.Responder[armoracledatabase.DbSystemsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method DbSystemsClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armoracledatabase.DbSystemsClientListByResourceGroupOptions) (resp azfake.PagerResponder[armoracledatabase.DbSystemsClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method DbSystemsClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armoracledatabase.DbSystemsClientListBySubscriptionOptions) (resp azfake.PagerResponder[armoracledatabase.DbSystemsClientListBySubscriptionResponse]) + + // BeginUpdate is the fake for method DbSystemsClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, dbSystemName string, properties armoracledatabase.DbSystemUpdate, options *armoracledatabase.DbSystemsClientBeginUpdateOptions) (resp azfake.PollerResponder[armoracledatabase.DbSystemsClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewDbSystemsServerTransport creates a new instance of DbSystemsServerTransport with the provided implementation. +// The returned DbSystemsServerTransport instance is connected to an instance of armoracledatabase.DbSystemsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDbSystemsServerTransport(srv *DbSystemsServer) *DbSystemsServerTransport { + return &DbSystemsServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armoracledatabase.DbSystemsClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armoracledatabase.DbSystemsClientDeleteResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armoracledatabase.DbSystemsClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armoracledatabase.DbSystemsClientListBySubscriptionResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armoracledatabase.DbSystemsClientUpdateResponse]](), + } +} + +// DbSystemsServerTransport connects instances of armoracledatabase.DbSystemsClient to instances of DbSystemsServer. +// Don't use this type directly, use NewDbSystemsServerTransport instead. +type DbSystemsServerTransport struct { + srv *DbSystemsServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armoracledatabase.DbSystemsClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armoracledatabase.DbSystemsClientDeleteResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armoracledatabase.DbSystemsClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armoracledatabase.DbSystemsClientListBySubscriptionResponse]] + beginUpdate *tracker[azfake.PollerResponder[armoracledatabase.DbSystemsClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for DbSystemsServerTransport. +func (d *DbSystemsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DbSystemsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if dbSystemsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = dbSystemsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DbSystemsClient.BeginCreateOrUpdate": + res.resp, res.err = d.dispatchBeginCreateOrUpdate(req) + case "DbSystemsClient.BeginDelete": + res.resp, res.err = d.dispatchBeginDelete(req) + case "DbSystemsClient.Get": + res.resp, res.err = d.dispatchGet(req) + case "DbSystemsClient.NewListByResourceGroupPager": + res.resp, res.err = d.dispatchNewListByResourceGroupPager(req) + case "DbSystemsClient.NewListBySubscriptionPager": + res.resp, res.err = d.dispatchNewListBySubscriptionPager(req) + case "DbSystemsClient.BeginUpdate": + res.resp, res.err = d.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DbSystemsServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if d.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := d.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/dbSystems/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.DbSystem](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + dbSystemNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("dbSystemName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, dbSystemNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + d.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + d.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + d.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (d *DbSystemsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if d.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := d.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/dbSystems/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + dbSystemNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("dbSystemName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.BeginDelete(req.Context(), resourceGroupNameParam, dbSystemNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + d.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + d.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + d.beginDelete.remove(req) + } + + return resp, nil +} + +func (d *DbSystemsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/dbSystems/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + dbSystemNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("dbSystemName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Get(req.Context(), resourceGroupNameParam, dbSystemNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DbSystem, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DbSystemsServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if d.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := d.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/dbSystems` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := d.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + d.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armoracledatabase.DbSystemsClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + d.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + d.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (d *DbSystemsServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if d.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := d.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/dbSystems` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := d.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + d.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armoracledatabase.DbSystemsClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + d.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + d.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (d *DbSystemsServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if d.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := d.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/dbSystems/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.DbSystemUpdate](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + dbSystemNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("dbSystemName")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.BeginUpdate(req.Context(), resourceGroupNameParam, dbSystemNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + d.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + d.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + d.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to DbSystemsServerTransport +var dbSystemsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armoracledatabase/fake/zz_dbsystemshapes_server.go b/test/local/armoracledatabase/fake/zz_dbsystemshapes_server.go new file mode 100644 index 000000000000..c075f3806bbf --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_dbsystemshapes_server.go @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armoracledatabase/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// DbSystemShapesServer is a fake server for instances of the armoracledatabase.DbSystemShapesClient type. +type DbSystemShapesServer struct { + // Get is the fake for method DbSystemShapesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, location string, dbsystemshapename string, options *armoracledatabase.DbSystemShapesClientGetOptions) (resp azfake.Responder[armoracledatabase.DbSystemShapesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByLocationPager is the fake for method DbSystemShapesClient.NewListByLocationPager + // HTTP status codes to indicate success: http.StatusOK + NewListByLocationPager func(location string, options *armoracledatabase.DbSystemShapesClientListByLocationOptions) (resp azfake.PagerResponder[armoracledatabase.DbSystemShapesClientListByLocationResponse]) +} + +// NewDbSystemShapesServerTransport creates a new instance of DbSystemShapesServerTransport with the provided implementation. +// The returned DbSystemShapesServerTransport instance is connected to an instance of armoracledatabase.DbSystemShapesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDbSystemShapesServerTransport(srv *DbSystemShapesServer) *DbSystemShapesServerTransport { + return &DbSystemShapesServerTransport{ + srv: srv, + newListByLocationPager: newTracker[azfake.PagerResponder[armoracledatabase.DbSystemShapesClientListByLocationResponse]](), + } +} + +// DbSystemShapesServerTransport connects instances of armoracledatabase.DbSystemShapesClient to instances of DbSystemShapesServer. +// Don't use this type directly, use NewDbSystemShapesServerTransport instead. +type DbSystemShapesServerTransport struct { + srv *DbSystemShapesServer + newListByLocationPager *tracker[azfake.PagerResponder[armoracledatabase.DbSystemShapesClientListByLocationResponse]] +} + +// Do implements the policy.Transporter interface for DbSystemShapesServerTransport. +func (d *DbSystemShapesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DbSystemShapesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if dbSystemShapesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = dbSystemShapesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DbSystemShapesClient.Get": + res.resp, res.err = d.dispatchGet(req) + case "DbSystemShapesClient.NewListByLocationPager": + res.resp, res.err = d.dispatchNewListByLocationPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DbSystemShapesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/dbSystemShapes/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + dbsystemshapenameParam, err := url.PathUnescape(matches[regex.SubexpIndex("dbsystemshapename")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Get(req.Context(), locationParam, dbsystemshapenameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DbSystemShape, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DbSystemShapesServerTransport) dispatchNewListByLocationPager(req *http.Request) (*http.Response, error) { + if d.srv.NewListByLocationPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByLocationPager not implemented")} + } + newListByLocationPager := d.newListByLocationPager.get(req) + if newListByLocationPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/dbSystemShapes` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + zoneParam := getOptional(qp.Get("zone")) + shapeAttributeParam := getOptional(qp.Get("shapeAttribute")) + var options *armoracledatabase.DbSystemShapesClientListByLocationOptions + if zoneParam != nil || shapeAttributeParam != nil { + options = &armoracledatabase.DbSystemShapesClientListByLocationOptions{ + Zone: zoneParam, + ShapeAttribute: shapeAttributeParam, + } + } + resp := d.srv.NewListByLocationPager(locationParam, options) + newListByLocationPager = &resp + d.newListByLocationPager.add(req, newListByLocationPager) + server.PagerResponderInjectNextLinks(newListByLocationPager, req, func(page *armoracledatabase.DbSystemShapesClientListByLocationResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByLocationPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + d.newListByLocationPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByLocationPager) { + d.newListByLocationPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DbSystemShapesServerTransport +var dbSystemShapesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armoracledatabase/fake/zz_dbversions_server.go b/test/local/armoracledatabase/fake/zz_dbversions_server.go new file mode 100644 index 000000000000..fbc2526a61b1 --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_dbversions_server.go @@ -0,0 +1,190 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armoracledatabase/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" + "strconv" +) + +// DbVersionsServer is a fake server for instances of the armoracledatabase.DbVersionsClient type. +type DbVersionsServer struct { + // Get is the fake for method DbVersionsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, location string, dbversionsname string, options *armoracledatabase.DbVersionsClientGetOptions) (resp azfake.Responder[armoracledatabase.DbVersionsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByLocationPager is the fake for method DbVersionsClient.NewListByLocationPager + // HTTP status codes to indicate success: http.StatusOK + NewListByLocationPager func(location string, options *armoracledatabase.DbVersionsClientListByLocationOptions) (resp azfake.PagerResponder[armoracledatabase.DbVersionsClientListByLocationResponse]) +} + +// NewDbVersionsServerTransport creates a new instance of DbVersionsServerTransport with the provided implementation. +// The returned DbVersionsServerTransport instance is connected to an instance of armoracledatabase.DbVersionsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDbVersionsServerTransport(srv *DbVersionsServer) *DbVersionsServerTransport { + return &DbVersionsServerTransport{ + srv: srv, + newListByLocationPager: newTracker[azfake.PagerResponder[armoracledatabase.DbVersionsClientListByLocationResponse]](), + } +} + +// DbVersionsServerTransport connects instances of armoracledatabase.DbVersionsClient to instances of DbVersionsServer. +// Don't use this type directly, use NewDbVersionsServerTransport instead. +type DbVersionsServerTransport struct { + srv *DbVersionsServer + newListByLocationPager *tracker[azfake.PagerResponder[armoracledatabase.DbVersionsClientListByLocationResponse]] +} + +// Do implements the policy.Transporter interface for DbVersionsServerTransport. +func (d *DbVersionsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DbVersionsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if dbVersionsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = dbVersionsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DbVersionsClient.Get": + res.resp, res.err = d.dispatchGet(req) + case "DbVersionsClient.NewListByLocationPager": + res.resp, res.err = d.dispatchNewListByLocationPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DbVersionsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/dbSystemDbVersions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + dbversionsnameParam, err := url.PathUnescape(matches[regex.SubexpIndex("dbversionsname")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Get(req.Context(), locationParam, dbversionsnameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DbVersion, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DbVersionsServerTransport) dispatchNewListByLocationPager(req *http.Request) (*http.Response, error) { + if d.srv.NewListByLocationPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByLocationPager not implemented")} + } + newListByLocationPager := d.newListByLocationPager.get(req) + if newListByLocationPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/dbSystemDbVersions` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + dbSystemShapeParam := getOptional(armoracledatabase.BaseDbSystemShapes(qp.Get("dbSystemShape"))) + dbSystemIDParam := getOptional(qp.Get("dbSystemId")) + storageManagementParam := getOptional(armoracledatabase.StorageManagementType(qp.Get("storageManagement"))) + isUpgradeSupportedParam, err := parseOptional(qp.Get("isUpgradeSupported"), strconv.ParseBool) + if err != nil { + return nil, err + } + isDatabaseSoftwareImageSupportedParam, err := parseOptional(qp.Get("isDatabaseSoftwareImageSupported"), strconv.ParseBool) + if err != nil { + return nil, err + } + shapeFamilyParam := getOptional(armoracledatabase.ShapeFamilyType(qp.Get("shapeFamily"))) + var options *armoracledatabase.DbVersionsClientListByLocationOptions + if dbSystemShapeParam != nil || dbSystemIDParam != nil || storageManagementParam != nil || isUpgradeSupportedParam != nil || isDatabaseSoftwareImageSupportedParam != nil || shapeFamilyParam != nil { + options = &armoracledatabase.DbVersionsClientListByLocationOptions{ + DbSystemShape: dbSystemShapeParam, + DbSystemID: dbSystemIDParam, + StorageManagement: storageManagementParam, + IsUpgradeSupported: isUpgradeSupportedParam, + IsDatabaseSoftwareImageSupported: isDatabaseSoftwareImageSupportedParam, + ShapeFamily: shapeFamilyParam, + } + } + resp := d.srv.NewListByLocationPager(locationParam, options) + newListByLocationPager = &resp + d.newListByLocationPager.add(req, newListByLocationPager) + server.PagerResponderInjectNextLinks(newListByLocationPager, req, func(page *armoracledatabase.DbVersionsClientListByLocationResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByLocationPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + d.newListByLocationPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByLocationPager) { + d.newListByLocationPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DbVersionsServerTransport +var dbVersionsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armoracledatabase/fake/zz_dnsprivateviews_server.go b/test/local/armoracledatabase/fake/zz_dnsprivateviews_server.go new file mode 100644 index 000000000000..7d0ad57dfc8c --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_dnsprivateviews_server.go @@ -0,0 +1,165 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armoracledatabase/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// DNSPrivateViewsServer is a fake server for instances of the armoracledatabase.DNSPrivateViewsClient type. +type DNSPrivateViewsServer struct { + // Get is the fake for method DNSPrivateViewsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, location string, dnsprivateviewocid string, options *armoracledatabase.DNSPrivateViewsClientGetOptions) (resp azfake.Responder[armoracledatabase.DNSPrivateViewsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByLocationPager is the fake for method DNSPrivateViewsClient.NewListByLocationPager + // HTTP status codes to indicate success: http.StatusOK + NewListByLocationPager func(location string, options *armoracledatabase.DNSPrivateViewsClientListByLocationOptions) (resp azfake.PagerResponder[armoracledatabase.DNSPrivateViewsClientListByLocationResponse]) +} + +// NewDNSPrivateViewsServerTransport creates a new instance of DNSPrivateViewsServerTransport with the provided implementation. +// The returned DNSPrivateViewsServerTransport instance is connected to an instance of armoracledatabase.DNSPrivateViewsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDNSPrivateViewsServerTransport(srv *DNSPrivateViewsServer) *DNSPrivateViewsServerTransport { + return &DNSPrivateViewsServerTransport{ + srv: srv, + newListByLocationPager: newTracker[azfake.PagerResponder[armoracledatabase.DNSPrivateViewsClientListByLocationResponse]](), + } +} + +// DNSPrivateViewsServerTransport connects instances of armoracledatabase.DNSPrivateViewsClient to instances of DNSPrivateViewsServer. +// Don't use this type directly, use NewDNSPrivateViewsServerTransport instead. +type DNSPrivateViewsServerTransport struct { + srv *DNSPrivateViewsServer + newListByLocationPager *tracker[azfake.PagerResponder[armoracledatabase.DNSPrivateViewsClientListByLocationResponse]] +} + +// Do implements the policy.Transporter interface for DNSPrivateViewsServerTransport. +func (d *DNSPrivateViewsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DNSPrivateViewsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if dnsPrivateViewsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = dnsPrivateViewsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DNSPrivateViewsClient.Get": + res.resp, res.err = d.dispatchGet(req) + case "DNSPrivateViewsClient.NewListByLocationPager": + res.resp, res.err = d.dispatchNewListByLocationPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DNSPrivateViewsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/dnsPrivateViews/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + dnsprivateviewocidParam, err := url.PathUnescape(matches[regex.SubexpIndex("dnsprivateviewocid")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Get(req.Context(), locationParam, dnsprivateviewocidParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DNSPrivateView, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DNSPrivateViewsServerTransport) dispatchNewListByLocationPager(req *http.Request) (*http.Response, error) { + if d.srv.NewListByLocationPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByLocationPager not implemented")} + } + newListByLocationPager := d.newListByLocationPager.get(req) + if newListByLocationPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/dnsPrivateViews` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + resp := d.srv.NewListByLocationPager(locationParam, nil) + newListByLocationPager = &resp + d.newListByLocationPager.add(req, newListByLocationPager) + server.PagerResponderInjectNextLinks(newListByLocationPager, req, func(page *armoracledatabase.DNSPrivateViewsClientListByLocationResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByLocationPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + d.newListByLocationPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByLocationPager) { + d.newListByLocationPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DNSPrivateViewsServerTransport +var dnsPrivateViewsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armoracledatabase/fake/zz_dnsprivatezones_server.go b/test/local/armoracledatabase/fake/zz_dnsprivatezones_server.go new file mode 100644 index 000000000000..f4c56fdca3b5 --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_dnsprivatezones_server.go @@ -0,0 +1,165 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armoracledatabase/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// DNSPrivateZonesServer is a fake server for instances of the armoracledatabase.DNSPrivateZonesClient type. +type DNSPrivateZonesServer struct { + // Get is the fake for method DNSPrivateZonesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, location string, dnsprivatezonename string, options *armoracledatabase.DNSPrivateZonesClientGetOptions) (resp azfake.Responder[armoracledatabase.DNSPrivateZonesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByLocationPager is the fake for method DNSPrivateZonesClient.NewListByLocationPager + // HTTP status codes to indicate success: http.StatusOK + NewListByLocationPager func(location string, options *armoracledatabase.DNSPrivateZonesClientListByLocationOptions) (resp azfake.PagerResponder[armoracledatabase.DNSPrivateZonesClientListByLocationResponse]) +} + +// NewDNSPrivateZonesServerTransport creates a new instance of DNSPrivateZonesServerTransport with the provided implementation. +// The returned DNSPrivateZonesServerTransport instance is connected to an instance of armoracledatabase.DNSPrivateZonesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewDNSPrivateZonesServerTransport(srv *DNSPrivateZonesServer) *DNSPrivateZonesServerTransport { + return &DNSPrivateZonesServerTransport{ + srv: srv, + newListByLocationPager: newTracker[azfake.PagerResponder[armoracledatabase.DNSPrivateZonesClientListByLocationResponse]](), + } +} + +// DNSPrivateZonesServerTransport connects instances of armoracledatabase.DNSPrivateZonesClient to instances of DNSPrivateZonesServer. +// Don't use this type directly, use NewDNSPrivateZonesServerTransport instead. +type DNSPrivateZonesServerTransport struct { + srv *DNSPrivateZonesServer + newListByLocationPager *tracker[azfake.PagerResponder[armoracledatabase.DNSPrivateZonesClientListByLocationResponse]] +} + +// Do implements the policy.Transporter interface for DNSPrivateZonesServerTransport. +func (d *DNSPrivateZonesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return d.dispatchToMethodFake(req, method) +} + +func (d *DNSPrivateZonesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if dnsPrivateZonesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = dnsPrivateZonesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "DNSPrivateZonesClient.Get": + res.resp, res.err = d.dispatchGet(req) + case "DNSPrivateZonesClient.NewListByLocationPager": + res.resp, res.err = d.dispatchNewListByLocationPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (d *DNSPrivateZonesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if d.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/dnsPrivateZones/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + dnsprivatezonenameParam, err := url.PathUnescape(matches[regex.SubexpIndex("dnsprivatezonename")]) + if err != nil { + return nil, err + } + respr, errRespr := d.srv.Get(req.Context(), locationParam, dnsprivatezonenameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DNSPrivateZone, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (d *DNSPrivateZonesServerTransport) dispatchNewListByLocationPager(req *http.Request) (*http.Response, error) { + if d.srv.NewListByLocationPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByLocationPager not implemented")} + } + newListByLocationPager := d.newListByLocationPager.get(req) + if newListByLocationPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/dnsPrivateZones` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + resp := d.srv.NewListByLocationPager(locationParam, nil) + newListByLocationPager = &resp + d.newListByLocationPager.add(req, newListByLocationPager) + server.PagerResponderInjectNextLinks(newListByLocationPager, req, func(page *armoracledatabase.DNSPrivateZonesClientListByLocationResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByLocationPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + d.newListByLocationPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByLocationPager) { + d.newListByLocationPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to DNSPrivateZonesServerTransport +var dnsPrivateZonesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armoracledatabase/fake/zz_exadbvmclusters_server.go b/test/local/armoracledatabase/fake/zz_exadbvmclusters_server.go new file mode 100644 index 000000000000..846802b61ed6 --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_exadbvmclusters_server.go @@ -0,0 +1,426 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armoracledatabase/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// ExadbVMClustersServer is a fake server for instances of the armoracledatabase.ExadbVMClustersClient type. +type ExadbVMClustersServer struct { + // BeginCreateOrUpdate is the fake for method ExadbVMClustersClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, exadbVMClusterName string, resource armoracledatabase.ExadbVMCluster, options *armoracledatabase.ExadbVMClustersClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armoracledatabase.ExadbVMClustersClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method ExadbVMClustersClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, exadbVMClusterName string, options *armoracledatabase.ExadbVMClustersClientBeginDeleteOptions) (resp azfake.PollerResponder[armoracledatabase.ExadbVMClustersClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method ExadbVMClustersClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, exadbVMClusterName string, options *armoracledatabase.ExadbVMClustersClientGetOptions) (resp azfake.Responder[armoracledatabase.ExadbVMClustersClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method ExadbVMClustersClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armoracledatabase.ExadbVMClustersClientListByResourceGroupOptions) (resp azfake.PagerResponder[armoracledatabase.ExadbVMClustersClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method ExadbVMClustersClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armoracledatabase.ExadbVMClustersClientListBySubscriptionOptions) (resp azfake.PagerResponder[armoracledatabase.ExadbVMClustersClientListBySubscriptionResponse]) + + // BeginRemoveVMs is the fake for method ExadbVMClustersClient.BeginRemoveVMs + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginRemoveVMs func(ctx context.Context, resourceGroupName string, exadbVMClusterName string, body armoracledatabase.RemoveVirtualMachineFromExadbVMClusterDetails, options *armoracledatabase.ExadbVMClustersClientBeginRemoveVMsOptions) (resp azfake.PollerResponder[armoracledatabase.ExadbVMClustersClientRemoveVMsResponse], errResp azfake.ErrorResponder) + + // BeginUpdate is the fake for method ExadbVMClustersClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, exadbVMClusterName string, properties armoracledatabase.ExadbVMClusterUpdate, options *armoracledatabase.ExadbVMClustersClientBeginUpdateOptions) (resp azfake.PollerResponder[armoracledatabase.ExadbVMClustersClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewExadbVMClustersServerTransport creates a new instance of ExadbVMClustersServerTransport with the provided implementation. +// The returned ExadbVMClustersServerTransport instance is connected to an instance of armoracledatabase.ExadbVMClustersClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewExadbVMClustersServerTransport(srv *ExadbVMClustersServer) *ExadbVMClustersServerTransport { + return &ExadbVMClustersServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armoracledatabase.ExadbVMClustersClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armoracledatabase.ExadbVMClustersClientDeleteResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armoracledatabase.ExadbVMClustersClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armoracledatabase.ExadbVMClustersClientListBySubscriptionResponse]](), + beginRemoveVMs: newTracker[azfake.PollerResponder[armoracledatabase.ExadbVMClustersClientRemoveVMsResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armoracledatabase.ExadbVMClustersClientUpdateResponse]](), + } +} + +// ExadbVMClustersServerTransport connects instances of armoracledatabase.ExadbVMClustersClient to instances of ExadbVMClustersServer. +// Don't use this type directly, use NewExadbVMClustersServerTransport instead. +type ExadbVMClustersServerTransport struct { + srv *ExadbVMClustersServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armoracledatabase.ExadbVMClustersClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armoracledatabase.ExadbVMClustersClientDeleteResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armoracledatabase.ExadbVMClustersClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armoracledatabase.ExadbVMClustersClientListBySubscriptionResponse]] + beginRemoveVMs *tracker[azfake.PollerResponder[armoracledatabase.ExadbVMClustersClientRemoveVMsResponse]] + beginUpdate *tracker[azfake.PollerResponder[armoracledatabase.ExadbVMClustersClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for ExadbVMClustersServerTransport. +func (e *ExadbVMClustersServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return e.dispatchToMethodFake(req, method) +} + +func (e *ExadbVMClustersServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if exadbVMClustersServerTransportInterceptor != nil { + res.resp, res.err, intercepted = exadbVMClustersServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ExadbVMClustersClient.BeginCreateOrUpdate": + res.resp, res.err = e.dispatchBeginCreateOrUpdate(req) + case "ExadbVMClustersClient.BeginDelete": + res.resp, res.err = e.dispatchBeginDelete(req) + case "ExadbVMClustersClient.Get": + res.resp, res.err = e.dispatchGet(req) + case "ExadbVMClustersClient.NewListByResourceGroupPager": + res.resp, res.err = e.dispatchNewListByResourceGroupPager(req) + case "ExadbVMClustersClient.NewListBySubscriptionPager": + res.resp, res.err = e.dispatchNewListBySubscriptionPager(req) + case "ExadbVMClustersClient.BeginRemoveVMs": + res.resp, res.err = e.dispatchBeginRemoveVMs(req) + case "ExadbVMClustersClient.BeginUpdate": + res.resp, res.err = e.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (e *ExadbVMClustersServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if e.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := e.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/exadbVmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.ExadbVMCluster](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + exadbVMClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("exadbVmClusterName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, exadbVMClusterNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + e.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + e.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + e.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (e *ExadbVMClustersServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if e.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := e.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/exadbVmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + exadbVMClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("exadbVmClusterName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.BeginDelete(req.Context(), resourceGroupNameParam, exadbVMClusterNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + e.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + e.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + e.beginDelete.remove(req) + } + + return resp, nil +} + +func (e *ExadbVMClustersServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if e.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/exadbVmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + exadbVMClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("exadbVmClusterName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.Get(req.Context(), resourceGroupNameParam, exadbVMClusterNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ExadbVMCluster, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *ExadbVMClustersServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if e.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := e.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/exadbVmClusters` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := e.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + e.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armoracledatabase.ExadbVMClustersClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + e.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + e.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (e *ExadbVMClustersServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if e.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := e.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/exadbVmClusters` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := e.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + e.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armoracledatabase.ExadbVMClustersClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + e.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + e.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (e *ExadbVMClustersServerTransport) dispatchBeginRemoveVMs(req *http.Request) (*http.Response, error) { + if e.srv.BeginRemoveVMs == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginRemoveVMs not implemented")} + } + beginRemoveVMs := e.beginRemoveVMs.get(req) + if beginRemoveVMs == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/exadbVmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/removeVms` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.RemoveVirtualMachineFromExadbVMClusterDetails](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + exadbVMClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("exadbVmClusterName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.BeginRemoveVMs(req.Context(), resourceGroupNameParam, exadbVMClusterNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginRemoveVMs = &respr + e.beginRemoveVMs.add(req, beginRemoveVMs) + } + + resp, err := server.PollerResponderNext(beginRemoveVMs, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + e.beginRemoveVMs.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginRemoveVMs) { + e.beginRemoveVMs.remove(req) + } + + return resp, nil +} + +func (e *ExadbVMClustersServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if e.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := e.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/exadbVmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.ExadbVMClusterUpdate](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + exadbVMClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("exadbVmClusterName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.BeginUpdate(req.Context(), resourceGroupNameParam, exadbVMClusterNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + e.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + e.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + e.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to ExadbVMClustersServerTransport +var exadbVMClustersServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armoracledatabase/fake/zz_exascaledbnodes_server.go b/test/local/armoracledatabase/fake/zz_exascaledbnodes_server.go new file mode 100644 index 000000000000..ec19f4362da4 --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_exascaledbnodes_server.go @@ -0,0 +1,233 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armoracledatabase/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// ExascaleDbNodesServer is a fake server for instances of the armoracledatabase.ExascaleDbNodesClient type. +type ExascaleDbNodesServer struct { + // BeginAction is the fake for method ExascaleDbNodesClient.BeginAction + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginAction func(ctx context.Context, resourceGroupName string, exadbVMClusterName string, exascaleDbNodeName string, body armoracledatabase.DbNodeAction, options *armoracledatabase.ExascaleDbNodesClientBeginActionOptions) (resp azfake.PollerResponder[armoracledatabase.ExascaleDbNodesClientActionResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method ExascaleDbNodesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, exadbVMClusterName string, exascaleDbNodeName string, options *armoracledatabase.ExascaleDbNodesClientGetOptions) (resp azfake.Responder[armoracledatabase.ExascaleDbNodesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByParentPager is the fake for method ExascaleDbNodesClient.NewListByParentPager + // HTTP status codes to indicate success: http.StatusOK + NewListByParentPager func(resourceGroupName string, exadbVMClusterName string, options *armoracledatabase.ExascaleDbNodesClientListByParentOptions) (resp azfake.PagerResponder[armoracledatabase.ExascaleDbNodesClientListByParentResponse]) +} + +// NewExascaleDbNodesServerTransport creates a new instance of ExascaleDbNodesServerTransport with the provided implementation. +// The returned ExascaleDbNodesServerTransport instance is connected to an instance of armoracledatabase.ExascaleDbNodesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewExascaleDbNodesServerTransport(srv *ExascaleDbNodesServer) *ExascaleDbNodesServerTransport { + return &ExascaleDbNodesServerTransport{ + srv: srv, + beginAction: newTracker[azfake.PollerResponder[armoracledatabase.ExascaleDbNodesClientActionResponse]](), + newListByParentPager: newTracker[azfake.PagerResponder[armoracledatabase.ExascaleDbNodesClientListByParentResponse]](), + } +} + +// ExascaleDbNodesServerTransport connects instances of armoracledatabase.ExascaleDbNodesClient to instances of ExascaleDbNodesServer. +// Don't use this type directly, use NewExascaleDbNodesServerTransport instead. +type ExascaleDbNodesServerTransport struct { + srv *ExascaleDbNodesServer + beginAction *tracker[azfake.PollerResponder[armoracledatabase.ExascaleDbNodesClientActionResponse]] + newListByParentPager *tracker[azfake.PagerResponder[armoracledatabase.ExascaleDbNodesClientListByParentResponse]] +} + +// Do implements the policy.Transporter interface for ExascaleDbNodesServerTransport. +func (e *ExascaleDbNodesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return e.dispatchToMethodFake(req, method) +} + +func (e *ExascaleDbNodesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if exascaleDbNodesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = exascaleDbNodesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ExascaleDbNodesClient.BeginAction": + res.resp, res.err = e.dispatchBeginAction(req) + case "ExascaleDbNodesClient.Get": + res.resp, res.err = e.dispatchGet(req) + case "ExascaleDbNodesClient.NewListByParentPager": + res.resp, res.err = e.dispatchNewListByParentPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (e *ExascaleDbNodesServerTransport) dispatchBeginAction(req *http.Request) (*http.Response, error) { + if e.srv.BeginAction == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginAction not implemented")} + } + beginAction := e.beginAction.get(req) + if beginAction == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/exadbVmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/dbNodes/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/action` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.DbNodeAction](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + exadbVMClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("exadbVmClusterName")]) + if err != nil { + return nil, err + } + exascaleDbNodeNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("exascaleDbNodeName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.BeginAction(req.Context(), resourceGroupNameParam, exadbVMClusterNameParam, exascaleDbNodeNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginAction = &respr + e.beginAction.add(req, beginAction) + } + + resp, err := server.PollerResponderNext(beginAction, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + e.beginAction.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginAction) { + e.beginAction.remove(req) + } + + return resp, nil +} + +func (e *ExascaleDbNodesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if e.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/exadbVmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/dbNodes/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + exadbVMClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("exadbVmClusterName")]) + if err != nil { + return nil, err + } + exascaleDbNodeNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("exascaleDbNodeName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.Get(req.Context(), resourceGroupNameParam, exadbVMClusterNameParam, exascaleDbNodeNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ExascaleDbNode, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *ExascaleDbNodesServerTransport) dispatchNewListByParentPager(req *http.Request) (*http.Response, error) { + if e.srv.NewListByParentPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByParentPager not implemented")} + } + newListByParentPager := e.newListByParentPager.get(req) + if newListByParentPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/exadbVmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/dbNodes` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + exadbVMClusterNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("exadbVmClusterName")]) + if err != nil { + return nil, err + } + resp := e.srv.NewListByParentPager(resourceGroupNameParam, exadbVMClusterNameParam, nil) + newListByParentPager = &resp + e.newListByParentPager.add(req, newListByParentPager) + server.PagerResponderInjectNextLinks(newListByParentPager, req, func(page *armoracledatabase.ExascaleDbNodesClientListByParentResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByParentPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + e.newListByParentPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByParentPager) { + e.newListByParentPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ExascaleDbNodesServerTransport +var exascaleDbNodesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armoracledatabase/fake/zz_exascaledbstoragevaults_server.go b/test/local/armoracledatabase/fake/zz_exascaledbstoragevaults_server.go new file mode 100644 index 000000000000..a61ddf665a8a --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_exascaledbstoragevaults_server.go @@ -0,0 +1,370 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armoracledatabase/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// ExascaleDbStorageVaultsServer is a fake server for instances of the armoracledatabase.ExascaleDbStorageVaultsClient type. +type ExascaleDbStorageVaultsServer struct { + // BeginCreate is the fake for method ExascaleDbStorageVaultsClient.BeginCreate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreate func(ctx context.Context, resourceGroupName string, exascaleDbStorageVaultName string, resource armoracledatabase.ExascaleDbStorageVault, options *armoracledatabase.ExascaleDbStorageVaultsClientBeginCreateOptions) (resp azfake.PollerResponder[armoracledatabase.ExascaleDbStorageVaultsClientCreateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method ExascaleDbStorageVaultsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, exascaleDbStorageVaultName string, options *armoracledatabase.ExascaleDbStorageVaultsClientBeginDeleteOptions) (resp azfake.PollerResponder[armoracledatabase.ExascaleDbStorageVaultsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method ExascaleDbStorageVaultsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, exascaleDbStorageVaultName string, options *armoracledatabase.ExascaleDbStorageVaultsClientGetOptions) (resp azfake.Responder[armoracledatabase.ExascaleDbStorageVaultsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method ExascaleDbStorageVaultsClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armoracledatabase.ExascaleDbStorageVaultsClientListByResourceGroupOptions) (resp azfake.PagerResponder[armoracledatabase.ExascaleDbStorageVaultsClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method ExascaleDbStorageVaultsClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armoracledatabase.ExascaleDbStorageVaultsClientListBySubscriptionOptions) (resp azfake.PagerResponder[armoracledatabase.ExascaleDbStorageVaultsClientListBySubscriptionResponse]) + + // BeginUpdate is the fake for method ExascaleDbStorageVaultsClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, exascaleDbStorageVaultName string, properties armoracledatabase.ExascaleDbStorageVaultTagsUpdate, options *armoracledatabase.ExascaleDbStorageVaultsClientBeginUpdateOptions) (resp azfake.PollerResponder[armoracledatabase.ExascaleDbStorageVaultsClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewExascaleDbStorageVaultsServerTransport creates a new instance of ExascaleDbStorageVaultsServerTransport with the provided implementation. +// The returned ExascaleDbStorageVaultsServerTransport instance is connected to an instance of armoracledatabase.ExascaleDbStorageVaultsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewExascaleDbStorageVaultsServerTransport(srv *ExascaleDbStorageVaultsServer) *ExascaleDbStorageVaultsServerTransport { + return &ExascaleDbStorageVaultsServerTransport{ + srv: srv, + beginCreate: newTracker[azfake.PollerResponder[armoracledatabase.ExascaleDbStorageVaultsClientCreateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armoracledatabase.ExascaleDbStorageVaultsClientDeleteResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armoracledatabase.ExascaleDbStorageVaultsClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armoracledatabase.ExascaleDbStorageVaultsClientListBySubscriptionResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armoracledatabase.ExascaleDbStorageVaultsClientUpdateResponse]](), + } +} + +// ExascaleDbStorageVaultsServerTransport connects instances of armoracledatabase.ExascaleDbStorageVaultsClient to instances of ExascaleDbStorageVaultsServer. +// Don't use this type directly, use NewExascaleDbStorageVaultsServerTransport instead. +type ExascaleDbStorageVaultsServerTransport struct { + srv *ExascaleDbStorageVaultsServer + beginCreate *tracker[azfake.PollerResponder[armoracledatabase.ExascaleDbStorageVaultsClientCreateResponse]] + beginDelete *tracker[azfake.PollerResponder[armoracledatabase.ExascaleDbStorageVaultsClientDeleteResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armoracledatabase.ExascaleDbStorageVaultsClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armoracledatabase.ExascaleDbStorageVaultsClientListBySubscriptionResponse]] + beginUpdate *tracker[azfake.PollerResponder[armoracledatabase.ExascaleDbStorageVaultsClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for ExascaleDbStorageVaultsServerTransport. +func (e *ExascaleDbStorageVaultsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return e.dispatchToMethodFake(req, method) +} + +func (e *ExascaleDbStorageVaultsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if exascaleDbStorageVaultsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = exascaleDbStorageVaultsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ExascaleDbStorageVaultsClient.BeginCreate": + res.resp, res.err = e.dispatchBeginCreate(req) + case "ExascaleDbStorageVaultsClient.BeginDelete": + res.resp, res.err = e.dispatchBeginDelete(req) + case "ExascaleDbStorageVaultsClient.Get": + res.resp, res.err = e.dispatchGet(req) + case "ExascaleDbStorageVaultsClient.NewListByResourceGroupPager": + res.resp, res.err = e.dispatchNewListByResourceGroupPager(req) + case "ExascaleDbStorageVaultsClient.NewListBySubscriptionPager": + res.resp, res.err = e.dispatchNewListBySubscriptionPager(req) + case "ExascaleDbStorageVaultsClient.BeginUpdate": + res.resp, res.err = e.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (e *ExascaleDbStorageVaultsServerTransport) dispatchBeginCreate(req *http.Request) (*http.Response, error) { + if e.srv.BeginCreate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreate not implemented")} + } + beginCreate := e.beginCreate.get(req) + if beginCreate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/exascaleDbStorageVaults/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.ExascaleDbStorageVault](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + exascaleDbStorageVaultNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("exascaleDbStorageVaultName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.BeginCreate(req.Context(), resourceGroupNameParam, exascaleDbStorageVaultNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreate = &respr + e.beginCreate.add(req, beginCreate) + } + + resp, err := server.PollerResponderNext(beginCreate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + e.beginCreate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreate) { + e.beginCreate.remove(req) + } + + return resp, nil +} + +func (e *ExascaleDbStorageVaultsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if e.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := e.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/exascaleDbStorageVaults/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + exascaleDbStorageVaultNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("exascaleDbStorageVaultName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.BeginDelete(req.Context(), resourceGroupNameParam, exascaleDbStorageVaultNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + e.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + e.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + e.beginDelete.remove(req) + } + + return resp, nil +} + +func (e *ExascaleDbStorageVaultsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if e.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/exascaleDbStorageVaults/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + exascaleDbStorageVaultNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("exascaleDbStorageVaultName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.Get(req.Context(), resourceGroupNameParam, exascaleDbStorageVaultNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ExascaleDbStorageVault, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (e *ExascaleDbStorageVaultsServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if e.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := e.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/exascaleDbStorageVaults` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := e.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + e.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armoracledatabase.ExascaleDbStorageVaultsClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + e.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + e.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (e *ExascaleDbStorageVaultsServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if e.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := e.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/exascaleDbStorageVaults` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := e.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + e.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armoracledatabase.ExascaleDbStorageVaultsClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + e.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + e.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (e *ExascaleDbStorageVaultsServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if e.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := e.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/exascaleDbStorageVaults/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.ExascaleDbStorageVaultTagsUpdate](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + exascaleDbStorageVaultNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("exascaleDbStorageVaultName")]) + if err != nil { + return nil, err + } + respr, errRespr := e.srv.BeginUpdate(req.Context(), resourceGroupNameParam, exascaleDbStorageVaultNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + e.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + e.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + e.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to ExascaleDbStorageVaultsServerTransport +var exascaleDbStorageVaultsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armoracledatabase/fake/zz_flexcomponents_server.go b/test/local/armoracledatabase/fake/zz_flexcomponents_server.go new file mode 100644 index 000000000000..2a79b22e1390 --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_flexcomponents_server.go @@ -0,0 +1,173 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armoracledatabase/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// FlexComponentsServer is a fake server for instances of the armoracledatabase.FlexComponentsClient type. +type FlexComponentsServer struct { + // Get is the fake for method FlexComponentsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, location string, flexComponentName string, options *armoracledatabase.FlexComponentsClientGetOptions) (resp azfake.Responder[armoracledatabase.FlexComponentsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByParentPager is the fake for method FlexComponentsClient.NewListByParentPager + // HTTP status codes to indicate success: http.StatusOK + NewListByParentPager func(location string, options *armoracledatabase.FlexComponentsClientListByParentOptions) (resp azfake.PagerResponder[armoracledatabase.FlexComponentsClientListByParentResponse]) +} + +// NewFlexComponentsServerTransport creates a new instance of FlexComponentsServerTransport with the provided implementation. +// The returned FlexComponentsServerTransport instance is connected to an instance of armoracledatabase.FlexComponentsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewFlexComponentsServerTransport(srv *FlexComponentsServer) *FlexComponentsServerTransport { + return &FlexComponentsServerTransport{ + srv: srv, + newListByParentPager: newTracker[azfake.PagerResponder[armoracledatabase.FlexComponentsClientListByParentResponse]](), + } +} + +// FlexComponentsServerTransport connects instances of armoracledatabase.FlexComponentsClient to instances of FlexComponentsServer. +// Don't use this type directly, use NewFlexComponentsServerTransport instead. +type FlexComponentsServerTransport struct { + srv *FlexComponentsServer + newListByParentPager *tracker[azfake.PagerResponder[armoracledatabase.FlexComponentsClientListByParentResponse]] +} + +// Do implements the policy.Transporter interface for FlexComponentsServerTransport. +func (f *FlexComponentsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return f.dispatchToMethodFake(req, method) +} + +func (f *FlexComponentsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if flexComponentsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = flexComponentsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "FlexComponentsClient.Get": + res.resp, res.err = f.dispatchGet(req) + case "FlexComponentsClient.NewListByParentPager": + res.resp, res.err = f.dispatchNewListByParentPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (f *FlexComponentsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if f.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/flexComponents/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + flexComponentNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("flexComponentName")]) + if err != nil { + return nil, err + } + respr, errRespr := f.srv.Get(req.Context(), locationParam, flexComponentNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).FlexComponent, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (f *FlexComponentsServerTransport) dispatchNewListByParentPager(req *http.Request) (*http.Response, error) { + if f.srv.NewListByParentPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByParentPager not implemented")} + } + newListByParentPager := f.newListByParentPager.get(req) + if newListByParentPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/flexComponents` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + shapeParam := getOptional(armoracledatabase.SystemShapes(qp.Get("shape"))) + var options *armoracledatabase.FlexComponentsClientListByParentOptions + if shapeParam != nil { + options = &armoracledatabase.FlexComponentsClientListByParentOptions{ + Shape: shapeParam, + } + } + resp := f.srv.NewListByParentPager(locationParam, options) + newListByParentPager = &resp + f.newListByParentPager.add(req, newListByParentPager) + server.PagerResponderInjectNextLinks(newListByParentPager, req, func(page *armoracledatabase.FlexComponentsClientListByParentResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByParentPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + f.newListByParentPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByParentPager) { + f.newListByParentPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to FlexComponentsServerTransport +var flexComponentsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armoracledatabase/fake/zz_giminorversions_server.go b/test/local/armoracledatabase/fake/zz_giminorversions_server.go new file mode 100644 index 000000000000..2179b25b09f7 --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_giminorversions_server.go @@ -0,0 +1,183 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armoracledatabase/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// GiMinorVersionsServer is a fake server for instances of the armoracledatabase.GiMinorVersionsClient type. +type GiMinorVersionsServer struct { + // Get is the fake for method GiMinorVersionsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, location string, giversionname string, giMinorVersionName string, options *armoracledatabase.GiMinorVersionsClientGetOptions) (resp azfake.Responder[armoracledatabase.GiMinorVersionsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByParentPager is the fake for method GiMinorVersionsClient.NewListByParentPager + // HTTP status codes to indicate success: http.StatusOK + NewListByParentPager func(location string, giversionname string, options *armoracledatabase.GiMinorVersionsClientListByParentOptions) (resp azfake.PagerResponder[armoracledatabase.GiMinorVersionsClientListByParentResponse]) +} + +// NewGiMinorVersionsServerTransport creates a new instance of GiMinorVersionsServerTransport with the provided implementation. +// The returned GiMinorVersionsServerTransport instance is connected to an instance of armoracledatabase.GiMinorVersionsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewGiMinorVersionsServerTransport(srv *GiMinorVersionsServer) *GiMinorVersionsServerTransport { + return &GiMinorVersionsServerTransport{ + srv: srv, + newListByParentPager: newTracker[azfake.PagerResponder[armoracledatabase.GiMinorVersionsClientListByParentResponse]](), + } +} + +// GiMinorVersionsServerTransport connects instances of armoracledatabase.GiMinorVersionsClient to instances of GiMinorVersionsServer. +// Don't use this type directly, use NewGiMinorVersionsServerTransport instead. +type GiMinorVersionsServerTransport struct { + srv *GiMinorVersionsServer + newListByParentPager *tracker[azfake.PagerResponder[armoracledatabase.GiMinorVersionsClientListByParentResponse]] +} + +// Do implements the policy.Transporter interface for GiMinorVersionsServerTransport. +func (g *GiMinorVersionsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return g.dispatchToMethodFake(req, method) +} + +func (g *GiMinorVersionsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if giMinorVersionsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = giMinorVersionsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "GiMinorVersionsClient.Get": + res.resp, res.err = g.dispatchGet(req) + case "GiMinorVersionsClient.NewListByParentPager": + res.resp, res.err = g.dispatchNewListByParentPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (g *GiMinorVersionsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if g.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/giVersions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/giMinorVersions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + giversionnameParam, err := url.PathUnescape(matches[regex.SubexpIndex("giversionname")]) + if err != nil { + return nil, err + } + giMinorVersionNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("giMinorVersionName")]) + if err != nil { + return nil, err + } + respr, errRespr := g.srv.Get(req.Context(), locationParam, giversionnameParam, giMinorVersionNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).GiMinorVersion, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (g *GiMinorVersionsServerTransport) dispatchNewListByParentPager(req *http.Request) (*http.Response, error) { + if g.srv.NewListByParentPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByParentPager not implemented")} + } + newListByParentPager := g.newListByParentPager.get(req) + if newListByParentPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/giVersions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/giMinorVersions` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + giversionnameParam, err := url.PathUnescape(matches[regex.SubexpIndex("giversionname")]) + if err != nil { + return nil, err + } + shapeFamilyParam := getOptional(armoracledatabase.ShapeFamily(qp.Get("shapeFamily"))) + zoneParam := getOptional(qp.Get("zone")) + var options *armoracledatabase.GiMinorVersionsClientListByParentOptions + if shapeFamilyParam != nil || zoneParam != nil { + options = &armoracledatabase.GiMinorVersionsClientListByParentOptions{ + ShapeFamily: shapeFamilyParam, + Zone: zoneParam, + } + } + resp := g.srv.NewListByParentPager(locationParam, giversionnameParam, options) + newListByParentPager = &resp + g.newListByParentPager.add(req, newListByParentPager) + server.PagerResponderInjectNextLinks(newListByParentPager, req, func(page *armoracledatabase.GiMinorVersionsClientListByParentResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByParentPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + g.newListByParentPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByParentPager) { + g.newListByParentPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to GiMinorVersionsServerTransport +var giMinorVersionsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armoracledatabase/fake/zz_giversions_server.go b/test/local/armoracledatabase/fake/zz_giversions_server.go new file mode 100644 index 000000000000..15036b725cb5 --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_giversions_server.go @@ -0,0 +1,177 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armoracledatabase/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// GiVersionsServer is a fake server for instances of the armoracledatabase.GiVersionsClient type. +type GiVersionsServer struct { + // Get is the fake for method GiVersionsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, location string, giversionname string, options *armoracledatabase.GiVersionsClientGetOptions) (resp azfake.Responder[armoracledatabase.GiVersionsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByLocationPager is the fake for method GiVersionsClient.NewListByLocationPager + // HTTP status codes to indicate success: http.StatusOK + NewListByLocationPager func(location string, options *armoracledatabase.GiVersionsClientListByLocationOptions) (resp azfake.PagerResponder[armoracledatabase.GiVersionsClientListByLocationResponse]) +} + +// NewGiVersionsServerTransport creates a new instance of GiVersionsServerTransport with the provided implementation. +// The returned GiVersionsServerTransport instance is connected to an instance of armoracledatabase.GiVersionsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewGiVersionsServerTransport(srv *GiVersionsServer) *GiVersionsServerTransport { + return &GiVersionsServerTransport{ + srv: srv, + newListByLocationPager: newTracker[azfake.PagerResponder[armoracledatabase.GiVersionsClientListByLocationResponse]](), + } +} + +// GiVersionsServerTransport connects instances of armoracledatabase.GiVersionsClient to instances of GiVersionsServer. +// Don't use this type directly, use NewGiVersionsServerTransport instead. +type GiVersionsServerTransport struct { + srv *GiVersionsServer + newListByLocationPager *tracker[azfake.PagerResponder[armoracledatabase.GiVersionsClientListByLocationResponse]] +} + +// Do implements the policy.Transporter interface for GiVersionsServerTransport. +func (g *GiVersionsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return g.dispatchToMethodFake(req, method) +} + +func (g *GiVersionsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if giVersionsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = giVersionsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "GiVersionsClient.Get": + res.resp, res.err = g.dispatchGet(req) + case "GiVersionsClient.NewListByLocationPager": + res.resp, res.err = g.dispatchNewListByLocationPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (g *GiVersionsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if g.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/giVersions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + giversionnameParam, err := url.PathUnescape(matches[regex.SubexpIndex("giversionname")]) + if err != nil { + return nil, err + } + respr, errRespr := g.srv.Get(req.Context(), locationParam, giversionnameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).GiVersion, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (g *GiVersionsServerTransport) dispatchNewListByLocationPager(req *http.Request) (*http.Response, error) { + if g.srv.NewListByLocationPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByLocationPager not implemented")} + } + newListByLocationPager := g.newListByLocationPager.get(req) + if newListByLocationPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/giVersions` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + shapeParam := getOptional(armoracledatabase.SystemShapes(qp.Get("shape"))) + zoneParam := getOptional(qp.Get("zone")) + shapeAttributeParam := getOptional(qp.Get("shapeAttribute")) + var options *armoracledatabase.GiVersionsClientListByLocationOptions + if shapeParam != nil || zoneParam != nil || shapeAttributeParam != nil { + options = &armoracledatabase.GiVersionsClientListByLocationOptions{ + Shape: shapeParam, + Zone: zoneParam, + ShapeAttribute: shapeAttributeParam, + } + } + resp := g.srv.NewListByLocationPager(locationParam, options) + newListByLocationPager = &resp + g.newListByLocationPager.add(req, newListByLocationPager) + server.PagerResponderInjectNextLinks(newListByLocationPager, req, func(page *armoracledatabase.GiVersionsClientListByLocationResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByLocationPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + g.newListByLocationPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByLocationPager) { + g.newListByLocationPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to GiVersionsServerTransport +var giVersionsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armoracledatabase/fake/zz_internal.go b/test/local/armoracledatabase/fake/zz_internal.go new file mode 100644 index 000000000000..504fffe54caa --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_internal.go @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "reflect" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getOptional[T any](v T) *T { + if reflect.ValueOf(v).IsZero() { + return nil + } + return &v +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func parseOptional[T any](v string, parse func(v string) (T, error)) (*T, error) { + if v == "" { + return nil, nil + } + t, err := parse(v) + if err != nil { + return nil, err + } + return &t, nil +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/local/armoracledatabase/fake/zz_networkanchors_server.go b/test/local/armoracledatabase/fake/zz_networkanchors_server.go new file mode 100644 index 000000000000..7559d8a3ceda --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_networkanchors_server.go @@ -0,0 +1,370 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armoracledatabase/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// NetworkAnchorsServer is a fake server for instances of the armoracledatabase.NetworkAnchorsClient type. +type NetworkAnchorsServer struct { + // BeginCreateOrUpdate is the fake for method NetworkAnchorsClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, networkAnchorName string, resource armoracledatabase.NetworkAnchor, options *armoracledatabase.NetworkAnchorsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armoracledatabase.NetworkAnchorsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method NetworkAnchorsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, networkAnchorName string, options *armoracledatabase.NetworkAnchorsClientBeginDeleteOptions) (resp azfake.PollerResponder[armoracledatabase.NetworkAnchorsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method NetworkAnchorsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, networkAnchorName string, options *armoracledatabase.NetworkAnchorsClientGetOptions) (resp azfake.Responder[armoracledatabase.NetworkAnchorsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method NetworkAnchorsClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armoracledatabase.NetworkAnchorsClientListByResourceGroupOptions) (resp azfake.PagerResponder[armoracledatabase.NetworkAnchorsClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method NetworkAnchorsClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armoracledatabase.NetworkAnchorsClientListBySubscriptionOptions) (resp azfake.PagerResponder[armoracledatabase.NetworkAnchorsClientListBySubscriptionResponse]) + + // BeginUpdate is the fake for method NetworkAnchorsClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, networkAnchorName string, properties armoracledatabase.NetworkAnchorUpdate, options *armoracledatabase.NetworkAnchorsClientBeginUpdateOptions) (resp azfake.PollerResponder[armoracledatabase.NetworkAnchorsClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewNetworkAnchorsServerTransport creates a new instance of NetworkAnchorsServerTransport with the provided implementation. +// The returned NetworkAnchorsServerTransport instance is connected to an instance of armoracledatabase.NetworkAnchorsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewNetworkAnchorsServerTransport(srv *NetworkAnchorsServer) *NetworkAnchorsServerTransport { + return &NetworkAnchorsServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armoracledatabase.NetworkAnchorsClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armoracledatabase.NetworkAnchorsClientDeleteResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armoracledatabase.NetworkAnchorsClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armoracledatabase.NetworkAnchorsClientListBySubscriptionResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armoracledatabase.NetworkAnchorsClientUpdateResponse]](), + } +} + +// NetworkAnchorsServerTransport connects instances of armoracledatabase.NetworkAnchorsClient to instances of NetworkAnchorsServer. +// Don't use this type directly, use NewNetworkAnchorsServerTransport instead. +type NetworkAnchorsServerTransport struct { + srv *NetworkAnchorsServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armoracledatabase.NetworkAnchorsClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armoracledatabase.NetworkAnchorsClientDeleteResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armoracledatabase.NetworkAnchorsClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armoracledatabase.NetworkAnchorsClientListBySubscriptionResponse]] + beginUpdate *tracker[azfake.PollerResponder[armoracledatabase.NetworkAnchorsClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for NetworkAnchorsServerTransport. +func (n *NetworkAnchorsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return n.dispatchToMethodFake(req, method) +} + +func (n *NetworkAnchorsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if networkAnchorsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = networkAnchorsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "NetworkAnchorsClient.BeginCreateOrUpdate": + res.resp, res.err = n.dispatchBeginCreateOrUpdate(req) + case "NetworkAnchorsClient.BeginDelete": + res.resp, res.err = n.dispatchBeginDelete(req) + case "NetworkAnchorsClient.Get": + res.resp, res.err = n.dispatchGet(req) + case "NetworkAnchorsClient.NewListByResourceGroupPager": + res.resp, res.err = n.dispatchNewListByResourceGroupPager(req) + case "NetworkAnchorsClient.NewListBySubscriptionPager": + res.resp, res.err = n.dispatchNewListBySubscriptionPager(req) + case "NetworkAnchorsClient.BeginUpdate": + res.resp, res.err = n.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (n *NetworkAnchorsServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if n.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := n.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/networkAnchors/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.NetworkAnchor](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + networkAnchorNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("networkAnchorName")]) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, networkAnchorNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + n.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + n.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + n.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (n *NetworkAnchorsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if n.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := n.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/networkAnchors/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + networkAnchorNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("networkAnchorName")]) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.BeginDelete(req.Context(), resourceGroupNameParam, networkAnchorNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + n.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + n.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + n.beginDelete.remove(req) + } + + return resp, nil +} + +func (n *NetworkAnchorsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if n.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/networkAnchors/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + networkAnchorNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("networkAnchorName")]) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.Get(req.Context(), resourceGroupNameParam, networkAnchorNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).NetworkAnchor, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (n *NetworkAnchorsServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if n.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := n.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/networkAnchors` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := n.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + n.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armoracledatabase.NetworkAnchorsClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + n.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + n.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (n *NetworkAnchorsServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if n.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := n.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/networkAnchors` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := n.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + n.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armoracledatabase.NetworkAnchorsClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + n.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + n.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (n *NetworkAnchorsServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if n.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := n.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/networkAnchors/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.NetworkAnchorUpdate](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + networkAnchorNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("networkAnchorName")]) + if err != nil { + return nil, err + } + respr, errRespr := n.srv.BeginUpdate(req.Context(), resourceGroupNameParam, networkAnchorNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + n.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + n.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + n.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to NetworkAnchorsServerTransport +var networkAnchorsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armoracledatabase/fake/zz_operations_server.go b/test/local/armoracledatabase/fake/zz_operations_server.go new file mode 100644 index 000000000000..2098bccf42be --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_operations_server.go @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armoracledatabase/v2" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "slices" +) + +// OperationsServer is a fake server for instances of the armoracledatabase.OperationsClient type. +type OperationsServer struct { + // NewListPager is the fake for method OperationsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armoracledatabase.OperationsClientListOptions) (resp azfake.PagerResponder[armoracledatabase.OperationsClientListResponse]) +} + +// NewOperationsServerTransport creates a new instance of OperationsServerTransport with the provided implementation. +// The returned OperationsServerTransport instance is connected to an instance of armoracledatabase.OperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOperationsServerTransport(srv *OperationsServer) *OperationsServerTransport { + return &OperationsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armoracledatabase.OperationsClientListResponse]](), + } +} + +// OperationsServerTransport connects instances of armoracledatabase.OperationsClient to instances of OperationsServer. +// Don't use this type directly, use NewOperationsServerTransport instead. +type OperationsServerTransport struct { + srv *OperationsServer + newListPager *tracker[azfake.PagerResponder[armoracledatabase.OperationsClientListResponse]] +} + +// Do implements the policy.Transporter interface for OperationsServerTransport. +func (o *OperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if operationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = operationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OperationsClient.NewListPager": + res.resp, res.err = o.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OperationsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := o.newListPager.get(req) + if newListPager == nil { + resp := o.srv.NewListPager(nil) + newListPager = &resp + o.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armoracledatabase.OperationsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + o.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + o.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to OperationsServerTransport +var operationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armoracledatabase/fake/zz_oraclesubscriptions_server.go b/test/local/armoracledatabase/fake/zz_oraclesubscriptions_server.go new file mode 100644 index 000000000000..603bb86e8d48 --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_oraclesubscriptions_server.go @@ -0,0 +1,472 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armoracledatabase/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "regexp" + "slices" +) + +// OracleSubscriptionsServer is a fake server for instances of the armoracledatabase.OracleSubscriptionsClient type. +type OracleSubscriptionsServer struct { + // BeginAddAzureSubscriptions is the fake for method OracleSubscriptionsClient.BeginAddAzureSubscriptions + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginAddAzureSubscriptions func(ctx context.Context, body armoracledatabase.AzureSubscriptions, options *armoracledatabase.OracleSubscriptionsClientBeginAddAzureSubscriptionsOptions) (resp azfake.PollerResponder[armoracledatabase.OracleSubscriptionsClientAddAzureSubscriptionsResponse], errResp azfake.ErrorResponder) + + // BeginCreateOrUpdate is the fake for method OracleSubscriptionsClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resource armoracledatabase.OracleSubscription, options *armoracledatabase.OracleSubscriptionsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armoracledatabase.OracleSubscriptionsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method OracleSubscriptionsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, options *armoracledatabase.OracleSubscriptionsClientBeginDeleteOptions) (resp azfake.PollerResponder[armoracledatabase.OracleSubscriptionsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method OracleSubscriptionsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *armoracledatabase.OracleSubscriptionsClientGetOptions) (resp azfake.Responder[armoracledatabase.OracleSubscriptionsClientGetResponse], errResp azfake.ErrorResponder) + + // BeginListActivationLinks is the fake for method OracleSubscriptionsClient.BeginListActivationLinks + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginListActivationLinks func(ctx context.Context, options *armoracledatabase.OracleSubscriptionsClientBeginListActivationLinksOptions) (resp azfake.PollerResponder[armoracledatabase.OracleSubscriptionsClientListActivationLinksResponse], errResp azfake.ErrorResponder) + + // NewListBySubscriptionPager is the fake for method OracleSubscriptionsClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armoracledatabase.OracleSubscriptionsClientListBySubscriptionOptions) (resp azfake.PagerResponder[armoracledatabase.OracleSubscriptionsClientListBySubscriptionResponse]) + + // BeginListCloudAccountDetails is the fake for method OracleSubscriptionsClient.BeginListCloudAccountDetails + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginListCloudAccountDetails func(ctx context.Context, options *armoracledatabase.OracleSubscriptionsClientBeginListCloudAccountDetailsOptions) (resp azfake.PollerResponder[armoracledatabase.OracleSubscriptionsClientListCloudAccountDetailsResponse], errResp azfake.ErrorResponder) + + // BeginListSaasSubscriptionDetails is the fake for method OracleSubscriptionsClient.BeginListSaasSubscriptionDetails + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginListSaasSubscriptionDetails func(ctx context.Context, options *armoracledatabase.OracleSubscriptionsClientBeginListSaasSubscriptionDetailsOptions) (resp azfake.PollerResponder[armoracledatabase.OracleSubscriptionsClientListSaasSubscriptionDetailsResponse], errResp azfake.ErrorResponder) + + // BeginUpdate is the fake for method OracleSubscriptionsClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, properties armoracledatabase.OracleSubscriptionUpdate, options *armoracledatabase.OracleSubscriptionsClientBeginUpdateOptions) (resp azfake.PollerResponder[armoracledatabase.OracleSubscriptionsClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewOracleSubscriptionsServerTransport creates a new instance of OracleSubscriptionsServerTransport with the provided implementation. +// The returned OracleSubscriptionsServerTransport instance is connected to an instance of armoracledatabase.OracleSubscriptionsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewOracleSubscriptionsServerTransport(srv *OracleSubscriptionsServer) *OracleSubscriptionsServerTransport { + return &OracleSubscriptionsServerTransport{ + srv: srv, + beginAddAzureSubscriptions: newTracker[azfake.PollerResponder[armoracledatabase.OracleSubscriptionsClientAddAzureSubscriptionsResponse]](), + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armoracledatabase.OracleSubscriptionsClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armoracledatabase.OracleSubscriptionsClientDeleteResponse]](), + beginListActivationLinks: newTracker[azfake.PollerResponder[armoracledatabase.OracleSubscriptionsClientListActivationLinksResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armoracledatabase.OracleSubscriptionsClientListBySubscriptionResponse]](), + beginListCloudAccountDetails: newTracker[azfake.PollerResponder[armoracledatabase.OracleSubscriptionsClientListCloudAccountDetailsResponse]](), + beginListSaasSubscriptionDetails: newTracker[azfake.PollerResponder[armoracledatabase.OracleSubscriptionsClientListSaasSubscriptionDetailsResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armoracledatabase.OracleSubscriptionsClientUpdateResponse]](), + } +} + +// OracleSubscriptionsServerTransport connects instances of armoracledatabase.OracleSubscriptionsClient to instances of OracleSubscriptionsServer. +// Don't use this type directly, use NewOracleSubscriptionsServerTransport instead. +type OracleSubscriptionsServerTransport struct { + srv *OracleSubscriptionsServer + beginAddAzureSubscriptions *tracker[azfake.PollerResponder[armoracledatabase.OracleSubscriptionsClientAddAzureSubscriptionsResponse]] + beginCreateOrUpdate *tracker[azfake.PollerResponder[armoracledatabase.OracleSubscriptionsClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armoracledatabase.OracleSubscriptionsClientDeleteResponse]] + beginListActivationLinks *tracker[azfake.PollerResponder[armoracledatabase.OracleSubscriptionsClientListActivationLinksResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armoracledatabase.OracleSubscriptionsClientListBySubscriptionResponse]] + beginListCloudAccountDetails *tracker[azfake.PollerResponder[armoracledatabase.OracleSubscriptionsClientListCloudAccountDetailsResponse]] + beginListSaasSubscriptionDetails *tracker[azfake.PollerResponder[armoracledatabase.OracleSubscriptionsClientListSaasSubscriptionDetailsResponse]] + beginUpdate *tracker[azfake.PollerResponder[armoracledatabase.OracleSubscriptionsClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for OracleSubscriptionsServerTransport. +func (o *OracleSubscriptionsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return o.dispatchToMethodFake(req, method) +} + +func (o *OracleSubscriptionsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if oracleSubscriptionsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = oracleSubscriptionsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "OracleSubscriptionsClient.BeginAddAzureSubscriptions": + res.resp, res.err = o.dispatchBeginAddAzureSubscriptions(req) + case "OracleSubscriptionsClient.BeginCreateOrUpdate": + res.resp, res.err = o.dispatchBeginCreateOrUpdate(req) + case "OracleSubscriptionsClient.BeginDelete": + res.resp, res.err = o.dispatchBeginDelete(req) + case "OracleSubscriptionsClient.Get": + res.resp, res.err = o.dispatchGet(req) + case "OracleSubscriptionsClient.BeginListActivationLinks": + res.resp, res.err = o.dispatchBeginListActivationLinks(req) + case "OracleSubscriptionsClient.NewListBySubscriptionPager": + res.resp, res.err = o.dispatchNewListBySubscriptionPager(req) + case "OracleSubscriptionsClient.BeginListCloudAccountDetails": + res.resp, res.err = o.dispatchBeginListCloudAccountDetails(req) + case "OracleSubscriptionsClient.BeginListSaasSubscriptionDetails": + res.resp, res.err = o.dispatchBeginListSaasSubscriptionDetails(req) + case "OracleSubscriptionsClient.BeginUpdate": + res.resp, res.err = o.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (o *OracleSubscriptionsServerTransport) dispatchBeginAddAzureSubscriptions(req *http.Request) (*http.Response, error) { + if o.srv.BeginAddAzureSubscriptions == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginAddAzureSubscriptions not implemented")} + } + beginAddAzureSubscriptions := o.beginAddAzureSubscriptions.get(req) + if beginAddAzureSubscriptions == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/oracleSubscriptions/default/addAzureSubscriptions` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.AzureSubscriptions](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.BeginAddAzureSubscriptions(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginAddAzureSubscriptions = &respr + o.beginAddAzureSubscriptions.add(req, beginAddAzureSubscriptions) + } + + resp, err := server.PollerResponderNext(beginAddAzureSubscriptions, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + o.beginAddAzureSubscriptions.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginAddAzureSubscriptions) { + o.beginAddAzureSubscriptions.remove(req) + } + + return resp, nil +} + +func (o *OracleSubscriptionsServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if o.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := o.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/oracleSubscriptions/default` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.OracleSubscription](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.BeginCreateOrUpdate(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + o.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + o.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + o.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (o *OracleSubscriptionsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if o.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := o.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/oracleSubscriptions/default` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + respr, errRespr := o.srv.BeginDelete(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + o.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + o.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + o.beginDelete.remove(req) + } + + return resp, nil +} + +func (o *OracleSubscriptionsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if o.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/oracleSubscriptions/default` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + respr, errRespr := o.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).OracleSubscription, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (o *OracleSubscriptionsServerTransport) dispatchBeginListActivationLinks(req *http.Request) (*http.Response, error) { + if o.srv.BeginListActivationLinks == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginListActivationLinks not implemented")} + } + beginListActivationLinks := o.beginListActivationLinks.get(req) + if beginListActivationLinks == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/oracleSubscriptions/default/listActivationLinks` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + respr, errRespr := o.srv.BeginListActivationLinks(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginListActivationLinks = &respr + o.beginListActivationLinks.add(req, beginListActivationLinks) + } + + resp, err := server.PollerResponderNext(beginListActivationLinks, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + o.beginListActivationLinks.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginListActivationLinks) { + o.beginListActivationLinks.remove(req) + } + + return resp, nil +} + +func (o *OracleSubscriptionsServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if o.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := o.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/oracleSubscriptions` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := o.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + o.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armoracledatabase.OracleSubscriptionsClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + o.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + o.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (o *OracleSubscriptionsServerTransport) dispatchBeginListCloudAccountDetails(req *http.Request) (*http.Response, error) { + if o.srv.BeginListCloudAccountDetails == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginListCloudAccountDetails not implemented")} + } + beginListCloudAccountDetails := o.beginListCloudAccountDetails.get(req) + if beginListCloudAccountDetails == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/oracleSubscriptions/default/listCloudAccountDetails` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + respr, errRespr := o.srv.BeginListCloudAccountDetails(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginListCloudAccountDetails = &respr + o.beginListCloudAccountDetails.add(req, beginListCloudAccountDetails) + } + + resp, err := server.PollerResponderNext(beginListCloudAccountDetails, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + o.beginListCloudAccountDetails.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginListCloudAccountDetails) { + o.beginListCloudAccountDetails.remove(req) + } + + return resp, nil +} + +func (o *OracleSubscriptionsServerTransport) dispatchBeginListSaasSubscriptionDetails(req *http.Request) (*http.Response, error) { + if o.srv.BeginListSaasSubscriptionDetails == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginListSaasSubscriptionDetails not implemented")} + } + beginListSaasSubscriptionDetails := o.beginListSaasSubscriptionDetails.get(req) + if beginListSaasSubscriptionDetails == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/oracleSubscriptions/default/listSaasSubscriptionDetails` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + respr, errRespr := o.srv.BeginListSaasSubscriptionDetails(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginListSaasSubscriptionDetails = &respr + o.beginListSaasSubscriptionDetails.add(req, beginListSaasSubscriptionDetails) + } + + resp, err := server.PollerResponderNext(beginListSaasSubscriptionDetails, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + o.beginListSaasSubscriptionDetails.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginListSaasSubscriptionDetails) { + o.beginListSaasSubscriptionDetails.remove(req) + } + + return resp, nil +} + +func (o *OracleSubscriptionsServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if o.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := o.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/oracleSubscriptions/default` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.OracleSubscriptionUpdate](req) + if err != nil { + return nil, err + } + respr, errRespr := o.srv.BeginUpdate(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + o.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + o.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + o.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to OracleSubscriptionsServerTransport +var oracleSubscriptionsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armoracledatabase/fake/zz_resourceanchors_server.go b/test/local/armoracledatabase/fake/zz_resourceanchors_server.go new file mode 100644 index 000000000000..37e1bd9d9f80 --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_resourceanchors_server.go @@ -0,0 +1,370 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armoracledatabase/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// ResourceAnchorsServer is a fake server for instances of the armoracledatabase.ResourceAnchorsClient type. +type ResourceAnchorsServer struct { + // BeginCreateOrUpdate is the fake for method ResourceAnchorsClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, resourceAnchorName string, resource armoracledatabase.ResourceAnchor, options *armoracledatabase.ResourceAnchorsClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armoracledatabase.ResourceAnchorsClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method ResourceAnchorsClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, resourceAnchorName string, options *armoracledatabase.ResourceAnchorsClientBeginDeleteOptions) (resp azfake.PollerResponder[armoracledatabase.ResourceAnchorsClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method ResourceAnchorsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, resourceAnchorName string, options *armoracledatabase.ResourceAnchorsClientGetOptions) (resp azfake.Responder[armoracledatabase.ResourceAnchorsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByResourceGroupPager is the fake for method ResourceAnchorsClient.NewListByResourceGroupPager + // HTTP status codes to indicate success: http.StatusOK + NewListByResourceGroupPager func(resourceGroupName string, options *armoracledatabase.ResourceAnchorsClientListByResourceGroupOptions) (resp azfake.PagerResponder[armoracledatabase.ResourceAnchorsClientListByResourceGroupResponse]) + + // NewListBySubscriptionPager is the fake for method ResourceAnchorsClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armoracledatabase.ResourceAnchorsClientListBySubscriptionOptions) (resp azfake.PagerResponder[armoracledatabase.ResourceAnchorsClientListBySubscriptionResponse]) + + // BeginUpdate is the fake for method ResourceAnchorsClient.BeginUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginUpdate func(ctx context.Context, resourceGroupName string, resourceAnchorName string, properties armoracledatabase.ResourceAnchorUpdate, options *armoracledatabase.ResourceAnchorsClientBeginUpdateOptions) (resp azfake.PollerResponder[armoracledatabase.ResourceAnchorsClientUpdateResponse], errResp azfake.ErrorResponder) +} + +// NewResourceAnchorsServerTransport creates a new instance of ResourceAnchorsServerTransport with the provided implementation. +// The returned ResourceAnchorsServerTransport instance is connected to an instance of armoracledatabase.ResourceAnchorsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewResourceAnchorsServerTransport(srv *ResourceAnchorsServer) *ResourceAnchorsServerTransport { + return &ResourceAnchorsServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armoracledatabase.ResourceAnchorsClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armoracledatabase.ResourceAnchorsClientDeleteResponse]](), + newListByResourceGroupPager: newTracker[azfake.PagerResponder[armoracledatabase.ResourceAnchorsClientListByResourceGroupResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armoracledatabase.ResourceAnchorsClientListBySubscriptionResponse]](), + beginUpdate: newTracker[azfake.PollerResponder[armoracledatabase.ResourceAnchorsClientUpdateResponse]](), + } +} + +// ResourceAnchorsServerTransport connects instances of armoracledatabase.ResourceAnchorsClient to instances of ResourceAnchorsServer. +// Don't use this type directly, use NewResourceAnchorsServerTransport instead. +type ResourceAnchorsServerTransport struct { + srv *ResourceAnchorsServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armoracledatabase.ResourceAnchorsClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armoracledatabase.ResourceAnchorsClientDeleteResponse]] + newListByResourceGroupPager *tracker[azfake.PagerResponder[armoracledatabase.ResourceAnchorsClientListByResourceGroupResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armoracledatabase.ResourceAnchorsClientListBySubscriptionResponse]] + beginUpdate *tracker[azfake.PollerResponder[armoracledatabase.ResourceAnchorsClientUpdateResponse]] +} + +// Do implements the policy.Transporter interface for ResourceAnchorsServerTransport. +func (r *ResourceAnchorsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return r.dispatchToMethodFake(req, method) +} + +func (r *ResourceAnchorsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if resourceAnchorsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = resourceAnchorsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ResourceAnchorsClient.BeginCreateOrUpdate": + res.resp, res.err = r.dispatchBeginCreateOrUpdate(req) + case "ResourceAnchorsClient.BeginDelete": + res.resp, res.err = r.dispatchBeginDelete(req) + case "ResourceAnchorsClient.Get": + res.resp, res.err = r.dispatchGet(req) + case "ResourceAnchorsClient.NewListByResourceGroupPager": + res.resp, res.err = r.dispatchNewListByResourceGroupPager(req) + case "ResourceAnchorsClient.NewListBySubscriptionPager": + res.resp, res.err = r.dispatchNewListBySubscriptionPager(req) + case "ResourceAnchorsClient.BeginUpdate": + res.resp, res.err = r.dispatchBeginUpdate(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (r *ResourceAnchorsServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if r.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := r.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/resourceAnchors/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.ResourceAnchor](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resourceAnchorNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceAnchorName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, resourceAnchorNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + r.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + r.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + r.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (r *ResourceAnchorsServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if r.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := r.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/resourceAnchors/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resourceAnchorNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceAnchorName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.BeginDelete(req.Context(), resourceGroupNameParam, resourceAnchorNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + r.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + r.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + r.beginDelete.remove(req) + } + + return resp, nil +} + +func (r *ResourceAnchorsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if r.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/resourceAnchors/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resourceAnchorNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceAnchorName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.Get(req.Context(), resourceGroupNameParam, resourceAnchorNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ResourceAnchor, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (r *ResourceAnchorsServerTransport) dispatchNewListByResourceGroupPager(req *http.Request) (*http.Response, error) { + if r.srv.NewListByResourceGroupPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByResourceGroupPager not implemented")} + } + newListByResourceGroupPager := r.newListByResourceGroupPager.get(req) + if newListByResourceGroupPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/resourceAnchors` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resp := r.srv.NewListByResourceGroupPager(resourceGroupNameParam, nil) + newListByResourceGroupPager = &resp + r.newListByResourceGroupPager.add(req, newListByResourceGroupPager) + server.PagerResponderInjectNextLinks(newListByResourceGroupPager, req, func(page *armoracledatabase.ResourceAnchorsClientListByResourceGroupResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByResourceGroupPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + r.newListByResourceGroupPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByResourceGroupPager) { + r.newListByResourceGroupPager.remove(req) + } + return resp, nil +} + +func (r *ResourceAnchorsServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if r.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := r.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/resourceAnchors` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := r.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + r.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armoracledatabase.ResourceAnchorsClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + r.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + r.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +func (r *ResourceAnchorsServerTransport) dispatchBeginUpdate(req *http.Request) (*http.Response, error) { + if r.srv.BeginUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginUpdate not implemented")} + } + beginUpdate := r.beginUpdate.get(req) + if beginUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/resourceAnchors/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.ResourceAnchorUpdate](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resourceAnchorNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceAnchorName")]) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.BeginUpdate(req.Context(), resourceGroupNameParam, resourceAnchorNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginUpdate = &respr + r.beginUpdate.add(req, beginUpdate) + } + + resp, err := server.PollerResponderNext(beginUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + r.beginUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginUpdate) { + r.beginUpdate.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to ResourceAnchorsServerTransport +var resourceAnchorsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armoracledatabase/fake/zz_server_factory.go b/test/local/armoracledatabase/fake/zz_server_factory.go new file mode 100644 index 000000000000..d1025fb95df7 --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_server_factory.go @@ -0,0 +1,279 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armoracledatabase.ClientFactory type. +type ServerFactory struct { + // AutonomousDatabaseBackupsServer contains the fakes for client AutonomousDatabaseBackupsClient + AutonomousDatabaseBackupsServer AutonomousDatabaseBackupsServer + + // AutonomousDatabaseCharacterSetsServer contains the fakes for client AutonomousDatabaseCharacterSetsClient + AutonomousDatabaseCharacterSetsServer AutonomousDatabaseCharacterSetsServer + + // AutonomousDatabaseNationalCharacterSetsServer contains the fakes for client AutonomousDatabaseNationalCharacterSetsClient + AutonomousDatabaseNationalCharacterSetsServer AutonomousDatabaseNationalCharacterSetsServer + + // AutonomousDatabaseVersionsServer contains the fakes for client AutonomousDatabaseVersionsClient + AutonomousDatabaseVersionsServer AutonomousDatabaseVersionsServer + + // AutonomousDatabasesServer contains the fakes for client AutonomousDatabasesClient + AutonomousDatabasesServer AutonomousDatabasesServer + + // CloudExadataInfrastructuresServer contains the fakes for client CloudExadataInfrastructuresClient + CloudExadataInfrastructuresServer CloudExadataInfrastructuresServer + + // CloudVMClustersServer contains the fakes for client CloudVMClustersClient + CloudVMClustersServer CloudVMClustersServer + + // DNSPrivateViewsServer contains the fakes for client DNSPrivateViewsClient + DNSPrivateViewsServer DNSPrivateViewsServer + + // DNSPrivateZonesServer contains the fakes for client DNSPrivateZonesClient + DNSPrivateZonesServer DNSPrivateZonesServer + + // DbNodesServer contains the fakes for client DbNodesClient + DbNodesServer DbNodesServer + + // DbServersServer contains the fakes for client DbServersClient + DbServersServer DbServersServer + + // DbSystemShapesServer contains the fakes for client DbSystemShapesClient + DbSystemShapesServer DbSystemShapesServer + + // DbSystemsServer contains the fakes for client DbSystemsClient + DbSystemsServer DbSystemsServer + + // DbVersionsServer contains the fakes for client DbVersionsClient + DbVersionsServer DbVersionsServer + + // ExadbVMClustersServer contains the fakes for client ExadbVMClustersClient + ExadbVMClustersServer ExadbVMClustersServer + + // ExascaleDbNodesServer contains the fakes for client ExascaleDbNodesClient + ExascaleDbNodesServer ExascaleDbNodesServer + + // ExascaleDbStorageVaultsServer contains the fakes for client ExascaleDbStorageVaultsClient + ExascaleDbStorageVaultsServer ExascaleDbStorageVaultsServer + + // FlexComponentsServer contains the fakes for client FlexComponentsClient + FlexComponentsServer FlexComponentsServer + + // GiMinorVersionsServer contains the fakes for client GiMinorVersionsClient + GiMinorVersionsServer GiMinorVersionsServer + + // GiVersionsServer contains the fakes for client GiVersionsClient + GiVersionsServer GiVersionsServer + + // NetworkAnchorsServer contains the fakes for client NetworkAnchorsClient + NetworkAnchorsServer NetworkAnchorsServer + + // OperationsServer contains the fakes for client OperationsClient + OperationsServer OperationsServer + + // OracleSubscriptionsServer contains the fakes for client OracleSubscriptionsClient + OracleSubscriptionsServer OracleSubscriptionsServer + + // ResourceAnchorsServer contains the fakes for client ResourceAnchorsClient + ResourceAnchorsServer ResourceAnchorsServer + + // SystemVersionsServer contains the fakes for client SystemVersionsClient + SystemVersionsServer SystemVersionsServer + + // VirtualNetworkAddressesServer contains the fakes for client VirtualNetworkAddressesClient + VirtualNetworkAddressesServer VirtualNetworkAddressesServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armoracledatabase.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of armoracledatabase.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trAutonomousDatabaseBackupsServer *AutonomousDatabaseBackupsServerTransport + trAutonomousDatabaseCharacterSetsServer *AutonomousDatabaseCharacterSetsServerTransport + trAutonomousDatabaseNationalCharacterSetsServer *AutonomousDatabaseNationalCharacterSetsServerTransport + trAutonomousDatabaseVersionsServer *AutonomousDatabaseVersionsServerTransport + trAutonomousDatabasesServer *AutonomousDatabasesServerTransport + trCloudExadataInfrastructuresServer *CloudExadataInfrastructuresServerTransport + trCloudVMClustersServer *CloudVMClustersServerTransport + trDNSPrivateViewsServer *DNSPrivateViewsServerTransport + trDNSPrivateZonesServer *DNSPrivateZonesServerTransport + trDbNodesServer *DbNodesServerTransport + trDbServersServer *DbServersServerTransport + trDbSystemShapesServer *DbSystemShapesServerTransport + trDbSystemsServer *DbSystemsServerTransport + trDbVersionsServer *DbVersionsServerTransport + trExadbVMClustersServer *ExadbVMClustersServerTransport + trExascaleDbNodesServer *ExascaleDbNodesServerTransport + trExascaleDbStorageVaultsServer *ExascaleDbStorageVaultsServerTransport + trFlexComponentsServer *FlexComponentsServerTransport + trGiMinorVersionsServer *GiMinorVersionsServerTransport + trGiVersionsServer *GiVersionsServerTransport + trNetworkAnchorsServer *NetworkAnchorsServerTransport + trOperationsServer *OperationsServerTransport + trOracleSubscriptionsServer *OracleSubscriptionsServerTransport + trResourceAnchorsServer *ResourceAnchorsServerTransport + trSystemVersionsServer *SystemVersionsServerTransport + trVirtualNetworkAddressesServer *VirtualNetworkAddressesServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "AutonomousDatabaseBackupsClient": + initServer(&s.trMu, &s.trAutonomousDatabaseBackupsServer, func() *AutonomousDatabaseBackupsServerTransport { + return NewAutonomousDatabaseBackupsServerTransport(&s.srv.AutonomousDatabaseBackupsServer) + }) + resp, err = s.trAutonomousDatabaseBackupsServer.Do(req) + case "AutonomousDatabaseCharacterSetsClient": + initServer(&s.trMu, &s.trAutonomousDatabaseCharacterSetsServer, func() *AutonomousDatabaseCharacterSetsServerTransport { + return NewAutonomousDatabaseCharacterSetsServerTransport(&s.srv.AutonomousDatabaseCharacterSetsServer) + }) + resp, err = s.trAutonomousDatabaseCharacterSetsServer.Do(req) + case "AutonomousDatabaseNationalCharacterSetsClient": + initServer(&s.trMu, &s.trAutonomousDatabaseNationalCharacterSetsServer, func() *AutonomousDatabaseNationalCharacterSetsServerTransport { + return NewAutonomousDatabaseNationalCharacterSetsServerTransport(&s.srv.AutonomousDatabaseNationalCharacterSetsServer) + }) + resp, err = s.trAutonomousDatabaseNationalCharacterSetsServer.Do(req) + case "AutonomousDatabaseVersionsClient": + initServer(&s.trMu, &s.trAutonomousDatabaseVersionsServer, func() *AutonomousDatabaseVersionsServerTransport { + return NewAutonomousDatabaseVersionsServerTransport(&s.srv.AutonomousDatabaseVersionsServer) + }) + resp, err = s.trAutonomousDatabaseVersionsServer.Do(req) + case "AutonomousDatabasesClient": + initServer(&s.trMu, &s.trAutonomousDatabasesServer, func() *AutonomousDatabasesServerTransport { + return NewAutonomousDatabasesServerTransport(&s.srv.AutonomousDatabasesServer) + }) + resp, err = s.trAutonomousDatabasesServer.Do(req) + case "CloudExadataInfrastructuresClient": + initServer(&s.trMu, &s.trCloudExadataInfrastructuresServer, func() *CloudExadataInfrastructuresServerTransport { + return NewCloudExadataInfrastructuresServerTransport(&s.srv.CloudExadataInfrastructuresServer) + }) + resp, err = s.trCloudExadataInfrastructuresServer.Do(req) + case "CloudVMClustersClient": + initServer(&s.trMu, &s.trCloudVMClustersServer, func() *CloudVMClustersServerTransport { + return NewCloudVMClustersServerTransport(&s.srv.CloudVMClustersServer) + }) + resp, err = s.trCloudVMClustersServer.Do(req) + case "DNSPrivateViewsClient": + initServer(&s.trMu, &s.trDNSPrivateViewsServer, func() *DNSPrivateViewsServerTransport { + return NewDNSPrivateViewsServerTransport(&s.srv.DNSPrivateViewsServer) + }) + resp, err = s.trDNSPrivateViewsServer.Do(req) + case "DNSPrivateZonesClient": + initServer(&s.trMu, &s.trDNSPrivateZonesServer, func() *DNSPrivateZonesServerTransport { + return NewDNSPrivateZonesServerTransport(&s.srv.DNSPrivateZonesServer) + }) + resp, err = s.trDNSPrivateZonesServer.Do(req) + case "DbNodesClient": + initServer(&s.trMu, &s.trDbNodesServer, func() *DbNodesServerTransport { return NewDbNodesServerTransport(&s.srv.DbNodesServer) }) + resp, err = s.trDbNodesServer.Do(req) + case "DbServersClient": + initServer(&s.trMu, &s.trDbServersServer, func() *DbServersServerTransport { return NewDbServersServerTransport(&s.srv.DbServersServer) }) + resp, err = s.trDbServersServer.Do(req) + case "DbSystemShapesClient": + initServer(&s.trMu, &s.trDbSystemShapesServer, func() *DbSystemShapesServerTransport { + return NewDbSystemShapesServerTransport(&s.srv.DbSystemShapesServer) + }) + resp, err = s.trDbSystemShapesServer.Do(req) + case "DbSystemsClient": + initServer(&s.trMu, &s.trDbSystemsServer, func() *DbSystemsServerTransport { return NewDbSystemsServerTransport(&s.srv.DbSystemsServer) }) + resp, err = s.trDbSystemsServer.Do(req) + case "DbVersionsClient": + initServer(&s.trMu, &s.trDbVersionsServer, func() *DbVersionsServerTransport { return NewDbVersionsServerTransport(&s.srv.DbVersionsServer) }) + resp, err = s.trDbVersionsServer.Do(req) + case "ExadbVMClustersClient": + initServer(&s.trMu, &s.trExadbVMClustersServer, func() *ExadbVMClustersServerTransport { + return NewExadbVMClustersServerTransport(&s.srv.ExadbVMClustersServer) + }) + resp, err = s.trExadbVMClustersServer.Do(req) + case "ExascaleDbNodesClient": + initServer(&s.trMu, &s.trExascaleDbNodesServer, func() *ExascaleDbNodesServerTransport { + return NewExascaleDbNodesServerTransport(&s.srv.ExascaleDbNodesServer) + }) + resp, err = s.trExascaleDbNodesServer.Do(req) + case "ExascaleDbStorageVaultsClient": + initServer(&s.trMu, &s.trExascaleDbStorageVaultsServer, func() *ExascaleDbStorageVaultsServerTransport { + return NewExascaleDbStorageVaultsServerTransport(&s.srv.ExascaleDbStorageVaultsServer) + }) + resp, err = s.trExascaleDbStorageVaultsServer.Do(req) + case "FlexComponentsClient": + initServer(&s.trMu, &s.trFlexComponentsServer, func() *FlexComponentsServerTransport { + return NewFlexComponentsServerTransport(&s.srv.FlexComponentsServer) + }) + resp, err = s.trFlexComponentsServer.Do(req) + case "GiMinorVersionsClient": + initServer(&s.trMu, &s.trGiMinorVersionsServer, func() *GiMinorVersionsServerTransport { + return NewGiMinorVersionsServerTransport(&s.srv.GiMinorVersionsServer) + }) + resp, err = s.trGiMinorVersionsServer.Do(req) + case "GiVersionsClient": + initServer(&s.trMu, &s.trGiVersionsServer, func() *GiVersionsServerTransport { return NewGiVersionsServerTransport(&s.srv.GiVersionsServer) }) + resp, err = s.trGiVersionsServer.Do(req) + case "NetworkAnchorsClient": + initServer(&s.trMu, &s.trNetworkAnchorsServer, func() *NetworkAnchorsServerTransport { + return NewNetworkAnchorsServerTransport(&s.srv.NetworkAnchorsServer) + }) + resp, err = s.trNetworkAnchorsServer.Do(req) + case "OperationsClient": + initServer(&s.trMu, &s.trOperationsServer, func() *OperationsServerTransport { return NewOperationsServerTransport(&s.srv.OperationsServer) }) + resp, err = s.trOperationsServer.Do(req) + case "OracleSubscriptionsClient": + initServer(&s.trMu, &s.trOracleSubscriptionsServer, func() *OracleSubscriptionsServerTransport { + return NewOracleSubscriptionsServerTransport(&s.srv.OracleSubscriptionsServer) + }) + resp, err = s.trOracleSubscriptionsServer.Do(req) + case "ResourceAnchorsClient": + initServer(&s.trMu, &s.trResourceAnchorsServer, func() *ResourceAnchorsServerTransport { + return NewResourceAnchorsServerTransport(&s.srv.ResourceAnchorsServer) + }) + resp, err = s.trResourceAnchorsServer.Do(req) + case "SystemVersionsClient": + initServer(&s.trMu, &s.trSystemVersionsServer, func() *SystemVersionsServerTransport { + return NewSystemVersionsServerTransport(&s.srv.SystemVersionsServer) + }) + resp, err = s.trSystemVersionsServer.Do(req) + case "VirtualNetworkAddressesClient": + initServer(&s.trMu, &s.trVirtualNetworkAddressesServer, func() *VirtualNetworkAddressesServerTransport { + return NewVirtualNetworkAddressesServerTransport(&s.srv.VirtualNetworkAddressesServer) + }) + resp, err = s.trVirtualNetworkAddressesServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} diff --git a/test/local/armoracledatabase/fake/zz_systemversions_server.go b/test/local/armoracledatabase/fake/zz_systemversions_server.go new file mode 100644 index 000000000000..0ab47fdae065 --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_systemversions_server.go @@ -0,0 +1,165 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armoracledatabase/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// SystemVersionsServer is a fake server for instances of the armoracledatabase.SystemVersionsClient type. +type SystemVersionsServer struct { + // Get is the fake for method SystemVersionsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, location string, systemversionname string, options *armoracledatabase.SystemVersionsClientGetOptions) (resp azfake.Responder[armoracledatabase.SystemVersionsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByLocationPager is the fake for method SystemVersionsClient.NewListByLocationPager + // HTTP status codes to indicate success: http.StatusOK + NewListByLocationPager func(location string, options *armoracledatabase.SystemVersionsClientListByLocationOptions) (resp azfake.PagerResponder[armoracledatabase.SystemVersionsClientListByLocationResponse]) +} + +// NewSystemVersionsServerTransport creates a new instance of SystemVersionsServerTransport with the provided implementation. +// The returned SystemVersionsServerTransport instance is connected to an instance of armoracledatabase.SystemVersionsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSystemVersionsServerTransport(srv *SystemVersionsServer) *SystemVersionsServerTransport { + return &SystemVersionsServerTransport{ + srv: srv, + newListByLocationPager: newTracker[azfake.PagerResponder[armoracledatabase.SystemVersionsClientListByLocationResponse]](), + } +} + +// SystemVersionsServerTransport connects instances of armoracledatabase.SystemVersionsClient to instances of SystemVersionsServer. +// Don't use this type directly, use NewSystemVersionsServerTransport instead. +type SystemVersionsServerTransport struct { + srv *SystemVersionsServer + newListByLocationPager *tracker[azfake.PagerResponder[armoracledatabase.SystemVersionsClientListByLocationResponse]] +} + +// Do implements the policy.Transporter interface for SystemVersionsServerTransport. +func (s *SystemVersionsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *SystemVersionsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if systemVersionsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = systemVersionsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SystemVersionsClient.Get": + res.resp, res.err = s.dispatchGet(req) + case "SystemVersionsClient.NewListByLocationPager": + res.resp, res.err = s.dispatchNewListByLocationPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *SystemVersionsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if s.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/systemVersions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + systemversionnameParam, err := url.PathUnescape(matches[regex.SubexpIndex("systemversionname")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Get(req.Context(), locationParam, systemversionnameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).SystemVersion, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SystemVersionsServerTransport) dispatchNewListByLocationPager(req *http.Request) (*http.Response, error) { + if s.srv.NewListByLocationPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByLocationPager not implemented")} + } + newListByLocationPager := s.newListByLocationPager.get(req) + if newListByLocationPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/locations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/systemVersions` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + locationParam, err := url.PathUnescape(matches[regex.SubexpIndex("location")]) + if err != nil { + return nil, err + } + resp := s.srv.NewListByLocationPager(locationParam, nil) + newListByLocationPager = &resp + s.newListByLocationPager.add(req, newListByLocationPager) + server.PagerResponderInjectNextLinks(newListByLocationPager, req, func(page *armoracledatabase.SystemVersionsClientListByLocationResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByLocationPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + s.newListByLocationPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByLocationPager) { + s.newListByLocationPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SystemVersionsServerTransport +var systemVersionsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armoracledatabase/fake/zz_virtualnetworkaddresses_server.go b/test/local/armoracledatabase/fake/zz_virtualnetworkaddresses_server.go new file mode 100644 index 000000000000..d5e50829569b --- /dev/null +++ b/test/local/armoracledatabase/fake/zz_virtualnetworkaddresses_server.go @@ -0,0 +1,289 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armoracledatabase/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// VirtualNetworkAddressesServer is a fake server for instances of the armoracledatabase.VirtualNetworkAddressesClient type. +type VirtualNetworkAddressesServer struct { + // BeginCreateOrUpdate is the fake for method VirtualNetworkAddressesClient.BeginCreateOrUpdate + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginCreateOrUpdate func(ctx context.Context, resourceGroupName string, cloudvmclustername string, virtualnetworkaddressname string, resource armoracledatabase.VirtualNetworkAddress, options *armoracledatabase.VirtualNetworkAddressesClientBeginCreateOrUpdateOptions) (resp azfake.PollerResponder[armoracledatabase.VirtualNetworkAddressesClientCreateOrUpdateResponse], errResp azfake.ErrorResponder) + + // BeginDelete is the fake for method VirtualNetworkAddressesClient.BeginDelete + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted, http.StatusNoContent + BeginDelete func(ctx context.Context, resourceGroupName string, cloudvmclustername string, virtualnetworkaddressname string, options *armoracledatabase.VirtualNetworkAddressesClientBeginDeleteOptions) (resp azfake.PollerResponder[armoracledatabase.VirtualNetworkAddressesClientDeleteResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method VirtualNetworkAddressesClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, cloudvmclustername string, virtualnetworkaddressname string, options *armoracledatabase.VirtualNetworkAddressesClientGetOptions) (resp azfake.Responder[armoracledatabase.VirtualNetworkAddressesClientGetResponse], errResp azfake.ErrorResponder) + + // NewListByCloudVMClusterPager is the fake for method VirtualNetworkAddressesClient.NewListByCloudVMClusterPager + // HTTP status codes to indicate success: http.StatusOK + NewListByCloudVMClusterPager func(resourceGroupName string, cloudvmclustername string, options *armoracledatabase.VirtualNetworkAddressesClientListByCloudVMClusterOptions) (resp azfake.PagerResponder[armoracledatabase.VirtualNetworkAddressesClientListByCloudVMClusterResponse]) +} + +// NewVirtualNetworkAddressesServerTransport creates a new instance of VirtualNetworkAddressesServerTransport with the provided implementation. +// The returned VirtualNetworkAddressesServerTransport instance is connected to an instance of armoracledatabase.VirtualNetworkAddressesClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewVirtualNetworkAddressesServerTransport(srv *VirtualNetworkAddressesServer) *VirtualNetworkAddressesServerTransport { + return &VirtualNetworkAddressesServerTransport{ + srv: srv, + beginCreateOrUpdate: newTracker[azfake.PollerResponder[armoracledatabase.VirtualNetworkAddressesClientCreateOrUpdateResponse]](), + beginDelete: newTracker[azfake.PollerResponder[armoracledatabase.VirtualNetworkAddressesClientDeleteResponse]](), + newListByCloudVMClusterPager: newTracker[azfake.PagerResponder[armoracledatabase.VirtualNetworkAddressesClientListByCloudVMClusterResponse]](), + } +} + +// VirtualNetworkAddressesServerTransport connects instances of armoracledatabase.VirtualNetworkAddressesClient to instances of VirtualNetworkAddressesServer. +// Don't use this type directly, use NewVirtualNetworkAddressesServerTransport instead. +type VirtualNetworkAddressesServerTransport struct { + srv *VirtualNetworkAddressesServer + beginCreateOrUpdate *tracker[azfake.PollerResponder[armoracledatabase.VirtualNetworkAddressesClientCreateOrUpdateResponse]] + beginDelete *tracker[azfake.PollerResponder[armoracledatabase.VirtualNetworkAddressesClientDeleteResponse]] + newListByCloudVMClusterPager *tracker[azfake.PagerResponder[armoracledatabase.VirtualNetworkAddressesClientListByCloudVMClusterResponse]] +} + +// Do implements the policy.Transporter interface for VirtualNetworkAddressesServerTransport. +func (v *VirtualNetworkAddressesServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return v.dispatchToMethodFake(req, method) +} + +func (v *VirtualNetworkAddressesServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if virtualNetworkAddressesServerTransportInterceptor != nil { + res.resp, res.err, intercepted = virtualNetworkAddressesServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "VirtualNetworkAddressesClient.BeginCreateOrUpdate": + res.resp, res.err = v.dispatchBeginCreateOrUpdate(req) + case "VirtualNetworkAddressesClient.BeginDelete": + res.resp, res.err = v.dispatchBeginDelete(req) + case "VirtualNetworkAddressesClient.Get": + res.resp, res.err = v.dispatchGet(req) + case "VirtualNetworkAddressesClient.NewListByCloudVMClusterPager": + res.resp, res.err = v.dispatchNewListByCloudVMClusterPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (v *VirtualNetworkAddressesServerTransport) dispatchBeginCreateOrUpdate(req *http.Request) (*http.Response, error) { + if v.srv.BeginCreateOrUpdate == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginCreateOrUpdate not implemented")} + } + beginCreateOrUpdate := v.beginCreateOrUpdate.get(req) + if beginCreateOrUpdate == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudVmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/virtualNetworkAddresses/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armoracledatabase.VirtualNetworkAddress](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudvmclusternameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudvmclustername")]) + if err != nil { + return nil, err + } + virtualnetworkaddressnameParam, err := url.PathUnescape(matches[regex.SubexpIndex("virtualnetworkaddressname")]) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.BeginCreateOrUpdate(req.Context(), resourceGroupNameParam, cloudvmclusternameParam, virtualnetworkaddressnameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginCreateOrUpdate = &respr + v.beginCreateOrUpdate.add(req, beginCreateOrUpdate) + } + + resp, err := server.PollerResponderNext(beginCreateOrUpdate, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + v.beginCreateOrUpdate.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginCreateOrUpdate) { + v.beginCreateOrUpdate.remove(req) + } + + return resp, nil +} + +func (v *VirtualNetworkAddressesServerTransport) dispatchBeginDelete(req *http.Request) (*http.Response, error) { + if v.srv.BeginDelete == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginDelete not implemented")} + } + beginDelete := v.beginDelete.get(req) + if beginDelete == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudVmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/virtualNetworkAddresses/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudvmclusternameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudvmclustername")]) + if err != nil { + return nil, err + } + virtualnetworkaddressnameParam, err := url.PathUnescape(matches[regex.SubexpIndex("virtualnetworkaddressname")]) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.BeginDelete(req.Context(), resourceGroupNameParam, cloudvmclusternameParam, virtualnetworkaddressnameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginDelete = &respr + v.beginDelete.add(req, beginDelete) + } + + resp, err := server.PollerResponderNext(beginDelete, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted, http.StatusNoContent}, resp.StatusCode) { + v.beginDelete.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted, http.StatusNoContent", resp.StatusCode)} + } + if !server.PollerResponderMore(beginDelete) { + v.beginDelete.remove(req) + } + + return resp, nil +} + +func (v *VirtualNetworkAddressesServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if v.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudVmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/virtualNetworkAddresses/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 5 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudvmclusternameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudvmclustername")]) + if err != nil { + return nil, err + } + virtualnetworkaddressnameParam, err := url.PathUnescape(matches[regex.SubexpIndex("virtualnetworkaddressname")]) + if err != nil { + return nil, err + } + respr, errRespr := v.srv.Get(req.Context(), resourceGroupNameParam, cloudvmclusternameParam, virtualnetworkaddressnameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).VirtualNetworkAddress, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (v *VirtualNetworkAddressesServerTransport) dispatchNewListByCloudVMClusterPager(req *http.Request) (*http.Response, error) { + if v.srv.NewListByCloudVMClusterPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListByCloudVMClusterPager not implemented")} + } + newListByCloudVMClusterPager := v.newListByCloudVMClusterPager.get(req) + if newListByCloudVMClusterPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Oracle\.Database/cloudVmClusters/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/virtualNetworkAddresses` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + cloudvmclusternameParam, err := url.PathUnescape(matches[regex.SubexpIndex("cloudvmclustername")]) + if err != nil { + return nil, err + } + resp := v.srv.NewListByCloudVMClusterPager(resourceGroupNameParam, cloudvmclusternameParam, nil) + newListByCloudVMClusterPager = &resp + v.newListByCloudVMClusterPager.add(req, newListByCloudVMClusterPager) + server.PagerResponderInjectNextLinks(newListByCloudVMClusterPager, req, func(page *armoracledatabase.VirtualNetworkAddressesClientListByCloudVMClusterResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListByCloudVMClusterPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + v.newListByCloudVMClusterPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListByCloudVMClusterPager) { + v.newListByCloudVMClusterPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to VirtualNetworkAddressesServerTransport +var virtualNetworkAddressesServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armoracledatabase/go.mod b/test/local/armoracledatabase/go.mod new file mode 100644 index 000000000000..725d6d49821e --- /dev/null +++ b/test/local/armoracledatabase/go.mod @@ -0,0 +1,11 @@ +module armoracledatabase/v2 + +go 1.25.0 + +require github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect +) diff --git a/test/local/armoracledatabase/go.sum b/test/local/armoracledatabase/go.sum new file mode 100644 index 000000000000..3fdb64caf441 --- /dev/null +++ b/test/local/armoracledatabase/go.sum @@ -0,0 +1,16 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/local/armoracledatabase/testdata/_metadata.json b/test/local/armoracledatabase/testdata/_metadata.json new file mode 100644 index 000000000000..39bb6a784f2e --- /dev/null +++ b/test/local/armoracledatabase/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Oracle.Database": "2025-09-01" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/local/armoracledatabase/zz_autonomousdatabasebackups_client.go b/test/local/armoracledatabase/zz_autonomousdatabasebackups_client.go new file mode 100644 index 000000000000..067a48e75215 --- /dev/null +++ b/test/local/armoracledatabase/zz_autonomousdatabasebackups_client.go @@ -0,0 +1,413 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// AutonomousDatabaseBackupsClient contains the methods for the AutonomousDatabaseBackups group. +// Don't use this type directly, use NewAutonomousDatabaseBackupsClient() instead. +// +// Generated from API version 2025-09-01 +type AutonomousDatabaseBackupsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAutonomousDatabaseBackupsClient creates a new instance of AutonomousDatabaseBackupsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewAutonomousDatabaseBackupsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AutonomousDatabaseBackupsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AutonomousDatabaseBackupsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create a AutonomousDatabaseBackup +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - autonomousdatabasename - The database name. +// - adbbackupid - AutonomousDatabaseBackup id +// - resource - Resource create parameters. +// - options - AutonomousDatabaseBackupsClientBeginCreateOrUpdateOptions contains the optional parameters for the AutonomousDatabaseBackupsClient.BeginCreateOrUpdate +// method. +func (client *AutonomousDatabaseBackupsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, autonomousdatabasename string, adbbackupid string, resource AutonomousDatabaseBackup, options *AutonomousDatabaseBackupsClientBeginCreateOrUpdateOptions) (*runtime.Poller[AutonomousDatabaseBackupsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, autonomousdatabasename, adbbackupid, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AutonomousDatabaseBackupsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AutonomousDatabaseBackupsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create a AutonomousDatabaseBackup +// If the operation fails it returns an *azcore.ResponseError type. +func (client *AutonomousDatabaseBackupsClient) createOrUpdate(ctx context.Context, resourceGroupName string, autonomousdatabasename string, adbbackupid string, resource AutonomousDatabaseBackup, options *AutonomousDatabaseBackupsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "AutonomousDatabaseBackupsClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, autonomousdatabasename, adbbackupid, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *AutonomousDatabaseBackupsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, autonomousdatabasename string, adbbackupid string, resource AutonomousDatabaseBackup, _ *AutonomousDatabaseBackupsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/autonomousDatabases/{autonomousdatabasename}/autonomousDatabaseBackups/{adbbackupid}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if autonomousdatabasename == "" { + return nil, errors.New("parameter autonomousdatabasename cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{autonomousdatabasename}", url.PathEscape(autonomousdatabasename)) + if adbbackupid == "" { + return nil, errors.New("parameter adbbackupid cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{adbbackupid}", url.PathEscape(adbbackupid)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a AutonomousDatabaseBackup +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - autonomousdatabasename - The database name. +// - adbbackupid - AutonomousDatabaseBackup id +// - options - AutonomousDatabaseBackupsClientBeginDeleteOptions contains the optional parameters for the AutonomousDatabaseBackupsClient.BeginDelete +// method. +func (client *AutonomousDatabaseBackupsClient) BeginDelete(ctx context.Context, resourceGroupName string, autonomousdatabasename string, adbbackupid string, options *AutonomousDatabaseBackupsClientBeginDeleteOptions) (*runtime.Poller[AutonomousDatabaseBackupsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, autonomousdatabasename, adbbackupid, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AutonomousDatabaseBackupsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AutonomousDatabaseBackupsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a AutonomousDatabaseBackup +// If the operation fails it returns an *azcore.ResponseError type. +func (client *AutonomousDatabaseBackupsClient) deleteOperation(ctx context.Context, resourceGroupName string, autonomousdatabasename string, adbbackupid string, options *AutonomousDatabaseBackupsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "AutonomousDatabaseBackupsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, autonomousdatabasename, adbbackupid, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *AutonomousDatabaseBackupsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, autonomousdatabasename string, adbbackupid string, _ *AutonomousDatabaseBackupsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/autonomousDatabases/{autonomousdatabasename}/autonomousDatabaseBackups/{adbbackupid}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if autonomousdatabasename == "" { + return nil, errors.New("parameter autonomousdatabasename cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{autonomousdatabasename}", url.PathEscape(autonomousdatabasename)) + if adbbackupid == "" { + return nil, errors.New("parameter adbbackupid cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{adbbackupid}", url.PathEscape(adbbackupid)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a AutonomousDatabaseBackup +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - autonomousdatabasename - The database name. +// - adbbackupid - AutonomousDatabaseBackup id +// - options - AutonomousDatabaseBackupsClientGetOptions contains the optional parameters for the AutonomousDatabaseBackupsClient.Get +// method. +func (client *AutonomousDatabaseBackupsClient) Get(ctx context.Context, resourceGroupName string, autonomousdatabasename string, adbbackupid string, options *AutonomousDatabaseBackupsClientGetOptions) (AutonomousDatabaseBackupsClientGetResponse, error) { + var err error + const operationName = "AutonomousDatabaseBackupsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, autonomousdatabasename, adbbackupid, options) + if err != nil { + return AutonomousDatabaseBackupsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AutonomousDatabaseBackupsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AutonomousDatabaseBackupsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *AutonomousDatabaseBackupsClient) getCreateRequest(ctx context.Context, resourceGroupName string, autonomousdatabasename string, adbbackupid string, _ *AutonomousDatabaseBackupsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/autonomousDatabases/{autonomousdatabasename}/autonomousDatabaseBackups/{adbbackupid}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if autonomousdatabasename == "" { + return nil, errors.New("parameter autonomousdatabasename cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{autonomousdatabasename}", url.PathEscape(autonomousdatabasename)) + if adbbackupid == "" { + return nil, errors.New("parameter adbbackupid cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{adbbackupid}", url.PathEscape(adbbackupid)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *AutonomousDatabaseBackupsClient) getHandleResponse(resp *http.Response) (AutonomousDatabaseBackupsClientGetResponse, error) { + result := AutonomousDatabaseBackupsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AutonomousDatabaseBackup); err != nil { + return AutonomousDatabaseBackupsClientGetResponse{}, err + } + return result, nil +} + +// NewListByAutonomousDatabasePager - List AutonomousDatabaseBackup resources by AutonomousDatabase +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - autonomousdatabasename - The database name. +// - options - AutonomousDatabaseBackupsClientListByAutonomousDatabaseOptions contains the optional parameters for the AutonomousDatabaseBackupsClient.NewListByAutonomousDatabasePager +// method. +func (client *AutonomousDatabaseBackupsClient) NewListByAutonomousDatabasePager(resourceGroupName string, autonomousdatabasename string, options *AutonomousDatabaseBackupsClientListByAutonomousDatabaseOptions) *runtime.Pager[AutonomousDatabaseBackupsClientListByAutonomousDatabaseResponse] { + return runtime.NewPager(runtime.PagingHandler[AutonomousDatabaseBackupsClientListByAutonomousDatabaseResponse]{ + More: func(page AutonomousDatabaseBackupsClientListByAutonomousDatabaseResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AutonomousDatabaseBackupsClientListByAutonomousDatabaseResponse) (AutonomousDatabaseBackupsClientListByAutonomousDatabaseResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AutonomousDatabaseBackupsClient.NewListByAutonomousDatabasePager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByAutonomousDatabaseCreateRequest(ctx, resourceGroupName, autonomousdatabasename, options) + }, nil) + if err != nil { + return AutonomousDatabaseBackupsClientListByAutonomousDatabaseResponse{}, err + } + return client.listByAutonomousDatabaseHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByAutonomousDatabaseCreateRequest creates the ListByAutonomousDatabase request. +func (client *AutonomousDatabaseBackupsClient) listByAutonomousDatabaseCreateRequest(ctx context.Context, resourceGroupName string, autonomousdatabasename string, _ *AutonomousDatabaseBackupsClientListByAutonomousDatabaseOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/autonomousDatabases/{autonomousdatabasename}/autonomousDatabaseBackups" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if autonomousdatabasename == "" { + return nil, errors.New("parameter autonomousdatabasename cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{autonomousdatabasename}", url.PathEscape(autonomousdatabasename)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByAutonomousDatabaseHandleResponse handles the ListByAutonomousDatabase response. +func (client *AutonomousDatabaseBackupsClient) listByAutonomousDatabaseHandleResponse(resp *http.Response) (AutonomousDatabaseBackupsClientListByAutonomousDatabaseResponse, error) { + result := AutonomousDatabaseBackupsClientListByAutonomousDatabaseResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AutonomousDatabaseBackupListResult); err != nil { + return AutonomousDatabaseBackupsClientListByAutonomousDatabaseResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update a AutonomousDatabaseBackup +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - autonomousdatabasename - The database name. +// - adbbackupid - AutonomousDatabaseBackup id +// - properties - The resource properties to be updated. +// - options - AutonomousDatabaseBackupsClientBeginUpdateOptions contains the optional parameters for the AutonomousDatabaseBackupsClient.BeginUpdate +// method. +func (client *AutonomousDatabaseBackupsClient) BeginUpdate(ctx context.Context, resourceGroupName string, autonomousdatabasename string, adbbackupid string, properties AutonomousDatabaseBackupUpdate, options *AutonomousDatabaseBackupsClientBeginUpdateOptions) (*runtime.Poller[AutonomousDatabaseBackupsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, autonomousdatabasename, adbbackupid, properties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AutonomousDatabaseBackupsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AutonomousDatabaseBackupsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a AutonomousDatabaseBackup +// If the operation fails it returns an *azcore.ResponseError type. +func (client *AutonomousDatabaseBackupsClient) update(ctx context.Context, resourceGroupName string, autonomousdatabasename string, adbbackupid string, properties AutonomousDatabaseBackupUpdate, options *AutonomousDatabaseBackupsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "AutonomousDatabaseBackupsClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, autonomousdatabasename, adbbackupid, properties, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *AutonomousDatabaseBackupsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, autonomousdatabasename string, adbbackupid string, properties AutonomousDatabaseBackupUpdate, _ *AutonomousDatabaseBackupsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/autonomousDatabases/{autonomousdatabasename}/autonomousDatabaseBackups/{adbbackupid}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if autonomousdatabasename == "" { + return nil, errors.New("parameter autonomousdatabasename cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{autonomousdatabasename}", url.PathEscape(autonomousdatabasename)) + if adbbackupid == "" { + return nil, errors.New("parameter adbbackupid cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{adbbackupid}", url.PathEscape(adbbackupid)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armoracledatabase/zz_autonomousdatabasecharactersets_client.go b/test/local/armoracledatabase/zz_autonomousdatabasecharactersets_client.go new file mode 100644 index 000000000000..8bde594eb75c --- /dev/null +++ b/test/local/armoracledatabase/zz_autonomousdatabasecharactersets_client.go @@ -0,0 +1,163 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// AutonomousDatabaseCharacterSetsClient contains the methods for the AutonomousDatabaseCharacterSets group. +// Don't use this type directly, use NewAutonomousDatabaseCharacterSetsClient() instead. +// +// Generated from API version 2025-09-01 +type AutonomousDatabaseCharacterSetsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAutonomousDatabaseCharacterSetsClient creates a new instance of AutonomousDatabaseCharacterSetsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewAutonomousDatabaseCharacterSetsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AutonomousDatabaseCharacterSetsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AutonomousDatabaseCharacterSetsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get a AutonomousDatabaseCharacterSet +// If the operation fails it returns an *azcore.ResponseError type. +// - location - The name of the Azure region. +// - adbscharsetname - AutonomousDatabaseCharacterSet name +// - options - AutonomousDatabaseCharacterSetsClientGetOptions contains the optional parameters for the AutonomousDatabaseCharacterSetsClient.Get +// method. +func (client *AutonomousDatabaseCharacterSetsClient) Get(ctx context.Context, location string, adbscharsetname string, options *AutonomousDatabaseCharacterSetsClientGetOptions) (AutonomousDatabaseCharacterSetsClientGetResponse, error) { + var err error + const operationName = "AutonomousDatabaseCharacterSetsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, location, adbscharsetname, options) + if err != nil { + return AutonomousDatabaseCharacterSetsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AutonomousDatabaseCharacterSetsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AutonomousDatabaseCharacterSetsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *AutonomousDatabaseCharacterSetsClient) getCreateRequest(ctx context.Context, location string, adbscharsetname string, _ *AutonomousDatabaseCharacterSetsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/locations/{location}/autonomousDatabaseCharacterSets/{adbscharsetname}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if adbscharsetname == "" { + return nil, errors.New("parameter adbscharsetname cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{adbscharsetname}", url.PathEscape(adbscharsetname)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *AutonomousDatabaseCharacterSetsClient) getHandleResponse(resp *http.Response) (AutonomousDatabaseCharacterSetsClientGetResponse, error) { + result := AutonomousDatabaseCharacterSetsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AutonomousDatabaseCharacterSet); err != nil { + return AutonomousDatabaseCharacterSetsClientGetResponse{}, err + } + return result, nil +} + +// NewListByLocationPager - List AutonomousDatabaseCharacterSet resources by SubscriptionLocationResource +// - location - The name of the Azure region. +// - options - AutonomousDatabaseCharacterSetsClientListByLocationOptions contains the optional parameters for the AutonomousDatabaseCharacterSetsClient.NewListByLocationPager +// method. +func (client *AutonomousDatabaseCharacterSetsClient) NewListByLocationPager(location string, options *AutonomousDatabaseCharacterSetsClientListByLocationOptions) *runtime.Pager[AutonomousDatabaseCharacterSetsClientListByLocationResponse] { + return runtime.NewPager(runtime.PagingHandler[AutonomousDatabaseCharacterSetsClientListByLocationResponse]{ + More: func(page AutonomousDatabaseCharacterSetsClientListByLocationResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AutonomousDatabaseCharacterSetsClientListByLocationResponse) (AutonomousDatabaseCharacterSetsClientListByLocationResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AutonomousDatabaseCharacterSetsClient.NewListByLocationPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByLocationCreateRequest(ctx, location, options) + }, nil) + if err != nil { + return AutonomousDatabaseCharacterSetsClientListByLocationResponse{}, err + } + return client.listByLocationHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByLocationCreateRequest creates the ListByLocation request. +func (client *AutonomousDatabaseCharacterSetsClient) listByLocationCreateRequest(ctx context.Context, location string, _ *AutonomousDatabaseCharacterSetsClientListByLocationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/locations/{location}/autonomousDatabaseCharacterSets" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByLocationHandleResponse handles the ListByLocation response. +func (client *AutonomousDatabaseCharacterSetsClient) listByLocationHandleResponse(resp *http.Response) (AutonomousDatabaseCharacterSetsClientListByLocationResponse, error) { + result := AutonomousDatabaseCharacterSetsClientListByLocationResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AutonomousDatabaseCharacterSetListResult); err != nil { + return AutonomousDatabaseCharacterSetsClientListByLocationResponse{}, err + } + return result, nil +} diff --git a/test/local/armoracledatabase/zz_autonomousdatabasenationalcharactersets_client.go b/test/local/armoracledatabase/zz_autonomousdatabasenationalcharactersets_client.go new file mode 100644 index 000000000000..364a3f580615 --- /dev/null +++ b/test/local/armoracledatabase/zz_autonomousdatabasenationalcharactersets_client.go @@ -0,0 +1,163 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// AutonomousDatabaseNationalCharacterSetsClient contains the methods for the AutonomousDatabaseNationalCharacterSets group. +// Don't use this type directly, use NewAutonomousDatabaseNationalCharacterSetsClient() instead. +// +// Generated from API version 2025-09-01 +type AutonomousDatabaseNationalCharacterSetsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAutonomousDatabaseNationalCharacterSetsClient creates a new instance of AutonomousDatabaseNationalCharacterSetsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewAutonomousDatabaseNationalCharacterSetsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AutonomousDatabaseNationalCharacterSetsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AutonomousDatabaseNationalCharacterSetsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get a AutonomousDatabaseNationalCharacterSet +// If the operation fails it returns an *azcore.ResponseError type. +// - location - The name of the Azure region. +// - adbsncharsetname - AutonomousDatabaseNationalCharacterSets name +// - options - AutonomousDatabaseNationalCharacterSetsClientGetOptions contains the optional parameters for the AutonomousDatabaseNationalCharacterSetsClient.Get +// method. +func (client *AutonomousDatabaseNationalCharacterSetsClient) Get(ctx context.Context, location string, adbsncharsetname string, options *AutonomousDatabaseNationalCharacterSetsClientGetOptions) (AutonomousDatabaseNationalCharacterSetsClientGetResponse, error) { + var err error + const operationName = "AutonomousDatabaseNationalCharacterSetsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, location, adbsncharsetname, options) + if err != nil { + return AutonomousDatabaseNationalCharacterSetsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AutonomousDatabaseNationalCharacterSetsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AutonomousDatabaseNationalCharacterSetsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *AutonomousDatabaseNationalCharacterSetsClient) getCreateRequest(ctx context.Context, location string, adbsncharsetname string, _ *AutonomousDatabaseNationalCharacterSetsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/locations/{location}/autonomousDatabaseNationalCharacterSets/{adbsncharsetname}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if adbsncharsetname == "" { + return nil, errors.New("parameter adbsncharsetname cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{adbsncharsetname}", url.PathEscape(adbsncharsetname)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *AutonomousDatabaseNationalCharacterSetsClient) getHandleResponse(resp *http.Response) (AutonomousDatabaseNationalCharacterSetsClientGetResponse, error) { + result := AutonomousDatabaseNationalCharacterSetsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AutonomousDatabaseNationalCharacterSet); err != nil { + return AutonomousDatabaseNationalCharacterSetsClientGetResponse{}, err + } + return result, nil +} + +// NewListByLocationPager - List AutonomousDatabaseNationalCharacterSet resources by SubscriptionLocationResource +// - location - The name of the Azure region. +// - options - AutonomousDatabaseNationalCharacterSetsClientListByLocationOptions contains the optional parameters for the AutonomousDatabaseNationalCharacterSetsClient.NewListByLocationPager +// method. +func (client *AutonomousDatabaseNationalCharacterSetsClient) NewListByLocationPager(location string, options *AutonomousDatabaseNationalCharacterSetsClientListByLocationOptions) *runtime.Pager[AutonomousDatabaseNationalCharacterSetsClientListByLocationResponse] { + return runtime.NewPager(runtime.PagingHandler[AutonomousDatabaseNationalCharacterSetsClientListByLocationResponse]{ + More: func(page AutonomousDatabaseNationalCharacterSetsClientListByLocationResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AutonomousDatabaseNationalCharacterSetsClientListByLocationResponse) (AutonomousDatabaseNationalCharacterSetsClientListByLocationResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AutonomousDatabaseNationalCharacterSetsClient.NewListByLocationPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByLocationCreateRequest(ctx, location, options) + }, nil) + if err != nil { + return AutonomousDatabaseNationalCharacterSetsClientListByLocationResponse{}, err + } + return client.listByLocationHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByLocationCreateRequest creates the ListByLocation request. +func (client *AutonomousDatabaseNationalCharacterSetsClient) listByLocationCreateRequest(ctx context.Context, location string, _ *AutonomousDatabaseNationalCharacterSetsClientListByLocationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/locations/{location}/autonomousDatabaseNationalCharacterSets" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByLocationHandleResponse handles the ListByLocation response. +func (client *AutonomousDatabaseNationalCharacterSetsClient) listByLocationHandleResponse(resp *http.Response) (AutonomousDatabaseNationalCharacterSetsClientListByLocationResponse, error) { + result := AutonomousDatabaseNationalCharacterSetsClientListByLocationResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AutonomousDatabaseNationalCharacterSetListResult); err != nil { + return AutonomousDatabaseNationalCharacterSetsClientListByLocationResponse{}, err + } + return result, nil +} diff --git a/test/local/armoracledatabase/zz_autonomousdatabases_client.go b/test/local/armoracledatabase/zz_autonomousdatabases_client.go new file mode 100644 index 000000000000..86c89bb2901e --- /dev/null +++ b/test/local/armoracledatabase/zz_autonomousdatabases_client.go @@ -0,0 +1,965 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// AutonomousDatabasesClient contains the methods for the AutonomousDatabases group. +// Don't use this type directly, use NewAutonomousDatabasesClient() instead. +// +// Generated from API version 2025-09-01 +type AutonomousDatabasesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAutonomousDatabasesClient creates a new instance of AutonomousDatabasesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewAutonomousDatabasesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AutonomousDatabasesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AutonomousDatabasesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginAction - Perform Lifecycle Management Action on Autonomous Database +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - autonomousdatabasename - The database name. +// - body - The content of the action request +// - options - AutonomousDatabasesClientBeginActionOptions contains the optional parameters for the AutonomousDatabasesClient.BeginAction +// method. +func (client *AutonomousDatabasesClient) BeginAction(ctx context.Context, resourceGroupName string, autonomousdatabasename string, body AutonomousDatabaseLifecycleAction, options *AutonomousDatabasesClientBeginActionOptions) (*runtime.Poller[AutonomousDatabasesClientActionResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.action(ctx, resourceGroupName, autonomousdatabasename, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AutonomousDatabasesClientActionResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AutonomousDatabasesClientActionResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Action - Perform Lifecycle Management Action on Autonomous Database +// If the operation fails it returns an *azcore.ResponseError type. +func (client *AutonomousDatabasesClient) action(ctx context.Context, resourceGroupName string, autonomousdatabasename string, body AutonomousDatabaseLifecycleAction, options *AutonomousDatabasesClientBeginActionOptions) (*http.Response, error) { + var err error + const operationName = "AutonomousDatabasesClient.BeginAction" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.actionCreateRequest(ctx, resourceGroupName, autonomousdatabasename, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// actionCreateRequest creates the Action request. +func (client *AutonomousDatabasesClient) actionCreateRequest(ctx context.Context, resourceGroupName string, autonomousdatabasename string, body AutonomousDatabaseLifecycleAction, _ *AutonomousDatabasesClientBeginActionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/autonomousDatabases/{autonomousdatabasename}/action" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if autonomousdatabasename == "" { + return nil, errors.New("parameter autonomousdatabasename cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{autonomousdatabasename}", url.PathEscape(autonomousdatabasename)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// BeginChangeDisasterRecoveryConfiguration - Perform ChangeDisasterRecoveryConfiguration action on Autonomous Database +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - autonomousdatabasename - The database name. +// - body - The content of the action request +// - options - AutonomousDatabasesClientBeginChangeDisasterRecoveryConfigurationOptions contains the optional parameters for +// the AutonomousDatabasesClient.BeginChangeDisasterRecoveryConfiguration method. +func (client *AutonomousDatabasesClient) BeginChangeDisasterRecoveryConfiguration(ctx context.Context, resourceGroupName string, autonomousdatabasename string, body DisasterRecoveryConfigurationDetails, options *AutonomousDatabasesClientBeginChangeDisasterRecoveryConfigurationOptions) (*runtime.Poller[AutonomousDatabasesClientChangeDisasterRecoveryConfigurationResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.changeDisasterRecoveryConfiguration(ctx, resourceGroupName, autonomousdatabasename, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AutonomousDatabasesClientChangeDisasterRecoveryConfigurationResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AutonomousDatabasesClientChangeDisasterRecoveryConfigurationResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ChangeDisasterRecoveryConfiguration - Perform ChangeDisasterRecoveryConfiguration action on Autonomous Database +// If the operation fails it returns an *azcore.ResponseError type. +func (client *AutonomousDatabasesClient) changeDisasterRecoveryConfiguration(ctx context.Context, resourceGroupName string, autonomousdatabasename string, body DisasterRecoveryConfigurationDetails, options *AutonomousDatabasesClientBeginChangeDisasterRecoveryConfigurationOptions) (*http.Response, error) { + var err error + const operationName = "AutonomousDatabasesClient.BeginChangeDisasterRecoveryConfiguration" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.changeDisasterRecoveryConfigurationCreateRequest(ctx, resourceGroupName, autonomousdatabasename, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// changeDisasterRecoveryConfigurationCreateRequest creates the ChangeDisasterRecoveryConfiguration request. +func (client *AutonomousDatabasesClient) changeDisasterRecoveryConfigurationCreateRequest(ctx context.Context, resourceGroupName string, autonomousdatabasename string, body DisasterRecoveryConfigurationDetails, _ *AutonomousDatabasesClientBeginChangeDisasterRecoveryConfigurationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/autonomousDatabases/{autonomousdatabasename}/changeDisasterRecoveryConfiguration" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if autonomousdatabasename == "" { + return nil, errors.New("parameter autonomousdatabasename cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{autonomousdatabasename}", url.PathEscape(autonomousdatabasename)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// BeginCreateOrUpdate - Create a AutonomousDatabase +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - autonomousdatabasename - The database name. +// - resource - Resource create parameters. +// - options - AutonomousDatabasesClientBeginCreateOrUpdateOptions contains the optional parameters for the AutonomousDatabasesClient.BeginCreateOrUpdate +// method. +func (client *AutonomousDatabasesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, autonomousdatabasename string, resource AutonomousDatabase, options *AutonomousDatabasesClientBeginCreateOrUpdateOptions) (*runtime.Poller[AutonomousDatabasesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, autonomousdatabasename, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AutonomousDatabasesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AutonomousDatabasesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create a AutonomousDatabase +// If the operation fails it returns an *azcore.ResponseError type. +func (client *AutonomousDatabasesClient) createOrUpdate(ctx context.Context, resourceGroupName string, autonomousdatabasename string, resource AutonomousDatabase, options *AutonomousDatabasesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "AutonomousDatabasesClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, autonomousdatabasename, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *AutonomousDatabasesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, autonomousdatabasename string, resource AutonomousDatabase, _ *AutonomousDatabasesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/autonomousDatabases/{autonomousdatabasename}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if autonomousdatabasename == "" { + return nil, errors.New("parameter autonomousdatabasename cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{autonomousdatabasename}", url.PathEscape(autonomousdatabasename)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a AutonomousDatabase +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - autonomousdatabasename - The database name. +// - options - AutonomousDatabasesClientBeginDeleteOptions contains the optional parameters for the AutonomousDatabasesClient.BeginDelete +// method. +func (client *AutonomousDatabasesClient) BeginDelete(ctx context.Context, resourceGroupName string, autonomousdatabasename string, options *AutonomousDatabasesClientBeginDeleteOptions) (*runtime.Poller[AutonomousDatabasesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, autonomousdatabasename, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AutonomousDatabasesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AutonomousDatabasesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a AutonomousDatabase +// If the operation fails it returns an *azcore.ResponseError type. +func (client *AutonomousDatabasesClient) deleteOperation(ctx context.Context, resourceGroupName string, autonomousdatabasename string, options *AutonomousDatabasesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "AutonomousDatabasesClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, autonomousdatabasename, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *AutonomousDatabasesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, autonomousdatabasename string, _ *AutonomousDatabasesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/autonomousDatabases/{autonomousdatabasename}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if autonomousdatabasename == "" { + return nil, errors.New("parameter autonomousdatabasename cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{autonomousdatabasename}", url.PathEscape(autonomousdatabasename)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// BeginFailover - Perform failover action on Autonomous Database +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - autonomousdatabasename - The database name. +// - body - The content of the action request +// - options - AutonomousDatabasesClientBeginFailoverOptions contains the optional parameters for the AutonomousDatabasesClient.BeginFailover +// method. +func (client *AutonomousDatabasesClient) BeginFailover(ctx context.Context, resourceGroupName string, autonomousdatabasename string, body PeerDbDetails, options *AutonomousDatabasesClientBeginFailoverOptions) (*runtime.Poller[AutonomousDatabasesClientFailoverResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.failover(ctx, resourceGroupName, autonomousdatabasename, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AutonomousDatabasesClientFailoverResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AutonomousDatabasesClientFailoverResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Failover - Perform failover action on Autonomous Database +// If the operation fails it returns an *azcore.ResponseError type. +func (client *AutonomousDatabasesClient) failover(ctx context.Context, resourceGroupName string, autonomousdatabasename string, body PeerDbDetails, options *AutonomousDatabasesClientBeginFailoverOptions) (*http.Response, error) { + var err error + const operationName = "AutonomousDatabasesClient.BeginFailover" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.failoverCreateRequest(ctx, resourceGroupName, autonomousdatabasename, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// failoverCreateRequest creates the Failover request. +func (client *AutonomousDatabasesClient) failoverCreateRequest(ctx context.Context, resourceGroupName string, autonomousdatabasename string, body PeerDbDetails, _ *AutonomousDatabasesClientBeginFailoverOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/autonomousDatabases/{autonomousdatabasename}/failover" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if autonomousdatabasename == "" { + return nil, errors.New("parameter autonomousdatabasename cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{autonomousdatabasename}", url.PathEscape(autonomousdatabasename)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// GenerateWallet - Generate wallet action on Autonomous Database +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - autonomousdatabasename - The database name. +// - body - The content of the action request +// - options - AutonomousDatabasesClientGenerateWalletOptions contains the optional parameters for the AutonomousDatabasesClient.GenerateWallet +// method. +func (client *AutonomousDatabasesClient) GenerateWallet(ctx context.Context, resourceGroupName string, autonomousdatabasename string, body GenerateAutonomousDatabaseWalletDetails, options *AutonomousDatabasesClientGenerateWalletOptions) (AutonomousDatabasesClientGenerateWalletResponse, error) { + var err error + const operationName = "AutonomousDatabasesClient.GenerateWallet" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.generateWalletCreateRequest(ctx, resourceGroupName, autonomousdatabasename, body, options) + if err != nil { + return AutonomousDatabasesClientGenerateWalletResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AutonomousDatabasesClientGenerateWalletResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AutonomousDatabasesClientGenerateWalletResponse{}, err + } + resp, err := client.generateWalletHandleResponse(httpResp) + return resp, err +} + +// generateWalletCreateRequest creates the GenerateWallet request. +func (client *AutonomousDatabasesClient) generateWalletCreateRequest(ctx context.Context, resourceGroupName string, autonomousdatabasename string, body GenerateAutonomousDatabaseWalletDetails, _ *AutonomousDatabasesClientGenerateWalletOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/autonomousDatabases/{autonomousdatabasename}/generateWallet" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if autonomousdatabasename == "" { + return nil, errors.New("parameter autonomousdatabasename cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{autonomousdatabasename}", url.PathEscape(autonomousdatabasename)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// generateWalletHandleResponse handles the GenerateWallet response. +func (client *AutonomousDatabasesClient) generateWalletHandleResponse(resp *http.Response) (AutonomousDatabasesClientGenerateWalletResponse, error) { + result := AutonomousDatabasesClientGenerateWalletResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AutonomousDatabaseWalletFile); err != nil { + return AutonomousDatabasesClientGenerateWalletResponse{}, err + } + return result, nil +} + +// Get - Get a AutonomousDatabase +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - autonomousdatabasename - The database name. +// - options - AutonomousDatabasesClientGetOptions contains the optional parameters for the AutonomousDatabasesClient.Get method. +func (client *AutonomousDatabasesClient) Get(ctx context.Context, resourceGroupName string, autonomousdatabasename string, options *AutonomousDatabasesClientGetOptions) (AutonomousDatabasesClientGetResponse, error) { + var err error + const operationName = "AutonomousDatabasesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, autonomousdatabasename, options) + if err != nil { + return AutonomousDatabasesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AutonomousDatabasesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AutonomousDatabasesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *AutonomousDatabasesClient) getCreateRequest(ctx context.Context, resourceGroupName string, autonomousdatabasename string, _ *AutonomousDatabasesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/autonomousDatabases/{autonomousdatabasename}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if autonomousdatabasename == "" { + return nil, errors.New("parameter autonomousdatabasename cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{autonomousdatabasename}", url.PathEscape(autonomousdatabasename)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *AutonomousDatabasesClient) getHandleResponse(resp *http.Response) (AutonomousDatabasesClientGetResponse, error) { + result := AutonomousDatabasesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AutonomousDatabase); err != nil { + return AutonomousDatabasesClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - List AutonomousDatabase resources by resource group +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - AutonomousDatabasesClientListByResourceGroupOptions contains the optional parameters for the AutonomousDatabasesClient.NewListByResourceGroupPager +// method. +func (client *AutonomousDatabasesClient) NewListByResourceGroupPager(resourceGroupName string, options *AutonomousDatabasesClientListByResourceGroupOptions) *runtime.Pager[AutonomousDatabasesClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[AutonomousDatabasesClientListByResourceGroupResponse]{ + More: func(page AutonomousDatabasesClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AutonomousDatabasesClientListByResourceGroupResponse) (AutonomousDatabasesClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AutonomousDatabasesClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return AutonomousDatabasesClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *AutonomousDatabasesClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *AutonomousDatabasesClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/autonomousDatabases" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *AutonomousDatabasesClient) listByResourceGroupHandleResponse(resp *http.Response) (AutonomousDatabasesClientListByResourceGroupResponse, error) { + result := AutonomousDatabasesClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AutonomousDatabaseListResult); err != nil { + return AutonomousDatabasesClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - List AutonomousDatabase resources by subscription ID +// - options - AutonomousDatabasesClientListBySubscriptionOptions contains the optional parameters for the AutonomousDatabasesClient.NewListBySubscriptionPager +// method. +func (client *AutonomousDatabasesClient) NewListBySubscriptionPager(options *AutonomousDatabasesClientListBySubscriptionOptions) *runtime.Pager[AutonomousDatabasesClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[AutonomousDatabasesClientListBySubscriptionResponse]{ + More: func(page AutonomousDatabasesClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AutonomousDatabasesClientListBySubscriptionResponse) (AutonomousDatabasesClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AutonomousDatabasesClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return AutonomousDatabasesClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *AutonomousDatabasesClient) listBySubscriptionCreateRequest(ctx context.Context, _ *AutonomousDatabasesClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/autonomousDatabases" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *AutonomousDatabasesClient) listBySubscriptionHandleResponse(resp *http.Response) (AutonomousDatabasesClientListBySubscriptionResponse, error) { + result := AutonomousDatabasesClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AutonomousDatabaseListResult); err != nil { + return AutonomousDatabasesClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// BeginRestore - Restores an Autonomous Database based on the provided request parameters. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - autonomousdatabasename - The database name. +// - body - The content of the action request +// - options - AutonomousDatabasesClientBeginRestoreOptions contains the optional parameters for the AutonomousDatabasesClient.BeginRestore +// method. +func (client *AutonomousDatabasesClient) BeginRestore(ctx context.Context, resourceGroupName string, autonomousdatabasename string, body RestoreAutonomousDatabaseDetails, options *AutonomousDatabasesClientBeginRestoreOptions) (*runtime.Poller[AutonomousDatabasesClientRestoreResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.restore(ctx, resourceGroupName, autonomousdatabasename, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AutonomousDatabasesClientRestoreResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AutonomousDatabasesClientRestoreResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Restore - Restores an Autonomous Database based on the provided request parameters. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *AutonomousDatabasesClient) restore(ctx context.Context, resourceGroupName string, autonomousdatabasename string, body RestoreAutonomousDatabaseDetails, options *AutonomousDatabasesClientBeginRestoreOptions) (*http.Response, error) { + var err error + const operationName = "AutonomousDatabasesClient.BeginRestore" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.restoreCreateRequest(ctx, resourceGroupName, autonomousdatabasename, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// restoreCreateRequest creates the Restore request. +func (client *AutonomousDatabasesClient) restoreCreateRequest(ctx context.Context, resourceGroupName string, autonomousdatabasename string, body RestoreAutonomousDatabaseDetails, _ *AutonomousDatabasesClientBeginRestoreOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/autonomousDatabases/{autonomousdatabasename}/restore" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if autonomousdatabasename == "" { + return nil, errors.New("parameter autonomousdatabasename cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{autonomousdatabasename}", url.PathEscape(autonomousdatabasename)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// BeginShrink - This operation shrinks the current allocated storage down to the current actual used data storage. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - autonomousdatabasename - The database name. +// - options - AutonomousDatabasesClientBeginShrinkOptions contains the optional parameters for the AutonomousDatabasesClient.BeginShrink +// method. +func (client *AutonomousDatabasesClient) BeginShrink(ctx context.Context, resourceGroupName string, autonomousdatabasename string, options *AutonomousDatabasesClientBeginShrinkOptions) (*runtime.Poller[AutonomousDatabasesClientShrinkResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.shrink(ctx, resourceGroupName, autonomousdatabasename, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AutonomousDatabasesClientShrinkResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AutonomousDatabasesClientShrinkResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Shrink - This operation shrinks the current allocated storage down to the current actual used data storage. +// If the operation fails it returns an *azcore.ResponseError type. +func (client *AutonomousDatabasesClient) shrink(ctx context.Context, resourceGroupName string, autonomousdatabasename string, options *AutonomousDatabasesClientBeginShrinkOptions) (*http.Response, error) { + var err error + const operationName = "AutonomousDatabasesClient.BeginShrink" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.shrinkCreateRequest(ctx, resourceGroupName, autonomousdatabasename, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// shrinkCreateRequest creates the Shrink request. +func (client *AutonomousDatabasesClient) shrinkCreateRequest(ctx context.Context, resourceGroupName string, autonomousdatabasename string, _ *AutonomousDatabasesClientBeginShrinkOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/autonomousDatabases/{autonomousdatabasename}/shrink" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if autonomousdatabasename == "" { + return nil, errors.New("parameter autonomousdatabasename cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{autonomousdatabasename}", url.PathEscape(autonomousdatabasename)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginSwitchover - Perform switchover action on Autonomous Database +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - autonomousdatabasename - The database name. +// - body - The content of the action request +// - options - AutonomousDatabasesClientBeginSwitchoverOptions contains the optional parameters for the AutonomousDatabasesClient.BeginSwitchover +// method. +func (client *AutonomousDatabasesClient) BeginSwitchover(ctx context.Context, resourceGroupName string, autonomousdatabasename string, body PeerDbDetails, options *AutonomousDatabasesClientBeginSwitchoverOptions) (*runtime.Poller[AutonomousDatabasesClientSwitchoverResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.switchover(ctx, resourceGroupName, autonomousdatabasename, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AutonomousDatabasesClientSwitchoverResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AutonomousDatabasesClientSwitchoverResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Switchover - Perform switchover action on Autonomous Database +// If the operation fails it returns an *azcore.ResponseError type. +func (client *AutonomousDatabasesClient) switchover(ctx context.Context, resourceGroupName string, autonomousdatabasename string, body PeerDbDetails, options *AutonomousDatabasesClientBeginSwitchoverOptions) (*http.Response, error) { + var err error + const operationName = "AutonomousDatabasesClient.BeginSwitchover" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.switchoverCreateRequest(ctx, resourceGroupName, autonomousdatabasename, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// switchoverCreateRequest creates the Switchover request. +func (client *AutonomousDatabasesClient) switchoverCreateRequest(ctx context.Context, resourceGroupName string, autonomousdatabasename string, body PeerDbDetails, _ *AutonomousDatabasesClientBeginSwitchoverOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/autonomousDatabases/{autonomousdatabasename}/switchover" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if autonomousdatabasename == "" { + return nil, errors.New("parameter autonomousdatabasename cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{autonomousdatabasename}", url.PathEscape(autonomousdatabasename)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// BeginUpdate - Update a AutonomousDatabase +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - autonomousdatabasename - The database name. +// - properties - The resource properties to be updated. +// - options - AutonomousDatabasesClientBeginUpdateOptions contains the optional parameters for the AutonomousDatabasesClient.BeginUpdate +// method. +func (client *AutonomousDatabasesClient) BeginUpdate(ctx context.Context, resourceGroupName string, autonomousdatabasename string, properties AutonomousDatabaseUpdate, options *AutonomousDatabasesClientBeginUpdateOptions) (*runtime.Poller[AutonomousDatabasesClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, autonomousdatabasename, properties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[AutonomousDatabasesClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[AutonomousDatabasesClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a AutonomousDatabase +// If the operation fails it returns an *azcore.ResponseError type. +func (client *AutonomousDatabasesClient) update(ctx context.Context, resourceGroupName string, autonomousdatabasename string, properties AutonomousDatabaseUpdate, options *AutonomousDatabasesClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "AutonomousDatabasesClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, autonomousdatabasename, properties, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *AutonomousDatabasesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, autonomousdatabasename string, properties AutonomousDatabaseUpdate, _ *AutonomousDatabasesClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/autonomousDatabases/{autonomousdatabasename}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if autonomousdatabasename == "" { + return nil, errors.New("parameter autonomousdatabasename cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{autonomousdatabasename}", url.PathEscape(autonomousdatabasename)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armoracledatabase/zz_autonomousdatabaseversions_client.go b/test/local/armoracledatabase/zz_autonomousdatabaseversions_client.go new file mode 100644 index 000000000000..9c0996617d03 --- /dev/null +++ b/test/local/armoracledatabase/zz_autonomousdatabaseversions_client.go @@ -0,0 +1,163 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// AutonomousDatabaseVersionsClient contains the methods for the AutonomousDatabaseVersions group. +// Don't use this type directly, use NewAutonomousDatabaseVersionsClient() instead. +// +// Generated from API version 2025-09-01 +type AutonomousDatabaseVersionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewAutonomousDatabaseVersionsClient creates a new instance of AutonomousDatabaseVersionsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewAutonomousDatabaseVersionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*AutonomousDatabaseVersionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AutonomousDatabaseVersionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get a AutonomousDbVersion +// If the operation fails it returns an *azcore.ResponseError type. +// - location - The name of the Azure region. +// - autonomousdbversionsname - AutonomousDbVersion name +// - options - AutonomousDatabaseVersionsClientGetOptions contains the optional parameters for the AutonomousDatabaseVersionsClient.Get +// method. +func (client *AutonomousDatabaseVersionsClient) Get(ctx context.Context, location string, autonomousdbversionsname string, options *AutonomousDatabaseVersionsClientGetOptions) (AutonomousDatabaseVersionsClientGetResponse, error) { + var err error + const operationName = "AutonomousDatabaseVersionsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, location, autonomousdbversionsname, options) + if err != nil { + return AutonomousDatabaseVersionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AutonomousDatabaseVersionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AutonomousDatabaseVersionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *AutonomousDatabaseVersionsClient) getCreateRequest(ctx context.Context, location string, autonomousdbversionsname string, _ *AutonomousDatabaseVersionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/locations/{location}/autonomousDbVersions/{autonomousdbversionsname}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if autonomousdbversionsname == "" { + return nil, errors.New("parameter autonomousdbversionsname cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{autonomousdbversionsname}", url.PathEscape(autonomousdbversionsname)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *AutonomousDatabaseVersionsClient) getHandleResponse(resp *http.Response) (AutonomousDatabaseVersionsClientGetResponse, error) { + result := AutonomousDatabaseVersionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AutonomousDbVersion); err != nil { + return AutonomousDatabaseVersionsClientGetResponse{}, err + } + return result, nil +} + +// NewListByLocationPager - List AutonomousDbVersion resources by SubscriptionLocationResource +// - location - The name of the Azure region. +// - options - AutonomousDatabaseVersionsClientListByLocationOptions contains the optional parameters for the AutonomousDatabaseVersionsClient.NewListByLocationPager +// method. +func (client *AutonomousDatabaseVersionsClient) NewListByLocationPager(location string, options *AutonomousDatabaseVersionsClientListByLocationOptions) *runtime.Pager[AutonomousDatabaseVersionsClientListByLocationResponse] { + return runtime.NewPager(runtime.PagingHandler[AutonomousDatabaseVersionsClientListByLocationResponse]{ + More: func(page AutonomousDatabaseVersionsClientListByLocationResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *AutonomousDatabaseVersionsClientListByLocationResponse) (AutonomousDatabaseVersionsClientListByLocationResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "AutonomousDatabaseVersionsClient.NewListByLocationPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByLocationCreateRequest(ctx, location, options) + }, nil) + if err != nil { + return AutonomousDatabaseVersionsClientListByLocationResponse{}, err + } + return client.listByLocationHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByLocationCreateRequest creates the ListByLocation request. +func (client *AutonomousDatabaseVersionsClient) listByLocationCreateRequest(ctx context.Context, location string, _ *AutonomousDatabaseVersionsClientListByLocationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/locations/{location}/autonomousDbVersions" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByLocationHandleResponse handles the ListByLocation response. +func (client *AutonomousDatabaseVersionsClient) listByLocationHandleResponse(resp *http.Response) (AutonomousDatabaseVersionsClientListByLocationResponse, error) { + result := AutonomousDatabaseVersionsClientListByLocationResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AutonomousDbVersionListResult); err != nil { + return AutonomousDatabaseVersionsClientListByLocationResponse{}, err + } + return result, nil +} diff --git a/test/local/armoracledatabase/zz_client_factory.go b/test/local/armoracledatabase/zz_client_factory.go new file mode 100644 index 000000000000..35a3f34f1d42 --- /dev/null +++ b/test/local/armoracledatabase/zz_client_factory.go @@ -0,0 +1,240 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + subscriptionID string + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, + internal: internal, + }, nil +} + +// NewAutonomousDatabaseBackupsClient creates a new instance of AutonomousDatabaseBackupsClient. +func (c *ClientFactory) NewAutonomousDatabaseBackupsClient() *AutonomousDatabaseBackupsClient { + return &AutonomousDatabaseBackupsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewAutonomousDatabaseCharacterSetsClient creates a new instance of AutonomousDatabaseCharacterSetsClient. +func (c *ClientFactory) NewAutonomousDatabaseCharacterSetsClient() *AutonomousDatabaseCharacterSetsClient { + return &AutonomousDatabaseCharacterSetsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewAutonomousDatabaseNationalCharacterSetsClient creates a new instance of AutonomousDatabaseNationalCharacterSetsClient. +func (c *ClientFactory) NewAutonomousDatabaseNationalCharacterSetsClient() *AutonomousDatabaseNationalCharacterSetsClient { + return &AutonomousDatabaseNationalCharacterSetsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewAutonomousDatabaseVersionsClient creates a new instance of AutonomousDatabaseVersionsClient. +func (c *ClientFactory) NewAutonomousDatabaseVersionsClient() *AutonomousDatabaseVersionsClient { + return &AutonomousDatabaseVersionsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewAutonomousDatabasesClient creates a new instance of AutonomousDatabasesClient. +func (c *ClientFactory) NewAutonomousDatabasesClient() *AutonomousDatabasesClient { + return &AutonomousDatabasesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewCloudExadataInfrastructuresClient creates a new instance of CloudExadataInfrastructuresClient. +func (c *ClientFactory) NewCloudExadataInfrastructuresClient() *CloudExadataInfrastructuresClient { + return &CloudExadataInfrastructuresClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewCloudVMClustersClient creates a new instance of CloudVMClustersClient. +func (c *ClientFactory) NewCloudVMClustersClient() *CloudVMClustersClient { + return &CloudVMClustersClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewDNSPrivateViewsClient creates a new instance of DNSPrivateViewsClient. +func (c *ClientFactory) NewDNSPrivateViewsClient() *DNSPrivateViewsClient { + return &DNSPrivateViewsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewDNSPrivateZonesClient creates a new instance of DNSPrivateZonesClient. +func (c *ClientFactory) NewDNSPrivateZonesClient() *DNSPrivateZonesClient { + return &DNSPrivateZonesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewDbNodesClient creates a new instance of DbNodesClient. +func (c *ClientFactory) NewDbNodesClient() *DbNodesClient { + return &DbNodesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewDbServersClient creates a new instance of DbServersClient. +func (c *ClientFactory) NewDbServersClient() *DbServersClient { + return &DbServersClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewDbSystemShapesClient creates a new instance of DbSystemShapesClient. +func (c *ClientFactory) NewDbSystemShapesClient() *DbSystemShapesClient { + return &DbSystemShapesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewDbSystemsClient creates a new instance of DbSystemsClient. +func (c *ClientFactory) NewDbSystemsClient() *DbSystemsClient { + return &DbSystemsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewDbVersionsClient creates a new instance of DbVersionsClient. +func (c *ClientFactory) NewDbVersionsClient() *DbVersionsClient { + return &DbVersionsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewExadbVMClustersClient creates a new instance of ExadbVMClustersClient. +func (c *ClientFactory) NewExadbVMClustersClient() *ExadbVMClustersClient { + return &ExadbVMClustersClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewExascaleDbNodesClient creates a new instance of ExascaleDbNodesClient. +func (c *ClientFactory) NewExascaleDbNodesClient() *ExascaleDbNodesClient { + return &ExascaleDbNodesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewExascaleDbStorageVaultsClient creates a new instance of ExascaleDbStorageVaultsClient. +func (c *ClientFactory) NewExascaleDbStorageVaultsClient() *ExascaleDbStorageVaultsClient { + return &ExascaleDbStorageVaultsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewFlexComponentsClient creates a new instance of FlexComponentsClient. +func (c *ClientFactory) NewFlexComponentsClient() *FlexComponentsClient { + return &FlexComponentsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewGiMinorVersionsClient creates a new instance of GiMinorVersionsClient. +func (c *ClientFactory) NewGiMinorVersionsClient() *GiMinorVersionsClient { + return &GiMinorVersionsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewGiVersionsClient creates a new instance of GiVersionsClient. +func (c *ClientFactory) NewGiVersionsClient() *GiVersionsClient { + return &GiVersionsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewNetworkAnchorsClient creates a new instance of NetworkAnchorsClient. +func (c *ClientFactory) NewNetworkAnchorsClient() *NetworkAnchorsClient { + return &NetworkAnchorsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewOperationsClient creates a new instance of OperationsClient. +func (c *ClientFactory) NewOperationsClient() *OperationsClient { + return &OperationsClient{ + internal: c.internal, + } +} + +// NewOracleSubscriptionsClient creates a new instance of OracleSubscriptionsClient. +func (c *ClientFactory) NewOracleSubscriptionsClient() *OracleSubscriptionsClient { + return &OracleSubscriptionsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewResourceAnchorsClient creates a new instance of ResourceAnchorsClient. +func (c *ClientFactory) NewResourceAnchorsClient() *ResourceAnchorsClient { + return &ResourceAnchorsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewSystemVersionsClient creates a new instance of SystemVersionsClient. +func (c *ClientFactory) NewSystemVersionsClient() *SystemVersionsClient { + return &SystemVersionsClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewVirtualNetworkAddressesClient creates a new instance of VirtualNetworkAddressesClient. +func (c *ClientFactory) NewVirtualNetworkAddressesClient() *VirtualNetworkAddressesClient { + return &VirtualNetworkAddressesClient{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} diff --git a/test/local/armoracledatabase/zz_cloudexadatainfrastructures_client.go b/test/local/armoracledatabase/zz_cloudexadatainfrastructures_client.go new file mode 100644 index 000000000000..95a9ce05f05a --- /dev/null +++ b/test/local/armoracledatabase/zz_cloudexadatainfrastructures_client.go @@ -0,0 +1,590 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// CloudExadataInfrastructuresClient contains the methods for the CloudExadataInfrastructures group. +// Don't use this type directly, use NewCloudExadataInfrastructuresClient() instead. +// +// Generated from API version 2025-09-01 +type CloudExadataInfrastructuresClient struct { + internal *arm.Client + subscriptionID string +} + +// NewCloudExadataInfrastructuresClient creates a new instance of CloudExadataInfrastructuresClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewCloudExadataInfrastructuresClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CloudExadataInfrastructuresClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CloudExadataInfrastructuresClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginAddStorageCapacity - Perform add storage capacity on exadata infra +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudexadatainfrastructurename - CloudExadataInfrastructure name +// - options - CloudExadataInfrastructuresClientBeginAddStorageCapacityOptions contains the optional parameters for the CloudExadataInfrastructuresClient.BeginAddStorageCapacity +// method. +func (client *CloudExadataInfrastructuresClient) BeginAddStorageCapacity(ctx context.Context, resourceGroupName string, cloudexadatainfrastructurename string, options *CloudExadataInfrastructuresClientBeginAddStorageCapacityOptions) (*runtime.Poller[CloudExadataInfrastructuresClientAddStorageCapacityResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.addStorageCapacity(ctx, resourceGroupName, cloudexadatainfrastructurename, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudExadataInfrastructuresClientAddStorageCapacityResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudExadataInfrastructuresClientAddStorageCapacityResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// AddStorageCapacity - Perform add storage capacity on exadata infra +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CloudExadataInfrastructuresClient) addStorageCapacity(ctx context.Context, resourceGroupName string, cloudexadatainfrastructurename string, options *CloudExadataInfrastructuresClientBeginAddStorageCapacityOptions) (*http.Response, error) { + var err error + const operationName = "CloudExadataInfrastructuresClient.BeginAddStorageCapacity" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.addStorageCapacityCreateRequest(ctx, resourceGroupName, cloudexadatainfrastructurename, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// addStorageCapacityCreateRequest creates the AddStorageCapacity request. +func (client *CloudExadataInfrastructuresClient) addStorageCapacityCreateRequest(ctx context.Context, resourceGroupName string, cloudexadatainfrastructurename string, _ *CloudExadataInfrastructuresClientBeginAddStorageCapacityOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/cloudExadataInfrastructures/{cloudexadatainfrastructurename}/addStorageCapacity" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudexadatainfrastructurename == "" { + return nil, errors.New("parameter cloudexadatainfrastructurename cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudexadatainfrastructurename}", url.PathEscape(cloudexadatainfrastructurename)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginConfigureExascale - Configures Exascale on Cloud exadata infrastructure resource +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudexadatainfrastructurename - CloudExadataInfrastructure name +// - body - The content of the action request +// - options - CloudExadataInfrastructuresClientBeginConfigureExascaleOptions contains the optional parameters for the CloudExadataInfrastructuresClient.BeginConfigureExascale +// method. +func (client *CloudExadataInfrastructuresClient) BeginConfigureExascale(ctx context.Context, resourceGroupName string, cloudexadatainfrastructurename string, body ConfigureExascaleCloudExadataInfrastructureDetails, options *CloudExadataInfrastructuresClientBeginConfigureExascaleOptions) (*runtime.Poller[CloudExadataInfrastructuresClientConfigureExascaleResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.configureExascale(ctx, resourceGroupName, cloudexadatainfrastructurename, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudExadataInfrastructuresClientConfigureExascaleResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudExadataInfrastructuresClientConfigureExascaleResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ConfigureExascale - Configures Exascale on Cloud exadata infrastructure resource +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CloudExadataInfrastructuresClient) configureExascale(ctx context.Context, resourceGroupName string, cloudexadatainfrastructurename string, body ConfigureExascaleCloudExadataInfrastructureDetails, options *CloudExadataInfrastructuresClientBeginConfigureExascaleOptions) (*http.Response, error) { + var err error + const operationName = "CloudExadataInfrastructuresClient.BeginConfigureExascale" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.configureExascaleCreateRequest(ctx, resourceGroupName, cloudexadatainfrastructurename, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// configureExascaleCreateRequest creates the ConfigureExascale request. +func (client *CloudExadataInfrastructuresClient) configureExascaleCreateRequest(ctx context.Context, resourceGroupName string, cloudexadatainfrastructurename string, body ConfigureExascaleCloudExadataInfrastructureDetails, _ *CloudExadataInfrastructuresClientBeginConfigureExascaleOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/cloudExadataInfrastructures/{cloudexadatainfrastructurename}/configureExascale" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudexadatainfrastructurename == "" { + return nil, errors.New("parameter cloudexadatainfrastructurename cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudexadatainfrastructurename}", url.PathEscape(cloudexadatainfrastructurename)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// BeginCreateOrUpdate - Create a CloudExadataInfrastructure +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudexadatainfrastructurename - CloudExadataInfrastructure name +// - resource - Resource create parameters. +// - options - CloudExadataInfrastructuresClientBeginCreateOrUpdateOptions contains the optional parameters for the CloudExadataInfrastructuresClient.BeginCreateOrUpdate +// method. +func (client *CloudExadataInfrastructuresClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, cloudexadatainfrastructurename string, resource CloudExadataInfrastructure, options *CloudExadataInfrastructuresClientBeginCreateOrUpdateOptions) (*runtime.Poller[CloudExadataInfrastructuresClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, cloudexadatainfrastructurename, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudExadataInfrastructuresClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudExadataInfrastructuresClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create a CloudExadataInfrastructure +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CloudExadataInfrastructuresClient) createOrUpdate(ctx context.Context, resourceGroupName string, cloudexadatainfrastructurename string, resource CloudExadataInfrastructure, options *CloudExadataInfrastructuresClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "CloudExadataInfrastructuresClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, cloudexadatainfrastructurename, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *CloudExadataInfrastructuresClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, cloudexadatainfrastructurename string, resource CloudExadataInfrastructure, _ *CloudExadataInfrastructuresClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/cloudExadataInfrastructures/{cloudexadatainfrastructurename}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudexadatainfrastructurename == "" { + return nil, errors.New("parameter cloudexadatainfrastructurename cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudexadatainfrastructurename}", url.PathEscape(cloudexadatainfrastructurename)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a CloudExadataInfrastructure +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudexadatainfrastructurename - CloudExadataInfrastructure name +// - options - CloudExadataInfrastructuresClientBeginDeleteOptions contains the optional parameters for the CloudExadataInfrastructuresClient.BeginDelete +// method. +func (client *CloudExadataInfrastructuresClient) BeginDelete(ctx context.Context, resourceGroupName string, cloudexadatainfrastructurename string, options *CloudExadataInfrastructuresClientBeginDeleteOptions) (*runtime.Poller[CloudExadataInfrastructuresClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, cloudexadatainfrastructurename, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudExadataInfrastructuresClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudExadataInfrastructuresClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a CloudExadataInfrastructure +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CloudExadataInfrastructuresClient) deleteOperation(ctx context.Context, resourceGroupName string, cloudexadatainfrastructurename string, options *CloudExadataInfrastructuresClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "CloudExadataInfrastructuresClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, cloudexadatainfrastructurename, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *CloudExadataInfrastructuresClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, cloudexadatainfrastructurename string, _ *CloudExadataInfrastructuresClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/cloudExadataInfrastructures/{cloudexadatainfrastructurename}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudexadatainfrastructurename == "" { + return nil, errors.New("parameter cloudexadatainfrastructurename cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudexadatainfrastructurename}", url.PathEscape(cloudexadatainfrastructurename)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a CloudExadataInfrastructure +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudexadatainfrastructurename - CloudExadataInfrastructure name +// - options - CloudExadataInfrastructuresClientGetOptions contains the optional parameters for the CloudExadataInfrastructuresClient.Get +// method. +func (client *CloudExadataInfrastructuresClient) Get(ctx context.Context, resourceGroupName string, cloudexadatainfrastructurename string, options *CloudExadataInfrastructuresClientGetOptions) (CloudExadataInfrastructuresClientGetResponse, error) { + var err error + const operationName = "CloudExadataInfrastructuresClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, cloudexadatainfrastructurename, options) + if err != nil { + return CloudExadataInfrastructuresClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CloudExadataInfrastructuresClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CloudExadataInfrastructuresClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *CloudExadataInfrastructuresClient) getCreateRequest(ctx context.Context, resourceGroupName string, cloudexadatainfrastructurename string, _ *CloudExadataInfrastructuresClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/cloudExadataInfrastructures/{cloudexadatainfrastructurename}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudexadatainfrastructurename == "" { + return nil, errors.New("parameter cloudexadatainfrastructurename cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudexadatainfrastructurename}", url.PathEscape(cloudexadatainfrastructurename)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *CloudExadataInfrastructuresClient) getHandleResponse(resp *http.Response) (CloudExadataInfrastructuresClientGetResponse, error) { + result := CloudExadataInfrastructuresClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CloudExadataInfrastructure); err != nil { + return CloudExadataInfrastructuresClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - List CloudExadataInfrastructure resources by resource group +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - CloudExadataInfrastructuresClientListByResourceGroupOptions contains the optional parameters for the CloudExadataInfrastructuresClient.NewListByResourceGroupPager +// method. +func (client *CloudExadataInfrastructuresClient) NewListByResourceGroupPager(resourceGroupName string, options *CloudExadataInfrastructuresClientListByResourceGroupOptions) *runtime.Pager[CloudExadataInfrastructuresClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[CloudExadataInfrastructuresClientListByResourceGroupResponse]{ + More: func(page CloudExadataInfrastructuresClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CloudExadataInfrastructuresClientListByResourceGroupResponse) (CloudExadataInfrastructuresClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CloudExadataInfrastructuresClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return CloudExadataInfrastructuresClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *CloudExadataInfrastructuresClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *CloudExadataInfrastructuresClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/cloudExadataInfrastructures" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *CloudExadataInfrastructuresClient) listByResourceGroupHandleResponse(resp *http.Response) (CloudExadataInfrastructuresClientListByResourceGroupResponse, error) { + result := CloudExadataInfrastructuresClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CloudExadataInfrastructureListResult); err != nil { + return CloudExadataInfrastructuresClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - List CloudExadataInfrastructure resources by subscription ID +// - options - CloudExadataInfrastructuresClientListBySubscriptionOptions contains the optional parameters for the CloudExadataInfrastructuresClient.NewListBySubscriptionPager +// method. +func (client *CloudExadataInfrastructuresClient) NewListBySubscriptionPager(options *CloudExadataInfrastructuresClientListBySubscriptionOptions) *runtime.Pager[CloudExadataInfrastructuresClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[CloudExadataInfrastructuresClientListBySubscriptionResponse]{ + More: func(page CloudExadataInfrastructuresClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CloudExadataInfrastructuresClientListBySubscriptionResponse) (CloudExadataInfrastructuresClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CloudExadataInfrastructuresClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return CloudExadataInfrastructuresClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *CloudExadataInfrastructuresClient) listBySubscriptionCreateRequest(ctx context.Context, _ *CloudExadataInfrastructuresClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/cloudExadataInfrastructures" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *CloudExadataInfrastructuresClient) listBySubscriptionHandleResponse(resp *http.Response) (CloudExadataInfrastructuresClientListBySubscriptionResponse, error) { + result := CloudExadataInfrastructuresClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CloudExadataInfrastructureListResult); err != nil { + return CloudExadataInfrastructuresClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update a CloudExadataInfrastructure +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudexadatainfrastructurename - CloudExadataInfrastructure name +// - properties - The resource properties to be updated. +// - options - CloudExadataInfrastructuresClientBeginUpdateOptions contains the optional parameters for the CloudExadataInfrastructuresClient.BeginUpdate +// method. +func (client *CloudExadataInfrastructuresClient) BeginUpdate(ctx context.Context, resourceGroupName string, cloudexadatainfrastructurename string, properties CloudExadataInfrastructureUpdate, options *CloudExadataInfrastructuresClientBeginUpdateOptions) (*runtime.Poller[CloudExadataInfrastructuresClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, cloudexadatainfrastructurename, properties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudExadataInfrastructuresClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudExadataInfrastructuresClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a CloudExadataInfrastructure +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CloudExadataInfrastructuresClient) update(ctx context.Context, resourceGroupName string, cloudexadatainfrastructurename string, properties CloudExadataInfrastructureUpdate, options *CloudExadataInfrastructuresClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "CloudExadataInfrastructuresClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, cloudexadatainfrastructurename, properties, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *CloudExadataInfrastructuresClient) updateCreateRequest(ctx context.Context, resourceGroupName string, cloudexadatainfrastructurename string, properties CloudExadataInfrastructureUpdate, _ *CloudExadataInfrastructuresClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/cloudExadataInfrastructures/{cloudexadatainfrastructurename}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudexadatainfrastructurename == "" { + return nil, errors.New("parameter cloudexadatainfrastructurename cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudexadatainfrastructurename}", url.PathEscape(cloudexadatainfrastructurename)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armoracledatabase/zz_cloudvmclusters_client.go b/test/local/armoracledatabase/zz_cloudvmclusters_client.go new file mode 100644 index 000000000000..e2ae2efb5c0b --- /dev/null +++ b/test/local/armoracledatabase/zz_cloudvmclusters_client.go @@ -0,0 +1,662 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// CloudVMClustersClient contains the methods for the CloudVMClusters group. +// Don't use this type directly, use NewCloudVMClustersClient() instead. +// +// Generated from API version 2025-09-01 +type CloudVMClustersClient struct { + internal *arm.Client + subscriptionID string +} + +// NewCloudVMClustersClient creates a new instance of CloudVMClustersClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewCloudVMClustersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CloudVMClustersClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &CloudVMClustersClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginAddVMs - Add VMs to the VM Cluster +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudvmclustername - CloudVmCluster name +// - body - The content of the action request +// - options - CloudVMClustersClientBeginAddVMsOptions contains the optional parameters for the CloudVMClustersClient.BeginAddVMs +// method. +func (client *CloudVMClustersClient) BeginAddVMs(ctx context.Context, resourceGroupName string, cloudvmclustername string, body AddRemoveDbNode, options *CloudVMClustersClientBeginAddVMsOptions) (*runtime.Poller[CloudVMClustersClientAddVMsResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.addVMs(ctx, resourceGroupName, cloudvmclustername, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudVMClustersClientAddVMsResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudVMClustersClientAddVMsResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// AddVMs - Add VMs to the VM Cluster +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CloudVMClustersClient) addVMs(ctx context.Context, resourceGroupName string, cloudvmclustername string, body AddRemoveDbNode, options *CloudVMClustersClientBeginAddVMsOptions) (*http.Response, error) { + var err error + const operationName = "CloudVMClustersClient.BeginAddVMs" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.addVMsCreateRequest(ctx, resourceGroupName, cloudvmclustername, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// addVMsCreateRequest creates the AddVMs request. +func (client *CloudVMClustersClient) addVMsCreateRequest(ctx context.Context, resourceGroupName string, cloudvmclustername string, body AddRemoveDbNode, _ *CloudVMClustersClientBeginAddVMsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/cloudVmClusters/{cloudvmclustername}/addVms" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudvmclustername == "" { + return nil, errors.New("parameter cloudvmclustername cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudvmclustername}", url.PathEscape(cloudvmclustername)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// BeginCreateOrUpdate - Create a CloudVmCluster +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudvmclustername - CloudVmCluster name +// - resource - Resource create parameters. +// - options - CloudVMClustersClientBeginCreateOrUpdateOptions contains the optional parameters for the CloudVMClustersClient.BeginCreateOrUpdate +// method. +func (client *CloudVMClustersClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, cloudvmclustername string, resource CloudVMCluster, options *CloudVMClustersClientBeginCreateOrUpdateOptions) (*runtime.Poller[CloudVMClustersClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, cloudvmclustername, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudVMClustersClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudVMClustersClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create a CloudVmCluster +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CloudVMClustersClient) createOrUpdate(ctx context.Context, resourceGroupName string, cloudvmclustername string, resource CloudVMCluster, options *CloudVMClustersClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "CloudVMClustersClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, cloudvmclustername, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *CloudVMClustersClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, cloudvmclustername string, resource CloudVMCluster, _ *CloudVMClustersClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/cloudVmClusters/{cloudvmclustername}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudvmclustername == "" { + return nil, errors.New("parameter cloudvmclustername cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudvmclustername}", url.PathEscape(cloudvmclustername)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a CloudVmCluster +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudvmclustername - CloudVmCluster name +// - options - CloudVMClustersClientBeginDeleteOptions contains the optional parameters for the CloudVMClustersClient.BeginDelete +// method. +func (client *CloudVMClustersClient) BeginDelete(ctx context.Context, resourceGroupName string, cloudvmclustername string, options *CloudVMClustersClientBeginDeleteOptions) (*runtime.Poller[CloudVMClustersClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, cloudvmclustername, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudVMClustersClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudVMClustersClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a CloudVmCluster +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CloudVMClustersClient) deleteOperation(ctx context.Context, resourceGroupName string, cloudvmclustername string, options *CloudVMClustersClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "CloudVMClustersClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, cloudvmclustername, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *CloudVMClustersClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, cloudvmclustername string, _ *CloudVMClustersClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/cloudVmClusters/{cloudvmclustername}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudvmclustername == "" { + return nil, errors.New("parameter cloudvmclustername cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudvmclustername}", url.PathEscape(cloudvmclustername)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a CloudVmCluster +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudvmclustername - CloudVmCluster name +// - options - CloudVMClustersClientGetOptions contains the optional parameters for the CloudVMClustersClient.Get method. +func (client *CloudVMClustersClient) Get(ctx context.Context, resourceGroupName string, cloudvmclustername string, options *CloudVMClustersClientGetOptions) (CloudVMClustersClientGetResponse, error) { + var err error + const operationName = "CloudVMClustersClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, cloudvmclustername, options) + if err != nil { + return CloudVMClustersClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CloudVMClustersClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CloudVMClustersClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *CloudVMClustersClient) getCreateRequest(ctx context.Context, resourceGroupName string, cloudvmclustername string, _ *CloudVMClustersClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/cloudVmClusters/{cloudvmclustername}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudvmclustername == "" { + return nil, errors.New("parameter cloudvmclustername cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudvmclustername}", url.PathEscape(cloudvmclustername)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *CloudVMClustersClient) getHandleResponse(resp *http.Response) (CloudVMClustersClientGetResponse, error) { + result := CloudVMClustersClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CloudVMCluster); err != nil { + return CloudVMClustersClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - List CloudVmCluster resources by resource group +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - CloudVMClustersClientListByResourceGroupOptions contains the optional parameters for the CloudVMClustersClient.NewListByResourceGroupPager +// method. +func (client *CloudVMClustersClient) NewListByResourceGroupPager(resourceGroupName string, options *CloudVMClustersClientListByResourceGroupOptions) *runtime.Pager[CloudVMClustersClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[CloudVMClustersClientListByResourceGroupResponse]{ + More: func(page CloudVMClustersClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CloudVMClustersClientListByResourceGroupResponse) (CloudVMClustersClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CloudVMClustersClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return CloudVMClustersClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *CloudVMClustersClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *CloudVMClustersClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/cloudVmClusters" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *CloudVMClustersClient) listByResourceGroupHandleResponse(resp *http.Response) (CloudVMClustersClientListByResourceGroupResponse, error) { + result := CloudVMClustersClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CloudVMClusterListResult); err != nil { + return CloudVMClustersClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - List CloudVmCluster resources by subscription ID +// - options - CloudVMClustersClientListBySubscriptionOptions contains the optional parameters for the CloudVMClustersClient.NewListBySubscriptionPager +// method. +func (client *CloudVMClustersClient) NewListBySubscriptionPager(options *CloudVMClustersClientListBySubscriptionOptions) *runtime.Pager[CloudVMClustersClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[CloudVMClustersClientListBySubscriptionResponse]{ + More: func(page CloudVMClustersClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *CloudVMClustersClientListBySubscriptionResponse) (CloudVMClustersClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "CloudVMClustersClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return CloudVMClustersClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *CloudVMClustersClient) listBySubscriptionCreateRequest(ctx context.Context, _ *CloudVMClustersClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/cloudVmClusters" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *CloudVMClustersClient) listBySubscriptionHandleResponse(resp *http.Response) (CloudVMClustersClientListBySubscriptionResponse, error) { + result := CloudVMClustersClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.CloudVMClusterListResult); err != nil { + return CloudVMClustersClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// ListPrivateIPAddresses - List Private IP Addresses by the provided filter +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudvmclustername - CloudVmCluster name +// - body - The content of the action request +// - options - CloudVMClustersClientListPrivateIPAddressesOptions contains the optional parameters for the CloudVMClustersClient.ListPrivateIPAddresses +// method. +func (client *CloudVMClustersClient) ListPrivateIPAddresses(ctx context.Context, resourceGroupName string, cloudvmclustername string, body PrivateIPAddressesFilter, options *CloudVMClustersClientListPrivateIPAddressesOptions) (CloudVMClustersClientListPrivateIPAddressesResponse, error) { + var err error + const operationName = "CloudVMClustersClient.ListPrivateIPAddresses" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listPrivateIPAddressesCreateRequest(ctx, resourceGroupName, cloudvmclustername, body, options) + if err != nil { + return CloudVMClustersClientListPrivateIPAddressesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CloudVMClustersClientListPrivateIPAddressesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CloudVMClustersClientListPrivateIPAddressesResponse{}, err + } + resp, err := client.listPrivateIPAddressesHandleResponse(httpResp) + return resp, err +} + +// listPrivateIPAddressesCreateRequest creates the ListPrivateIPAddresses request. +func (client *CloudVMClustersClient) listPrivateIPAddressesCreateRequest(ctx context.Context, resourceGroupName string, cloudvmclustername string, body PrivateIPAddressesFilter, _ *CloudVMClustersClientListPrivateIPAddressesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/cloudVmClusters/{cloudvmclustername}/listPrivateIpAddresses" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudvmclustername == "" { + return nil, errors.New("parameter cloudvmclustername cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudvmclustername}", url.PathEscape(cloudvmclustername)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// listPrivateIPAddressesHandleResponse handles the ListPrivateIPAddresses response. +func (client *CloudVMClustersClient) listPrivateIPAddressesHandleResponse(resp *http.Response) (CloudVMClustersClientListPrivateIPAddressesResponse, error) { + result := CloudVMClustersClientListPrivateIPAddressesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateIPAddressPropertiesArray); err != nil { + return CloudVMClustersClientListPrivateIPAddressesResponse{}, err + } + return result, nil +} + +// BeginRemoveVMs - Remove VMs from the VM Cluster +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudvmclustername - CloudVmCluster name +// - body - The content of the action request +// - options - CloudVMClustersClientBeginRemoveVMsOptions contains the optional parameters for the CloudVMClustersClient.BeginRemoveVMs +// method. +func (client *CloudVMClustersClient) BeginRemoveVMs(ctx context.Context, resourceGroupName string, cloudvmclustername string, body AddRemoveDbNode, options *CloudVMClustersClientBeginRemoveVMsOptions) (*runtime.Poller[CloudVMClustersClientRemoveVMsResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.removeVMs(ctx, resourceGroupName, cloudvmclustername, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudVMClustersClientRemoveVMsResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudVMClustersClientRemoveVMsResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// RemoveVMs - Remove VMs from the VM Cluster +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CloudVMClustersClient) removeVMs(ctx context.Context, resourceGroupName string, cloudvmclustername string, body AddRemoveDbNode, options *CloudVMClustersClientBeginRemoveVMsOptions) (*http.Response, error) { + var err error + const operationName = "CloudVMClustersClient.BeginRemoveVMs" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.removeVMsCreateRequest(ctx, resourceGroupName, cloudvmclustername, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// removeVMsCreateRequest creates the RemoveVMs request. +func (client *CloudVMClustersClient) removeVMsCreateRequest(ctx context.Context, resourceGroupName string, cloudvmclustername string, body AddRemoveDbNode, _ *CloudVMClustersClientBeginRemoveVMsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/cloudVmClusters/{cloudvmclustername}/removeVms" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudvmclustername == "" { + return nil, errors.New("parameter cloudvmclustername cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudvmclustername}", url.PathEscape(cloudvmclustername)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// BeginUpdate - Update a CloudVmCluster +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudvmclustername - CloudVmCluster name +// - properties - The resource properties to be updated. +// - options - CloudVMClustersClientBeginUpdateOptions contains the optional parameters for the CloudVMClustersClient.BeginUpdate +// method. +func (client *CloudVMClustersClient) BeginUpdate(ctx context.Context, resourceGroupName string, cloudvmclustername string, properties CloudVMClusterUpdate, options *CloudVMClustersClientBeginUpdateOptions) (*runtime.Poller[CloudVMClustersClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, cloudvmclustername, properties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[CloudVMClustersClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[CloudVMClustersClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a CloudVmCluster +// If the operation fails it returns an *azcore.ResponseError type. +func (client *CloudVMClustersClient) update(ctx context.Context, resourceGroupName string, cloudvmclustername string, properties CloudVMClusterUpdate, options *CloudVMClustersClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "CloudVMClustersClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, cloudvmclustername, properties, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *CloudVMClustersClient) updateCreateRequest(ctx context.Context, resourceGroupName string, cloudvmclustername string, properties CloudVMClusterUpdate, _ *CloudVMClustersClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/cloudVmClusters/{cloudvmclustername}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudvmclustername == "" { + return nil, errors.New("parameter cloudvmclustername cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudvmclustername}", url.PathEscape(cloudvmclustername)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armoracledatabase/zz_constants.go b/test/local/armoracledatabase/zz_constants.go new file mode 100644 index 000000000000..5549f05a8b8f --- /dev/null +++ b/test/local/armoracledatabase/zz_constants.go @@ -0,0 +1,1683 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +const ( + version20250901 string = "2025-09-01" +) + +// ActionType - Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +type ActionType string + +const ( + // ActionTypeInternal - Actions are for internal-only APIs. + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// AddSubscriptionOperationState - Add Subscription Operation state enum +type AddSubscriptionOperationState string + +const ( + // AddSubscriptionOperationStateFailed - Failed - State when Add Subscription operation failed + AddSubscriptionOperationStateFailed AddSubscriptionOperationState = "Failed" + // AddSubscriptionOperationStateSucceeded - Succeeded - State when Add Subscription operation succeeded + AddSubscriptionOperationStateSucceeded AddSubscriptionOperationState = "Succeeded" + // AddSubscriptionOperationStateUpdating - Updating - State when Add Subscription operation is being Updated + AddSubscriptionOperationStateUpdating AddSubscriptionOperationState = "Updating" +) + +// PossibleAddSubscriptionOperationStateValues returns the possible values for the AddSubscriptionOperationState const type. +func PossibleAddSubscriptionOperationStateValues() []AddSubscriptionOperationState { + return []AddSubscriptionOperationState{ + AddSubscriptionOperationStateFailed, + AddSubscriptionOperationStateSucceeded, + AddSubscriptionOperationStateUpdating, + } +} + +// AutonomousDatabaseBackupLifecycleState - Autonomous database backup lifecycle state enum +type AutonomousDatabaseBackupLifecycleState string + +const ( + // AutonomousDatabaseBackupLifecycleStateActive - AutonomousDatabase backup is active + AutonomousDatabaseBackupLifecycleStateActive AutonomousDatabaseBackupLifecycleState = "Active" + // AutonomousDatabaseBackupLifecycleStateCreating - AutonomousDatabase backup is creating + AutonomousDatabaseBackupLifecycleStateCreating AutonomousDatabaseBackupLifecycleState = "Creating" + // AutonomousDatabaseBackupLifecycleStateDeleting - AutonomousDatabase backup is deleting + AutonomousDatabaseBackupLifecycleStateDeleting AutonomousDatabaseBackupLifecycleState = "Deleting" + // AutonomousDatabaseBackupLifecycleStateFailed - AutonomousDatabase backup is failed + AutonomousDatabaseBackupLifecycleStateFailed AutonomousDatabaseBackupLifecycleState = "Failed" + // AutonomousDatabaseBackupLifecycleStateUpdating - AutonomousDatabase backup is updating + AutonomousDatabaseBackupLifecycleStateUpdating AutonomousDatabaseBackupLifecycleState = "Updating" +) + +// PossibleAutonomousDatabaseBackupLifecycleStateValues returns the possible values for the AutonomousDatabaseBackupLifecycleState const type. +func PossibleAutonomousDatabaseBackupLifecycleStateValues() []AutonomousDatabaseBackupLifecycleState { + return []AutonomousDatabaseBackupLifecycleState{ + AutonomousDatabaseBackupLifecycleStateActive, + AutonomousDatabaseBackupLifecycleStateCreating, + AutonomousDatabaseBackupLifecycleStateDeleting, + AutonomousDatabaseBackupLifecycleStateFailed, + AutonomousDatabaseBackupLifecycleStateUpdating, + } +} + +// AutonomousDatabaseBackupType - Autonomous database backup type enum +type AutonomousDatabaseBackupType string + +const ( + // AutonomousDatabaseBackupTypeFull - Full backup + AutonomousDatabaseBackupTypeFull AutonomousDatabaseBackupType = "Full" + // AutonomousDatabaseBackupTypeIncremental - Incremental backup + AutonomousDatabaseBackupTypeIncremental AutonomousDatabaseBackupType = "Incremental" + // AutonomousDatabaseBackupTypeLongTerm - LongTerm backup + AutonomousDatabaseBackupTypeLongTerm AutonomousDatabaseBackupType = "LongTerm" +) + +// PossibleAutonomousDatabaseBackupTypeValues returns the possible values for the AutonomousDatabaseBackupType const type. +func PossibleAutonomousDatabaseBackupTypeValues() []AutonomousDatabaseBackupType { + return []AutonomousDatabaseBackupType{ + AutonomousDatabaseBackupTypeFull, + AutonomousDatabaseBackupTypeIncremental, + AutonomousDatabaseBackupTypeLongTerm, + } +} + +// AutonomousDatabaseLifecycleActionEnum - Autonomous Database Action Enum +type AutonomousDatabaseLifecycleActionEnum string + +const ( + // AutonomousDatabaseLifecycleActionEnumRestart - Restart Autonomous Database + AutonomousDatabaseLifecycleActionEnumRestart AutonomousDatabaseLifecycleActionEnum = "Restart" + // AutonomousDatabaseLifecycleActionEnumStart - Start Autonomous Database + AutonomousDatabaseLifecycleActionEnumStart AutonomousDatabaseLifecycleActionEnum = "Start" + // AutonomousDatabaseLifecycleActionEnumStop - Stop Autonomous Database + AutonomousDatabaseLifecycleActionEnumStop AutonomousDatabaseLifecycleActionEnum = "Stop" +) + +// PossibleAutonomousDatabaseLifecycleActionEnumValues returns the possible values for the AutonomousDatabaseLifecycleActionEnum const type. +func PossibleAutonomousDatabaseLifecycleActionEnumValues() []AutonomousDatabaseLifecycleActionEnum { + return []AutonomousDatabaseLifecycleActionEnum{ + AutonomousDatabaseLifecycleActionEnumRestart, + AutonomousDatabaseLifecycleActionEnumStart, + AutonomousDatabaseLifecycleActionEnumStop, + } +} + +// AutonomousDatabaseLifecycleState - Autonomous database lifecycle state enum +type AutonomousDatabaseLifecycleState string + +const ( + // AutonomousDatabaseLifecycleStateAvailable - Indicates that resource in Available state + AutonomousDatabaseLifecycleStateAvailable AutonomousDatabaseLifecycleState = "Available" + // AutonomousDatabaseLifecycleStateAvailableNeedsAttention - Indicates that resource is available but needs attention + AutonomousDatabaseLifecycleStateAvailableNeedsAttention AutonomousDatabaseLifecycleState = "AvailableNeedsAttention" + // AutonomousDatabaseLifecycleStateBackupInProgress - Indicates that resource in BackupInProgress state + AutonomousDatabaseLifecycleStateBackupInProgress AutonomousDatabaseLifecycleState = "BackupInProgress" + // AutonomousDatabaseLifecycleStateInaccessible - IIndicates that resource in Inaccessible state + AutonomousDatabaseLifecycleStateInaccessible AutonomousDatabaseLifecycleState = "Inaccessible" + // AutonomousDatabaseLifecycleStateMaintenanceInProgress - Indicates that resource maintenance in progress state + AutonomousDatabaseLifecycleStateMaintenanceInProgress AutonomousDatabaseLifecycleState = "MaintenanceInProgress" + // AutonomousDatabaseLifecycleStateProvisioning - Indicates that resource in Provisioning state + AutonomousDatabaseLifecycleStateProvisioning AutonomousDatabaseLifecycleState = "Provisioning" + // AutonomousDatabaseLifecycleStateRecreating - Indicates that resource in Recreating state + AutonomousDatabaseLifecycleStateRecreating AutonomousDatabaseLifecycleState = "Recreating" + // AutonomousDatabaseLifecycleStateRestarting - Indicates that resource in Restarting state + AutonomousDatabaseLifecycleStateRestarting AutonomousDatabaseLifecycleState = "Restarting" + // AutonomousDatabaseLifecycleStateRestoreFailed - Indicates that resource in RestoreFailed state + AutonomousDatabaseLifecycleStateRestoreFailed AutonomousDatabaseLifecycleState = "RestoreFailed" + // AutonomousDatabaseLifecycleStateRestoreInProgress - Indicates that resource in RestoreInProgress state + AutonomousDatabaseLifecycleStateRestoreInProgress AutonomousDatabaseLifecycleState = "RestoreInProgress" + // AutonomousDatabaseLifecycleStateRoleChangeInProgress - Indicates that resource role change in progress state + AutonomousDatabaseLifecycleStateRoleChangeInProgress AutonomousDatabaseLifecycleState = "RoleChangeInProgress" + // AutonomousDatabaseLifecycleStateScaleInProgress - Indicates that resource in ScaleInProgress state + AutonomousDatabaseLifecycleStateScaleInProgress AutonomousDatabaseLifecycleState = "ScaleInProgress" + // AutonomousDatabaseLifecycleStateStandby - Indicates that resource in Standby state + AutonomousDatabaseLifecycleStateStandby AutonomousDatabaseLifecycleState = "Standby" + // AutonomousDatabaseLifecycleStateStarting - Indicates that resource in Starting state + AutonomousDatabaseLifecycleStateStarting AutonomousDatabaseLifecycleState = "Starting" + // AutonomousDatabaseLifecycleStateStopped - Indicates that resource in Stopped state + AutonomousDatabaseLifecycleStateStopped AutonomousDatabaseLifecycleState = "Stopped" + // AutonomousDatabaseLifecycleStateStopping - Indicates that resource in Stopping state + AutonomousDatabaseLifecycleStateStopping AutonomousDatabaseLifecycleState = "Stopping" + // AutonomousDatabaseLifecycleStateTerminated - Indicates that resource in Terminated state + AutonomousDatabaseLifecycleStateTerminated AutonomousDatabaseLifecycleState = "Terminated" + // AutonomousDatabaseLifecycleStateTerminating - Indicates that resource in Terminating state + AutonomousDatabaseLifecycleStateTerminating AutonomousDatabaseLifecycleState = "Terminating" + // AutonomousDatabaseLifecycleStateUnavailable - Indicates that resource in Unavailable state + AutonomousDatabaseLifecycleStateUnavailable AutonomousDatabaseLifecycleState = "Unavailable" + // AutonomousDatabaseLifecycleStateUpdating - Indicates that resource in Updating state + AutonomousDatabaseLifecycleStateUpdating AutonomousDatabaseLifecycleState = "Updating" + // AutonomousDatabaseLifecycleStateUpgrading - Indicates that resource in Upgrading state + AutonomousDatabaseLifecycleStateUpgrading AutonomousDatabaseLifecycleState = "Upgrading" +) + +// PossibleAutonomousDatabaseLifecycleStateValues returns the possible values for the AutonomousDatabaseLifecycleState const type. +func PossibleAutonomousDatabaseLifecycleStateValues() []AutonomousDatabaseLifecycleState { + return []AutonomousDatabaseLifecycleState{ + AutonomousDatabaseLifecycleStateAvailable, + AutonomousDatabaseLifecycleStateAvailableNeedsAttention, + AutonomousDatabaseLifecycleStateBackupInProgress, + AutonomousDatabaseLifecycleStateInaccessible, + AutonomousDatabaseLifecycleStateMaintenanceInProgress, + AutonomousDatabaseLifecycleStateProvisioning, + AutonomousDatabaseLifecycleStateRecreating, + AutonomousDatabaseLifecycleStateRestarting, + AutonomousDatabaseLifecycleStateRestoreFailed, + AutonomousDatabaseLifecycleStateRestoreInProgress, + AutonomousDatabaseLifecycleStateRoleChangeInProgress, + AutonomousDatabaseLifecycleStateScaleInProgress, + AutonomousDatabaseLifecycleStateStandby, + AutonomousDatabaseLifecycleStateStarting, + AutonomousDatabaseLifecycleStateStopped, + AutonomousDatabaseLifecycleStateStopping, + AutonomousDatabaseLifecycleStateTerminated, + AutonomousDatabaseLifecycleStateTerminating, + AutonomousDatabaseLifecycleStateUnavailable, + AutonomousDatabaseLifecycleStateUpdating, + AutonomousDatabaseLifecycleStateUpgrading, + } +} + +// AutonomousMaintenanceScheduleType - Autonomous database maintenance schedule type enum. +type AutonomousMaintenanceScheduleType string + +const ( + // AutonomousMaintenanceScheduleTypeEarly - Early maintenance schedule + AutonomousMaintenanceScheduleTypeEarly AutonomousMaintenanceScheduleType = "Early" + // AutonomousMaintenanceScheduleTypeRegular - Regular maintenance schedule + AutonomousMaintenanceScheduleTypeRegular AutonomousMaintenanceScheduleType = "Regular" +) + +// PossibleAutonomousMaintenanceScheduleTypeValues returns the possible values for the AutonomousMaintenanceScheduleType const type. +func PossibleAutonomousMaintenanceScheduleTypeValues() []AutonomousMaintenanceScheduleType { + return []AutonomousMaintenanceScheduleType{ + AutonomousMaintenanceScheduleTypeEarly, + AutonomousMaintenanceScheduleTypeRegular, + } +} + +// AzureResourceProvisioningState - Azure Resource Provisioning State enum +type AzureResourceProvisioningState string + +const ( + // AzureResourceProvisioningStateCanceled - Resource creation was canceled. + AzureResourceProvisioningStateCanceled AzureResourceProvisioningState = "Canceled" + // AzureResourceProvisioningStateFailed - Resource creation failed. + AzureResourceProvisioningStateFailed AzureResourceProvisioningState = "Failed" + // AzureResourceProvisioningStateProvisioning - Indicates that resource in Provisioning state + AzureResourceProvisioningStateProvisioning AzureResourceProvisioningState = "Provisioning" + // AzureResourceProvisioningStateSucceeded - Resource has been created. + AzureResourceProvisioningStateSucceeded AzureResourceProvisioningState = "Succeeded" +) + +// PossibleAzureResourceProvisioningStateValues returns the possible values for the AzureResourceProvisioningState const type. +func PossibleAzureResourceProvisioningStateValues() []AzureResourceProvisioningState { + return []AzureResourceProvisioningState{ + AzureResourceProvisioningStateCanceled, + AzureResourceProvisioningStateFailed, + AzureResourceProvisioningStateProvisioning, + AzureResourceProvisioningStateSucceeded, + } +} + +// BaseDbSystemShapes - Allowed values for BaseDb System Shapes +type BaseDbSystemShapes string + +const ( + // BaseDbSystemShapesVMStandardX86 - Vm Standard X86 + BaseDbSystemShapesVMStandardX86 BaseDbSystemShapes = "VM.Standard.x86" +) + +// PossibleBaseDbSystemShapesValues returns the possible values for the BaseDbSystemShapes const type. +func PossibleBaseDbSystemShapesValues() []BaseDbSystemShapes { + return []BaseDbSystemShapes{ + BaseDbSystemShapesVMStandardX86, + } +} + +// CloneType - Clone type enum +type CloneType string + +const ( + // CloneTypeFull - Full clone + CloneTypeFull CloneType = "Full" + // CloneTypeMetadata - Metadata only + CloneTypeMetadata CloneType = "Metadata" +) + +// PossibleCloneTypeValues returns the possible values for the CloneType const type. +func PossibleCloneTypeValues() []CloneType { + return []CloneType{ + CloneTypeFull, + CloneTypeMetadata, + } +} + +// CloudAccountProvisioningState - CloudAccountProvisioningState enum +type CloudAccountProvisioningState string + +const ( + // CloudAccountProvisioningStateAvailable - Available - State when Oracle cloud account cloud linking is complete and it is + // available + CloudAccountProvisioningStateAvailable CloudAccountProvisioningState = "Available" + // CloudAccountProvisioningStatePending - Pending - Initial state when Oracle cloud account is not configured + CloudAccountProvisioningStatePending CloudAccountProvisioningState = "Pending" + // CloudAccountProvisioningStateProvisioning - Provisioning - State when Oracle cloud account is being provisioned + CloudAccountProvisioningStateProvisioning CloudAccountProvisioningState = "Provisioning" +) + +// PossibleCloudAccountProvisioningStateValues returns the possible values for the CloudAccountProvisioningState const type. +func PossibleCloudAccountProvisioningStateValues() []CloudAccountProvisioningState { + return []CloudAccountProvisioningState{ + CloudAccountProvisioningStateAvailable, + CloudAccountProvisioningStatePending, + CloudAccountProvisioningStateProvisioning, + } +} + +// CloudExadataInfrastructureLifecycleState - CloudExadataInfrastructureLifecycleState enum +type CloudExadataInfrastructureLifecycleState string + +const ( + // CloudExadataInfrastructureLifecycleStateAvailable - Indicates that resource in Available state + CloudExadataInfrastructureLifecycleStateAvailable CloudExadataInfrastructureLifecycleState = "Available" + // CloudExadataInfrastructureLifecycleStateFailed - Indicates that resource in Failed state + CloudExadataInfrastructureLifecycleStateFailed CloudExadataInfrastructureLifecycleState = "Failed" + // CloudExadataInfrastructureLifecycleStateMaintenanceInProgress - Indicates that resource maintenance in progress state + CloudExadataInfrastructureLifecycleStateMaintenanceInProgress CloudExadataInfrastructureLifecycleState = "MaintenanceInProgress" + // CloudExadataInfrastructureLifecycleStateProvisioning - Indicates that resource in Provisioning state + CloudExadataInfrastructureLifecycleStateProvisioning CloudExadataInfrastructureLifecycleState = "Provisioning" + // CloudExadataInfrastructureLifecycleStateTerminated - Indicates that resource in Terminated state + CloudExadataInfrastructureLifecycleStateTerminated CloudExadataInfrastructureLifecycleState = "Terminated" + // CloudExadataInfrastructureLifecycleStateTerminating - Indicates that resource in Terminating state + CloudExadataInfrastructureLifecycleStateTerminating CloudExadataInfrastructureLifecycleState = "Terminating" + // CloudExadataInfrastructureLifecycleStateUpdating - Indicates that resource in Updating state + CloudExadataInfrastructureLifecycleStateUpdating CloudExadataInfrastructureLifecycleState = "Updating" +) + +// PossibleCloudExadataInfrastructureLifecycleStateValues returns the possible values for the CloudExadataInfrastructureLifecycleState const type. +func PossibleCloudExadataInfrastructureLifecycleStateValues() []CloudExadataInfrastructureLifecycleState { + return []CloudExadataInfrastructureLifecycleState{ + CloudExadataInfrastructureLifecycleStateAvailable, + CloudExadataInfrastructureLifecycleStateFailed, + CloudExadataInfrastructureLifecycleStateMaintenanceInProgress, + CloudExadataInfrastructureLifecycleStateProvisioning, + CloudExadataInfrastructureLifecycleStateTerminated, + CloudExadataInfrastructureLifecycleStateTerminating, + CloudExadataInfrastructureLifecycleStateUpdating, + } +} + +// CloudVMClusterLifecycleState - Cloud VM Cluster lifecycle state enum +type CloudVMClusterLifecycleState string + +const ( + // CloudVMClusterLifecycleStateAvailable - Indicates that resource in Available state + CloudVMClusterLifecycleStateAvailable CloudVMClusterLifecycleState = "Available" + // CloudVMClusterLifecycleStateFailed - Indicates that resource in Failed state + CloudVMClusterLifecycleStateFailed CloudVMClusterLifecycleState = "Failed" + // CloudVMClusterLifecycleStateMaintenanceInProgress - Indicates that resource Maintenance in progress state + CloudVMClusterLifecycleStateMaintenanceInProgress CloudVMClusterLifecycleState = "MaintenanceInProgress" + // CloudVMClusterLifecycleStateProvisioning - Indicates that resource in Provisioning state + CloudVMClusterLifecycleStateProvisioning CloudVMClusterLifecycleState = "Provisioning" + // CloudVMClusterLifecycleStateTerminated - Indicates that resource in Terminated state + CloudVMClusterLifecycleStateTerminated CloudVMClusterLifecycleState = "Terminated" + // CloudVMClusterLifecycleStateTerminating - Indicates that resource in Terminating state + CloudVMClusterLifecycleStateTerminating CloudVMClusterLifecycleState = "Terminating" + // CloudVMClusterLifecycleStateUpdating - Indicates that resource in Updating state + CloudVMClusterLifecycleStateUpdating CloudVMClusterLifecycleState = "Updating" +) + +// PossibleCloudVMClusterLifecycleStateValues returns the possible values for the CloudVMClusterLifecycleState const type. +func PossibleCloudVMClusterLifecycleStateValues() []CloudVMClusterLifecycleState { + return []CloudVMClusterLifecycleState{ + CloudVMClusterLifecycleStateAvailable, + CloudVMClusterLifecycleStateFailed, + CloudVMClusterLifecycleStateMaintenanceInProgress, + CloudVMClusterLifecycleStateProvisioning, + CloudVMClusterLifecycleStateTerminated, + CloudVMClusterLifecycleStateTerminating, + CloudVMClusterLifecycleStateUpdating, + } +} + +// ComputeModel - Compute model enum +type ComputeModel string + +const ( + // ComputeModelECPU - ECPU model type + ComputeModelECPU ComputeModel = "ECPU" + // ComputeModelOCPU - OCPU model type + ComputeModelOCPU ComputeModel = "OCPU" +) + +// PossibleComputeModelValues returns the possible values for the ComputeModel const type. +func PossibleComputeModelValues() []ComputeModel { + return []ComputeModel{ + ComputeModelECPU, + ComputeModelOCPU, + } +} + +// ConsumerGroup - Consumer group enum. +type ConsumerGroup string + +const ( + // ConsumerGroupHigh - High group + ConsumerGroupHigh ConsumerGroup = "High" + // ConsumerGroupLow - Low group + ConsumerGroupLow ConsumerGroup = "Low" + // ConsumerGroupMedium - Medium group + ConsumerGroupMedium ConsumerGroup = "Medium" + // ConsumerGroupTp - TP group + ConsumerGroupTp ConsumerGroup = "Tp" + // ConsumerGroupTpurgent - TPurgent group + ConsumerGroupTpurgent ConsumerGroup = "Tpurgent" +) + +// PossibleConsumerGroupValues returns the possible values for the ConsumerGroup const type. +func PossibleConsumerGroupValues() []ConsumerGroup { + return []ConsumerGroup{ + ConsumerGroupHigh, + ConsumerGroupLow, + ConsumerGroupMedium, + ConsumerGroupTp, + ConsumerGroupTpurgent, + } +} + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// DNSPrivateViewsLifecycleState - DNS Private Views lifecycle state enum +type DNSPrivateViewsLifecycleState string + +const ( + // DNSPrivateViewsLifecycleStateActive - DNS Private View is active + DNSPrivateViewsLifecycleStateActive DNSPrivateViewsLifecycleState = "Active" + // DNSPrivateViewsLifecycleStateDeleted - DNS Private View is deleted + DNSPrivateViewsLifecycleStateDeleted DNSPrivateViewsLifecycleState = "Deleted" + // DNSPrivateViewsLifecycleStateDeleting - DNS Private View is deleting + DNSPrivateViewsLifecycleStateDeleting DNSPrivateViewsLifecycleState = "Deleting" + // DNSPrivateViewsLifecycleStateUpdating - DNS Private View is updating + DNSPrivateViewsLifecycleStateUpdating DNSPrivateViewsLifecycleState = "Updating" +) + +// PossibleDNSPrivateViewsLifecycleStateValues returns the possible values for the DNSPrivateViewsLifecycleState const type. +func PossibleDNSPrivateViewsLifecycleStateValues() []DNSPrivateViewsLifecycleState { + return []DNSPrivateViewsLifecycleState{ + DNSPrivateViewsLifecycleStateActive, + DNSPrivateViewsLifecycleStateDeleted, + DNSPrivateViewsLifecycleStateDeleting, + DNSPrivateViewsLifecycleStateUpdating, + } +} + +// DNSPrivateZonesLifecycleState - DNS Private Zones lifecycle state enum +type DNSPrivateZonesLifecycleState string + +const ( + // DNSPrivateZonesLifecycleStateActive - DNS Private Zones is active + DNSPrivateZonesLifecycleStateActive DNSPrivateZonesLifecycleState = "Active" + // DNSPrivateZonesLifecycleStateCreating - DNS Private Zones is creating + DNSPrivateZonesLifecycleStateCreating DNSPrivateZonesLifecycleState = "Creating" + // DNSPrivateZonesLifecycleStateDeleted - DNS Private Zones is deleted + DNSPrivateZonesLifecycleStateDeleted DNSPrivateZonesLifecycleState = "Deleted" + // DNSPrivateZonesLifecycleStateDeleting - DNS Private Zones is deleting + DNSPrivateZonesLifecycleStateDeleting DNSPrivateZonesLifecycleState = "Deleting" + // DNSPrivateZonesLifecycleStateUpdating - DNS Private Zones is updating + DNSPrivateZonesLifecycleStateUpdating DNSPrivateZonesLifecycleState = "Updating" +) + +// PossibleDNSPrivateZonesLifecycleStateValues returns the possible values for the DNSPrivateZonesLifecycleState const type. +func PossibleDNSPrivateZonesLifecycleStateValues() []DNSPrivateZonesLifecycleState { + return []DNSPrivateZonesLifecycleState{ + DNSPrivateZonesLifecycleStateActive, + DNSPrivateZonesLifecycleStateCreating, + DNSPrivateZonesLifecycleStateDeleted, + DNSPrivateZonesLifecycleStateDeleting, + DNSPrivateZonesLifecycleStateUpdating, + } +} + +// DataBaseType - Database type enum +type DataBaseType string + +const ( + // DataBaseTypeClone - Clone DB + DataBaseTypeClone DataBaseType = "Clone" + // DataBaseTypeCloneFromBackupTimestamp - Clone DB from backup timestamp + DataBaseTypeCloneFromBackupTimestamp DataBaseType = "CloneFromBackupTimestamp" + // DataBaseTypeCrossRegionDisasterRecovery - Cross Region Disaster Recovery + DataBaseTypeCrossRegionDisasterRecovery DataBaseType = "CrossRegionDisasterRecovery" + // DataBaseTypeRegular - Regular DB + DataBaseTypeRegular DataBaseType = "Regular" +) + +// PossibleDataBaseTypeValues returns the possible values for the DataBaseType const type. +func PossibleDataBaseTypeValues() []DataBaseType { + return []DataBaseType{ + DataBaseTypeClone, + DataBaseTypeCloneFromBackupTimestamp, + DataBaseTypeCrossRegionDisasterRecovery, + DataBaseTypeRegular, + } +} + +// DataSafeStatusType - DataSafe status type enum. +type DataSafeStatusType string + +const ( + // DataSafeStatusTypeDeregistering - Deregistering status + DataSafeStatusTypeDeregistering DataSafeStatusType = "Deregistering" + // DataSafeStatusTypeFailed - Failed status + DataSafeStatusTypeFailed DataSafeStatusType = "Failed" + // DataSafeStatusTypeNotRegistered - NotRegistered status + DataSafeStatusTypeNotRegistered DataSafeStatusType = "NotRegistered" + // DataSafeStatusTypeRegistered - Registered status + DataSafeStatusTypeRegistered DataSafeStatusType = "Registered" + // DataSafeStatusTypeRegistering - Registering status + DataSafeStatusTypeRegistering DataSafeStatusType = "Registering" +) + +// PossibleDataSafeStatusTypeValues returns the possible values for the DataSafeStatusType const type. +func PossibleDataSafeStatusTypeValues() []DataSafeStatusType { + return []DataSafeStatusType{ + DataSafeStatusTypeDeregistering, + DataSafeStatusTypeFailed, + DataSafeStatusTypeNotRegistered, + DataSafeStatusTypeRegistered, + DataSafeStatusTypeRegistering, + } +} + +// DatabaseEditionType - Database edition type enum. +type DatabaseEditionType string + +const ( + // DatabaseEditionTypeEnterpriseEdition - Enterprise edition + DatabaseEditionTypeEnterpriseEdition DatabaseEditionType = "EnterpriseEdition" + // DatabaseEditionTypeStandardEdition - Standard edition + DatabaseEditionTypeStandardEdition DatabaseEditionType = "StandardEdition" +) + +// PossibleDatabaseEditionTypeValues returns the possible values for the DatabaseEditionType const type. +func PossibleDatabaseEditionTypeValues() []DatabaseEditionType { + return []DatabaseEditionType{ + DatabaseEditionTypeEnterpriseEdition, + DatabaseEditionTypeStandardEdition, + } +} + +// DayOfWeekName - DayOfWeekName enum +type DayOfWeekName string + +const ( + // DayOfWeekNameFriday - Friday value + DayOfWeekNameFriday DayOfWeekName = "Friday" + // DayOfWeekNameMonday - Monday value + DayOfWeekNameMonday DayOfWeekName = "Monday" + // DayOfWeekNameSaturday - Saturday value + DayOfWeekNameSaturday DayOfWeekName = "Saturday" + // DayOfWeekNameSunday - Sunday value + DayOfWeekNameSunday DayOfWeekName = "Sunday" + // DayOfWeekNameThursday - Thursday value + DayOfWeekNameThursday DayOfWeekName = "Thursday" + // DayOfWeekNameTuesday - Tuesday value + DayOfWeekNameTuesday DayOfWeekName = "Tuesday" + // DayOfWeekNameWednesday - Wednesday value + DayOfWeekNameWednesday DayOfWeekName = "Wednesday" +) + +// PossibleDayOfWeekNameValues returns the possible values for the DayOfWeekName const type. +func PossibleDayOfWeekNameValues() []DayOfWeekName { + return []DayOfWeekName{ + DayOfWeekNameFriday, + DayOfWeekNameMonday, + DayOfWeekNameSaturday, + DayOfWeekNameSunday, + DayOfWeekNameThursday, + DayOfWeekNameTuesday, + DayOfWeekNameWednesday, + } +} + +// DbNodeActionEnum - DbNode action enum +type DbNodeActionEnum string + +const ( + // DbNodeActionEnumReset - Reset DbNode + DbNodeActionEnumReset DbNodeActionEnum = "Reset" + // DbNodeActionEnumSoftReset - Soft reset DbNode + DbNodeActionEnumSoftReset DbNodeActionEnum = "SoftReset" + // DbNodeActionEnumStart - Start DbNode + DbNodeActionEnumStart DbNodeActionEnum = "Start" + // DbNodeActionEnumStop - Stop DbNode + DbNodeActionEnumStop DbNodeActionEnum = "Stop" +) + +// PossibleDbNodeActionEnumValues returns the possible values for the DbNodeActionEnum const type. +func PossibleDbNodeActionEnumValues() []DbNodeActionEnum { + return []DbNodeActionEnum{ + DbNodeActionEnumReset, + DbNodeActionEnumSoftReset, + DbNodeActionEnumStart, + DbNodeActionEnumStop, + } +} + +// DbNodeMaintenanceType - The type of database node maintenance. +type DbNodeMaintenanceType string + +const ( + // DbNodeMaintenanceTypeVmdbRebootMigration - VMDB reboot migration maintenance type + DbNodeMaintenanceTypeVmdbRebootMigration DbNodeMaintenanceType = "VmdbRebootMigration" +) + +// PossibleDbNodeMaintenanceTypeValues returns the possible values for the DbNodeMaintenanceType const type. +func PossibleDbNodeMaintenanceTypeValues() []DbNodeMaintenanceType { + return []DbNodeMaintenanceType{ + DbNodeMaintenanceTypeVmdbRebootMigration, + } +} + +// DbNodeProvisioningState - DnNode provisioning state enum +type DbNodeProvisioningState string + +const ( + // DbNodeProvisioningStateAvailable - Indicates that resource in Available state + DbNodeProvisioningStateAvailable DbNodeProvisioningState = "Available" + // DbNodeProvisioningStateFailed - Indicates that resource in Failed state + DbNodeProvisioningStateFailed DbNodeProvisioningState = "Failed" + // DbNodeProvisioningStateProvisioning - Indicates that resource in Provisioning state + DbNodeProvisioningStateProvisioning DbNodeProvisioningState = "Provisioning" + // DbNodeProvisioningStateStarting - Indicates that resource in Starting state + DbNodeProvisioningStateStarting DbNodeProvisioningState = "Starting" + // DbNodeProvisioningStateStopped - Indicates that resource in Stopped state + DbNodeProvisioningStateStopped DbNodeProvisioningState = "Stopped" + // DbNodeProvisioningStateStopping - Indicates that resource in Stopping state + DbNodeProvisioningStateStopping DbNodeProvisioningState = "Stopping" + // DbNodeProvisioningStateTerminated - Indicates that resource in Terminated state + DbNodeProvisioningStateTerminated DbNodeProvisioningState = "Terminated" + // DbNodeProvisioningStateTerminating - Indicates that resource in Terminating state + DbNodeProvisioningStateTerminating DbNodeProvisioningState = "Terminating" + // DbNodeProvisioningStateUpdating - Indicates that resource in Updating state + DbNodeProvisioningStateUpdating DbNodeProvisioningState = "Updating" +) + +// PossibleDbNodeProvisioningStateValues returns the possible values for the DbNodeProvisioningState const type. +func PossibleDbNodeProvisioningStateValues() []DbNodeProvisioningState { + return []DbNodeProvisioningState{ + DbNodeProvisioningStateAvailable, + DbNodeProvisioningStateFailed, + DbNodeProvisioningStateProvisioning, + DbNodeProvisioningStateStarting, + DbNodeProvisioningStateStopped, + DbNodeProvisioningStateStopping, + DbNodeProvisioningStateTerminated, + DbNodeProvisioningStateTerminating, + DbNodeProvisioningStateUpdating, + } +} + +// DbServerPatchingStatus - DB Server patching status enum +type DbServerPatchingStatus string + +const ( + // DbServerPatchingStatusComplete - Patching completed + DbServerPatchingStatusComplete DbServerPatchingStatus = "Complete" + // DbServerPatchingStatusFailed - Patching failed + DbServerPatchingStatusFailed DbServerPatchingStatus = "Failed" + // DbServerPatchingStatusMaintenanceInProgress - Patching in progress + DbServerPatchingStatusMaintenanceInProgress DbServerPatchingStatus = "MaintenanceInProgress" + // DbServerPatchingStatusScheduled - Patching scheduled + DbServerPatchingStatusScheduled DbServerPatchingStatus = "Scheduled" +) + +// PossibleDbServerPatchingStatusValues returns the possible values for the DbServerPatchingStatus const type. +func PossibleDbServerPatchingStatusValues() []DbServerPatchingStatus { + return []DbServerPatchingStatus{ + DbServerPatchingStatusComplete, + DbServerPatchingStatusFailed, + DbServerPatchingStatusMaintenanceInProgress, + DbServerPatchingStatusScheduled, + } +} + +// DbServerProvisioningState - DbServerProvisioningState enum +type DbServerProvisioningState string + +const ( + // DbServerProvisioningStateAvailable - Indicates that resource in Available state + DbServerProvisioningStateAvailable DbServerProvisioningState = "Available" + // DbServerProvisioningStateCreating - Indicates that resource in Creating state + DbServerProvisioningStateCreating DbServerProvisioningState = "Creating" + // DbServerProvisioningStateDeleted - Indicates that resource in Deleted state + DbServerProvisioningStateDeleted DbServerProvisioningState = "Deleted" + // DbServerProvisioningStateDeleting - Indicates that resource in Deleting state + DbServerProvisioningStateDeleting DbServerProvisioningState = "Deleting" + // DbServerProvisioningStateMaintenanceInProgress - Indicates that resource maintenance in progress state + DbServerProvisioningStateMaintenanceInProgress DbServerProvisioningState = "MaintenanceInProgress" + // DbServerProvisioningStateUnavailable - Indicates that resource in Unavailable state + DbServerProvisioningStateUnavailable DbServerProvisioningState = "Unavailable" +) + +// PossibleDbServerProvisioningStateValues returns the possible values for the DbServerProvisioningState const type. +func PossibleDbServerProvisioningStateValues() []DbServerProvisioningState { + return []DbServerProvisioningState{ + DbServerProvisioningStateAvailable, + DbServerProvisioningStateCreating, + DbServerProvisioningStateDeleted, + DbServerProvisioningStateDeleting, + DbServerProvisioningStateMaintenanceInProgress, + DbServerProvisioningStateUnavailable, + } +} + +// DbSystemDatabaseEditionType - Database edition type enum. +type DbSystemDatabaseEditionType string + +const ( + // DbSystemDatabaseEditionTypeEnterpriseEdition - Enterprise edition + DbSystemDatabaseEditionTypeEnterpriseEdition DbSystemDatabaseEditionType = "EnterpriseEdition" + // DbSystemDatabaseEditionTypeEnterpriseEditionDeveloper - Enterprise edition developer + DbSystemDatabaseEditionTypeEnterpriseEditionDeveloper DbSystemDatabaseEditionType = "EnterpriseEditionDeveloper" + // DbSystemDatabaseEditionTypeEnterpriseEditionExtreme - Enterprise edition extreme + DbSystemDatabaseEditionTypeEnterpriseEditionExtreme DbSystemDatabaseEditionType = "EnterpriseEditionExtreme" + // DbSystemDatabaseEditionTypeEnterpriseEditionHighPerformance - Enterprise edition high performance + DbSystemDatabaseEditionTypeEnterpriseEditionHighPerformance DbSystemDatabaseEditionType = "EnterpriseEditionHighPerformance" + // DbSystemDatabaseEditionTypeStandardEdition - Standard edition + DbSystemDatabaseEditionTypeStandardEdition DbSystemDatabaseEditionType = "StandardEdition" +) + +// PossibleDbSystemDatabaseEditionTypeValues returns the possible values for the DbSystemDatabaseEditionType const type. +func PossibleDbSystemDatabaseEditionTypeValues() []DbSystemDatabaseEditionType { + return []DbSystemDatabaseEditionType{ + DbSystemDatabaseEditionTypeEnterpriseEdition, + DbSystemDatabaseEditionTypeEnterpriseEditionDeveloper, + DbSystemDatabaseEditionTypeEnterpriseEditionExtreme, + DbSystemDatabaseEditionTypeEnterpriseEditionHighPerformance, + DbSystemDatabaseEditionTypeStandardEdition, + } +} + +// DbSystemLifecycleState - DB System lifecycle state enum +type DbSystemLifecycleState string + +const ( + // DbSystemLifecycleStateAvailable - Indicates that resource in Available state + DbSystemLifecycleStateAvailable DbSystemLifecycleState = "Available" + // DbSystemLifecycleStateFailed - Indicates that resource in Failed state + DbSystemLifecycleStateFailed DbSystemLifecycleState = "Failed" + // DbSystemLifecycleStateMaintenanceInProgress - Indicates that resource maintenance in progress state + DbSystemLifecycleStateMaintenanceInProgress DbSystemLifecycleState = "MaintenanceInProgress" + // DbSystemLifecycleStateMigrated - Indicates that resource is Migrated state + DbSystemLifecycleStateMigrated DbSystemLifecycleState = "Migrated" + // DbSystemLifecycleStateNeedsAttention - Indicates that resource needs attention state + DbSystemLifecycleStateNeedsAttention DbSystemLifecycleState = "NeedsAttention" + // DbSystemLifecycleStateProvisioning - Indicates that resource in Provisioning state + DbSystemLifecycleStateProvisioning DbSystemLifecycleState = "Provisioning" + // DbSystemLifecycleStateTerminated - Indicates that resource in Terminated state + DbSystemLifecycleStateTerminated DbSystemLifecycleState = "Terminated" + // DbSystemLifecycleStateTerminating - Indicates that resource in Terminating state + DbSystemLifecycleStateTerminating DbSystemLifecycleState = "Terminating" + // DbSystemLifecycleStateUpdating - Indicates that resource in Updating state + DbSystemLifecycleStateUpdating DbSystemLifecycleState = "Updating" + // DbSystemLifecycleStateUpgrading - Indicates that resource in Upgrading state + DbSystemLifecycleStateUpgrading DbSystemLifecycleState = "Upgrading" +) + +// PossibleDbSystemLifecycleStateValues returns the possible values for the DbSystemLifecycleState const type. +func PossibleDbSystemLifecycleStateValues() []DbSystemLifecycleState { + return []DbSystemLifecycleState{ + DbSystemLifecycleStateAvailable, + DbSystemLifecycleStateFailed, + DbSystemLifecycleStateMaintenanceInProgress, + DbSystemLifecycleStateMigrated, + DbSystemLifecycleStateNeedsAttention, + DbSystemLifecycleStateProvisioning, + DbSystemLifecycleStateTerminated, + DbSystemLifecycleStateTerminating, + DbSystemLifecycleStateUpdating, + DbSystemLifecycleStateUpgrading, + } +} + +// DbSystemSourceType - The DbSystem source type of the database. +type DbSystemSourceType string + +const ( + // DbSystemSourceTypeNone - for creating a new database. + DbSystemSourceTypeNone DbSystemSourceType = "None" +) + +// PossibleDbSystemSourceTypeValues returns the possible values for the DbSystemSourceType const type. +func PossibleDbSystemSourceTypeValues() []DbSystemSourceType { + return []DbSystemSourceType{ + DbSystemSourceTypeNone, + } +} + +// DisasterRecoveryType - Disaster recovery type enum. +type DisasterRecoveryType string + +const ( + // DisasterRecoveryTypeAdg - ADG type + DisasterRecoveryTypeAdg DisasterRecoveryType = "Adg" + // DisasterRecoveryTypeBackupBased - Backup based type + DisasterRecoveryTypeBackupBased DisasterRecoveryType = "BackupBased" +) + +// PossibleDisasterRecoveryTypeValues returns the possible values for the DisasterRecoveryType const type. +func PossibleDisasterRecoveryTypeValues() []DisasterRecoveryType { + return []DisasterRecoveryType{ + DisasterRecoveryTypeAdg, + DisasterRecoveryTypeBackupBased, + } +} + +// DiskRedundancy - Disk redundancy enum +type DiskRedundancy string + +const ( + // DiskRedundancyHigh - High redundancy + DiskRedundancyHigh DiskRedundancy = "High" + // DiskRedundancyNormal - Normal redundancy + DiskRedundancyNormal DiskRedundancy = "Normal" +) + +// PossibleDiskRedundancyValues returns the possible values for the DiskRedundancy const type. +func PossibleDiskRedundancyValues() []DiskRedundancy { + return []DiskRedundancy{ + DiskRedundancyHigh, + DiskRedundancyNormal, + } +} + +// DiskRedundancyType - Disk redundancy type enum. +type DiskRedundancyType string + +const ( + // DiskRedundancyTypeHigh - 3-way redundancy. + DiskRedundancyTypeHigh DiskRedundancyType = "High" + // DiskRedundancyTypeNormal - 2-way redundancy. + DiskRedundancyTypeNormal DiskRedundancyType = "Normal" +) + +// PossibleDiskRedundancyTypeValues returns the possible values for the DiskRedundancyType const type. +func PossibleDiskRedundancyTypeValues() []DiskRedundancyType { + return []DiskRedundancyType{ + DiskRedundancyTypeHigh, + DiskRedundancyTypeNormal, + } +} + +// ExadataVMClusterStorageManagementType - Specifies the type of storage management for the Cloud VM Cluster if its ASM or +// Exascale. +type ExadataVMClusterStorageManagementType string + +const ( + // ExadataVMClusterStorageManagementTypeASM - Indicates that storage management for the Cloud VM Cluster is ASM + ExadataVMClusterStorageManagementTypeASM ExadataVMClusterStorageManagementType = "ASM" + // ExadataVMClusterStorageManagementTypeExascale - Indicates that storage management for the Cloud VM Cluster is Exascale + ExadataVMClusterStorageManagementTypeExascale ExadataVMClusterStorageManagementType = "Exascale" +) + +// PossibleExadataVMClusterStorageManagementTypeValues returns the possible values for the ExadataVMClusterStorageManagementType const type. +func PossibleExadataVMClusterStorageManagementTypeValues() []ExadataVMClusterStorageManagementType { + return []ExadataVMClusterStorageManagementType{ + ExadataVMClusterStorageManagementTypeASM, + ExadataVMClusterStorageManagementTypeExascale, + } +} + +// ExadbVMClusterLifecycleState - Exadata VM cluster on Exascale Infrastructure lifecycle state enum +type ExadbVMClusterLifecycleState string + +const ( + // ExadbVMClusterLifecycleStateAvailable - Indicates that resource in Available state + ExadbVMClusterLifecycleStateAvailable ExadbVMClusterLifecycleState = "Available" + // ExadbVMClusterLifecycleStateFailed - Indicates that resource in Failed state + ExadbVMClusterLifecycleStateFailed ExadbVMClusterLifecycleState = "Failed" + // ExadbVMClusterLifecycleStateMaintenanceInProgress - Indicates that resource Maintenance in progress state + ExadbVMClusterLifecycleStateMaintenanceInProgress ExadbVMClusterLifecycleState = "MaintenanceInProgress" + // ExadbVMClusterLifecycleStateProvisioning - Indicates that resource in Provisioning state + ExadbVMClusterLifecycleStateProvisioning ExadbVMClusterLifecycleState = "Provisioning" + // ExadbVMClusterLifecycleStateTerminated - Indicates that resource in Terminated state + ExadbVMClusterLifecycleStateTerminated ExadbVMClusterLifecycleState = "Terminated" + // ExadbVMClusterLifecycleStateTerminating - Indicates that resource in Terminating state + ExadbVMClusterLifecycleStateTerminating ExadbVMClusterLifecycleState = "Terminating" + // ExadbVMClusterLifecycleStateUpdating - Indicates that resource in Updating state + ExadbVMClusterLifecycleStateUpdating ExadbVMClusterLifecycleState = "Updating" +) + +// PossibleExadbVMClusterLifecycleStateValues returns the possible values for the ExadbVMClusterLifecycleState const type. +func PossibleExadbVMClusterLifecycleStateValues() []ExadbVMClusterLifecycleState { + return []ExadbVMClusterLifecycleState{ + ExadbVMClusterLifecycleStateAvailable, + ExadbVMClusterLifecycleStateFailed, + ExadbVMClusterLifecycleStateMaintenanceInProgress, + ExadbVMClusterLifecycleStateProvisioning, + ExadbVMClusterLifecycleStateTerminated, + ExadbVMClusterLifecycleStateTerminating, + ExadbVMClusterLifecycleStateUpdating, + } +} + +// ExascaleDbStorageVaultLifecycleState - Exadata Database Storage Vault lifecycle state enum +type ExascaleDbStorageVaultLifecycleState string + +const ( + // ExascaleDbStorageVaultLifecycleStateAvailable - Indicates that resource in Available state + ExascaleDbStorageVaultLifecycleStateAvailable ExascaleDbStorageVaultLifecycleState = "Available" + // ExascaleDbStorageVaultLifecycleStateFailed - Indicates that resource in Failed state + ExascaleDbStorageVaultLifecycleStateFailed ExascaleDbStorageVaultLifecycleState = "Failed" + // ExascaleDbStorageVaultLifecycleStateProvisioning - Indicates that resource in Provisioning state + ExascaleDbStorageVaultLifecycleStateProvisioning ExascaleDbStorageVaultLifecycleState = "Provisioning" + // ExascaleDbStorageVaultLifecycleStateTerminated - Indicates that resource in Terminated state + ExascaleDbStorageVaultLifecycleStateTerminated ExascaleDbStorageVaultLifecycleState = "Terminated" + // ExascaleDbStorageVaultLifecycleStateTerminating - Indicates that resource in Terminating state + ExascaleDbStorageVaultLifecycleStateTerminating ExascaleDbStorageVaultLifecycleState = "Terminating" + // ExascaleDbStorageVaultLifecycleStateUpdating - Indicates that resource in Updating state + ExascaleDbStorageVaultLifecycleStateUpdating ExascaleDbStorageVaultLifecycleState = "Updating" +) + +// PossibleExascaleDbStorageVaultLifecycleStateValues returns the possible values for the ExascaleDbStorageVaultLifecycleState const type. +func PossibleExascaleDbStorageVaultLifecycleStateValues() []ExascaleDbStorageVaultLifecycleState { + return []ExascaleDbStorageVaultLifecycleState{ + ExascaleDbStorageVaultLifecycleStateAvailable, + ExascaleDbStorageVaultLifecycleStateFailed, + ExascaleDbStorageVaultLifecycleStateProvisioning, + ExascaleDbStorageVaultLifecycleStateTerminated, + ExascaleDbStorageVaultLifecycleStateTerminating, + ExascaleDbStorageVaultLifecycleStateUpdating, + } +} + +// GenerateType - Generate type enum +type GenerateType string + +const ( + // GenerateTypeAll - Generate all + GenerateTypeAll GenerateType = "All" + // GenerateTypeSingle - Generate single + GenerateTypeSingle GenerateType = "Single" +) + +// PossibleGenerateTypeValues returns the possible values for the GenerateType const type. +func PossibleGenerateTypeValues() []GenerateType { + return []GenerateType{ + GenerateTypeAll, + GenerateTypeSingle, + } +} + +// GridImageType - GridImageType enum +type GridImageType string + +const ( + // GridImageTypeCustomImage - Custom image + GridImageTypeCustomImage GridImageType = "CustomImage" + // GridImageTypeReleaseUpdate - Release update + GridImageTypeReleaseUpdate GridImageType = "ReleaseUpdate" +) + +// PossibleGridImageTypeValues returns the possible values for the GridImageType const type. +func PossibleGridImageTypeValues() []GridImageType { + return []GridImageType{ + GridImageTypeCustomImage, + GridImageTypeReleaseUpdate, + } +} + +// HardwareType - Hardware Type enum +type HardwareType string + +const ( + // HardwareTypeCELL - Hardware type is Storage Server + HardwareTypeCELL HardwareType = "CELL" + // HardwareTypeCOMPUTE - Hardware type is Database Server + HardwareTypeCOMPUTE HardwareType = "COMPUTE" +) + +// PossibleHardwareTypeValues returns the possible values for the HardwareType const type. +func PossibleHardwareTypeValues() []HardwareType { + return []HardwareType{ + HardwareTypeCELL, + HardwareTypeCOMPUTE, + } +} + +// HostFormatType - Host format type enum. +type HostFormatType string + +const ( + // HostFormatTypeFqdn - FQDN format + HostFormatTypeFqdn HostFormatType = "Fqdn" + // HostFormatTypeIP - IP format + HostFormatTypeIP HostFormatType = "Ip" +) + +// PossibleHostFormatTypeValues returns the possible values for the HostFormatType const type. +func PossibleHostFormatTypeValues() []HostFormatType { + return []HostFormatType{ + HostFormatTypeFqdn, + HostFormatTypeIP, + } +} + +// Intent - Intent enum +type Intent string + +const ( + // IntentReset - Reset intent + IntentReset Intent = "Reset" + // IntentRetain - Retain intent + IntentRetain Intent = "Retain" +) + +// PossibleIntentValues returns the possible values for the Intent const type. +func PossibleIntentValues() []Intent { + return []Intent{ + IntentReset, + IntentRetain, + } +} + +// IormLifecycleState - ORM lifecycle state enum +type IormLifecycleState string + +const ( + // IormLifecycleStateBootStrapping - Indicates that resource in Provisioning state + IormLifecycleStateBootStrapping IormLifecycleState = "BootStrapping" + // IormLifecycleStateDisabled - Indicates that resource in Disabled state + IormLifecycleStateDisabled IormLifecycleState = "Disabled" + // IormLifecycleStateEnabled - Indicates that resource in Enabled state + IormLifecycleStateEnabled IormLifecycleState = "Enabled" + // IormLifecycleStateFailed - Indicates that resource in Failed state + IormLifecycleStateFailed IormLifecycleState = "Failed" + // IormLifecycleStateUpdating - Indicates that resource in Updating state + IormLifecycleStateUpdating IormLifecycleState = "Updating" +) + +// PossibleIormLifecycleStateValues returns the possible values for the IormLifecycleState const type. +func PossibleIormLifecycleStateValues() []IormLifecycleState { + return []IormLifecycleState{ + IormLifecycleStateBootStrapping, + IormLifecycleStateDisabled, + IormLifecycleStateEnabled, + IormLifecycleStateFailed, + IormLifecycleStateUpdating, + } +} + +// LicenseModel - LicenseModel enum +type LicenseModel string + +const ( + // LicenseModelBringYourOwnLicense - Bring Your Own License + LicenseModelBringYourOwnLicense LicenseModel = "BringYourOwnLicense" + // LicenseModelLicenseIncluded - License included + LicenseModelLicenseIncluded LicenseModel = "LicenseIncluded" +) + +// PossibleLicenseModelValues returns the possible values for the LicenseModel const type. +func PossibleLicenseModelValues() []LicenseModel { + return []LicenseModel{ + LicenseModelBringYourOwnLicense, + LicenseModelLicenseIncluded, + } +} + +// MonthName - MonthName enum +type MonthName string + +const ( + // MonthNameApril - April value + MonthNameApril MonthName = "April" + // MonthNameAugust - August value + MonthNameAugust MonthName = "August" + // MonthNameDecember - December value + MonthNameDecember MonthName = "December" + // MonthNameFebruary - February value + MonthNameFebruary MonthName = "February" + // MonthNameJanuary - January value + MonthNameJanuary MonthName = "January" + // MonthNameJuly - July value + MonthNameJuly MonthName = "July" + // MonthNameJune - June value + MonthNameJune MonthName = "June" + // MonthNameMarch - March value + MonthNameMarch MonthName = "March" + // MonthNameMay - May value + MonthNameMay MonthName = "May" + // MonthNameNovember - November value + MonthNameNovember MonthName = "November" + // MonthNameOctober - October value + MonthNameOctober MonthName = "October" + // MonthNameSeptember - September value + MonthNameSeptember MonthName = "September" +) + +// PossibleMonthNameValues returns the possible values for the MonthName const type. +func PossibleMonthNameValues() []MonthName { + return []MonthName{ + MonthNameApril, + MonthNameAugust, + MonthNameDecember, + MonthNameFebruary, + MonthNameJanuary, + MonthNameJuly, + MonthNameJune, + MonthNameMarch, + MonthNameMay, + MonthNameNovember, + MonthNameOctober, + MonthNameSeptember, + } +} + +// Objective - Objective enum +type Objective string + +const ( + // ObjectiveAuto - Auto objective + ObjectiveAuto Objective = "Auto" + // ObjectiveBalanced - Balanced objective + ObjectiveBalanced Objective = "Balanced" + // ObjectiveBasic - Basic objective + ObjectiveBasic Objective = "Basic" + // ObjectiveHighThroughput - High throughput objective + ObjectiveHighThroughput Objective = "HighThroughput" + // ObjectiveLowLatency - Low latency objective + ObjectiveLowLatency Objective = "LowLatency" +) + +// PossibleObjectiveValues returns the possible values for the Objective const type. +func PossibleObjectiveValues() []Objective { + return []Objective{ + ObjectiveAuto, + ObjectiveBalanced, + ObjectiveBasic, + ObjectiveHighThroughput, + ObjectiveLowLatency, + } +} + +// OpenModeType - Open mode type enum. +type OpenModeType string + +const ( + // OpenModeTypeReadOnly - ReadOnly mode + OpenModeTypeReadOnly OpenModeType = "ReadOnly" + // OpenModeTypeReadWrite - ReadWrite mode + OpenModeTypeReadWrite OpenModeType = "ReadWrite" +) + +// PossibleOpenModeTypeValues returns the possible values for the OpenModeType const type. +func PossibleOpenModeTypeValues() []OpenModeType { + return []OpenModeType{ + OpenModeTypeReadOnly, + OpenModeTypeReadWrite, + } +} + +// OperationsInsightsStatusType - Operations Insights status type enum. +type OperationsInsightsStatusType string + +const ( + // OperationsInsightsStatusTypeDisabling - Disabling status + OperationsInsightsStatusTypeDisabling OperationsInsightsStatusType = "Disabling" + // OperationsInsightsStatusTypeEnabled - Enabled status + OperationsInsightsStatusTypeEnabled OperationsInsightsStatusType = "Enabled" + // OperationsInsightsStatusTypeEnabling - Enabling status + OperationsInsightsStatusTypeEnabling OperationsInsightsStatusType = "Enabling" + // OperationsInsightsStatusTypeFailedDisabling - FailedDisabling status + OperationsInsightsStatusTypeFailedDisabling OperationsInsightsStatusType = "FailedDisabling" + // OperationsInsightsStatusTypeFailedEnabling - FailedEnabling status + OperationsInsightsStatusTypeFailedEnabling OperationsInsightsStatusType = "FailedEnabling" + // OperationsInsightsStatusTypeNotEnabled - NotEnabled status + OperationsInsightsStatusTypeNotEnabled OperationsInsightsStatusType = "NotEnabled" +) + +// PossibleOperationsInsightsStatusTypeValues returns the possible values for the OperationsInsightsStatusType const type. +func PossibleOperationsInsightsStatusTypeValues() []OperationsInsightsStatusType { + return []OperationsInsightsStatusType{ + OperationsInsightsStatusTypeDisabling, + OperationsInsightsStatusTypeEnabled, + OperationsInsightsStatusTypeEnabling, + OperationsInsightsStatusTypeFailedDisabling, + OperationsInsightsStatusTypeFailedEnabling, + OperationsInsightsStatusTypeNotEnabled, + } +} + +// OracleSubscriptionProvisioningState - OracleSubscriptionProvisioningState enum +type OracleSubscriptionProvisioningState string + +const ( + // OracleSubscriptionProvisioningStateCanceled - Resource creation was canceled. + OracleSubscriptionProvisioningStateCanceled OracleSubscriptionProvisioningState = "Canceled" + // OracleSubscriptionProvisioningStateFailed - Resource creation failed. + OracleSubscriptionProvisioningStateFailed OracleSubscriptionProvisioningState = "Failed" + // OracleSubscriptionProvisioningStateSucceeded - Resource has been created. + OracleSubscriptionProvisioningStateSucceeded OracleSubscriptionProvisioningState = "Succeeded" +) + +// PossibleOracleSubscriptionProvisioningStateValues returns the possible values for the OracleSubscriptionProvisioningState const type. +func PossibleOracleSubscriptionProvisioningStateValues() []OracleSubscriptionProvisioningState { + return []OracleSubscriptionProvisioningState{ + OracleSubscriptionProvisioningStateCanceled, + OracleSubscriptionProvisioningStateFailed, + OracleSubscriptionProvisioningStateSucceeded, + } +} + +// Origin - The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default +// value is "user,system" +type Origin string + +const ( + // OriginSystem - Indicates the operation is initiated by a system. + OriginSystem Origin = "system" + // OriginUser - Indicates the operation is initiated by a user. + OriginUser Origin = "user" + // OriginUserSystem - Indicates the operation is initiated by a user or system. + OriginUserSystem Origin = "user,system" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginSystem, + OriginUser, + OriginUserSystem, + } +} + +// PatchingMode - Patching mode enum +type PatchingMode string + +const ( + // PatchingModeNonRolling - Non Rolling patching + PatchingModeNonRolling PatchingMode = "NonRolling" + // PatchingModeRolling - Rolling patching + PatchingModeRolling PatchingMode = "Rolling" +) + +// PossiblePatchingModeValues returns the possible values for the PatchingMode const type. +func PossiblePatchingModeValues() []PatchingMode { + return []PatchingMode{ + PatchingModeNonRolling, + PatchingModeRolling, + } +} + +// PermissionLevelType - Permission level type enum. +type PermissionLevelType string + +const ( + // PermissionLevelTypeRestricted - Restricted permission level + PermissionLevelTypeRestricted PermissionLevelType = "Restricted" + // PermissionLevelTypeUnrestricted - Unrestricted permission level + PermissionLevelTypeUnrestricted PermissionLevelType = "Unrestricted" +) + +// PossiblePermissionLevelTypeValues returns the possible values for the PermissionLevelType const type. +func PossiblePermissionLevelTypeValues() []PermissionLevelType { + return []PermissionLevelType{ + PermissionLevelTypeRestricted, + PermissionLevelTypeUnrestricted, + } +} + +// Preference - Preference enum +type Preference string + +const ( + // PreferenceCustomPreference - Custom preference + PreferenceCustomPreference Preference = "CustomPreference" + // PreferenceNoPreference - No preference + PreferenceNoPreference Preference = "NoPreference" +) + +// PossiblePreferenceValues returns the possible values for the Preference const type. +func PossiblePreferenceValues() []Preference { + return []Preference{ + PreferenceCustomPreference, + PreferenceNoPreference, + } +} + +// ProtocolType - Protocol type enum. +type ProtocolType string + +const ( + // ProtocolTypeTCP - TCP protocol + ProtocolTypeTCP ProtocolType = "TCP" + // ProtocolTypeTCPS - TCPS protocol + ProtocolTypeTCPS ProtocolType = "TCPS" +) + +// PossibleProtocolTypeValues returns the possible values for the ProtocolType const type. +func PossibleProtocolTypeValues() []ProtocolType { + return []ProtocolType{ + ProtocolTypeTCP, + ProtocolTypeTCPS, + } +} + +// RefreshableModelType - Refreshable model type enum +type RefreshableModelType string + +const ( + // RefreshableModelTypeAutomatic - Automatic refreshable model type + RefreshableModelTypeAutomatic RefreshableModelType = "Automatic" + // RefreshableModelTypeManual - Manual refreshable model type + RefreshableModelTypeManual RefreshableModelType = "Manual" +) + +// PossibleRefreshableModelTypeValues returns the possible values for the RefreshableModelType const type. +func PossibleRefreshableModelTypeValues() []RefreshableModelType { + return []RefreshableModelType{ + RefreshableModelTypeAutomatic, + RefreshableModelTypeManual, + } +} + +// RefreshableStatusType - Refreshable status type enum. +type RefreshableStatusType string + +const ( + // RefreshableStatusTypeNotRefreshing - NotRefreshing status + RefreshableStatusTypeNotRefreshing RefreshableStatusType = "NotRefreshing" + // RefreshableStatusTypeRefreshing - Refreshing status + RefreshableStatusTypeRefreshing RefreshableStatusType = "Refreshing" +) + +// PossibleRefreshableStatusTypeValues returns the possible values for the RefreshableStatusType const type. +func PossibleRefreshableStatusTypeValues() []RefreshableStatusType { + return []RefreshableStatusType{ + RefreshableStatusTypeNotRefreshing, + RefreshableStatusTypeRefreshing, + } +} + +// RepeatCadenceType - Repeat cadence type enum +type RepeatCadenceType string + +const ( + // RepeatCadenceTypeMonthly - Repeat monthly + RepeatCadenceTypeMonthly RepeatCadenceType = "Monthly" + // RepeatCadenceTypeOneTime - Repeat one time + RepeatCadenceTypeOneTime RepeatCadenceType = "OneTime" + // RepeatCadenceTypeWeekly - Repeat weekly + RepeatCadenceTypeWeekly RepeatCadenceType = "Weekly" + // RepeatCadenceTypeYearly - Repeat yearly + RepeatCadenceTypeYearly RepeatCadenceType = "Yearly" +) + +// PossibleRepeatCadenceTypeValues returns the possible values for the RepeatCadenceType const type. +func PossibleRepeatCadenceTypeValues() []RepeatCadenceType { + return []RepeatCadenceType{ + RepeatCadenceTypeMonthly, + RepeatCadenceTypeOneTime, + RepeatCadenceTypeWeekly, + RepeatCadenceTypeYearly, + } +} + +// ResourceProvisioningState - The provisioning state of a resource type. +type ResourceProvisioningState string + +const ( + // ResourceProvisioningStateCanceled - Resource creation was canceled. + ResourceProvisioningStateCanceled ResourceProvisioningState = "Canceled" + // ResourceProvisioningStateFailed - Resource creation failed. + ResourceProvisioningStateFailed ResourceProvisioningState = "Failed" + // ResourceProvisioningStateSucceeded - Resource has been created. + ResourceProvisioningStateSucceeded ResourceProvisioningState = "Succeeded" +) + +// PossibleResourceProvisioningStateValues returns the possible values for the ResourceProvisioningState const type. +func PossibleResourceProvisioningStateValues() []ResourceProvisioningState { + return []ResourceProvisioningState{ + ResourceProvisioningStateCanceled, + ResourceProvisioningStateFailed, + ResourceProvisioningStateSucceeded, + } +} + +// RoleType - Role type enum. +type RoleType string + +const ( + // RoleTypeBackupCopy - BackupCopy role + RoleTypeBackupCopy RoleType = "BackupCopy" + // RoleTypeDisabledStandby - DisabledStandby role + RoleTypeDisabledStandby RoleType = "DisabledStandby" + // RoleTypePrimary - Primary role + RoleTypePrimary RoleType = "Primary" + // RoleTypeSnapshotStandby - SnapshotStandby role + RoleTypeSnapshotStandby RoleType = "SnapshotStandby" + // RoleTypeStandby - Standby role + RoleTypeStandby RoleType = "Standby" +) + +// PossibleRoleTypeValues returns the possible values for the RoleType const type. +func PossibleRoleTypeValues() []RoleType { + return []RoleType{ + RoleTypeBackupCopy, + RoleTypeDisabledStandby, + RoleTypePrimary, + RoleTypeSnapshotStandby, + RoleTypeStandby, + } +} + +// SessionModeType - Session mode type enum. +type SessionModeType string + +const ( + // SessionModeTypeDirect - Direct session mode + SessionModeTypeDirect SessionModeType = "Direct" + // SessionModeTypeRedirect - Redirect session mode + SessionModeTypeRedirect SessionModeType = "Redirect" +) + +// PossibleSessionModeTypeValues returns the possible values for the SessionModeType const type. +func PossibleSessionModeTypeValues() []SessionModeType { + return []SessionModeType{ + SessionModeTypeDirect, + SessionModeTypeRedirect, + } +} + +// ShapeAttribute - The type of Exascale storage used for Exadata VM cluster. The default is SMART_STORAGE which supports +// Oracle Database 23ai and later +type ShapeAttribute string + +const ( + // ShapeAttributeBLOCKSTORAGE - block storage + ShapeAttributeBLOCKSTORAGE ShapeAttribute = "BLOCK_STORAGE" + // ShapeAttributeSMARTSTORAGE - Smart storage + ShapeAttributeSMARTSTORAGE ShapeAttribute = "SMART_STORAGE" +) + +// PossibleShapeAttributeValues returns the possible values for the ShapeAttribute const type. +func PossibleShapeAttributeValues() []ShapeAttribute { + return []ShapeAttribute{ + ShapeAttributeBLOCKSTORAGE, + ShapeAttributeSMARTSTORAGE, + } +} + +// ShapeFamily - Allowed values for GI Minor Versions shapeFamily filter +type ShapeFamily string + +const ( + // ShapeFamilyExadata - Family value for Exadata Shape + ShapeFamilyExadata ShapeFamily = "EXADATA" + // ShapeFamilyExadbXs - Family value for Exadb XS Shape + ShapeFamilyExadbXs ShapeFamily = "EXADB_XS" +) + +// PossibleShapeFamilyValues returns the possible values for the ShapeFamily const type. +func PossibleShapeFamilyValues() []ShapeFamily { + return []ShapeFamily{ + ShapeFamilyExadata, + ShapeFamilyExadbXs, + } +} + +// ShapeFamilyType - Allowed values for shape family. +type ShapeFamilyType string + +const ( + // ShapeFamilyTypeExadata - Family value for Exadata Shape + ShapeFamilyTypeExadata ShapeFamilyType = "EXADATA" + // ShapeFamilyTypeExadbXs - Family value for Exadb XS Shape + ShapeFamilyTypeExadbXs ShapeFamilyType = "EXADB_XS" + // ShapeFamilyTypeSingleNode - Family value for Single Node Shape + ShapeFamilyTypeSingleNode ShapeFamilyType = "SINGLENODE" + // ShapeFamilyTypeVirtualMachine - Family value for Virtual Machine Shape + ShapeFamilyTypeVirtualMachine ShapeFamilyType = "VIRTUALMACHINE" +) + +// PossibleShapeFamilyTypeValues returns the possible values for the ShapeFamilyType const type. +func PossibleShapeFamilyTypeValues() []ShapeFamilyType { + return []ShapeFamilyType{ + ShapeFamilyTypeExadata, + ShapeFamilyTypeExadbXs, + ShapeFamilyTypeSingleNode, + ShapeFamilyTypeVirtualMachine, + } +} + +// SourceType - Source type enum. +type SourceType string + +const ( + // SourceTypeBackupFromID - Backup from ID source + SourceTypeBackupFromID SourceType = "BackupFromId" + // SourceTypeBackupFromTimestamp - Backup from timestamp source + SourceTypeBackupFromTimestamp SourceType = "BackupFromTimestamp" + // SourceTypeCloneToRefreshable - Clone to refreshable source + SourceTypeCloneToRefreshable SourceType = "CloneToRefreshable" + // SourceTypeCrossRegionDataguard - Cross region dataguard source + SourceTypeCrossRegionDataguard SourceType = "CrossRegionDataguard" + // SourceTypeCrossRegionDisasterRecovery - cross region disaster recovery source + SourceTypeCrossRegionDisasterRecovery SourceType = "CrossRegionDisasterRecovery" + // SourceTypeDatabase - Database source + SourceTypeDatabase SourceType = "Database" + // SourceTypeNone - None source + SourceTypeNone SourceType = "None" +) + +// PossibleSourceTypeValues returns the possible values for the SourceType const type. +func PossibleSourceTypeValues() []SourceType { + return []SourceType{ + SourceTypeBackupFromID, + SourceTypeBackupFromTimestamp, + SourceTypeCloneToRefreshable, + SourceTypeCrossRegionDataguard, + SourceTypeCrossRegionDisasterRecovery, + SourceTypeDatabase, + SourceTypeNone, + } +} + +// StorageManagementType - Storage Management type enum. +type StorageManagementType string + +const ( + // StorageManagementTypeLVM - Logical Volume management + StorageManagementTypeLVM StorageManagementType = "LVM" +) + +// PossibleStorageManagementTypeValues returns the possible values for the StorageManagementType const type. +func PossibleStorageManagementTypeValues() []StorageManagementType { + return []StorageManagementType{ + StorageManagementTypeLVM, + } +} + +// StorageVolumePerformanceMode - Storage volume performance mode. +type StorageVolumePerformanceMode string + +const ( + // StorageVolumePerformanceModeBalanced - With this option, you are purchasing 10 VPUs per GB/month. For more information, + // including specific throughput and IOPS performance numbers for various volume sizes. + StorageVolumePerformanceModeBalanced StorageVolumePerformanceMode = "Balanced" + // StorageVolumePerformanceModeHighPerformance - With this option, you are purchasing 20 VPUs per GB/month. For more information, + // including specific throughput and IOPS performance numbers for various volume sizes. + StorageVolumePerformanceModeHighPerformance StorageVolumePerformanceMode = "HighPerformance" +) + +// PossibleStorageVolumePerformanceModeValues returns the possible values for the StorageVolumePerformanceMode const type. +func PossibleStorageVolumePerformanceModeValues() []StorageVolumePerformanceMode { + return []StorageVolumePerformanceMode{ + StorageVolumePerformanceModeBalanced, + StorageVolumePerformanceModeHighPerformance, + } +} + +// SyntaxFormatType - Syntax format type enum. +type SyntaxFormatType string + +const ( + // SyntaxFormatTypeEzconnect - Ezconnect format + SyntaxFormatTypeEzconnect SyntaxFormatType = "Ezconnect" + // SyntaxFormatTypeEzconnectplus - Ezconnectplus format + SyntaxFormatTypeEzconnectplus SyntaxFormatType = "Ezconnectplus" + // SyntaxFormatTypeLong - Long format + SyntaxFormatTypeLong SyntaxFormatType = "Long" +) + +// PossibleSyntaxFormatTypeValues returns the possible values for the SyntaxFormatType const type. +func PossibleSyntaxFormatTypeValues() []SyntaxFormatType { + return []SyntaxFormatType{ + SyntaxFormatTypeEzconnect, + SyntaxFormatTypeEzconnectplus, + SyntaxFormatTypeLong, + } +} + +// SystemShapes - Allowed values for System Shapes +type SystemShapes string + +const ( + // SystemShapesExaDbXs - Exadata DB on Exascale Infrastructure shape + SystemShapesExaDbXs SystemShapes = "ExaDbXS" + // SystemShapesExadataX11M - Exadata X11M shape + SystemShapesExadataX11M SystemShapes = "Exadata.X11M" + // SystemShapesExadataX9M - Exadata X9M shape + SystemShapesExadataX9M SystemShapes = "Exadata.X9M" +) + +// PossibleSystemShapesValues returns the possible values for the SystemShapes const type. +func PossibleSystemShapesValues() []SystemShapes { + return []SystemShapes{ + SystemShapesExaDbXs, + SystemShapesExadataX11M, + SystemShapesExadataX9M, + } +} + +// TLSAuthenticationType - TLS authentication type enum. +type TLSAuthenticationType string + +const ( + // TLSAuthenticationTypeMutual - Mutual TLS + TLSAuthenticationTypeMutual TLSAuthenticationType = "Mutual" + // TLSAuthenticationTypeServer - Server authentication + TLSAuthenticationTypeServer TLSAuthenticationType = "Server" +) + +// PossibleTLSAuthenticationTypeValues returns the possible values for the TLSAuthenticationType const type. +func PossibleTLSAuthenticationTypeValues() []TLSAuthenticationType { + return []TLSAuthenticationType{ + TLSAuthenticationTypeMutual, + TLSAuthenticationTypeServer, + } +} + +// VirtualNetworkAddressLifecycleState - VirtualNetworkAddressLifecycleState enum +type VirtualNetworkAddressLifecycleState string + +const ( + // VirtualNetworkAddressLifecycleStateAvailable - Indicates that resource in Available state + VirtualNetworkAddressLifecycleStateAvailable VirtualNetworkAddressLifecycleState = "Available" + // VirtualNetworkAddressLifecycleStateFailed - Indicates that resource in Failed state + VirtualNetworkAddressLifecycleStateFailed VirtualNetworkAddressLifecycleState = "Failed" + // VirtualNetworkAddressLifecycleStateProvisioning - Indicates that resource in Provisioning state + VirtualNetworkAddressLifecycleStateProvisioning VirtualNetworkAddressLifecycleState = "Provisioning" + // VirtualNetworkAddressLifecycleStateTerminated - Indicates that resource in Terminated state + VirtualNetworkAddressLifecycleStateTerminated VirtualNetworkAddressLifecycleState = "Terminated" + // VirtualNetworkAddressLifecycleStateTerminating - Indicates that resource in Terminating state + VirtualNetworkAddressLifecycleStateTerminating VirtualNetworkAddressLifecycleState = "Terminating" +) + +// PossibleVirtualNetworkAddressLifecycleStateValues returns the possible values for the VirtualNetworkAddressLifecycleState const type. +func PossibleVirtualNetworkAddressLifecycleStateValues() []VirtualNetworkAddressLifecycleState { + return []VirtualNetworkAddressLifecycleState{ + VirtualNetworkAddressLifecycleStateAvailable, + VirtualNetworkAddressLifecycleStateFailed, + VirtualNetworkAddressLifecycleStateProvisioning, + VirtualNetworkAddressLifecycleStateTerminated, + VirtualNetworkAddressLifecycleStateTerminating, + } +} + +// WorkloadType - WorkloadType enum +type WorkloadType string + +const ( + // WorkloadTypeAJD - AJD - indicates an Autonomous JSON Database + WorkloadTypeAJD WorkloadType = "AJD" + // WorkloadTypeAPEX - APEX - indicates an Autonomous Database with the Oracle APEX Application Development workload type. + WorkloadTypeAPEX WorkloadType = "APEX" + // WorkloadTypeDW - DW - indicates an Autonomous Data Warehouse database + WorkloadTypeDW WorkloadType = "DW" + // WorkloadTypeOLTP - OLTP - indicates an Autonomous Transaction Processing database + WorkloadTypeOLTP WorkloadType = "OLTP" +) + +// PossibleWorkloadTypeValues returns the possible values for the WorkloadType const type. +func PossibleWorkloadTypeValues() []WorkloadType { + return []WorkloadType{ + WorkloadTypeAJD, + WorkloadTypeAPEX, + WorkloadTypeDW, + WorkloadTypeOLTP, + } +} + +// ZoneType - Zone type enum +type ZoneType string + +const ( + // ZoneTypePrimary - Primary zone + ZoneTypePrimary ZoneType = "Primary" + // ZoneTypeSecondary - Secondary zone + ZoneTypeSecondary ZoneType = "Secondary" +) + +// PossibleZoneTypeValues returns the possible values for the ZoneType const type. +func PossibleZoneTypeValues() []ZoneType { + return []ZoneType{ + ZoneTypePrimary, + ZoneTypeSecondary, + } +} diff --git a/test/local/armoracledatabase/zz_dbnodes_client.go b/test/local/armoracledatabase/zz_dbnodes_client.go new file mode 100644 index 000000000000..a8c3466cee21 --- /dev/null +++ b/test/local/armoracledatabase/zz_dbnodes_client.go @@ -0,0 +1,253 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// DbNodesClient contains the methods for the DbNodes group. +// Don't use this type directly, use NewDbNodesClient() instead. +// +// Generated from API version 2025-09-01 +type DbNodesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDbNodesClient creates a new instance of DbNodesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewDbNodesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DbNodesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DbNodesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginAction - VM actions on DbNode of VM Cluster by the provided filter +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudvmclustername - CloudVmCluster name +// - dbnodeocid - DbNode OCID. +// - body - The content of the action request +// - options - DbNodesClientBeginActionOptions contains the optional parameters for the DbNodesClient.BeginAction method. +func (client *DbNodesClient) BeginAction(ctx context.Context, resourceGroupName string, cloudvmclustername string, dbnodeocid string, body DbNodeAction, options *DbNodesClientBeginActionOptions) (*runtime.Poller[DbNodesClientActionResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.action(ctx, resourceGroupName, cloudvmclustername, dbnodeocid, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DbNodesClientActionResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DbNodesClientActionResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Action - VM actions on DbNode of VM Cluster by the provided filter +// If the operation fails it returns an *azcore.ResponseError type. +func (client *DbNodesClient) action(ctx context.Context, resourceGroupName string, cloudvmclustername string, dbnodeocid string, body DbNodeAction, options *DbNodesClientBeginActionOptions) (*http.Response, error) { + var err error + const operationName = "DbNodesClient.BeginAction" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.actionCreateRequest(ctx, resourceGroupName, cloudvmclustername, dbnodeocid, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// actionCreateRequest creates the Action request. +func (client *DbNodesClient) actionCreateRequest(ctx context.Context, resourceGroupName string, cloudvmclustername string, dbnodeocid string, body DbNodeAction, _ *DbNodesClientBeginActionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/cloudVmClusters/{cloudvmclustername}/dbNodes/{dbnodeocid}/action" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudvmclustername == "" { + return nil, errors.New("parameter cloudvmclustername cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudvmclustername}", url.PathEscape(cloudvmclustername)) + if dbnodeocid == "" { + return nil, errors.New("parameter dbnodeocid cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{dbnodeocid}", url.PathEscape(dbnodeocid)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// Get - Get a DbNode +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudvmclustername - CloudVmCluster name +// - dbnodeocid - DbNode OCID. +// - options - DbNodesClientGetOptions contains the optional parameters for the DbNodesClient.Get method. +func (client *DbNodesClient) Get(ctx context.Context, resourceGroupName string, cloudvmclustername string, dbnodeocid string, options *DbNodesClientGetOptions) (DbNodesClientGetResponse, error) { + var err error + const operationName = "DbNodesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, cloudvmclustername, dbnodeocid, options) + if err != nil { + return DbNodesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DbNodesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DbNodesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DbNodesClient) getCreateRequest(ctx context.Context, resourceGroupName string, cloudvmclustername string, dbnodeocid string, _ *DbNodesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/cloudVmClusters/{cloudvmclustername}/dbNodes/{dbnodeocid}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudvmclustername == "" { + return nil, errors.New("parameter cloudvmclustername cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudvmclustername}", url.PathEscape(cloudvmclustername)) + if dbnodeocid == "" { + return nil, errors.New("parameter dbnodeocid cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{dbnodeocid}", url.PathEscape(dbnodeocid)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DbNodesClient) getHandleResponse(resp *http.Response) (DbNodesClientGetResponse, error) { + result := DbNodesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DbNode); err != nil { + return DbNodesClientGetResponse{}, err + } + return result, nil +} + +// NewListByCloudVMClusterPager - List DbNode resources by CloudVmCluster +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudvmclustername - CloudVmCluster name +// - options - DbNodesClientListByCloudVMClusterOptions contains the optional parameters for the DbNodesClient.NewListByCloudVMClusterPager +// method. +func (client *DbNodesClient) NewListByCloudVMClusterPager(resourceGroupName string, cloudvmclustername string, options *DbNodesClientListByCloudVMClusterOptions) *runtime.Pager[DbNodesClientListByCloudVMClusterResponse] { + return runtime.NewPager(runtime.PagingHandler[DbNodesClientListByCloudVMClusterResponse]{ + More: func(page DbNodesClientListByCloudVMClusterResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DbNodesClientListByCloudVMClusterResponse) (DbNodesClientListByCloudVMClusterResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DbNodesClient.NewListByCloudVMClusterPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByCloudVMClusterCreateRequest(ctx, resourceGroupName, cloudvmclustername, options) + }, nil) + if err != nil { + return DbNodesClientListByCloudVMClusterResponse{}, err + } + return client.listByCloudVMClusterHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByCloudVMClusterCreateRequest creates the ListByCloudVMCluster request. +func (client *DbNodesClient) listByCloudVMClusterCreateRequest(ctx context.Context, resourceGroupName string, cloudvmclustername string, _ *DbNodesClientListByCloudVMClusterOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/cloudVmClusters/{cloudvmclustername}/dbNodes" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudvmclustername == "" { + return nil, errors.New("parameter cloudvmclustername cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudvmclustername}", url.PathEscape(cloudvmclustername)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByCloudVMClusterHandleResponse handles the ListByCloudVMCluster response. +func (client *DbNodesClient) listByCloudVMClusterHandleResponse(resp *http.Response) (DbNodesClientListByCloudVMClusterResponse, error) { + result := DbNodesClientListByCloudVMClusterResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DbNodeListResult); err != nil { + return DbNodesClientListByCloudVMClusterResponse{}, err + } + return result, nil +} diff --git a/test/local/armoracledatabase/zz_dbservers_client.go b/test/local/armoracledatabase/zz_dbservers_client.go new file mode 100644 index 000000000000..20903a5acf01 --- /dev/null +++ b/test/local/armoracledatabase/zz_dbservers_client.go @@ -0,0 +1,172 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// DbServersClient contains the methods for the DbServers group. +// Don't use this type directly, use NewDbServersClient() instead. +// +// Generated from API version 2025-09-01 +type DbServersClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDbServersClient creates a new instance of DbServersClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewDbServersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DbServersClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DbServersClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get a DbServer +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudexadatainfrastructurename - CloudExadataInfrastructure name +// - dbserverocid - DbServer OCID. +// - options - DbServersClientGetOptions contains the optional parameters for the DbServersClient.Get method. +func (client *DbServersClient) Get(ctx context.Context, resourceGroupName string, cloudexadatainfrastructurename string, dbserverocid string, options *DbServersClientGetOptions) (DbServersClientGetResponse, error) { + var err error + const operationName = "DbServersClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, cloudexadatainfrastructurename, dbserverocid, options) + if err != nil { + return DbServersClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DbServersClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DbServersClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DbServersClient) getCreateRequest(ctx context.Context, resourceGroupName string, cloudexadatainfrastructurename string, dbserverocid string, _ *DbServersClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/cloudExadataInfrastructures/{cloudexadatainfrastructurename}/dbServers/{dbserverocid}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudexadatainfrastructurename == "" { + return nil, errors.New("parameter cloudexadatainfrastructurename cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudexadatainfrastructurename}", url.PathEscape(cloudexadatainfrastructurename)) + if dbserverocid == "" { + return nil, errors.New("parameter dbserverocid cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{dbserverocid}", url.PathEscape(dbserverocid)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DbServersClient) getHandleResponse(resp *http.Response) (DbServersClientGetResponse, error) { + result := DbServersClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DbServer); err != nil { + return DbServersClientGetResponse{}, err + } + return result, nil +} + +// NewListByCloudExadataInfrastructurePager - List DbServer resources by CloudExadataInfrastructure +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudexadatainfrastructurename - CloudExadataInfrastructure name +// - options - DbServersClientListByCloudExadataInfrastructureOptions contains the optional parameters for the DbServersClient.NewListByCloudExadataInfrastructurePager +// method. +func (client *DbServersClient) NewListByCloudExadataInfrastructurePager(resourceGroupName string, cloudexadatainfrastructurename string, options *DbServersClientListByCloudExadataInfrastructureOptions) *runtime.Pager[DbServersClientListByCloudExadataInfrastructureResponse] { + return runtime.NewPager(runtime.PagingHandler[DbServersClientListByCloudExadataInfrastructureResponse]{ + More: func(page DbServersClientListByCloudExadataInfrastructureResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DbServersClientListByCloudExadataInfrastructureResponse) (DbServersClientListByCloudExadataInfrastructureResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DbServersClient.NewListByCloudExadataInfrastructurePager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByCloudExadataInfrastructureCreateRequest(ctx, resourceGroupName, cloudexadatainfrastructurename, options) + }, nil) + if err != nil { + return DbServersClientListByCloudExadataInfrastructureResponse{}, err + } + return client.listByCloudExadataInfrastructureHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByCloudExadataInfrastructureCreateRequest creates the ListByCloudExadataInfrastructure request. +func (client *DbServersClient) listByCloudExadataInfrastructureCreateRequest(ctx context.Context, resourceGroupName string, cloudexadatainfrastructurename string, _ *DbServersClientListByCloudExadataInfrastructureOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/cloudExadataInfrastructures/{cloudexadatainfrastructurename}/dbServers" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudexadatainfrastructurename == "" { + return nil, errors.New("parameter cloudexadatainfrastructurename cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudexadatainfrastructurename}", url.PathEscape(cloudexadatainfrastructurename)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByCloudExadataInfrastructureHandleResponse handles the ListByCloudExadataInfrastructure response. +func (client *DbServersClient) listByCloudExadataInfrastructureHandleResponse(resp *http.Response) (DbServersClientListByCloudExadataInfrastructureResponse, error) { + result := DbServersClientListByCloudExadataInfrastructureResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DbServerListResult); err != nil { + return DbServersClientListByCloudExadataInfrastructureResponse{}, err + } + return result, nil +} diff --git a/test/local/armoracledatabase/zz_dbsystems_client.go b/test/local/armoracledatabase/zz_dbsystems_client.go new file mode 100644 index 000000000000..49b2ffb92e5d --- /dev/null +++ b/test/local/armoracledatabase/zz_dbsystems_client.go @@ -0,0 +1,438 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// DbSystemsClient contains the methods for the DbSystems group. +// Don't use this type directly, use NewDbSystemsClient() instead. +// +// Generated from API version 2025-09-01 +type DbSystemsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDbSystemsClient creates a new instance of DbSystemsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewDbSystemsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DbSystemsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DbSystemsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create a DbSystem +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - dbSystemName - The name of the DbSystem +// - resource - Resource create parameters. +// - options - DbSystemsClientBeginCreateOrUpdateOptions contains the optional parameters for the DbSystemsClient.BeginCreateOrUpdate +// method. +func (client *DbSystemsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, dbSystemName string, resource DbSystem, options *DbSystemsClientBeginCreateOrUpdateOptions) (*runtime.Poller[DbSystemsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, dbSystemName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DbSystemsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DbSystemsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create a DbSystem +// If the operation fails it returns an *azcore.ResponseError type. +func (client *DbSystemsClient) createOrUpdate(ctx context.Context, resourceGroupName string, dbSystemName string, resource DbSystem, options *DbSystemsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "DbSystemsClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, dbSystemName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *DbSystemsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, dbSystemName string, resource DbSystem, _ *DbSystemsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/dbSystems/{dbSystemName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if dbSystemName == "" { + return nil, errors.New("parameter dbSystemName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{dbSystemName}", url.PathEscape(dbSystemName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a DbSystem +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - dbSystemName - The name of the DbSystem +// - options - DbSystemsClientBeginDeleteOptions contains the optional parameters for the DbSystemsClient.BeginDelete method. +func (client *DbSystemsClient) BeginDelete(ctx context.Context, resourceGroupName string, dbSystemName string, options *DbSystemsClientBeginDeleteOptions) (*runtime.Poller[DbSystemsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, dbSystemName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DbSystemsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DbSystemsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a DbSystem +// If the operation fails it returns an *azcore.ResponseError type. +func (client *DbSystemsClient) deleteOperation(ctx context.Context, resourceGroupName string, dbSystemName string, options *DbSystemsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "DbSystemsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, dbSystemName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *DbSystemsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, dbSystemName string, _ *DbSystemsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/dbSystems/{dbSystemName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if dbSystemName == "" { + return nil, errors.New("parameter dbSystemName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{dbSystemName}", url.PathEscape(dbSystemName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a DbSystem +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - dbSystemName - The name of the DbSystem +// - options - DbSystemsClientGetOptions contains the optional parameters for the DbSystemsClient.Get method. +func (client *DbSystemsClient) Get(ctx context.Context, resourceGroupName string, dbSystemName string, options *DbSystemsClientGetOptions) (DbSystemsClientGetResponse, error) { + var err error + const operationName = "DbSystemsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, dbSystemName, options) + if err != nil { + return DbSystemsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DbSystemsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DbSystemsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DbSystemsClient) getCreateRequest(ctx context.Context, resourceGroupName string, dbSystemName string, _ *DbSystemsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/dbSystems/{dbSystemName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if dbSystemName == "" { + return nil, errors.New("parameter dbSystemName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{dbSystemName}", url.PathEscape(dbSystemName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DbSystemsClient) getHandleResponse(resp *http.Response) (DbSystemsClientGetResponse, error) { + result := DbSystemsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DbSystem); err != nil { + return DbSystemsClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - List DbSystem resources by resource group +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - DbSystemsClientListByResourceGroupOptions contains the optional parameters for the DbSystemsClient.NewListByResourceGroupPager +// method. +func (client *DbSystemsClient) NewListByResourceGroupPager(resourceGroupName string, options *DbSystemsClientListByResourceGroupOptions) *runtime.Pager[DbSystemsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[DbSystemsClientListByResourceGroupResponse]{ + More: func(page DbSystemsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DbSystemsClientListByResourceGroupResponse) (DbSystemsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DbSystemsClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return DbSystemsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *DbSystemsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *DbSystemsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/dbSystems" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *DbSystemsClient) listByResourceGroupHandleResponse(resp *http.Response) (DbSystemsClientListByResourceGroupResponse, error) { + result := DbSystemsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DbSystemListResult); err != nil { + return DbSystemsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - List DbSystem resources by subscription ID +// - options - DbSystemsClientListBySubscriptionOptions contains the optional parameters for the DbSystemsClient.NewListBySubscriptionPager +// method. +func (client *DbSystemsClient) NewListBySubscriptionPager(options *DbSystemsClientListBySubscriptionOptions) *runtime.Pager[DbSystemsClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[DbSystemsClientListBySubscriptionResponse]{ + More: func(page DbSystemsClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DbSystemsClientListBySubscriptionResponse) (DbSystemsClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DbSystemsClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return DbSystemsClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *DbSystemsClient) listBySubscriptionCreateRequest(ctx context.Context, _ *DbSystemsClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/dbSystems" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *DbSystemsClient) listBySubscriptionHandleResponse(resp *http.Response) (DbSystemsClientListBySubscriptionResponse, error) { + result := DbSystemsClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DbSystemListResult); err != nil { + return DbSystemsClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update a DbSystem +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - dbSystemName - The name of the DbSystem +// - properties - The resource properties to be updated. +// - options - DbSystemsClientBeginUpdateOptions contains the optional parameters for the DbSystemsClient.BeginUpdate method. +func (client *DbSystemsClient) BeginUpdate(ctx context.Context, resourceGroupName string, dbSystemName string, properties DbSystemUpdate, options *DbSystemsClientBeginUpdateOptions) (*runtime.Poller[DbSystemsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, dbSystemName, properties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[DbSystemsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[DbSystemsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a DbSystem +// If the operation fails it returns an *azcore.ResponseError type. +func (client *DbSystemsClient) update(ctx context.Context, resourceGroupName string, dbSystemName string, properties DbSystemUpdate, options *DbSystemsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "DbSystemsClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, dbSystemName, properties, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *DbSystemsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, dbSystemName string, properties DbSystemUpdate, _ *DbSystemsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/dbSystems/{dbSystemName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if dbSystemName == "" { + return nil, errors.New("parameter dbSystemName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{dbSystemName}", url.PathEscape(dbSystemName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armoracledatabase/zz_dbsystemshapes_client.go b/test/local/armoracledatabase/zz_dbsystemshapes_client.go new file mode 100644 index 000000000000..baecaf7de54f --- /dev/null +++ b/test/local/armoracledatabase/zz_dbsystemshapes_client.go @@ -0,0 +1,168 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// DbSystemShapesClient contains the methods for the DbSystemShapes group. +// Don't use this type directly, use NewDbSystemShapesClient() instead. +// +// Generated from API version 2025-09-01 +type DbSystemShapesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDbSystemShapesClient creates a new instance of DbSystemShapesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewDbSystemShapesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DbSystemShapesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DbSystemShapesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get a DbSystemShape +// If the operation fails it returns an *azcore.ResponseError type. +// - location - The name of the Azure region. +// - dbsystemshapename - DbSystemShape name +// - options - DbSystemShapesClientGetOptions contains the optional parameters for the DbSystemShapesClient.Get method. +func (client *DbSystemShapesClient) Get(ctx context.Context, location string, dbsystemshapename string, options *DbSystemShapesClientGetOptions) (DbSystemShapesClientGetResponse, error) { + var err error + const operationName = "DbSystemShapesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, location, dbsystemshapename, options) + if err != nil { + return DbSystemShapesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DbSystemShapesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DbSystemShapesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DbSystemShapesClient) getCreateRequest(ctx context.Context, location string, dbsystemshapename string, _ *DbSystemShapesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/locations/{location}/dbSystemShapes/{dbsystemshapename}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if dbsystemshapename == "" { + return nil, errors.New("parameter dbsystemshapename cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{dbsystemshapename}", url.PathEscape(dbsystemshapename)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DbSystemShapesClient) getHandleResponse(resp *http.Response) (DbSystemShapesClientGetResponse, error) { + result := DbSystemShapesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DbSystemShape); err != nil { + return DbSystemShapesClientGetResponse{}, err + } + return result, nil +} + +// NewListByLocationPager - List DbSystemShape resources by SubscriptionLocationResource +// - location - The name of the Azure region. +// - options - DbSystemShapesClientListByLocationOptions contains the optional parameters for the DbSystemShapesClient.NewListByLocationPager +// method. +func (client *DbSystemShapesClient) NewListByLocationPager(location string, options *DbSystemShapesClientListByLocationOptions) *runtime.Pager[DbSystemShapesClientListByLocationResponse] { + return runtime.NewPager(runtime.PagingHandler[DbSystemShapesClientListByLocationResponse]{ + More: func(page DbSystemShapesClientListByLocationResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DbSystemShapesClientListByLocationResponse) (DbSystemShapesClientListByLocationResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DbSystemShapesClient.NewListByLocationPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByLocationCreateRequest(ctx, location, options) + }, nil) + if err != nil { + return DbSystemShapesClientListByLocationResponse{}, err + } + return client.listByLocationHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByLocationCreateRequest creates the ListByLocation request. +func (client *DbSystemShapesClient) listByLocationCreateRequest(ctx context.Context, location string, options *DbSystemShapesClientListByLocationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/locations/{location}/dbSystemShapes" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + if options != nil && options.ShapeAttribute != nil { + reqQP.Set("shapeAttribute", *options.ShapeAttribute) + } + if options != nil && options.Zone != nil { + reqQP.Set("zone", *options.Zone) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByLocationHandleResponse handles the ListByLocation response. +func (client *DbSystemShapesClient) listByLocationHandleResponse(resp *http.Response) (DbSystemShapesClientListByLocationResponse, error) { + result := DbSystemShapesClientListByLocationResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DbSystemShapeListResult); err != nil { + return DbSystemShapesClientListByLocationResponse{}, err + } + return result, nil +} diff --git a/test/local/armoracledatabase/zz_dbversions_client.go b/test/local/armoracledatabase/zz_dbversions_client.go new file mode 100644 index 000000000000..90591330735a --- /dev/null +++ b/test/local/armoracledatabase/zz_dbversions_client.go @@ -0,0 +1,181 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" +) + +// DbVersionsClient contains the methods for the DbVersions group. +// Don't use this type directly, use NewDbVersionsClient() instead. +// +// Generated from API version 2025-09-01 +type DbVersionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDbVersionsClient creates a new instance of DbVersionsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewDbVersionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DbVersionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DbVersionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get a DbVersion +// If the operation fails it returns an *azcore.ResponseError type. +// - location - The name of the Azure region. +// - dbversionsname - DbVersion name +// - options - DbVersionsClientGetOptions contains the optional parameters for the DbVersionsClient.Get method. +func (client *DbVersionsClient) Get(ctx context.Context, location string, dbversionsname string, options *DbVersionsClientGetOptions) (DbVersionsClientGetResponse, error) { + var err error + const operationName = "DbVersionsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, location, dbversionsname, options) + if err != nil { + return DbVersionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DbVersionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DbVersionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DbVersionsClient) getCreateRequest(ctx context.Context, location string, dbversionsname string, _ *DbVersionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/locations/{location}/dbSystemDbVersions/{dbversionsname}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if dbversionsname == "" { + return nil, errors.New("parameter dbversionsname cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{dbversionsname}", url.PathEscape(dbversionsname)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DbVersionsClient) getHandleResponse(resp *http.Response) (DbVersionsClientGetResponse, error) { + result := DbVersionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DbVersion); err != nil { + return DbVersionsClientGetResponse{}, err + } + return result, nil +} + +// NewListByLocationPager - List DbVersion resources by SubscriptionLocationResource +// - location - The name of the Azure region. +// - options - DbVersionsClientListByLocationOptions contains the optional parameters for the DbVersionsClient.NewListByLocationPager +// method. +func (client *DbVersionsClient) NewListByLocationPager(location string, options *DbVersionsClientListByLocationOptions) *runtime.Pager[DbVersionsClientListByLocationResponse] { + return runtime.NewPager(runtime.PagingHandler[DbVersionsClientListByLocationResponse]{ + More: func(page DbVersionsClientListByLocationResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DbVersionsClientListByLocationResponse) (DbVersionsClientListByLocationResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DbVersionsClient.NewListByLocationPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByLocationCreateRequest(ctx, location, options) + }, nil) + if err != nil { + return DbVersionsClientListByLocationResponse{}, err + } + return client.listByLocationHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByLocationCreateRequest creates the ListByLocation request. +func (client *DbVersionsClient) listByLocationCreateRequest(ctx context.Context, location string, options *DbVersionsClientListByLocationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/locations/{location}/dbSystemDbVersions" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + if options != nil && options.DbSystemID != nil { + reqQP.Set("dbSystemId", *options.DbSystemID) + } + if options != nil && options.DbSystemShape != nil { + reqQP.Set("dbSystemShape", string(*options.DbSystemShape)) + } + if options != nil && options.IsDatabaseSoftwareImageSupported != nil { + reqQP.Set("isDatabaseSoftwareImageSupported", strconv.FormatBool(*options.IsDatabaseSoftwareImageSupported)) + } + if options != nil && options.IsUpgradeSupported != nil { + reqQP.Set("isUpgradeSupported", strconv.FormatBool(*options.IsUpgradeSupported)) + } + if options != nil && options.ShapeFamily != nil { + reqQP.Set("shapeFamily", string(*options.ShapeFamily)) + } + if options != nil && options.StorageManagement != nil { + reqQP.Set("storageManagement", string(*options.StorageManagement)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByLocationHandleResponse handles the ListByLocation response. +func (client *DbVersionsClient) listByLocationHandleResponse(resp *http.Response) (DbVersionsClientListByLocationResponse, error) { + result := DbVersionsClientListByLocationResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DbVersionListResult); err != nil { + return DbVersionsClientListByLocationResponse{}, err + } + return result, nil +} diff --git a/test/local/armoracledatabase/zz_dnsprivateviews_client.go b/test/local/armoracledatabase/zz_dnsprivateviews_client.go new file mode 100644 index 000000000000..53b377ad95fb --- /dev/null +++ b/test/local/armoracledatabase/zz_dnsprivateviews_client.go @@ -0,0 +1,162 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// DNSPrivateViewsClient contains the methods for the DNSPrivateViews group. +// Don't use this type directly, use NewDNSPrivateViewsClient() instead. +// +// Generated from API version 2025-09-01 +type DNSPrivateViewsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDNSPrivateViewsClient creates a new instance of DNSPrivateViewsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewDNSPrivateViewsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DNSPrivateViewsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DNSPrivateViewsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get a DnsPrivateView +// If the operation fails it returns an *azcore.ResponseError type. +// - location - The name of the Azure region. +// - dnsprivateviewocid - DnsPrivateView OCID +// - options - DNSPrivateViewsClientGetOptions contains the optional parameters for the DNSPrivateViewsClient.Get method. +func (client *DNSPrivateViewsClient) Get(ctx context.Context, location string, dnsprivateviewocid string, options *DNSPrivateViewsClientGetOptions) (DNSPrivateViewsClientGetResponse, error) { + var err error + const operationName = "DNSPrivateViewsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, location, dnsprivateviewocid, options) + if err != nil { + return DNSPrivateViewsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DNSPrivateViewsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DNSPrivateViewsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DNSPrivateViewsClient) getCreateRequest(ctx context.Context, location string, dnsprivateviewocid string, _ *DNSPrivateViewsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/locations/{location}/dnsPrivateViews/{dnsprivateviewocid}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if dnsprivateviewocid == "" { + return nil, errors.New("parameter dnsprivateviewocid cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{dnsprivateviewocid}", url.PathEscape(dnsprivateviewocid)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DNSPrivateViewsClient) getHandleResponse(resp *http.Response) (DNSPrivateViewsClientGetResponse, error) { + result := DNSPrivateViewsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DNSPrivateView); err != nil { + return DNSPrivateViewsClientGetResponse{}, err + } + return result, nil +} + +// NewListByLocationPager - List DnsPrivateView resources by SubscriptionLocationResource +// - location - The name of the Azure region. +// - options - DNSPrivateViewsClientListByLocationOptions contains the optional parameters for the DNSPrivateViewsClient.NewListByLocationPager +// method. +func (client *DNSPrivateViewsClient) NewListByLocationPager(location string, options *DNSPrivateViewsClientListByLocationOptions) *runtime.Pager[DNSPrivateViewsClientListByLocationResponse] { + return runtime.NewPager(runtime.PagingHandler[DNSPrivateViewsClientListByLocationResponse]{ + More: func(page DNSPrivateViewsClientListByLocationResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DNSPrivateViewsClientListByLocationResponse) (DNSPrivateViewsClientListByLocationResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DNSPrivateViewsClient.NewListByLocationPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByLocationCreateRequest(ctx, location, options) + }, nil) + if err != nil { + return DNSPrivateViewsClientListByLocationResponse{}, err + } + return client.listByLocationHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByLocationCreateRequest creates the ListByLocation request. +func (client *DNSPrivateViewsClient) listByLocationCreateRequest(ctx context.Context, location string, _ *DNSPrivateViewsClientListByLocationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/locations/{location}/dnsPrivateViews" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByLocationHandleResponse handles the ListByLocation response. +func (client *DNSPrivateViewsClient) listByLocationHandleResponse(resp *http.Response) (DNSPrivateViewsClientListByLocationResponse, error) { + result := DNSPrivateViewsClientListByLocationResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DNSPrivateViewListResult); err != nil { + return DNSPrivateViewsClientListByLocationResponse{}, err + } + return result, nil +} diff --git a/test/local/armoracledatabase/zz_dnsprivatezones_client.go b/test/local/armoracledatabase/zz_dnsprivatezones_client.go new file mode 100644 index 000000000000..15dcad014582 --- /dev/null +++ b/test/local/armoracledatabase/zz_dnsprivatezones_client.go @@ -0,0 +1,162 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// DNSPrivateZonesClient contains the methods for the DNSPrivateZones group. +// Don't use this type directly, use NewDNSPrivateZonesClient() instead. +// +// Generated from API version 2025-09-01 +type DNSPrivateZonesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewDNSPrivateZonesClient creates a new instance of DNSPrivateZonesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewDNSPrivateZonesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DNSPrivateZonesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &DNSPrivateZonesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get a DnsPrivateZone +// If the operation fails it returns an *azcore.ResponseError type. +// - location - The name of the Azure region. +// - dnsprivatezonename - DnsPrivateZone name +// - options - DNSPrivateZonesClientGetOptions contains the optional parameters for the DNSPrivateZonesClient.Get method. +func (client *DNSPrivateZonesClient) Get(ctx context.Context, location string, dnsprivatezonename string, options *DNSPrivateZonesClientGetOptions) (DNSPrivateZonesClientGetResponse, error) { + var err error + const operationName = "DNSPrivateZonesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, location, dnsprivatezonename, options) + if err != nil { + return DNSPrivateZonesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DNSPrivateZonesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DNSPrivateZonesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *DNSPrivateZonesClient) getCreateRequest(ctx context.Context, location string, dnsprivatezonename string, _ *DNSPrivateZonesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/locations/{location}/dnsPrivateZones/{dnsprivatezonename}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if dnsprivatezonename == "" { + return nil, errors.New("parameter dnsprivatezonename cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{dnsprivatezonename}", url.PathEscape(dnsprivatezonename)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DNSPrivateZonesClient) getHandleResponse(resp *http.Response) (DNSPrivateZonesClientGetResponse, error) { + result := DNSPrivateZonesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DNSPrivateZone); err != nil { + return DNSPrivateZonesClientGetResponse{}, err + } + return result, nil +} + +// NewListByLocationPager - List DnsPrivateZone resources by SubscriptionLocationResource +// - location - The name of the Azure region. +// - options - DNSPrivateZonesClientListByLocationOptions contains the optional parameters for the DNSPrivateZonesClient.NewListByLocationPager +// method. +func (client *DNSPrivateZonesClient) NewListByLocationPager(location string, options *DNSPrivateZonesClientListByLocationOptions) *runtime.Pager[DNSPrivateZonesClientListByLocationResponse] { + return runtime.NewPager(runtime.PagingHandler[DNSPrivateZonesClientListByLocationResponse]{ + More: func(page DNSPrivateZonesClientListByLocationResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *DNSPrivateZonesClientListByLocationResponse) (DNSPrivateZonesClientListByLocationResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "DNSPrivateZonesClient.NewListByLocationPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByLocationCreateRequest(ctx, location, options) + }, nil) + if err != nil { + return DNSPrivateZonesClientListByLocationResponse{}, err + } + return client.listByLocationHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByLocationCreateRequest creates the ListByLocation request. +func (client *DNSPrivateZonesClient) listByLocationCreateRequest(ctx context.Context, location string, _ *DNSPrivateZonesClientListByLocationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/locations/{location}/dnsPrivateZones" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByLocationHandleResponse handles the ListByLocation response. +func (client *DNSPrivateZonesClient) listByLocationHandleResponse(resp *http.Response) (DNSPrivateZonesClientListByLocationResponse, error) { + result := DNSPrivateZonesClientListByLocationResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DNSPrivateZoneListResult); err != nil { + return DNSPrivateZonesClientListByLocationResponse{}, err + } + return result, nil +} diff --git a/test/local/armoracledatabase/zz_exadbvmclusters_client.go b/test/local/armoracledatabase/zz_exadbvmclusters_client.go new file mode 100644 index 000000000000..f35557101a6a --- /dev/null +++ b/test/local/armoracledatabase/zz_exadbvmclusters_client.go @@ -0,0 +1,517 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ExadbVMClustersClient contains the methods for the ExadbVMClusters group. +// Don't use this type directly, use NewExadbVMClustersClient() instead. +// +// Generated from API version 2025-09-01 +type ExadbVMClustersClient struct { + internal *arm.Client + subscriptionID string +} + +// NewExadbVMClustersClient creates a new instance of ExadbVMClustersClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewExadbVMClustersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ExadbVMClustersClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ExadbVMClustersClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create a ExadbVmCluster +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - exadbVMClusterName - The name of the ExadbVmCluster +// - resource - Resource create parameters. +// - options - ExadbVMClustersClientBeginCreateOrUpdateOptions contains the optional parameters for the ExadbVMClustersClient.BeginCreateOrUpdate +// method. +func (client *ExadbVMClustersClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, exadbVMClusterName string, resource ExadbVMCluster, options *ExadbVMClustersClientBeginCreateOrUpdateOptions) (*runtime.Poller[ExadbVMClustersClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, exadbVMClusterName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExadbVMClustersClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExadbVMClustersClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create a ExadbVmCluster +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ExadbVMClustersClient) createOrUpdate(ctx context.Context, resourceGroupName string, exadbVMClusterName string, resource ExadbVMCluster, options *ExadbVMClustersClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ExadbVMClustersClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, exadbVMClusterName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *ExadbVMClustersClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, exadbVMClusterName string, resource ExadbVMCluster, _ *ExadbVMClustersClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/exadbVmClusters/{exadbVmClusterName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if exadbVMClusterName == "" { + return nil, errors.New("parameter exadbVMClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{exadbVmClusterName}", url.PathEscape(exadbVMClusterName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a ExadbVmCluster +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - exadbVMClusterName - The name of the ExadbVmCluster +// - options - ExadbVMClustersClientBeginDeleteOptions contains the optional parameters for the ExadbVMClustersClient.BeginDelete +// method. +func (client *ExadbVMClustersClient) BeginDelete(ctx context.Context, resourceGroupName string, exadbVMClusterName string, options *ExadbVMClustersClientBeginDeleteOptions) (*runtime.Poller[ExadbVMClustersClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, exadbVMClusterName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExadbVMClustersClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExadbVMClustersClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a ExadbVmCluster +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ExadbVMClustersClient) deleteOperation(ctx context.Context, resourceGroupName string, exadbVMClusterName string, options *ExadbVMClustersClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ExadbVMClustersClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, exadbVMClusterName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ExadbVMClustersClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, exadbVMClusterName string, _ *ExadbVMClustersClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/exadbVmClusters/{exadbVmClusterName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if exadbVMClusterName == "" { + return nil, errors.New("parameter exadbVMClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{exadbVmClusterName}", url.PathEscape(exadbVMClusterName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a ExadbVmCluster +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - exadbVMClusterName - The name of the ExadbVmCluster +// - options - ExadbVMClustersClientGetOptions contains the optional parameters for the ExadbVMClustersClient.Get method. +func (client *ExadbVMClustersClient) Get(ctx context.Context, resourceGroupName string, exadbVMClusterName string, options *ExadbVMClustersClientGetOptions) (ExadbVMClustersClientGetResponse, error) { + var err error + const operationName = "ExadbVMClustersClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, exadbVMClusterName, options) + if err != nil { + return ExadbVMClustersClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExadbVMClustersClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExadbVMClustersClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ExadbVMClustersClient) getCreateRequest(ctx context.Context, resourceGroupName string, exadbVMClusterName string, _ *ExadbVMClustersClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/exadbVmClusters/{exadbVmClusterName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if exadbVMClusterName == "" { + return nil, errors.New("parameter exadbVMClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{exadbVmClusterName}", url.PathEscape(exadbVMClusterName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ExadbVMClustersClient) getHandleResponse(resp *http.Response) (ExadbVMClustersClientGetResponse, error) { + result := ExadbVMClustersClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExadbVMCluster); err != nil { + return ExadbVMClustersClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - List ExadbVmCluster resources by resource group +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - ExadbVMClustersClientListByResourceGroupOptions contains the optional parameters for the ExadbVMClustersClient.NewListByResourceGroupPager +// method. +func (client *ExadbVMClustersClient) NewListByResourceGroupPager(resourceGroupName string, options *ExadbVMClustersClientListByResourceGroupOptions) *runtime.Pager[ExadbVMClustersClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[ExadbVMClustersClientListByResourceGroupResponse]{ + More: func(page ExadbVMClustersClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ExadbVMClustersClientListByResourceGroupResponse) (ExadbVMClustersClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ExadbVMClustersClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return ExadbVMClustersClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *ExadbVMClustersClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *ExadbVMClustersClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/exadbVmClusters" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *ExadbVMClustersClient) listByResourceGroupHandleResponse(resp *http.Response) (ExadbVMClustersClientListByResourceGroupResponse, error) { + result := ExadbVMClustersClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExadbVMClusterListResult); err != nil { + return ExadbVMClustersClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - List ExadbVmCluster resources by subscription ID +// - options - ExadbVMClustersClientListBySubscriptionOptions contains the optional parameters for the ExadbVMClustersClient.NewListBySubscriptionPager +// method. +func (client *ExadbVMClustersClient) NewListBySubscriptionPager(options *ExadbVMClustersClientListBySubscriptionOptions) *runtime.Pager[ExadbVMClustersClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[ExadbVMClustersClientListBySubscriptionResponse]{ + More: func(page ExadbVMClustersClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ExadbVMClustersClientListBySubscriptionResponse) (ExadbVMClustersClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ExadbVMClustersClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return ExadbVMClustersClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *ExadbVMClustersClient) listBySubscriptionCreateRequest(ctx context.Context, _ *ExadbVMClustersClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/exadbVmClusters" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *ExadbVMClustersClient) listBySubscriptionHandleResponse(resp *http.Response) (ExadbVMClustersClientListBySubscriptionResponse, error) { + result := ExadbVMClustersClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExadbVMClusterListResult); err != nil { + return ExadbVMClustersClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// BeginRemoveVMs - Remove VMs from the VM Cluster +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - exadbVMClusterName - The name of the ExadbVmCluster +// - body - The content of the action request +// - options - ExadbVMClustersClientBeginRemoveVMsOptions contains the optional parameters for the ExadbVMClustersClient.BeginRemoveVMs +// method. +func (client *ExadbVMClustersClient) BeginRemoveVMs(ctx context.Context, resourceGroupName string, exadbVMClusterName string, body RemoveVirtualMachineFromExadbVMClusterDetails, options *ExadbVMClustersClientBeginRemoveVMsOptions) (*runtime.Poller[ExadbVMClustersClientRemoveVMsResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.removeVMs(ctx, resourceGroupName, exadbVMClusterName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExadbVMClustersClientRemoveVMsResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExadbVMClustersClientRemoveVMsResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// RemoveVMs - Remove VMs from the VM Cluster +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ExadbVMClustersClient) removeVMs(ctx context.Context, resourceGroupName string, exadbVMClusterName string, body RemoveVirtualMachineFromExadbVMClusterDetails, options *ExadbVMClustersClientBeginRemoveVMsOptions) (*http.Response, error) { + var err error + const operationName = "ExadbVMClustersClient.BeginRemoveVMs" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.removeVMsCreateRequest(ctx, resourceGroupName, exadbVMClusterName, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// removeVMsCreateRequest creates the RemoveVMs request. +func (client *ExadbVMClustersClient) removeVMsCreateRequest(ctx context.Context, resourceGroupName string, exadbVMClusterName string, body RemoveVirtualMachineFromExadbVMClusterDetails, _ *ExadbVMClustersClientBeginRemoveVMsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/exadbVmClusters/{exadbVmClusterName}/removeVms" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if exadbVMClusterName == "" { + return nil, errors.New("parameter exadbVMClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{exadbVmClusterName}", url.PathEscape(exadbVMClusterName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// BeginUpdate - Update a ExadbVmCluster +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - exadbVMClusterName - The name of the ExadbVmCluster +// - properties - The resource properties to be updated. +// - options - ExadbVMClustersClientBeginUpdateOptions contains the optional parameters for the ExadbVMClustersClient.BeginUpdate +// method. +func (client *ExadbVMClustersClient) BeginUpdate(ctx context.Context, resourceGroupName string, exadbVMClusterName string, properties ExadbVMClusterUpdate, options *ExadbVMClustersClientBeginUpdateOptions) (*runtime.Poller[ExadbVMClustersClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, exadbVMClusterName, properties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExadbVMClustersClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExadbVMClustersClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a ExadbVmCluster +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ExadbVMClustersClient) update(ctx context.Context, resourceGroupName string, exadbVMClusterName string, properties ExadbVMClusterUpdate, options *ExadbVMClustersClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ExadbVMClustersClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, exadbVMClusterName, properties, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *ExadbVMClustersClient) updateCreateRequest(ctx context.Context, resourceGroupName string, exadbVMClusterName string, properties ExadbVMClusterUpdate, _ *ExadbVMClustersClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/exadbVmClusters/{exadbVmClusterName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if exadbVMClusterName == "" { + return nil, errors.New("parameter exadbVMClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{exadbVmClusterName}", url.PathEscape(exadbVMClusterName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armoracledatabase/zz_exascaledbnodes_client.go b/test/local/armoracledatabase/zz_exascaledbnodes_client.go new file mode 100644 index 000000000000..06e4002d59e4 --- /dev/null +++ b/test/local/armoracledatabase/zz_exascaledbnodes_client.go @@ -0,0 +1,254 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ExascaleDbNodesClient contains the methods for the ExascaleDbNodes group. +// Don't use this type directly, use NewExascaleDbNodesClient() instead. +// +// Generated from API version 2025-09-01 +type ExascaleDbNodesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewExascaleDbNodesClient creates a new instance of ExascaleDbNodesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewExascaleDbNodesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ExascaleDbNodesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ExascaleDbNodesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginAction - VM actions on DbNode of ExadbVmCluster by the provided filter +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - exadbVMClusterName - The name of the ExadbVmCluster +// - exascaleDbNodeName - The name of the ExascaleDbNode +// - body - The content of the action request +// - options - ExascaleDbNodesClientBeginActionOptions contains the optional parameters for the ExascaleDbNodesClient.BeginAction +// method. +func (client *ExascaleDbNodesClient) BeginAction(ctx context.Context, resourceGroupName string, exadbVMClusterName string, exascaleDbNodeName string, body DbNodeAction, options *ExascaleDbNodesClientBeginActionOptions) (*runtime.Poller[ExascaleDbNodesClientActionResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.action(ctx, resourceGroupName, exadbVMClusterName, exascaleDbNodeName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExascaleDbNodesClientActionResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExascaleDbNodesClientActionResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Action - VM actions on DbNode of ExadbVmCluster by the provided filter +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ExascaleDbNodesClient) action(ctx context.Context, resourceGroupName string, exadbVMClusterName string, exascaleDbNodeName string, body DbNodeAction, options *ExascaleDbNodesClientBeginActionOptions) (*http.Response, error) { + var err error + const operationName = "ExascaleDbNodesClient.BeginAction" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.actionCreateRequest(ctx, resourceGroupName, exadbVMClusterName, exascaleDbNodeName, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// actionCreateRequest creates the Action request. +func (client *ExascaleDbNodesClient) actionCreateRequest(ctx context.Context, resourceGroupName string, exadbVMClusterName string, exascaleDbNodeName string, body DbNodeAction, _ *ExascaleDbNodesClientBeginActionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/exadbVmClusters/{exadbVmClusterName}/dbNodes/{exascaleDbNodeName}/action" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if exadbVMClusterName == "" { + return nil, errors.New("parameter exadbVMClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{exadbVmClusterName}", url.PathEscape(exadbVMClusterName)) + if exascaleDbNodeName == "" { + return nil, errors.New("parameter exascaleDbNodeName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{exascaleDbNodeName}", url.PathEscape(exascaleDbNodeName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// Get - Get a ExascaleDbNode +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - exadbVMClusterName - The name of the ExadbVmCluster +// - exascaleDbNodeName - The name of the ExascaleDbNode +// - options - ExascaleDbNodesClientGetOptions contains the optional parameters for the ExascaleDbNodesClient.Get method. +func (client *ExascaleDbNodesClient) Get(ctx context.Context, resourceGroupName string, exadbVMClusterName string, exascaleDbNodeName string, options *ExascaleDbNodesClientGetOptions) (ExascaleDbNodesClientGetResponse, error) { + var err error + const operationName = "ExascaleDbNodesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, exadbVMClusterName, exascaleDbNodeName, options) + if err != nil { + return ExascaleDbNodesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExascaleDbNodesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExascaleDbNodesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ExascaleDbNodesClient) getCreateRequest(ctx context.Context, resourceGroupName string, exadbVMClusterName string, exascaleDbNodeName string, _ *ExascaleDbNodesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/exadbVmClusters/{exadbVmClusterName}/dbNodes/{exascaleDbNodeName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if exadbVMClusterName == "" { + return nil, errors.New("parameter exadbVMClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{exadbVmClusterName}", url.PathEscape(exadbVMClusterName)) + if exascaleDbNodeName == "" { + return nil, errors.New("parameter exascaleDbNodeName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{exascaleDbNodeName}", url.PathEscape(exascaleDbNodeName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ExascaleDbNodesClient) getHandleResponse(resp *http.Response) (ExascaleDbNodesClientGetResponse, error) { + result := ExascaleDbNodesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExascaleDbNode); err != nil { + return ExascaleDbNodesClientGetResponse{}, err + } + return result, nil +} + +// NewListByParentPager - List ExascaleDbNode resources by ExadbVmCluster +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - exadbVMClusterName - The name of the ExadbVmCluster +// - options - ExascaleDbNodesClientListByParentOptions contains the optional parameters for the ExascaleDbNodesClient.NewListByParentPager +// method. +func (client *ExascaleDbNodesClient) NewListByParentPager(resourceGroupName string, exadbVMClusterName string, options *ExascaleDbNodesClientListByParentOptions) *runtime.Pager[ExascaleDbNodesClientListByParentResponse] { + return runtime.NewPager(runtime.PagingHandler[ExascaleDbNodesClientListByParentResponse]{ + More: func(page ExascaleDbNodesClientListByParentResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ExascaleDbNodesClientListByParentResponse) (ExascaleDbNodesClientListByParentResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ExascaleDbNodesClient.NewListByParentPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByParentCreateRequest(ctx, resourceGroupName, exadbVMClusterName, options) + }, nil) + if err != nil { + return ExascaleDbNodesClientListByParentResponse{}, err + } + return client.listByParentHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByParentCreateRequest creates the ListByParent request. +func (client *ExascaleDbNodesClient) listByParentCreateRequest(ctx context.Context, resourceGroupName string, exadbVMClusterName string, _ *ExascaleDbNodesClientListByParentOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/exadbVmClusters/{exadbVmClusterName}/dbNodes" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if exadbVMClusterName == "" { + return nil, errors.New("parameter exadbVMClusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{exadbVmClusterName}", url.PathEscape(exadbVMClusterName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByParentHandleResponse handles the ListByParent response. +func (client *ExascaleDbNodesClient) listByParentHandleResponse(resp *http.Response) (ExascaleDbNodesClientListByParentResponse, error) { + result := ExascaleDbNodesClientListByParentResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExascaleDbNodeListResult); err != nil { + return ExascaleDbNodesClientListByParentResponse{}, err + } + return result, nil +} diff --git a/test/local/armoracledatabase/zz_exascaledbstoragevaults_client.go b/test/local/armoracledatabase/zz_exascaledbstoragevaults_client.go new file mode 100644 index 000000000000..73f65e06a9de --- /dev/null +++ b/test/local/armoracledatabase/zz_exascaledbstoragevaults_client.go @@ -0,0 +1,441 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ExascaleDbStorageVaultsClient contains the methods for the ExascaleDbStorageVaults group. +// Don't use this type directly, use NewExascaleDbStorageVaultsClient() instead. +// +// Generated from API version 2025-09-01 +type ExascaleDbStorageVaultsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewExascaleDbStorageVaultsClient creates a new instance of ExascaleDbStorageVaultsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewExascaleDbStorageVaultsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ExascaleDbStorageVaultsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ExascaleDbStorageVaultsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreate - Create a ExascaleDbStorageVault +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - exascaleDbStorageVaultName - The name of the ExascaleDbStorageVault +// - resource - Resource create parameters. +// - options - ExascaleDbStorageVaultsClientBeginCreateOptions contains the optional parameters for the ExascaleDbStorageVaultsClient.BeginCreate +// method. +func (client *ExascaleDbStorageVaultsClient) BeginCreate(ctx context.Context, resourceGroupName string, exascaleDbStorageVaultName string, resource ExascaleDbStorageVault, options *ExascaleDbStorageVaultsClientBeginCreateOptions) (*runtime.Poller[ExascaleDbStorageVaultsClientCreateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.create(ctx, resourceGroupName, exascaleDbStorageVaultName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExascaleDbStorageVaultsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExascaleDbStorageVaultsClientCreateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Create - Create a ExascaleDbStorageVault +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ExascaleDbStorageVaultsClient) create(ctx context.Context, resourceGroupName string, exascaleDbStorageVaultName string, resource ExascaleDbStorageVault, options *ExascaleDbStorageVaultsClientBeginCreateOptions) (*http.Response, error) { + var err error + const operationName = "ExascaleDbStorageVaultsClient.BeginCreate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createCreateRequest(ctx, resourceGroupName, exascaleDbStorageVaultName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createCreateRequest creates the Create request. +func (client *ExascaleDbStorageVaultsClient) createCreateRequest(ctx context.Context, resourceGroupName string, exascaleDbStorageVaultName string, resource ExascaleDbStorageVault, _ *ExascaleDbStorageVaultsClientBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/exascaleDbStorageVaults/{exascaleDbStorageVaultName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if exascaleDbStorageVaultName == "" { + return nil, errors.New("parameter exascaleDbStorageVaultName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{exascaleDbStorageVaultName}", url.PathEscape(exascaleDbStorageVaultName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a ExascaleDbStorageVault +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - exascaleDbStorageVaultName - The name of the ExascaleDbStorageVault +// - options - ExascaleDbStorageVaultsClientBeginDeleteOptions contains the optional parameters for the ExascaleDbStorageVaultsClient.BeginDelete +// method. +func (client *ExascaleDbStorageVaultsClient) BeginDelete(ctx context.Context, resourceGroupName string, exascaleDbStorageVaultName string, options *ExascaleDbStorageVaultsClientBeginDeleteOptions) (*runtime.Poller[ExascaleDbStorageVaultsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, exascaleDbStorageVaultName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExascaleDbStorageVaultsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExascaleDbStorageVaultsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a ExascaleDbStorageVault +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ExascaleDbStorageVaultsClient) deleteOperation(ctx context.Context, resourceGroupName string, exascaleDbStorageVaultName string, options *ExascaleDbStorageVaultsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ExascaleDbStorageVaultsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, exascaleDbStorageVaultName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ExascaleDbStorageVaultsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, exascaleDbStorageVaultName string, _ *ExascaleDbStorageVaultsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/exascaleDbStorageVaults/{exascaleDbStorageVaultName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if exascaleDbStorageVaultName == "" { + return nil, errors.New("parameter exascaleDbStorageVaultName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{exascaleDbStorageVaultName}", url.PathEscape(exascaleDbStorageVaultName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a ExascaleDbStorageVault +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - exascaleDbStorageVaultName - The name of the ExascaleDbStorageVault +// - options - ExascaleDbStorageVaultsClientGetOptions contains the optional parameters for the ExascaleDbStorageVaultsClient.Get +// method. +func (client *ExascaleDbStorageVaultsClient) Get(ctx context.Context, resourceGroupName string, exascaleDbStorageVaultName string, options *ExascaleDbStorageVaultsClientGetOptions) (ExascaleDbStorageVaultsClientGetResponse, error) { + var err error + const operationName = "ExascaleDbStorageVaultsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, exascaleDbStorageVaultName, options) + if err != nil { + return ExascaleDbStorageVaultsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ExascaleDbStorageVaultsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ExascaleDbStorageVaultsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ExascaleDbStorageVaultsClient) getCreateRequest(ctx context.Context, resourceGroupName string, exascaleDbStorageVaultName string, _ *ExascaleDbStorageVaultsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/exascaleDbStorageVaults/{exascaleDbStorageVaultName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if exascaleDbStorageVaultName == "" { + return nil, errors.New("parameter exascaleDbStorageVaultName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{exascaleDbStorageVaultName}", url.PathEscape(exascaleDbStorageVaultName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ExascaleDbStorageVaultsClient) getHandleResponse(resp *http.Response) (ExascaleDbStorageVaultsClientGetResponse, error) { + result := ExascaleDbStorageVaultsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExascaleDbStorageVault); err != nil { + return ExascaleDbStorageVaultsClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - List ExascaleDbStorageVault resources by resource group +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - ExascaleDbStorageVaultsClientListByResourceGroupOptions contains the optional parameters for the ExascaleDbStorageVaultsClient.NewListByResourceGroupPager +// method. +func (client *ExascaleDbStorageVaultsClient) NewListByResourceGroupPager(resourceGroupName string, options *ExascaleDbStorageVaultsClientListByResourceGroupOptions) *runtime.Pager[ExascaleDbStorageVaultsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[ExascaleDbStorageVaultsClientListByResourceGroupResponse]{ + More: func(page ExascaleDbStorageVaultsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ExascaleDbStorageVaultsClientListByResourceGroupResponse) (ExascaleDbStorageVaultsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ExascaleDbStorageVaultsClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return ExascaleDbStorageVaultsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *ExascaleDbStorageVaultsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *ExascaleDbStorageVaultsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/exascaleDbStorageVaults" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *ExascaleDbStorageVaultsClient) listByResourceGroupHandleResponse(resp *http.Response) (ExascaleDbStorageVaultsClientListByResourceGroupResponse, error) { + result := ExascaleDbStorageVaultsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExascaleDbStorageVaultListResult); err != nil { + return ExascaleDbStorageVaultsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - List ExascaleDbStorageVault resources by subscription ID +// - options - ExascaleDbStorageVaultsClientListBySubscriptionOptions contains the optional parameters for the ExascaleDbStorageVaultsClient.NewListBySubscriptionPager +// method. +func (client *ExascaleDbStorageVaultsClient) NewListBySubscriptionPager(options *ExascaleDbStorageVaultsClientListBySubscriptionOptions) *runtime.Pager[ExascaleDbStorageVaultsClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[ExascaleDbStorageVaultsClientListBySubscriptionResponse]{ + More: func(page ExascaleDbStorageVaultsClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ExascaleDbStorageVaultsClientListBySubscriptionResponse) (ExascaleDbStorageVaultsClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ExascaleDbStorageVaultsClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return ExascaleDbStorageVaultsClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *ExascaleDbStorageVaultsClient) listBySubscriptionCreateRequest(ctx context.Context, _ *ExascaleDbStorageVaultsClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/exascaleDbStorageVaults" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *ExascaleDbStorageVaultsClient) listBySubscriptionHandleResponse(resp *http.Response) (ExascaleDbStorageVaultsClientListBySubscriptionResponse, error) { + result := ExascaleDbStorageVaultsClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ExascaleDbStorageVaultListResult); err != nil { + return ExascaleDbStorageVaultsClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update a ExascaleDbStorageVault +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - exascaleDbStorageVaultName - The name of the ExascaleDbStorageVault +// - properties - The resource properties to be updated. +// - options - ExascaleDbStorageVaultsClientBeginUpdateOptions contains the optional parameters for the ExascaleDbStorageVaultsClient.BeginUpdate +// method. +func (client *ExascaleDbStorageVaultsClient) BeginUpdate(ctx context.Context, resourceGroupName string, exascaleDbStorageVaultName string, properties ExascaleDbStorageVaultTagsUpdate, options *ExascaleDbStorageVaultsClientBeginUpdateOptions) (*runtime.Poller[ExascaleDbStorageVaultsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, exascaleDbStorageVaultName, properties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ExascaleDbStorageVaultsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ExascaleDbStorageVaultsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a ExascaleDbStorageVault +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ExascaleDbStorageVaultsClient) update(ctx context.Context, resourceGroupName string, exascaleDbStorageVaultName string, properties ExascaleDbStorageVaultTagsUpdate, options *ExascaleDbStorageVaultsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ExascaleDbStorageVaultsClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, exascaleDbStorageVaultName, properties, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *ExascaleDbStorageVaultsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, exascaleDbStorageVaultName string, properties ExascaleDbStorageVaultTagsUpdate, _ *ExascaleDbStorageVaultsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/exascaleDbStorageVaults/{exascaleDbStorageVaultName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if exascaleDbStorageVaultName == "" { + return nil, errors.New("parameter exascaleDbStorageVaultName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{exascaleDbStorageVaultName}", url.PathEscape(exascaleDbStorageVaultName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armoracledatabase/zz_flexcomponents_client.go b/test/local/armoracledatabase/zz_flexcomponents_client.go new file mode 100644 index 000000000000..9b13256a5f01 --- /dev/null +++ b/test/local/armoracledatabase/zz_flexcomponents_client.go @@ -0,0 +1,165 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// FlexComponentsClient contains the methods for the FlexComponents group. +// Don't use this type directly, use NewFlexComponentsClient() instead. +// +// Generated from API version 2025-09-01 +type FlexComponentsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewFlexComponentsClient creates a new instance of FlexComponentsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewFlexComponentsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*FlexComponentsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &FlexComponentsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get a FlexComponent +// If the operation fails it returns an *azcore.ResponseError type. +// - location - The name of the Azure region. +// - flexComponentName - The name of the FlexComponent +// - options - FlexComponentsClientGetOptions contains the optional parameters for the FlexComponentsClient.Get method. +func (client *FlexComponentsClient) Get(ctx context.Context, location string, flexComponentName string, options *FlexComponentsClientGetOptions) (FlexComponentsClientGetResponse, error) { + var err error + const operationName = "FlexComponentsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, location, flexComponentName, options) + if err != nil { + return FlexComponentsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return FlexComponentsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return FlexComponentsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *FlexComponentsClient) getCreateRequest(ctx context.Context, location string, flexComponentName string, _ *FlexComponentsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/locations/{location}/flexComponents/{flexComponentName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if flexComponentName == "" { + return nil, errors.New("parameter flexComponentName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{flexComponentName}", url.PathEscape(flexComponentName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *FlexComponentsClient) getHandleResponse(resp *http.Response) (FlexComponentsClientGetResponse, error) { + result := FlexComponentsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FlexComponent); err != nil { + return FlexComponentsClientGetResponse{}, err + } + return result, nil +} + +// NewListByParentPager - List FlexComponent resources by SubscriptionLocationResource +// - location - The name of the Azure region. +// - options - FlexComponentsClientListByParentOptions contains the optional parameters for the FlexComponentsClient.NewListByParentPager +// method. +func (client *FlexComponentsClient) NewListByParentPager(location string, options *FlexComponentsClientListByParentOptions) *runtime.Pager[FlexComponentsClientListByParentResponse] { + return runtime.NewPager(runtime.PagingHandler[FlexComponentsClientListByParentResponse]{ + More: func(page FlexComponentsClientListByParentResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *FlexComponentsClientListByParentResponse) (FlexComponentsClientListByParentResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "FlexComponentsClient.NewListByParentPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByParentCreateRequest(ctx, location, options) + }, nil) + if err != nil { + return FlexComponentsClientListByParentResponse{}, err + } + return client.listByParentHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByParentCreateRequest creates the ListByParent request. +func (client *FlexComponentsClient) listByParentCreateRequest(ctx context.Context, location string, options *FlexComponentsClientListByParentOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/locations/{location}/flexComponents" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + if options != nil && options.Shape != nil { + reqQP.Set("shape", string(*options.Shape)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByParentHandleResponse handles the ListByParent response. +func (client *FlexComponentsClient) listByParentHandleResponse(resp *http.Response) (FlexComponentsClientListByParentResponse, error) { + result := FlexComponentsClientListByParentResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FlexComponentListResult); err != nil { + return FlexComponentsClientListByParentResponse{}, err + } + return result, nil +} diff --git a/test/local/armoracledatabase/zz_giminorversions_client.go b/test/local/armoracledatabase/zz_giminorversions_client.go new file mode 100644 index 000000000000..e48c9cb7197b --- /dev/null +++ b/test/local/armoracledatabase/zz_giminorversions_client.go @@ -0,0 +1,178 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// GiMinorVersionsClient contains the methods for the GiMinorVersions group. +// Don't use this type directly, use NewGiMinorVersionsClient() instead. +// +// Generated from API version 2025-09-01 +type GiMinorVersionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewGiMinorVersionsClient creates a new instance of GiMinorVersionsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewGiMinorVersionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*GiMinorVersionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &GiMinorVersionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get a GiMinorVersion +// If the operation fails it returns an *azcore.ResponseError type. +// - location - The name of the Azure region. +// - giversionname - GiVersion name +// - giMinorVersionName - The name of the GiMinorVersion +// - options - GiMinorVersionsClientGetOptions contains the optional parameters for the GiMinorVersionsClient.Get method. +func (client *GiMinorVersionsClient) Get(ctx context.Context, location string, giversionname string, giMinorVersionName string, options *GiMinorVersionsClientGetOptions) (GiMinorVersionsClientGetResponse, error) { + var err error + const operationName = "GiMinorVersionsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, location, giversionname, giMinorVersionName, options) + if err != nil { + return GiMinorVersionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GiMinorVersionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GiMinorVersionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *GiMinorVersionsClient) getCreateRequest(ctx context.Context, location string, giversionname string, giMinorVersionName string, _ *GiMinorVersionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/locations/{location}/giVersions/{giversionname}/giMinorVersions/{giMinorVersionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if giversionname == "" { + return nil, errors.New("parameter giversionname cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{giversionname}", url.PathEscape(giversionname)) + if giMinorVersionName == "" { + return nil, errors.New("parameter giMinorVersionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{giMinorVersionName}", url.PathEscape(giMinorVersionName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *GiMinorVersionsClient) getHandleResponse(resp *http.Response) (GiMinorVersionsClientGetResponse, error) { + result := GiMinorVersionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.GiMinorVersion); err != nil { + return GiMinorVersionsClientGetResponse{}, err + } + return result, nil +} + +// NewListByParentPager - List GiMinorVersion resources by GiVersion +// - location - The name of the Azure region. +// - giversionname - GiVersion name +// - options - GiMinorVersionsClientListByParentOptions contains the optional parameters for the GiMinorVersionsClient.NewListByParentPager +// method. +func (client *GiMinorVersionsClient) NewListByParentPager(location string, giversionname string, options *GiMinorVersionsClientListByParentOptions) *runtime.Pager[GiMinorVersionsClientListByParentResponse] { + return runtime.NewPager(runtime.PagingHandler[GiMinorVersionsClientListByParentResponse]{ + More: func(page GiMinorVersionsClientListByParentResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *GiMinorVersionsClientListByParentResponse) (GiMinorVersionsClientListByParentResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "GiMinorVersionsClient.NewListByParentPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByParentCreateRequest(ctx, location, giversionname, options) + }, nil) + if err != nil { + return GiMinorVersionsClientListByParentResponse{}, err + } + return client.listByParentHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByParentCreateRequest creates the ListByParent request. +func (client *GiMinorVersionsClient) listByParentCreateRequest(ctx context.Context, location string, giversionname string, options *GiMinorVersionsClientListByParentOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/locations/{location}/giVersions/{giversionname}/giMinorVersions" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if giversionname == "" { + return nil, errors.New("parameter giversionname cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{giversionname}", url.PathEscape(giversionname)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + if options != nil && options.ShapeFamily != nil { + reqQP.Set("shapeFamily", string(*options.ShapeFamily)) + } + if options != nil && options.Zone != nil { + reqQP.Set("zone", *options.Zone) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByParentHandleResponse handles the ListByParent response. +func (client *GiMinorVersionsClient) listByParentHandleResponse(resp *http.Response) (GiMinorVersionsClientListByParentResponse, error) { + result := GiMinorVersionsClientListByParentResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.GiMinorVersionListResult); err != nil { + return GiMinorVersionsClientListByParentResponse{}, err + } + return result, nil +} diff --git a/test/local/armoracledatabase/zz_giversions_client.go b/test/local/armoracledatabase/zz_giversions_client.go new file mode 100644 index 000000000000..be199970b641 --- /dev/null +++ b/test/local/armoracledatabase/zz_giversions_client.go @@ -0,0 +1,171 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// GiVersionsClient contains the methods for the GiVersions group. +// Don't use this type directly, use NewGiVersionsClient() instead. +// +// Generated from API version 2025-09-01 +type GiVersionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewGiVersionsClient creates a new instance of GiVersionsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewGiVersionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*GiVersionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &GiVersionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get a GiVersion +// If the operation fails it returns an *azcore.ResponseError type. +// - location - The name of the Azure region. +// - giversionname - GiVersion name +// - options - GiVersionsClientGetOptions contains the optional parameters for the GiVersionsClient.Get method. +func (client *GiVersionsClient) Get(ctx context.Context, location string, giversionname string, options *GiVersionsClientGetOptions) (GiVersionsClientGetResponse, error) { + var err error + const operationName = "GiVersionsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, location, giversionname, options) + if err != nil { + return GiVersionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GiVersionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GiVersionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *GiVersionsClient) getCreateRequest(ctx context.Context, location string, giversionname string, _ *GiVersionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/locations/{location}/giVersions/{giversionname}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if giversionname == "" { + return nil, errors.New("parameter giversionname cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{giversionname}", url.PathEscape(giversionname)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *GiVersionsClient) getHandleResponse(resp *http.Response) (GiVersionsClientGetResponse, error) { + result := GiVersionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.GiVersion); err != nil { + return GiVersionsClientGetResponse{}, err + } + return result, nil +} + +// NewListByLocationPager - List GiVersion resources by SubscriptionLocationResource +// - location - The name of the Azure region. +// - options - GiVersionsClientListByLocationOptions contains the optional parameters for the GiVersionsClient.NewListByLocationPager +// method. +func (client *GiVersionsClient) NewListByLocationPager(location string, options *GiVersionsClientListByLocationOptions) *runtime.Pager[GiVersionsClientListByLocationResponse] { + return runtime.NewPager(runtime.PagingHandler[GiVersionsClientListByLocationResponse]{ + More: func(page GiVersionsClientListByLocationResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *GiVersionsClientListByLocationResponse) (GiVersionsClientListByLocationResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "GiVersionsClient.NewListByLocationPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByLocationCreateRequest(ctx, location, options) + }, nil) + if err != nil { + return GiVersionsClientListByLocationResponse{}, err + } + return client.listByLocationHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByLocationCreateRequest creates the ListByLocation request. +func (client *GiVersionsClient) listByLocationCreateRequest(ctx context.Context, location string, options *GiVersionsClientListByLocationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/locations/{location}/giVersions" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + if options != nil && options.Shape != nil { + reqQP.Set("shape", string(*options.Shape)) + } + if options != nil && options.ShapeAttribute != nil { + reqQP.Set("shapeAttribute", *options.ShapeAttribute) + } + if options != nil && options.Zone != nil { + reqQP.Set("zone", *options.Zone) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByLocationHandleResponse handles the ListByLocation response. +func (client *GiVersionsClient) listByLocationHandleResponse(resp *http.Response) (GiVersionsClientListByLocationResponse, error) { + result := GiVersionsClientListByLocationResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.GiVersionListResult); err != nil { + return GiVersionsClientListByLocationResponse{}, err + } + return result, nil +} diff --git a/test/local/armoracledatabase/zz_interfaces.go b/test/local/armoracledatabase/zz_interfaces.go new file mode 100644 index 000000000000..bf3cf1669f11 --- /dev/null +++ b/test/local/armoracledatabase/zz_interfaces.go @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +// AutonomousDatabaseBasePropertiesClassification provides polymorphic access to related types. +// Call the interface's GetAutonomousDatabaseBaseProperties() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *AutonomousDatabaseBaseProperties, *AutonomousDatabaseCloneProperties, *AutonomousDatabaseCrossRegionDisasterRecoveryProperties, +// - *AutonomousDatabaseFromBackupTimestampProperties, *AutonomousDatabaseProperties +type AutonomousDatabaseBasePropertiesClassification interface { + // GetAutonomousDatabaseBaseProperties returns the AutonomousDatabaseBaseProperties content of the underlying type. + GetAutonomousDatabaseBaseProperties() *AutonomousDatabaseBaseProperties +} + +// DbSystemBasePropertiesClassification provides polymorphic access to related types. +// Call the interface's GetDbSystemBaseProperties() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *DbSystemBaseProperties, *DbSystemProperties +type DbSystemBasePropertiesClassification interface { + // GetDbSystemBaseProperties returns the DbSystemBaseProperties content of the underlying type. + GetDbSystemBaseProperties() *DbSystemBaseProperties +} diff --git a/test/local/armoracledatabase/zz_models.go b/test/local/armoracledatabase/zz_models.go new file mode 100644 index 000000000000..88e8bcc6641c --- /dev/null +++ b/test/local/armoracledatabase/zz_models.go @@ -0,0 +1,4684 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import "time" + +// ActivationLinks - Activation Links model +type ActivationLinks struct { + // READ-ONLY; Existing Cloud Account Activation Link + ExistingCloudAccountActivationLink *string + + // READ-ONLY; New Cloud Account Activation Link + NewCloudAccountActivationLink *string +} + +// AddRemoveDbNode - Add/Remove (Virtual Machine) DbNode model +type AddRemoveDbNode struct { + // REQUIRED; Db servers ocids + DbServers []*string +} + +// AllConnectionStringType - The connection string profile to allow clients to group, filter and select connection string +// values based on structured metadata. +type AllConnectionStringType struct { + // The High database service provides the highest level of resources to each SQL statement resulting in the highest performance, + // but supports the fewest number of concurrent SQL statements. + High *string + + // The Low database service provides the least level of resources to each SQL statement, but supports the most number of concurrent + // SQL statements. + Low *string + + // The Medium database service provides a lower level of resources to each SQL statement potentially resulting a lower level + // of performance, but supports more concurrent SQL statements. + Medium *string +} + +// ApexDetailsType - Information about Oracle APEX Application Development. +type ApexDetailsType struct { + // The Oracle APEX Application Development version. + ApexVersion *string + + // The Oracle REST Data Services (ORDS) version. + OrdsVersion *string +} + +// AutonomousDatabase - Autonomous Database resource model. +type AutonomousDatabase struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties AutonomousDatabaseBasePropertiesClassification + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// AutonomousDatabaseBackup resource definition +type AutonomousDatabaseBackup struct { + // The resource-specific properties for this resource. + Properties *AutonomousDatabaseBackupProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// AutonomousDatabaseBackupListResult - The response of a AutonomousDatabaseBackup list operation. +type AutonomousDatabaseBackupListResult struct { + // REQUIRED; The AutonomousDatabaseBackup items on this page + Value []*AutonomousDatabaseBackup + + // The link to the next page of items + NextLink *string +} + +// AutonomousDatabaseBackupProperties - AutonomousDatabaseBackup resource model +type AutonomousDatabaseBackupProperties struct { + // The user-friendly name for the backup. The name does not have to be unique. + DisplayName *string + + // Retention period, in days + RetentionPeriodInDays *int32 + + // READ-ONLY; The OCID of the Autonomous Database. + AutonomousDatabaseOcid *string + + // READ-ONLY; The type of backup. + BackupType *AutonomousDatabaseBackupType + + // READ-ONLY; The size of the database in terabytes at the time the backup was taken. + DatabaseSizeInTbs *float64 + + // READ-ONLY; A valid Oracle Database version for Autonomous Database. + DbVersion *string + + // READ-ONLY; Indicates whether the backup is user-initiated or automatic. + IsAutomatic *bool + + // READ-ONLY; Indicates whether the backup can be used to restore the associated Autonomous Database. + IsRestorable *bool + + // READ-ONLY; Additional information about the current lifecycle state. + LifecycleDetails *string + + // READ-ONLY; The current state of the backup. + LifecycleState *AutonomousDatabaseBackupLifecycleState + + // READ-ONLY; The OCID of the Autonomous Database backup. + Ocid *string + + // READ-ONLY; Azure resource provisioning state. + ProvisioningState *AzureResourceProvisioningState + + // READ-ONLY; The backup size in terabytes (TB). + SizeInTbs *float64 + + // READ-ONLY; Timestamp until when the backup will be available. + TimeAvailableTil *time.Time + + // READ-ONLY; The date and time the backup completed. + TimeEnded *string + + // READ-ONLY; The date and time the backup started. + TimeStarted *string +} + +// AutonomousDatabaseBackupUpdate - The type used for update operations of the AutonomousDatabaseBackup. +type AutonomousDatabaseBackupUpdate struct { + // The resource-specific properties for this resource. + Properties *AutonomousDatabaseBackupUpdateProperties +} + +// AutonomousDatabaseBackupUpdateProperties - The updatable properties of the AutonomousDatabaseBackup. +type AutonomousDatabaseBackupUpdateProperties struct { + // Retention period, in days + RetentionPeriodInDays *int32 +} + +// AutonomousDatabaseBaseProperties - Autonomous Database base resource model. +type AutonomousDatabaseBaseProperties struct { + // REQUIRED; Database type to be created. + DataBaseType *DataBaseType + + // Admin password. + AdminPassword *string + + // Autonomous Database ID + AutonomousDatabaseID *string + + // The maintenance schedule type of the Autonomous Database Serverless. + AutonomousMaintenanceScheduleType *AutonomousMaintenanceScheduleType + + // Retention period, in days, for long-term backups + BackupRetentionPeriodInDays *int32 + + // The number of CPU cores to be made available to the database. + CPUCoreCount *int32 + + // The character set for the autonomous database. + CharacterSet *string + + // The compute amount (CPUs) available to the database. + ComputeCount *float32 + + // The compute model of the Autonomous Database. + ComputeModel *ComputeModel + + // Customer Contacts. + CustomerContacts []*CustomerContact + + // The size, in gigabytes, of the data volume that will be created and attached to the database. + DataStorageSizeInGbs *int32 + + // The quantity of data in the database, in terabytes. + DataStorageSizeInTbs *int32 + + // The Oracle Database Edition that applies to the Autonomous databases. + DatabaseEdition *DatabaseEditionType + + // A valid Oracle Database version for Autonomous Database. + DbVersion *string + + // The Autonomous Database workload type + DbWorkload *WorkloadType + + // The user-friendly name for the Autonomous Database. + DisplayName *string + + // Indicates if auto scaling is enabled for the Autonomous Database CPU core count. + IsAutoScalingEnabled *bool + + // Indicates if auto scaling is enabled for the Autonomous Database storage. + IsAutoScalingForStorageEnabled *bool + + // Indicates whether the Autonomous Database has local or called in-region Data Guard enabled. + IsLocalDataGuardEnabled *bool + + // Specifies if the Autonomous Database requires mTLS connections. + IsMtlsConnectionRequired *bool + + // Specifies if the Autonomous Database preview version is being provisioned. + IsPreviewVersionWithServiceTermsAccepted *bool + + // The Oracle license model that applies to the Oracle Autonomous Database. The default is LICENSE_INCLUDED. + LicenseModel *LicenseModel + + // Parameter that allows users to select an acceptable maximum data loss limit in seconds, up to which Automatic Failover + // will be triggered when necessary for a Local Autonomous Data Guard + LocalAdgAutoFailoverMaxDataLossLimit *int32 + + // Details for the long-term backup schedule. + LongTermBackupSchedule *LongTermBackUpScheduleDetails + + // The character set for the Autonomous Database. + NcharacterSet *string + + // Indicates the Autonomous Database mode. + OpenMode *OpenModeType + + // The Azure resource ID of the Disaster Recovery peer database, which is located in a different region from the current peer + // database. + PeerDbID *string + + // The Autonomous Database permission level. + PermissionLevel *PermissionLevelType + + // The private endpoint Ip address for the resource. + PrivateEndpointIP *string + + // The resource's private endpoint label. + PrivateEndpointLabel *string + + // The Data Guard role of the Autonomous Container Database or Autonomous Database, if Autonomous Data Guard is enabled. + Role *RoleType + + // The list of scheduled operations. + ScheduledOperationsList []*ScheduledOperationsType + + // Client subnet + SubnetID *string + + // VNET for network connectivity + VnetID *string + + // The client IP access control list (ACL). This is an array of CIDR notations and/or IP addresses. Values should be separate + // strings, separated by commas. Example: ['1.1.1.1','1.1.1.0/24','1.1.2.25'] + WhitelistedIPs []*string + + // READ-ONLY; The current amount of storage in use for user and system data, in terabytes (TB). + ActualUsedDataStorageSizeInTbs *float64 + + // READ-ONLY; The amount of storage currently allocated for the database tables and billed for, rounded up. + AllocatedStorageSizeInTbs *float64 + + // READ-ONLY; Information about Oracle APEX Application Development. + ApexDetails *ApexDetailsType + + // READ-ONLY; List of Oracle Database versions available for a database upgrade. If there are no version upgrades available, + // this list is empty. + AvailableUpgradeVersions []*string + + // READ-ONLY; The connection string used to connect to the Autonomous Database. + ConnectionStrings *ConnectionStringType + + // READ-ONLY; The URLs for accessing Oracle Application Express (APEX) and SQL Developer Web with a browser from a Compute + // instance within your VCN or that has a direct connection to your VCN. + ConnectionUrls *ConnectionURLType + + // READ-ONLY; Status of the Data Safe registration for this Autonomous Database. + DataSafeStatus *DataSafeStatusType + + // READ-ONLY; Indicates the number of seconds of data loss for a Data Guard failover. + FailedDataRecoveryInSeconds *int32 + + // READ-ONLY; The area assigned to In-Memory tables in Autonomous Database. + InMemoryAreaInGbs *int32 + + // READ-ONLY; Indicates if the Autonomous Database version is a preview version. + IsPreview *bool + + // READ-ONLY; Indicates whether the Autonomous Database has Cross Region Data Guard enabled. + IsRemoteDataGuardEnabled *bool + + // READ-ONLY; Additional information about the current lifecycle state. + LifecycleDetails *string + + // READ-ONLY; Views lifecycleState + LifecycleState *AutonomousDatabaseLifecycleState + + // READ-ONLY; Indicates the local disaster recovery (DR) type of the Autonomous Database Serverless instance.Autonomous Data + // Guard (ADG) DR type provides business critical DR with a faster recovery time objective (RTO) during failover or switchover.Backup-based + // DR type provides lower cost DR with a slower RTO during failover or switchover. + LocalDisasterRecoveryType *DisasterRecoveryType + + // READ-ONLY; Local Autonomous Disaster Recovery standby database details. + LocalStandbyDb *AutonomousDatabaseStandbySummary + + // READ-ONLY; The amount of memory (in GBs) enabled per ECPU or OCPU. + MemoryPerOracleComputeUnitInGbs *int32 + + // READ-ONLY; The date and time when the next long-term backup would be created. + NextLongTermBackupTimeStamp *time.Time + + // READ-ONLY; HTTPS link to OCI resources exposed to Azure Customer via Azure Interface. + OciURL *string + + // READ-ONLY; Database ocid + Ocid *string + + // READ-ONLY; Status of Operations Insights for this Autonomous Database. + OperationsInsightsStatus *OperationsInsightsStatusType + + // READ-ONLY; The list of Azure resource IDs of standby databases located in Autonomous Data Guard remote regions that are + // associated with the source database. Note that for Autonomous Database Serverless instances, standby databases located + // in the same region as the source primary database do not have Azure IDs. + PeerDbIDs []*string + + // READ-ONLY; The private endpoint for the resource. + PrivateEndpoint *string + + // READ-ONLY; An array of CPU values that an Autonomous Database can be scaled to. + ProvisionableCpus []*int32 + + // READ-ONLY; Azure resource provisioning state. + ProvisioningState *AzureResourceProvisioningState + + // READ-ONLY; Indicates remote disaster recovery configuration + RemoteDisasterRecoveryConfiguration *DisasterRecoveryConfigurationDetails + + // READ-ONLY; The SQL Web Developer URL for the Oracle Autonomous Database. + SQLWebDeveloperURL *string + + // READ-ONLY; The URL of the Service Console for the Autonomous Database. + ServiceConsoleURL *string + + // READ-ONLY; The list of regions that support the creation of an Autonomous Database clone or an Autonomous Data Guard standby + // database. + SupportedRegionsToCloneTo []*string + + // READ-ONLY; The date and time that the database was created. + TimeCreated *time.Time + + // READ-ONLY; The date and time the Autonomous Data Guard role was switched for the Autonomous Database. + TimeDataGuardRoleChanged *string + + // READ-ONLY; The date and time the Always Free database will be automatically deleted because of inactivity. + TimeDeletionOfFreeAutonomousDatabase *string + + // READ-ONLY; The date and time the Disaster Recovery role was switched for the standby Autonomous Database. + TimeDisasterRecoveryRoleChanged *time.Time + + // READ-ONLY; The date and time that Autonomous Data Guard was enabled for an Autonomous Database where the standby was provisioned + // in the same region as the primary database. + TimeLocalDataGuardEnabled *string + + // READ-ONLY; The date and time when maintenance will begin. + TimeMaintenanceBegin *time.Time + + // READ-ONLY; The date and time when maintenance will end. + TimeMaintenanceEnd *time.Time + + // READ-ONLY; The timestamp of the last failover operation. + TimeOfLastFailover *string + + // READ-ONLY; The date and time when last refresh happened. + TimeOfLastRefresh *string + + // READ-ONLY; The refresh point timestamp (UTC). + TimeOfLastRefreshPoint *string + + // READ-ONLY; The timestamp of the last switchover operation for the Autonomous Database. + TimeOfLastSwitchover *string + + // READ-ONLY; The date and time the Always Free database will be stopped because of inactivity. + TimeReclamationOfFreeAutonomousDatabase *string + + // READ-ONLY; The storage space consumed by Autonomous Database in GBs. + UsedDataStorageSizeInGbs *int32 + + // READ-ONLY; The amount of storage that has been used, in terabytes. + UsedDataStorageSizeInTbs *int32 +} + +// GetAutonomousDatabaseBaseProperties implements the AutonomousDatabaseBasePropertiesClassification interface for type AutonomousDatabaseBaseProperties. +func (a *AutonomousDatabaseBaseProperties) GetAutonomousDatabaseBaseProperties() *AutonomousDatabaseBaseProperties { + return a +} + +// AutonomousDatabaseCharacterSets resource definition +type AutonomousDatabaseCharacterSet struct { + // The resource-specific properties for this resource. + Properties *AutonomousDatabaseCharacterSetProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// AutonomousDatabaseCharacterSetListResult - The response of a AutonomousDatabaseCharacterSet list operation. +type AutonomousDatabaseCharacterSetListResult struct { + // REQUIRED; The AutonomousDatabaseCharacterSet items on this page + Value []*AutonomousDatabaseCharacterSet + + // The link to the next page of items + NextLink *string +} + +// AutonomousDatabaseCharacterSetProperties - AutonomousDatabaseCharacterSet resource model +type AutonomousDatabaseCharacterSetProperties struct { + // REQUIRED; The Oracle Autonomous Database supported character sets. + CharacterSet *string +} + +// AutonomousDatabaseCloneProperties - Autonomous Database clone resource model. +type AutonomousDatabaseCloneProperties struct { + // REQUIRED; The Autonomous Database clone type. + CloneType *CloneType + + // CONSTANT; Database type to be created. + // Field has constant value DataBaseTypeClone, any specified value is ignored. + DataBaseType *DataBaseType + + // REQUIRED; The Azure resource ID of the Autonomous Database that was cloned to create the current Autonomous Database. + SourceID *string + + // Admin password. + AdminPassword *string + + // Autonomous Database ID + AutonomousDatabaseID *string + + // The maintenance schedule type of the Autonomous Database Serverless. + AutonomousMaintenanceScheduleType *AutonomousMaintenanceScheduleType + + // Retention period, in days, for long-term backups + BackupRetentionPeriodInDays *int32 + + // The number of CPU cores to be made available to the database. + CPUCoreCount *int32 + + // The character set for the autonomous database. + CharacterSet *string + + // The compute amount (CPUs) available to the database. + ComputeCount *float32 + + // The compute model of the Autonomous Database. + ComputeModel *ComputeModel + + // Customer Contacts. + CustomerContacts []*CustomerContact + + // The size, in gigabytes, of the data volume that will be created and attached to the database. + DataStorageSizeInGbs *int32 + + // The quantity of data in the database, in terabytes. + DataStorageSizeInTbs *int32 + + // The Oracle Database Edition that applies to the Autonomous databases. + DatabaseEdition *DatabaseEditionType + + // A valid Oracle Database version for Autonomous Database. + DbVersion *string + + // The Autonomous Database workload type + DbWorkload *WorkloadType + + // The user-friendly name for the Autonomous Database. + DisplayName *string + + // Indicates if auto scaling is enabled for the Autonomous Database CPU core count. + IsAutoScalingEnabled *bool + + // Indicates if auto scaling is enabled for the Autonomous Database storage. + IsAutoScalingForStorageEnabled *bool + + // Indicates whether the Autonomous Database has local or called in-region Data Guard enabled. + IsLocalDataGuardEnabled *bool + + // Specifies if the Autonomous Database requires mTLS connections. + IsMtlsConnectionRequired *bool + + // Specifies if the Autonomous Database preview version is being provisioned. + IsPreviewVersionWithServiceTermsAccepted *bool + + // The Oracle license model that applies to the Oracle Autonomous Database. The default is LICENSE_INCLUDED. + LicenseModel *LicenseModel + + // Parameter that allows users to select an acceptable maximum data loss limit in seconds, up to which Automatic Failover + // will be triggered when necessary for a Local Autonomous Data Guard + LocalAdgAutoFailoverMaxDataLossLimit *int32 + + // Details for the long-term backup schedule. + LongTermBackupSchedule *LongTermBackUpScheduleDetails + + // The character set for the Autonomous Database. + NcharacterSet *string + + // Indicates the Autonomous Database mode. + OpenMode *OpenModeType + + // The Azure resource ID of the Disaster Recovery peer database, which is located in a different region from the current peer + // database. + PeerDbID *string + + // The Autonomous Database permission level. + PermissionLevel *PermissionLevelType + + // The private endpoint Ip address for the resource. + PrivateEndpointIP *string + + // The resource's private endpoint label. + PrivateEndpointLabel *string + + // The refresh mode of the clone. + RefreshableModel *RefreshableModelType + + // The Data Guard role of the Autonomous Container Database or Autonomous Database, if Autonomous Data Guard is enabled. + Role *RoleType + + // The list of scheduled operations. + ScheduledOperationsList []*ScheduledOperationsType + + // The source of the database. + Source *SourceType + + // Client subnet + SubnetID *string + + // The time and date as an RFC3339 formatted string, e.g., 2022-01-01T12:00:00.000Z, to set the limit for a refreshable clone + // to be reconnected to its source database. + TimeUntilReconnectCloneEnabled *string + + // VNET for network connectivity + VnetID *string + + // The client IP access control list (ACL). This is an array of CIDR notations and/or IP addresses. Values should be separate + // strings, separated by commas. Example: ['1.1.1.1','1.1.1.0/24','1.1.2.25'] + WhitelistedIPs []*string + + // READ-ONLY; The current amount of storage in use for user and system data, in terabytes (TB). + ActualUsedDataStorageSizeInTbs *float64 + + // READ-ONLY; The amount of storage currently allocated for the database tables and billed for, rounded up. + AllocatedStorageSizeInTbs *float64 + + // READ-ONLY; Information about Oracle APEX Application Development. + ApexDetails *ApexDetailsType + + // READ-ONLY; List of Oracle Database versions available for a database upgrade. If there are no version upgrades available, + // this list is empty. + AvailableUpgradeVersions []*string + + // READ-ONLY; The connection string used to connect to the Autonomous Database. + ConnectionStrings *ConnectionStringType + + // READ-ONLY; The URLs for accessing Oracle Application Express (APEX) and SQL Developer Web with a browser from a Compute + // instance within your VCN or that has a direct connection to your VCN. + ConnectionUrls *ConnectionURLType + + // READ-ONLY; Status of the Data Safe registration for this Autonomous Database. + DataSafeStatus *DataSafeStatusType + + // READ-ONLY; Indicates the number of seconds of data loss for a Data Guard failover. + FailedDataRecoveryInSeconds *int32 + + // READ-ONLY; The area assigned to In-Memory tables in Autonomous Database. + InMemoryAreaInGbs *int32 + + // READ-ONLY; Indicates if the Autonomous Database version is a preview version. + IsPreview *bool + + // READ-ONLY; Indicates if the refreshable clone can be reconnected to its source database. + IsReconnectCloneEnabled *bool + + // READ-ONLY; Indicates if the Autonomous Database is a refreshable clone. + IsRefreshableClone *bool + + // READ-ONLY; Indicates whether the Autonomous Database has Cross Region Data Guard enabled. + IsRemoteDataGuardEnabled *bool + + // READ-ONLY; Additional information about the current lifecycle state. + LifecycleDetails *string + + // READ-ONLY; Views lifecycleState + LifecycleState *AutonomousDatabaseLifecycleState + + // READ-ONLY; Indicates the local disaster recovery (DR) type of the Autonomous Database Serverless instance.Autonomous Data + // Guard (ADG) DR type provides business critical DR with a faster recovery time objective (RTO) during failover or switchover.Backup-based + // DR type provides lower cost DR with a slower RTO during failover or switchover. + LocalDisasterRecoveryType *DisasterRecoveryType + + // READ-ONLY; Local Autonomous Disaster Recovery standby database details. + LocalStandbyDb *AutonomousDatabaseStandbySummary + + // READ-ONLY; The amount of memory (in GBs) enabled per ECPU or OCPU. + MemoryPerOracleComputeUnitInGbs *int32 + + // READ-ONLY; The date and time when the next long-term backup would be created. + NextLongTermBackupTimeStamp *time.Time + + // READ-ONLY; HTTPS link to OCI resources exposed to Azure Customer via Azure Interface. + OciURL *string + + // READ-ONLY; Database ocid + Ocid *string + + // READ-ONLY; Status of Operations Insights for this Autonomous Database. + OperationsInsightsStatus *OperationsInsightsStatusType + + // READ-ONLY; The list of Azure resource IDs of standby databases located in Autonomous Data Guard remote regions that are + // associated with the source database. Note that for Autonomous Database Serverless instances, standby databases located + // in the same region as the source primary database do not have Azure IDs. + PeerDbIDs []*string + + // READ-ONLY; The private endpoint for the resource. + PrivateEndpoint *string + + // READ-ONLY; An array of CPU values that an Autonomous Database can be scaled to. + ProvisionableCpus []*int32 + + // READ-ONLY; Azure resource provisioning state. + ProvisioningState *AzureResourceProvisioningState + + // READ-ONLY; The refresh status of the clone. + RefreshableStatus *RefreshableStatusType + + // READ-ONLY; Indicates remote disaster recovery configuration + RemoteDisasterRecoveryConfiguration *DisasterRecoveryConfigurationDetails + + // READ-ONLY; The SQL Web Developer URL for the Oracle Autonomous Database. + SQLWebDeveloperURL *string + + // READ-ONLY; The URL of the Service Console for the Autonomous Database. + ServiceConsoleURL *string + + // READ-ONLY; The list of regions that support the creation of an Autonomous Database clone or an Autonomous Data Guard standby + // database. + SupportedRegionsToCloneTo []*string + + // READ-ONLY; The date and time that the database was created. + TimeCreated *time.Time + + // READ-ONLY; The date and time the Autonomous Data Guard role was switched for the Autonomous Database. + TimeDataGuardRoleChanged *string + + // READ-ONLY; The date and time the Always Free database will be automatically deleted because of inactivity. + TimeDeletionOfFreeAutonomousDatabase *string + + // READ-ONLY; The date and time the Disaster Recovery role was switched for the standby Autonomous Database. + TimeDisasterRecoveryRoleChanged *time.Time + + // READ-ONLY; The date and time that Autonomous Data Guard was enabled for an Autonomous Database where the standby was provisioned + // in the same region as the primary database. + TimeLocalDataGuardEnabled *string + + // READ-ONLY; The date and time when maintenance will begin. + TimeMaintenanceBegin *time.Time + + // READ-ONLY; The date and time when maintenance will end. + TimeMaintenanceEnd *time.Time + + // READ-ONLY; The timestamp of the last failover operation. + TimeOfLastFailover *string + + // READ-ONLY; The date and time when last refresh happened. + TimeOfLastRefresh *string + + // READ-ONLY; The refresh point timestamp (UTC). + TimeOfLastRefreshPoint *string + + // READ-ONLY; The timestamp of the last switchover operation for the Autonomous Database. + TimeOfLastSwitchover *string + + // READ-ONLY; The date and time the Always Free database will be stopped because of inactivity. + TimeReclamationOfFreeAutonomousDatabase *string + + // READ-ONLY; The storage space consumed by Autonomous Database in GBs. + UsedDataStorageSizeInGbs *int32 + + // READ-ONLY; The amount of storage that has been used, in terabytes. + UsedDataStorageSizeInTbs *int32 +} + +// GetAutonomousDatabaseBaseProperties implements the AutonomousDatabaseBasePropertiesClassification interface for type AutonomousDatabaseCloneProperties. +func (a *AutonomousDatabaseCloneProperties) GetAutonomousDatabaseBaseProperties() *AutonomousDatabaseBaseProperties { + return &AutonomousDatabaseBaseProperties{ + ActualUsedDataStorageSizeInTbs: a.ActualUsedDataStorageSizeInTbs, + AdminPassword: a.AdminPassword, + AllocatedStorageSizeInTbs: a.AllocatedStorageSizeInTbs, + ApexDetails: a.ApexDetails, + AutonomousDatabaseID: a.AutonomousDatabaseID, + AutonomousMaintenanceScheduleType: a.AutonomousMaintenanceScheduleType, + AvailableUpgradeVersions: a.AvailableUpgradeVersions, + BackupRetentionPeriodInDays: a.BackupRetentionPeriodInDays, + CPUCoreCount: a.CPUCoreCount, + CharacterSet: a.CharacterSet, + ComputeCount: a.ComputeCount, + ComputeModel: a.ComputeModel, + ConnectionStrings: a.ConnectionStrings, + ConnectionUrls: a.ConnectionUrls, + CustomerContacts: a.CustomerContacts, + DataBaseType: a.DataBaseType, + DataSafeStatus: a.DataSafeStatus, + DataStorageSizeInGbs: a.DataStorageSizeInGbs, + DataStorageSizeInTbs: a.DataStorageSizeInTbs, + DatabaseEdition: a.DatabaseEdition, + DbVersion: a.DbVersion, + DbWorkload: a.DbWorkload, + DisplayName: a.DisplayName, + FailedDataRecoveryInSeconds: a.FailedDataRecoveryInSeconds, + InMemoryAreaInGbs: a.InMemoryAreaInGbs, + IsAutoScalingEnabled: a.IsAutoScalingEnabled, + IsAutoScalingForStorageEnabled: a.IsAutoScalingForStorageEnabled, + IsLocalDataGuardEnabled: a.IsLocalDataGuardEnabled, + IsMtlsConnectionRequired: a.IsMtlsConnectionRequired, + IsPreview: a.IsPreview, + IsPreviewVersionWithServiceTermsAccepted: a.IsPreviewVersionWithServiceTermsAccepted, + IsRemoteDataGuardEnabled: a.IsRemoteDataGuardEnabled, + LicenseModel: a.LicenseModel, + LifecycleDetails: a.LifecycleDetails, + LifecycleState: a.LifecycleState, + LocalAdgAutoFailoverMaxDataLossLimit: a.LocalAdgAutoFailoverMaxDataLossLimit, + LocalDisasterRecoveryType: a.LocalDisasterRecoveryType, + LocalStandbyDb: a.LocalStandbyDb, + LongTermBackupSchedule: a.LongTermBackupSchedule, + MemoryPerOracleComputeUnitInGbs: a.MemoryPerOracleComputeUnitInGbs, + NcharacterSet: a.NcharacterSet, + NextLongTermBackupTimeStamp: a.NextLongTermBackupTimeStamp, + OciURL: a.OciURL, + Ocid: a.Ocid, + OpenMode: a.OpenMode, + OperationsInsightsStatus: a.OperationsInsightsStatus, + PeerDbID: a.PeerDbID, + PeerDbIDs: a.PeerDbIDs, + PermissionLevel: a.PermissionLevel, + PrivateEndpoint: a.PrivateEndpoint, + PrivateEndpointIP: a.PrivateEndpointIP, + PrivateEndpointLabel: a.PrivateEndpointLabel, + ProvisionableCpus: a.ProvisionableCpus, + ProvisioningState: a.ProvisioningState, + RemoteDisasterRecoveryConfiguration: a.RemoteDisasterRecoveryConfiguration, + Role: a.Role, + SQLWebDeveloperURL: a.SQLWebDeveloperURL, + ScheduledOperationsList: a.ScheduledOperationsList, + ServiceConsoleURL: a.ServiceConsoleURL, + SubnetID: a.SubnetID, + SupportedRegionsToCloneTo: a.SupportedRegionsToCloneTo, + TimeCreated: a.TimeCreated, + TimeDataGuardRoleChanged: a.TimeDataGuardRoleChanged, + TimeDeletionOfFreeAutonomousDatabase: a.TimeDeletionOfFreeAutonomousDatabase, + TimeDisasterRecoveryRoleChanged: a.TimeDisasterRecoveryRoleChanged, + TimeLocalDataGuardEnabled: a.TimeLocalDataGuardEnabled, + TimeMaintenanceBegin: a.TimeMaintenanceBegin, + TimeMaintenanceEnd: a.TimeMaintenanceEnd, + TimeOfLastFailover: a.TimeOfLastFailover, + TimeOfLastRefresh: a.TimeOfLastRefresh, + TimeOfLastRefreshPoint: a.TimeOfLastRefreshPoint, + TimeOfLastSwitchover: a.TimeOfLastSwitchover, + TimeReclamationOfFreeAutonomousDatabase: a.TimeReclamationOfFreeAutonomousDatabase, + UsedDataStorageSizeInGbs: a.UsedDataStorageSizeInGbs, + UsedDataStorageSizeInTbs: a.UsedDataStorageSizeInTbs, + VnetID: a.VnetID, + WhitelistedIPs: a.WhitelistedIPs, + } +} + +// AutonomousDatabaseCrossRegionDisasterRecoveryProperties - Autonomous Database Cross Region Disaster Recovery resource model. +type AutonomousDatabaseCrossRegionDisasterRecoveryProperties struct { + // CONSTANT; Database type to be created. + // Field has constant value DataBaseTypeCrossRegionDisasterRecovery, any specified value is ignored. + DataBaseType *DataBaseType + + // REQUIRED; Indicates the cross-region disaster recovery (DR) type of the standby Autonomous Database Serverless instance. + // Autonomous Data Guard (ADG) DR type provides business critical DR with a faster recovery time objective (RTO) during failover + // or switchover. Backup-based DR type provides lower cost DR with a slower RTO during failover or switchover. + RemoteDisasterRecoveryType *DisasterRecoveryType + + // CONSTANT; The source of the database. + // Field has constant value SourceTypeCrossRegionDisasterRecovery, any specified value is ignored. + Source *SourceType + + // REQUIRED; The Azure ID of the source Autonomous Database that will be used to create a new peer database for the DR association. + SourceID *string + + // Admin password. + AdminPassword *string + + // Autonomous Database ID + AutonomousDatabaseID *string + + // The maintenance schedule type of the Autonomous Database Serverless. + AutonomousMaintenanceScheduleType *AutonomousMaintenanceScheduleType + + // Retention period, in days, for long-term backups + BackupRetentionPeriodInDays *int32 + + // The number of CPU cores to be made available to the database. + CPUCoreCount *int32 + + // The character set for the autonomous database. + CharacterSet *string + + // The compute amount (CPUs) available to the database. + ComputeCount *float32 + + // The compute model of the Autonomous Database. + ComputeModel *ComputeModel + + // Customer Contacts. + CustomerContacts []*CustomerContact + + // The size, in gigabytes, of the data volume that will be created and attached to the database. + DataStorageSizeInGbs *int32 + + // The quantity of data in the database, in terabytes. + DataStorageSizeInTbs *int32 + + // The Oracle Database Edition that applies to the Autonomous databases. + DatabaseEdition *DatabaseEditionType + + // A valid Oracle Database version for Autonomous Database. + DbVersion *string + + // The Autonomous Database workload type + DbWorkload *WorkloadType + + // The user-friendly name for the Autonomous Database. + DisplayName *string + + // Indicates if auto scaling is enabled for the Autonomous Database CPU core count. + IsAutoScalingEnabled *bool + + // Indicates if auto scaling is enabled for the Autonomous Database storage. + IsAutoScalingForStorageEnabled *bool + + // Indicates whether the Autonomous Database has local or called in-region Data Guard enabled. + IsLocalDataGuardEnabled *bool + + // Specifies if the Autonomous Database requires mTLS connections. + IsMtlsConnectionRequired *bool + + // Specifies if the Autonomous Database preview version is being provisioned. + IsPreviewVersionWithServiceTermsAccepted *bool + + // If true, 7 days worth of backups are replicated across regions for Cross-Region ADB or Backup-Based DR between Primary + // and Standby. If false, the backups taken on the Primary are not replicated to the Standby database. + IsReplicateAutomaticBackups *bool + + // The Oracle license model that applies to the Oracle Autonomous Database. The default is LICENSE_INCLUDED. + LicenseModel *LicenseModel + + // Parameter that allows users to select an acceptable maximum data loss limit in seconds, up to which Automatic Failover + // will be triggered when necessary for a Local Autonomous Data Guard + LocalAdgAutoFailoverMaxDataLossLimit *int32 + + // Details for the long-term backup schedule. + LongTermBackupSchedule *LongTermBackUpScheduleDetails + + // The character set for the Autonomous Database. + NcharacterSet *string + + // Indicates the Autonomous Database mode. + OpenMode *OpenModeType + + // The Azure resource ID of the Disaster Recovery peer database, which is located in a different region from the current peer + // database. + PeerDbID *string + + // The Autonomous Database permission level. + PermissionLevel *PermissionLevelType + + // The private endpoint Ip address for the resource. + PrivateEndpointIP *string + + // The resource's private endpoint label. + PrivateEndpointLabel *string + + // The Data Guard role of the Autonomous Container Database or Autonomous Database, if Autonomous Data Guard is enabled. + Role *RoleType + + // The list of scheduled operations. + ScheduledOperationsList []*ScheduledOperationsType + + // The name of the region where source Autonomous Database exists. + SourceLocation *string + + // The source database ocid + SourceOcid *string + + // Client subnet + SubnetID *string + + // VNET for network connectivity + VnetID *string + + // The client IP access control list (ACL). This is an array of CIDR notations and/or IP addresses. Values should be separate + // strings, separated by commas. Example: ['1.1.1.1','1.1.1.0/24','1.1.2.25'] + WhitelistedIPs []*string + + // READ-ONLY; The current amount of storage in use for user and system data, in terabytes (TB). + ActualUsedDataStorageSizeInTbs *float64 + + // READ-ONLY; The amount of storage currently allocated for the database tables and billed for, rounded up. + AllocatedStorageSizeInTbs *float64 + + // READ-ONLY; Information about Oracle APEX Application Development. + ApexDetails *ApexDetailsType + + // READ-ONLY; List of Oracle Database versions available for a database upgrade. If there are no version upgrades available, + // this list is empty. + AvailableUpgradeVersions []*string + + // READ-ONLY; The connection string used to connect to the Autonomous Database. + ConnectionStrings *ConnectionStringType + + // READ-ONLY; The URLs for accessing Oracle Application Express (APEX) and SQL Developer Web with a browser from a Compute + // instance within your VCN or that has a direct connection to your VCN. + ConnectionUrls *ConnectionURLType + + // READ-ONLY; Status of the Data Safe registration for this Autonomous Database. + DataSafeStatus *DataSafeStatusType + + // READ-ONLY; Indicates the number of seconds of data loss for a Data Guard failover. + FailedDataRecoveryInSeconds *int32 + + // READ-ONLY; The area assigned to In-Memory tables in Autonomous Database. + InMemoryAreaInGbs *int32 + + // READ-ONLY; Indicates if the Autonomous Database version is a preview version. + IsPreview *bool + + // READ-ONLY; Indicates whether the Autonomous Database has Cross Region Data Guard enabled. + IsRemoteDataGuardEnabled *bool + + // READ-ONLY; Additional information about the current lifecycle state. + LifecycleDetails *string + + // READ-ONLY; Views lifecycleState + LifecycleState *AutonomousDatabaseLifecycleState + + // READ-ONLY; Indicates the local disaster recovery (DR) type of the Autonomous Database Serverless instance.Autonomous Data + // Guard (ADG) DR type provides business critical DR with a faster recovery time objective (RTO) during failover or switchover.Backup-based + // DR type provides lower cost DR with a slower RTO during failover or switchover. + LocalDisasterRecoveryType *DisasterRecoveryType + + // READ-ONLY; Local Autonomous Disaster Recovery standby database details. + LocalStandbyDb *AutonomousDatabaseStandbySummary + + // READ-ONLY; The amount of memory (in GBs) enabled per ECPU or OCPU. + MemoryPerOracleComputeUnitInGbs *int32 + + // READ-ONLY; The date and time when the next long-term backup would be created. + NextLongTermBackupTimeStamp *time.Time + + // READ-ONLY; HTTPS link to OCI resources exposed to Azure Customer via Azure Interface. + OciURL *string + + // READ-ONLY; Database ocid + Ocid *string + + // READ-ONLY; Status of Operations Insights for this Autonomous Database. + OperationsInsightsStatus *OperationsInsightsStatusType + + // READ-ONLY; The list of Azure resource IDs of standby databases located in Autonomous Data Guard remote regions that are + // associated with the source database. Note that for Autonomous Database Serverless instances, standby databases located + // in the same region as the source primary database do not have Azure IDs. + PeerDbIDs []*string + + // READ-ONLY; The private endpoint for the resource. + PrivateEndpoint *string + + // READ-ONLY; An array of CPU values that an Autonomous Database can be scaled to. + ProvisionableCpus []*int32 + + // READ-ONLY; Azure resource provisioning state. + ProvisioningState *AzureResourceProvisioningState + + // READ-ONLY; Indicates remote disaster recovery configuration + RemoteDisasterRecoveryConfiguration *DisasterRecoveryConfigurationDetails + + // READ-ONLY; The SQL Web Developer URL for the Oracle Autonomous Database. + SQLWebDeveloperURL *string + + // READ-ONLY; The URL of the Service Console for the Autonomous Database. + ServiceConsoleURL *string + + // READ-ONLY; The list of regions that support the creation of an Autonomous Database clone or an Autonomous Data Guard standby + // database. + SupportedRegionsToCloneTo []*string + + // READ-ONLY; The date and time that the database was created. + TimeCreated *time.Time + + // READ-ONLY; The date and time the Autonomous Data Guard role was switched for the Autonomous Database. + TimeDataGuardRoleChanged *string + + // READ-ONLY; The date and time the Always Free database will be automatically deleted because of inactivity. + TimeDeletionOfFreeAutonomousDatabase *string + + // READ-ONLY; The date and time the Disaster Recovery role was switched for the standby Autonomous Database. + TimeDisasterRecoveryRoleChanged *time.Time + + // READ-ONLY; The date and time that Autonomous Data Guard was enabled for an Autonomous Database where the standby was provisioned + // in the same region as the primary database. + TimeLocalDataGuardEnabled *string + + // READ-ONLY; The date and time when maintenance will begin. + TimeMaintenanceBegin *time.Time + + // READ-ONLY; The date and time when maintenance will end. + TimeMaintenanceEnd *time.Time + + // READ-ONLY; The timestamp of the last failover operation. + TimeOfLastFailover *string + + // READ-ONLY; The date and time when last refresh happened. + TimeOfLastRefresh *string + + // READ-ONLY; The refresh point timestamp (UTC). + TimeOfLastRefreshPoint *string + + // READ-ONLY; The timestamp of the last switchover operation for the Autonomous Database. + TimeOfLastSwitchover *string + + // READ-ONLY; The date and time the Always Free database will be stopped because of inactivity. + TimeReclamationOfFreeAutonomousDatabase *string + + // READ-ONLY; The storage space consumed by Autonomous Database in GBs. + UsedDataStorageSizeInGbs *int32 + + // READ-ONLY; The amount of storage that has been used, in terabytes. + UsedDataStorageSizeInTbs *int32 +} + +// GetAutonomousDatabaseBaseProperties implements the AutonomousDatabaseBasePropertiesClassification interface for type AutonomousDatabaseCrossRegionDisasterRecoveryProperties. +func (a *AutonomousDatabaseCrossRegionDisasterRecoveryProperties) GetAutonomousDatabaseBaseProperties() *AutonomousDatabaseBaseProperties { + return &AutonomousDatabaseBaseProperties{ + ActualUsedDataStorageSizeInTbs: a.ActualUsedDataStorageSizeInTbs, + AdminPassword: a.AdminPassword, + AllocatedStorageSizeInTbs: a.AllocatedStorageSizeInTbs, + ApexDetails: a.ApexDetails, + AutonomousDatabaseID: a.AutonomousDatabaseID, + AutonomousMaintenanceScheduleType: a.AutonomousMaintenanceScheduleType, + AvailableUpgradeVersions: a.AvailableUpgradeVersions, + BackupRetentionPeriodInDays: a.BackupRetentionPeriodInDays, + CPUCoreCount: a.CPUCoreCount, + CharacterSet: a.CharacterSet, + ComputeCount: a.ComputeCount, + ComputeModel: a.ComputeModel, + ConnectionStrings: a.ConnectionStrings, + ConnectionUrls: a.ConnectionUrls, + CustomerContacts: a.CustomerContacts, + DataBaseType: a.DataBaseType, + DataSafeStatus: a.DataSafeStatus, + DataStorageSizeInGbs: a.DataStorageSizeInGbs, + DataStorageSizeInTbs: a.DataStorageSizeInTbs, + DatabaseEdition: a.DatabaseEdition, + DbVersion: a.DbVersion, + DbWorkload: a.DbWorkload, + DisplayName: a.DisplayName, + FailedDataRecoveryInSeconds: a.FailedDataRecoveryInSeconds, + InMemoryAreaInGbs: a.InMemoryAreaInGbs, + IsAutoScalingEnabled: a.IsAutoScalingEnabled, + IsAutoScalingForStorageEnabled: a.IsAutoScalingForStorageEnabled, + IsLocalDataGuardEnabled: a.IsLocalDataGuardEnabled, + IsMtlsConnectionRequired: a.IsMtlsConnectionRequired, + IsPreview: a.IsPreview, + IsPreviewVersionWithServiceTermsAccepted: a.IsPreviewVersionWithServiceTermsAccepted, + IsRemoteDataGuardEnabled: a.IsRemoteDataGuardEnabled, + LicenseModel: a.LicenseModel, + LifecycleDetails: a.LifecycleDetails, + LifecycleState: a.LifecycleState, + LocalAdgAutoFailoverMaxDataLossLimit: a.LocalAdgAutoFailoverMaxDataLossLimit, + LocalDisasterRecoveryType: a.LocalDisasterRecoveryType, + LocalStandbyDb: a.LocalStandbyDb, + LongTermBackupSchedule: a.LongTermBackupSchedule, + MemoryPerOracleComputeUnitInGbs: a.MemoryPerOracleComputeUnitInGbs, + NcharacterSet: a.NcharacterSet, + NextLongTermBackupTimeStamp: a.NextLongTermBackupTimeStamp, + OciURL: a.OciURL, + Ocid: a.Ocid, + OpenMode: a.OpenMode, + OperationsInsightsStatus: a.OperationsInsightsStatus, + PeerDbID: a.PeerDbID, + PeerDbIDs: a.PeerDbIDs, + PermissionLevel: a.PermissionLevel, + PrivateEndpoint: a.PrivateEndpoint, + PrivateEndpointIP: a.PrivateEndpointIP, + PrivateEndpointLabel: a.PrivateEndpointLabel, + ProvisionableCpus: a.ProvisionableCpus, + ProvisioningState: a.ProvisioningState, + RemoteDisasterRecoveryConfiguration: a.RemoteDisasterRecoveryConfiguration, + Role: a.Role, + SQLWebDeveloperURL: a.SQLWebDeveloperURL, + ScheduledOperationsList: a.ScheduledOperationsList, + ServiceConsoleURL: a.ServiceConsoleURL, + SubnetID: a.SubnetID, + SupportedRegionsToCloneTo: a.SupportedRegionsToCloneTo, + TimeCreated: a.TimeCreated, + TimeDataGuardRoleChanged: a.TimeDataGuardRoleChanged, + TimeDeletionOfFreeAutonomousDatabase: a.TimeDeletionOfFreeAutonomousDatabase, + TimeDisasterRecoveryRoleChanged: a.TimeDisasterRecoveryRoleChanged, + TimeLocalDataGuardEnabled: a.TimeLocalDataGuardEnabled, + TimeMaintenanceBegin: a.TimeMaintenanceBegin, + TimeMaintenanceEnd: a.TimeMaintenanceEnd, + TimeOfLastFailover: a.TimeOfLastFailover, + TimeOfLastRefresh: a.TimeOfLastRefresh, + TimeOfLastRefreshPoint: a.TimeOfLastRefreshPoint, + TimeOfLastSwitchover: a.TimeOfLastSwitchover, + TimeReclamationOfFreeAutonomousDatabase: a.TimeReclamationOfFreeAutonomousDatabase, + UsedDataStorageSizeInGbs: a.UsedDataStorageSizeInGbs, + UsedDataStorageSizeInTbs: a.UsedDataStorageSizeInTbs, + VnetID: a.VnetID, + WhitelistedIPs: a.WhitelistedIPs, + } +} + +// AutonomousDatabaseFromBackupTimestampProperties - Autonomous Database From Backup Timestamp resource model. +type AutonomousDatabaseFromBackupTimestampProperties struct { + // REQUIRED; The Autonomous Database clone type. + CloneType *CloneType + + // CONSTANT; Database type to be created. + // Field has constant value DataBaseTypeCloneFromBackupTimestamp, any specified value is ignored. + DataBaseType *DataBaseType + + // CONSTANT; The source of the database. + // Field has constant value SourceTypeBackupFromTimestamp, any specified value is ignored. + Source *SourceType + + // REQUIRED; The ID of the source Autonomous Database that you will clone to create a new Autonomous Database. + SourceID *string + + // Admin password. + AdminPassword *string + + // Autonomous Database ID + AutonomousDatabaseID *string + + // The maintenance schedule type of the Autonomous Database Serverless. + AutonomousMaintenanceScheduleType *AutonomousMaintenanceScheduleType + + // Retention period, in days, for long-term backups + BackupRetentionPeriodInDays *int32 + + // The number of CPU cores to be made available to the database. + CPUCoreCount *int32 + + // The character set for the autonomous database. + CharacterSet *string + + // The compute amount (CPUs) available to the database. + ComputeCount *float32 + + // The compute model of the Autonomous Database. + ComputeModel *ComputeModel + + // Customer Contacts. + CustomerContacts []*CustomerContact + + // The size, in gigabytes, of the data volume that will be created and attached to the database. + DataStorageSizeInGbs *int32 + + // The quantity of data in the database, in terabytes. + DataStorageSizeInTbs *int32 + + // The Oracle Database Edition that applies to the Autonomous databases. + DatabaseEdition *DatabaseEditionType + + // A valid Oracle Database version for Autonomous Database. + DbVersion *string + + // The Autonomous Database workload type + DbWorkload *WorkloadType + + // The user-friendly name for the Autonomous Database. + DisplayName *string + + // Indicates if auto scaling is enabled for the Autonomous Database CPU core count. + IsAutoScalingEnabled *bool + + // Indicates if auto scaling is enabled for the Autonomous Database storage. + IsAutoScalingForStorageEnabled *bool + + // Indicates whether the Autonomous Database has local or called in-region Data Guard enabled. + IsLocalDataGuardEnabled *bool + + // Specifies if the Autonomous Database requires mTLS connections. + IsMtlsConnectionRequired *bool + + // Specifies if the Autonomous Database preview version is being provisioned. + IsPreviewVersionWithServiceTermsAccepted *bool + + // The Oracle license model that applies to the Oracle Autonomous Database. The default is LICENSE_INCLUDED. + LicenseModel *LicenseModel + + // Parameter that allows users to select an acceptable maximum data loss limit in seconds, up to which Automatic Failover + // will be triggered when necessary for a Local Autonomous Data Guard + LocalAdgAutoFailoverMaxDataLossLimit *int32 + + // Details for the long-term backup schedule. + LongTermBackupSchedule *LongTermBackUpScheduleDetails + + // The character set for the Autonomous Database. + NcharacterSet *string + + // Indicates the Autonomous Database mode. + OpenMode *OpenModeType + + // The Azure resource ID of the Disaster Recovery peer database, which is located in a different region from the current peer + // database. + PeerDbID *string + + // The Autonomous Database permission level. + PermissionLevel *PermissionLevelType + + // The private endpoint Ip address for the resource. + PrivateEndpointIP *string + + // The resource's private endpoint label. + PrivateEndpointLabel *string + + // The Data Guard role of the Autonomous Container Database or Autonomous Database, if Autonomous Data Guard is enabled. + Role *RoleType + + // The list of scheduled operations. + ScheduledOperationsList []*ScheduledOperationsType + + // Client subnet + SubnetID *string + + // The timestamp specified for the point-in-time clone of the source Autonomous Database. The timestamp must be in the past. + Timestamp *time.Time + + // Clone from latest available backup timestamp. + UseLatestAvailableBackupTimeStamp *bool + + // VNET for network connectivity + VnetID *string + + // The client IP access control list (ACL). This is an array of CIDR notations and/or IP addresses. Values should be separate + // strings, separated by commas. Example: ['1.1.1.1','1.1.1.0/24','1.1.2.25'] + WhitelistedIPs []*string + + // READ-ONLY; The current amount of storage in use for user and system data, in terabytes (TB). + ActualUsedDataStorageSizeInTbs *float64 + + // READ-ONLY; The amount of storage currently allocated for the database tables and billed for, rounded up. + AllocatedStorageSizeInTbs *float64 + + // READ-ONLY; Information about Oracle APEX Application Development. + ApexDetails *ApexDetailsType + + // READ-ONLY; List of Oracle Database versions available for a database upgrade. If there are no version upgrades available, + // this list is empty. + AvailableUpgradeVersions []*string + + // READ-ONLY; The connection string used to connect to the Autonomous Database. + ConnectionStrings *ConnectionStringType + + // READ-ONLY; The URLs for accessing Oracle Application Express (APEX) and SQL Developer Web with a browser from a Compute + // instance within your VCN or that has a direct connection to your VCN. + ConnectionUrls *ConnectionURLType + + // READ-ONLY; Status of the Data Safe registration for this Autonomous Database. + DataSafeStatus *DataSafeStatusType + + // READ-ONLY; Indicates the number of seconds of data loss for a Data Guard failover. + FailedDataRecoveryInSeconds *int32 + + // READ-ONLY; The area assigned to In-Memory tables in Autonomous Database. + InMemoryAreaInGbs *int32 + + // READ-ONLY; Indicates if the Autonomous Database version is a preview version. + IsPreview *bool + + // READ-ONLY; Indicates whether the Autonomous Database has Cross Region Data Guard enabled. + IsRemoteDataGuardEnabled *bool + + // READ-ONLY; Additional information about the current lifecycle state. + LifecycleDetails *string + + // READ-ONLY; Views lifecycleState + LifecycleState *AutonomousDatabaseLifecycleState + + // READ-ONLY; Indicates the local disaster recovery (DR) type of the Autonomous Database Serverless instance.Autonomous Data + // Guard (ADG) DR type provides business critical DR with a faster recovery time objective (RTO) during failover or switchover.Backup-based + // DR type provides lower cost DR with a slower RTO during failover or switchover. + LocalDisasterRecoveryType *DisasterRecoveryType + + // READ-ONLY; Local Autonomous Disaster Recovery standby database details. + LocalStandbyDb *AutonomousDatabaseStandbySummary + + // READ-ONLY; The amount of memory (in GBs) enabled per ECPU or OCPU. + MemoryPerOracleComputeUnitInGbs *int32 + + // READ-ONLY; The date and time when the next long-term backup would be created. + NextLongTermBackupTimeStamp *time.Time + + // READ-ONLY; HTTPS link to OCI resources exposed to Azure Customer via Azure Interface. + OciURL *string + + // READ-ONLY; Database ocid + Ocid *string + + // READ-ONLY; Status of Operations Insights for this Autonomous Database. + OperationsInsightsStatus *OperationsInsightsStatusType + + // READ-ONLY; The list of Azure resource IDs of standby databases located in Autonomous Data Guard remote regions that are + // associated with the source database. Note that for Autonomous Database Serverless instances, standby databases located + // in the same region as the source primary database do not have Azure IDs. + PeerDbIDs []*string + + // READ-ONLY; The private endpoint for the resource. + PrivateEndpoint *string + + // READ-ONLY; An array of CPU values that an Autonomous Database can be scaled to. + ProvisionableCpus []*int32 + + // READ-ONLY; Azure resource provisioning state. + ProvisioningState *AzureResourceProvisioningState + + // READ-ONLY; Indicates remote disaster recovery configuration + RemoteDisasterRecoveryConfiguration *DisasterRecoveryConfigurationDetails + + // READ-ONLY; The SQL Web Developer URL for the Oracle Autonomous Database. + SQLWebDeveloperURL *string + + // READ-ONLY; The URL of the Service Console for the Autonomous Database. + ServiceConsoleURL *string + + // READ-ONLY; The list of regions that support the creation of an Autonomous Database clone or an Autonomous Data Guard standby + // database. + SupportedRegionsToCloneTo []*string + + // READ-ONLY; The date and time that the database was created. + TimeCreated *time.Time + + // READ-ONLY; The date and time the Autonomous Data Guard role was switched for the Autonomous Database. + TimeDataGuardRoleChanged *string + + // READ-ONLY; The date and time the Always Free database will be automatically deleted because of inactivity. + TimeDeletionOfFreeAutonomousDatabase *string + + // READ-ONLY; The date and time the Disaster Recovery role was switched for the standby Autonomous Database. + TimeDisasterRecoveryRoleChanged *time.Time + + // READ-ONLY; The date and time that Autonomous Data Guard was enabled for an Autonomous Database where the standby was provisioned + // in the same region as the primary database. + TimeLocalDataGuardEnabled *string + + // READ-ONLY; The date and time when maintenance will begin. + TimeMaintenanceBegin *time.Time + + // READ-ONLY; The date and time when maintenance will end. + TimeMaintenanceEnd *time.Time + + // READ-ONLY; The timestamp of the last failover operation. + TimeOfLastFailover *string + + // READ-ONLY; The date and time when last refresh happened. + TimeOfLastRefresh *string + + // READ-ONLY; The refresh point timestamp (UTC). + TimeOfLastRefreshPoint *string + + // READ-ONLY; The timestamp of the last switchover operation for the Autonomous Database. + TimeOfLastSwitchover *string + + // READ-ONLY; The date and time the Always Free database will be stopped because of inactivity. + TimeReclamationOfFreeAutonomousDatabase *string + + // READ-ONLY; The storage space consumed by Autonomous Database in GBs. + UsedDataStorageSizeInGbs *int32 + + // READ-ONLY; The amount of storage that has been used, in terabytes. + UsedDataStorageSizeInTbs *int32 +} + +// GetAutonomousDatabaseBaseProperties implements the AutonomousDatabaseBasePropertiesClassification interface for type AutonomousDatabaseFromBackupTimestampProperties. +func (a *AutonomousDatabaseFromBackupTimestampProperties) GetAutonomousDatabaseBaseProperties() *AutonomousDatabaseBaseProperties { + return &AutonomousDatabaseBaseProperties{ + ActualUsedDataStorageSizeInTbs: a.ActualUsedDataStorageSizeInTbs, + AdminPassword: a.AdminPassword, + AllocatedStorageSizeInTbs: a.AllocatedStorageSizeInTbs, + ApexDetails: a.ApexDetails, + AutonomousDatabaseID: a.AutonomousDatabaseID, + AutonomousMaintenanceScheduleType: a.AutonomousMaintenanceScheduleType, + AvailableUpgradeVersions: a.AvailableUpgradeVersions, + BackupRetentionPeriodInDays: a.BackupRetentionPeriodInDays, + CPUCoreCount: a.CPUCoreCount, + CharacterSet: a.CharacterSet, + ComputeCount: a.ComputeCount, + ComputeModel: a.ComputeModel, + ConnectionStrings: a.ConnectionStrings, + ConnectionUrls: a.ConnectionUrls, + CustomerContacts: a.CustomerContacts, + DataBaseType: a.DataBaseType, + DataSafeStatus: a.DataSafeStatus, + DataStorageSizeInGbs: a.DataStorageSizeInGbs, + DataStorageSizeInTbs: a.DataStorageSizeInTbs, + DatabaseEdition: a.DatabaseEdition, + DbVersion: a.DbVersion, + DbWorkload: a.DbWorkload, + DisplayName: a.DisplayName, + FailedDataRecoveryInSeconds: a.FailedDataRecoveryInSeconds, + InMemoryAreaInGbs: a.InMemoryAreaInGbs, + IsAutoScalingEnabled: a.IsAutoScalingEnabled, + IsAutoScalingForStorageEnabled: a.IsAutoScalingForStorageEnabled, + IsLocalDataGuardEnabled: a.IsLocalDataGuardEnabled, + IsMtlsConnectionRequired: a.IsMtlsConnectionRequired, + IsPreview: a.IsPreview, + IsPreviewVersionWithServiceTermsAccepted: a.IsPreviewVersionWithServiceTermsAccepted, + IsRemoteDataGuardEnabled: a.IsRemoteDataGuardEnabled, + LicenseModel: a.LicenseModel, + LifecycleDetails: a.LifecycleDetails, + LifecycleState: a.LifecycleState, + LocalAdgAutoFailoverMaxDataLossLimit: a.LocalAdgAutoFailoverMaxDataLossLimit, + LocalDisasterRecoveryType: a.LocalDisasterRecoveryType, + LocalStandbyDb: a.LocalStandbyDb, + LongTermBackupSchedule: a.LongTermBackupSchedule, + MemoryPerOracleComputeUnitInGbs: a.MemoryPerOracleComputeUnitInGbs, + NcharacterSet: a.NcharacterSet, + NextLongTermBackupTimeStamp: a.NextLongTermBackupTimeStamp, + OciURL: a.OciURL, + Ocid: a.Ocid, + OpenMode: a.OpenMode, + OperationsInsightsStatus: a.OperationsInsightsStatus, + PeerDbID: a.PeerDbID, + PeerDbIDs: a.PeerDbIDs, + PermissionLevel: a.PermissionLevel, + PrivateEndpoint: a.PrivateEndpoint, + PrivateEndpointIP: a.PrivateEndpointIP, + PrivateEndpointLabel: a.PrivateEndpointLabel, + ProvisionableCpus: a.ProvisionableCpus, + ProvisioningState: a.ProvisioningState, + RemoteDisasterRecoveryConfiguration: a.RemoteDisasterRecoveryConfiguration, + Role: a.Role, + SQLWebDeveloperURL: a.SQLWebDeveloperURL, + ScheduledOperationsList: a.ScheduledOperationsList, + ServiceConsoleURL: a.ServiceConsoleURL, + SubnetID: a.SubnetID, + SupportedRegionsToCloneTo: a.SupportedRegionsToCloneTo, + TimeCreated: a.TimeCreated, + TimeDataGuardRoleChanged: a.TimeDataGuardRoleChanged, + TimeDeletionOfFreeAutonomousDatabase: a.TimeDeletionOfFreeAutonomousDatabase, + TimeDisasterRecoveryRoleChanged: a.TimeDisasterRecoveryRoleChanged, + TimeLocalDataGuardEnabled: a.TimeLocalDataGuardEnabled, + TimeMaintenanceBegin: a.TimeMaintenanceBegin, + TimeMaintenanceEnd: a.TimeMaintenanceEnd, + TimeOfLastFailover: a.TimeOfLastFailover, + TimeOfLastRefresh: a.TimeOfLastRefresh, + TimeOfLastRefreshPoint: a.TimeOfLastRefreshPoint, + TimeOfLastSwitchover: a.TimeOfLastSwitchover, + TimeReclamationOfFreeAutonomousDatabase: a.TimeReclamationOfFreeAutonomousDatabase, + UsedDataStorageSizeInGbs: a.UsedDataStorageSizeInGbs, + UsedDataStorageSizeInTbs: a.UsedDataStorageSizeInTbs, + VnetID: a.VnetID, + WhitelistedIPs: a.WhitelistedIPs, + } +} + +// AutonomousDatabaseLifecycleAction - Autonomous Database Action Object +type AutonomousDatabaseLifecycleAction struct { + // REQUIRED; Autonomous Database lifecycle action + Action *AutonomousDatabaseLifecycleActionEnum +} + +// AutonomousDatabaseListResult - The response of a AutonomousDatabase list operation. +type AutonomousDatabaseListResult struct { + // REQUIRED; The AutonomousDatabase items on this page + Value []*AutonomousDatabase + + // The link to the next page of items + NextLink *string +} + +// AutonomousDatabaseNationalCharacterSets resource definition +type AutonomousDatabaseNationalCharacterSet struct { + // The resource-specific properties for this resource. + Properties *AutonomousDatabaseNationalCharacterSetProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// AutonomousDatabaseNationalCharacterSetListResult - The response of a AutonomousDatabaseNationalCharacterSet list operation. +type AutonomousDatabaseNationalCharacterSetListResult struct { + // REQUIRED; The AutonomousDatabaseNationalCharacterSet items on this page + Value []*AutonomousDatabaseNationalCharacterSet + + // The link to the next page of items + NextLink *string +} + +// AutonomousDatabaseNationalCharacterSetProperties - AutonomousDatabaseNationalCharacterSet resource model +type AutonomousDatabaseNationalCharacterSetProperties struct { + // REQUIRED; The Oracle Autonomous Database supported national character sets. + CharacterSet *string +} + +// AutonomousDatabaseProperties - Autonomous Database resource model. +type AutonomousDatabaseProperties struct { + // CONSTANT; Database type to be created. + // Field has constant value DataBaseTypeRegular, any specified value is ignored. + DataBaseType *DataBaseType + + // Admin password. + AdminPassword *string + + // Autonomous Database ID + AutonomousDatabaseID *string + + // The maintenance schedule type of the Autonomous Database Serverless. + AutonomousMaintenanceScheduleType *AutonomousMaintenanceScheduleType + + // Retention period, in days, for long-term backups + BackupRetentionPeriodInDays *int32 + + // The number of CPU cores to be made available to the database. + CPUCoreCount *int32 + + // The character set for the autonomous database. + CharacterSet *string + + // The compute amount (CPUs) available to the database. + ComputeCount *float32 + + // The compute model of the Autonomous Database. + ComputeModel *ComputeModel + + // Customer Contacts. + CustomerContacts []*CustomerContact + + // The size, in gigabytes, of the data volume that will be created and attached to the database. + DataStorageSizeInGbs *int32 + + // The quantity of data in the database, in terabytes. + DataStorageSizeInTbs *int32 + + // The Oracle Database Edition that applies to the Autonomous databases. + DatabaseEdition *DatabaseEditionType + + // A valid Oracle Database version for Autonomous Database. + DbVersion *string + + // The Autonomous Database workload type + DbWorkload *WorkloadType + + // The user-friendly name for the Autonomous Database. + DisplayName *string + + // Indicates if auto scaling is enabled for the Autonomous Database CPU core count. + IsAutoScalingEnabled *bool + + // Indicates if auto scaling is enabled for the Autonomous Database storage. + IsAutoScalingForStorageEnabled *bool + + // Indicates whether the Autonomous Database has local or called in-region Data Guard enabled. + IsLocalDataGuardEnabled *bool + + // Specifies if the Autonomous Database requires mTLS connections. + IsMtlsConnectionRequired *bool + + // Specifies if the Autonomous Database preview version is being provisioned. + IsPreviewVersionWithServiceTermsAccepted *bool + + // The Oracle license model that applies to the Oracle Autonomous Database. The default is LICENSE_INCLUDED. + LicenseModel *LicenseModel + + // Parameter that allows users to select an acceptable maximum data loss limit in seconds, up to which Automatic Failover + // will be triggered when necessary for a Local Autonomous Data Guard + LocalAdgAutoFailoverMaxDataLossLimit *int32 + + // Details for the long-term backup schedule. + LongTermBackupSchedule *LongTermBackUpScheduleDetails + + // The character set for the Autonomous Database. + NcharacterSet *string + + // Indicates the Autonomous Database mode. + OpenMode *OpenModeType + + // The Azure resource ID of the Disaster Recovery peer database, which is located in a different region from the current peer + // database. + PeerDbID *string + + // The Autonomous Database permission level. + PermissionLevel *PermissionLevelType + + // The private endpoint Ip address for the resource. + PrivateEndpointIP *string + + // The resource's private endpoint label. + PrivateEndpointLabel *string + + // The Data Guard role of the Autonomous Container Database or Autonomous Database, if Autonomous Data Guard is enabled. + Role *RoleType + + // The list of scheduled operations. + ScheduledOperationsList []*ScheduledOperationsType + + // Client subnet + SubnetID *string + + // VNET for network connectivity + VnetID *string + + // The client IP access control list (ACL). This is an array of CIDR notations and/or IP addresses. Values should be separate + // strings, separated by commas. Example: ['1.1.1.1','1.1.1.0/24','1.1.2.25'] + WhitelistedIPs []*string + + // READ-ONLY; The current amount of storage in use for user and system data, in terabytes (TB). + ActualUsedDataStorageSizeInTbs *float64 + + // READ-ONLY; The amount of storage currently allocated for the database tables and billed for, rounded up. + AllocatedStorageSizeInTbs *float64 + + // READ-ONLY; Information about Oracle APEX Application Development. + ApexDetails *ApexDetailsType + + // READ-ONLY; List of Oracle Database versions available for a database upgrade. If there are no version upgrades available, + // this list is empty. + AvailableUpgradeVersions []*string + + // READ-ONLY; The connection string used to connect to the Autonomous Database. + ConnectionStrings *ConnectionStringType + + // READ-ONLY; The URLs for accessing Oracle Application Express (APEX) and SQL Developer Web with a browser from a Compute + // instance within your VCN or that has a direct connection to your VCN. + ConnectionUrls *ConnectionURLType + + // READ-ONLY; Status of the Data Safe registration for this Autonomous Database. + DataSafeStatus *DataSafeStatusType + + // READ-ONLY; Indicates the number of seconds of data loss for a Data Guard failover. + FailedDataRecoveryInSeconds *int32 + + // READ-ONLY; The area assigned to In-Memory tables in Autonomous Database. + InMemoryAreaInGbs *int32 + + // READ-ONLY; Indicates if the Autonomous Database version is a preview version. + IsPreview *bool + + // READ-ONLY; Indicates whether the Autonomous Database has Cross Region Data Guard enabled. + IsRemoteDataGuardEnabled *bool + + // READ-ONLY; Additional information about the current lifecycle state. + LifecycleDetails *string + + // READ-ONLY; Views lifecycleState + LifecycleState *AutonomousDatabaseLifecycleState + + // READ-ONLY; Indicates the local disaster recovery (DR) type of the Autonomous Database Serverless instance.Autonomous Data + // Guard (ADG) DR type provides business critical DR with a faster recovery time objective (RTO) during failover or switchover.Backup-based + // DR type provides lower cost DR with a slower RTO during failover or switchover. + LocalDisasterRecoveryType *DisasterRecoveryType + + // READ-ONLY; Local Autonomous Disaster Recovery standby database details. + LocalStandbyDb *AutonomousDatabaseStandbySummary + + // READ-ONLY; The amount of memory (in GBs) enabled per ECPU or OCPU. + MemoryPerOracleComputeUnitInGbs *int32 + + // READ-ONLY; The date and time when the next long-term backup would be created. + NextLongTermBackupTimeStamp *time.Time + + // READ-ONLY; HTTPS link to OCI resources exposed to Azure Customer via Azure Interface. + OciURL *string + + // READ-ONLY; Database ocid + Ocid *string + + // READ-ONLY; Status of Operations Insights for this Autonomous Database. + OperationsInsightsStatus *OperationsInsightsStatusType + + // READ-ONLY; The list of Azure resource IDs of standby databases located in Autonomous Data Guard remote regions that are + // associated with the source database. Note that for Autonomous Database Serverless instances, standby databases located + // in the same region as the source primary database do not have Azure IDs. + PeerDbIDs []*string + + // READ-ONLY; The private endpoint for the resource. + PrivateEndpoint *string + + // READ-ONLY; An array of CPU values that an Autonomous Database can be scaled to. + ProvisionableCpus []*int32 + + // READ-ONLY; Azure resource provisioning state. + ProvisioningState *AzureResourceProvisioningState + + // READ-ONLY; Indicates remote disaster recovery configuration + RemoteDisasterRecoveryConfiguration *DisasterRecoveryConfigurationDetails + + // READ-ONLY; The SQL Web Developer URL for the Oracle Autonomous Database. + SQLWebDeveloperURL *string + + // READ-ONLY; The URL of the Service Console for the Autonomous Database. + ServiceConsoleURL *string + + // READ-ONLY; The list of regions that support the creation of an Autonomous Database clone or an Autonomous Data Guard standby + // database. + SupportedRegionsToCloneTo []*string + + // READ-ONLY; The date and time that the database was created. + TimeCreated *time.Time + + // READ-ONLY; The date and time the Autonomous Data Guard role was switched for the Autonomous Database. + TimeDataGuardRoleChanged *string + + // READ-ONLY; The date and time the Always Free database will be automatically deleted because of inactivity. + TimeDeletionOfFreeAutonomousDatabase *string + + // READ-ONLY; The date and time the Disaster Recovery role was switched for the standby Autonomous Database. + TimeDisasterRecoveryRoleChanged *time.Time + + // READ-ONLY; The date and time that Autonomous Data Guard was enabled for an Autonomous Database where the standby was provisioned + // in the same region as the primary database. + TimeLocalDataGuardEnabled *string + + // READ-ONLY; The date and time when maintenance will begin. + TimeMaintenanceBegin *time.Time + + // READ-ONLY; The date and time when maintenance will end. + TimeMaintenanceEnd *time.Time + + // READ-ONLY; The timestamp of the last failover operation. + TimeOfLastFailover *string + + // READ-ONLY; The date and time when last refresh happened. + TimeOfLastRefresh *string + + // READ-ONLY; The refresh point timestamp (UTC). + TimeOfLastRefreshPoint *string + + // READ-ONLY; The timestamp of the last switchover operation for the Autonomous Database. + TimeOfLastSwitchover *string + + // READ-ONLY; The date and time the Always Free database will be stopped because of inactivity. + TimeReclamationOfFreeAutonomousDatabase *string + + // READ-ONLY; The storage space consumed by Autonomous Database in GBs. + UsedDataStorageSizeInGbs *int32 + + // READ-ONLY; The amount of storage that has been used, in terabytes. + UsedDataStorageSizeInTbs *int32 +} + +// GetAutonomousDatabaseBaseProperties implements the AutonomousDatabaseBasePropertiesClassification interface for type AutonomousDatabaseProperties. +func (a *AutonomousDatabaseProperties) GetAutonomousDatabaseBaseProperties() *AutonomousDatabaseBaseProperties { + return &AutonomousDatabaseBaseProperties{ + ActualUsedDataStorageSizeInTbs: a.ActualUsedDataStorageSizeInTbs, + AdminPassword: a.AdminPassword, + AllocatedStorageSizeInTbs: a.AllocatedStorageSizeInTbs, + ApexDetails: a.ApexDetails, + AutonomousDatabaseID: a.AutonomousDatabaseID, + AutonomousMaintenanceScheduleType: a.AutonomousMaintenanceScheduleType, + AvailableUpgradeVersions: a.AvailableUpgradeVersions, + BackupRetentionPeriodInDays: a.BackupRetentionPeriodInDays, + CPUCoreCount: a.CPUCoreCount, + CharacterSet: a.CharacterSet, + ComputeCount: a.ComputeCount, + ComputeModel: a.ComputeModel, + ConnectionStrings: a.ConnectionStrings, + ConnectionUrls: a.ConnectionUrls, + CustomerContacts: a.CustomerContacts, + DataBaseType: a.DataBaseType, + DataSafeStatus: a.DataSafeStatus, + DataStorageSizeInGbs: a.DataStorageSizeInGbs, + DataStorageSizeInTbs: a.DataStorageSizeInTbs, + DatabaseEdition: a.DatabaseEdition, + DbVersion: a.DbVersion, + DbWorkload: a.DbWorkload, + DisplayName: a.DisplayName, + FailedDataRecoveryInSeconds: a.FailedDataRecoveryInSeconds, + InMemoryAreaInGbs: a.InMemoryAreaInGbs, + IsAutoScalingEnabled: a.IsAutoScalingEnabled, + IsAutoScalingForStorageEnabled: a.IsAutoScalingForStorageEnabled, + IsLocalDataGuardEnabled: a.IsLocalDataGuardEnabled, + IsMtlsConnectionRequired: a.IsMtlsConnectionRequired, + IsPreview: a.IsPreview, + IsPreviewVersionWithServiceTermsAccepted: a.IsPreviewVersionWithServiceTermsAccepted, + IsRemoteDataGuardEnabled: a.IsRemoteDataGuardEnabled, + LicenseModel: a.LicenseModel, + LifecycleDetails: a.LifecycleDetails, + LifecycleState: a.LifecycleState, + LocalAdgAutoFailoverMaxDataLossLimit: a.LocalAdgAutoFailoverMaxDataLossLimit, + LocalDisasterRecoveryType: a.LocalDisasterRecoveryType, + LocalStandbyDb: a.LocalStandbyDb, + LongTermBackupSchedule: a.LongTermBackupSchedule, + MemoryPerOracleComputeUnitInGbs: a.MemoryPerOracleComputeUnitInGbs, + NcharacterSet: a.NcharacterSet, + NextLongTermBackupTimeStamp: a.NextLongTermBackupTimeStamp, + OciURL: a.OciURL, + Ocid: a.Ocid, + OpenMode: a.OpenMode, + OperationsInsightsStatus: a.OperationsInsightsStatus, + PeerDbID: a.PeerDbID, + PeerDbIDs: a.PeerDbIDs, + PermissionLevel: a.PermissionLevel, + PrivateEndpoint: a.PrivateEndpoint, + PrivateEndpointIP: a.PrivateEndpointIP, + PrivateEndpointLabel: a.PrivateEndpointLabel, + ProvisionableCpus: a.ProvisionableCpus, + ProvisioningState: a.ProvisioningState, + RemoteDisasterRecoveryConfiguration: a.RemoteDisasterRecoveryConfiguration, + Role: a.Role, + SQLWebDeveloperURL: a.SQLWebDeveloperURL, + ScheduledOperationsList: a.ScheduledOperationsList, + ServiceConsoleURL: a.ServiceConsoleURL, + SubnetID: a.SubnetID, + SupportedRegionsToCloneTo: a.SupportedRegionsToCloneTo, + TimeCreated: a.TimeCreated, + TimeDataGuardRoleChanged: a.TimeDataGuardRoleChanged, + TimeDeletionOfFreeAutonomousDatabase: a.TimeDeletionOfFreeAutonomousDatabase, + TimeDisasterRecoveryRoleChanged: a.TimeDisasterRecoveryRoleChanged, + TimeLocalDataGuardEnabled: a.TimeLocalDataGuardEnabled, + TimeMaintenanceBegin: a.TimeMaintenanceBegin, + TimeMaintenanceEnd: a.TimeMaintenanceEnd, + TimeOfLastFailover: a.TimeOfLastFailover, + TimeOfLastRefresh: a.TimeOfLastRefresh, + TimeOfLastRefreshPoint: a.TimeOfLastRefreshPoint, + TimeOfLastSwitchover: a.TimeOfLastSwitchover, + TimeReclamationOfFreeAutonomousDatabase: a.TimeReclamationOfFreeAutonomousDatabase, + UsedDataStorageSizeInGbs: a.UsedDataStorageSizeInGbs, + UsedDataStorageSizeInTbs: a.UsedDataStorageSizeInTbs, + VnetID: a.VnetID, + WhitelistedIPs: a.WhitelistedIPs, + } +} + +// AutonomousDatabaseStandbySummary - Autonomous Disaster Recovery standby database details. +type AutonomousDatabaseStandbySummary struct { + // The amount of time, in seconds, that the data of the standby database lags the data of the primary database. Can be used + // to determine the potential data loss in the event of a failover. + LagTimeInSeconds *int32 + + // Additional information about the current lifecycle state. + LifecycleDetails *string + + // The current state of the Autonomous Database. + LifecycleState *AutonomousDatabaseLifecycleState + + // The date and time the Autonomous Data Guard role was switched for the standby Autonomous Database. + TimeDataGuardRoleChanged *string + + // The date and time the Disaster Recovery role was switched for the standby Autonomous Database. + TimeDisasterRecoveryRoleChanged *string +} + +// AutonomousDatabaseUpdate - The type used for update operations of the AutonomousDatabase. +type AutonomousDatabaseUpdate struct { + // The resource-specific properties for this resource. + Properties *AutonomousDatabaseUpdateProperties + + // Resource tags. + Tags map[string]*string +} + +// AutonomousDatabaseUpdateProperties - The updatable properties of the AutonomousDatabase. +type AutonomousDatabaseUpdateProperties struct { + // Admin password. + AdminPassword *string + + // The maintenance schedule type of the Autonomous Database Serverless. + AutonomousMaintenanceScheduleType *AutonomousMaintenanceScheduleType + + // Retention period, in days, for long-term backups + BackupRetentionPeriodInDays *int32 + + // The number of CPU cores to be made available to the database. + CPUCoreCount *int32 + + // The compute amount (CPUs) available to the database. + ComputeCount *float32 + + // Customer Contacts. + CustomerContacts []*CustomerContact + + // The size, in gigabytes, of the data volume that will be created and attached to the database. + DataStorageSizeInGbs *int32 + + // The quantity of data in the database, in terabytes. + DataStorageSizeInTbs *int32 + + // The Oracle Database Edition that applies to the Autonomous databases. + DatabaseEdition *DatabaseEditionType + + // The user-friendly name for the Autonomous Database. + DisplayName *string + + // Indicates if auto scaling is enabled for the Autonomous Database CPU core count. + IsAutoScalingEnabled *bool + + // Indicates if auto scaling is enabled for the Autonomous Database storage. + IsAutoScalingForStorageEnabled *bool + + // Indicates whether the Autonomous Database has local or called in-region Data Guard enabled. + IsLocalDataGuardEnabled *bool + + // Specifies if the Autonomous Database requires mTLS connections. + IsMtlsConnectionRequired *bool + + // The Oracle license model that applies to the Oracle Autonomous Database. The default is LICENSE_INCLUDED. + LicenseModel *LicenseModel + + // Parameter that allows users to select an acceptable maximum data loss limit in seconds, up to which Automatic Failover + // will be triggered when necessary for a Local Autonomous Data Guard + LocalAdgAutoFailoverMaxDataLossLimit *int32 + + // Details for the long-term backup schedule. + LongTermBackupSchedule *LongTermBackUpScheduleDetails + + // Indicates the Autonomous Database mode. + OpenMode *OpenModeType + + // The Azure resource ID of the Disaster Recovery peer database, which is located in a different region from the current peer + // database. + PeerDbID *string + + // The Autonomous Database permission level. + PermissionLevel *PermissionLevelType + + // The Data Guard role of the Autonomous Container Database or Autonomous Database, if Autonomous Data Guard is enabled. + Role *RoleType + + // The list of scheduled operations. + ScheduledOperationsList []*ScheduledOperationsTypeUpdate + + // The client IP access control list (ACL). This is an array of CIDR notations and/or IP addresses. Values should be separate + // strings, separated by commas. Example: ['1.1.1.1','1.1.1.0/24','1.1.2.25'] + WhitelistedIPs []*string +} + +// AutonomousDatabaseWalletFile - Autonomous Database Wallet File resource model. +type AutonomousDatabaseWalletFile struct { + // REQUIRED; The base64 encoded wallet files + WalletFiles *string +} + +// AutonomousDbVersion resource definition +type AutonomousDbVersion struct { + // The resource-specific properties for this resource. + Properties *AutonomousDbVersionProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// AutonomousDbVersionListResult - The response of a AutonomousDbVersion list operation. +type AutonomousDbVersionListResult struct { + // REQUIRED; The AutonomousDbVersion items on this page + Value []*AutonomousDbVersion + + // The link to the next page of items + NextLink *string +} + +// AutonomousDbVersionProperties - AutonomousDbVersion resource model +type AutonomousDbVersionProperties struct { + // REQUIRED; Supported Autonomous Db versions. + Version *string + + // The Autonomous Database workload type + DbWorkload *WorkloadType + + // True if this version of the Oracle Database software's default is free. + IsDefaultForFree *bool + + // True if this version of the Oracle Database software's default is paid. + IsDefaultForPaid *bool + + // True if this version of the Oracle Database software can be used for Always-Free Autonomous Databases. + IsFreeTierEnabled *bool + + // True if this version of the Oracle Database software has payments enabled. + IsPaidEnabled *bool +} + +// AzureSubscriptions - Azure Subscriptions model +type AzureSubscriptions struct { + // REQUIRED; Azure Subscription Ids to be updated + AzureSubscriptionIDs []*string +} + +// CloudAccountDetails - Cloud Account Details model +type CloudAccountDetails struct { + // READ-ONLY; Cloud Account Home region + CloudAccountHomeRegion *string + + // READ-ONLY; Cloud Account name + CloudAccountName *string +} + +// CloudExadataInfrastructure resource definition +type CloudExadataInfrastructure struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // REQUIRED; CloudExadataInfrastructure zones + Zones []*string + + // The resource-specific properties for this resource. + Properties *CloudExadataInfrastructureProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// CloudExadataInfrastructureListResult - The response of a CloudExadataInfrastructure list operation. +type CloudExadataInfrastructureListResult struct { + // REQUIRED; The CloudExadataInfrastructure items on this page + Value []*CloudExadataInfrastructure + + // The link to the next page of items + NextLink *string +} + +// CloudExadataInfrastructureProperties - CloudExadataInfrastructure resource model +type CloudExadataInfrastructureProperties struct { + // REQUIRED; The name for the Exadata infrastructure. + DisplayName *string + + // REQUIRED; The model name of the cloud Exadata infrastructure resource. + Shape *string + + // The number of compute servers for the cloud Exadata infrastructure. + ComputeCount *int32 + + // The list of customer email addresses that receive information from Oracle about the specified OCI Database service resource. + // Oracle uses these email addresses to send notifications about planned and unplanned software maintenance updates, information + // about system hardware, and other information needed by administrators. Up to 10 email addresses can be added to the customer + // contacts for a cloud Exadata infrastructure instance. + CustomerContacts []*CustomerContact + + // The database server model type of the cloud Exadata infrastructure resource. + DatabaseServerType *string + + // maintenanceWindow property + MaintenanceWindow *MaintenanceWindow + + // The number of storage servers for the cloud Exadata infrastructure. + StorageCount *int32 + + // The storage server model type of the cloud Exadata infrastructure resource. + StorageServerType *string + + // READ-ONLY; The requested number of additional storage servers activated for the Exadata infrastructure. + ActivatedStorageCount *int32 + + // READ-ONLY; The requested number of additional storage servers for the Exadata infrastructure. + AdditionalStorageCount *int32 + + // READ-ONLY; The available storage can be allocated to the cloud Exadata infrastructure resource, in gigabytes (GB). + AvailableStorageSizeInGbs *int32 + + // READ-ONLY; The total number of CPU cores allocated. + CPUCount *int32 + + // READ-ONLY; The compute model of the Exadata Infrastructure + ComputeModel *ComputeModel + + // READ-ONLY; The quantity of data in the database, in terabytes. + DataStorageSizeInTbs *float64 + + // READ-ONLY; The local node storage to be allocated in GBs. + DbNodeStorageSizeInGbs *int32 + + // READ-ONLY; The software version of the database servers (dom0) in the Exadata infrastructure. + DbServerVersion *string + + // READ-ONLY; Defined file system configurations + DefinedFileSystemConfiguration []*DefinedFileSystemConfiguration + + // READ-ONLY; The estimated total time required in minutes for all patching operations (database server, storage server, and + // network switch patching). + EstimatedPatchingTime *EstimatedPatchingTime + + // READ-ONLY; The exascale config details for the cloud Exadata infrastructure + ExascaleConfig *ExascaleConfigDetails + + // READ-ONLY; The OCID of the last maintenance run. + LastMaintenanceRunID *string + + // READ-ONLY; Additional information about the current lifecycle state. + LifecycleDetails *string + + // READ-ONLY; CloudExadataInfrastructure lifecycle state + LifecycleState *CloudExadataInfrastructureLifecycleState + + // READ-ONLY; The total number of CPU cores available. + MaxCPUCount *int32 + + // READ-ONLY; The total available DATA disk group size. + MaxDataStorageInTbs *float64 + + // READ-ONLY; The total local node storage available in GBs. + MaxDbNodeStorageSizeInGbs *int32 + + // READ-ONLY; The total memory available in GBs. + MaxMemoryInGbs *int32 + + // READ-ONLY; The memory allocated in GBs. + MemorySizeInGbs *int32 + + // READ-ONLY; Monthly Db Server version + MonthlyDbServerVersion *string + + // READ-ONLY; Monthly Storage Server version + MonthlyStorageServerVersion *string + + // READ-ONLY; The OCID of the next maintenance run. + NextMaintenanceRunID *string + + // READ-ONLY; HTTPS link to OCI resources exposed to Azure Customer via Azure Interface. + OciURL *string + + // READ-ONLY; Exadata infra ocid + Ocid *string + + // READ-ONLY; CloudExadataInfrastructure provisioning state + ProvisioningState *AzureResourceProvisioningState + + // READ-ONLY; The software version of the storage servers (cells) in the Exadata infrastructure. + StorageServerVersion *string + + // READ-ONLY; The date and time the cloud Exadata infrastructure resource was created. + TimeCreated *string + + // READ-ONLY; The total storage allocated to the cloud Exadata infrastructure resource, in gigabytes (GB). + TotalStorageSizeInGbs *int32 +} + +// CloudExadataInfrastructureUpdate - The type used for update operations of the CloudExadataInfrastructure. +type CloudExadataInfrastructureUpdate struct { + // The resource-specific properties for this resource. + Properties *CloudExadataInfrastructureUpdateProperties + + // Resource tags. + Tags map[string]*string + + // CloudExadataInfrastructure zones + Zones []*string +} + +// CloudExadataInfrastructureUpdateProperties - The updatable properties of the CloudExadataInfrastructure. +type CloudExadataInfrastructureUpdateProperties struct { + // The number of compute servers for the cloud Exadata infrastructure. + ComputeCount *int32 + + // The list of customer email addresses that receive information from Oracle about the specified OCI Database service resource. + // Oracle uses these email addresses to send notifications about planned and unplanned software maintenance updates, information + // about system hardware, and other information needed by administrators. Up to 10 email addresses can be added to the customer + // contacts for a cloud Exadata infrastructure instance. + CustomerContacts []*CustomerContact + + // The name for the Exadata infrastructure. + DisplayName *string + + // maintenanceWindow property + MaintenanceWindow *MaintenanceWindow + + // The number of storage servers for the cloud Exadata infrastructure. + StorageCount *int32 +} + +// CloudVMCluster - CloudVmCluster resource definition +type CloudVMCluster struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *CloudVMClusterProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// CloudVMClusterListResult - The response of a CloudVmCluster list operation. +type CloudVMClusterListResult struct { + // REQUIRED; The CloudVmCluster items on this page + Value []*CloudVMCluster + + // The link to the next page of items + NextLink *string +} + +// CloudVMClusterProperties - CloudVmCluster resource model +type CloudVMClusterProperties struct { + // REQUIRED; The number of CPU cores enabled on the cloud VM cluster. + CPUCoreCount *int32 + + // REQUIRED; Cloud Exadata Infrastructure ID + CloudExadataInfrastructureID *string + + // REQUIRED; Display Name + DisplayName *string + + // REQUIRED; Oracle Grid Infrastructure (GI) software version + GiVersion *string + + // REQUIRED; The hostname for the cloud VM cluster. + Hostname *string + + // REQUIRED; The public key portion of one or more key pairs used for SSH access to the cloud VM cluster. + SSHPublicKeys []*string + + // REQUIRED; Client subnet + SubnetID *string + + // REQUIRED; VNET for network connectivity + VnetID *string + + // Client OCI backup subnet CIDR, default is 192.168.252.0/22 + BackupSubnetCidr *string + + // The cluster name for cloud VM cluster. The cluster name must begin with an alphabetic character, and may contain hyphens + // (-). Underscores (_) are not permitted. The cluster name can be no longer than 11 characters and is not case sensitive. + ClusterName *string + + // The list of compute servers to be added to the cloud VM cluster. + ComputeNodes []*string + + // Indicates user preferences for the various diagnostic collection options for the VM cluster/Cloud VM cluster/VMBM DBCS. + DataCollectionOptions *DataCollectionOptions + + // The percentage assigned to DATA storage (user data and database files). The remaining percentage is assigned to RECO storage + // (database redo logs, archive logs, and recovery manager backups). Accepted values are 35, 40, 60 and 80. The default is + // 80 percent assigned to DATA storage. See [Storage Configuration](/Content/Database/Concepts/exaoverview.htm#Exadata) in + // the Exadata documentation for details on the impact of the configuration settings on storage. + DataStoragePercentage *int32 + + // The data disk group size to be allocated in TBs. + DataStorageSizeInTbs *float64 + + // The local node storage to be allocated in GBs. + DbNodeStorageSizeInGbs *int32 + + // The list of DB servers. + DbServers []*string + + // The domain name for the cloud VM cluster. + Domain *string + + // Exadata Database Storage Vault ID + ExascaleDbStorageVaultID *string + + // Array of mount path and size. + FileSystemConfigurationDetails []*FileSystemConfigurationDetails + + // If true, database backup on local Exadata storage is configured for the cloud VM cluster. If false, database backup on + // local Exadata storage is not available in the cloud VM cluster. + IsLocalBackupEnabled *bool + + // If true, sparse disk group is configured for the cloud VM cluster. If false, sparse disk group is not created. + IsSparseDiskgroupEnabled *bool + + // The Oracle license model that applies to the cloud VM cluster. The default is LICENSE_INCLUDED. + LicenseModel *LicenseModel + + // The memory to be allocated in GBs. + MemorySizeInGbs *int32 + + // CIDR blocks for additional NSG ingress rules. The VNET CIDRs used to provision the VM Cluster will be added by default. + NsgCidrs []*NsgCidr + + // The number of OCPU cores to enable on the cloud VM cluster. Only 1 decimal place is allowed for the fractional part. + OcpuCount *float32 + + // The TCP Single Client Access Name (SCAN) port. The default port is 1521. + ScanListenerPortTCP *int32 + + // The TCPS Single Client Access Name (SCAN) port. The default port is 2484. + ScanListenerPortTCPSSL *int32 + + // The data disk group size to be allocated in GBs per VM. + StorageSizeInGbs *int32 + + // Operating system version of the image. + SystemVersion *string + + // The time zone of the cloud VM cluster. For details, see [Exadata Infrastructure Time Zones](/Content/Database/References/timezones.htm). + TimeZone *string + + // The OCID of the zone the cloud VM cluster is associated with. + ZoneID *string + + // READ-ONLY; Cluster compartmentId + CompartmentID *string + + // READ-ONLY; The compute model of the VM Cluster. + ComputeModel *ComputeModel + + // READ-ONLY; The type of redundancy configured for the cloud Vm cluster. NORMAL is 2-way redundancy. HIGH is 3-way redundancy. + DiskRedundancy *DiskRedundancy + + // READ-ONLY; iormConfigCache details for cloud VM cluster. + IormConfigCache *ExadataIormConfig + + // READ-ONLY; The OCID of the last maintenance update history entry. + LastUpdateHistoryEntryID *string + + // READ-ONLY; Additional information about the current lifecycle state. + LifecycleDetails *string + + // READ-ONLY; CloudVmCluster lifecycle state + LifecycleState *CloudVMClusterLifecycleState + + // READ-ONLY; The port number configured for the listener on the cloud VM cluster. + ListenerPort *int64 + + // READ-ONLY; The number of nodes in the cloud VM cluster. + NodeCount *int32 + + // READ-ONLY; HTTPS link to OCI Network Security Group exposed to Azure Customer via the Azure Interface. + NsgURL *string + + // READ-ONLY; HTTPS link to OCI resources exposed to Azure Customer via Azure Interface. + OciURL *string + + // READ-ONLY; Cloud VM Cluster ocid + Ocid *string + + // READ-ONLY; CloudVmCluster provisioning state + ProvisioningState *AzureResourceProvisioningState + + // READ-ONLY; The FQDN of the DNS record for the SCAN IP addresses that are associated with the cloud VM cluster. + ScanDNSName *string + + // READ-ONLY; The OCID of the DNS record for the SCAN IP addresses that are associated with the cloud VM cluster. + ScanDNSRecordID *string + + // READ-ONLY; The Single Client Access Name (SCAN) IP addresses associated with the cloud VM cluster. SCAN IP addresses are + // typically used for load balancing and are not assigned to any interface. Oracle Clusterware directs the requests to the + // appropriate nodes in the cluster. **Note:** For a single-node DB system, this list is empty. + ScanIPIDs []*string + + // READ-ONLY; The model name of the Exadata hardware running the cloud VM cluster. + Shape *string + + // READ-ONLY; Specifies whether the type of storage management for the VM cluster is ASM or Exascale. + StorageManagementType *ExadataVMClusterStorageManagementType + + // READ-ONLY; Cluster subnet ocid + SubnetOcid *string + + // READ-ONLY; The date and time that the cloud VM cluster was created. + TimeCreated *time.Time + + // READ-ONLY; The virtual IP (VIP) addresses associated with the cloud VM cluster. The Cluster Ready Services (CRS) creates + // and maintains one VIP address for each node in the Exadata Cloud Service instance to enable failover. If one node fails, + // the VIP is reassigned to another active node in the cluster. **Note:** For a single-node DB system, this list is empty. + VipIDs []*string +} + +// CloudVMClusterUpdate - The type used for update operations of the CloudVmCluster. +type CloudVMClusterUpdate struct { + // The resource-specific properties for this resource. + Properties *CloudVMClusterUpdateProperties + + // Resource tags. + Tags map[string]*string +} + +// CloudVMClusterUpdateProperties - The updatable properties of the CloudVmCluster. +type CloudVMClusterUpdateProperties struct { + // The number of CPU cores enabled on the cloud VM cluster. + CPUCoreCount *int32 + + // The list of compute servers to be added to the cloud VM cluster. + ComputeNodes []*string + + // Indicates user preferences for the various diagnostic collection options for the VM cluster/Cloud VM cluster/VMBM DBCS. + DataCollectionOptions *DataCollectionOptions + + // The data disk group size to be allocated in TBs. + DataStorageSizeInTbs *float64 + + // The local node storage to be allocated in GBs. + DbNodeStorageSizeInGbs *int32 + + // Display Name + DisplayName *string + + // Array of mount path and size. + FileSystemConfigurationDetails []*FileSystemConfigurationDetails + + // The Oracle license model that applies to the cloud VM cluster. The default is LICENSE_INCLUDED. + LicenseModel *LicenseModel + + // The memory to be allocated in GBs. + MemorySizeInGbs *int32 + + // The number of OCPU cores to enable on the cloud VM cluster. Only 1 decimal place is allowed for the fractional part. + OcpuCount *float32 + + // The public key portion of one or more key pairs used for SSH access to the cloud VM cluster. + SSHPublicKeys []*string + + // The data disk group size to be allocated in GBs per VM. + StorageSizeInGbs *int32 +} + +// ConfigureExascaleCloudExadataInfrastructureDetails - The exascale config request details for the Cloud Exadata infrastructure. +type ConfigureExascaleCloudExadataInfrastructureDetails struct { + // REQUIRED; Storage size needed for Exascale in GBs. + TotalStorageInGbs *int32 +} + +// ConnectionStringType - Connection strings to connect to an Oracle Autonomous Database. +type ConnectionStringType struct { + // Returns all connection strings that can be used to connect to the Autonomous Database. + AllConnectionStrings *AllConnectionStringType + + // The database service provides the least level of resources to each SQL statement, but supports the most number of concurrent + // SQL statements. + Dedicated *string + + // The High database service provides the highest level of resources to each SQL statement resulting in the highest performance, + // but supports the fewest number of concurrent SQL statements. + High *string + + // The Low database service provides the least level of resources to each SQL statement, but supports the most number of concurrent + // SQL statements. + Low *string + + // The Medium database service provides a lower level of resources to each SQL statement potentially resulting a lower level + // of performance, but supports more concurrent SQL statements. + Medium *string + + // A list of connection string profiles to allow clients to group, filter and select connection string values based on structured + // metadata. + Profiles []*ProfileType +} + +// ConnectionURLType - The URLs for accessing Oracle Application Express (APEX) and SQL Developer Web with a browser from +// a Compute instance within your VCN or that has a direct connection to your VCN. +type ConnectionURLType struct { + // Oracle Application Express (APEX) URL. + ApexURL *string + + // The URL of the Database Transforms for the Autonomous Database. + DatabaseTransformsURL *string + + // The URL of the Graph Studio for the Autonomous Database. + GraphStudioURL *string + + // The URL of the Oracle Machine Learning (OML) Notebook for the Autonomous Database. + MachineLearningNotebookURL *string + + // The URL of the MongoDB API for the Autonomous Database. + MongoDbURL *string + + // The Oracle REST Data Services (ORDS) URL of the Web Access for the Autonomous Database. + OrdsURL *string + + // Oracle SQL Developer Web URL. + SQLDevWebURL *string +} + +// CustomerContact resource properties +type CustomerContact struct { + // REQUIRED; The email address used by Oracle to send notifications regarding databases and infrastructure. + Email *string +} + +// DNSForwardingRule - DNS forwarding rule properties +type DNSForwardingRule struct { + // REQUIRED; Comma-separated domain names + DomainNames *string + + // REQUIRED; Forwarding ip address + ForwardingIPAddress *string +} + +// DNSPrivateView - DnsPrivateView resource definition +type DNSPrivateView struct { + // The resource-specific properties for this resource. + Properties *DNSPrivateViewProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// DNSPrivateViewListResult - The response of a DnsPrivateView list operation. +type DNSPrivateViewListResult struct { + // REQUIRED; The DnsPrivateView items on this page + Value []*DNSPrivateView + + // The link to the next page of items + NextLink *string +} + +// DNSPrivateViewProperties - Views resource model +type DNSPrivateViewProperties struct { + // REQUIRED; The display name of the view resource + DisplayName *string + + // REQUIRED; A Boolean flag indicating whether or not parts of the resource are unable to be explicitly managed. + IsProtected *bool + + // REQUIRED; Views lifecycleState + LifecycleState *DNSPrivateViewsLifecycleState + + // REQUIRED; The OCID of the view + Ocid *string + + // REQUIRED; The canonical absolute URL of the resource. + Self *string + + // REQUIRED; views timeCreated + TimeCreated *time.Time + + // REQUIRED; views timeCreated + TimeUpdated *time.Time + + // READ-ONLY; Azure resource provisioning state. + ProvisioningState *ResourceProvisioningState +} + +// DNSPrivateZone - DnsPrivateZone resource definition +type DNSPrivateZone struct { + // The resource-specific properties for this resource. + Properties *DNSPrivateZoneProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// DNSPrivateZoneListResult - The response of a DnsPrivateZone list operation. +type DNSPrivateZoneListResult struct { + // REQUIRED; The DnsPrivateZone items on this page + Value []*DNSPrivateZone + + // The link to the next page of items + NextLink *string +} + +// DNSPrivateZoneProperties - Zones resource model +type DNSPrivateZoneProperties struct { + // REQUIRED; A Boolean flag indicating whether or not parts of the resource are unable to be explicitly managed. + IsProtected *bool + + // REQUIRED; Zones lifecycleState + LifecycleState *DNSPrivateZonesLifecycleState + + // REQUIRED; The OCID of the Zone + Ocid *string + + // REQUIRED; The canonical absolute URL of the resource. + Self *string + + // REQUIRED; The current serial of the zone. As seen in the zone's SOA record. + Serial *int32 + + // REQUIRED; Zones timeCreated + TimeCreated *time.Time + + // REQUIRED; Version is the never-repeating, totally-orderable, version of the zone, from which the serial field of the zone's + // SOA record is derived. + Version *string + + // REQUIRED; The type of the zone. Must be either PRIMARY or SECONDARY. SECONDARY is only supported for GLOBAL zones. + ZoneType *ZoneType + + // The OCID of the private view containing the zone. This value will be null for zones in the global DNS, which are publicly + // resolvable and not part of a private view. + ViewID *string + + // READ-ONLY; Azure resource provisioning state. + ProvisioningState *ResourceProvisioningState +} + +// DataCollectionOptions resource properties +type DataCollectionOptions struct { + // Indicates whether diagnostic collection is enabled for the VM cluster/Cloud VM cluster/VMBM DBCS. + IsDiagnosticsEventsEnabled *bool + + // Indicates whether health monitoring is enabled for the VM cluster / Cloud VM cluster / VMBM DBCS. + IsHealthMonitoringEnabled *bool + + // Indicates whether incident logs and trace collection are enabled for the VM cluster / Cloud VM cluster / VMBM DBCS. + IsIncidentLogsEnabled *bool +} + +// DayOfWeek resource properties +type DayOfWeek struct { + // REQUIRED; Name of the day of the week. + Name *DayOfWeekName +} + +// DayOfWeekUpdate - DayOfWeek resource properties +type DayOfWeekUpdate struct { + // Name of the day of the week. + Name *DayOfWeekName +} + +// DbActionResponse - ExascaleDbNode action response +type DbActionResponse struct { + // ExascaleDbNode provisioning state + ProvisioningState *AzureResourceProvisioningState +} + +// DbIormConfig for cloud vm cluster +type DbIormConfig struct { + // The database name. For the default DbPlan, the dbName is default. + DbName *string + + // The flash cache limit for this database. This value is internally configured based on the share value assigned to the database. + FlashCacheLimit *string + + // The relative priority of this database. + Share *int32 +} + +// DbNode - The DbNode resource belonging to vmCluster +type DbNode struct { + // The resource-specific properties for this resource. + Properties *DbNodeProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// DbNodeAction - DbNode action object +type DbNodeAction struct { + // REQUIRED; Db action + Action *DbNodeActionEnum +} + +// DbNodeDetails - Details of the ExaCS Db node. Applies to Exadata Database Service on Exascale Infrastructure only. +type DbNodeDetails struct { + // REQUIRED; Exascale DbNode Azure Resource ID + DbNodeID *string +} + +// DbNodeListResult - The response of a DbNode list operation. +type DbNodeListResult struct { + // REQUIRED; The DbNode items on this page + Value []*DbNode + + // The link to the next page of items + NextLink *string +} + +// DbNodeProperties - The properties of DbNodeResource +type DbNodeProperties struct { + // REQUIRED; The OCID of the DB system. + DbSystemID *string + + // REQUIRED; The current state of the database node. + LifecycleState *DbNodeProvisioningState + + // REQUIRED; DbNode OCID + Ocid *string + + // REQUIRED; The date and time that the database node was created. + TimeCreated *time.Time + + // REQUIRED; The OCID of the VNIC. + VnicID *string + + // Additional information about the planned maintenance. + AdditionalDetails *string + + // The OCID of the backup IP address associated with the database node. + BackupIPID *string + + // The OCID of the second backup VNIC. + BackupVnic2ID *string + + // The OCID of the backup VNIC. + BackupVnicID *string + + // The number of CPU cores enabled on the Db node. + CPUCoreCount *int32 + + // The allocated local node storage in GBs on the Db node. + DbNodeStorageSizeInGbs *int32 + + // The OCID of the Exacc Db server associated with the database node. + DbServerID *string + + // The name of the Fault Domain the instance is contained in. + FaultDomain *string + + // The OCID of the host IP address associated with the database node. + HostIPID *string + + // The host name for the database node. + Hostname *string + + // Lifecycle details of Db Node. + LifecycleDetails *string + + // The type of database node maintenance. + MaintenanceType *DbNodeMaintenanceType + + // The allocated memory in GBs on the Db node. + MemorySizeInGbs *int32 + + // The size (in GB) of the block storage volume allocation for the DB system. This attribute applies only for virtual machine + // DB systems. + SoftwareStorageSizeInGb *int32 + + // End date and time of maintenance window. + TimeMaintenanceWindowEnd *time.Time + + // Start date and time of maintenance window. + TimeMaintenanceWindowStart *time.Time + + // The OCID of the second VNIC. + Vnic2ID *string + + // READ-ONLY; Azure resource provisioning state. + ProvisioningState *ResourceProvisioningState +} + +// DbServer resource model +type DbServer struct { + // The resource-specific properties for this resource. + Properties *DbServerProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// DbServerListResult - The response of a DbServer list operation. +type DbServerListResult struct { + // REQUIRED; The DbServer items on this page + Value []*DbServer + + // The link to the next page of items + NextLink *string +} + +// DbServerPatchingDetails - DbServer Patching Properties +type DbServerPatchingDetails struct { + // READ-ONLY; Estimated Patch Duration + EstimatedPatchDuration *int32 + + // READ-ONLY; Patching Status + PatchingStatus *DbServerPatchingStatus + + // READ-ONLY; Time Patching Ended + TimePatchingEnded *time.Time + + // READ-ONLY; Time Patching Started + TimePatchingStarted *time.Time +} + +// DbServerProperties - DbServer resource properties +type DbServerProperties struct { + // READ-ONLY; The list of OCIDs of the Autonomous VM Clusters associated with the Db server. + AutonomousVMClusterIDs []*string + + // READ-ONLY; The list of OCIDs of the Autonomous Virtual Machines associated with the Db server. + AutonomousVirtualMachineIDs []*string + + // READ-ONLY; The number of CPU cores enabled on the Db server. + CPUCoreCount *int32 + + // READ-ONLY; The OCID of the compartment. + CompartmentID *string + + // READ-ONLY; The compute model of the Exadata Infrastructure + ComputeModel *ComputeModel + + // READ-ONLY; The OCID of the Db nodes associated with the Db server. + DbNodeIDs []*string + + // READ-ONLY; The allocated local node storage in GBs on the Db server. + DbNodeStorageSizeInGbs *int32 + + // READ-ONLY; dbServerPatching details of the Db server. + DbServerPatchingDetails *DbServerPatchingDetails + + // READ-ONLY; The name for the Db Server. + DisplayName *string + + // READ-ONLY; The OCID of the Exadata infrastructure. + ExadataInfrastructureID *string + + // READ-ONLY; Lifecycle details of dbServer. + LifecycleDetails *string + + // READ-ONLY; DbServer provisioning state. + LifecycleState *DbServerProvisioningState + + // READ-ONLY; The total number of CPU cores available. + MaxCPUCount *int32 + + // READ-ONLY; The total max dbNode storage in GBs. + MaxDbNodeStorageInGbs *int32 + + // READ-ONLY; The total memory available in GBs. + MaxMemoryInGbs *int32 + + // READ-ONLY; The total memory size in GBs. + MemorySizeInGbs *int32 + + // READ-ONLY; Db server name. + Ocid *string + + // READ-ONLY; Azure resource provisioning state. + ProvisioningState *ResourceProvisioningState + + // READ-ONLY; The shape of the Db server. The shape determines the amount of CPU, storage, and memory resources available. + Shape *string + + // READ-ONLY; The date and time that the Db Server was created. + TimeCreated *time.Time + + // READ-ONLY; The OCID of the VM Clusters associated with the Db server. + VMClusterIDs []*string +} + +// DbSystem resource definition +type DbSystem struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *DbSystemProperties + + // Resource tags. + Tags map[string]*string + + // The availability zones. + Zones []*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// DbSystemBaseProperties - DbSystem resource base model. +type DbSystemBaseProperties struct { + // REQUIRED; The hostname for the DB system. + Hostname *string + + // REQUIRED; Azure Network Anchor ID + NetworkAnchorID *string + + // REQUIRED; Azure Resource Anchor ID + ResourceAnchorID *string + + // REQUIRED; The public key portion of one or more key pairs used for SSH access to the DB system. + SSHPublicKeys []*string + + // REQUIRED; The shape of the DB system. The shape determines resources to allocate to the DB system. For virtual machine + // shapes, the number of CPU cores and memory. For bare metal and Exadata shapes, the number of CPU cores, storage, and memory. + Shape *string + + // The cluster name for Exadata and 2-node RAC virtual machine DB systems. The cluster name must begin with an alphabetic + // character, and may contain hyphens (-). Underscores (_) are not permitted. The cluster name can be no longer than 11 characters + // and is not case sensitive. + ClusterName *string + + // The number of compute servers for the DB system. + ComputeCount *int32 + + // The compute model for Base Database Service. This is required if using the `computeCount` parameter. If using `cpuCoreCount` + // then it is an error to specify `computeModel` to a non-null value. The ECPU compute model is the recommended model, and + // the OCPU compute model is legacy. + ComputeModel *ComputeModel + + // The DB system options. + DbSystemOptions *DbSystemOptions + + // The type of redundancy configured for the DB system. NORMAL is 2-way redundancy. HIGH is 3-way redundancy. + DiskRedundancy *DiskRedundancyType + + // The user-friendly name for the DB system. The name does not have to be unique. + DisplayName *string + + // The domain name for the DB system. + DomainV2 *string + + // Size in GB of the initial data volume that will be created and attached to a virtual machine DB system. You can scale up + // storage after provisioning, as needed. Note that the total storage size attached will be more than the amount you specify + // to allow for REDO/RECO space and software volume. + InitialDataStorageSizeInGb *int32 + + // The Oracle license model that applies to all the databases on the DB system. The default is LicenseIncluded. + LicenseModelV2 *LicenseModel + + // The number of nodes in the DB system. For RAC DB systems, the value is greater than 1. + NodeCount *int32 + + // The source of the database: Use `None` for creating a new database. The default is `None`. + Source *DbSystemSourceType + + // The block storage volume performance level. Valid values are Balanced and HighPerformance. See [Block Volume Performance](/Content/Block/Concepts/blockvolumeperformance.htm) + // for more information. + StorageVolumePerformanceMode *StorageVolumePerformanceMode + + // The time zone of the DB system, e.g., UTC, to set the timeZone as UTC. + TimeZone *string + + // READ-ONLY; The data storage size, in gigabytes, that is currently available to the DB system. Applies only for virtual + // machine DB systems. + DataStorageSizeInGbs *int32 + + // READ-ONLY; The OCID of a grid infrastructure software image. This is a database software image of the type GRID_IMAGE. + GridImageOcid *string + + // READ-ONLY; Additional information about the current lifecycle state. + LifecycleDetails *string + + // READ-ONLY; The current state of the DB system. + LifecycleState *DbSystemLifecycleState + + // READ-ONLY; The port number configured for the listener on the DB system. + ListenerPort *int32 + + // READ-ONLY; Memory allocated to the DB system, in gigabytes. + MemorySizeInGbs *int32 + + // READ-ONLY; HTTPS link to OCI resources exposed to Azure Customer via Azure Interface. + OciURL *string + + // READ-ONLY; The OCID of the DB system. + Ocid *string + + // READ-ONLY; dbSystem provisioning state + ProvisioningState *AzureResourceProvisioningState + + // READ-ONLY; The FQDN of the DNS record for the SCAN IP addresses that are associated with the DB system. + ScanDNSName *string + + // READ-ONLY; The list of Single Client Access Name (SCAN) IP addresses associated with the DB system. SCAN IP addresses are + // typically used for load balancing and are not assigned to any interface. Oracle Clusterware directs the requests to the + // appropriate nodes in the cluster. Note: For a single-node DB system, this list is empty. + ScanIPs []*string + + // READ-ONLY; The Oracle Database version of the DB system. + Version *string +} + +// GetDbSystemBaseProperties implements the DbSystemBasePropertiesClassification interface for type DbSystemBaseProperties. +func (d *DbSystemBaseProperties) GetDbSystemBaseProperties() *DbSystemBaseProperties { return d } + +// DbSystemListResult - The response of a DbSystem list operation. +type DbSystemListResult struct { + // REQUIRED; The DbSystem items on this page + Value []*DbSystem + + // The link to the next page of items + NextLink *string +} + +// DbSystemOptions resource properties. +type DbSystemOptions struct { + // The storage option used in DB system. ASM - Automatic storage management, LVM - Logical Volume management. + StorageManagement *StorageManagementType +} + +// DbSystemProperties - DbSystem resource model. +type DbSystemProperties struct { + // REQUIRED; The Oracle Database Edition that applies to all the databases on the DB system. Exadata DB systems and 2-node + // RAC DB systems require EnterpriseEditionExtremePerformance. + DatabaseEdition *DbSystemDatabaseEditionType + + // REQUIRED; A valid Oracle Database version. For a list of supported versions, use the ListDbVersions operation. + DbVersion *string + + // REQUIRED; The hostname for the DB system. + Hostname *string + + // REQUIRED; Azure Network Anchor ID + NetworkAnchorID *string + + // REQUIRED; Azure Resource Anchor ID + ResourceAnchorID *string + + // REQUIRED; The public key portion of one or more key pairs used for SSH access to the DB system. + SSHPublicKeys []*string + + // REQUIRED; The shape of the DB system. The shape determines resources to allocate to the DB system. For virtual machine + // shapes, the number of CPU cores and memory. For bare metal and Exadata shapes, the number of CPU cores, storage, and memory. + Shape *string + + // CONSTANT; The source of the database for creating a new database. + // Field has constant value DbSystemSourceTypeNone, any specified value is ignored. + Source *DbSystemSourceType + + // A strong password for SYS, SYSTEM, and PDB Admin. The password must be at least nine characters and contain at least two + // uppercase, two lowercase, two numbers, and two special characters. The special characters must be _, #, or -. + AdminPassword *string + + // The cluster name for Exadata and 2-node RAC virtual machine DB systems. The cluster name must begin with an alphabetic + // character, and may contain hyphens (-). Underscores (_) are not permitted. The cluster name can be no longer than 11 characters + // and is not case sensitive. + ClusterName *string + + // The number of compute servers for the DB system. + ComputeCount *int32 + + // The compute model for Base Database Service. This is required if using the `computeCount` parameter. If using `cpuCoreCount` + // then it is an error to specify `computeModel` to a non-null value. The ECPU compute model is the recommended model, and + // the OCPU compute model is legacy. + ComputeModel *ComputeModel + + // The DB system options. + DbSystemOptions *DbSystemOptions + + // The type of redundancy configured for the DB system. NORMAL is 2-way redundancy. HIGH is 3-way redundancy. + DiskRedundancy *DiskRedundancyType + + // The user-friendly name for the DB system. The name does not have to be unique. + DisplayName *string + + // The domain name for the DB system. + DomainV2 *string + + // Size in GB of the initial data volume that will be created and attached to a virtual machine DB system. You can scale up + // storage after provisioning, as needed. Note that the total storage size attached will be more than the amount you specify + // to allow for REDO/RECO space and software volume. + InitialDataStorageSizeInGb *int32 + + // The Oracle license model that applies to all the databases on the DB system. The default is LicenseIncluded. + LicenseModelV2 *LicenseModel + + // The number of nodes in the DB system. For RAC DB systems, the value is greater than 1. + NodeCount *int32 + + // The name of the pluggable database. The name must begin with an alphabetic character and can contain a maximum of thirty + // alphanumeric characters. Special characters are not permitted. Pluggable database should not be same as database name. + PdbName *string + + // The block storage volume performance level. Valid values are Balanced and HighPerformance. See [Block Volume Performance](/Content/Block/Concepts/blockvolumeperformance.htm) + // for more information. + StorageVolumePerformanceMode *StorageVolumePerformanceMode + + // The time zone of the DB system, e.g., UTC, to set the timeZone as UTC. + TimeZone *string + + // READ-ONLY; The data storage size, in gigabytes, that is currently available to the DB system. Applies only for virtual + // machine DB systems. + DataStorageSizeInGbs *int32 + + // READ-ONLY; The OCID of a grid infrastructure software image. This is a database software image of the type GRID_IMAGE. + GridImageOcid *string + + // READ-ONLY; Additional information about the current lifecycle state. + LifecycleDetails *string + + // READ-ONLY; The current state of the DB system. + LifecycleState *DbSystemLifecycleState + + // READ-ONLY; The port number configured for the listener on the DB system. + ListenerPort *int32 + + // READ-ONLY; Memory allocated to the DB system, in gigabytes. + MemorySizeInGbs *int32 + + // READ-ONLY; HTTPS link to OCI resources exposed to Azure Customer via Azure Interface. + OciURL *string + + // READ-ONLY; The OCID of the DB system. + Ocid *string + + // READ-ONLY; dbSystem provisioning state + ProvisioningState *AzureResourceProvisioningState + + // READ-ONLY; The FQDN of the DNS record for the SCAN IP addresses that are associated with the DB system. + ScanDNSName *string + + // READ-ONLY; The list of Single Client Access Name (SCAN) IP addresses associated with the DB system. SCAN IP addresses are + // typically used for load balancing and are not assigned to any interface. Oracle Clusterware directs the requests to the + // appropriate nodes in the cluster. Note: For a single-node DB system, this list is empty. + ScanIPs []*string + + // READ-ONLY; The Oracle Database version of the DB system. + Version *string +} + +// GetDbSystemBaseProperties implements the DbSystemBasePropertiesClassification interface for type DbSystemProperties. +func (d *DbSystemProperties) GetDbSystemBaseProperties() *DbSystemBaseProperties { + return &DbSystemBaseProperties{ + ClusterName: d.ClusterName, + ComputeCount: d.ComputeCount, + ComputeModel: d.ComputeModel, + DataStorageSizeInGbs: d.DataStorageSizeInGbs, + DbSystemOptions: d.DbSystemOptions, + DiskRedundancy: d.DiskRedundancy, + DisplayName: d.DisplayName, + DomainV2: d.DomainV2, + GridImageOcid: d.GridImageOcid, + Hostname: d.Hostname, + InitialDataStorageSizeInGb: d.InitialDataStorageSizeInGb, + LicenseModelV2: d.LicenseModelV2, + LifecycleDetails: d.LifecycleDetails, + LifecycleState: d.LifecycleState, + ListenerPort: d.ListenerPort, + MemorySizeInGbs: d.MemorySizeInGbs, + NetworkAnchorID: d.NetworkAnchorID, + NodeCount: d.NodeCount, + OciURL: d.OciURL, + Ocid: d.Ocid, + ProvisioningState: d.ProvisioningState, + ResourceAnchorID: d.ResourceAnchorID, + SSHPublicKeys: d.SSHPublicKeys, + ScanDNSName: d.ScanDNSName, + ScanIPs: d.ScanIPs, + Shape: d.Shape, + Source: d.Source, + StorageVolumePerformanceMode: d.StorageVolumePerformanceMode, + TimeZone: d.TimeZone, + Version: d.Version, + } +} + +// DbSystemShape resource definition +type DbSystemShape struct { + // The resource-specific properties for this resource. + Properties *DbSystemShapeProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// DbSystemShapeListResult - The response of a DbSystemShape list operation. +type DbSystemShapeListResult struct { + // REQUIRED; The DbSystemShape items on this page + Value []*DbSystemShape + + // The link to the next page of items + NextLink *string +} + +// DbSystemShapeProperties - DbSystemShape resource model +type DbSystemShapeProperties struct { + // REQUIRED; The maximum number of CPU cores that can be enabled on the DB system for this shape. + AvailableCoreCount *int32 + + // REQUIRED; The shape used for the DB system. + ShapeName *string + + // Indicates if the shape supports database and storage server types + AreServerTypesSupported *bool + + // The maximum number of CPU cores per database node that can be enabled for this shape. Only applicable to the flex Exadata + // shape and ExaCC Elastic shapes. + AvailableCoreCountPerNode *int32 + + // The maximum DATA storage that can be enabled for this shape. + AvailableDataStorageInTbs *int32 + + // The maximum data storage available per storage server for this shape. Only applicable to ExaCC Elastic shapes. + AvailableDataStoragePerServerInTbs *float64 + + // The maximum Db Node storage available per database node for this shape. Only applicable to ExaCC Elastic shapes. + AvailableDbNodePerNodeInGbs *int32 + + // The maximum Db Node storage that can be enabled for this shape. + AvailableDbNodeStorageInGbs *int32 + + // The maximum memory that can be enabled for this shape. + AvailableMemoryInGbs *int32 + + // The maximum memory available per database node for this shape. Only applicable to ExaCC Elastic shapes. + AvailableMemoryPerNodeInGbs *int32 + + // The compute model of the Exadata Infrastructure + ComputeModel *ComputeModel + + // The discrete number by which the CPU core count for this shape can be increased or decreased. + CoreCountIncrement *int32 + + // The display name of the shape used for the DB system + DisplayName *string + + // The maximum number of Exadata storage servers available for the Exadata infrastructure. + MaxStorageCount *int32 + + // The maximum number of database nodes available for this shape. + MaximumNodeCount *int32 + + // The minimum number of CPU cores that can be enabled per node for this shape. + MinCoreCountPerNode *int32 + + // The minimum data storage that need be allocated for this shape. + MinDataStorageInTbs *int32 + + // The minimum Db Node storage that need be allocated per node for this shape. + MinDbNodeStoragePerNodeInGbs *int32 + + // The minimum memory that need be allocated per node for this shape. + MinMemoryPerNodeInGbs *int32 + + // The minimum number of Exadata storage servers available for the Exadata infrastructure. + MinStorageCount *int32 + + // The minimum number of CPU cores that can be enabled on the DB system for this shape. + MinimumCoreCount *int32 + + // The minimum number of database nodes available for this shape. + MinimumNodeCount *int32 + + // The runtime minimum number of CPU cores that can be enabled on the DB system for this shape. + RuntimeMinimumCoreCount *int32 + + // The shapeAttributes of the DB system shape.. + ShapeAttributes []*string + + // The family of the shape used for the DB system. + ShapeFamily *string +} + +// DbSystemUpdate - The type used for update operations of the DbSystem. +type DbSystemUpdate struct { + // The resource-specific properties for this resource. + Properties *DbSystemUpdateProperties + + // Resource tags. + Tags map[string]*string + + // The availability zones. + Zones []*string +} + +// DbSystemUpdateProperties - The updatable properties of the DbSystem. +type DbSystemUpdateProperties struct { + // FLAG; CONSTANT; The source of the database for creating a new database. + // Field has constant value DbSystemSourceTypeNone, any specified value is ignored. + Source *DbSystemSourceType +} + +// DbVersion - Oracle Database DbVersion resource definition +type DbVersion struct { + // The resource-specific properties for this resource. + Properties *DbVersionProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// DbVersionListResult - The response of a DbVersion list operation. +type DbVersionListResult struct { + // REQUIRED; The DbVersion items on this page + Value []*DbVersion + + // The link to the next page of items + NextLink *string +} + +// DbVersionProperties - DbVersion resource model +type DbVersionProperties struct { + // REQUIRED; A valid Oracle Database version. + Version *string + + // True if this version of the Oracle Database software is the latest version for a release. + IsLatestForMajorVersion *bool + + // True if this version of the Oracle Database software is the preview version. + IsPreviewDbVersion *bool + + // True if this version of the Oracle Database software is supported for Upgrade. + IsUpgradeSupported *bool + + // True if this version of the Oracle Database software supports pluggable databases. + SupportsPdb *bool +} + +// DefinedFileSystemConfiguration - Predefined configurations for the file system +type DefinedFileSystemConfiguration struct { + // Checks if the data can be backed up + IsBackupPartition *bool + + // Checks if the mount path is resizable + IsResizable *bool + + // Minimum size of mount path in Gb + MinSizeGb *int32 + + // Mount path for the file system + MountPoint *string +} + +// DisasterRecoveryConfigurationDetails - Configurations of a Disaster Recovery Details +type DisasterRecoveryConfigurationDetails struct { + // Indicates the disaster recovery (DR) type of the Autonomous Database Serverless instance. Autonomous Data Guard (ADG) DR + // type provides business critical DR with a faster recovery time objective (RTO) during failover or switchover. Backup-based + // DR type provides lower cost DR with a slower RTO during failover or switchover. + DisasterRecoveryType *DisasterRecoveryType + + // If true, 7 days worth of backups are replicated across regions for Cross-Region ADB or Backup-Based DR between Primary + // and Standby. If false, the backups taken on the Primary are not replicated to the Standby database. + IsReplicateAutomaticBackups *bool + + // Indicates if user wants to convert to a snapshot standby. For example, true would set a standby database to snapshot standby + // database. False would set a snapshot standby database back to regular standby database. + IsSnapshotStandby *bool + + // Time and date stored as an RFC 3339 formatted timestamp string. For example, 2022-01-01T12:00:00.000Z would set a limit + // for the snapshot standby to be converted back to a cross-region standby database. + TimeSnapshotStandbyEnabledTill *time.Time +} + +// EstimatedPatchingTime - The estimated total time required in minutes for all patching operations (database server, storage +// server, and network switch patching). +type EstimatedPatchingTime struct { + // READ-ONLY; The estimated time required in minutes for database server patching. + EstimatedDbServerPatchingTime *int32 + + // READ-ONLY; The estimated time required in minutes for network switch patching. + EstimatedNetworkSwitchesPatchingTime *int32 + + // READ-ONLY; The estimated time required in minutes for storage server patching. + EstimatedStorageServerPatchingTime *int32 + + // READ-ONLY; The estimated total time required in minutes for all patching operations. + TotalEstimatedPatchingTime *int32 +} + +// ExadataIormConfig for cloud vm cluster +type ExadataIormConfig struct { + // An array of IORM settings for all the database in the Exadata DB system. + DbPlans []*DbIormConfig + + // Additional information about the current lifecycleState. + LifecycleDetails *string + + // The current state of IORM configuration for the Exadata DB system. + LifecycleState *IormLifecycleState + + // The current value for the IORM objective. The default is AUTO. + Objective *Objective +} + +// ExadbVMCluster - ExadbVmCluster resource definition +type ExadbVMCluster struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *ExadbVMClusterProperties + + // Resource tags. + Tags map[string]*string + + // The availability zones. + Zones []*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ExadbVMClusterListResult - The response of a ExadbVmCluster list operation. +type ExadbVMClusterListResult struct { + // REQUIRED; The ExadbVmCluster items on this page + Value []*ExadbVMCluster + + // The link to the next page of items + NextLink *string +} + +// ExadbVMClusterProperties - ExadbVmCluster resource model +type ExadbVMClusterProperties struct { + // REQUIRED; Display Name + DisplayName *string + + // REQUIRED; The number of ECPUs to enable for an Exadata VM cluster on Exascale Infrastructure. + EnabledEcpuCount *int32 + + // REQUIRED; The Azure Resource ID of the Exadata Database Storage Vault. + ExascaleDbStorageVaultID *string + + // REQUIRED; The hostname for the Exadata VM cluster on Exascale Infrastructure. + Hostname *string + + // REQUIRED; The number of nodes in the Exadata VM cluster on Exascale Infrastructure. + NodeCount *int32 + + // REQUIRED; The public key portion of one or more key pairs used for SSH access to the Exadata VM cluster on Exascale Infrastructure. + SSHPublicKeys []*string + + // REQUIRED; The shape of the Exadata VM cluster on Exascale Infrastructure resource + Shape *string + + // REQUIRED; Client subnet + SubnetID *string + + // REQUIRED; The number of Total ECPUs for an Exadata VM cluster on Exascale Infrastructure. + TotalEcpuCount *int32 + + // REQUIRED; Filesystem storage details. + VMFileSystemStorage *ExadbVMClusterStorageDetails + + // REQUIRED; VNET for network connectivity + VnetID *string + + // Client OCI backup subnet CIDR, default is 192.168.252.0/22 + BackupSubnetCidr *string + + // The cluster name for Exadata VM cluster on Exascale Infrastructure. The cluster name must begin with an alphabetic character, + // and may contain hyphens (-). Underscores (_) are not permitted. The cluster name can be no longer than 11 characters and + // is not case sensitive. + ClusterName *string + + // Indicates user preferences for the various diagnostic collection options for the VM cluster/Cloud VM cluster/VMBM DBCS. + DataCollectionOptions *DataCollectionOptions + + // A domain name used for the Exadata VM cluster on Exascale Infrastructure + Domain *string + + // Grid Setup will be done using this Grid Image OCID. Can be obtained using giMinorVersions API + GridImageOcid *string + + // The Oracle license model that applies to the Exadata VM cluster on Exascale Infrastructure. The default is LICENSE_INCLUDED. + LicenseModel *LicenseModel + + // CIDR blocks for additional NSG ingress rules. The VNET CIDRs used to provision the VM Cluster will be added by default. + NsgCidrs []*NsgCidr + + // The OCID of the zone the Exadata VM cluster on Exascale Infrastructure is associated with. + PrivateZoneOcid *string + + // The TCP Single Client Access Name (SCAN) port. The default port is 1521. + ScanListenerPortTCP *int32 + + // The TCPS Single Client Access Name (SCAN) port. The default port is 2484. + ScanListenerPortTCPSSL *int32 + + // The type of Exascale storage used for Exadata VM cluster. + ShapeAttribute *ShapeAttribute + + // Operating system version of the image. + SystemVersion *string + + // The time zone of the Exadata VM cluster on Exascale Infrastructure. For details, see [Exadata Infrastructure Time Zones](/Content/Database/References/timezones.htm). + TimeZone *string + + // READ-ONLY; Cluster backup subnet ocid + BackupSubnetOcid *string + + // READ-ONLY; Oracle Grid Infrastructure (GI) software version + GiVersion *string + + // READ-ONLY; The type of Grid Image + GridImageType *GridImageType + + // READ-ONLY; iormConfigCache details for Exadata VM cluster on Exascale Infrastructure. + IormConfigCache *ExadataIormConfig + + // READ-ONLY; Additional information about the current lifecycle state. + LifecycleDetails *string + + // READ-ONLY; CloudVmCluster lifecycle state + LifecycleState *ExadbVMClusterLifecycleState + + // READ-ONLY; The port number configured for the listener on the Exadata VM cluster on Exascale Infrastructure. + ListenerPort *int32 + + // READ-ONLY; The memory that you want to be allocated in GBs. Memory is calculated based on 11 GB per VM core reserved. + MemorySizeInGbs *int32 + + // READ-ONLY; HTTPS link to OCI Network Security Group exposed to Azure Customer via the Azure Interface. + NsgURL *string + + // READ-ONLY; HTTPS link to OCI resources exposed to Azure Customer via Azure Interface. + OciURL *string + + // READ-ONLY; ExadbVmCluster ocid + Ocid *string + + // READ-ONLY; Exadata VM cluster on Exascale Infrastructure provisioning state + ProvisioningState *AzureResourceProvisioningState + + // READ-ONLY; The FQDN of the DNS record for the SCAN IP addresses that are associated with the Exadata VM cluster on Exascale + // Infrastructure. + ScanDNSName *string + + // READ-ONLY; The OCID of the DNS record for the SCAN IP addresses that are associated with the Exadata VM cluster on Exascale + // Infrastructure. + ScanDNSRecordID *string + + // READ-ONLY; The Single Client Access Name (SCAN) IP addresses associated with the Exadata VM cluster on Exascale Infrastructure. + // SCAN IP addresses are typically used for load balancing and are not assigned to any interface. Oracle Clusterware directs + // the requests to the appropriate nodes in the cluster. **Note:** For a single-node DB system, this list is empty. + ScanIPIDs []*string + + // READ-ONLY; Snapshot filesystem storage details. + SnapshotFileSystemStorage *ExadbVMClusterStorageDetails + + // READ-ONLY; Cluster subnet ocid + SubnetOcid *string + + // READ-ONLY; Total file system storage details. + TotalFileSystemStorage *ExadbVMClusterStorageDetails + + // READ-ONLY; The virtual IP (VIP) addresses associated with the Exadata VM cluster on Exascale Infrastructure. The Cluster + // Ready Services (CRS) creates and maintains one VIP address for each node in the Exadata Cloud Service instance to enable + // failover. If one node fails, the VIP is reassigned to another active node in the cluster. **Note:** For a single-node DB + // system, this list is empty. + VipIDs []*string + + // READ-ONLY; The OCID of the zone the Exadata VM cluster on Exascale Infrastructure is associated with. + ZoneOcid *string +} + +// ExadbVMClusterStorageDetails - Storage Details on the Exadata VM cluster. +type ExadbVMClusterStorageDetails struct { + // REQUIRED; Total Capacity + TotalSizeInGbs *int32 +} + +// ExadbVMClusterUpdate - The type used for update operations of the ExadbVmCluster. +type ExadbVMClusterUpdate struct { + // The resource-specific properties for this resource. + Properties *ExadbVMClusterUpdateProperties + + // Resource tags. + Tags map[string]*string + + // The availability zones. + Zones []*string +} + +// ExadbVMClusterUpdateProperties - The updatable properties of the ExadbVmCluster. +type ExadbVMClusterUpdateProperties struct { + // The number of nodes in the Exadata VM cluster on Exascale Infrastructure. + NodeCount *int32 +} + +// ExascaleConfigDetails - The exascale config response details for the cloud Exadata infrastructure +type ExascaleConfigDetails struct { + // REQUIRED; Storage size needed for Exascale in GBs. + TotalStorageInGbs *int32 + + // Available storage size for Exascale in GBs. + AvailableStorageInGbs *int32 +} + +// ExascaleDbNode - The DbNode resource belonging to ExadbVmCluster +type ExascaleDbNode struct { + // The resource-specific properties for this resource. + Properties *ExascaleDbNodeProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ExascaleDbNodeListResult - The response of a ExascaleDbNode list operation. +type ExascaleDbNodeListResult struct { + // REQUIRED; The ExascaleDbNode items on this page + Value []*ExascaleDbNode + + // The link to the next page of items + NextLink *string +} + +// ExascaleDbNodeProperties - The properties of DbNodeResource +type ExascaleDbNodeProperties struct { + // REQUIRED; DbNode OCID + Ocid *string + + // Additional information about the planned maintenance. + AdditionalDetails *string + + // The number of CPU cores enabled on the Db node. + CPUCoreCount *int32 + + // The allocated local node storage in GBs on the Db node. + DbNodeStorageSizeInGbs *int32 + + // The name of the Fault Domain the instance is contained in. + FaultDomain *string + + // The host name for the database node. + Hostname *string + + // The current state of the database node. + LifecycleState *DbNodeProvisioningState + + // The type of database node maintenance. + MaintenanceType *string + + // The allocated memory in GBs on the Db node. + MemorySizeInGbs *int32 + + // The size (in GB) of the block storage volume allocation for the DB system. This attribute applies only for virtual machine + // DB systems. + SoftwareStorageSizeInGb *int32 + + // End date and time of maintenance window. + TimeMaintenanceWindowEnd *time.Time + + // Start date and time of maintenance window. + TimeMaintenanceWindowStart *time.Time + + // The total number of CPU cores reserved on the Db node. + TotalCPUCoreCount *int32 +} + +// ExascaleDbStorageDetails - Exadata Database Storage Details +type ExascaleDbStorageDetails struct { + // Available Capacity + AvailableSizeInGbs *int32 + + // Total Capacity + TotalSizeInGbs *int32 +} + +// ExascaleDbStorageInputDetails - Create exadata Database Storage Details model +type ExascaleDbStorageInputDetails struct { + // REQUIRED; Total Capacity + TotalSizeInGbs *int32 +} + +// ExascaleDbStorageVault resource definition +type ExascaleDbStorageVault struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *ExascaleDbStorageVaultProperties + + // Resource tags. + Tags map[string]*string + + // The availability zones. + Zones []*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ExascaleDbStorageVaultListResult - The response of a ExascaleDbStorageVault list operation. +type ExascaleDbStorageVaultListResult struct { + // REQUIRED; The ExascaleDbStorageVault items on this page + Value []*ExascaleDbStorageVault + + // The link to the next page of items + NextLink *string +} + +// ExascaleDbStorageVaultProperties - ExascaleDbStorageVault resource model +type ExascaleDbStorageVaultProperties struct { + // REQUIRED; The user-friendly name for the Exadata Database Storage Vault. The name does not need to be unique. + DisplayName *string + + // REQUIRED; Create exadata Database Storage Details + HighCapacityDatabaseStorageInput *ExascaleDbStorageInputDetails + + // The size of additional Flash Cache in percentage of High Capacity database storage. + AdditionalFlashCacheInPercent *int32 + + // Exadata Database Storage Vault description. + Description *string + + // Cloud Exadata infrastructure ID + ExadataInfrastructureID *string + + // The time zone that you want to use for the Exadata Database Storage Vault + TimeZone *string + + // READ-ONLY; The shapeAttribute of the Exadata VM cluster(s) associated with the Exadata Database Storage Vault. + AttachedShapeAttributes []*ShapeAttribute + + // READ-ONLY; Response exadata Database Storage Details + HighCapacityDatabaseStorage *ExascaleDbStorageDetails + + // READ-ONLY; Additional information about the current lifecycle state. + LifecycleDetails *string + + // READ-ONLY; Exadata Database Storage Vault lifecycle state + LifecycleState *ExascaleDbStorageVaultLifecycleState + + // READ-ONLY; HTTPS link to OCI resources exposed to Azure Customer via Azure Interface. + OciURL *string + + // READ-ONLY; The OCID of the Exadata Database Storage Vault. + Ocid *string + + // READ-ONLY; Exadata Database Storage Vault provisioning state + ProvisioningState *AzureResourceProvisioningState + + // READ-ONLY; The number of Exadata VM clusters used the Exadata Database Storage Vault. + VMClusterCount *int32 +} + +// ExascaleDbStorageVaultTagsUpdate - The type used for updating tags in ExascaleDbStorageVault resources. +type ExascaleDbStorageVaultTagsUpdate struct { + // Resource tags. + Tags map[string]*string +} + +// FileSystemConfigurationDetails - File configuration options +type FileSystemConfigurationDetails struct { + // Size of the VM + FileSystemSizeGb *int32 + + // Mount path + MountPoint *string +} + +// FlexComponent Resource Definition +type FlexComponent struct { + // The resource-specific properties for this resource. + Properties *FlexComponentProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// FlexComponentListResult - The response of a FlexComponent list operation. +type FlexComponentListResult struct { + // REQUIRED; The FlexComponent items on this page + Value []*FlexComponent + + // The link to the next page of items + NextLink *string +} + +// FlexComponentProperties - FlexComponent resource model +type FlexComponentProperties struct { + // READ-ONLY; The maximum number of CPU cores that can be enabled on the DB Server for this Flex Component. + AvailableCoreCount *int32 + + // READ-ONLY; The maximum storage that can be enabled on the Storage Server for this Flex Component. + AvailableDbStorageInGbs *int32 + + // READ-ONLY; The maximum local storage that can be enabled on the DB Server for this Flex Component. + AvailableLocalStorageInGbs *int32 + + // READ-ONLY; The maximum memory size that can be enabled on the DB Server for this Flex Component. + AvailableMemoryInGbs *int32 + + // READ-ONLY; The compute model of the DB Server for this Flex Component. + ComputeModel *string + + // READ-ONLY; The description summary for this Flex Component. + DescriptionSummary *string + + // READ-ONLY; The hardware type of the DB (Compute) or Storage (Cell) Server for this Flex Component. + HardwareType *HardwareType + + // READ-ONLY; The minimum number of CPU cores that can be enabled on the DB Server for this Flex Component. + MinimumCoreCount *int32 + + // READ-ONLY; The runtime minimum number of CPU cores that can be enabled for this Flex Component. + RuntimeMinimumCoreCount *int32 + + // READ-ONLY; The name of the DB system shape for this Flex Component. + Shape *string +} + +// GenerateAutonomousDatabaseWalletDetails - Autonomous Database Generate Wallet resource model. +type GenerateAutonomousDatabaseWalletDetails struct { + // REQUIRED; The password to encrypt the keys inside the wallet + Password *string + + // The type of wallet to generate. + GenerateType *GenerateType + + // True when requesting regional connection strings in PDB connect info, applicable to cross-region DG only. + IsRegional *bool +} + +// GiMinorVersion - The Oracle Grid Infrastructure (GI) minor version resource definition. +type GiMinorVersion struct { + // The resource-specific properties for this resource. + Properties *GiMinorVersionProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// GiMinorVersionListResult - The response of a GiMinorVersion list operation. +type GiMinorVersionListResult struct { + // REQUIRED; The GiMinorVersion items on this page + Value []*GiMinorVersion + + // The link to the next page of items + NextLink *string +} + +// GiMinorVersionProperties - The Oracle Grid Infrastructure (GI) minor version properties +type GiMinorVersionProperties struct { + // REQUIRED; A valid Oracle Grid Infrastructure (GI) software version. + Version *string + + // Grid Infrastructure Image Id + GridImageOcid *string +} + +// GiVersion resource definition +type GiVersion struct { + // The resource-specific properties for this resource. + Properties *GiVersionProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// GiVersionListResult - The response of a GiVersion list operation. +type GiVersionListResult struct { + // REQUIRED; The GiVersion items on this page + Value []*GiVersion + + // The link to the next page of items + NextLink *string +} + +// GiVersionProperties - GiVersion resource model +type GiVersionProperties struct { + // REQUIRED; A valid Oracle Grid Infrastructure (GI) software version. + Version *string +} + +// LongTermBackUpScheduleDetails - Details for the long-term backup schedule. +type LongTermBackUpScheduleDetails struct { + // Indicates if the long-term backup schedule should be deleted. The default value is `FALSE`. + IsDisabled *bool + + // The frequency of the long-term backup schedule + RepeatCadence *RepeatCadenceType + + // Retention period, in days, for backups. + RetentionPeriodInDays *int32 + + // The timestamp for the long-term backup schedule. For a MONTHLY cadence, months having fewer days than the provided date + // will have the backup taken on the last day of that month. + TimeOfBackup *time.Time +} + +// MaintenanceWindow resource properties +type MaintenanceWindow struct { + // Determines the amount of time the system will wait before the start of each database server patching operation. Custom + // action timeout is in minutes and valid value is between 15 to 120 (inclusive). + CustomActionTimeoutInMins *int32 + + // Days during the week when maintenance should be performed. + DaysOfWeek []*DayOfWeek + + // The window of hours during the day when maintenance should be performed. The window is a 4 hour slot. Valid values are + // - 0 - represents time slot 0:00 - 3:59 UTC - 4 - represents time slot 4:00 - 7:59 UTC - 8 - represents time slot 8:00 - + // 11:59 UTC - 12 - represents time slot 12:00 - 15:59 UTC - 16 - represents time slot 16:00 - 19:59 UTC - 20 - represents + // time slot 20:00 - 23:59 UTC + HoursOfDay []*int32 + + // If true, enables the configuration of a custom action timeout (waiting period) between database server patching operations. + IsCustomActionTimeoutEnabled *bool + + // is Monthly Patching Enabled + IsMonthlyPatchingEnabled *bool + + // Lead time window allows user to set a lead time to prepare for a down time. The lead time is in weeks and valid value is + // between 1 to 4. + LeadTimeInWeeks *int32 + + // Months during the year when maintenance should be performed. + Months []*Month + + // Cloud Exadata infrastructure node patching method. + PatchingMode *PatchingMode + + // The maintenance window scheduling preference. + Preference *Preference + + // Weeks during the month when maintenance should be performed. Weeks start on the 1st, 8th, 15th, and 22nd days of the month, + // and have a duration of 7 days. Weeks start and end based on calendar dates, not days of the week. For example, to allow + // maintenance during the 2nd week of the month (from the 8th day to the 14th day of the month), use the value 2. Maintenance + // cannot be scheduled for the fifth week of months that contain more than 28 days. Note that this parameter works in conjunction + // with the daysOfWeek and hoursOfDay parameters to allow you to specify specific days of the week and hours that maintenance + // will be performed. + WeeksOfMonth []*int32 +} + +// Month resource properties +type Month struct { + // REQUIRED; Name of the month of the year. + Name *MonthName +} + +// NetworkAnchor - Network Anchor resource model. +type NetworkAnchor struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *NetworkAnchorProperties + + // Resource tags. + Tags map[string]*string + + // The availability zones. + Zones []*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// NetworkAnchorListResult - The response of a NetworkAnchor list operation. +type NetworkAnchorListResult struct { + // REQUIRED; The NetworkAnchor items on this page + Value []*NetworkAnchor + + // The link to the next page of items + NextLink *string +} + +// NetworkAnchorProperties - Network Anchor properties +type NetworkAnchorProperties struct { + // REQUIRED; Corresponding resource anchor Azure ID + ResourceAnchorID *string + + // REQUIRED; Client subnet + SubnetID *string + + // DNS forwarding rules + DNSForwardingRules []*DNSForwardingRule + + // Comma-separated list of CIDRs that are allowed to send requests to the DNS listening endpoint + DNSListeningEndpointAllowedCidrs *string + + // Indicates whether the Oracle DNS forwarding endpoint is enabled + IsOracleDNSForwardingEndpointEnabled *bool + + // Indicates whether the Oracle DNS listening endpoint is enabled + IsOracleDNSListeningEndpointEnabled *bool + + // Indicates whether DNS zone sync from OCI to Azure is enabled + IsOracleToAzureDNSZoneSyncEnabled *bool + + // OCI backup subnet cidr block. + OciBackupCidrBlock *string + + // OCI DNS label. This is optional if DNS config is provided. + OciVcnDNSLabel *string + + // READ-ONLY; Delegated Azure subnet cidr block. + CidrBlock *string + + // READ-ONLY; DNS forwarding endpoint IP address + DNSForwardingEndpointIPAddress *string + + // READ-ONLY; Deep link to OCI console DNS Forwarding endpoint NSG rules + DNSForwardingEndpointNsgRulesURL *string + + // READ-ONLY; Deep link to OCI console DNS Forwarding rules page + DNSForwardingRulesURL *string + + // READ-ONLY; DNS listening endpoint IP address + DNSListeningEndpointIPAddress *string + + // READ-ONLY; Deep link to OCI console DNS Listening endpoint NSG rules + DNSListeningEndpointNsgRulesURL *string + + // READ-ONLY; Oracle Cloud Infrastructure subnet OCID + OciSubnetID *string + + // READ-ONLY; Oracle Cloud Infrastructure VCN OCID + OciVcnID *string + + // READ-ONLY; NetworkAnchor provisioning state + ProvisioningState *AzureResourceProvisioningState + + // READ-ONLY; VNET for network connectivity + VnetID *string +} + +// NetworkAnchorUpdate - The type used for update operations of the NetworkAnchor. +type NetworkAnchorUpdate struct { + // The resource-specific properties for this resource. + Properties *NetworkAnchorUpdateProperties + + // Resource tags. + Tags map[string]*string + + // The availability zones. + Zones []*string +} + +// NetworkAnchorUpdateProperties - The updatable properties of the NetworkAnchor. +type NetworkAnchorUpdateProperties struct { + // Indicates whether the Oracle DNS forwarding endpoint is enabled + IsOracleDNSForwardingEndpointEnabled *bool + + // Indicates whether the Oracle DNS listening endpoint is enabled + IsOracleDNSListeningEndpointEnabled *bool + + // Indicates whether DNS zone sync from OCI to Azure is enabled + IsOracleToAzureDNSZoneSyncEnabled *bool + + // OCI backup subnet cidr block. + OciBackupCidrBlock *string +} + +// NsgCidr - A rule for allowing inbound (INGRESS) IP packets +type NsgCidr struct { + // REQUIRED; Conceptually, this is the range of IP addresses that a packet coming into the instance can come from. + Source *string + + // Destination port range to specify particular destination ports for TCP rules. + DestinationPortRange *PortRange +} + +// Operation - REST API Operation +// +// Details of a REST API operation, returned from the Resource Provider Operations API +type Operation struct { + // Localized display information for this particular operation. + Display *OperationDisplay + + // READ-ONLY; Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + ActionType *ActionType + + // READ-ONLY; Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure + // Resource Manager/control-plane operations. + IsDataAction *bool + + // READ-ONLY; The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + // "Microsoft.Compute/virtualMachines/capture/action" + Name *string + + // READ-ONLY; The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default + // value is "user,system" + Origin *Origin +} + +// OperationDisplay - Localized display information for an operation. +type OperationDisplay struct { + // READ-ONLY; The short, localized friendly description of the operation; suitable for tool tips and detailed views. + Description *string + + // READ-ONLY; The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual + // Machine", "Restart Virtual Machine". + Operation *string + + // READ-ONLY; The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft + // Compute". + Provider *string + + // READ-ONLY; The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job + // Schedule Collections". + Resource *string +} + +// OperationListResult - A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to +// get the next set of results. +type OperationListResult struct { + // REQUIRED; The Operation items on this page + Value []*Operation + + // The link to the next page of items + NextLink *string +} + +// OracleSubscription resource definition +type OracleSubscription struct { + // Details of the resource plan. + Plan *Plan + + // The resource-specific properties for this resource. + Properties *OracleSubscriptionProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// OracleSubscriptionListResult - The response of a OracleSubscription list operation. +type OracleSubscriptionListResult struct { + // REQUIRED; The OracleSubscription items on this page + Value []*OracleSubscription + + // The link to the next page of items + NextLink *string +} + +// OracleSubscriptionProperties - Oracle Subscription resource model +type OracleSubscriptionProperties struct { + // Intent for the update operation + Intent *Intent + + // Product code for the term unit + ProductCode *string + + // Term Unit. P1Y, P3Y, etc, see Durations https://en.wikipedia.org/wiki/ISO_8601 + TermUnit *string + + // READ-ONLY; State of the add Azure subscription operation on Oracle subscription + AddSubscriptionOperationState *AddSubscriptionOperationState + + // READ-ONLY; Azure subscriptions to be added + AzureSubscriptionIDs []*string + + // READ-ONLY; Cloud Account Id + CloudAccountID *string + + // READ-ONLY; Cloud Account provisioning state. + CloudAccountState *CloudAccountProvisioningState + + // READ-ONLY; Status details of the last operation on Oracle subscription + LastOperationStatusDetail *string + + // READ-ONLY; OracleSubscriptionProvisioningState provisioning state + ProvisioningState *OracleSubscriptionProvisioningState + + // READ-ONLY; SAAS subscription ID generated by Marketplace + SaasSubscriptionID *string +} + +// OracleSubscriptionUpdate - The type used for update operations of the OracleSubscription. +type OracleSubscriptionUpdate struct { + // Details of the resource plan. + Plan *PlanUpdate + + // The resource-specific properties for this resource. + Properties *OracleSubscriptionUpdateProperties +} + +// OracleSubscriptionUpdateProperties - The updatable properties of the OracleSubscription. +type OracleSubscriptionUpdateProperties struct { + // Intent for the update operation + Intent *Intent + + // Product code for the term unit + ProductCode *string +} + +// PeerDbDetails - PeerDb Details +type PeerDbDetails struct { + // The Azure resource ID of the Disaster Recovery peer database, which is located in a different region from the current peer + // database. + PeerDbID *string + + // The location of the Disaster Recovery peer database. + PeerDbLocation *string + + // Ocid of the Disaster Recovery peer database, which is located in a different region from the current peer database. + PeerDbOcid *string +} + +// Plan for the resource. +type Plan struct { + // REQUIRED; A user defined name of the 3rd Party Artifact that is being procured. + Name *string + + // REQUIRED; The 3rd Party artifact that is being procured. E.g. NewRelic. Product maps to the OfferID specified for the artifact + // at the time of Data Market onboarding. + Product *string + + // REQUIRED; The publisher of the 3rd Party Artifact that is being bought. E.g. NewRelic + Publisher *string + + // A publisher provided promotion code as provisioned in Data Market for the said product/artifact. + PromotionCode *string + + // The version of the desired product/artifact. + Version *string +} + +// PlanUpdate - ResourcePlanTypeUpdate model definition +type PlanUpdate struct { + // A user defined name of the 3rd Party Artifact that is being procured. + Name *string + + // The 3rd Party artifact that is being procured. E.g. NewRelic. Product maps to the OfferID specified for the artifact at + // the time of Data Market onboarding. + Product *string + + // A publisher provided promotion code as provisioned in Data Market for the said product/artifact. + PromotionCode *string + + // The publisher of the 3rd Party Artifact that is being bought. E.g. NewRelic + Publisher *string + + // The version of the desired product/artifact. + Version *string +} + +// PortRange - Port Range to specify particular destination ports for TCP rules. +type PortRange struct { + // REQUIRED; The maximum port number, which must not be less than the minimum port number. To specify a single port number, + // set both the min and max to the same value. + Max *int32 + + // REQUIRED; The minimum port number, which must not be greater than the maximum port number. + Min *int32 +} + +// PrivateIPAddressProperties - PrivateIpAddress resource properties +type PrivateIPAddressProperties struct { + // REQUIRED; PrivateIpAddresses displayName + DisplayName *string + + // REQUIRED; PrivateIpAddresses hostnameLabel + HostnameLabel *string + + // REQUIRED; PrivateIpAddresses ipAddress + IPAddress *string + + // REQUIRED; PrivateIpAddresses Id + Ocid *string + + // REQUIRED; PrivateIpAddresses subnetId + SubnetID *string +} + +// PrivateIPAddressesFilter - Private Ip Addresses filter +type PrivateIPAddressesFilter struct { + // REQUIRED; Subnet OCID + SubnetID *string + + // REQUIRED; VCN OCID + VnicID *string +} + +// ProfileType - The connection string profile to allow clients to group, filter and select connection string values based +// on structured metadata. +type ProfileType struct { + // REQUIRED; A user-friendly name for the connection. + DisplayName *string + + // REQUIRED; Host format used in connection string. + HostFormat *HostFormatType + + // REQUIRED; Protocol used by the connection. + Protocol *ProtocolType + + // REQUIRED; Specifies whether the listener performs a direct hand-off of the session, or redirects the session. + SessionMode *SessionModeType + + // REQUIRED; Specifies whether the connection string is using the long (LONG), Easy Connect (EZCONNECT), or Easy Connect Plus + // (EZCONNECTPLUS) format. + SyntaxFormat *SyntaxFormatType + + // REQUIRED; Connection string value. + Value *string + + // Consumer group used by the connection. + ConsumerGroup *ConsumerGroup + + // True for a regional connection string, applicable to cross-region DG only. + IsRegional *bool + + // Specifies whether the TLS handshake is using one-way (SERVER) or mutual (MUTUAL) authentication. + TLSAuthentication *TLSAuthenticationType +} + +// RemoveVirtualMachineFromExadbVMClusterDetails - Details of removing Virtual Machines from the Exadata VM cluster on Exascale +// Infrastructure. Applies to Exadata Database Service on Exascale Infrastructure only. +type RemoveVirtualMachineFromExadbVMClusterDetails struct { + // REQUIRED; The list of ExaCS DB nodes for the Exadata VM cluster on Exascale Infrastructure to be removed. + DbNodes []*DbNodeDetails +} + +// ResourceAnchor - Resource Anchor model. +type ResourceAnchor struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *ResourceAnchorProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ResourceAnchorListResult - The response of a ResourceAnchor list operation. +type ResourceAnchorListResult struct { + // REQUIRED; The ResourceAnchor items on this page + Value []*ResourceAnchor + + // The link to the next page of items + NextLink *string +} + +// ResourceAnchorProperties - Resource Anchor properties. +type ResourceAnchorProperties struct { + // READ-ONLY; Oracle Cloud Infrastructure compartment Id (ocid) which was created or linked by customer with resource anchor. + // This compartmentId is different from where resource Anchor lives + LinkedCompartmentID *string + + // READ-ONLY; ResourceAnchor provisioning state + ProvisioningState *AzureResourceProvisioningState +} + +// ResourceAnchorUpdate - The type used for update operations of the ResourceAnchor. +type ResourceAnchorUpdate struct { + // Resource tags. + Tags map[string]*string +} + +// RestoreAutonomousDatabaseDetails - Details to restore an Oracle Autonomous Database. +type RestoreAutonomousDatabaseDetails struct { + // REQUIRED; The time to restore the database to. + Timestamp *time.Time +} + +// SaasSubscriptionDetails - SaaS Subscription Details model +type SaasSubscriptionDetails struct { + // READ-ONLY; Purchased SaaS subscription ID + ID *string + + // READ-ONLY; AutoRenew flag + IsAutoRenew *bool + + // READ-ONLY; FreeTrial flag + IsFreeTrial *bool + + // READ-ONLY; Purchased offer ID + OfferID *string + + // READ-ONLY; Purchased offer's plan ID + PlanID *string + + // READ-ONLY; Publisher ID + PublisherID *string + + // READ-ONLY; Purchaser Email ID + PurchaserEmailID *string + + // READ-ONLY; Purchaser Tenant ID + PurchaserTenantID *string + + // READ-ONLY; Indicates the status of the Subscription. + SaasSubscriptionStatus *string + + // READ-ONLY; SaaS subscription name + SubscriptionName *string + + // READ-ONLY; Purchase Term Unit + TermUnit *string + + // READ-ONLY; Creation Date and Time + TimeCreated *time.Time +} + +// ScheduledOperationsType - The list of scheduled operations. +type ScheduledOperationsType struct { + // REQUIRED; Day of week + DayOfWeek *DayOfWeek + + // auto start time. value must be of ISO-8601 format HH:mm + ScheduledStartTime *string + + // auto stop time. value must be of ISO-8601 format HH:mm + ScheduledStopTime *string +} + +// ScheduledOperationsTypeUpdate - The list of scheduled operations. +type ScheduledOperationsTypeUpdate struct { + // Day of week + DayOfWeek *DayOfWeekUpdate + + // auto start time. value must be of ISO-8601 format HH:mm + ScheduledStartTime *string + + // auto stop time. value must be of ISO-8601 format HH:mm + ScheduledStopTime *string +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time + + // The identity that created the resource. + CreatedBy *string + + // The type of identity that created the resource. + CreatedByType *CreatedByType + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time + + // The identity that last modified the resource. + LastModifiedBy *string + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType +} + +// SystemVersion resource Definition +type SystemVersion struct { + // The resource-specific properties for this resource. + Properties *SystemVersionProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// SystemVersionListResult - The response of a SystemVersion list operation. +type SystemVersionListResult struct { + // REQUIRED; The SystemVersion items on this page + Value []*SystemVersion + + // The link to the next page of items + NextLink *string +} + +// SystemVersionProperties - System Version Resource model +type SystemVersionProperties struct { + // REQUIRED; A valid Oracle System Version + SystemVersion *string +} + +// VirtualNetworkAddress - Virtual IP resource belonging to a vm cluster resource. +type VirtualNetworkAddress struct { + // The resource-specific properties for this resource. + Properties *VirtualNetworkAddressProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// VirtualNetworkAddressListResult - The response of a VirtualNetworkAddress list operation. +type VirtualNetworkAddressListResult struct { + // REQUIRED; The VirtualNetworkAddress items on this page + Value []*VirtualNetworkAddress + + // The link to the next page of items + NextLink *string +} + +// VirtualNetworkAddressProperties - virtualNetworkAddress resource properties +type VirtualNetworkAddressProperties struct { + // Virtual network Address address. + IPAddress *string + + // Virtual Machine OCID. + VMOcid *string + + // READ-ONLY; Virtual network address fully qualified domain name. + Domain *string + + // READ-ONLY; Additional information about the current lifecycle state of the application virtual IP (VIP) address. + LifecycleDetails *string + + // READ-ONLY; virtual network address lifecycle state. + LifecycleState *VirtualNetworkAddressLifecycleState + + // READ-ONLY; Application VIP OCID. + Ocid *string + + // READ-ONLY; Azure resource provisioning state. + ProvisioningState *AzureResourceProvisioningState + + // READ-ONLY; The date and time when the create operation for the application virtual IP (VIP) address completed. + TimeAssigned *time.Time +} diff --git a/test/local/armoracledatabase/zz_models_serde.go b/test/local/armoracledatabase/zz_models_serde.go new file mode 100644 index 000000000000..1d6348f854d2 --- /dev/null +++ b/test/local/armoracledatabase/zz_models_serde.go @@ -0,0 +1,8441 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type ActivationLinks. +func (a ActivationLinks) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "existingCloudAccountActivationLink", a.ExistingCloudAccountActivationLink) + populate(objectMap, "newCloudAccountActivationLink", a.NewCloudAccountActivationLink) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ActivationLinks. +func (a *ActivationLinks) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "existingCloudAccountActivationLink": + err = unpopulate(val, "ExistingCloudAccountActivationLink", &a.ExistingCloudAccountActivationLink) + delete(rawMsg, key) + case "newCloudAccountActivationLink": + err = unpopulate(val, "NewCloudAccountActivationLink", &a.NewCloudAccountActivationLink) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AddRemoveDbNode. +func (a AddRemoveDbNode) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dbServers", a.DbServers) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AddRemoveDbNode. +func (a *AddRemoveDbNode) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "dbServers": + err = unpopulate(val, "DbServers", &a.DbServers) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AllConnectionStringType. +func (a AllConnectionStringType) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "high", a.High) + populate(objectMap, "low", a.Low) + populate(objectMap, "medium", a.Medium) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AllConnectionStringType. +func (a *AllConnectionStringType) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "high": + err = unpopulate(val, "High", &a.High) + delete(rawMsg, key) + case "low": + err = unpopulate(val, "Low", &a.Low) + delete(rawMsg, key) + case "medium": + err = unpopulate(val, "Medium", &a.Medium) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ApexDetailsType. +func (a ApexDetailsType) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "apexVersion", a.ApexVersion) + populate(objectMap, "ordsVersion", a.OrdsVersion) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ApexDetailsType. +func (a *ApexDetailsType) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "apexVersion": + err = unpopulate(val, "ApexVersion", &a.ApexVersion) + delete(rawMsg, key) + case "ordsVersion": + err = unpopulate(val, "OrdsVersion", &a.OrdsVersion) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutonomousDatabase. +func (a AutonomousDatabase) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "location", a.Location) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "tags", a.Tags) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutonomousDatabase. +func (a *AutonomousDatabase) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &a.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "properties": + a.Properties, err = unmarshalAutonomousDatabaseBasePropertiesClassification(val) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &a.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &a.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutonomousDatabaseBackup. +func (a AutonomousDatabaseBackup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutonomousDatabaseBackup. +func (a *AutonomousDatabaseBackup) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &a.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutonomousDatabaseBackupListResult. +func (a AutonomousDatabaseBackupListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutonomousDatabaseBackupListResult. +func (a *AutonomousDatabaseBackupListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &a.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutonomousDatabaseBackupProperties. +func (a AutonomousDatabaseBackupProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "autonomousDatabaseOcid", a.AutonomousDatabaseOcid) + populate(objectMap, "backupType", a.BackupType) + populate(objectMap, "databaseSizeInTbs", a.DatabaseSizeInTbs) + populate(objectMap, "dbVersion", a.DbVersion) + populate(objectMap, "displayName", a.DisplayName) + populate(objectMap, "isAutomatic", a.IsAutomatic) + populate(objectMap, "isRestorable", a.IsRestorable) + populate(objectMap, "lifecycleDetails", a.LifecycleDetails) + populate(objectMap, "lifecycleState", a.LifecycleState) + populate(objectMap, "ocid", a.Ocid) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "retentionPeriodInDays", a.RetentionPeriodInDays) + populate(objectMap, "sizeInTbs", a.SizeInTbs) + populateTime[datetime.RFC3339](objectMap, "timeAvailableTil", a.TimeAvailableTil) + populate(objectMap, "timeEnded", a.TimeEnded) + populate(objectMap, "timeStarted", a.TimeStarted) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutonomousDatabaseBackupProperties. +func (a *AutonomousDatabaseBackupProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "autonomousDatabaseOcid": + err = unpopulate(val, "AutonomousDatabaseOcid", &a.AutonomousDatabaseOcid) + delete(rawMsg, key) + case "backupType": + err = unpopulate(val, "BackupType", &a.BackupType) + delete(rawMsg, key) + case "databaseSizeInTbs": + err = unpopulate(val, "DatabaseSizeInTbs", &a.DatabaseSizeInTbs) + delete(rawMsg, key) + case "dbVersion": + err = unpopulate(val, "DbVersion", &a.DbVersion) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &a.DisplayName) + delete(rawMsg, key) + case "isAutomatic": + err = unpopulate(val, "IsAutomatic", &a.IsAutomatic) + delete(rawMsg, key) + case "isRestorable": + err = unpopulate(val, "IsRestorable", &a.IsRestorable) + delete(rawMsg, key) + case "lifecycleDetails": + err = unpopulate(val, "LifecycleDetails", &a.LifecycleDetails) + delete(rawMsg, key) + case "lifecycleState": + err = unpopulate(val, "LifecycleState", &a.LifecycleState) + delete(rawMsg, key) + case "ocid": + err = unpopulate(val, "Ocid", &a.Ocid) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "retentionPeriodInDays": + err = unpopulate(val, "RetentionPeriodInDays", &a.RetentionPeriodInDays) + delete(rawMsg, key) + case "sizeInTbs": + err = unpopulate(val, "SizeInTbs", &a.SizeInTbs) + delete(rawMsg, key) + case "timeAvailableTil": + err = unpopulateTime[datetime.RFC3339](val, "TimeAvailableTil", &a.TimeAvailableTil) + delete(rawMsg, key) + case "timeEnded": + err = unpopulate(val, "TimeEnded", &a.TimeEnded) + delete(rawMsg, key) + case "timeStarted": + err = unpopulate(val, "TimeStarted", &a.TimeStarted) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutonomousDatabaseBackupUpdate. +func (a AutonomousDatabaseBackupUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", a.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutonomousDatabaseBackupUpdate. +func (a *AutonomousDatabaseBackupUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutonomousDatabaseBackupUpdateProperties. +func (a AutonomousDatabaseBackupUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "retentionPeriodInDays", a.RetentionPeriodInDays) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutonomousDatabaseBackupUpdateProperties. +func (a *AutonomousDatabaseBackupUpdateProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "retentionPeriodInDays": + err = unpopulate(val, "RetentionPeriodInDays", &a.RetentionPeriodInDays) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutonomousDatabaseBaseProperties. +func (a AutonomousDatabaseBaseProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actualUsedDataStorageSizeInTbs", a.ActualUsedDataStorageSizeInTbs) + populate(objectMap, "adminPassword", a.AdminPassword) + populate(objectMap, "allocatedStorageSizeInTbs", a.AllocatedStorageSizeInTbs) + populate(objectMap, "apexDetails", a.ApexDetails) + populate(objectMap, "autonomousDatabaseId", a.AutonomousDatabaseID) + populate(objectMap, "autonomousMaintenanceScheduleType", a.AutonomousMaintenanceScheduleType) + populate(objectMap, "availableUpgradeVersions", a.AvailableUpgradeVersions) + populate(objectMap, "backupRetentionPeriodInDays", a.BackupRetentionPeriodInDays) + populate(objectMap, "cpuCoreCount", a.CPUCoreCount) + populate(objectMap, "characterSet", a.CharacterSet) + populate(objectMap, "computeCount", a.ComputeCount) + populate(objectMap, "computeModel", a.ComputeModel) + populate(objectMap, "connectionStrings", a.ConnectionStrings) + populate(objectMap, "connectionUrls", a.ConnectionUrls) + populate(objectMap, "customerContacts", a.CustomerContacts) + populate(objectMap, "dataBaseType", a.DataBaseType) + populate(objectMap, "dataSafeStatus", a.DataSafeStatus) + populate(objectMap, "dataStorageSizeInGbs", a.DataStorageSizeInGbs) + populate(objectMap, "dataStorageSizeInTbs", a.DataStorageSizeInTbs) + populate(objectMap, "databaseEdition", a.DatabaseEdition) + populate(objectMap, "dbVersion", a.DbVersion) + populate(objectMap, "dbWorkload", a.DbWorkload) + populate(objectMap, "displayName", a.DisplayName) + populate(objectMap, "failedDataRecoveryInSeconds", a.FailedDataRecoveryInSeconds) + populate(objectMap, "inMemoryAreaInGbs", a.InMemoryAreaInGbs) + populate(objectMap, "isAutoScalingEnabled", a.IsAutoScalingEnabled) + populate(objectMap, "isAutoScalingForStorageEnabled", a.IsAutoScalingForStorageEnabled) + populate(objectMap, "isLocalDataGuardEnabled", a.IsLocalDataGuardEnabled) + populate(objectMap, "isMtlsConnectionRequired", a.IsMtlsConnectionRequired) + populate(objectMap, "isPreview", a.IsPreview) + populate(objectMap, "isPreviewVersionWithServiceTermsAccepted", a.IsPreviewVersionWithServiceTermsAccepted) + populate(objectMap, "isRemoteDataGuardEnabled", a.IsRemoteDataGuardEnabled) + populate(objectMap, "licenseModel", a.LicenseModel) + populate(objectMap, "lifecycleDetails", a.LifecycleDetails) + populate(objectMap, "lifecycleState", a.LifecycleState) + populate(objectMap, "localAdgAutoFailoverMaxDataLossLimit", a.LocalAdgAutoFailoverMaxDataLossLimit) + populate(objectMap, "localDisasterRecoveryType", a.LocalDisasterRecoveryType) + populate(objectMap, "localStandbyDb", a.LocalStandbyDb) + populate(objectMap, "longTermBackupSchedule", a.LongTermBackupSchedule) + populate(objectMap, "memoryPerOracleComputeUnitInGbs", a.MemoryPerOracleComputeUnitInGbs) + populate(objectMap, "ncharacterSet", a.NcharacterSet) + populateTime[datetime.RFC3339](objectMap, "nextLongTermBackupTimeStamp", a.NextLongTermBackupTimeStamp) + populate(objectMap, "ociUrl", a.OciURL) + populate(objectMap, "ocid", a.Ocid) + populate(objectMap, "openMode", a.OpenMode) + populate(objectMap, "operationsInsightsStatus", a.OperationsInsightsStatus) + populate(objectMap, "peerDbId", a.PeerDbID) + populate(objectMap, "peerDbIds", a.PeerDbIDs) + populate(objectMap, "permissionLevel", a.PermissionLevel) + populate(objectMap, "privateEndpoint", a.PrivateEndpoint) + populate(objectMap, "privateEndpointIp", a.PrivateEndpointIP) + populate(objectMap, "privateEndpointLabel", a.PrivateEndpointLabel) + populate(objectMap, "provisionableCpus", a.ProvisionableCpus) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "remoteDisasterRecoveryConfiguration", a.RemoteDisasterRecoveryConfiguration) + populate(objectMap, "role", a.Role) + populate(objectMap, "sqlWebDeveloperUrl", a.SQLWebDeveloperURL) + populate(objectMap, "scheduledOperationsList", a.ScheduledOperationsList) + populate(objectMap, "serviceConsoleUrl", a.ServiceConsoleURL) + populate(objectMap, "subnetId", a.SubnetID) + populate(objectMap, "supportedRegionsToCloneTo", a.SupportedRegionsToCloneTo) + populateTime[datetime.RFC3339](objectMap, "timeCreated", a.TimeCreated) + populate(objectMap, "timeDataGuardRoleChanged", a.TimeDataGuardRoleChanged) + populate(objectMap, "timeDeletionOfFreeAutonomousDatabase", a.TimeDeletionOfFreeAutonomousDatabase) + populateTime[datetime.RFC3339](objectMap, "timeDisasterRecoveryRoleChanged", a.TimeDisasterRecoveryRoleChanged) + populate(objectMap, "timeLocalDataGuardEnabled", a.TimeLocalDataGuardEnabled) + populateTime[datetime.RFC3339](objectMap, "timeMaintenanceBegin", a.TimeMaintenanceBegin) + populateTime[datetime.RFC3339](objectMap, "timeMaintenanceEnd", a.TimeMaintenanceEnd) + populate(objectMap, "timeOfLastFailover", a.TimeOfLastFailover) + populate(objectMap, "timeOfLastRefresh", a.TimeOfLastRefresh) + populate(objectMap, "timeOfLastRefreshPoint", a.TimeOfLastRefreshPoint) + populate(objectMap, "timeOfLastSwitchover", a.TimeOfLastSwitchover) + populate(objectMap, "timeReclamationOfFreeAutonomousDatabase", a.TimeReclamationOfFreeAutonomousDatabase) + populate(objectMap, "usedDataStorageSizeInGbs", a.UsedDataStorageSizeInGbs) + populate(objectMap, "usedDataStorageSizeInTbs", a.UsedDataStorageSizeInTbs) + populate(objectMap, "vnetId", a.VnetID) + populate(objectMap, "whitelistedIps", a.WhitelistedIPs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutonomousDatabaseBaseProperties. +func (a *AutonomousDatabaseBaseProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actualUsedDataStorageSizeInTbs": + err = unpopulate(val, "ActualUsedDataStorageSizeInTbs", &a.ActualUsedDataStorageSizeInTbs) + delete(rawMsg, key) + case "adminPassword": + err = unpopulate(val, "AdminPassword", &a.AdminPassword) + delete(rawMsg, key) + case "allocatedStorageSizeInTbs": + err = unpopulate(val, "AllocatedStorageSizeInTbs", &a.AllocatedStorageSizeInTbs) + delete(rawMsg, key) + case "apexDetails": + err = unpopulate(val, "ApexDetails", &a.ApexDetails) + delete(rawMsg, key) + case "autonomousDatabaseId": + err = unpopulate(val, "AutonomousDatabaseID", &a.AutonomousDatabaseID) + delete(rawMsg, key) + case "autonomousMaintenanceScheduleType": + err = unpopulate(val, "AutonomousMaintenanceScheduleType", &a.AutonomousMaintenanceScheduleType) + delete(rawMsg, key) + case "availableUpgradeVersions": + err = unpopulate(val, "AvailableUpgradeVersions", &a.AvailableUpgradeVersions) + delete(rawMsg, key) + case "backupRetentionPeriodInDays": + err = unpopulate(val, "BackupRetentionPeriodInDays", &a.BackupRetentionPeriodInDays) + delete(rawMsg, key) + case "cpuCoreCount": + err = unpopulate(val, "CPUCoreCount", &a.CPUCoreCount) + delete(rawMsg, key) + case "characterSet": + err = unpopulate(val, "CharacterSet", &a.CharacterSet) + delete(rawMsg, key) + case "computeCount": + err = unpopulate(val, "ComputeCount", &a.ComputeCount) + delete(rawMsg, key) + case "computeModel": + err = unpopulate(val, "ComputeModel", &a.ComputeModel) + delete(rawMsg, key) + case "connectionStrings": + err = unpopulate(val, "ConnectionStrings", &a.ConnectionStrings) + delete(rawMsg, key) + case "connectionUrls": + err = unpopulate(val, "ConnectionUrls", &a.ConnectionUrls) + delete(rawMsg, key) + case "customerContacts": + err = unpopulate(val, "CustomerContacts", &a.CustomerContacts) + delete(rawMsg, key) + case "dataBaseType": + err = unpopulate(val, "DataBaseType", &a.DataBaseType) + delete(rawMsg, key) + case "dataSafeStatus": + err = unpopulate(val, "DataSafeStatus", &a.DataSafeStatus) + delete(rawMsg, key) + case "dataStorageSizeInGbs": + err = unpopulate(val, "DataStorageSizeInGbs", &a.DataStorageSizeInGbs) + delete(rawMsg, key) + case "dataStorageSizeInTbs": + err = unpopulate(val, "DataStorageSizeInTbs", &a.DataStorageSizeInTbs) + delete(rawMsg, key) + case "databaseEdition": + err = unpopulate(val, "DatabaseEdition", &a.DatabaseEdition) + delete(rawMsg, key) + case "dbVersion": + err = unpopulate(val, "DbVersion", &a.DbVersion) + delete(rawMsg, key) + case "dbWorkload": + err = unpopulate(val, "DbWorkload", &a.DbWorkload) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &a.DisplayName) + delete(rawMsg, key) + case "failedDataRecoveryInSeconds": + err = unpopulate(val, "FailedDataRecoveryInSeconds", &a.FailedDataRecoveryInSeconds) + delete(rawMsg, key) + case "inMemoryAreaInGbs": + err = unpopulate(val, "InMemoryAreaInGbs", &a.InMemoryAreaInGbs) + delete(rawMsg, key) + case "isAutoScalingEnabled": + err = unpopulate(val, "IsAutoScalingEnabled", &a.IsAutoScalingEnabled) + delete(rawMsg, key) + case "isAutoScalingForStorageEnabled": + err = unpopulate(val, "IsAutoScalingForStorageEnabled", &a.IsAutoScalingForStorageEnabled) + delete(rawMsg, key) + case "isLocalDataGuardEnabled": + err = unpopulate(val, "IsLocalDataGuardEnabled", &a.IsLocalDataGuardEnabled) + delete(rawMsg, key) + case "isMtlsConnectionRequired": + err = unpopulate(val, "IsMtlsConnectionRequired", &a.IsMtlsConnectionRequired) + delete(rawMsg, key) + case "isPreview": + err = unpopulate(val, "IsPreview", &a.IsPreview) + delete(rawMsg, key) + case "isPreviewVersionWithServiceTermsAccepted": + err = unpopulate(val, "IsPreviewVersionWithServiceTermsAccepted", &a.IsPreviewVersionWithServiceTermsAccepted) + delete(rawMsg, key) + case "isRemoteDataGuardEnabled": + err = unpopulate(val, "IsRemoteDataGuardEnabled", &a.IsRemoteDataGuardEnabled) + delete(rawMsg, key) + case "licenseModel": + err = unpopulate(val, "LicenseModel", &a.LicenseModel) + delete(rawMsg, key) + case "lifecycleDetails": + err = unpopulate(val, "LifecycleDetails", &a.LifecycleDetails) + delete(rawMsg, key) + case "lifecycleState": + err = unpopulate(val, "LifecycleState", &a.LifecycleState) + delete(rawMsg, key) + case "localAdgAutoFailoverMaxDataLossLimit": + err = unpopulate(val, "LocalAdgAutoFailoverMaxDataLossLimit", &a.LocalAdgAutoFailoverMaxDataLossLimit) + delete(rawMsg, key) + case "localDisasterRecoveryType": + err = unpopulate(val, "LocalDisasterRecoveryType", &a.LocalDisasterRecoveryType) + delete(rawMsg, key) + case "localStandbyDb": + err = unpopulate(val, "LocalStandbyDb", &a.LocalStandbyDb) + delete(rawMsg, key) + case "longTermBackupSchedule": + err = unpopulate(val, "LongTermBackupSchedule", &a.LongTermBackupSchedule) + delete(rawMsg, key) + case "memoryPerOracleComputeUnitInGbs": + err = unpopulate(val, "MemoryPerOracleComputeUnitInGbs", &a.MemoryPerOracleComputeUnitInGbs) + delete(rawMsg, key) + case "ncharacterSet": + err = unpopulate(val, "NcharacterSet", &a.NcharacterSet) + delete(rawMsg, key) + case "nextLongTermBackupTimeStamp": + err = unpopulateTime[datetime.RFC3339](val, "NextLongTermBackupTimeStamp", &a.NextLongTermBackupTimeStamp) + delete(rawMsg, key) + case "ociUrl": + err = unpopulate(val, "OciURL", &a.OciURL) + delete(rawMsg, key) + case "ocid": + err = unpopulate(val, "Ocid", &a.Ocid) + delete(rawMsg, key) + case "openMode": + err = unpopulate(val, "OpenMode", &a.OpenMode) + delete(rawMsg, key) + case "operationsInsightsStatus": + err = unpopulate(val, "OperationsInsightsStatus", &a.OperationsInsightsStatus) + delete(rawMsg, key) + case "peerDbId": + err = unpopulate(val, "PeerDbID", &a.PeerDbID) + delete(rawMsg, key) + case "peerDbIds": + err = unpopulate(val, "PeerDbIDs", &a.PeerDbIDs) + delete(rawMsg, key) + case "permissionLevel": + err = unpopulate(val, "PermissionLevel", &a.PermissionLevel) + delete(rawMsg, key) + case "privateEndpoint": + err = unpopulate(val, "PrivateEndpoint", &a.PrivateEndpoint) + delete(rawMsg, key) + case "privateEndpointIp": + err = unpopulate(val, "PrivateEndpointIP", &a.PrivateEndpointIP) + delete(rawMsg, key) + case "privateEndpointLabel": + err = unpopulate(val, "PrivateEndpointLabel", &a.PrivateEndpointLabel) + delete(rawMsg, key) + case "provisionableCpus": + err = unpopulate(val, "ProvisionableCpus", &a.ProvisionableCpus) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "remoteDisasterRecoveryConfiguration": + err = unpopulate(val, "RemoteDisasterRecoveryConfiguration", &a.RemoteDisasterRecoveryConfiguration) + delete(rawMsg, key) + case "role": + err = unpopulate(val, "Role", &a.Role) + delete(rawMsg, key) + case "sqlWebDeveloperUrl": + err = unpopulate(val, "SQLWebDeveloperURL", &a.SQLWebDeveloperURL) + delete(rawMsg, key) + case "scheduledOperationsList": + err = unpopulate(val, "ScheduledOperationsList", &a.ScheduledOperationsList) + delete(rawMsg, key) + case "serviceConsoleUrl": + err = unpopulate(val, "ServiceConsoleURL", &a.ServiceConsoleURL) + delete(rawMsg, key) + case "subnetId": + err = unpopulate(val, "SubnetID", &a.SubnetID) + delete(rawMsg, key) + case "supportedRegionsToCloneTo": + err = unpopulate(val, "SupportedRegionsToCloneTo", &a.SupportedRegionsToCloneTo) + delete(rawMsg, key) + case "timeCreated": + err = unpopulateTime[datetime.RFC3339](val, "TimeCreated", &a.TimeCreated) + delete(rawMsg, key) + case "timeDataGuardRoleChanged": + err = unpopulate(val, "TimeDataGuardRoleChanged", &a.TimeDataGuardRoleChanged) + delete(rawMsg, key) + case "timeDeletionOfFreeAutonomousDatabase": + err = unpopulate(val, "TimeDeletionOfFreeAutonomousDatabase", &a.TimeDeletionOfFreeAutonomousDatabase) + delete(rawMsg, key) + case "timeDisasterRecoveryRoleChanged": + err = unpopulateTime[datetime.RFC3339](val, "TimeDisasterRecoveryRoleChanged", &a.TimeDisasterRecoveryRoleChanged) + delete(rawMsg, key) + case "timeLocalDataGuardEnabled": + err = unpopulate(val, "TimeLocalDataGuardEnabled", &a.TimeLocalDataGuardEnabled) + delete(rawMsg, key) + case "timeMaintenanceBegin": + err = unpopulateTime[datetime.RFC3339](val, "TimeMaintenanceBegin", &a.TimeMaintenanceBegin) + delete(rawMsg, key) + case "timeMaintenanceEnd": + err = unpopulateTime[datetime.RFC3339](val, "TimeMaintenanceEnd", &a.TimeMaintenanceEnd) + delete(rawMsg, key) + case "timeOfLastFailover": + err = unpopulate(val, "TimeOfLastFailover", &a.TimeOfLastFailover) + delete(rawMsg, key) + case "timeOfLastRefresh": + err = unpopulate(val, "TimeOfLastRefresh", &a.TimeOfLastRefresh) + delete(rawMsg, key) + case "timeOfLastRefreshPoint": + err = unpopulate(val, "TimeOfLastRefreshPoint", &a.TimeOfLastRefreshPoint) + delete(rawMsg, key) + case "timeOfLastSwitchover": + err = unpopulate(val, "TimeOfLastSwitchover", &a.TimeOfLastSwitchover) + delete(rawMsg, key) + case "timeReclamationOfFreeAutonomousDatabase": + err = unpopulate(val, "TimeReclamationOfFreeAutonomousDatabase", &a.TimeReclamationOfFreeAutonomousDatabase) + delete(rawMsg, key) + case "usedDataStorageSizeInGbs": + err = unpopulate(val, "UsedDataStorageSizeInGbs", &a.UsedDataStorageSizeInGbs) + delete(rawMsg, key) + case "usedDataStorageSizeInTbs": + err = unpopulate(val, "UsedDataStorageSizeInTbs", &a.UsedDataStorageSizeInTbs) + delete(rawMsg, key) + case "vnetId": + err = unpopulate(val, "VnetID", &a.VnetID) + delete(rawMsg, key) + case "whitelistedIps": + err = unpopulate(val, "WhitelistedIPs", &a.WhitelistedIPs) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutonomousDatabaseCharacterSet. +func (a AutonomousDatabaseCharacterSet) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutonomousDatabaseCharacterSet. +func (a *AutonomousDatabaseCharacterSet) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &a.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutonomousDatabaseCharacterSetListResult. +func (a AutonomousDatabaseCharacterSetListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutonomousDatabaseCharacterSetListResult. +func (a *AutonomousDatabaseCharacterSetListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &a.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutonomousDatabaseCharacterSetProperties. +func (a AutonomousDatabaseCharacterSetProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "characterSet", a.CharacterSet) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutonomousDatabaseCharacterSetProperties. +func (a *AutonomousDatabaseCharacterSetProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "characterSet": + err = unpopulate(val, "CharacterSet", &a.CharacterSet) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutonomousDatabaseCloneProperties. +func (a AutonomousDatabaseCloneProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actualUsedDataStorageSizeInTbs", a.ActualUsedDataStorageSizeInTbs) + populate(objectMap, "adminPassword", a.AdminPassword) + populate(objectMap, "allocatedStorageSizeInTbs", a.AllocatedStorageSizeInTbs) + populate(objectMap, "apexDetails", a.ApexDetails) + populate(objectMap, "autonomousDatabaseId", a.AutonomousDatabaseID) + populate(objectMap, "autonomousMaintenanceScheduleType", a.AutonomousMaintenanceScheduleType) + populate(objectMap, "availableUpgradeVersions", a.AvailableUpgradeVersions) + populate(objectMap, "backupRetentionPeriodInDays", a.BackupRetentionPeriodInDays) + populate(objectMap, "cpuCoreCount", a.CPUCoreCount) + populate(objectMap, "characterSet", a.CharacterSet) + populate(objectMap, "cloneType", a.CloneType) + populate(objectMap, "computeCount", a.ComputeCount) + populate(objectMap, "computeModel", a.ComputeModel) + populate(objectMap, "connectionStrings", a.ConnectionStrings) + populate(objectMap, "connectionUrls", a.ConnectionUrls) + populate(objectMap, "customerContacts", a.CustomerContacts) + objectMap["dataBaseType"] = DataBaseTypeClone + populate(objectMap, "dataSafeStatus", a.DataSafeStatus) + populate(objectMap, "dataStorageSizeInGbs", a.DataStorageSizeInGbs) + populate(objectMap, "dataStorageSizeInTbs", a.DataStorageSizeInTbs) + populate(objectMap, "databaseEdition", a.DatabaseEdition) + populate(objectMap, "dbVersion", a.DbVersion) + populate(objectMap, "dbWorkload", a.DbWorkload) + populate(objectMap, "displayName", a.DisplayName) + populate(objectMap, "failedDataRecoveryInSeconds", a.FailedDataRecoveryInSeconds) + populate(objectMap, "inMemoryAreaInGbs", a.InMemoryAreaInGbs) + populate(objectMap, "isAutoScalingEnabled", a.IsAutoScalingEnabled) + populate(objectMap, "isAutoScalingForStorageEnabled", a.IsAutoScalingForStorageEnabled) + populate(objectMap, "isLocalDataGuardEnabled", a.IsLocalDataGuardEnabled) + populate(objectMap, "isMtlsConnectionRequired", a.IsMtlsConnectionRequired) + populate(objectMap, "isPreview", a.IsPreview) + populate(objectMap, "isPreviewVersionWithServiceTermsAccepted", a.IsPreviewVersionWithServiceTermsAccepted) + populate(objectMap, "isReconnectCloneEnabled", a.IsReconnectCloneEnabled) + populate(objectMap, "isRefreshableClone", a.IsRefreshableClone) + populate(objectMap, "isRemoteDataGuardEnabled", a.IsRemoteDataGuardEnabled) + populate(objectMap, "licenseModel", a.LicenseModel) + populate(objectMap, "lifecycleDetails", a.LifecycleDetails) + populate(objectMap, "lifecycleState", a.LifecycleState) + populate(objectMap, "localAdgAutoFailoverMaxDataLossLimit", a.LocalAdgAutoFailoverMaxDataLossLimit) + populate(objectMap, "localDisasterRecoveryType", a.LocalDisasterRecoveryType) + populate(objectMap, "localStandbyDb", a.LocalStandbyDb) + populate(objectMap, "longTermBackupSchedule", a.LongTermBackupSchedule) + populate(objectMap, "memoryPerOracleComputeUnitInGbs", a.MemoryPerOracleComputeUnitInGbs) + populate(objectMap, "ncharacterSet", a.NcharacterSet) + populateTime[datetime.RFC3339](objectMap, "nextLongTermBackupTimeStamp", a.NextLongTermBackupTimeStamp) + populate(objectMap, "ociUrl", a.OciURL) + populate(objectMap, "ocid", a.Ocid) + populate(objectMap, "openMode", a.OpenMode) + populate(objectMap, "operationsInsightsStatus", a.OperationsInsightsStatus) + populate(objectMap, "peerDbId", a.PeerDbID) + populate(objectMap, "peerDbIds", a.PeerDbIDs) + populate(objectMap, "permissionLevel", a.PermissionLevel) + populate(objectMap, "privateEndpoint", a.PrivateEndpoint) + populate(objectMap, "privateEndpointIp", a.PrivateEndpointIP) + populate(objectMap, "privateEndpointLabel", a.PrivateEndpointLabel) + populate(objectMap, "provisionableCpus", a.ProvisionableCpus) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "refreshableModel", a.RefreshableModel) + populate(objectMap, "refreshableStatus", a.RefreshableStatus) + populate(objectMap, "remoteDisasterRecoveryConfiguration", a.RemoteDisasterRecoveryConfiguration) + populate(objectMap, "role", a.Role) + populate(objectMap, "sqlWebDeveloperUrl", a.SQLWebDeveloperURL) + populate(objectMap, "scheduledOperationsList", a.ScheduledOperationsList) + populate(objectMap, "serviceConsoleUrl", a.ServiceConsoleURL) + populate(objectMap, "source", a.Source) + populate(objectMap, "sourceId", a.SourceID) + populate(objectMap, "subnetId", a.SubnetID) + populate(objectMap, "supportedRegionsToCloneTo", a.SupportedRegionsToCloneTo) + populateTime[datetime.RFC3339](objectMap, "timeCreated", a.TimeCreated) + populate(objectMap, "timeDataGuardRoleChanged", a.TimeDataGuardRoleChanged) + populate(objectMap, "timeDeletionOfFreeAutonomousDatabase", a.TimeDeletionOfFreeAutonomousDatabase) + populateTime[datetime.RFC3339](objectMap, "timeDisasterRecoveryRoleChanged", a.TimeDisasterRecoveryRoleChanged) + populate(objectMap, "timeLocalDataGuardEnabled", a.TimeLocalDataGuardEnabled) + populateTime[datetime.RFC3339](objectMap, "timeMaintenanceBegin", a.TimeMaintenanceBegin) + populateTime[datetime.RFC3339](objectMap, "timeMaintenanceEnd", a.TimeMaintenanceEnd) + populate(objectMap, "timeOfLastFailover", a.TimeOfLastFailover) + populate(objectMap, "timeOfLastRefresh", a.TimeOfLastRefresh) + populate(objectMap, "timeOfLastRefreshPoint", a.TimeOfLastRefreshPoint) + populate(objectMap, "timeOfLastSwitchover", a.TimeOfLastSwitchover) + populate(objectMap, "timeReclamationOfFreeAutonomousDatabase", a.TimeReclamationOfFreeAutonomousDatabase) + populate(objectMap, "timeUntilReconnectCloneEnabled", a.TimeUntilReconnectCloneEnabled) + populate(objectMap, "usedDataStorageSizeInGbs", a.UsedDataStorageSizeInGbs) + populate(objectMap, "usedDataStorageSizeInTbs", a.UsedDataStorageSizeInTbs) + populate(objectMap, "vnetId", a.VnetID) + populate(objectMap, "whitelistedIps", a.WhitelistedIPs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutonomousDatabaseCloneProperties. +func (a *AutonomousDatabaseCloneProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actualUsedDataStorageSizeInTbs": + err = unpopulate(val, "ActualUsedDataStorageSizeInTbs", &a.ActualUsedDataStorageSizeInTbs) + delete(rawMsg, key) + case "adminPassword": + err = unpopulate(val, "AdminPassword", &a.AdminPassword) + delete(rawMsg, key) + case "allocatedStorageSizeInTbs": + err = unpopulate(val, "AllocatedStorageSizeInTbs", &a.AllocatedStorageSizeInTbs) + delete(rawMsg, key) + case "apexDetails": + err = unpopulate(val, "ApexDetails", &a.ApexDetails) + delete(rawMsg, key) + case "autonomousDatabaseId": + err = unpopulate(val, "AutonomousDatabaseID", &a.AutonomousDatabaseID) + delete(rawMsg, key) + case "autonomousMaintenanceScheduleType": + err = unpopulate(val, "AutonomousMaintenanceScheduleType", &a.AutonomousMaintenanceScheduleType) + delete(rawMsg, key) + case "availableUpgradeVersions": + err = unpopulate(val, "AvailableUpgradeVersions", &a.AvailableUpgradeVersions) + delete(rawMsg, key) + case "backupRetentionPeriodInDays": + err = unpopulate(val, "BackupRetentionPeriodInDays", &a.BackupRetentionPeriodInDays) + delete(rawMsg, key) + case "cpuCoreCount": + err = unpopulate(val, "CPUCoreCount", &a.CPUCoreCount) + delete(rawMsg, key) + case "characterSet": + err = unpopulate(val, "CharacterSet", &a.CharacterSet) + delete(rawMsg, key) + case "cloneType": + err = unpopulate(val, "CloneType", &a.CloneType) + delete(rawMsg, key) + case "computeCount": + err = unpopulate(val, "ComputeCount", &a.ComputeCount) + delete(rawMsg, key) + case "computeModel": + err = unpopulate(val, "ComputeModel", &a.ComputeModel) + delete(rawMsg, key) + case "connectionStrings": + err = unpopulate(val, "ConnectionStrings", &a.ConnectionStrings) + delete(rawMsg, key) + case "connectionUrls": + err = unpopulate(val, "ConnectionUrls", &a.ConnectionUrls) + delete(rawMsg, key) + case "customerContacts": + err = unpopulate(val, "CustomerContacts", &a.CustomerContacts) + delete(rawMsg, key) + case "dataBaseType": + err = unpopulate(val, "DataBaseType", &a.DataBaseType) + delete(rawMsg, key) + case "dataSafeStatus": + err = unpopulate(val, "DataSafeStatus", &a.DataSafeStatus) + delete(rawMsg, key) + case "dataStorageSizeInGbs": + err = unpopulate(val, "DataStorageSizeInGbs", &a.DataStorageSizeInGbs) + delete(rawMsg, key) + case "dataStorageSizeInTbs": + err = unpopulate(val, "DataStorageSizeInTbs", &a.DataStorageSizeInTbs) + delete(rawMsg, key) + case "databaseEdition": + err = unpopulate(val, "DatabaseEdition", &a.DatabaseEdition) + delete(rawMsg, key) + case "dbVersion": + err = unpopulate(val, "DbVersion", &a.DbVersion) + delete(rawMsg, key) + case "dbWorkload": + err = unpopulate(val, "DbWorkload", &a.DbWorkload) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &a.DisplayName) + delete(rawMsg, key) + case "failedDataRecoveryInSeconds": + err = unpopulate(val, "FailedDataRecoveryInSeconds", &a.FailedDataRecoveryInSeconds) + delete(rawMsg, key) + case "inMemoryAreaInGbs": + err = unpopulate(val, "InMemoryAreaInGbs", &a.InMemoryAreaInGbs) + delete(rawMsg, key) + case "isAutoScalingEnabled": + err = unpopulate(val, "IsAutoScalingEnabled", &a.IsAutoScalingEnabled) + delete(rawMsg, key) + case "isAutoScalingForStorageEnabled": + err = unpopulate(val, "IsAutoScalingForStorageEnabled", &a.IsAutoScalingForStorageEnabled) + delete(rawMsg, key) + case "isLocalDataGuardEnabled": + err = unpopulate(val, "IsLocalDataGuardEnabled", &a.IsLocalDataGuardEnabled) + delete(rawMsg, key) + case "isMtlsConnectionRequired": + err = unpopulate(val, "IsMtlsConnectionRequired", &a.IsMtlsConnectionRequired) + delete(rawMsg, key) + case "isPreview": + err = unpopulate(val, "IsPreview", &a.IsPreview) + delete(rawMsg, key) + case "isPreviewVersionWithServiceTermsAccepted": + err = unpopulate(val, "IsPreviewVersionWithServiceTermsAccepted", &a.IsPreviewVersionWithServiceTermsAccepted) + delete(rawMsg, key) + case "isReconnectCloneEnabled": + err = unpopulate(val, "IsReconnectCloneEnabled", &a.IsReconnectCloneEnabled) + delete(rawMsg, key) + case "isRefreshableClone": + err = unpopulate(val, "IsRefreshableClone", &a.IsRefreshableClone) + delete(rawMsg, key) + case "isRemoteDataGuardEnabled": + err = unpopulate(val, "IsRemoteDataGuardEnabled", &a.IsRemoteDataGuardEnabled) + delete(rawMsg, key) + case "licenseModel": + err = unpopulate(val, "LicenseModel", &a.LicenseModel) + delete(rawMsg, key) + case "lifecycleDetails": + err = unpopulate(val, "LifecycleDetails", &a.LifecycleDetails) + delete(rawMsg, key) + case "lifecycleState": + err = unpopulate(val, "LifecycleState", &a.LifecycleState) + delete(rawMsg, key) + case "localAdgAutoFailoverMaxDataLossLimit": + err = unpopulate(val, "LocalAdgAutoFailoverMaxDataLossLimit", &a.LocalAdgAutoFailoverMaxDataLossLimit) + delete(rawMsg, key) + case "localDisasterRecoveryType": + err = unpopulate(val, "LocalDisasterRecoveryType", &a.LocalDisasterRecoveryType) + delete(rawMsg, key) + case "localStandbyDb": + err = unpopulate(val, "LocalStandbyDb", &a.LocalStandbyDb) + delete(rawMsg, key) + case "longTermBackupSchedule": + err = unpopulate(val, "LongTermBackupSchedule", &a.LongTermBackupSchedule) + delete(rawMsg, key) + case "memoryPerOracleComputeUnitInGbs": + err = unpopulate(val, "MemoryPerOracleComputeUnitInGbs", &a.MemoryPerOracleComputeUnitInGbs) + delete(rawMsg, key) + case "ncharacterSet": + err = unpopulate(val, "NcharacterSet", &a.NcharacterSet) + delete(rawMsg, key) + case "nextLongTermBackupTimeStamp": + err = unpopulateTime[datetime.RFC3339](val, "NextLongTermBackupTimeStamp", &a.NextLongTermBackupTimeStamp) + delete(rawMsg, key) + case "ociUrl": + err = unpopulate(val, "OciURL", &a.OciURL) + delete(rawMsg, key) + case "ocid": + err = unpopulate(val, "Ocid", &a.Ocid) + delete(rawMsg, key) + case "openMode": + err = unpopulate(val, "OpenMode", &a.OpenMode) + delete(rawMsg, key) + case "operationsInsightsStatus": + err = unpopulate(val, "OperationsInsightsStatus", &a.OperationsInsightsStatus) + delete(rawMsg, key) + case "peerDbId": + err = unpopulate(val, "PeerDbID", &a.PeerDbID) + delete(rawMsg, key) + case "peerDbIds": + err = unpopulate(val, "PeerDbIDs", &a.PeerDbIDs) + delete(rawMsg, key) + case "permissionLevel": + err = unpopulate(val, "PermissionLevel", &a.PermissionLevel) + delete(rawMsg, key) + case "privateEndpoint": + err = unpopulate(val, "PrivateEndpoint", &a.PrivateEndpoint) + delete(rawMsg, key) + case "privateEndpointIp": + err = unpopulate(val, "PrivateEndpointIP", &a.PrivateEndpointIP) + delete(rawMsg, key) + case "privateEndpointLabel": + err = unpopulate(val, "PrivateEndpointLabel", &a.PrivateEndpointLabel) + delete(rawMsg, key) + case "provisionableCpus": + err = unpopulate(val, "ProvisionableCpus", &a.ProvisionableCpus) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "refreshableModel": + err = unpopulate(val, "RefreshableModel", &a.RefreshableModel) + delete(rawMsg, key) + case "refreshableStatus": + err = unpopulate(val, "RefreshableStatus", &a.RefreshableStatus) + delete(rawMsg, key) + case "remoteDisasterRecoveryConfiguration": + err = unpopulate(val, "RemoteDisasterRecoveryConfiguration", &a.RemoteDisasterRecoveryConfiguration) + delete(rawMsg, key) + case "role": + err = unpopulate(val, "Role", &a.Role) + delete(rawMsg, key) + case "sqlWebDeveloperUrl": + err = unpopulate(val, "SQLWebDeveloperURL", &a.SQLWebDeveloperURL) + delete(rawMsg, key) + case "scheduledOperationsList": + err = unpopulate(val, "ScheduledOperationsList", &a.ScheduledOperationsList) + delete(rawMsg, key) + case "serviceConsoleUrl": + err = unpopulate(val, "ServiceConsoleURL", &a.ServiceConsoleURL) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &a.Source) + delete(rawMsg, key) + case "sourceId": + err = unpopulate(val, "SourceID", &a.SourceID) + delete(rawMsg, key) + case "subnetId": + err = unpopulate(val, "SubnetID", &a.SubnetID) + delete(rawMsg, key) + case "supportedRegionsToCloneTo": + err = unpopulate(val, "SupportedRegionsToCloneTo", &a.SupportedRegionsToCloneTo) + delete(rawMsg, key) + case "timeCreated": + err = unpopulateTime[datetime.RFC3339](val, "TimeCreated", &a.TimeCreated) + delete(rawMsg, key) + case "timeDataGuardRoleChanged": + err = unpopulate(val, "TimeDataGuardRoleChanged", &a.TimeDataGuardRoleChanged) + delete(rawMsg, key) + case "timeDeletionOfFreeAutonomousDatabase": + err = unpopulate(val, "TimeDeletionOfFreeAutonomousDatabase", &a.TimeDeletionOfFreeAutonomousDatabase) + delete(rawMsg, key) + case "timeDisasterRecoveryRoleChanged": + err = unpopulateTime[datetime.RFC3339](val, "TimeDisasterRecoveryRoleChanged", &a.TimeDisasterRecoveryRoleChanged) + delete(rawMsg, key) + case "timeLocalDataGuardEnabled": + err = unpopulate(val, "TimeLocalDataGuardEnabled", &a.TimeLocalDataGuardEnabled) + delete(rawMsg, key) + case "timeMaintenanceBegin": + err = unpopulateTime[datetime.RFC3339](val, "TimeMaintenanceBegin", &a.TimeMaintenanceBegin) + delete(rawMsg, key) + case "timeMaintenanceEnd": + err = unpopulateTime[datetime.RFC3339](val, "TimeMaintenanceEnd", &a.TimeMaintenanceEnd) + delete(rawMsg, key) + case "timeOfLastFailover": + err = unpopulate(val, "TimeOfLastFailover", &a.TimeOfLastFailover) + delete(rawMsg, key) + case "timeOfLastRefresh": + err = unpopulate(val, "TimeOfLastRefresh", &a.TimeOfLastRefresh) + delete(rawMsg, key) + case "timeOfLastRefreshPoint": + err = unpopulate(val, "TimeOfLastRefreshPoint", &a.TimeOfLastRefreshPoint) + delete(rawMsg, key) + case "timeOfLastSwitchover": + err = unpopulate(val, "TimeOfLastSwitchover", &a.TimeOfLastSwitchover) + delete(rawMsg, key) + case "timeReclamationOfFreeAutonomousDatabase": + err = unpopulate(val, "TimeReclamationOfFreeAutonomousDatabase", &a.TimeReclamationOfFreeAutonomousDatabase) + delete(rawMsg, key) + case "timeUntilReconnectCloneEnabled": + err = unpopulate(val, "TimeUntilReconnectCloneEnabled", &a.TimeUntilReconnectCloneEnabled) + delete(rawMsg, key) + case "usedDataStorageSizeInGbs": + err = unpopulate(val, "UsedDataStorageSizeInGbs", &a.UsedDataStorageSizeInGbs) + delete(rawMsg, key) + case "usedDataStorageSizeInTbs": + err = unpopulate(val, "UsedDataStorageSizeInTbs", &a.UsedDataStorageSizeInTbs) + delete(rawMsg, key) + case "vnetId": + err = unpopulate(val, "VnetID", &a.VnetID) + delete(rawMsg, key) + case "whitelistedIps": + err = unpopulate(val, "WhitelistedIPs", &a.WhitelistedIPs) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutonomousDatabaseCrossRegionDisasterRecoveryProperties. +func (a AutonomousDatabaseCrossRegionDisasterRecoveryProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actualUsedDataStorageSizeInTbs", a.ActualUsedDataStorageSizeInTbs) + populate(objectMap, "adminPassword", a.AdminPassword) + populate(objectMap, "allocatedStorageSizeInTbs", a.AllocatedStorageSizeInTbs) + populate(objectMap, "apexDetails", a.ApexDetails) + populate(objectMap, "autonomousDatabaseId", a.AutonomousDatabaseID) + populate(objectMap, "autonomousMaintenanceScheduleType", a.AutonomousMaintenanceScheduleType) + populate(objectMap, "availableUpgradeVersions", a.AvailableUpgradeVersions) + populate(objectMap, "backupRetentionPeriodInDays", a.BackupRetentionPeriodInDays) + populate(objectMap, "cpuCoreCount", a.CPUCoreCount) + populate(objectMap, "characterSet", a.CharacterSet) + populate(objectMap, "computeCount", a.ComputeCount) + populate(objectMap, "computeModel", a.ComputeModel) + populate(objectMap, "connectionStrings", a.ConnectionStrings) + populate(objectMap, "connectionUrls", a.ConnectionUrls) + populate(objectMap, "customerContacts", a.CustomerContacts) + objectMap["dataBaseType"] = DataBaseTypeCrossRegionDisasterRecovery + populate(objectMap, "dataSafeStatus", a.DataSafeStatus) + populate(objectMap, "dataStorageSizeInGbs", a.DataStorageSizeInGbs) + populate(objectMap, "dataStorageSizeInTbs", a.DataStorageSizeInTbs) + populate(objectMap, "databaseEdition", a.DatabaseEdition) + populate(objectMap, "dbVersion", a.DbVersion) + populate(objectMap, "dbWorkload", a.DbWorkload) + populate(objectMap, "displayName", a.DisplayName) + populate(objectMap, "failedDataRecoveryInSeconds", a.FailedDataRecoveryInSeconds) + populate(objectMap, "inMemoryAreaInGbs", a.InMemoryAreaInGbs) + populate(objectMap, "isAutoScalingEnabled", a.IsAutoScalingEnabled) + populate(objectMap, "isAutoScalingForStorageEnabled", a.IsAutoScalingForStorageEnabled) + populate(objectMap, "isLocalDataGuardEnabled", a.IsLocalDataGuardEnabled) + populate(objectMap, "isMtlsConnectionRequired", a.IsMtlsConnectionRequired) + populate(objectMap, "isPreview", a.IsPreview) + populate(objectMap, "isPreviewVersionWithServiceTermsAccepted", a.IsPreviewVersionWithServiceTermsAccepted) + populate(objectMap, "isRemoteDataGuardEnabled", a.IsRemoteDataGuardEnabled) + populate(objectMap, "isReplicateAutomaticBackups", a.IsReplicateAutomaticBackups) + populate(objectMap, "licenseModel", a.LicenseModel) + populate(objectMap, "lifecycleDetails", a.LifecycleDetails) + populate(objectMap, "lifecycleState", a.LifecycleState) + populate(objectMap, "localAdgAutoFailoverMaxDataLossLimit", a.LocalAdgAutoFailoverMaxDataLossLimit) + populate(objectMap, "localDisasterRecoveryType", a.LocalDisasterRecoveryType) + populate(objectMap, "localStandbyDb", a.LocalStandbyDb) + populate(objectMap, "longTermBackupSchedule", a.LongTermBackupSchedule) + populate(objectMap, "memoryPerOracleComputeUnitInGbs", a.MemoryPerOracleComputeUnitInGbs) + populate(objectMap, "ncharacterSet", a.NcharacterSet) + populateTime[datetime.RFC3339](objectMap, "nextLongTermBackupTimeStamp", a.NextLongTermBackupTimeStamp) + populate(objectMap, "ociUrl", a.OciURL) + populate(objectMap, "ocid", a.Ocid) + populate(objectMap, "openMode", a.OpenMode) + populate(objectMap, "operationsInsightsStatus", a.OperationsInsightsStatus) + populate(objectMap, "peerDbId", a.PeerDbID) + populate(objectMap, "peerDbIds", a.PeerDbIDs) + populate(objectMap, "permissionLevel", a.PermissionLevel) + populate(objectMap, "privateEndpoint", a.PrivateEndpoint) + populate(objectMap, "privateEndpointIp", a.PrivateEndpointIP) + populate(objectMap, "privateEndpointLabel", a.PrivateEndpointLabel) + populate(objectMap, "provisionableCpus", a.ProvisionableCpus) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "remoteDisasterRecoveryConfiguration", a.RemoteDisasterRecoveryConfiguration) + populate(objectMap, "remoteDisasterRecoveryType", a.RemoteDisasterRecoveryType) + populate(objectMap, "role", a.Role) + populate(objectMap, "sqlWebDeveloperUrl", a.SQLWebDeveloperURL) + populate(objectMap, "scheduledOperationsList", a.ScheduledOperationsList) + populate(objectMap, "serviceConsoleUrl", a.ServiceConsoleURL) + objectMap["source"] = SourceTypeCrossRegionDisasterRecovery + populate(objectMap, "sourceId", a.SourceID) + populate(objectMap, "sourceLocation", a.SourceLocation) + populate(objectMap, "sourceOcid", a.SourceOcid) + populate(objectMap, "subnetId", a.SubnetID) + populate(objectMap, "supportedRegionsToCloneTo", a.SupportedRegionsToCloneTo) + populateTime[datetime.RFC3339](objectMap, "timeCreated", a.TimeCreated) + populate(objectMap, "timeDataGuardRoleChanged", a.TimeDataGuardRoleChanged) + populate(objectMap, "timeDeletionOfFreeAutonomousDatabase", a.TimeDeletionOfFreeAutonomousDatabase) + populateTime[datetime.RFC3339](objectMap, "timeDisasterRecoveryRoleChanged", a.TimeDisasterRecoveryRoleChanged) + populate(objectMap, "timeLocalDataGuardEnabled", a.TimeLocalDataGuardEnabled) + populateTime[datetime.RFC3339](objectMap, "timeMaintenanceBegin", a.TimeMaintenanceBegin) + populateTime[datetime.RFC3339](objectMap, "timeMaintenanceEnd", a.TimeMaintenanceEnd) + populate(objectMap, "timeOfLastFailover", a.TimeOfLastFailover) + populate(objectMap, "timeOfLastRefresh", a.TimeOfLastRefresh) + populate(objectMap, "timeOfLastRefreshPoint", a.TimeOfLastRefreshPoint) + populate(objectMap, "timeOfLastSwitchover", a.TimeOfLastSwitchover) + populate(objectMap, "timeReclamationOfFreeAutonomousDatabase", a.TimeReclamationOfFreeAutonomousDatabase) + populate(objectMap, "usedDataStorageSizeInGbs", a.UsedDataStorageSizeInGbs) + populate(objectMap, "usedDataStorageSizeInTbs", a.UsedDataStorageSizeInTbs) + populate(objectMap, "vnetId", a.VnetID) + populate(objectMap, "whitelistedIps", a.WhitelistedIPs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutonomousDatabaseCrossRegionDisasterRecoveryProperties. +func (a *AutonomousDatabaseCrossRegionDisasterRecoveryProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actualUsedDataStorageSizeInTbs": + err = unpopulate(val, "ActualUsedDataStorageSizeInTbs", &a.ActualUsedDataStorageSizeInTbs) + delete(rawMsg, key) + case "adminPassword": + err = unpopulate(val, "AdminPassword", &a.AdminPassword) + delete(rawMsg, key) + case "allocatedStorageSizeInTbs": + err = unpopulate(val, "AllocatedStorageSizeInTbs", &a.AllocatedStorageSizeInTbs) + delete(rawMsg, key) + case "apexDetails": + err = unpopulate(val, "ApexDetails", &a.ApexDetails) + delete(rawMsg, key) + case "autonomousDatabaseId": + err = unpopulate(val, "AutonomousDatabaseID", &a.AutonomousDatabaseID) + delete(rawMsg, key) + case "autonomousMaintenanceScheduleType": + err = unpopulate(val, "AutonomousMaintenanceScheduleType", &a.AutonomousMaintenanceScheduleType) + delete(rawMsg, key) + case "availableUpgradeVersions": + err = unpopulate(val, "AvailableUpgradeVersions", &a.AvailableUpgradeVersions) + delete(rawMsg, key) + case "backupRetentionPeriodInDays": + err = unpopulate(val, "BackupRetentionPeriodInDays", &a.BackupRetentionPeriodInDays) + delete(rawMsg, key) + case "cpuCoreCount": + err = unpopulate(val, "CPUCoreCount", &a.CPUCoreCount) + delete(rawMsg, key) + case "characterSet": + err = unpopulate(val, "CharacterSet", &a.CharacterSet) + delete(rawMsg, key) + case "computeCount": + err = unpopulate(val, "ComputeCount", &a.ComputeCount) + delete(rawMsg, key) + case "computeModel": + err = unpopulate(val, "ComputeModel", &a.ComputeModel) + delete(rawMsg, key) + case "connectionStrings": + err = unpopulate(val, "ConnectionStrings", &a.ConnectionStrings) + delete(rawMsg, key) + case "connectionUrls": + err = unpopulate(val, "ConnectionUrls", &a.ConnectionUrls) + delete(rawMsg, key) + case "customerContacts": + err = unpopulate(val, "CustomerContacts", &a.CustomerContacts) + delete(rawMsg, key) + case "dataBaseType": + err = unpopulate(val, "DataBaseType", &a.DataBaseType) + delete(rawMsg, key) + case "dataSafeStatus": + err = unpopulate(val, "DataSafeStatus", &a.DataSafeStatus) + delete(rawMsg, key) + case "dataStorageSizeInGbs": + err = unpopulate(val, "DataStorageSizeInGbs", &a.DataStorageSizeInGbs) + delete(rawMsg, key) + case "dataStorageSizeInTbs": + err = unpopulate(val, "DataStorageSizeInTbs", &a.DataStorageSizeInTbs) + delete(rawMsg, key) + case "databaseEdition": + err = unpopulate(val, "DatabaseEdition", &a.DatabaseEdition) + delete(rawMsg, key) + case "dbVersion": + err = unpopulate(val, "DbVersion", &a.DbVersion) + delete(rawMsg, key) + case "dbWorkload": + err = unpopulate(val, "DbWorkload", &a.DbWorkload) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &a.DisplayName) + delete(rawMsg, key) + case "failedDataRecoveryInSeconds": + err = unpopulate(val, "FailedDataRecoveryInSeconds", &a.FailedDataRecoveryInSeconds) + delete(rawMsg, key) + case "inMemoryAreaInGbs": + err = unpopulate(val, "InMemoryAreaInGbs", &a.InMemoryAreaInGbs) + delete(rawMsg, key) + case "isAutoScalingEnabled": + err = unpopulate(val, "IsAutoScalingEnabled", &a.IsAutoScalingEnabled) + delete(rawMsg, key) + case "isAutoScalingForStorageEnabled": + err = unpopulate(val, "IsAutoScalingForStorageEnabled", &a.IsAutoScalingForStorageEnabled) + delete(rawMsg, key) + case "isLocalDataGuardEnabled": + err = unpopulate(val, "IsLocalDataGuardEnabled", &a.IsLocalDataGuardEnabled) + delete(rawMsg, key) + case "isMtlsConnectionRequired": + err = unpopulate(val, "IsMtlsConnectionRequired", &a.IsMtlsConnectionRequired) + delete(rawMsg, key) + case "isPreview": + err = unpopulate(val, "IsPreview", &a.IsPreview) + delete(rawMsg, key) + case "isPreviewVersionWithServiceTermsAccepted": + err = unpopulate(val, "IsPreviewVersionWithServiceTermsAccepted", &a.IsPreviewVersionWithServiceTermsAccepted) + delete(rawMsg, key) + case "isRemoteDataGuardEnabled": + err = unpopulate(val, "IsRemoteDataGuardEnabled", &a.IsRemoteDataGuardEnabled) + delete(rawMsg, key) + case "isReplicateAutomaticBackups": + err = unpopulate(val, "IsReplicateAutomaticBackups", &a.IsReplicateAutomaticBackups) + delete(rawMsg, key) + case "licenseModel": + err = unpopulate(val, "LicenseModel", &a.LicenseModel) + delete(rawMsg, key) + case "lifecycleDetails": + err = unpopulate(val, "LifecycleDetails", &a.LifecycleDetails) + delete(rawMsg, key) + case "lifecycleState": + err = unpopulate(val, "LifecycleState", &a.LifecycleState) + delete(rawMsg, key) + case "localAdgAutoFailoverMaxDataLossLimit": + err = unpopulate(val, "LocalAdgAutoFailoverMaxDataLossLimit", &a.LocalAdgAutoFailoverMaxDataLossLimit) + delete(rawMsg, key) + case "localDisasterRecoveryType": + err = unpopulate(val, "LocalDisasterRecoveryType", &a.LocalDisasterRecoveryType) + delete(rawMsg, key) + case "localStandbyDb": + err = unpopulate(val, "LocalStandbyDb", &a.LocalStandbyDb) + delete(rawMsg, key) + case "longTermBackupSchedule": + err = unpopulate(val, "LongTermBackupSchedule", &a.LongTermBackupSchedule) + delete(rawMsg, key) + case "memoryPerOracleComputeUnitInGbs": + err = unpopulate(val, "MemoryPerOracleComputeUnitInGbs", &a.MemoryPerOracleComputeUnitInGbs) + delete(rawMsg, key) + case "ncharacterSet": + err = unpopulate(val, "NcharacterSet", &a.NcharacterSet) + delete(rawMsg, key) + case "nextLongTermBackupTimeStamp": + err = unpopulateTime[datetime.RFC3339](val, "NextLongTermBackupTimeStamp", &a.NextLongTermBackupTimeStamp) + delete(rawMsg, key) + case "ociUrl": + err = unpopulate(val, "OciURL", &a.OciURL) + delete(rawMsg, key) + case "ocid": + err = unpopulate(val, "Ocid", &a.Ocid) + delete(rawMsg, key) + case "openMode": + err = unpopulate(val, "OpenMode", &a.OpenMode) + delete(rawMsg, key) + case "operationsInsightsStatus": + err = unpopulate(val, "OperationsInsightsStatus", &a.OperationsInsightsStatus) + delete(rawMsg, key) + case "peerDbId": + err = unpopulate(val, "PeerDbID", &a.PeerDbID) + delete(rawMsg, key) + case "peerDbIds": + err = unpopulate(val, "PeerDbIDs", &a.PeerDbIDs) + delete(rawMsg, key) + case "permissionLevel": + err = unpopulate(val, "PermissionLevel", &a.PermissionLevel) + delete(rawMsg, key) + case "privateEndpoint": + err = unpopulate(val, "PrivateEndpoint", &a.PrivateEndpoint) + delete(rawMsg, key) + case "privateEndpointIp": + err = unpopulate(val, "PrivateEndpointIP", &a.PrivateEndpointIP) + delete(rawMsg, key) + case "privateEndpointLabel": + err = unpopulate(val, "PrivateEndpointLabel", &a.PrivateEndpointLabel) + delete(rawMsg, key) + case "provisionableCpus": + err = unpopulate(val, "ProvisionableCpus", &a.ProvisionableCpus) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "remoteDisasterRecoveryConfiguration": + err = unpopulate(val, "RemoteDisasterRecoveryConfiguration", &a.RemoteDisasterRecoveryConfiguration) + delete(rawMsg, key) + case "remoteDisasterRecoveryType": + err = unpopulate(val, "RemoteDisasterRecoveryType", &a.RemoteDisasterRecoveryType) + delete(rawMsg, key) + case "role": + err = unpopulate(val, "Role", &a.Role) + delete(rawMsg, key) + case "sqlWebDeveloperUrl": + err = unpopulate(val, "SQLWebDeveloperURL", &a.SQLWebDeveloperURL) + delete(rawMsg, key) + case "scheduledOperationsList": + err = unpopulate(val, "ScheduledOperationsList", &a.ScheduledOperationsList) + delete(rawMsg, key) + case "serviceConsoleUrl": + err = unpopulate(val, "ServiceConsoleURL", &a.ServiceConsoleURL) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &a.Source) + delete(rawMsg, key) + case "sourceId": + err = unpopulate(val, "SourceID", &a.SourceID) + delete(rawMsg, key) + case "sourceLocation": + err = unpopulate(val, "SourceLocation", &a.SourceLocation) + delete(rawMsg, key) + case "sourceOcid": + err = unpopulate(val, "SourceOcid", &a.SourceOcid) + delete(rawMsg, key) + case "subnetId": + err = unpopulate(val, "SubnetID", &a.SubnetID) + delete(rawMsg, key) + case "supportedRegionsToCloneTo": + err = unpopulate(val, "SupportedRegionsToCloneTo", &a.SupportedRegionsToCloneTo) + delete(rawMsg, key) + case "timeCreated": + err = unpopulateTime[datetime.RFC3339](val, "TimeCreated", &a.TimeCreated) + delete(rawMsg, key) + case "timeDataGuardRoleChanged": + err = unpopulate(val, "TimeDataGuardRoleChanged", &a.TimeDataGuardRoleChanged) + delete(rawMsg, key) + case "timeDeletionOfFreeAutonomousDatabase": + err = unpopulate(val, "TimeDeletionOfFreeAutonomousDatabase", &a.TimeDeletionOfFreeAutonomousDatabase) + delete(rawMsg, key) + case "timeDisasterRecoveryRoleChanged": + err = unpopulateTime[datetime.RFC3339](val, "TimeDisasterRecoveryRoleChanged", &a.TimeDisasterRecoveryRoleChanged) + delete(rawMsg, key) + case "timeLocalDataGuardEnabled": + err = unpopulate(val, "TimeLocalDataGuardEnabled", &a.TimeLocalDataGuardEnabled) + delete(rawMsg, key) + case "timeMaintenanceBegin": + err = unpopulateTime[datetime.RFC3339](val, "TimeMaintenanceBegin", &a.TimeMaintenanceBegin) + delete(rawMsg, key) + case "timeMaintenanceEnd": + err = unpopulateTime[datetime.RFC3339](val, "TimeMaintenanceEnd", &a.TimeMaintenanceEnd) + delete(rawMsg, key) + case "timeOfLastFailover": + err = unpopulate(val, "TimeOfLastFailover", &a.TimeOfLastFailover) + delete(rawMsg, key) + case "timeOfLastRefresh": + err = unpopulate(val, "TimeOfLastRefresh", &a.TimeOfLastRefresh) + delete(rawMsg, key) + case "timeOfLastRefreshPoint": + err = unpopulate(val, "TimeOfLastRefreshPoint", &a.TimeOfLastRefreshPoint) + delete(rawMsg, key) + case "timeOfLastSwitchover": + err = unpopulate(val, "TimeOfLastSwitchover", &a.TimeOfLastSwitchover) + delete(rawMsg, key) + case "timeReclamationOfFreeAutonomousDatabase": + err = unpopulate(val, "TimeReclamationOfFreeAutonomousDatabase", &a.TimeReclamationOfFreeAutonomousDatabase) + delete(rawMsg, key) + case "usedDataStorageSizeInGbs": + err = unpopulate(val, "UsedDataStorageSizeInGbs", &a.UsedDataStorageSizeInGbs) + delete(rawMsg, key) + case "usedDataStorageSizeInTbs": + err = unpopulate(val, "UsedDataStorageSizeInTbs", &a.UsedDataStorageSizeInTbs) + delete(rawMsg, key) + case "vnetId": + err = unpopulate(val, "VnetID", &a.VnetID) + delete(rawMsg, key) + case "whitelistedIps": + err = unpopulate(val, "WhitelistedIPs", &a.WhitelistedIPs) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutonomousDatabaseFromBackupTimestampProperties. +func (a AutonomousDatabaseFromBackupTimestampProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actualUsedDataStorageSizeInTbs", a.ActualUsedDataStorageSizeInTbs) + populate(objectMap, "adminPassword", a.AdminPassword) + populate(objectMap, "allocatedStorageSizeInTbs", a.AllocatedStorageSizeInTbs) + populate(objectMap, "apexDetails", a.ApexDetails) + populate(objectMap, "autonomousDatabaseId", a.AutonomousDatabaseID) + populate(objectMap, "autonomousMaintenanceScheduleType", a.AutonomousMaintenanceScheduleType) + populate(objectMap, "availableUpgradeVersions", a.AvailableUpgradeVersions) + populate(objectMap, "backupRetentionPeriodInDays", a.BackupRetentionPeriodInDays) + populate(objectMap, "cpuCoreCount", a.CPUCoreCount) + populate(objectMap, "characterSet", a.CharacterSet) + populate(objectMap, "cloneType", a.CloneType) + populate(objectMap, "computeCount", a.ComputeCount) + populate(objectMap, "computeModel", a.ComputeModel) + populate(objectMap, "connectionStrings", a.ConnectionStrings) + populate(objectMap, "connectionUrls", a.ConnectionUrls) + populate(objectMap, "customerContacts", a.CustomerContacts) + objectMap["dataBaseType"] = DataBaseTypeCloneFromBackupTimestamp + populate(objectMap, "dataSafeStatus", a.DataSafeStatus) + populate(objectMap, "dataStorageSizeInGbs", a.DataStorageSizeInGbs) + populate(objectMap, "dataStorageSizeInTbs", a.DataStorageSizeInTbs) + populate(objectMap, "databaseEdition", a.DatabaseEdition) + populate(objectMap, "dbVersion", a.DbVersion) + populate(objectMap, "dbWorkload", a.DbWorkload) + populate(objectMap, "displayName", a.DisplayName) + populate(objectMap, "failedDataRecoveryInSeconds", a.FailedDataRecoveryInSeconds) + populate(objectMap, "inMemoryAreaInGbs", a.InMemoryAreaInGbs) + populate(objectMap, "isAutoScalingEnabled", a.IsAutoScalingEnabled) + populate(objectMap, "isAutoScalingForStorageEnabled", a.IsAutoScalingForStorageEnabled) + populate(objectMap, "isLocalDataGuardEnabled", a.IsLocalDataGuardEnabled) + populate(objectMap, "isMtlsConnectionRequired", a.IsMtlsConnectionRequired) + populate(objectMap, "isPreview", a.IsPreview) + populate(objectMap, "isPreviewVersionWithServiceTermsAccepted", a.IsPreviewVersionWithServiceTermsAccepted) + populate(objectMap, "isRemoteDataGuardEnabled", a.IsRemoteDataGuardEnabled) + populate(objectMap, "licenseModel", a.LicenseModel) + populate(objectMap, "lifecycleDetails", a.LifecycleDetails) + populate(objectMap, "lifecycleState", a.LifecycleState) + populate(objectMap, "localAdgAutoFailoverMaxDataLossLimit", a.LocalAdgAutoFailoverMaxDataLossLimit) + populate(objectMap, "localDisasterRecoveryType", a.LocalDisasterRecoveryType) + populate(objectMap, "localStandbyDb", a.LocalStandbyDb) + populate(objectMap, "longTermBackupSchedule", a.LongTermBackupSchedule) + populate(objectMap, "memoryPerOracleComputeUnitInGbs", a.MemoryPerOracleComputeUnitInGbs) + populate(objectMap, "ncharacterSet", a.NcharacterSet) + populateTime[datetime.RFC3339](objectMap, "nextLongTermBackupTimeStamp", a.NextLongTermBackupTimeStamp) + populate(objectMap, "ociUrl", a.OciURL) + populate(objectMap, "ocid", a.Ocid) + populate(objectMap, "openMode", a.OpenMode) + populate(objectMap, "operationsInsightsStatus", a.OperationsInsightsStatus) + populate(objectMap, "peerDbId", a.PeerDbID) + populate(objectMap, "peerDbIds", a.PeerDbIDs) + populate(objectMap, "permissionLevel", a.PermissionLevel) + populate(objectMap, "privateEndpoint", a.PrivateEndpoint) + populate(objectMap, "privateEndpointIp", a.PrivateEndpointIP) + populate(objectMap, "privateEndpointLabel", a.PrivateEndpointLabel) + populate(objectMap, "provisionableCpus", a.ProvisionableCpus) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "remoteDisasterRecoveryConfiguration", a.RemoteDisasterRecoveryConfiguration) + populate(objectMap, "role", a.Role) + populate(objectMap, "sqlWebDeveloperUrl", a.SQLWebDeveloperURL) + populate(objectMap, "scheduledOperationsList", a.ScheduledOperationsList) + populate(objectMap, "serviceConsoleUrl", a.ServiceConsoleURL) + objectMap["source"] = SourceTypeBackupFromTimestamp + populate(objectMap, "sourceId", a.SourceID) + populate(objectMap, "subnetId", a.SubnetID) + populate(objectMap, "supportedRegionsToCloneTo", a.SupportedRegionsToCloneTo) + populateTime[datetime.RFC3339](objectMap, "timeCreated", a.TimeCreated) + populate(objectMap, "timeDataGuardRoleChanged", a.TimeDataGuardRoleChanged) + populate(objectMap, "timeDeletionOfFreeAutonomousDatabase", a.TimeDeletionOfFreeAutonomousDatabase) + populateTime[datetime.RFC3339](objectMap, "timeDisasterRecoveryRoleChanged", a.TimeDisasterRecoveryRoleChanged) + populate(objectMap, "timeLocalDataGuardEnabled", a.TimeLocalDataGuardEnabled) + populateTime[datetime.RFC3339](objectMap, "timeMaintenanceBegin", a.TimeMaintenanceBegin) + populateTime[datetime.RFC3339](objectMap, "timeMaintenanceEnd", a.TimeMaintenanceEnd) + populate(objectMap, "timeOfLastFailover", a.TimeOfLastFailover) + populate(objectMap, "timeOfLastRefresh", a.TimeOfLastRefresh) + populate(objectMap, "timeOfLastRefreshPoint", a.TimeOfLastRefreshPoint) + populate(objectMap, "timeOfLastSwitchover", a.TimeOfLastSwitchover) + populate(objectMap, "timeReclamationOfFreeAutonomousDatabase", a.TimeReclamationOfFreeAutonomousDatabase) + populateTime[datetime.RFC3339](objectMap, "timestamp", a.Timestamp) + populate(objectMap, "useLatestAvailableBackupTimeStamp", a.UseLatestAvailableBackupTimeStamp) + populate(objectMap, "usedDataStorageSizeInGbs", a.UsedDataStorageSizeInGbs) + populate(objectMap, "usedDataStorageSizeInTbs", a.UsedDataStorageSizeInTbs) + populate(objectMap, "vnetId", a.VnetID) + populate(objectMap, "whitelistedIps", a.WhitelistedIPs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutonomousDatabaseFromBackupTimestampProperties. +func (a *AutonomousDatabaseFromBackupTimestampProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actualUsedDataStorageSizeInTbs": + err = unpopulate(val, "ActualUsedDataStorageSizeInTbs", &a.ActualUsedDataStorageSizeInTbs) + delete(rawMsg, key) + case "adminPassword": + err = unpopulate(val, "AdminPassword", &a.AdminPassword) + delete(rawMsg, key) + case "allocatedStorageSizeInTbs": + err = unpopulate(val, "AllocatedStorageSizeInTbs", &a.AllocatedStorageSizeInTbs) + delete(rawMsg, key) + case "apexDetails": + err = unpopulate(val, "ApexDetails", &a.ApexDetails) + delete(rawMsg, key) + case "autonomousDatabaseId": + err = unpopulate(val, "AutonomousDatabaseID", &a.AutonomousDatabaseID) + delete(rawMsg, key) + case "autonomousMaintenanceScheduleType": + err = unpopulate(val, "AutonomousMaintenanceScheduleType", &a.AutonomousMaintenanceScheduleType) + delete(rawMsg, key) + case "availableUpgradeVersions": + err = unpopulate(val, "AvailableUpgradeVersions", &a.AvailableUpgradeVersions) + delete(rawMsg, key) + case "backupRetentionPeriodInDays": + err = unpopulate(val, "BackupRetentionPeriodInDays", &a.BackupRetentionPeriodInDays) + delete(rawMsg, key) + case "cpuCoreCount": + err = unpopulate(val, "CPUCoreCount", &a.CPUCoreCount) + delete(rawMsg, key) + case "characterSet": + err = unpopulate(val, "CharacterSet", &a.CharacterSet) + delete(rawMsg, key) + case "cloneType": + err = unpopulate(val, "CloneType", &a.CloneType) + delete(rawMsg, key) + case "computeCount": + err = unpopulate(val, "ComputeCount", &a.ComputeCount) + delete(rawMsg, key) + case "computeModel": + err = unpopulate(val, "ComputeModel", &a.ComputeModel) + delete(rawMsg, key) + case "connectionStrings": + err = unpopulate(val, "ConnectionStrings", &a.ConnectionStrings) + delete(rawMsg, key) + case "connectionUrls": + err = unpopulate(val, "ConnectionUrls", &a.ConnectionUrls) + delete(rawMsg, key) + case "customerContacts": + err = unpopulate(val, "CustomerContacts", &a.CustomerContacts) + delete(rawMsg, key) + case "dataBaseType": + err = unpopulate(val, "DataBaseType", &a.DataBaseType) + delete(rawMsg, key) + case "dataSafeStatus": + err = unpopulate(val, "DataSafeStatus", &a.DataSafeStatus) + delete(rawMsg, key) + case "dataStorageSizeInGbs": + err = unpopulate(val, "DataStorageSizeInGbs", &a.DataStorageSizeInGbs) + delete(rawMsg, key) + case "dataStorageSizeInTbs": + err = unpopulate(val, "DataStorageSizeInTbs", &a.DataStorageSizeInTbs) + delete(rawMsg, key) + case "databaseEdition": + err = unpopulate(val, "DatabaseEdition", &a.DatabaseEdition) + delete(rawMsg, key) + case "dbVersion": + err = unpopulate(val, "DbVersion", &a.DbVersion) + delete(rawMsg, key) + case "dbWorkload": + err = unpopulate(val, "DbWorkload", &a.DbWorkload) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &a.DisplayName) + delete(rawMsg, key) + case "failedDataRecoveryInSeconds": + err = unpopulate(val, "FailedDataRecoveryInSeconds", &a.FailedDataRecoveryInSeconds) + delete(rawMsg, key) + case "inMemoryAreaInGbs": + err = unpopulate(val, "InMemoryAreaInGbs", &a.InMemoryAreaInGbs) + delete(rawMsg, key) + case "isAutoScalingEnabled": + err = unpopulate(val, "IsAutoScalingEnabled", &a.IsAutoScalingEnabled) + delete(rawMsg, key) + case "isAutoScalingForStorageEnabled": + err = unpopulate(val, "IsAutoScalingForStorageEnabled", &a.IsAutoScalingForStorageEnabled) + delete(rawMsg, key) + case "isLocalDataGuardEnabled": + err = unpopulate(val, "IsLocalDataGuardEnabled", &a.IsLocalDataGuardEnabled) + delete(rawMsg, key) + case "isMtlsConnectionRequired": + err = unpopulate(val, "IsMtlsConnectionRequired", &a.IsMtlsConnectionRequired) + delete(rawMsg, key) + case "isPreview": + err = unpopulate(val, "IsPreview", &a.IsPreview) + delete(rawMsg, key) + case "isPreviewVersionWithServiceTermsAccepted": + err = unpopulate(val, "IsPreviewVersionWithServiceTermsAccepted", &a.IsPreviewVersionWithServiceTermsAccepted) + delete(rawMsg, key) + case "isRemoteDataGuardEnabled": + err = unpopulate(val, "IsRemoteDataGuardEnabled", &a.IsRemoteDataGuardEnabled) + delete(rawMsg, key) + case "licenseModel": + err = unpopulate(val, "LicenseModel", &a.LicenseModel) + delete(rawMsg, key) + case "lifecycleDetails": + err = unpopulate(val, "LifecycleDetails", &a.LifecycleDetails) + delete(rawMsg, key) + case "lifecycleState": + err = unpopulate(val, "LifecycleState", &a.LifecycleState) + delete(rawMsg, key) + case "localAdgAutoFailoverMaxDataLossLimit": + err = unpopulate(val, "LocalAdgAutoFailoverMaxDataLossLimit", &a.LocalAdgAutoFailoverMaxDataLossLimit) + delete(rawMsg, key) + case "localDisasterRecoveryType": + err = unpopulate(val, "LocalDisasterRecoveryType", &a.LocalDisasterRecoveryType) + delete(rawMsg, key) + case "localStandbyDb": + err = unpopulate(val, "LocalStandbyDb", &a.LocalStandbyDb) + delete(rawMsg, key) + case "longTermBackupSchedule": + err = unpopulate(val, "LongTermBackupSchedule", &a.LongTermBackupSchedule) + delete(rawMsg, key) + case "memoryPerOracleComputeUnitInGbs": + err = unpopulate(val, "MemoryPerOracleComputeUnitInGbs", &a.MemoryPerOracleComputeUnitInGbs) + delete(rawMsg, key) + case "ncharacterSet": + err = unpopulate(val, "NcharacterSet", &a.NcharacterSet) + delete(rawMsg, key) + case "nextLongTermBackupTimeStamp": + err = unpopulateTime[datetime.RFC3339](val, "NextLongTermBackupTimeStamp", &a.NextLongTermBackupTimeStamp) + delete(rawMsg, key) + case "ociUrl": + err = unpopulate(val, "OciURL", &a.OciURL) + delete(rawMsg, key) + case "ocid": + err = unpopulate(val, "Ocid", &a.Ocid) + delete(rawMsg, key) + case "openMode": + err = unpopulate(val, "OpenMode", &a.OpenMode) + delete(rawMsg, key) + case "operationsInsightsStatus": + err = unpopulate(val, "OperationsInsightsStatus", &a.OperationsInsightsStatus) + delete(rawMsg, key) + case "peerDbId": + err = unpopulate(val, "PeerDbID", &a.PeerDbID) + delete(rawMsg, key) + case "peerDbIds": + err = unpopulate(val, "PeerDbIDs", &a.PeerDbIDs) + delete(rawMsg, key) + case "permissionLevel": + err = unpopulate(val, "PermissionLevel", &a.PermissionLevel) + delete(rawMsg, key) + case "privateEndpoint": + err = unpopulate(val, "PrivateEndpoint", &a.PrivateEndpoint) + delete(rawMsg, key) + case "privateEndpointIp": + err = unpopulate(val, "PrivateEndpointIP", &a.PrivateEndpointIP) + delete(rawMsg, key) + case "privateEndpointLabel": + err = unpopulate(val, "PrivateEndpointLabel", &a.PrivateEndpointLabel) + delete(rawMsg, key) + case "provisionableCpus": + err = unpopulate(val, "ProvisionableCpus", &a.ProvisionableCpus) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "remoteDisasterRecoveryConfiguration": + err = unpopulate(val, "RemoteDisasterRecoveryConfiguration", &a.RemoteDisasterRecoveryConfiguration) + delete(rawMsg, key) + case "role": + err = unpopulate(val, "Role", &a.Role) + delete(rawMsg, key) + case "sqlWebDeveloperUrl": + err = unpopulate(val, "SQLWebDeveloperURL", &a.SQLWebDeveloperURL) + delete(rawMsg, key) + case "scheduledOperationsList": + err = unpopulate(val, "ScheduledOperationsList", &a.ScheduledOperationsList) + delete(rawMsg, key) + case "serviceConsoleUrl": + err = unpopulate(val, "ServiceConsoleURL", &a.ServiceConsoleURL) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &a.Source) + delete(rawMsg, key) + case "sourceId": + err = unpopulate(val, "SourceID", &a.SourceID) + delete(rawMsg, key) + case "subnetId": + err = unpopulate(val, "SubnetID", &a.SubnetID) + delete(rawMsg, key) + case "supportedRegionsToCloneTo": + err = unpopulate(val, "SupportedRegionsToCloneTo", &a.SupportedRegionsToCloneTo) + delete(rawMsg, key) + case "timeCreated": + err = unpopulateTime[datetime.RFC3339](val, "TimeCreated", &a.TimeCreated) + delete(rawMsg, key) + case "timeDataGuardRoleChanged": + err = unpopulate(val, "TimeDataGuardRoleChanged", &a.TimeDataGuardRoleChanged) + delete(rawMsg, key) + case "timeDeletionOfFreeAutonomousDatabase": + err = unpopulate(val, "TimeDeletionOfFreeAutonomousDatabase", &a.TimeDeletionOfFreeAutonomousDatabase) + delete(rawMsg, key) + case "timeDisasterRecoveryRoleChanged": + err = unpopulateTime[datetime.RFC3339](val, "TimeDisasterRecoveryRoleChanged", &a.TimeDisasterRecoveryRoleChanged) + delete(rawMsg, key) + case "timeLocalDataGuardEnabled": + err = unpopulate(val, "TimeLocalDataGuardEnabled", &a.TimeLocalDataGuardEnabled) + delete(rawMsg, key) + case "timeMaintenanceBegin": + err = unpopulateTime[datetime.RFC3339](val, "TimeMaintenanceBegin", &a.TimeMaintenanceBegin) + delete(rawMsg, key) + case "timeMaintenanceEnd": + err = unpopulateTime[datetime.RFC3339](val, "TimeMaintenanceEnd", &a.TimeMaintenanceEnd) + delete(rawMsg, key) + case "timeOfLastFailover": + err = unpopulate(val, "TimeOfLastFailover", &a.TimeOfLastFailover) + delete(rawMsg, key) + case "timeOfLastRefresh": + err = unpopulate(val, "TimeOfLastRefresh", &a.TimeOfLastRefresh) + delete(rawMsg, key) + case "timeOfLastRefreshPoint": + err = unpopulate(val, "TimeOfLastRefreshPoint", &a.TimeOfLastRefreshPoint) + delete(rawMsg, key) + case "timeOfLastSwitchover": + err = unpopulate(val, "TimeOfLastSwitchover", &a.TimeOfLastSwitchover) + delete(rawMsg, key) + case "timeReclamationOfFreeAutonomousDatabase": + err = unpopulate(val, "TimeReclamationOfFreeAutonomousDatabase", &a.TimeReclamationOfFreeAutonomousDatabase) + delete(rawMsg, key) + case "timestamp": + err = unpopulateTime[datetime.RFC3339](val, "Timestamp", &a.Timestamp) + delete(rawMsg, key) + case "useLatestAvailableBackupTimeStamp": + err = unpopulate(val, "UseLatestAvailableBackupTimeStamp", &a.UseLatestAvailableBackupTimeStamp) + delete(rawMsg, key) + case "usedDataStorageSizeInGbs": + err = unpopulate(val, "UsedDataStorageSizeInGbs", &a.UsedDataStorageSizeInGbs) + delete(rawMsg, key) + case "usedDataStorageSizeInTbs": + err = unpopulate(val, "UsedDataStorageSizeInTbs", &a.UsedDataStorageSizeInTbs) + delete(rawMsg, key) + case "vnetId": + err = unpopulate(val, "VnetID", &a.VnetID) + delete(rawMsg, key) + case "whitelistedIps": + err = unpopulate(val, "WhitelistedIPs", &a.WhitelistedIPs) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutonomousDatabaseLifecycleAction. +func (a AutonomousDatabaseLifecycleAction) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "action", a.Action) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutonomousDatabaseLifecycleAction. +func (a *AutonomousDatabaseLifecycleAction) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "action": + err = unpopulate(val, "Action", &a.Action) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutonomousDatabaseListResult. +func (a AutonomousDatabaseListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutonomousDatabaseListResult. +func (a *AutonomousDatabaseListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &a.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutonomousDatabaseNationalCharacterSet. +func (a AutonomousDatabaseNationalCharacterSet) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutonomousDatabaseNationalCharacterSet. +func (a *AutonomousDatabaseNationalCharacterSet) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &a.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutonomousDatabaseNationalCharacterSetListResult. +func (a AutonomousDatabaseNationalCharacterSetListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutonomousDatabaseNationalCharacterSetListResult. +func (a *AutonomousDatabaseNationalCharacterSetListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &a.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutonomousDatabaseNationalCharacterSetProperties. +func (a AutonomousDatabaseNationalCharacterSetProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "characterSet", a.CharacterSet) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutonomousDatabaseNationalCharacterSetProperties. +func (a *AutonomousDatabaseNationalCharacterSetProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "characterSet": + err = unpopulate(val, "CharacterSet", &a.CharacterSet) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutonomousDatabaseProperties. +func (a AutonomousDatabaseProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actualUsedDataStorageSizeInTbs", a.ActualUsedDataStorageSizeInTbs) + populate(objectMap, "adminPassword", a.AdminPassword) + populate(objectMap, "allocatedStorageSizeInTbs", a.AllocatedStorageSizeInTbs) + populate(objectMap, "apexDetails", a.ApexDetails) + populate(objectMap, "autonomousDatabaseId", a.AutonomousDatabaseID) + populate(objectMap, "autonomousMaintenanceScheduleType", a.AutonomousMaintenanceScheduleType) + populate(objectMap, "availableUpgradeVersions", a.AvailableUpgradeVersions) + populate(objectMap, "backupRetentionPeriodInDays", a.BackupRetentionPeriodInDays) + populate(objectMap, "cpuCoreCount", a.CPUCoreCount) + populate(objectMap, "characterSet", a.CharacterSet) + populate(objectMap, "computeCount", a.ComputeCount) + populate(objectMap, "computeModel", a.ComputeModel) + populate(objectMap, "connectionStrings", a.ConnectionStrings) + populate(objectMap, "connectionUrls", a.ConnectionUrls) + populate(objectMap, "customerContacts", a.CustomerContacts) + objectMap["dataBaseType"] = DataBaseTypeRegular + populate(objectMap, "dataSafeStatus", a.DataSafeStatus) + populate(objectMap, "dataStorageSizeInGbs", a.DataStorageSizeInGbs) + populate(objectMap, "dataStorageSizeInTbs", a.DataStorageSizeInTbs) + populate(objectMap, "databaseEdition", a.DatabaseEdition) + populate(objectMap, "dbVersion", a.DbVersion) + populate(objectMap, "dbWorkload", a.DbWorkload) + populate(objectMap, "displayName", a.DisplayName) + populate(objectMap, "failedDataRecoveryInSeconds", a.FailedDataRecoveryInSeconds) + populate(objectMap, "inMemoryAreaInGbs", a.InMemoryAreaInGbs) + populate(objectMap, "isAutoScalingEnabled", a.IsAutoScalingEnabled) + populate(objectMap, "isAutoScalingForStorageEnabled", a.IsAutoScalingForStorageEnabled) + populate(objectMap, "isLocalDataGuardEnabled", a.IsLocalDataGuardEnabled) + populate(objectMap, "isMtlsConnectionRequired", a.IsMtlsConnectionRequired) + populate(objectMap, "isPreview", a.IsPreview) + populate(objectMap, "isPreviewVersionWithServiceTermsAccepted", a.IsPreviewVersionWithServiceTermsAccepted) + populate(objectMap, "isRemoteDataGuardEnabled", a.IsRemoteDataGuardEnabled) + populate(objectMap, "licenseModel", a.LicenseModel) + populate(objectMap, "lifecycleDetails", a.LifecycleDetails) + populate(objectMap, "lifecycleState", a.LifecycleState) + populate(objectMap, "localAdgAutoFailoverMaxDataLossLimit", a.LocalAdgAutoFailoverMaxDataLossLimit) + populate(objectMap, "localDisasterRecoveryType", a.LocalDisasterRecoveryType) + populate(objectMap, "localStandbyDb", a.LocalStandbyDb) + populate(objectMap, "longTermBackupSchedule", a.LongTermBackupSchedule) + populate(objectMap, "memoryPerOracleComputeUnitInGbs", a.MemoryPerOracleComputeUnitInGbs) + populate(objectMap, "ncharacterSet", a.NcharacterSet) + populateTime[datetime.RFC3339](objectMap, "nextLongTermBackupTimeStamp", a.NextLongTermBackupTimeStamp) + populate(objectMap, "ociUrl", a.OciURL) + populate(objectMap, "ocid", a.Ocid) + populate(objectMap, "openMode", a.OpenMode) + populate(objectMap, "operationsInsightsStatus", a.OperationsInsightsStatus) + populate(objectMap, "peerDbId", a.PeerDbID) + populate(objectMap, "peerDbIds", a.PeerDbIDs) + populate(objectMap, "permissionLevel", a.PermissionLevel) + populate(objectMap, "privateEndpoint", a.PrivateEndpoint) + populate(objectMap, "privateEndpointIp", a.PrivateEndpointIP) + populate(objectMap, "privateEndpointLabel", a.PrivateEndpointLabel) + populate(objectMap, "provisionableCpus", a.ProvisionableCpus) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "remoteDisasterRecoveryConfiguration", a.RemoteDisasterRecoveryConfiguration) + populate(objectMap, "role", a.Role) + populate(objectMap, "sqlWebDeveloperUrl", a.SQLWebDeveloperURL) + populate(objectMap, "scheduledOperationsList", a.ScheduledOperationsList) + populate(objectMap, "serviceConsoleUrl", a.ServiceConsoleURL) + populate(objectMap, "subnetId", a.SubnetID) + populate(objectMap, "supportedRegionsToCloneTo", a.SupportedRegionsToCloneTo) + populateTime[datetime.RFC3339](objectMap, "timeCreated", a.TimeCreated) + populate(objectMap, "timeDataGuardRoleChanged", a.TimeDataGuardRoleChanged) + populate(objectMap, "timeDeletionOfFreeAutonomousDatabase", a.TimeDeletionOfFreeAutonomousDatabase) + populateTime[datetime.RFC3339](objectMap, "timeDisasterRecoveryRoleChanged", a.TimeDisasterRecoveryRoleChanged) + populate(objectMap, "timeLocalDataGuardEnabled", a.TimeLocalDataGuardEnabled) + populateTime[datetime.RFC3339](objectMap, "timeMaintenanceBegin", a.TimeMaintenanceBegin) + populateTime[datetime.RFC3339](objectMap, "timeMaintenanceEnd", a.TimeMaintenanceEnd) + populate(objectMap, "timeOfLastFailover", a.TimeOfLastFailover) + populate(objectMap, "timeOfLastRefresh", a.TimeOfLastRefresh) + populate(objectMap, "timeOfLastRefreshPoint", a.TimeOfLastRefreshPoint) + populate(objectMap, "timeOfLastSwitchover", a.TimeOfLastSwitchover) + populate(objectMap, "timeReclamationOfFreeAutonomousDatabase", a.TimeReclamationOfFreeAutonomousDatabase) + populate(objectMap, "usedDataStorageSizeInGbs", a.UsedDataStorageSizeInGbs) + populate(objectMap, "usedDataStorageSizeInTbs", a.UsedDataStorageSizeInTbs) + populate(objectMap, "vnetId", a.VnetID) + populate(objectMap, "whitelistedIps", a.WhitelistedIPs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutonomousDatabaseProperties. +func (a *AutonomousDatabaseProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actualUsedDataStorageSizeInTbs": + err = unpopulate(val, "ActualUsedDataStorageSizeInTbs", &a.ActualUsedDataStorageSizeInTbs) + delete(rawMsg, key) + case "adminPassword": + err = unpopulate(val, "AdminPassword", &a.AdminPassword) + delete(rawMsg, key) + case "allocatedStorageSizeInTbs": + err = unpopulate(val, "AllocatedStorageSizeInTbs", &a.AllocatedStorageSizeInTbs) + delete(rawMsg, key) + case "apexDetails": + err = unpopulate(val, "ApexDetails", &a.ApexDetails) + delete(rawMsg, key) + case "autonomousDatabaseId": + err = unpopulate(val, "AutonomousDatabaseID", &a.AutonomousDatabaseID) + delete(rawMsg, key) + case "autonomousMaintenanceScheduleType": + err = unpopulate(val, "AutonomousMaintenanceScheduleType", &a.AutonomousMaintenanceScheduleType) + delete(rawMsg, key) + case "availableUpgradeVersions": + err = unpopulate(val, "AvailableUpgradeVersions", &a.AvailableUpgradeVersions) + delete(rawMsg, key) + case "backupRetentionPeriodInDays": + err = unpopulate(val, "BackupRetentionPeriodInDays", &a.BackupRetentionPeriodInDays) + delete(rawMsg, key) + case "cpuCoreCount": + err = unpopulate(val, "CPUCoreCount", &a.CPUCoreCount) + delete(rawMsg, key) + case "characterSet": + err = unpopulate(val, "CharacterSet", &a.CharacterSet) + delete(rawMsg, key) + case "computeCount": + err = unpopulate(val, "ComputeCount", &a.ComputeCount) + delete(rawMsg, key) + case "computeModel": + err = unpopulate(val, "ComputeModel", &a.ComputeModel) + delete(rawMsg, key) + case "connectionStrings": + err = unpopulate(val, "ConnectionStrings", &a.ConnectionStrings) + delete(rawMsg, key) + case "connectionUrls": + err = unpopulate(val, "ConnectionUrls", &a.ConnectionUrls) + delete(rawMsg, key) + case "customerContacts": + err = unpopulate(val, "CustomerContacts", &a.CustomerContacts) + delete(rawMsg, key) + case "dataBaseType": + err = unpopulate(val, "DataBaseType", &a.DataBaseType) + delete(rawMsg, key) + case "dataSafeStatus": + err = unpopulate(val, "DataSafeStatus", &a.DataSafeStatus) + delete(rawMsg, key) + case "dataStorageSizeInGbs": + err = unpopulate(val, "DataStorageSizeInGbs", &a.DataStorageSizeInGbs) + delete(rawMsg, key) + case "dataStorageSizeInTbs": + err = unpopulate(val, "DataStorageSizeInTbs", &a.DataStorageSizeInTbs) + delete(rawMsg, key) + case "databaseEdition": + err = unpopulate(val, "DatabaseEdition", &a.DatabaseEdition) + delete(rawMsg, key) + case "dbVersion": + err = unpopulate(val, "DbVersion", &a.DbVersion) + delete(rawMsg, key) + case "dbWorkload": + err = unpopulate(val, "DbWorkload", &a.DbWorkload) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &a.DisplayName) + delete(rawMsg, key) + case "failedDataRecoveryInSeconds": + err = unpopulate(val, "FailedDataRecoveryInSeconds", &a.FailedDataRecoveryInSeconds) + delete(rawMsg, key) + case "inMemoryAreaInGbs": + err = unpopulate(val, "InMemoryAreaInGbs", &a.InMemoryAreaInGbs) + delete(rawMsg, key) + case "isAutoScalingEnabled": + err = unpopulate(val, "IsAutoScalingEnabled", &a.IsAutoScalingEnabled) + delete(rawMsg, key) + case "isAutoScalingForStorageEnabled": + err = unpopulate(val, "IsAutoScalingForStorageEnabled", &a.IsAutoScalingForStorageEnabled) + delete(rawMsg, key) + case "isLocalDataGuardEnabled": + err = unpopulate(val, "IsLocalDataGuardEnabled", &a.IsLocalDataGuardEnabled) + delete(rawMsg, key) + case "isMtlsConnectionRequired": + err = unpopulate(val, "IsMtlsConnectionRequired", &a.IsMtlsConnectionRequired) + delete(rawMsg, key) + case "isPreview": + err = unpopulate(val, "IsPreview", &a.IsPreview) + delete(rawMsg, key) + case "isPreviewVersionWithServiceTermsAccepted": + err = unpopulate(val, "IsPreviewVersionWithServiceTermsAccepted", &a.IsPreviewVersionWithServiceTermsAccepted) + delete(rawMsg, key) + case "isRemoteDataGuardEnabled": + err = unpopulate(val, "IsRemoteDataGuardEnabled", &a.IsRemoteDataGuardEnabled) + delete(rawMsg, key) + case "licenseModel": + err = unpopulate(val, "LicenseModel", &a.LicenseModel) + delete(rawMsg, key) + case "lifecycleDetails": + err = unpopulate(val, "LifecycleDetails", &a.LifecycleDetails) + delete(rawMsg, key) + case "lifecycleState": + err = unpopulate(val, "LifecycleState", &a.LifecycleState) + delete(rawMsg, key) + case "localAdgAutoFailoverMaxDataLossLimit": + err = unpopulate(val, "LocalAdgAutoFailoverMaxDataLossLimit", &a.LocalAdgAutoFailoverMaxDataLossLimit) + delete(rawMsg, key) + case "localDisasterRecoveryType": + err = unpopulate(val, "LocalDisasterRecoveryType", &a.LocalDisasterRecoveryType) + delete(rawMsg, key) + case "localStandbyDb": + err = unpopulate(val, "LocalStandbyDb", &a.LocalStandbyDb) + delete(rawMsg, key) + case "longTermBackupSchedule": + err = unpopulate(val, "LongTermBackupSchedule", &a.LongTermBackupSchedule) + delete(rawMsg, key) + case "memoryPerOracleComputeUnitInGbs": + err = unpopulate(val, "MemoryPerOracleComputeUnitInGbs", &a.MemoryPerOracleComputeUnitInGbs) + delete(rawMsg, key) + case "ncharacterSet": + err = unpopulate(val, "NcharacterSet", &a.NcharacterSet) + delete(rawMsg, key) + case "nextLongTermBackupTimeStamp": + err = unpopulateTime[datetime.RFC3339](val, "NextLongTermBackupTimeStamp", &a.NextLongTermBackupTimeStamp) + delete(rawMsg, key) + case "ociUrl": + err = unpopulate(val, "OciURL", &a.OciURL) + delete(rawMsg, key) + case "ocid": + err = unpopulate(val, "Ocid", &a.Ocid) + delete(rawMsg, key) + case "openMode": + err = unpopulate(val, "OpenMode", &a.OpenMode) + delete(rawMsg, key) + case "operationsInsightsStatus": + err = unpopulate(val, "OperationsInsightsStatus", &a.OperationsInsightsStatus) + delete(rawMsg, key) + case "peerDbId": + err = unpopulate(val, "PeerDbID", &a.PeerDbID) + delete(rawMsg, key) + case "peerDbIds": + err = unpopulate(val, "PeerDbIDs", &a.PeerDbIDs) + delete(rawMsg, key) + case "permissionLevel": + err = unpopulate(val, "PermissionLevel", &a.PermissionLevel) + delete(rawMsg, key) + case "privateEndpoint": + err = unpopulate(val, "PrivateEndpoint", &a.PrivateEndpoint) + delete(rawMsg, key) + case "privateEndpointIp": + err = unpopulate(val, "PrivateEndpointIP", &a.PrivateEndpointIP) + delete(rawMsg, key) + case "privateEndpointLabel": + err = unpopulate(val, "PrivateEndpointLabel", &a.PrivateEndpointLabel) + delete(rawMsg, key) + case "provisionableCpus": + err = unpopulate(val, "ProvisionableCpus", &a.ProvisionableCpus) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + case "remoteDisasterRecoveryConfiguration": + err = unpopulate(val, "RemoteDisasterRecoveryConfiguration", &a.RemoteDisasterRecoveryConfiguration) + delete(rawMsg, key) + case "role": + err = unpopulate(val, "Role", &a.Role) + delete(rawMsg, key) + case "sqlWebDeveloperUrl": + err = unpopulate(val, "SQLWebDeveloperURL", &a.SQLWebDeveloperURL) + delete(rawMsg, key) + case "scheduledOperationsList": + err = unpopulate(val, "ScheduledOperationsList", &a.ScheduledOperationsList) + delete(rawMsg, key) + case "serviceConsoleUrl": + err = unpopulate(val, "ServiceConsoleURL", &a.ServiceConsoleURL) + delete(rawMsg, key) + case "subnetId": + err = unpopulate(val, "SubnetID", &a.SubnetID) + delete(rawMsg, key) + case "supportedRegionsToCloneTo": + err = unpopulate(val, "SupportedRegionsToCloneTo", &a.SupportedRegionsToCloneTo) + delete(rawMsg, key) + case "timeCreated": + err = unpopulateTime[datetime.RFC3339](val, "TimeCreated", &a.TimeCreated) + delete(rawMsg, key) + case "timeDataGuardRoleChanged": + err = unpopulate(val, "TimeDataGuardRoleChanged", &a.TimeDataGuardRoleChanged) + delete(rawMsg, key) + case "timeDeletionOfFreeAutonomousDatabase": + err = unpopulate(val, "TimeDeletionOfFreeAutonomousDatabase", &a.TimeDeletionOfFreeAutonomousDatabase) + delete(rawMsg, key) + case "timeDisasterRecoveryRoleChanged": + err = unpopulateTime[datetime.RFC3339](val, "TimeDisasterRecoveryRoleChanged", &a.TimeDisasterRecoveryRoleChanged) + delete(rawMsg, key) + case "timeLocalDataGuardEnabled": + err = unpopulate(val, "TimeLocalDataGuardEnabled", &a.TimeLocalDataGuardEnabled) + delete(rawMsg, key) + case "timeMaintenanceBegin": + err = unpopulateTime[datetime.RFC3339](val, "TimeMaintenanceBegin", &a.TimeMaintenanceBegin) + delete(rawMsg, key) + case "timeMaintenanceEnd": + err = unpopulateTime[datetime.RFC3339](val, "TimeMaintenanceEnd", &a.TimeMaintenanceEnd) + delete(rawMsg, key) + case "timeOfLastFailover": + err = unpopulate(val, "TimeOfLastFailover", &a.TimeOfLastFailover) + delete(rawMsg, key) + case "timeOfLastRefresh": + err = unpopulate(val, "TimeOfLastRefresh", &a.TimeOfLastRefresh) + delete(rawMsg, key) + case "timeOfLastRefreshPoint": + err = unpopulate(val, "TimeOfLastRefreshPoint", &a.TimeOfLastRefreshPoint) + delete(rawMsg, key) + case "timeOfLastSwitchover": + err = unpopulate(val, "TimeOfLastSwitchover", &a.TimeOfLastSwitchover) + delete(rawMsg, key) + case "timeReclamationOfFreeAutonomousDatabase": + err = unpopulate(val, "TimeReclamationOfFreeAutonomousDatabase", &a.TimeReclamationOfFreeAutonomousDatabase) + delete(rawMsg, key) + case "usedDataStorageSizeInGbs": + err = unpopulate(val, "UsedDataStorageSizeInGbs", &a.UsedDataStorageSizeInGbs) + delete(rawMsg, key) + case "usedDataStorageSizeInTbs": + err = unpopulate(val, "UsedDataStorageSizeInTbs", &a.UsedDataStorageSizeInTbs) + delete(rawMsg, key) + case "vnetId": + err = unpopulate(val, "VnetID", &a.VnetID) + delete(rawMsg, key) + case "whitelistedIps": + err = unpopulate(val, "WhitelistedIPs", &a.WhitelistedIPs) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutonomousDatabaseStandbySummary. +func (a AutonomousDatabaseStandbySummary) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "lagTimeInSeconds", a.LagTimeInSeconds) + populate(objectMap, "lifecycleDetails", a.LifecycleDetails) + populate(objectMap, "lifecycleState", a.LifecycleState) + populate(objectMap, "timeDataGuardRoleChanged", a.TimeDataGuardRoleChanged) + populate(objectMap, "timeDisasterRecoveryRoleChanged", a.TimeDisasterRecoveryRoleChanged) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutonomousDatabaseStandbySummary. +func (a *AutonomousDatabaseStandbySummary) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "lagTimeInSeconds": + err = unpopulate(val, "LagTimeInSeconds", &a.LagTimeInSeconds) + delete(rawMsg, key) + case "lifecycleDetails": + err = unpopulate(val, "LifecycleDetails", &a.LifecycleDetails) + delete(rawMsg, key) + case "lifecycleState": + err = unpopulate(val, "LifecycleState", &a.LifecycleState) + delete(rawMsg, key) + case "timeDataGuardRoleChanged": + err = unpopulate(val, "TimeDataGuardRoleChanged", &a.TimeDataGuardRoleChanged) + delete(rawMsg, key) + case "timeDisasterRecoveryRoleChanged": + err = unpopulate(val, "TimeDisasterRecoveryRoleChanged", &a.TimeDisasterRecoveryRoleChanged) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutonomousDatabaseUpdate. +func (a AutonomousDatabaseUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "tags", a.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutonomousDatabaseUpdate. +func (a *AutonomousDatabaseUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &a.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutonomousDatabaseUpdateProperties. +func (a AutonomousDatabaseUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "adminPassword", a.AdminPassword) + populate(objectMap, "autonomousMaintenanceScheduleType", a.AutonomousMaintenanceScheduleType) + populate(objectMap, "backupRetentionPeriodInDays", a.BackupRetentionPeriodInDays) + populate(objectMap, "cpuCoreCount", a.CPUCoreCount) + populate(objectMap, "computeCount", a.ComputeCount) + populate(objectMap, "customerContacts", a.CustomerContacts) + populate(objectMap, "dataStorageSizeInGbs", a.DataStorageSizeInGbs) + populate(objectMap, "dataStorageSizeInTbs", a.DataStorageSizeInTbs) + populate(objectMap, "databaseEdition", a.DatabaseEdition) + populate(objectMap, "displayName", a.DisplayName) + populate(objectMap, "isAutoScalingEnabled", a.IsAutoScalingEnabled) + populate(objectMap, "isAutoScalingForStorageEnabled", a.IsAutoScalingForStorageEnabled) + populate(objectMap, "isLocalDataGuardEnabled", a.IsLocalDataGuardEnabled) + populate(objectMap, "isMtlsConnectionRequired", a.IsMtlsConnectionRequired) + populate(objectMap, "licenseModel", a.LicenseModel) + populate(objectMap, "localAdgAutoFailoverMaxDataLossLimit", a.LocalAdgAutoFailoverMaxDataLossLimit) + populate(objectMap, "longTermBackupSchedule", a.LongTermBackupSchedule) + populate(objectMap, "openMode", a.OpenMode) + populate(objectMap, "peerDbId", a.PeerDbID) + populate(objectMap, "permissionLevel", a.PermissionLevel) + populate(objectMap, "role", a.Role) + populate(objectMap, "scheduledOperationsList", a.ScheduledOperationsList) + populate(objectMap, "whitelistedIps", a.WhitelistedIPs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutonomousDatabaseUpdateProperties. +func (a *AutonomousDatabaseUpdateProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "adminPassword": + err = unpopulate(val, "AdminPassword", &a.AdminPassword) + delete(rawMsg, key) + case "autonomousMaintenanceScheduleType": + err = unpopulate(val, "AutonomousMaintenanceScheduleType", &a.AutonomousMaintenanceScheduleType) + delete(rawMsg, key) + case "backupRetentionPeriodInDays": + err = unpopulate(val, "BackupRetentionPeriodInDays", &a.BackupRetentionPeriodInDays) + delete(rawMsg, key) + case "cpuCoreCount": + err = unpopulate(val, "CPUCoreCount", &a.CPUCoreCount) + delete(rawMsg, key) + case "computeCount": + err = unpopulate(val, "ComputeCount", &a.ComputeCount) + delete(rawMsg, key) + case "customerContacts": + err = unpopulate(val, "CustomerContacts", &a.CustomerContacts) + delete(rawMsg, key) + case "dataStorageSizeInGbs": + err = unpopulate(val, "DataStorageSizeInGbs", &a.DataStorageSizeInGbs) + delete(rawMsg, key) + case "dataStorageSizeInTbs": + err = unpopulate(val, "DataStorageSizeInTbs", &a.DataStorageSizeInTbs) + delete(rawMsg, key) + case "databaseEdition": + err = unpopulate(val, "DatabaseEdition", &a.DatabaseEdition) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &a.DisplayName) + delete(rawMsg, key) + case "isAutoScalingEnabled": + err = unpopulate(val, "IsAutoScalingEnabled", &a.IsAutoScalingEnabled) + delete(rawMsg, key) + case "isAutoScalingForStorageEnabled": + err = unpopulate(val, "IsAutoScalingForStorageEnabled", &a.IsAutoScalingForStorageEnabled) + delete(rawMsg, key) + case "isLocalDataGuardEnabled": + err = unpopulate(val, "IsLocalDataGuardEnabled", &a.IsLocalDataGuardEnabled) + delete(rawMsg, key) + case "isMtlsConnectionRequired": + err = unpopulate(val, "IsMtlsConnectionRequired", &a.IsMtlsConnectionRequired) + delete(rawMsg, key) + case "licenseModel": + err = unpopulate(val, "LicenseModel", &a.LicenseModel) + delete(rawMsg, key) + case "localAdgAutoFailoverMaxDataLossLimit": + err = unpopulate(val, "LocalAdgAutoFailoverMaxDataLossLimit", &a.LocalAdgAutoFailoverMaxDataLossLimit) + delete(rawMsg, key) + case "longTermBackupSchedule": + err = unpopulate(val, "LongTermBackupSchedule", &a.LongTermBackupSchedule) + delete(rawMsg, key) + case "openMode": + err = unpopulate(val, "OpenMode", &a.OpenMode) + delete(rawMsg, key) + case "peerDbId": + err = unpopulate(val, "PeerDbID", &a.PeerDbID) + delete(rawMsg, key) + case "permissionLevel": + err = unpopulate(val, "PermissionLevel", &a.PermissionLevel) + delete(rawMsg, key) + case "role": + err = unpopulate(val, "Role", &a.Role) + delete(rawMsg, key) + case "scheduledOperationsList": + err = unpopulate(val, "ScheduledOperationsList", &a.ScheduledOperationsList) + delete(rawMsg, key) + case "whitelistedIps": + err = unpopulate(val, "WhitelistedIPs", &a.WhitelistedIPs) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutonomousDatabaseWalletFile. +func (a AutonomousDatabaseWalletFile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "walletFiles", a.WalletFiles) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutonomousDatabaseWalletFile. +func (a *AutonomousDatabaseWalletFile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "walletFiles": + err = unpopulate(val, "WalletFiles", &a.WalletFiles) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutonomousDbVersion. +func (a AutonomousDbVersion) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutonomousDbVersion. +func (a *AutonomousDbVersion) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &a.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutonomousDbVersionListResult. +func (a AutonomousDbVersionListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutonomousDbVersionListResult. +func (a *AutonomousDbVersionListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &a.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &a.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AutonomousDbVersionProperties. +func (a AutonomousDbVersionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dbWorkload", a.DbWorkload) + populate(objectMap, "isDefaultForFree", a.IsDefaultForFree) + populate(objectMap, "isDefaultForPaid", a.IsDefaultForPaid) + populate(objectMap, "isFreeTierEnabled", a.IsFreeTierEnabled) + populate(objectMap, "isPaidEnabled", a.IsPaidEnabled) + populate(objectMap, "version", a.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AutonomousDbVersionProperties. +func (a *AutonomousDbVersionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "dbWorkload": + err = unpopulate(val, "DbWorkload", &a.DbWorkload) + delete(rawMsg, key) + case "isDefaultForFree": + err = unpopulate(val, "IsDefaultForFree", &a.IsDefaultForFree) + delete(rawMsg, key) + case "isDefaultForPaid": + err = unpopulate(val, "IsDefaultForPaid", &a.IsDefaultForPaid) + delete(rawMsg, key) + case "isFreeTierEnabled": + err = unpopulate(val, "IsFreeTierEnabled", &a.IsFreeTierEnabled) + delete(rawMsg, key) + case "isPaidEnabled": + err = unpopulate(val, "IsPaidEnabled", &a.IsPaidEnabled) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &a.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AzureSubscriptions. +func (a AzureSubscriptions) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "azureSubscriptionIds", a.AzureSubscriptionIDs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureSubscriptions. +func (a *AzureSubscriptions) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "azureSubscriptionIds": + err = unpopulate(val, "AzureSubscriptionIDs", &a.AzureSubscriptionIDs) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CloudAccountDetails. +func (c CloudAccountDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "cloudAccountHomeRegion", c.CloudAccountHomeRegion) + populate(objectMap, "cloudAccountName", c.CloudAccountName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudAccountDetails. +func (c *CloudAccountDetails) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "cloudAccountHomeRegion": + err = unpopulate(val, "CloudAccountHomeRegion", &c.CloudAccountHomeRegion) + delete(rawMsg, key) + case "cloudAccountName": + err = unpopulate(val, "CloudAccountName", &c.CloudAccountName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CloudExadataInfrastructure. +func (c CloudExadataInfrastructure) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", c.ID) + populate(objectMap, "location", c.Location) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "systemData", c.SystemData) + populate(objectMap, "tags", c.Tags) + populate(objectMap, "type", c.Type) + populate(objectMap, "zones", c.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudExadataInfrastructure. +func (c *CloudExadataInfrastructure) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &c.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &c.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &c.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + case "zones": + err = unpopulate(val, "Zones", &c.Zones) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CloudExadataInfrastructureListResult. +func (c CloudExadataInfrastructureListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", c.NextLink) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudExadataInfrastructureListResult. +func (c *CloudExadataInfrastructureListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &c.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &c.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CloudExadataInfrastructureProperties. +func (c CloudExadataInfrastructureProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "activatedStorageCount", c.ActivatedStorageCount) + populate(objectMap, "additionalStorageCount", c.AdditionalStorageCount) + populate(objectMap, "availableStorageSizeInGbs", c.AvailableStorageSizeInGbs) + populate(objectMap, "cpuCount", c.CPUCount) + populate(objectMap, "computeCount", c.ComputeCount) + populate(objectMap, "computeModel", c.ComputeModel) + populate(objectMap, "customerContacts", c.CustomerContacts) + populate(objectMap, "dataStorageSizeInTbs", c.DataStorageSizeInTbs) + populate(objectMap, "databaseServerType", c.DatabaseServerType) + populate(objectMap, "dbNodeStorageSizeInGbs", c.DbNodeStorageSizeInGbs) + populate(objectMap, "dbServerVersion", c.DbServerVersion) + populate(objectMap, "definedFileSystemConfiguration", c.DefinedFileSystemConfiguration) + populate(objectMap, "displayName", c.DisplayName) + populate(objectMap, "estimatedPatchingTime", c.EstimatedPatchingTime) + populate(objectMap, "exascaleConfig", c.ExascaleConfig) + populate(objectMap, "lastMaintenanceRunId", c.LastMaintenanceRunID) + populate(objectMap, "lifecycleDetails", c.LifecycleDetails) + populate(objectMap, "lifecycleState", c.LifecycleState) + populate(objectMap, "maintenanceWindow", c.MaintenanceWindow) + populate(objectMap, "maxCpuCount", c.MaxCPUCount) + populate(objectMap, "maxDataStorageInTbs", c.MaxDataStorageInTbs) + populate(objectMap, "maxDbNodeStorageSizeInGbs", c.MaxDbNodeStorageSizeInGbs) + populate(objectMap, "maxMemoryInGbs", c.MaxMemoryInGbs) + populate(objectMap, "memorySizeInGbs", c.MemorySizeInGbs) + populate(objectMap, "monthlyDbServerVersion", c.MonthlyDbServerVersion) + populate(objectMap, "monthlyStorageServerVersion", c.MonthlyStorageServerVersion) + populate(objectMap, "nextMaintenanceRunId", c.NextMaintenanceRunID) + populate(objectMap, "ociUrl", c.OciURL) + populate(objectMap, "ocid", c.Ocid) + populate(objectMap, "provisioningState", c.ProvisioningState) + populate(objectMap, "shape", c.Shape) + populate(objectMap, "storageCount", c.StorageCount) + populate(objectMap, "storageServerType", c.StorageServerType) + populate(objectMap, "storageServerVersion", c.StorageServerVersion) + populate(objectMap, "timeCreated", c.TimeCreated) + populate(objectMap, "totalStorageSizeInGbs", c.TotalStorageSizeInGbs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudExadataInfrastructureProperties. +func (c *CloudExadataInfrastructureProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "activatedStorageCount": + err = unpopulate(val, "ActivatedStorageCount", &c.ActivatedStorageCount) + delete(rawMsg, key) + case "additionalStorageCount": + err = unpopulate(val, "AdditionalStorageCount", &c.AdditionalStorageCount) + delete(rawMsg, key) + case "availableStorageSizeInGbs": + err = unpopulate(val, "AvailableStorageSizeInGbs", &c.AvailableStorageSizeInGbs) + delete(rawMsg, key) + case "cpuCount": + err = unpopulate(val, "CPUCount", &c.CPUCount) + delete(rawMsg, key) + case "computeCount": + err = unpopulate(val, "ComputeCount", &c.ComputeCount) + delete(rawMsg, key) + case "computeModel": + err = unpopulate(val, "ComputeModel", &c.ComputeModel) + delete(rawMsg, key) + case "customerContacts": + err = unpopulate(val, "CustomerContacts", &c.CustomerContacts) + delete(rawMsg, key) + case "dataStorageSizeInTbs": + err = unpopulate(val, "DataStorageSizeInTbs", &c.DataStorageSizeInTbs) + delete(rawMsg, key) + case "databaseServerType": + err = unpopulate(val, "DatabaseServerType", &c.DatabaseServerType) + delete(rawMsg, key) + case "dbNodeStorageSizeInGbs": + err = unpopulate(val, "DbNodeStorageSizeInGbs", &c.DbNodeStorageSizeInGbs) + delete(rawMsg, key) + case "dbServerVersion": + err = unpopulate(val, "DbServerVersion", &c.DbServerVersion) + delete(rawMsg, key) + case "definedFileSystemConfiguration": + err = unpopulate(val, "DefinedFileSystemConfiguration", &c.DefinedFileSystemConfiguration) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &c.DisplayName) + delete(rawMsg, key) + case "estimatedPatchingTime": + err = unpopulate(val, "EstimatedPatchingTime", &c.EstimatedPatchingTime) + delete(rawMsg, key) + case "exascaleConfig": + err = unpopulate(val, "ExascaleConfig", &c.ExascaleConfig) + delete(rawMsg, key) + case "lastMaintenanceRunId": + err = unpopulate(val, "LastMaintenanceRunID", &c.LastMaintenanceRunID) + delete(rawMsg, key) + case "lifecycleDetails": + err = unpopulate(val, "LifecycleDetails", &c.LifecycleDetails) + delete(rawMsg, key) + case "lifecycleState": + err = unpopulate(val, "LifecycleState", &c.LifecycleState) + delete(rawMsg, key) + case "maintenanceWindow": + err = unpopulate(val, "MaintenanceWindow", &c.MaintenanceWindow) + delete(rawMsg, key) + case "maxCpuCount": + err = unpopulate(val, "MaxCPUCount", &c.MaxCPUCount) + delete(rawMsg, key) + case "maxDataStorageInTbs": + err = unpopulate(val, "MaxDataStorageInTbs", &c.MaxDataStorageInTbs) + delete(rawMsg, key) + case "maxDbNodeStorageSizeInGbs": + err = unpopulate(val, "MaxDbNodeStorageSizeInGbs", &c.MaxDbNodeStorageSizeInGbs) + delete(rawMsg, key) + case "maxMemoryInGbs": + err = unpopulate(val, "MaxMemoryInGbs", &c.MaxMemoryInGbs) + delete(rawMsg, key) + case "memorySizeInGbs": + err = unpopulate(val, "MemorySizeInGbs", &c.MemorySizeInGbs) + delete(rawMsg, key) + case "monthlyDbServerVersion": + err = unpopulate(val, "MonthlyDbServerVersion", &c.MonthlyDbServerVersion) + delete(rawMsg, key) + case "monthlyStorageServerVersion": + err = unpopulate(val, "MonthlyStorageServerVersion", &c.MonthlyStorageServerVersion) + delete(rawMsg, key) + case "nextMaintenanceRunId": + err = unpopulate(val, "NextMaintenanceRunID", &c.NextMaintenanceRunID) + delete(rawMsg, key) + case "ociUrl": + err = unpopulate(val, "OciURL", &c.OciURL) + delete(rawMsg, key) + case "ocid": + err = unpopulate(val, "Ocid", &c.Ocid) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &c.ProvisioningState) + delete(rawMsg, key) + case "shape": + err = unpopulate(val, "Shape", &c.Shape) + delete(rawMsg, key) + case "storageCount": + err = unpopulate(val, "StorageCount", &c.StorageCount) + delete(rawMsg, key) + case "storageServerType": + err = unpopulate(val, "StorageServerType", &c.StorageServerType) + delete(rawMsg, key) + case "storageServerVersion": + err = unpopulate(val, "StorageServerVersion", &c.StorageServerVersion) + delete(rawMsg, key) + case "timeCreated": + err = unpopulate(val, "TimeCreated", &c.TimeCreated) + delete(rawMsg, key) + case "totalStorageSizeInGbs": + err = unpopulate(val, "TotalStorageSizeInGbs", &c.TotalStorageSizeInGbs) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CloudExadataInfrastructureUpdate. +func (c CloudExadataInfrastructureUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "tags", c.Tags) + populate(objectMap, "zones", c.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudExadataInfrastructureUpdate. +func (c *CloudExadataInfrastructureUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &c.Tags) + delete(rawMsg, key) + case "zones": + err = unpopulate(val, "Zones", &c.Zones) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CloudExadataInfrastructureUpdateProperties. +func (c CloudExadataInfrastructureUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "computeCount", c.ComputeCount) + populate(objectMap, "customerContacts", c.CustomerContacts) + populate(objectMap, "displayName", c.DisplayName) + populate(objectMap, "maintenanceWindow", c.MaintenanceWindow) + populate(objectMap, "storageCount", c.StorageCount) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudExadataInfrastructureUpdateProperties. +func (c *CloudExadataInfrastructureUpdateProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "computeCount": + err = unpopulate(val, "ComputeCount", &c.ComputeCount) + delete(rawMsg, key) + case "customerContacts": + err = unpopulate(val, "CustomerContacts", &c.CustomerContacts) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &c.DisplayName) + delete(rawMsg, key) + case "maintenanceWindow": + err = unpopulate(val, "MaintenanceWindow", &c.MaintenanceWindow) + delete(rawMsg, key) + case "storageCount": + err = unpopulate(val, "StorageCount", &c.StorageCount) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CloudVMCluster. +func (c CloudVMCluster) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", c.ID) + populate(objectMap, "location", c.Location) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "systemData", c.SystemData) + populate(objectMap, "tags", c.Tags) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudVMCluster. +func (c *CloudVMCluster) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &c.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &c.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &c.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CloudVMClusterListResult. +func (c CloudVMClusterListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", c.NextLink) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudVMClusterListResult. +func (c *CloudVMClusterListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &c.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &c.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CloudVMClusterProperties. +func (c CloudVMClusterProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "backupSubnetCidr", c.BackupSubnetCidr) + populate(objectMap, "cpuCoreCount", c.CPUCoreCount) + populate(objectMap, "cloudExadataInfrastructureId", c.CloudExadataInfrastructureID) + populate(objectMap, "clusterName", c.ClusterName) + populate(objectMap, "compartmentId", c.CompartmentID) + populate(objectMap, "computeModel", c.ComputeModel) + populate(objectMap, "computeNodes", c.ComputeNodes) + populate(objectMap, "dataCollectionOptions", c.DataCollectionOptions) + populate(objectMap, "dataStoragePercentage", c.DataStoragePercentage) + populate(objectMap, "dataStorageSizeInTbs", c.DataStorageSizeInTbs) + populate(objectMap, "dbNodeStorageSizeInGbs", c.DbNodeStorageSizeInGbs) + populate(objectMap, "dbServers", c.DbServers) + populate(objectMap, "diskRedundancy", c.DiskRedundancy) + populate(objectMap, "displayName", c.DisplayName) + populate(objectMap, "domain", c.Domain) + populate(objectMap, "exascaleDbStorageVaultId", c.ExascaleDbStorageVaultID) + populate(objectMap, "fileSystemConfigurationDetails", c.FileSystemConfigurationDetails) + populate(objectMap, "giVersion", c.GiVersion) + populate(objectMap, "hostname", c.Hostname) + populate(objectMap, "iormConfigCache", c.IormConfigCache) + populate(objectMap, "isLocalBackupEnabled", c.IsLocalBackupEnabled) + populate(objectMap, "isSparseDiskgroupEnabled", c.IsSparseDiskgroupEnabled) + populate(objectMap, "lastUpdateHistoryEntryId", c.LastUpdateHistoryEntryID) + populate(objectMap, "licenseModel", c.LicenseModel) + populate(objectMap, "lifecycleDetails", c.LifecycleDetails) + populate(objectMap, "lifecycleState", c.LifecycleState) + populate(objectMap, "listenerPort", c.ListenerPort) + populate(objectMap, "memorySizeInGbs", c.MemorySizeInGbs) + populate(objectMap, "nodeCount", c.NodeCount) + populate(objectMap, "nsgCidrs", c.NsgCidrs) + populate(objectMap, "nsgUrl", c.NsgURL) + populate(objectMap, "ociUrl", c.OciURL) + populate(objectMap, "ocid", c.Ocid) + populate(objectMap, "ocpuCount", c.OcpuCount) + populate(objectMap, "provisioningState", c.ProvisioningState) + populate(objectMap, "sshPublicKeys", c.SSHPublicKeys) + populate(objectMap, "scanDnsName", c.ScanDNSName) + populate(objectMap, "scanDnsRecordId", c.ScanDNSRecordID) + populate(objectMap, "scanIpIds", c.ScanIPIDs) + populate(objectMap, "scanListenerPortTcp", c.ScanListenerPortTCP) + populate(objectMap, "scanListenerPortTcpSsl", c.ScanListenerPortTCPSSL) + populate(objectMap, "shape", c.Shape) + populate(objectMap, "storageManagementType", c.StorageManagementType) + populate(objectMap, "storageSizeInGbs", c.StorageSizeInGbs) + populate(objectMap, "subnetId", c.SubnetID) + populate(objectMap, "subnetOcid", c.SubnetOcid) + populate(objectMap, "systemVersion", c.SystemVersion) + populateTime[datetime.RFC3339](objectMap, "timeCreated", c.TimeCreated) + populate(objectMap, "timeZone", c.TimeZone) + populate(objectMap, "vipIds", c.VipIDs) + populate(objectMap, "vnetId", c.VnetID) + populate(objectMap, "zoneId", c.ZoneID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudVMClusterProperties. +func (c *CloudVMClusterProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "backupSubnetCidr": + err = unpopulate(val, "BackupSubnetCidr", &c.BackupSubnetCidr) + delete(rawMsg, key) + case "cpuCoreCount": + err = unpopulate(val, "CPUCoreCount", &c.CPUCoreCount) + delete(rawMsg, key) + case "cloudExadataInfrastructureId": + err = unpopulate(val, "CloudExadataInfrastructureID", &c.CloudExadataInfrastructureID) + delete(rawMsg, key) + case "clusterName": + err = unpopulate(val, "ClusterName", &c.ClusterName) + delete(rawMsg, key) + case "compartmentId": + err = unpopulate(val, "CompartmentID", &c.CompartmentID) + delete(rawMsg, key) + case "computeModel": + err = unpopulate(val, "ComputeModel", &c.ComputeModel) + delete(rawMsg, key) + case "computeNodes": + err = unpopulate(val, "ComputeNodes", &c.ComputeNodes) + delete(rawMsg, key) + case "dataCollectionOptions": + err = unpopulate(val, "DataCollectionOptions", &c.DataCollectionOptions) + delete(rawMsg, key) + case "dataStoragePercentage": + err = unpopulate(val, "DataStoragePercentage", &c.DataStoragePercentage) + delete(rawMsg, key) + case "dataStorageSizeInTbs": + err = unpopulate(val, "DataStorageSizeInTbs", &c.DataStorageSizeInTbs) + delete(rawMsg, key) + case "dbNodeStorageSizeInGbs": + err = unpopulate(val, "DbNodeStorageSizeInGbs", &c.DbNodeStorageSizeInGbs) + delete(rawMsg, key) + case "dbServers": + err = unpopulate(val, "DbServers", &c.DbServers) + delete(rawMsg, key) + case "diskRedundancy": + err = unpopulate(val, "DiskRedundancy", &c.DiskRedundancy) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &c.DisplayName) + delete(rawMsg, key) + case "domain": + err = unpopulate(val, "Domain", &c.Domain) + delete(rawMsg, key) + case "exascaleDbStorageVaultId": + err = unpopulate(val, "ExascaleDbStorageVaultID", &c.ExascaleDbStorageVaultID) + delete(rawMsg, key) + case "fileSystemConfigurationDetails": + err = unpopulate(val, "FileSystemConfigurationDetails", &c.FileSystemConfigurationDetails) + delete(rawMsg, key) + case "giVersion": + err = unpopulate(val, "GiVersion", &c.GiVersion) + delete(rawMsg, key) + case "hostname": + err = unpopulate(val, "Hostname", &c.Hostname) + delete(rawMsg, key) + case "iormConfigCache": + err = unpopulate(val, "IormConfigCache", &c.IormConfigCache) + delete(rawMsg, key) + case "isLocalBackupEnabled": + err = unpopulate(val, "IsLocalBackupEnabled", &c.IsLocalBackupEnabled) + delete(rawMsg, key) + case "isSparseDiskgroupEnabled": + err = unpopulate(val, "IsSparseDiskgroupEnabled", &c.IsSparseDiskgroupEnabled) + delete(rawMsg, key) + case "lastUpdateHistoryEntryId": + err = unpopulate(val, "LastUpdateHistoryEntryID", &c.LastUpdateHistoryEntryID) + delete(rawMsg, key) + case "licenseModel": + err = unpopulate(val, "LicenseModel", &c.LicenseModel) + delete(rawMsg, key) + case "lifecycleDetails": + err = unpopulate(val, "LifecycleDetails", &c.LifecycleDetails) + delete(rawMsg, key) + case "lifecycleState": + err = unpopulate(val, "LifecycleState", &c.LifecycleState) + delete(rawMsg, key) + case "listenerPort": + err = unpopulate(val, "ListenerPort", &c.ListenerPort) + delete(rawMsg, key) + case "memorySizeInGbs": + err = unpopulate(val, "MemorySizeInGbs", &c.MemorySizeInGbs) + delete(rawMsg, key) + case "nodeCount": + err = unpopulate(val, "NodeCount", &c.NodeCount) + delete(rawMsg, key) + case "nsgCidrs": + err = unpopulate(val, "NsgCidrs", &c.NsgCidrs) + delete(rawMsg, key) + case "nsgUrl": + err = unpopulate(val, "NsgURL", &c.NsgURL) + delete(rawMsg, key) + case "ociUrl": + err = unpopulate(val, "OciURL", &c.OciURL) + delete(rawMsg, key) + case "ocid": + err = unpopulate(val, "Ocid", &c.Ocid) + delete(rawMsg, key) + case "ocpuCount": + err = unpopulate(val, "OcpuCount", &c.OcpuCount) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &c.ProvisioningState) + delete(rawMsg, key) + case "sshPublicKeys": + err = unpopulate(val, "SSHPublicKeys", &c.SSHPublicKeys) + delete(rawMsg, key) + case "scanDnsName": + err = unpopulate(val, "ScanDNSName", &c.ScanDNSName) + delete(rawMsg, key) + case "scanDnsRecordId": + err = unpopulate(val, "ScanDNSRecordID", &c.ScanDNSRecordID) + delete(rawMsg, key) + case "scanIpIds": + err = unpopulate(val, "ScanIPIDs", &c.ScanIPIDs) + delete(rawMsg, key) + case "scanListenerPortTcp": + err = unpopulate(val, "ScanListenerPortTCP", &c.ScanListenerPortTCP) + delete(rawMsg, key) + case "scanListenerPortTcpSsl": + err = unpopulate(val, "ScanListenerPortTCPSSL", &c.ScanListenerPortTCPSSL) + delete(rawMsg, key) + case "shape": + err = unpopulate(val, "Shape", &c.Shape) + delete(rawMsg, key) + case "storageManagementType": + err = unpopulate(val, "StorageManagementType", &c.StorageManagementType) + delete(rawMsg, key) + case "storageSizeInGbs": + err = unpopulate(val, "StorageSizeInGbs", &c.StorageSizeInGbs) + delete(rawMsg, key) + case "subnetId": + err = unpopulate(val, "SubnetID", &c.SubnetID) + delete(rawMsg, key) + case "subnetOcid": + err = unpopulate(val, "SubnetOcid", &c.SubnetOcid) + delete(rawMsg, key) + case "systemVersion": + err = unpopulate(val, "SystemVersion", &c.SystemVersion) + delete(rawMsg, key) + case "timeCreated": + err = unpopulateTime[datetime.RFC3339](val, "TimeCreated", &c.TimeCreated) + delete(rawMsg, key) + case "timeZone": + err = unpopulate(val, "TimeZone", &c.TimeZone) + delete(rawMsg, key) + case "vipIds": + err = unpopulate(val, "VipIDs", &c.VipIDs) + delete(rawMsg, key) + case "vnetId": + err = unpopulate(val, "VnetID", &c.VnetID) + delete(rawMsg, key) + case "zoneId": + err = unpopulate(val, "ZoneID", &c.ZoneID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CloudVMClusterUpdate. +func (c CloudVMClusterUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "tags", c.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudVMClusterUpdate. +func (c *CloudVMClusterUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &c.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CloudVMClusterUpdateProperties. +func (c CloudVMClusterUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "cpuCoreCount", c.CPUCoreCount) + populate(objectMap, "computeNodes", c.ComputeNodes) + populate(objectMap, "dataCollectionOptions", c.DataCollectionOptions) + populate(objectMap, "dataStorageSizeInTbs", c.DataStorageSizeInTbs) + populate(objectMap, "dbNodeStorageSizeInGbs", c.DbNodeStorageSizeInGbs) + populate(objectMap, "displayName", c.DisplayName) + populate(objectMap, "fileSystemConfigurationDetails", c.FileSystemConfigurationDetails) + populate(objectMap, "licenseModel", c.LicenseModel) + populate(objectMap, "memorySizeInGbs", c.MemorySizeInGbs) + populate(objectMap, "ocpuCount", c.OcpuCount) + populate(objectMap, "sshPublicKeys", c.SSHPublicKeys) + populate(objectMap, "storageSizeInGbs", c.StorageSizeInGbs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CloudVMClusterUpdateProperties. +func (c *CloudVMClusterUpdateProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "cpuCoreCount": + err = unpopulate(val, "CPUCoreCount", &c.CPUCoreCount) + delete(rawMsg, key) + case "computeNodes": + err = unpopulate(val, "ComputeNodes", &c.ComputeNodes) + delete(rawMsg, key) + case "dataCollectionOptions": + err = unpopulate(val, "DataCollectionOptions", &c.DataCollectionOptions) + delete(rawMsg, key) + case "dataStorageSizeInTbs": + err = unpopulate(val, "DataStorageSizeInTbs", &c.DataStorageSizeInTbs) + delete(rawMsg, key) + case "dbNodeStorageSizeInGbs": + err = unpopulate(val, "DbNodeStorageSizeInGbs", &c.DbNodeStorageSizeInGbs) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &c.DisplayName) + delete(rawMsg, key) + case "fileSystemConfigurationDetails": + err = unpopulate(val, "FileSystemConfigurationDetails", &c.FileSystemConfigurationDetails) + delete(rawMsg, key) + case "licenseModel": + err = unpopulate(val, "LicenseModel", &c.LicenseModel) + delete(rawMsg, key) + case "memorySizeInGbs": + err = unpopulate(val, "MemorySizeInGbs", &c.MemorySizeInGbs) + delete(rawMsg, key) + case "ocpuCount": + err = unpopulate(val, "OcpuCount", &c.OcpuCount) + delete(rawMsg, key) + case "sshPublicKeys": + err = unpopulate(val, "SSHPublicKeys", &c.SSHPublicKeys) + delete(rawMsg, key) + case "storageSizeInGbs": + err = unpopulate(val, "StorageSizeInGbs", &c.StorageSizeInGbs) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConfigureExascaleCloudExadataInfrastructureDetails. +func (c ConfigureExascaleCloudExadataInfrastructureDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "totalStorageInGbs", c.TotalStorageInGbs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConfigureExascaleCloudExadataInfrastructureDetails. +func (c *ConfigureExascaleCloudExadataInfrastructureDetails) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "totalStorageInGbs": + err = unpopulate(val, "TotalStorageInGbs", &c.TotalStorageInGbs) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConnectionStringType. +func (c ConnectionStringType) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "allConnectionStrings", c.AllConnectionStrings) + populate(objectMap, "dedicated", c.Dedicated) + populate(objectMap, "high", c.High) + populate(objectMap, "low", c.Low) + populate(objectMap, "medium", c.Medium) + populate(objectMap, "profiles", c.Profiles) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionStringType. +func (c *ConnectionStringType) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "allConnectionStrings": + err = unpopulate(val, "AllConnectionStrings", &c.AllConnectionStrings) + delete(rawMsg, key) + case "dedicated": + err = unpopulate(val, "Dedicated", &c.Dedicated) + delete(rawMsg, key) + case "high": + err = unpopulate(val, "High", &c.High) + delete(rawMsg, key) + case "low": + err = unpopulate(val, "Low", &c.Low) + delete(rawMsg, key) + case "medium": + err = unpopulate(val, "Medium", &c.Medium) + delete(rawMsg, key) + case "profiles": + err = unpopulate(val, "Profiles", &c.Profiles) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConnectionURLType. +func (c ConnectionURLType) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "apexUrl", c.ApexURL) + populate(objectMap, "databaseTransformsUrl", c.DatabaseTransformsURL) + populate(objectMap, "graphStudioUrl", c.GraphStudioURL) + populate(objectMap, "machineLearningNotebookUrl", c.MachineLearningNotebookURL) + populate(objectMap, "mongoDbUrl", c.MongoDbURL) + populate(objectMap, "ordsUrl", c.OrdsURL) + populate(objectMap, "sqlDevWebUrl", c.SQLDevWebURL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConnectionURLType. +func (c *ConnectionURLType) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "apexUrl": + err = unpopulate(val, "ApexURL", &c.ApexURL) + delete(rawMsg, key) + case "databaseTransformsUrl": + err = unpopulate(val, "DatabaseTransformsURL", &c.DatabaseTransformsURL) + delete(rawMsg, key) + case "graphStudioUrl": + err = unpopulate(val, "GraphStudioURL", &c.GraphStudioURL) + delete(rawMsg, key) + case "machineLearningNotebookUrl": + err = unpopulate(val, "MachineLearningNotebookURL", &c.MachineLearningNotebookURL) + delete(rawMsg, key) + case "mongoDbUrl": + err = unpopulate(val, "MongoDbURL", &c.MongoDbURL) + delete(rawMsg, key) + case "ordsUrl": + err = unpopulate(val, "OrdsURL", &c.OrdsURL) + delete(rawMsg, key) + case "sqlDevWebUrl": + err = unpopulate(val, "SQLDevWebURL", &c.SQLDevWebURL) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CustomerContact. +func (c CustomerContact) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "email", c.Email) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CustomerContact. +func (c *CustomerContact) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "email": + err = unpopulate(val, "Email", &c.Email) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DNSForwardingRule. +func (d DNSForwardingRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "domainNames", d.DomainNames) + populate(objectMap, "forwardingIpAddress", d.ForwardingIPAddress) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DNSForwardingRule. +func (d *DNSForwardingRule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "domainNames": + err = unpopulate(val, "DomainNames", &d.DomainNames) + delete(rawMsg, key) + case "forwardingIpAddress": + err = unpopulate(val, "ForwardingIPAddress", &d.ForwardingIPAddress) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DNSPrivateView. +func (d DNSPrivateView) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", d.ID) + populate(objectMap, "name", d.Name) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "systemData", d.SystemData) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DNSPrivateView. +func (d *DNSPrivateView) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &d.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &d.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &d.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DNSPrivateViewListResult. +func (d DNSPrivateViewListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", d.NextLink) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DNSPrivateViewListResult. +func (d *DNSPrivateViewListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &d.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &d.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DNSPrivateViewProperties. +func (d DNSPrivateViewProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "displayName", d.DisplayName) + populate(objectMap, "isProtected", d.IsProtected) + populate(objectMap, "lifecycleState", d.LifecycleState) + populate(objectMap, "ocid", d.Ocid) + populate(objectMap, "provisioningState", d.ProvisioningState) + populate(objectMap, "self", d.Self) + populateTime[datetime.RFC3339](objectMap, "timeCreated", d.TimeCreated) + populateTime[datetime.RFC3339](objectMap, "timeUpdated", d.TimeUpdated) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DNSPrivateViewProperties. +func (d *DNSPrivateViewProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "displayName": + err = unpopulate(val, "DisplayName", &d.DisplayName) + delete(rawMsg, key) + case "isProtected": + err = unpopulate(val, "IsProtected", &d.IsProtected) + delete(rawMsg, key) + case "lifecycleState": + err = unpopulate(val, "LifecycleState", &d.LifecycleState) + delete(rawMsg, key) + case "ocid": + err = unpopulate(val, "Ocid", &d.Ocid) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &d.ProvisioningState) + delete(rawMsg, key) + case "self": + err = unpopulate(val, "Self", &d.Self) + delete(rawMsg, key) + case "timeCreated": + err = unpopulateTime[datetime.RFC3339](val, "TimeCreated", &d.TimeCreated) + delete(rawMsg, key) + case "timeUpdated": + err = unpopulateTime[datetime.RFC3339](val, "TimeUpdated", &d.TimeUpdated) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DNSPrivateZone. +func (d DNSPrivateZone) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", d.ID) + populate(objectMap, "name", d.Name) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "systemData", d.SystemData) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DNSPrivateZone. +func (d *DNSPrivateZone) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &d.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &d.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &d.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DNSPrivateZoneListResult. +func (d DNSPrivateZoneListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", d.NextLink) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DNSPrivateZoneListResult. +func (d *DNSPrivateZoneListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &d.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &d.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DNSPrivateZoneProperties. +func (d DNSPrivateZoneProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "isProtected", d.IsProtected) + populate(objectMap, "lifecycleState", d.LifecycleState) + populate(objectMap, "ocid", d.Ocid) + populate(objectMap, "provisioningState", d.ProvisioningState) + populate(objectMap, "self", d.Self) + populate(objectMap, "serial", d.Serial) + populateTime[datetime.RFC3339](objectMap, "timeCreated", d.TimeCreated) + populate(objectMap, "version", d.Version) + populate(objectMap, "viewId", d.ViewID) + populate(objectMap, "zoneType", d.ZoneType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DNSPrivateZoneProperties. +func (d *DNSPrivateZoneProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "isProtected": + err = unpopulate(val, "IsProtected", &d.IsProtected) + delete(rawMsg, key) + case "lifecycleState": + err = unpopulate(val, "LifecycleState", &d.LifecycleState) + delete(rawMsg, key) + case "ocid": + err = unpopulate(val, "Ocid", &d.Ocid) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &d.ProvisioningState) + delete(rawMsg, key) + case "self": + err = unpopulate(val, "Self", &d.Self) + delete(rawMsg, key) + case "serial": + err = unpopulate(val, "Serial", &d.Serial) + delete(rawMsg, key) + case "timeCreated": + err = unpopulateTime[datetime.RFC3339](val, "TimeCreated", &d.TimeCreated) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &d.Version) + delete(rawMsg, key) + case "viewId": + err = unpopulate(val, "ViewID", &d.ViewID) + delete(rawMsg, key) + case "zoneType": + err = unpopulate(val, "ZoneType", &d.ZoneType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DataCollectionOptions. +func (d DataCollectionOptions) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "isDiagnosticsEventsEnabled", d.IsDiagnosticsEventsEnabled) + populate(objectMap, "isHealthMonitoringEnabled", d.IsHealthMonitoringEnabled) + populate(objectMap, "isIncidentLogsEnabled", d.IsIncidentLogsEnabled) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DataCollectionOptions. +func (d *DataCollectionOptions) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "isDiagnosticsEventsEnabled": + err = unpopulate(val, "IsDiagnosticsEventsEnabled", &d.IsDiagnosticsEventsEnabled) + delete(rawMsg, key) + case "isHealthMonitoringEnabled": + err = unpopulate(val, "IsHealthMonitoringEnabled", &d.IsHealthMonitoringEnabled) + delete(rawMsg, key) + case "isIncidentLogsEnabled": + err = unpopulate(val, "IsIncidentLogsEnabled", &d.IsIncidentLogsEnabled) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DayOfWeek. +func (d DayOfWeek) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", d.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DayOfWeek. +func (d *DayOfWeek) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DayOfWeekUpdate. +func (d DayOfWeekUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", d.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DayOfWeekUpdate. +func (d *DayOfWeekUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DbActionResponse. +func (d DbActionResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", d.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DbActionResponse. +func (d *DbActionResponse) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &d.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DbIormConfig. +func (d DbIormConfig) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dbName", d.DbName) + populate(objectMap, "flashCacheLimit", d.FlashCacheLimit) + populate(objectMap, "share", d.Share) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DbIormConfig. +func (d *DbIormConfig) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "dbName": + err = unpopulate(val, "DbName", &d.DbName) + delete(rawMsg, key) + case "flashCacheLimit": + err = unpopulate(val, "FlashCacheLimit", &d.FlashCacheLimit) + delete(rawMsg, key) + case "share": + err = unpopulate(val, "Share", &d.Share) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DbNode. +func (d DbNode) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", d.ID) + populate(objectMap, "name", d.Name) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "systemData", d.SystemData) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DbNode. +func (d *DbNode) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &d.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &d.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &d.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DbNodeAction. +func (d DbNodeAction) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "action", d.Action) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DbNodeAction. +func (d *DbNodeAction) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "action": + err = unpopulate(val, "Action", &d.Action) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DbNodeDetails. +func (d DbNodeDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dbNodeId", d.DbNodeID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DbNodeDetails. +func (d *DbNodeDetails) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "dbNodeId": + err = unpopulate(val, "DbNodeID", &d.DbNodeID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DbNodeListResult. +func (d DbNodeListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", d.NextLink) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DbNodeListResult. +func (d *DbNodeListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &d.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &d.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DbNodeProperties. +func (d DbNodeProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "additionalDetails", d.AdditionalDetails) + populate(objectMap, "backupIpId", d.BackupIPID) + populate(objectMap, "backupVnic2Id", d.BackupVnic2ID) + populate(objectMap, "backupVnicId", d.BackupVnicID) + populate(objectMap, "cpuCoreCount", d.CPUCoreCount) + populate(objectMap, "dbNodeStorageSizeInGbs", d.DbNodeStorageSizeInGbs) + populate(objectMap, "dbServerId", d.DbServerID) + populate(objectMap, "dbSystemId", d.DbSystemID) + populate(objectMap, "faultDomain", d.FaultDomain) + populate(objectMap, "hostIpId", d.HostIPID) + populate(objectMap, "hostname", d.Hostname) + populate(objectMap, "lifecycleDetails", d.LifecycleDetails) + populate(objectMap, "lifecycleState", d.LifecycleState) + populate(objectMap, "maintenanceType", d.MaintenanceType) + populate(objectMap, "memorySizeInGbs", d.MemorySizeInGbs) + populate(objectMap, "ocid", d.Ocid) + populate(objectMap, "provisioningState", d.ProvisioningState) + populate(objectMap, "softwareStorageSizeInGb", d.SoftwareStorageSizeInGb) + populateTime[datetime.RFC3339](objectMap, "timeCreated", d.TimeCreated) + populateTime[datetime.RFC3339](objectMap, "timeMaintenanceWindowEnd", d.TimeMaintenanceWindowEnd) + populateTime[datetime.RFC3339](objectMap, "timeMaintenanceWindowStart", d.TimeMaintenanceWindowStart) + populate(objectMap, "vnic2Id", d.Vnic2ID) + populate(objectMap, "vnicId", d.VnicID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DbNodeProperties. +func (d *DbNodeProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "additionalDetails": + err = unpopulate(val, "AdditionalDetails", &d.AdditionalDetails) + delete(rawMsg, key) + case "backupIpId": + err = unpopulate(val, "BackupIPID", &d.BackupIPID) + delete(rawMsg, key) + case "backupVnic2Id": + err = unpopulate(val, "BackupVnic2ID", &d.BackupVnic2ID) + delete(rawMsg, key) + case "backupVnicId": + err = unpopulate(val, "BackupVnicID", &d.BackupVnicID) + delete(rawMsg, key) + case "cpuCoreCount": + err = unpopulate(val, "CPUCoreCount", &d.CPUCoreCount) + delete(rawMsg, key) + case "dbNodeStorageSizeInGbs": + err = unpopulate(val, "DbNodeStorageSizeInGbs", &d.DbNodeStorageSizeInGbs) + delete(rawMsg, key) + case "dbServerId": + err = unpopulate(val, "DbServerID", &d.DbServerID) + delete(rawMsg, key) + case "dbSystemId": + err = unpopulate(val, "DbSystemID", &d.DbSystemID) + delete(rawMsg, key) + case "faultDomain": + err = unpopulate(val, "FaultDomain", &d.FaultDomain) + delete(rawMsg, key) + case "hostIpId": + err = unpopulate(val, "HostIPID", &d.HostIPID) + delete(rawMsg, key) + case "hostname": + err = unpopulate(val, "Hostname", &d.Hostname) + delete(rawMsg, key) + case "lifecycleDetails": + err = unpopulate(val, "LifecycleDetails", &d.LifecycleDetails) + delete(rawMsg, key) + case "lifecycleState": + err = unpopulate(val, "LifecycleState", &d.LifecycleState) + delete(rawMsg, key) + case "maintenanceType": + err = unpopulate(val, "MaintenanceType", &d.MaintenanceType) + delete(rawMsg, key) + case "memorySizeInGbs": + err = unpopulate(val, "MemorySizeInGbs", &d.MemorySizeInGbs) + delete(rawMsg, key) + case "ocid": + err = unpopulate(val, "Ocid", &d.Ocid) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &d.ProvisioningState) + delete(rawMsg, key) + case "softwareStorageSizeInGb": + err = unpopulate(val, "SoftwareStorageSizeInGb", &d.SoftwareStorageSizeInGb) + delete(rawMsg, key) + case "timeCreated": + err = unpopulateTime[datetime.RFC3339](val, "TimeCreated", &d.TimeCreated) + delete(rawMsg, key) + case "timeMaintenanceWindowEnd": + err = unpopulateTime[datetime.RFC3339](val, "TimeMaintenanceWindowEnd", &d.TimeMaintenanceWindowEnd) + delete(rawMsg, key) + case "timeMaintenanceWindowStart": + err = unpopulateTime[datetime.RFC3339](val, "TimeMaintenanceWindowStart", &d.TimeMaintenanceWindowStart) + delete(rawMsg, key) + case "vnic2Id": + err = unpopulate(val, "Vnic2ID", &d.Vnic2ID) + delete(rawMsg, key) + case "vnicId": + err = unpopulate(val, "VnicID", &d.VnicID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DbServer. +func (d DbServer) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", d.ID) + populate(objectMap, "name", d.Name) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "systemData", d.SystemData) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DbServer. +func (d *DbServer) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &d.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &d.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &d.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DbServerListResult. +func (d DbServerListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", d.NextLink) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DbServerListResult. +func (d *DbServerListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &d.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &d.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DbServerPatchingDetails. +func (d DbServerPatchingDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "estimatedPatchDuration", d.EstimatedPatchDuration) + populate(objectMap, "patchingStatus", d.PatchingStatus) + populateTime[datetime.RFC3339](objectMap, "timePatchingEnded", d.TimePatchingEnded) + populateTime[datetime.RFC3339](objectMap, "timePatchingStarted", d.TimePatchingStarted) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DbServerPatchingDetails. +func (d *DbServerPatchingDetails) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "estimatedPatchDuration": + err = unpopulate(val, "EstimatedPatchDuration", &d.EstimatedPatchDuration) + delete(rawMsg, key) + case "patchingStatus": + err = unpopulate(val, "PatchingStatus", &d.PatchingStatus) + delete(rawMsg, key) + case "timePatchingEnded": + err = unpopulateTime[datetime.RFC3339](val, "TimePatchingEnded", &d.TimePatchingEnded) + delete(rawMsg, key) + case "timePatchingStarted": + err = unpopulateTime[datetime.RFC3339](val, "TimePatchingStarted", &d.TimePatchingStarted) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DbServerProperties. +func (d DbServerProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "autonomousVmClusterIds", d.AutonomousVMClusterIDs) + populate(objectMap, "autonomousVirtualMachineIds", d.AutonomousVirtualMachineIDs) + populate(objectMap, "cpuCoreCount", d.CPUCoreCount) + populate(objectMap, "compartmentId", d.CompartmentID) + populate(objectMap, "computeModel", d.ComputeModel) + populate(objectMap, "dbNodeIds", d.DbNodeIDs) + populate(objectMap, "dbNodeStorageSizeInGbs", d.DbNodeStorageSizeInGbs) + populate(objectMap, "dbServerPatchingDetails", d.DbServerPatchingDetails) + populate(objectMap, "displayName", d.DisplayName) + populate(objectMap, "exadataInfrastructureId", d.ExadataInfrastructureID) + populate(objectMap, "lifecycleDetails", d.LifecycleDetails) + populate(objectMap, "lifecycleState", d.LifecycleState) + populate(objectMap, "maxCpuCount", d.MaxCPUCount) + populate(objectMap, "maxDbNodeStorageInGbs", d.MaxDbNodeStorageInGbs) + populate(objectMap, "maxMemoryInGbs", d.MaxMemoryInGbs) + populate(objectMap, "memorySizeInGbs", d.MemorySizeInGbs) + populate(objectMap, "ocid", d.Ocid) + populate(objectMap, "provisioningState", d.ProvisioningState) + populate(objectMap, "shape", d.Shape) + populateTime[datetime.RFC3339](objectMap, "timeCreated", d.TimeCreated) + populate(objectMap, "vmClusterIds", d.VMClusterIDs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DbServerProperties. +func (d *DbServerProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "autonomousVmClusterIds": + err = unpopulate(val, "AutonomousVMClusterIDs", &d.AutonomousVMClusterIDs) + delete(rawMsg, key) + case "autonomousVirtualMachineIds": + err = unpopulate(val, "AutonomousVirtualMachineIDs", &d.AutonomousVirtualMachineIDs) + delete(rawMsg, key) + case "cpuCoreCount": + err = unpopulate(val, "CPUCoreCount", &d.CPUCoreCount) + delete(rawMsg, key) + case "compartmentId": + err = unpopulate(val, "CompartmentID", &d.CompartmentID) + delete(rawMsg, key) + case "computeModel": + err = unpopulate(val, "ComputeModel", &d.ComputeModel) + delete(rawMsg, key) + case "dbNodeIds": + err = unpopulate(val, "DbNodeIDs", &d.DbNodeIDs) + delete(rawMsg, key) + case "dbNodeStorageSizeInGbs": + err = unpopulate(val, "DbNodeStorageSizeInGbs", &d.DbNodeStorageSizeInGbs) + delete(rawMsg, key) + case "dbServerPatchingDetails": + err = unpopulate(val, "DbServerPatchingDetails", &d.DbServerPatchingDetails) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &d.DisplayName) + delete(rawMsg, key) + case "exadataInfrastructureId": + err = unpopulate(val, "ExadataInfrastructureID", &d.ExadataInfrastructureID) + delete(rawMsg, key) + case "lifecycleDetails": + err = unpopulate(val, "LifecycleDetails", &d.LifecycleDetails) + delete(rawMsg, key) + case "lifecycleState": + err = unpopulate(val, "LifecycleState", &d.LifecycleState) + delete(rawMsg, key) + case "maxCpuCount": + err = unpopulate(val, "MaxCPUCount", &d.MaxCPUCount) + delete(rawMsg, key) + case "maxDbNodeStorageInGbs": + err = unpopulate(val, "MaxDbNodeStorageInGbs", &d.MaxDbNodeStorageInGbs) + delete(rawMsg, key) + case "maxMemoryInGbs": + err = unpopulate(val, "MaxMemoryInGbs", &d.MaxMemoryInGbs) + delete(rawMsg, key) + case "memorySizeInGbs": + err = unpopulate(val, "MemorySizeInGbs", &d.MemorySizeInGbs) + delete(rawMsg, key) + case "ocid": + err = unpopulate(val, "Ocid", &d.Ocid) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &d.ProvisioningState) + delete(rawMsg, key) + case "shape": + err = unpopulate(val, "Shape", &d.Shape) + delete(rawMsg, key) + case "timeCreated": + err = unpopulateTime[datetime.RFC3339](val, "TimeCreated", &d.TimeCreated) + delete(rawMsg, key) + case "vmClusterIds": + err = unpopulate(val, "VMClusterIDs", &d.VMClusterIDs) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DbSystem. +func (d DbSystem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", d.ID) + populate(objectMap, "location", d.Location) + populate(objectMap, "name", d.Name) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "systemData", d.SystemData) + populate(objectMap, "tags", d.Tags) + populate(objectMap, "type", d.Type) + populate(objectMap, "zones", d.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DbSystem. +func (d *DbSystem) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &d.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &d.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &d.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &d.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &d.Type) + delete(rawMsg, key) + case "zones": + err = unpopulate(val, "Zones", &d.Zones) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DbSystemBaseProperties. +func (d DbSystemBaseProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "clusterName", d.ClusterName) + populate(objectMap, "computeCount", d.ComputeCount) + populate(objectMap, "computeModel", d.ComputeModel) + populate(objectMap, "dataStorageSizeInGbs", d.DataStorageSizeInGbs) + populate(objectMap, "dbSystemOptions", d.DbSystemOptions) + populate(objectMap, "diskRedundancy", d.DiskRedundancy) + populate(objectMap, "displayName", d.DisplayName) + populate(objectMap, "domain", d.DomainV2) + populate(objectMap, "gridImageOcid", d.GridImageOcid) + populate(objectMap, "hostname", d.Hostname) + populate(objectMap, "initialDataStorageSizeInGb", d.InitialDataStorageSizeInGb) + populate(objectMap, "licenseModel", d.LicenseModelV2) + populate(objectMap, "lifecycleDetails", d.LifecycleDetails) + populate(objectMap, "lifecycleState", d.LifecycleState) + populate(objectMap, "listenerPort", d.ListenerPort) + populate(objectMap, "memorySizeInGbs", d.MemorySizeInGbs) + populate(objectMap, "networkAnchorId", d.NetworkAnchorID) + populate(objectMap, "nodeCount", d.NodeCount) + populate(objectMap, "ociUrl", d.OciURL) + populate(objectMap, "ocid", d.Ocid) + populate(objectMap, "provisioningState", d.ProvisioningState) + populate(objectMap, "resourceAnchorId", d.ResourceAnchorID) + populate(objectMap, "sshPublicKeys", d.SSHPublicKeys) + populate(objectMap, "scanDnsName", d.ScanDNSName) + populate(objectMap, "scanIps", d.ScanIPs) + populate(objectMap, "shape", d.Shape) + populate(objectMap, "source", d.Source) + populate(objectMap, "storageVolumePerformanceMode", d.StorageVolumePerformanceMode) + populate(objectMap, "timeZone", d.TimeZone) + populate(objectMap, "version", d.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DbSystemBaseProperties. +func (d *DbSystemBaseProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "clusterName": + err = unpopulate(val, "ClusterName", &d.ClusterName) + delete(rawMsg, key) + case "computeCount": + err = unpopulate(val, "ComputeCount", &d.ComputeCount) + delete(rawMsg, key) + case "computeModel": + err = unpopulate(val, "ComputeModel", &d.ComputeModel) + delete(rawMsg, key) + case "dataStorageSizeInGbs": + err = unpopulate(val, "DataStorageSizeInGbs", &d.DataStorageSizeInGbs) + delete(rawMsg, key) + case "dbSystemOptions": + err = unpopulate(val, "DbSystemOptions", &d.DbSystemOptions) + delete(rawMsg, key) + case "diskRedundancy": + err = unpopulate(val, "DiskRedundancy", &d.DiskRedundancy) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &d.DisplayName) + delete(rawMsg, key) + case "domain": + err = unpopulate(val, "DomainV2", &d.DomainV2) + delete(rawMsg, key) + case "gridImageOcid": + err = unpopulate(val, "GridImageOcid", &d.GridImageOcid) + delete(rawMsg, key) + case "hostname": + err = unpopulate(val, "Hostname", &d.Hostname) + delete(rawMsg, key) + case "initialDataStorageSizeInGb": + err = unpopulate(val, "InitialDataStorageSizeInGb", &d.InitialDataStorageSizeInGb) + delete(rawMsg, key) + case "licenseModel": + err = unpopulate(val, "LicenseModelV2", &d.LicenseModelV2) + delete(rawMsg, key) + case "lifecycleDetails": + err = unpopulate(val, "LifecycleDetails", &d.LifecycleDetails) + delete(rawMsg, key) + case "lifecycleState": + err = unpopulate(val, "LifecycleState", &d.LifecycleState) + delete(rawMsg, key) + case "listenerPort": + err = unpopulate(val, "ListenerPort", &d.ListenerPort) + delete(rawMsg, key) + case "memorySizeInGbs": + err = unpopulate(val, "MemorySizeInGbs", &d.MemorySizeInGbs) + delete(rawMsg, key) + case "networkAnchorId": + err = unpopulate(val, "NetworkAnchorID", &d.NetworkAnchorID) + delete(rawMsg, key) + case "nodeCount": + err = unpopulate(val, "NodeCount", &d.NodeCount) + delete(rawMsg, key) + case "ociUrl": + err = unpopulate(val, "OciURL", &d.OciURL) + delete(rawMsg, key) + case "ocid": + err = unpopulate(val, "Ocid", &d.Ocid) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &d.ProvisioningState) + delete(rawMsg, key) + case "resourceAnchorId": + err = unpopulate(val, "ResourceAnchorID", &d.ResourceAnchorID) + delete(rawMsg, key) + case "sshPublicKeys": + err = unpopulate(val, "SSHPublicKeys", &d.SSHPublicKeys) + delete(rawMsg, key) + case "scanDnsName": + err = unpopulate(val, "ScanDNSName", &d.ScanDNSName) + delete(rawMsg, key) + case "scanIps": + err = unpopulate(val, "ScanIPs", &d.ScanIPs) + delete(rawMsg, key) + case "shape": + err = unpopulate(val, "Shape", &d.Shape) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &d.Source) + delete(rawMsg, key) + case "storageVolumePerformanceMode": + err = unpopulate(val, "StorageVolumePerformanceMode", &d.StorageVolumePerformanceMode) + delete(rawMsg, key) + case "timeZone": + err = unpopulate(val, "TimeZone", &d.TimeZone) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &d.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DbSystemListResult. +func (d DbSystemListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", d.NextLink) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DbSystemListResult. +func (d *DbSystemListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &d.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &d.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DbSystemOptions. +func (d DbSystemOptions) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "storageManagement", d.StorageManagement) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DbSystemOptions. +func (d *DbSystemOptions) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "storageManagement": + err = unpopulate(val, "StorageManagement", &d.StorageManagement) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DbSystemProperties. +func (d DbSystemProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "adminPassword", d.AdminPassword) + populate(objectMap, "clusterName", d.ClusterName) + populate(objectMap, "computeCount", d.ComputeCount) + populate(objectMap, "computeModel", d.ComputeModel) + populate(objectMap, "dataStorageSizeInGbs", d.DataStorageSizeInGbs) + populate(objectMap, "databaseEdition", d.DatabaseEdition) + populate(objectMap, "dbSystemOptions", d.DbSystemOptions) + populate(objectMap, "dbVersion", d.DbVersion) + populate(objectMap, "diskRedundancy", d.DiskRedundancy) + populate(objectMap, "displayName", d.DisplayName) + populate(objectMap, "domain", d.DomainV2) + populate(objectMap, "gridImageOcid", d.GridImageOcid) + populate(objectMap, "hostname", d.Hostname) + populate(objectMap, "initialDataStorageSizeInGb", d.InitialDataStorageSizeInGb) + populate(objectMap, "licenseModel", d.LicenseModelV2) + populate(objectMap, "lifecycleDetails", d.LifecycleDetails) + populate(objectMap, "lifecycleState", d.LifecycleState) + populate(objectMap, "listenerPort", d.ListenerPort) + populate(objectMap, "memorySizeInGbs", d.MemorySizeInGbs) + populate(objectMap, "networkAnchorId", d.NetworkAnchorID) + populate(objectMap, "nodeCount", d.NodeCount) + populate(objectMap, "ociUrl", d.OciURL) + populate(objectMap, "ocid", d.Ocid) + populate(objectMap, "pdbName", d.PdbName) + populate(objectMap, "provisioningState", d.ProvisioningState) + populate(objectMap, "resourceAnchorId", d.ResourceAnchorID) + populate(objectMap, "sshPublicKeys", d.SSHPublicKeys) + populate(objectMap, "scanDnsName", d.ScanDNSName) + populate(objectMap, "scanIps", d.ScanIPs) + populate(objectMap, "shape", d.Shape) + objectMap["source"] = DbSystemSourceTypeNone + populate(objectMap, "storageVolumePerformanceMode", d.StorageVolumePerformanceMode) + populate(objectMap, "timeZone", d.TimeZone) + populate(objectMap, "version", d.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DbSystemProperties. +func (d *DbSystemProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "adminPassword": + err = unpopulate(val, "AdminPassword", &d.AdminPassword) + delete(rawMsg, key) + case "clusterName": + err = unpopulate(val, "ClusterName", &d.ClusterName) + delete(rawMsg, key) + case "computeCount": + err = unpopulate(val, "ComputeCount", &d.ComputeCount) + delete(rawMsg, key) + case "computeModel": + err = unpopulate(val, "ComputeModel", &d.ComputeModel) + delete(rawMsg, key) + case "dataStorageSizeInGbs": + err = unpopulate(val, "DataStorageSizeInGbs", &d.DataStorageSizeInGbs) + delete(rawMsg, key) + case "databaseEdition": + err = unpopulate(val, "DatabaseEdition", &d.DatabaseEdition) + delete(rawMsg, key) + case "dbSystemOptions": + err = unpopulate(val, "DbSystemOptions", &d.DbSystemOptions) + delete(rawMsg, key) + case "dbVersion": + err = unpopulate(val, "DbVersion", &d.DbVersion) + delete(rawMsg, key) + case "diskRedundancy": + err = unpopulate(val, "DiskRedundancy", &d.DiskRedundancy) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &d.DisplayName) + delete(rawMsg, key) + case "domain": + err = unpopulate(val, "DomainV2", &d.DomainV2) + delete(rawMsg, key) + case "gridImageOcid": + err = unpopulate(val, "GridImageOcid", &d.GridImageOcid) + delete(rawMsg, key) + case "hostname": + err = unpopulate(val, "Hostname", &d.Hostname) + delete(rawMsg, key) + case "initialDataStorageSizeInGb": + err = unpopulate(val, "InitialDataStorageSizeInGb", &d.InitialDataStorageSizeInGb) + delete(rawMsg, key) + case "licenseModel": + err = unpopulate(val, "LicenseModelV2", &d.LicenseModelV2) + delete(rawMsg, key) + case "lifecycleDetails": + err = unpopulate(val, "LifecycleDetails", &d.LifecycleDetails) + delete(rawMsg, key) + case "lifecycleState": + err = unpopulate(val, "LifecycleState", &d.LifecycleState) + delete(rawMsg, key) + case "listenerPort": + err = unpopulate(val, "ListenerPort", &d.ListenerPort) + delete(rawMsg, key) + case "memorySizeInGbs": + err = unpopulate(val, "MemorySizeInGbs", &d.MemorySizeInGbs) + delete(rawMsg, key) + case "networkAnchorId": + err = unpopulate(val, "NetworkAnchorID", &d.NetworkAnchorID) + delete(rawMsg, key) + case "nodeCount": + err = unpopulate(val, "NodeCount", &d.NodeCount) + delete(rawMsg, key) + case "ociUrl": + err = unpopulate(val, "OciURL", &d.OciURL) + delete(rawMsg, key) + case "ocid": + err = unpopulate(val, "Ocid", &d.Ocid) + delete(rawMsg, key) + case "pdbName": + err = unpopulate(val, "PdbName", &d.PdbName) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &d.ProvisioningState) + delete(rawMsg, key) + case "resourceAnchorId": + err = unpopulate(val, "ResourceAnchorID", &d.ResourceAnchorID) + delete(rawMsg, key) + case "sshPublicKeys": + err = unpopulate(val, "SSHPublicKeys", &d.SSHPublicKeys) + delete(rawMsg, key) + case "scanDnsName": + err = unpopulate(val, "ScanDNSName", &d.ScanDNSName) + delete(rawMsg, key) + case "scanIps": + err = unpopulate(val, "ScanIPs", &d.ScanIPs) + delete(rawMsg, key) + case "shape": + err = unpopulate(val, "Shape", &d.Shape) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &d.Source) + delete(rawMsg, key) + case "storageVolumePerformanceMode": + err = unpopulate(val, "StorageVolumePerformanceMode", &d.StorageVolumePerformanceMode) + delete(rawMsg, key) + case "timeZone": + err = unpopulate(val, "TimeZone", &d.TimeZone) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &d.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DbSystemShape. +func (d DbSystemShape) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", d.ID) + populate(objectMap, "name", d.Name) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "systemData", d.SystemData) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DbSystemShape. +func (d *DbSystemShape) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &d.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &d.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &d.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DbSystemShapeListResult. +func (d DbSystemShapeListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", d.NextLink) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DbSystemShapeListResult. +func (d *DbSystemShapeListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &d.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &d.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DbSystemShapeProperties. +func (d DbSystemShapeProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "areServerTypesSupported", d.AreServerTypesSupported) + populate(objectMap, "availableCoreCount", d.AvailableCoreCount) + populate(objectMap, "availableCoreCountPerNode", d.AvailableCoreCountPerNode) + populate(objectMap, "availableDataStorageInTbs", d.AvailableDataStorageInTbs) + populate(objectMap, "availableDataStoragePerServerInTbs", d.AvailableDataStoragePerServerInTbs) + populate(objectMap, "availableDbNodePerNodeInGbs", d.AvailableDbNodePerNodeInGbs) + populate(objectMap, "availableDbNodeStorageInGbs", d.AvailableDbNodeStorageInGbs) + populate(objectMap, "availableMemoryInGbs", d.AvailableMemoryInGbs) + populate(objectMap, "availableMemoryPerNodeInGbs", d.AvailableMemoryPerNodeInGbs) + populate(objectMap, "computeModel", d.ComputeModel) + populate(objectMap, "coreCountIncrement", d.CoreCountIncrement) + populate(objectMap, "displayName", d.DisplayName) + populate(objectMap, "maxStorageCount", d.MaxStorageCount) + populate(objectMap, "maximumNodeCount", d.MaximumNodeCount) + populate(objectMap, "minCoreCountPerNode", d.MinCoreCountPerNode) + populate(objectMap, "minDataStorageInTbs", d.MinDataStorageInTbs) + populate(objectMap, "minDbNodeStoragePerNodeInGbs", d.MinDbNodeStoragePerNodeInGbs) + populate(objectMap, "minMemoryPerNodeInGbs", d.MinMemoryPerNodeInGbs) + populate(objectMap, "minStorageCount", d.MinStorageCount) + populate(objectMap, "minimumCoreCount", d.MinimumCoreCount) + populate(objectMap, "minimumNodeCount", d.MinimumNodeCount) + populate(objectMap, "runtimeMinimumCoreCount", d.RuntimeMinimumCoreCount) + populate(objectMap, "shapeAttributes", d.ShapeAttributes) + populate(objectMap, "shapeFamily", d.ShapeFamily) + populate(objectMap, "shapeName", d.ShapeName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DbSystemShapeProperties. +func (d *DbSystemShapeProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "areServerTypesSupported": + err = unpopulate(val, "AreServerTypesSupported", &d.AreServerTypesSupported) + delete(rawMsg, key) + case "availableCoreCount": + err = unpopulate(val, "AvailableCoreCount", &d.AvailableCoreCount) + delete(rawMsg, key) + case "availableCoreCountPerNode": + err = unpopulate(val, "AvailableCoreCountPerNode", &d.AvailableCoreCountPerNode) + delete(rawMsg, key) + case "availableDataStorageInTbs": + err = unpopulate(val, "AvailableDataStorageInTbs", &d.AvailableDataStorageInTbs) + delete(rawMsg, key) + case "availableDataStoragePerServerInTbs": + err = unpopulate(val, "AvailableDataStoragePerServerInTbs", &d.AvailableDataStoragePerServerInTbs) + delete(rawMsg, key) + case "availableDbNodePerNodeInGbs": + err = unpopulate(val, "AvailableDbNodePerNodeInGbs", &d.AvailableDbNodePerNodeInGbs) + delete(rawMsg, key) + case "availableDbNodeStorageInGbs": + err = unpopulate(val, "AvailableDbNodeStorageInGbs", &d.AvailableDbNodeStorageInGbs) + delete(rawMsg, key) + case "availableMemoryInGbs": + err = unpopulate(val, "AvailableMemoryInGbs", &d.AvailableMemoryInGbs) + delete(rawMsg, key) + case "availableMemoryPerNodeInGbs": + err = unpopulate(val, "AvailableMemoryPerNodeInGbs", &d.AvailableMemoryPerNodeInGbs) + delete(rawMsg, key) + case "computeModel": + err = unpopulate(val, "ComputeModel", &d.ComputeModel) + delete(rawMsg, key) + case "coreCountIncrement": + err = unpopulate(val, "CoreCountIncrement", &d.CoreCountIncrement) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &d.DisplayName) + delete(rawMsg, key) + case "maxStorageCount": + err = unpopulate(val, "MaxStorageCount", &d.MaxStorageCount) + delete(rawMsg, key) + case "maximumNodeCount": + err = unpopulate(val, "MaximumNodeCount", &d.MaximumNodeCount) + delete(rawMsg, key) + case "minCoreCountPerNode": + err = unpopulate(val, "MinCoreCountPerNode", &d.MinCoreCountPerNode) + delete(rawMsg, key) + case "minDataStorageInTbs": + err = unpopulate(val, "MinDataStorageInTbs", &d.MinDataStorageInTbs) + delete(rawMsg, key) + case "minDbNodeStoragePerNodeInGbs": + err = unpopulate(val, "MinDbNodeStoragePerNodeInGbs", &d.MinDbNodeStoragePerNodeInGbs) + delete(rawMsg, key) + case "minMemoryPerNodeInGbs": + err = unpopulate(val, "MinMemoryPerNodeInGbs", &d.MinMemoryPerNodeInGbs) + delete(rawMsg, key) + case "minStorageCount": + err = unpopulate(val, "MinStorageCount", &d.MinStorageCount) + delete(rawMsg, key) + case "minimumCoreCount": + err = unpopulate(val, "MinimumCoreCount", &d.MinimumCoreCount) + delete(rawMsg, key) + case "minimumNodeCount": + err = unpopulate(val, "MinimumNodeCount", &d.MinimumNodeCount) + delete(rawMsg, key) + case "runtimeMinimumCoreCount": + err = unpopulate(val, "RuntimeMinimumCoreCount", &d.RuntimeMinimumCoreCount) + delete(rawMsg, key) + case "shapeAttributes": + err = unpopulate(val, "ShapeAttributes", &d.ShapeAttributes) + delete(rawMsg, key) + case "shapeFamily": + err = unpopulate(val, "ShapeFamily", &d.ShapeFamily) + delete(rawMsg, key) + case "shapeName": + err = unpopulate(val, "ShapeName", &d.ShapeName) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DbSystemUpdate. +func (d DbSystemUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "tags", d.Tags) + populate(objectMap, "zones", d.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DbSystemUpdate. +func (d *DbSystemUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &d.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &d.Tags) + delete(rawMsg, key) + case "zones": + err = unpopulate(val, "Zones", &d.Zones) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DbSystemUpdateProperties. +func (d DbSystemUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + if d.Source != nil { + objectMap["source"] = DbSystemSourceTypeNone + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DbSystemUpdateProperties. +func (d *DbSystemUpdateProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "source": + err = unpopulate(val, "Source", &d.Source) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DbVersion. +func (d DbVersion) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", d.ID) + populate(objectMap, "name", d.Name) + populate(objectMap, "properties", d.Properties) + populate(objectMap, "systemData", d.SystemData) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DbVersion. +func (d *DbVersion) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &d.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &d.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &d.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DbVersionListResult. +func (d DbVersionListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", d.NextLink) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DbVersionListResult. +func (d *DbVersionListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &d.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &d.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DbVersionProperties. +func (d DbVersionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "isLatestForMajorVersion", d.IsLatestForMajorVersion) + populate(objectMap, "isPreviewDbVersion", d.IsPreviewDbVersion) + populate(objectMap, "isUpgradeSupported", d.IsUpgradeSupported) + populate(objectMap, "supportsPdb", d.SupportsPdb) + populate(objectMap, "version", d.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DbVersionProperties. +func (d *DbVersionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "isLatestForMajorVersion": + err = unpopulate(val, "IsLatestForMajorVersion", &d.IsLatestForMajorVersion) + delete(rawMsg, key) + case "isPreviewDbVersion": + err = unpopulate(val, "IsPreviewDbVersion", &d.IsPreviewDbVersion) + delete(rawMsg, key) + case "isUpgradeSupported": + err = unpopulate(val, "IsUpgradeSupported", &d.IsUpgradeSupported) + delete(rawMsg, key) + case "supportsPdb": + err = unpopulate(val, "SupportsPdb", &d.SupportsPdb) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &d.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DefinedFileSystemConfiguration. +func (d DefinedFileSystemConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "isBackupPartition", d.IsBackupPartition) + populate(objectMap, "isResizable", d.IsResizable) + populate(objectMap, "minSizeGb", d.MinSizeGb) + populate(objectMap, "mountPoint", d.MountPoint) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DefinedFileSystemConfiguration. +func (d *DefinedFileSystemConfiguration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "isBackupPartition": + err = unpopulate(val, "IsBackupPartition", &d.IsBackupPartition) + delete(rawMsg, key) + case "isResizable": + err = unpopulate(val, "IsResizable", &d.IsResizable) + delete(rawMsg, key) + case "minSizeGb": + err = unpopulate(val, "MinSizeGb", &d.MinSizeGb) + delete(rawMsg, key) + case "mountPoint": + err = unpopulate(val, "MountPoint", &d.MountPoint) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DisasterRecoveryConfigurationDetails. +func (d DisasterRecoveryConfigurationDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "disasterRecoveryType", d.DisasterRecoveryType) + populate(objectMap, "isReplicateAutomaticBackups", d.IsReplicateAutomaticBackups) + populate(objectMap, "isSnapshotStandby", d.IsSnapshotStandby) + populateTime[datetime.RFC3339](objectMap, "timeSnapshotStandbyEnabledTill", d.TimeSnapshotStandbyEnabledTill) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DisasterRecoveryConfigurationDetails. +func (d *DisasterRecoveryConfigurationDetails) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "disasterRecoveryType": + err = unpopulate(val, "DisasterRecoveryType", &d.DisasterRecoveryType) + delete(rawMsg, key) + case "isReplicateAutomaticBackups": + err = unpopulate(val, "IsReplicateAutomaticBackups", &d.IsReplicateAutomaticBackups) + delete(rawMsg, key) + case "isSnapshotStandby": + err = unpopulate(val, "IsSnapshotStandby", &d.IsSnapshotStandby) + delete(rawMsg, key) + case "timeSnapshotStandbyEnabledTill": + err = unpopulateTime[datetime.RFC3339](val, "TimeSnapshotStandbyEnabledTill", &d.TimeSnapshotStandbyEnabledTill) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type EstimatedPatchingTime. +func (e EstimatedPatchingTime) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "estimatedDbServerPatchingTime", e.EstimatedDbServerPatchingTime) + populate(objectMap, "estimatedNetworkSwitchesPatchingTime", e.EstimatedNetworkSwitchesPatchingTime) + populate(objectMap, "estimatedStorageServerPatchingTime", e.EstimatedStorageServerPatchingTime) + populate(objectMap, "totalEstimatedPatchingTime", e.TotalEstimatedPatchingTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EstimatedPatchingTime. +func (e *EstimatedPatchingTime) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "estimatedDbServerPatchingTime": + err = unpopulate(val, "EstimatedDbServerPatchingTime", &e.EstimatedDbServerPatchingTime) + delete(rawMsg, key) + case "estimatedNetworkSwitchesPatchingTime": + err = unpopulate(val, "EstimatedNetworkSwitchesPatchingTime", &e.EstimatedNetworkSwitchesPatchingTime) + delete(rawMsg, key) + case "estimatedStorageServerPatchingTime": + err = unpopulate(val, "EstimatedStorageServerPatchingTime", &e.EstimatedStorageServerPatchingTime) + delete(rawMsg, key) + case "totalEstimatedPatchingTime": + err = unpopulate(val, "TotalEstimatedPatchingTime", &e.TotalEstimatedPatchingTime) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExadataIormConfig. +func (e ExadataIormConfig) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dbPlans", e.DbPlans) + populate(objectMap, "lifecycleDetails", e.LifecycleDetails) + populate(objectMap, "lifecycleState", e.LifecycleState) + populate(objectMap, "objective", e.Objective) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExadataIormConfig. +func (e *ExadataIormConfig) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "dbPlans": + err = unpopulate(val, "DbPlans", &e.DbPlans) + delete(rawMsg, key) + case "lifecycleDetails": + err = unpopulate(val, "LifecycleDetails", &e.LifecycleDetails) + delete(rawMsg, key) + case "lifecycleState": + err = unpopulate(val, "LifecycleState", &e.LifecycleState) + delete(rawMsg, key) + case "objective": + err = unpopulate(val, "Objective", &e.Objective) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExadbVMCluster. +func (e ExadbVMCluster) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", e.ID) + populate(objectMap, "location", e.Location) + populate(objectMap, "name", e.Name) + populate(objectMap, "properties", e.Properties) + populate(objectMap, "systemData", e.SystemData) + populate(objectMap, "tags", e.Tags) + populate(objectMap, "type", e.Type) + populate(objectMap, "zones", e.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExadbVMCluster. +func (e *ExadbVMCluster) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &e.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &e.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &e.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &e.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &e.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &e.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &e.Type) + delete(rawMsg, key) + case "zones": + err = unpopulate(val, "Zones", &e.Zones) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExadbVMClusterListResult. +func (e ExadbVMClusterListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", e.NextLink) + populate(objectMap, "value", e.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExadbVMClusterListResult. +func (e *ExadbVMClusterListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &e.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &e.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExadbVMClusterProperties. +func (e ExadbVMClusterProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "backupSubnetCidr", e.BackupSubnetCidr) + populate(objectMap, "backupSubnetOcid", e.BackupSubnetOcid) + populate(objectMap, "clusterName", e.ClusterName) + populate(objectMap, "dataCollectionOptions", e.DataCollectionOptions) + populate(objectMap, "displayName", e.DisplayName) + populate(objectMap, "domain", e.Domain) + populate(objectMap, "enabledEcpuCount", e.EnabledEcpuCount) + populate(objectMap, "exascaleDbStorageVaultId", e.ExascaleDbStorageVaultID) + populate(objectMap, "giVersion", e.GiVersion) + populate(objectMap, "gridImageOcid", e.GridImageOcid) + populate(objectMap, "gridImageType", e.GridImageType) + populate(objectMap, "hostname", e.Hostname) + populate(objectMap, "iormConfigCache", e.IormConfigCache) + populate(objectMap, "licenseModel", e.LicenseModel) + populate(objectMap, "lifecycleDetails", e.LifecycleDetails) + populate(objectMap, "lifecycleState", e.LifecycleState) + populate(objectMap, "listenerPort", e.ListenerPort) + populate(objectMap, "memorySizeInGbs", e.MemorySizeInGbs) + populate(objectMap, "nodeCount", e.NodeCount) + populate(objectMap, "nsgCidrs", e.NsgCidrs) + populate(objectMap, "nsgUrl", e.NsgURL) + populate(objectMap, "ociUrl", e.OciURL) + populate(objectMap, "ocid", e.Ocid) + populate(objectMap, "privateZoneOcid", e.PrivateZoneOcid) + populate(objectMap, "provisioningState", e.ProvisioningState) + populate(objectMap, "sshPublicKeys", e.SSHPublicKeys) + populate(objectMap, "scanDnsName", e.ScanDNSName) + populate(objectMap, "scanDnsRecordId", e.ScanDNSRecordID) + populate(objectMap, "scanIpIds", e.ScanIPIDs) + populate(objectMap, "scanListenerPortTcp", e.ScanListenerPortTCP) + populate(objectMap, "scanListenerPortTcpSsl", e.ScanListenerPortTCPSSL) + populate(objectMap, "shape", e.Shape) + populate(objectMap, "shapeAttribute", e.ShapeAttribute) + populate(objectMap, "snapshotFileSystemStorage", e.SnapshotFileSystemStorage) + populate(objectMap, "subnetId", e.SubnetID) + populate(objectMap, "subnetOcid", e.SubnetOcid) + populate(objectMap, "systemVersion", e.SystemVersion) + populate(objectMap, "timeZone", e.TimeZone) + populate(objectMap, "totalEcpuCount", e.TotalEcpuCount) + populate(objectMap, "totalFileSystemStorage", e.TotalFileSystemStorage) + populate(objectMap, "vmFileSystemStorage", e.VMFileSystemStorage) + populate(objectMap, "vipIds", e.VipIDs) + populate(objectMap, "vnetId", e.VnetID) + populate(objectMap, "zoneOcid", e.ZoneOcid) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExadbVMClusterProperties. +func (e *ExadbVMClusterProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "backupSubnetCidr": + err = unpopulate(val, "BackupSubnetCidr", &e.BackupSubnetCidr) + delete(rawMsg, key) + case "backupSubnetOcid": + err = unpopulate(val, "BackupSubnetOcid", &e.BackupSubnetOcid) + delete(rawMsg, key) + case "clusterName": + err = unpopulate(val, "ClusterName", &e.ClusterName) + delete(rawMsg, key) + case "dataCollectionOptions": + err = unpopulate(val, "DataCollectionOptions", &e.DataCollectionOptions) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &e.DisplayName) + delete(rawMsg, key) + case "domain": + err = unpopulate(val, "Domain", &e.Domain) + delete(rawMsg, key) + case "enabledEcpuCount": + err = unpopulate(val, "EnabledEcpuCount", &e.EnabledEcpuCount) + delete(rawMsg, key) + case "exascaleDbStorageVaultId": + err = unpopulate(val, "ExascaleDbStorageVaultID", &e.ExascaleDbStorageVaultID) + delete(rawMsg, key) + case "giVersion": + err = unpopulate(val, "GiVersion", &e.GiVersion) + delete(rawMsg, key) + case "gridImageOcid": + err = unpopulate(val, "GridImageOcid", &e.GridImageOcid) + delete(rawMsg, key) + case "gridImageType": + err = unpopulate(val, "GridImageType", &e.GridImageType) + delete(rawMsg, key) + case "hostname": + err = unpopulate(val, "Hostname", &e.Hostname) + delete(rawMsg, key) + case "iormConfigCache": + err = unpopulate(val, "IormConfigCache", &e.IormConfigCache) + delete(rawMsg, key) + case "licenseModel": + err = unpopulate(val, "LicenseModel", &e.LicenseModel) + delete(rawMsg, key) + case "lifecycleDetails": + err = unpopulate(val, "LifecycleDetails", &e.LifecycleDetails) + delete(rawMsg, key) + case "lifecycleState": + err = unpopulate(val, "LifecycleState", &e.LifecycleState) + delete(rawMsg, key) + case "listenerPort": + err = unpopulate(val, "ListenerPort", &e.ListenerPort) + delete(rawMsg, key) + case "memorySizeInGbs": + err = unpopulate(val, "MemorySizeInGbs", &e.MemorySizeInGbs) + delete(rawMsg, key) + case "nodeCount": + err = unpopulate(val, "NodeCount", &e.NodeCount) + delete(rawMsg, key) + case "nsgCidrs": + err = unpopulate(val, "NsgCidrs", &e.NsgCidrs) + delete(rawMsg, key) + case "nsgUrl": + err = unpopulate(val, "NsgURL", &e.NsgURL) + delete(rawMsg, key) + case "ociUrl": + err = unpopulate(val, "OciURL", &e.OciURL) + delete(rawMsg, key) + case "ocid": + err = unpopulate(val, "Ocid", &e.Ocid) + delete(rawMsg, key) + case "privateZoneOcid": + err = unpopulate(val, "PrivateZoneOcid", &e.PrivateZoneOcid) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &e.ProvisioningState) + delete(rawMsg, key) + case "sshPublicKeys": + err = unpopulate(val, "SSHPublicKeys", &e.SSHPublicKeys) + delete(rawMsg, key) + case "scanDnsName": + err = unpopulate(val, "ScanDNSName", &e.ScanDNSName) + delete(rawMsg, key) + case "scanDnsRecordId": + err = unpopulate(val, "ScanDNSRecordID", &e.ScanDNSRecordID) + delete(rawMsg, key) + case "scanIpIds": + err = unpopulate(val, "ScanIPIDs", &e.ScanIPIDs) + delete(rawMsg, key) + case "scanListenerPortTcp": + err = unpopulate(val, "ScanListenerPortTCP", &e.ScanListenerPortTCP) + delete(rawMsg, key) + case "scanListenerPortTcpSsl": + err = unpopulate(val, "ScanListenerPortTCPSSL", &e.ScanListenerPortTCPSSL) + delete(rawMsg, key) + case "shape": + err = unpopulate(val, "Shape", &e.Shape) + delete(rawMsg, key) + case "shapeAttribute": + err = unpopulate(val, "ShapeAttribute", &e.ShapeAttribute) + delete(rawMsg, key) + case "snapshotFileSystemStorage": + err = unpopulate(val, "SnapshotFileSystemStorage", &e.SnapshotFileSystemStorage) + delete(rawMsg, key) + case "subnetId": + err = unpopulate(val, "SubnetID", &e.SubnetID) + delete(rawMsg, key) + case "subnetOcid": + err = unpopulate(val, "SubnetOcid", &e.SubnetOcid) + delete(rawMsg, key) + case "systemVersion": + err = unpopulate(val, "SystemVersion", &e.SystemVersion) + delete(rawMsg, key) + case "timeZone": + err = unpopulate(val, "TimeZone", &e.TimeZone) + delete(rawMsg, key) + case "totalEcpuCount": + err = unpopulate(val, "TotalEcpuCount", &e.TotalEcpuCount) + delete(rawMsg, key) + case "totalFileSystemStorage": + err = unpopulate(val, "TotalFileSystemStorage", &e.TotalFileSystemStorage) + delete(rawMsg, key) + case "vmFileSystemStorage": + err = unpopulate(val, "VMFileSystemStorage", &e.VMFileSystemStorage) + delete(rawMsg, key) + case "vipIds": + err = unpopulate(val, "VipIDs", &e.VipIDs) + delete(rawMsg, key) + case "vnetId": + err = unpopulate(val, "VnetID", &e.VnetID) + delete(rawMsg, key) + case "zoneOcid": + err = unpopulate(val, "ZoneOcid", &e.ZoneOcid) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExadbVMClusterStorageDetails. +func (e ExadbVMClusterStorageDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "totalSizeInGbs", e.TotalSizeInGbs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExadbVMClusterStorageDetails. +func (e *ExadbVMClusterStorageDetails) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "totalSizeInGbs": + err = unpopulate(val, "TotalSizeInGbs", &e.TotalSizeInGbs) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExadbVMClusterUpdate. +func (e ExadbVMClusterUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", e.Properties) + populate(objectMap, "tags", e.Tags) + populate(objectMap, "zones", e.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExadbVMClusterUpdate. +func (e *ExadbVMClusterUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &e.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &e.Tags) + delete(rawMsg, key) + case "zones": + err = unpopulate(val, "Zones", &e.Zones) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExadbVMClusterUpdateProperties. +func (e ExadbVMClusterUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nodeCount", e.NodeCount) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExadbVMClusterUpdateProperties. +func (e *ExadbVMClusterUpdateProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nodeCount": + err = unpopulate(val, "NodeCount", &e.NodeCount) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExascaleConfigDetails. +func (e ExascaleConfigDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "availableStorageInGbs", e.AvailableStorageInGbs) + populate(objectMap, "totalStorageInGbs", e.TotalStorageInGbs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExascaleConfigDetails. +func (e *ExascaleConfigDetails) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "availableStorageInGbs": + err = unpopulate(val, "AvailableStorageInGbs", &e.AvailableStorageInGbs) + delete(rawMsg, key) + case "totalStorageInGbs": + err = unpopulate(val, "TotalStorageInGbs", &e.TotalStorageInGbs) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExascaleDbNode. +func (e ExascaleDbNode) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", e.ID) + populate(objectMap, "name", e.Name) + populate(objectMap, "properties", e.Properties) + populate(objectMap, "systemData", e.SystemData) + populate(objectMap, "type", e.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExascaleDbNode. +func (e *ExascaleDbNode) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &e.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &e.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &e.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &e.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &e.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExascaleDbNodeListResult. +func (e ExascaleDbNodeListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", e.NextLink) + populate(objectMap, "value", e.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExascaleDbNodeListResult. +func (e *ExascaleDbNodeListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &e.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &e.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExascaleDbNodeProperties. +func (e ExascaleDbNodeProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "additionalDetails", e.AdditionalDetails) + populate(objectMap, "cpuCoreCount", e.CPUCoreCount) + populate(objectMap, "dbNodeStorageSizeInGbs", e.DbNodeStorageSizeInGbs) + populate(objectMap, "faultDomain", e.FaultDomain) + populate(objectMap, "hostname", e.Hostname) + populate(objectMap, "lifecycleState", e.LifecycleState) + populate(objectMap, "maintenanceType", e.MaintenanceType) + populate(objectMap, "memorySizeInGbs", e.MemorySizeInGbs) + populate(objectMap, "ocid", e.Ocid) + populate(objectMap, "softwareStorageSizeInGb", e.SoftwareStorageSizeInGb) + populateTime[datetime.RFC3339](objectMap, "timeMaintenanceWindowEnd", e.TimeMaintenanceWindowEnd) + populateTime[datetime.RFC3339](objectMap, "timeMaintenanceWindowStart", e.TimeMaintenanceWindowStart) + populate(objectMap, "totalCpuCoreCount", e.TotalCPUCoreCount) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExascaleDbNodeProperties. +func (e *ExascaleDbNodeProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "additionalDetails": + err = unpopulate(val, "AdditionalDetails", &e.AdditionalDetails) + delete(rawMsg, key) + case "cpuCoreCount": + err = unpopulate(val, "CPUCoreCount", &e.CPUCoreCount) + delete(rawMsg, key) + case "dbNodeStorageSizeInGbs": + err = unpopulate(val, "DbNodeStorageSizeInGbs", &e.DbNodeStorageSizeInGbs) + delete(rawMsg, key) + case "faultDomain": + err = unpopulate(val, "FaultDomain", &e.FaultDomain) + delete(rawMsg, key) + case "hostname": + err = unpopulate(val, "Hostname", &e.Hostname) + delete(rawMsg, key) + case "lifecycleState": + err = unpopulate(val, "LifecycleState", &e.LifecycleState) + delete(rawMsg, key) + case "maintenanceType": + err = unpopulate(val, "MaintenanceType", &e.MaintenanceType) + delete(rawMsg, key) + case "memorySizeInGbs": + err = unpopulate(val, "MemorySizeInGbs", &e.MemorySizeInGbs) + delete(rawMsg, key) + case "ocid": + err = unpopulate(val, "Ocid", &e.Ocid) + delete(rawMsg, key) + case "softwareStorageSizeInGb": + err = unpopulate(val, "SoftwareStorageSizeInGb", &e.SoftwareStorageSizeInGb) + delete(rawMsg, key) + case "timeMaintenanceWindowEnd": + err = unpopulateTime[datetime.RFC3339](val, "TimeMaintenanceWindowEnd", &e.TimeMaintenanceWindowEnd) + delete(rawMsg, key) + case "timeMaintenanceWindowStart": + err = unpopulateTime[datetime.RFC3339](val, "TimeMaintenanceWindowStart", &e.TimeMaintenanceWindowStart) + delete(rawMsg, key) + case "totalCpuCoreCount": + err = unpopulate(val, "TotalCPUCoreCount", &e.TotalCPUCoreCount) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExascaleDbStorageDetails. +func (e ExascaleDbStorageDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "availableSizeInGbs", e.AvailableSizeInGbs) + populate(objectMap, "totalSizeInGbs", e.TotalSizeInGbs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExascaleDbStorageDetails. +func (e *ExascaleDbStorageDetails) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "availableSizeInGbs": + err = unpopulate(val, "AvailableSizeInGbs", &e.AvailableSizeInGbs) + delete(rawMsg, key) + case "totalSizeInGbs": + err = unpopulate(val, "TotalSizeInGbs", &e.TotalSizeInGbs) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExascaleDbStorageInputDetails. +func (e ExascaleDbStorageInputDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "totalSizeInGbs", e.TotalSizeInGbs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExascaleDbStorageInputDetails. +func (e *ExascaleDbStorageInputDetails) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "totalSizeInGbs": + err = unpopulate(val, "TotalSizeInGbs", &e.TotalSizeInGbs) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExascaleDbStorageVault. +func (e ExascaleDbStorageVault) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", e.ID) + populate(objectMap, "location", e.Location) + populate(objectMap, "name", e.Name) + populate(objectMap, "properties", e.Properties) + populate(objectMap, "systemData", e.SystemData) + populate(objectMap, "tags", e.Tags) + populate(objectMap, "type", e.Type) + populate(objectMap, "zones", e.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExascaleDbStorageVault. +func (e *ExascaleDbStorageVault) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &e.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &e.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &e.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &e.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &e.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &e.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &e.Type) + delete(rawMsg, key) + case "zones": + err = unpopulate(val, "Zones", &e.Zones) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExascaleDbStorageVaultListResult. +func (e ExascaleDbStorageVaultListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", e.NextLink) + populate(objectMap, "value", e.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExascaleDbStorageVaultListResult. +func (e *ExascaleDbStorageVaultListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &e.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &e.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExascaleDbStorageVaultProperties. +func (e ExascaleDbStorageVaultProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "additionalFlashCacheInPercent", e.AdditionalFlashCacheInPercent) + populate(objectMap, "attachedShapeAttributes", e.AttachedShapeAttributes) + populate(objectMap, "description", e.Description) + populate(objectMap, "displayName", e.DisplayName) + populate(objectMap, "exadataInfrastructureId", e.ExadataInfrastructureID) + populate(objectMap, "highCapacityDatabaseStorage", e.HighCapacityDatabaseStorage) + populate(objectMap, "highCapacityDatabaseStorageInput", e.HighCapacityDatabaseStorageInput) + populate(objectMap, "lifecycleDetails", e.LifecycleDetails) + populate(objectMap, "lifecycleState", e.LifecycleState) + populate(objectMap, "ociUrl", e.OciURL) + populate(objectMap, "ocid", e.Ocid) + populate(objectMap, "provisioningState", e.ProvisioningState) + populate(objectMap, "timeZone", e.TimeZone) + populate(objectMap, "vmClusterCount", e.VMClusterCount) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExascaleDbStorageVaultProperties. +func (e *ExascaleDbStorageVaultProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "additionalFlashCacheInPercent": + err = unpopulate(val, "AdditionalFlashCacheInPercent", &e.AdditionalFlashCacheInPercent) + delete(rawMsg, key) + case "attachedShapeAttributes": + err = unpopulate(val, "AttachedShapeAttributes", &e.AttachedShapeAttributes) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &e.Description) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &e.DisplayName) + delete(rawMsg, key) + case "exadataInfrastructureId": + err = unpopulate(val, "ExadataInfrastructureID", &e.ExadataInfrastructureID) + delete(rawMsg, key) + case "highCapacityDatabaseStorage": + err = unpopulate(val, "HighCapacityDatabaseStorage", &e.HighCapacityDatabaseStorage) + delete(rawMsg, key) + case "highCapacityDatabaseStorageInput": + err = unpopulate(val, "HighCapacityDatabaseStorageInput", &e.HighCapacityDatabaseStorageInput) + delete(rawMsg, key) + case "lifecycleDetails": + err = unpopulate(val, "LifecycleDetails", &e.LifecycleDetails) + delete(rawMsg, key) + case "lifecycleState": + err = unpopulate(val, "LifecycleState", &e.LifecycleState) + delete(rawMsg, key) + case "ociUrl": + err = unpopulate(val, "OciURL", &e.OciURL) + delete(rawMsg, key) + case "ocid": + err = unpopulate(val, "Ocid", &e.Ocid) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &e.ProvisioningState) + delete(rawMsg, key) + case "timeZone": + err = unpopulate(val, "TimeZone", &e.TimeZone) + delete(rawMsg, key) + case "vmClusterCount": + err = unpopulate(val, "VMClusterCount", &e.VMClusterCount) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExascaleDbStorageVaultTagsUpdate. +func (e ExascaleDbStorageVaultTagsUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "tags", e.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExascaleDbStorageVaultTagsUpdate. +func (e *ExascaleDbStorageVaultTagsUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "tags": + err = unpopulate(val, "Tags", &e.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FileSystemConfigurationDetails. +func (f FileSystemConfigurationDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "fileSystemSizeGb", f.FileSystemSizeGb) + populate(objectMap, "mountPoint", f.MountPoint) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FileSystemConfigurationDetails. +func (f *FileSystemConfigurationDetails) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "fileSystemSizeGb": + err = unpopulate(val, "FileSystemSizeGb", &f.FileSystemSizeGb) + delete(rawMsg, key) + case "mountPoint": + err = unpopulate(val, "MountPoint", &f.MountPoint) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FlexComponent. +func (f FlexComponent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", f.ID) + populate(objectMap, "name", f.Name) + populate(objectMap, "properties", f.Properties) + populate(objectMap, "systemData", f.SystemData) + populate(objectMap, "type", f.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FlexComponent. +func (f *FlexComponent) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &f.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &f.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &f.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &f.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &f.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FlexComponentListResult. +func (f FlexComponentListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", f.NextLink) + populate(objectMap, "value", f.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FlexComponentListResult. +func (f *FlexComponentListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &f.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &f.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FlexComponentProperties. +func (f FlexComponentProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "availableCoreCount", f.AvailableCoreCount) + populate(objectMap, "availableDbStorageInGbs", f.AvailableDbStorageInGbs) + populate(objectMap, "availableLocalStorageInGbs", f.AvailableLocalStorageInGbs) + populate(objectMap, "availableMemoryInGbs", f.AvailableMemoryInGbs) + populate(objectMap, "computeModel", f.ComputeModel) + populate(objectMap, "descriptionSummary", f.DescriptionSummary) + populate(objectMap, "hardwareType", f.HardwareType) + populate(objectMap, "minimumCoreCount", f.MinimumCoreCount) + populate(objectMap, "runtimeMinimumCoreCount", f.RuntimeMinimumCoreCount) + populate(objectMap, "shape", f.Shape) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FlexComponentProperties. +func (f *FlexComponentProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "availableCoreCount": + err = unpopulate(val, "AvailableCoreCount", &f.AvailableCoreCount) + delete(rawMsg, key) + case "availableDbStorageInGbs": + err = unpopulate(val, "AvailableDbStorageInGbs", &f.AvailableDbStorageInGbs) + delete(rawMsg, key) + case "availableLocalStorageInGbs": + err = unpopulate(val, "AvailableLocalStorageInGbs", &f.AvailableLocalStorageInGbs) + delete(rawMsg, key) + case "availableMemoryInGbs": + err = unpopulate(val, "AvailableMemoryInGbs", &f.AvailableMemoryInGbs) + delete(rawMsg, key) + case "computeModel": + err = unpopulate(val, "ComputeModel", &f.ComputeModel) + delete(rawMsg, key) + case "descriptionSummary": + err = unpopulate(val, "DescriptionSummary", &f.DescriptionSummary) + delete(rawMsg, key) + case "hardwareType": + err = unpopulate(val, "HardwareType", &f.HardwareType) + delete(rawMsg, key) + case "minimumCoreCount": + err = unpopulate(val, "MinimumCoreCount", &f.MinimumCoreCount) + delete(rawMsg, key) + case "runtimeMinimumCoreCount": + err = unpopulate(val, "RuntimeMinimumCoreCount", &f.RuntimeMinimumCoreCount) + delete(rawMsg, key) + case "shape": + err = unpopulate(val, "Shape", &f.Shape) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type GenerateAutonomousDatabaseWalletDetails. +func (g GenerateAutonomousDatabaseWalletDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "generateType", g.GenerateType) + populate(objectMap, "isRegional", g.IsRegional) + populate(objectMap, "password", g.Password) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GenerateAutonomousDatabaseWalletDetails. +func (g *GenerateAutonomousDatabaseWalletDetails) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "generateType": + err = unpopulate(val, "GenerateType", &g.GenerateType) + delete(rawMsg, key) + case "isRegional": + err = unpopulate(val, "IsRegional", &g.IsRegional) + delete(rawMsg, key) + case "password": + err = unpopulate(val, "Password", &g.Password) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type GiMinorVersion. +func (g GiMinorVersion) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", g.ID) + populate(objectMap, "name", g.Name) + populate(objectMap, "properties", g.Properties) + populate(objectMap, "systemData", g.SystemData) + populate(objectMap, "type", g.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GiMinorVersion. +func (g *GiMinorVersion) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &g.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &g.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &g.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &g.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &g.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type GiMinorVersionListResult. +func (g GiMinorVersionListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", g.NextLink) + populate(objectMap, "value", g.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GiMinorVersionListResult. +func (g *GiMinorVersionListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &g.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &g.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type GiMinorVersionProperties. +func (g GiMinorVersionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "gridImageOcid", g.GridImageOcid) + populate(objectMap, "version", g.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GiMinorVersionProperties. +func (g *GiMinorVersionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "gridImageOcid": + err = unpopulate(val, "GridImageOcid", &g.GridImageOcid) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &g.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type GiVersion. +func (g GiVersion) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", g.ID) + populate(objectMap, "name", g.Name) + populate(objectMap, "properties", g.Properties) + populate(objectMap, "systemData", g.SystemData) + populate(objectMap, "type", g.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GiVersion. +func (g *GiVersion) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &g.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &g.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &g.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &g.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &g.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type GiVersionListResult. +func (g GiVersionListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", g.NextLink) + populate(objectMap, "value", g.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GiVersionListResult. +func (g *GiVersionListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &g.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &g.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type GiVersionProperties. +func (g GiVersionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "version", g.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GiVersionProperties. +func (g *GiVersionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "version": + err = unpopulate(val, "Version", &g.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LongTermBackUpScheduleDetails. +func (l LongTermBackUpScheduleDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "isDisabled", l.IsDisabled) + populate(objectMap, "repeatCadence", l.RepeatCadence) + populate(objectMap, "retentionPeriodInDays", l.RetentionPeriodInDays) + populateTime[datetime.RFC3339](objectMap, "timeOfBackup", l.TimeOfBackup) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LongTermBackUpScheduleDetails. +func (l *LongTermBackUpScheduleDetails) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "isDisabled": + err = unpopulate(val, "IsDisabled", &l.IsDisabled) + delete(rawMsg, key) + case "repeatCadence": + err = unpopulate(val, "RepeatCadence", &l.RepeatCadence) + delete(rawMsg, key) + case "retentionPeriodInDays": + err = unpopulate(val, "RetentionPeriodInDays", &l.RetentionPeriodInDays) + delete(rawMsg, key) + case "timeOfBackup": + err = unpopulateTime[datetime.RFC3339](val, "TimeOfBackup", &l.TimeOfBackup) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MaintenanceWindow. +func (m MaintenanceWindow) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "customActionTimeoutInMins", m.CustomActionTimeoutInMins) + populate(objectMap, "daysOfWeek", m.DaysOfWeek) + populate(objectMap, "hoursOfDay", m.HoursOfDay) + populate(objectMap, "isCustomActionTimeoutEnabled", m.IsCustomActionTimeoutEnabled) + populate(objectMap, "isMonthlyPatchingEnabled", m.IsMonthlyPatchingEnabled) + populate(objectMap, "leadTimeInWeeks", m.LeadTimeInWeeks) + populate(objectMap, "months", m.Months) + populate(objectMap, "patchingMode", m.PatchingMode) + populate(objectMap, "preference", m.Preference) + populate(objectMap, "weeksOfMonth", m.WeeksOfMonth) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MaintenanceWindow. +func (m *MaintenanceWindow) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "customActionTimeoutInMins": + err = unpopulate(val, "CustomActionTimeoutInMins", &m.CustomActionTimeoutInMins) + delete(rawMsg, key) + case "daysOfWeek": + err = unpopulate(val, "DaysOfWeek", &m.DaysOfWeek) + delete(rawMsg, key) + case "hoursOfDay": + err = unpopulate(val, "HoursOfDay", &m.HoursOfDay) + delete(rawMsg, key) + case "isCustomActionTimeoutEnabled": + err = unpopulate(val, "IsCustomActionTimeoutEnabled", &m.IsCustomActionTimeoutEnabled) + delete(rawMsg, key) + case "isMonthlyPatchingEnabled": + err = unpopulate(val, "IsMonthlyPatchingEnabled", &m.IsMonthlyPatchingEnabled) + delete(rawMsg, key) + case "leadTimeInWeeks": + err = unpopulate(val, "LeadTimeInWeeks", &m.LeadTimeInWeeks) + delete(rawMsg, key) + case "months": + err = unpopulate(val, "Months", &m.Months) + delete(rawMsg, key) + case "patchingMode": + err = unpopulate(val, "PatchingMode", &m.PatchingMode) + delete(rawMsg, key) + case "preference": + err = unpopulate(val, "Preference", &m.Preference) + delete(rawMsg, key) + case "weeksOfMonth": + err = unpopulate(val, "WeeksOfMonth", &m.WeeksOfMonth) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Month. +func (m Month) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", m.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Month. +func (m *Month) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &m.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkAnchor. +func (n NetworkAnchor) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", n.ID) + populate(objectMap, "location", n.Location) + populate(objectMap, "name", n.Name) + populate(objectMap, "properties", n.Properties) + populate(objectMap, "systemData", n.SystemData) + populate(objectMap, "tags", n.Tags) + populate(objectMap, "type", n.Type) + populate(objectMap, "zones", n.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkAnchor. +func (n *NetworkAnchor) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &n.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &n.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &n.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &n.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &n.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &n.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &n.Type) + delete(rawMsg, key) + case "zones": + err = unpopulate(val, "Zones", &n.Zones) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkAnchorListResult. +func (n NetworkAnchorListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", n.NextLink) + populate(objectMap, "value", n.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkAnchorListResult. +func (n *NetworkAnchorListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &n.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &n.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkAnchorProperties. +func (n NetworkAnchorProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "cidrBlock", n.CidrBlock) + populate(objectMap, "dnsForwardingEndpointIpAddress", n.DNSForwardingEndpointIPAddress) + populate(objectMap, "dnsForwardingEndpointNsgRulesUrl", n.DNSForwardingEndpointNsgRulesURL) + populate(objectMap, "dnsForwardingRules", n.DNSForwardingRules) + populate(objectMap, "dnsForwardingRulesUrl", n.DNSForwardingRulesURL) + populate(objectMap, "dnsListeningEndpointAllowedCidrs", n.DNSListeningEndpointAllowedCidrs) + populate(objectMap, "dnsListeningEndpointIpAddress", n.DNSListeningEndpointIPAddress) + populate(objectMap, "dnsListeningEndpointNsgRulesUrl", n.DNSListeningEndpointNsgRulesURL) + populate(objectMap, "isOracleDnsForwardingEndpointEnabled", n.IsOracleDNSForwardingEndpointEnabled) + populate(objectMap, "isOracleDnsListeningEndpointEnabled", n.IsOracleDNSListeningEndpointEnabled) + populate(objectMap, "isOracleToAzureDnsZoneSyncEnabled", n.IsOracleToAzureDNSZoneSyncEnabled) + populate(objectMap, "ociBackupCidrBlock", n.OciBackupCidrBlock) + populate(objectMap, "ociSubnetId", n.OciSubnetID) + populate(objectMap, "ociVcnDnsLabel", n.OciVcnDNSLabel) + populate(objectMap, "ociVcnId", n.OciVcnID) + populate(objectMap, "provisioningState", n.ProvisioningState) + populate(objectMap, "resourceAnchorId", n.ResourceAnchorID) + populate(objectMap, "subnetId", n.SubnetID) + populate(objectMap, "vnetId", n.VnetID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkAnchorProperties. +func (n *NetworkAnchorProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "cidrBlock": + err = unpopulate(val, "CidrBlock", &n.CidrBlock) + delete(rawMsg, key) + case "dnsForwardingEndpointIpAddress": + err = unpopulate(val, "DNSForwardingEndpointIPAddress", &n.DNSForwardingEndpointIPAddress) + delete(rawMsg, key) + case "dnsForwardingEndpointNsgRulesUrl": + err = unpopulate(val, "DNSForwardingEndpointNsgRulesURL", &n.DNSForwardingEndpointNsgRulesURL) + delete(rawMsg, key) + case "dnsForwardingRules": + err = unpopulate(val, "DNSForwardingRules", &n.DNSForwardingRules) + delete(rawMsg, key) + case "dnsForwardingRulesUrl": + err = unpopulate(val, "DNSForwardingRulesURL", &n.DNSForwardingRulesURL) + delete(rawMsg, key) + case "dnsListeningEndpointAllowedCidrs": + err = unpopulate(val, "DNSListeningEndpointAllowedCidrs", &n.DNSListeningEndpointAllowedCidrs) + delete(rawMsg, key) + case "dnsListeningEndpointIpAddress": + err = unpopulate(val, "DNSListeningEndpointIPAddress", &n.DNSListeningEndpointIPAddress) + delete(rawMsg, key) + case "dnsListeningEndpointNsgRulesUrl": + err = unpopulate(val, "DNSListeningEndpointNsgRulesURL", &n.DNSListeningEndpointNsgRulesURL) + delete(rawMsg, key) + case "isOracleDnsForwardingEndpointEnabled": + err = unpopulate(val, "IsOracleDNSForwardingEndpointEnabled", &n.IsOracleDNSForwardingEndpointEnabled) + delete(rawMsg, key) + case "isOracleDnsListeningEndpointEnabled": + err = unpopulate(val, "IsOracleDNSListeningEndpointEnabled", &n.IsOracleDNSListeningEndpointEnabled) + delete(rawMsg, key) + case "isOracleToAzureDnsZoneSyncEnabled": + err = unpopulate(val, "IsOracleToAzureDNSZoneSyncEnabled", &n.IsOracleToAzureDNSZoneSyncEnabled) + delete(rawMsg, key) + case "ociBackupCidrBlock": + err = unpopulate(val, "OciBackupCidrBlock", &n.OciBackupCidrBlock) + delete(rawMsg, key) + case "ociSubnetId": + err = unpopulate(val, "OciSubnetID", &n.OciSubnetID) + delete(rawMsg, key) + case "ociVcnDnsLabel": + err = unpopulate(val, "OciVcnDNSLabel", &n.OciVcnDNSLabel) + delete(rawMsg, key) + case "ociVcnId": + err = unpopulate(val, "OciVcnID", &n.OciVcnID) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &n.ProvisioningState) + delete(rawMsg, key) + case "resourceAnchorId": + err = unpopulate(val, "ResourceAnchorID", &n.ResourceAnchorID) + delete(rawMsg, key) + case "subnetId": + err = unpopulate(val, "SubnetID", &n.SubnetID) + delete(rawMsg, key) + case "vnetId": + err = unpopulate(val, "VnetID", &n.VnetID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkAnchorUpdate. +func (n NetworkAnchorUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "properties", n.Properties) + populate(objectMap, "tags", n.Tags) + populate(objectMap, "zones", n.Zones) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkAnchorUpdate. +func (n *NetworkAnchorUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, "Properties", &n.Properties) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &n.Tags) + delete(rawMsg, key) + case "zones": + err = unpopulate(val, "Zones", &n.Zones) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkAnchorUpdateProperties. +func (n NetworkAnchorUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "isOracleDnsForwardingEndpointEnabled", n.IsOracleDNSForwardingEndpointEnabled) + populate(objectMap, "isOracleDnsListeningEndpointEnabled", n.IsOracleDNSListeningEndpointEnabled) + populate(objectMap, "isOracleToAzureDnsZoneSyncEnabled", n.IsOracleToAzureDNSZoneSyncEnabled) + populate(objectMap, "ociBackupCidrBlock", n.OciBackupCidrBlock) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NetworkAnchorUpdateProperties. +func (n *NetworkAnchorUpdateProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "isOracleDnsForwardingEndpointEnabled": + err = unpopulate(val, "IsOracleDNSForwardingEndpointEnabled", &n.IsOracleDNSForwardingEndpointEnabled) + delete(rawMsg, key) + case "isOracleDnsListeningEndpointEnabled": + err = unpopulate(val, "IsOracleDNSListeningEndpointEnabled", &n.IsOracleDNSListeningEndpointEnabled) + delete(rawMsg, key) + case "isOracleToAzureDnsZoneSyncEnabled": + err = unpopulate(val, "IsOracleToAzureDNSZoneSyncEnabled", &n.IsOracleToAzureDNSZoneSyncEnabled) + delete(rawMsg, key) + case "ociBackupCidrBlock": + err = unpopulate(val, "OciBackupCidrBlock", &n.OciBackupCidrBlock) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type NsgCidr. +func (n NsgCidr) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "destinationPortRange", n.DestinationPortRange) + populate(objectMap, "source", n.Source) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NsgCidr. +func (n *NsgCidr) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "destinationPortRange": + err = unpopulate(val, "DestinationPortRange", &n.DestinationPortRange) + delete(rawMsg, key) + case "source": + err = unpopulate(val, "Source", &n.Source) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", n, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Operation. +func (o Operation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "actionType", o.ActionType) + populate(objectMap, "display", o.Display) + populate(objectMap, "isDataAction", o.IsDataAction) + populate(objectMap, "name", o.Name) + populate(objectMap, "origin", o.Origin) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Operation. +func (o *Operation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "actionType": + err = unpopulate(val, "ActionType", &o.ActionType) + delete(rawMsg, key) + case "display": + err = unpopulate(val, "Display", &o.Display) + delete(rawMsg, key) + case "isDataAction": + err = unpopulate(val, "IsDataAction", &o.IsDataAction) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "origin": + err = unpopulate(val, "Origin", &o.Origin) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationDisplay. +func (o OperationDisplay) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", o.Description) + populate(objectMap, "operation", o.Operation) + populate(objectMap, "provider", o.Provider) + populate(objectMap, "resource", o.Resource) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationDisplay. +func (o *OperationDisplay) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &o.Description) + delete(rawMsg, key) + case "operation": + err = unpopulate(val, "Operation", &o.Operation) + delete(rawMsg, key) + case "provider": + err = unpopulate(val, "Provider", &o.Provider) + delete(rawMsg, key) + case "resource": + err = unpopulate(val, "Resource", &o.Resource) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OperationListResult. +func (o *OperationListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &o.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OracleSubscription. +func (o OracleSubscription) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", o.ID) + populate(objectMap, "name", o.Name) + populate(objectMap, "plan", o.Plan) + populate(objectMap, "properties", o.Properties) + populate(objectMap, "systemData", o.SystemData) + populate(objectMap, "type", o.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OracleSubscription. +func (o *OracleSubscription) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &o.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &o.Name) + delete(rawMsg, key) + case "plan": + err = unpopulate(val, "Plan", &o.Plan) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &o.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &o.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &o.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OracleSubscriptionListResult. +func (o OracleSubscriptionListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OracleSubscriptionListResult. +func (o *OracleSubscriptionListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &o.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &o.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OracleSubscriptionProperties. +func (o OracleSubscriptionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "addSubscriptionOperationState", o.AddSubscriptionOperationState) + populate(objectMap, "azureSubscriptionIds", o.AzureSubscriptionIDs) + populate(objectMap, "cloudAccountId", o.CloudAccountID) + populate(objectMap, "cloudAccountState", o.CloudAccountState) + populate(objectMap, "intent", o.Intent) + populate(objectMap, "lastOperationStatusDetail", o.LastOperationStatusDetail) + populate(objectMap, "productCode", o.ProductCode) + populate(objectMap, "provisioningState", o.ProvisioningState) + populate(objectMap, "saasSubscriptionId", o.SaasSubscriptionID) + populate(objectMap, "termUnit", o.TermUnit) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OracleSubscriptionProperties. +func (o *OracleSubscriptionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "addSubscriptionOperationState": + err = unpopulate(val, "AddSubscriptionOperationState", &o.AddSubscriptionOperationState) + delete(rawMsg, key) + case "azureSubscriptionIds": + err = unpopulate(val, "AzureSubscriptionIDs", &o.AzureSubscriptionIDs) + delete(rawMsg, key) + case "cloudAccountId": + err = unpopulate(val, "CloudAccountID", &o.CloudAccountID) + delete(rawMsg, key) + case "cloudAccountState": + err = unpopulate(val, "CloudAccountState", &o.CloudAccountState) + delete(rawMsg, key) + case "intent": + err = unpopulate(val, "Intent", &o.Intent) + delete(rawMsg, key) + case "lastOperationStatusDetail": + err = unpopulate(val, "LastOperationStatusDetail", &o.LastOperationStatusDetail) + delete(rawMsg, key) + case "productCode": + err = unpopulate(val, "ProductCode", &o.ProductCode) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &o.ProvisioningState) + delete(rawMsg, key) + case "saasSubscriptionId": + err = unpopulate(val, "SaasSubscriptionID", &o.SaasSubscriptionID) + delete(rawMsg, key) + case "termUnit": + err = unpopulate(val, "TermUnit", &o.TermUnit) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OracleSubscriptionUpdate. +func (o OracleSubscriptionUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "plan", o.Plan) + populate(objectMap, "properties", o.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OracleSubscriptionUpdate. +func (o *OracleSubscriptionUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "plan": + err = unpopulate(val, "Plan", &o.Plan) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &o.Properties) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type OracleSubscriptionUpdateProperties. +func (o OracleSubscriptionUpdateProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "intent", o.Intent) + populate(objectMap, "productCode", o.ProductCode) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OracleSubscriptionUpdateProperties. +func (o *OracleSubscriptionUpdateProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "intent": + err = unpopulate(val, "Intent", &o.Intent) + delete(rawMsg, key) + case "productCode": + err = unpopulate(val, "ProductCode", &o.ProductCode) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", o, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PeerDbDetails. +func (p PeerDbDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "peerDbId", p.PeerDbID) + populate(objectMap, "peerDbLocation", p.PeerDbLocation) + populate(objectMap, "peerDbOcid", p.PeerDbOcid) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PeerDbDetails. +func (p *PeerDbDetails) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "peerDbId": + err = unpopulate(val, "PeerDbID", &p.PeerDbID) + delete(rawMsg, key) + case "peerDbLocation": + err = unpopulate(val, "PeerDbLocation", &p.PeerDbLocation) + delete(rawMsg, key) + case "peerDbOcid": + err = unpopulate(val, "PeerDbOcid", &p.PeerDbOcid) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Plan. +func (p Plan) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", p.Name) + populate(objectMap, "product", p.Product) + populate(objectMap, "promotionCode", p.PromotionCode) + populate(objectMap, "publisher", p.Publisher) + populate(objectMap, "version", p.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Plan. +func (p *Plan) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "product": + err = unpopulate(val, "Product", &p.Product) + delete(rawMsg, key) + case "promotionCode": + err = unpopulate(val, "PromotionCode", &p.PromotionCode) + delete(rawMsg, key) + case "publisher": + err = unpopulate(val, "Publisher", &p.Publisher) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &p.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PlanUpdate. +func (p PlanUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", p.Name) + populate(objectMap, "product", p.Product) + populate(objectMap, "promotionCode", p.PromotionCode) + populate(objectMap, "publisher", p.Publisher) + populate(objectMap, "version", p.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PlanUpdate. +func (p *PlanUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "product": + err = unpopulate(val, "Product", &p.Product) + delete(rawMsg, key) + case "promotionCode": + err = unpopulate(val, "PromotionCode", &p.PromotionCode) + delete(rawMsg, key) + case "publisher": + err = unpopulate(val, "Publisher", &p.Publisher) + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &p.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PortRange. +func (p PortRange) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "max", p.Max) + populate(objectMap, "min", p.Min) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PortRange. +func (p *PortRange) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "max": + err = unpopulate(val, "Max", &p.Max) + delete(rawMsg, key) + case "min": + err = unpopulate(val, "Min", &p.Min) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateIPAddressProperties. +func (p PrivateIPAddressProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "displayName", p.DisplayName) + populate(objectMap, "hostnameLabel", p.HostnameLabel) + populate(objectMap, "ipAddress", p.IPAddress) + populate(objectMap, "ocid", p.Ocid) + populate(objectMap, "subnetId", p.SubnetID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateIPAddressProperties. +func (p *PrivateIPAddressProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "displayName": + err = unpopulate(val, "DisplayName", &p.DisplayName) + delete(rawMsg, key) + case "hostnameLabel": + err = unpopulate(val, "HostnameLabel", &p.HostnameLabel) + delete(rawMsg, key) + case "ipAddress": + err = unpopulate(val, "IPAddress", &p.IPAddress) + delete(rawMsg, key) + case "ocid": + err = unpopulate(val, "Ocid", &p.Ocid) + delete(rawMsg, key) + case "subnetId": + err = unpopulate(val, "SubnetID", &p.SubnetID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateIPAddressesFilter. +func (p PrivateIPAddressesFilter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "subnetId", p.SubnetID) + populate(objectMap, "vnicId", p.VnicID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PrivateIPAddressesFilter. +func (p *PrivateIPAddressesFilter) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "subnetId": + err = unpopulate(val, "SubnetID", &p.SubnetID) + delete(rawMsg, key) + case "vnicId": + err = unpopulate(val, "VnicID", &p.VnicID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ProfileType. +func (p ProfileType) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "consumerGroup", p.ConsumerGroup) + populate(objectMap, "displayName", p.DisplayName) + populate(objectMap, "hostFormat", p.HostFormat) + populate(objectMap, "isRegional", p.IsRegional) + populate(objectMap, "protocol", p.Protocol) + populate(objectMap, "sessionMode", p.SessionMode) + populate(objectMap, "syntaxFormat", p.SyntaxFormat) + populate(objectMap, "tlsAuthentication", p.TLSAuthentication) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ProfileType. +func (p *ProfileType) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "consumerGroup": + err = unpopulate(val, "ConsumerGroup", &p.ConsumerGroup) + delete(rawMsg, key) + case "displayName": + err = unpopulate(val, "DisplayName", &p.DisplayName) + delete(rawMsg, key) + case "hostFormat": + err = unpopulate(val, "HostFormat", &p.HostFormat) + delete(rawMsg, key) + case "isRegional": + err = unpopulate(val, "IsRegional", &p.IsRegional) + delete(rawMsg, key) + case "protocol": + err = unpopulate(val, "Protocol", &p.Protocol) + delete(rawMsg, key) + case "sessionMode": + err = unpopulate(val, "SessionMode", &p.SessionMode) + delete(rawMsg, key) + case "syntaxFormat": + err = unpopulate(val, "SyntaxFormat", &p.SyntaxFormat) + delete(rawMsg, key) + case "tlsAuthentication": + err = unpopulate(val, "TLSAuthentication", &p.TLSAuthentication) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &p.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RemoveVirtualMachineFromExadbVMClusterDetails. +func (r RemoveVirtualMachineFromExadbVMClusterDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dbNodes", r.DbNodes) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RemoveVirtualMachineFromExadbVMClusterDetails. +func (r *RemoveVirtualMachineFromExadbVMClusterDetails) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "dbNodes": + err = unpopulate(val, "DbNodes", &r.DbNodes) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceAnchor. +func (r ResourceAnchor) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", r.ID) + populate(objectMap, "location", r.Location) + populate(objectMap, "name", r.Name) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "systemData", r.SystemData) + populate(objectMap, "tags", r.Tags) + populate(objectMap, "type", r.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceAnchor. +func (r *ResourceAnchor) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &r.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &r.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &r.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &r.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &r.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &r.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceAnchorListResult. +func (r ResourceAnchorListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", r.NextLink) + populate(objectMap, "value", r.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceAnchorListResult. +func (r *ResourceAnchorListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &r.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &r.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceAnchorProperties. +func (r ResourceAnchorProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "linkedCompartmentId", r.LinkedCompartmentID) + populate(objectMap, "provisioningState", r.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceAnchorProperties. +func (r *ResourceAnchorProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "linkedCompartmentId": + err = unpopulate(val, "LinkedCompartmentID", &r.LinkedCompartmentID) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &r.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceAnchorUpdate. +func (r ResourceAnchorUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "tags", r.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ResourceAnchorUpdate. +func (r *ResourceAnchorUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "tags": + err = unpopulate(val, "Tags", &r.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RestoreAutonomousDatabaseDetails. +func (r RestoreAutonomousDatabaseDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "timestamp", r.Timestamp) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RestoreAutonomousDatabaseDetails. +func (r *RestoreAutonomousDatabaseDetails) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "timestamp": + err = unpopulateTime[datetime.RFC3339](val, "Timestamp", &r.Timestamp) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SaasSubscriptionDetails. +func (s SaasSubscriptionDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + populate(objectMap, "isAutoRenew", s.IsAutoRenew) + populate(objectMap, "isFreeTrial", s.IsFreeTrial) + populate(objectMap, "offerId", s.OfferID) + populate(objectMap, "planId", s.PlanID) + populate(objectMap, "publisherId", s.PublisherID) + populate(objectMap, "purchaserEmailId", s.PurchaserEmailID) + populate(objectMap, "purchaserTenantId", s.PurchaserTenantID) + populate(objectMap, "saasSubscriptionStatus", s.SaasSubscriptionStatus) + populate(objectMap, "subscriptionName", s.SubscriptionName) + populate(objectMap, "termUnit", s.TermUnit) + populateTime[datetime.RFC3339](objectMap, "timeCreated", s.TimeCreated) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SaasSubscriptionDetails. +func (s *SaasSubscriptionDetails) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "isAutoRenew": + err = unpopulate(val, "IsAutoRenew", &s.IsAutoRenew) + delete(rawMsg, key) + case "isFreeTrial": + err = unpopulate(val, "IsFreeTrial", &s.IsFreeTrial) + delete(rawMsg, key) + case "offerId": + err = unpopulate(val, "OfferID", &s.OfferID) + delete(rawMsg, key) + case "planId": + err = unpopulate(val, "PlanID", &s.PlanID) + delete(rawMsg, key) + case "publisherId": + err = unpopulate(val, "PublisherID", &s.PublisherID) + delete(rawMsg, key) + case "purchaserEmailId": + err = unpopulate(val, "PurchaserEmailID", &s.PurchaserEmailID) + delete(rawMsg, key) + case "purchaserTenantId": + err = unpopulate(val, "PurchaserTenantID", &s.PurchaserTenantID) + delete(rawMsg, key) + case "saasSubscriptionStatus": + err = unpopulate(val, "SaasSubscriptionStatus", &s.SaasSubscriptionStatus) + delete(rawMsg, key) + case "subscriptionName": + err = unpopulate(val, "SubscriptionName", &s.SubscriptionName) + delete(rawMsg, key) + case "termUnit": + err = unpopulate(val, "TermUnit", &s.TermUnit) + delete(rawMsg, key) + case "timeCreated": + err = unpopulateTime[datetime.RFC3339](val, "TimeCreated", &s.TimeCreated) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ScheduledOperationsType. +func (s ScheduledOperationsType) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dayOfWeek", s.DayOfWeek) + populate(objectMap, "scheduledStartTime", s.ScheduledStartTime) + populate(objectMap, "scheduledStopTime", s.ScheduledStopTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScheduledOperationsType. +func (s *ScheduledOperationsType) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "dayOfWeek": + err = unpopulate(val, "DayOfWeek", &s.DayOfWeek) + delete(rawMsg, key) + case "scheduledStartTime": + err = unpopulate(val, "ScheduledStartTime", &s.ScheduledStartTime) + delete(rawMsg, key) + case "scheduledStopTime": + err = unpopulate(val, "ScheduledStopTime", &s.ScheduledStopTime) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ScheduledOperationsTypeUpdate. +func (s ScheduledOperationsTypeUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "dayOfWeek", s.DayOfWeek) + populate(objectMap, "scheduledStartTime", s.ScheduledStartTime) + populate(objectMap, "scheduledStopTime", s.ScheduledStopTime) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ScheduledOperationsTypeUpdate. +func (s *ScheduledOperationsTypeUpdate) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "dayOfWeek": + err = unpopulate(val, "DayOfWeek", &s.DayOfWeek) + delete(rawMsg, key) + case "scheduledStartTime": + err = unpopulate(val, "ScheduledStartTime", &s.ScheduledStartTime) + delete(rawMsg, key) + case "scheduledStopTime": + err = unpopulate(val, "ScheduledStopTime", &s.ScheduledStopTime) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateTime[datetime.RFC3339](objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateTime[datetime.RFC3339](val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateTime[datetime.RFC3339](val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemVersion. +func (s SystemVersion) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", s.ID) + populate(objectMap, "name", s.Name) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "systemData", s.SystemData) + populate(objectMap, "type", s.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemVersion. +func (s *SystemVersion) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &s.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &s.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &s.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &s.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemVersionListResult. +func (s SystemVersionListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemVersionListResult. +func (s *SystemVersionListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &s.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemVersionProperties. +func (s SystemVersionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "systemVersion", s.SystemVersion) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemVersionProperties. +func (s *SystemVersionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "systemVersion": + err = unpopulate(val, "SystemVersion", &s.SystemVersion) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualNetworkAddress. +func (v VirtualNetworkAddress) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", v.ID) + populate(objectMap, "name", v.Name) + populate(objectMap, "properties", v.Properties) + populate(objectMap, "systemData", v.SystemData) + populate(objectMap, "type", v.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkAddress. +func (v *VirtualNetworkAddress) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &v.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &v.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &v.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &v.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &v.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualNetworkAddressListResult. +func (v VirtualNetworkAddressListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", v.NextLink) + populate(objectMap, "value", v.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkAddressListResult. +func (v *VirtualNetworkAddressListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &v.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &v.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualNetworkAddressProperties. +func (v VirtualNetworkAddressProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "domain", v.Domain) + populate(objectMap, "ipAddress", v.IPAddress) + populate(objectMap, "lifecycleDetails", v.LifecycleDetails) + populate(objectMap, "lifecycleState", v.LifecycleState) + populate(objectMap, "ocid", v.Ocid) + populate(objectMap, "provisioningState", v.ProvisioningState) + populateTime[datetime.RFC3339](objectMap, "timeAssigned", v.TimeAssigned) + populate(objectMap, "vmOcid", v.VMOcid) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VirtualNetworkAddressProperties. +func (v *VirtualNetworkAddressProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "domain": + err = unpopulate(val, "Domain", &v.Domain) + delete(rawMsg, key) + case "ipAddress": + err = unpopulate(val, "IPAddress", &v.IPAddress) + delete(rawMsg, key) + case "lifecycleDetails": + err = unpopulate(val, "LifecycleDetails", &v.LifecycleDetails) + delete(rawMsg, key) + case "lifecycleState": + err = unpopulate(val, "LifecycleState", &v.LifecycleState) + delete(rawMsg, key) + case "ocid": + err = unpopulate(val, "Ocid", &v.Ocid) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &v.ProvisioningState) + delete(rawMsg, key) + case "timeAssigned": + err = unpopulateTime[datetime.RFC3339](val, "TimeAssigned", &v.TimeAssigned) + delete(rawMsg, key) + case "vmOcid": + err = unpopulate(val, "VMOcid", &v.VMOcid) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/local/armoracledatabase/zz_networkanchors_client.go b/test/local/armoracledatabase/zz_networkanchors_client.go new file mode 100644 index 000000000000..b647e0614bc9 --- /dev/null +++ b/test/local/armoracledatabase/zz_networkanchors_client.go @@ -0,0 +1,440 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// NetworkAnchorsClient contains the methods for the NetworkAnchors group. +// Don't use this type directly, use NewNetworkAnchorsClient() instead. +// +// Generated from API version 2025-09-01 +type NetworkAnchorsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewNetworkAnchorsClient creates a new instance of NetworkAnchorsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewNetworkAnchorsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*NetworkAnchorsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &NetworkAnchorsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create a NetworkAnchor +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - networkAnchorName - The name of the NetworkAnchor +// - resource - Resource create parameters. +// - options - NetworkAnchorsClientBeginCreateOrUpdateOptions contains the optional parameters for the NetworkAnchorsClient.BeginCreateOrUpdate +// method. +func (client *NetworkAnchorsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, networkAnchorName string, resource NetworkAnchor, options *NetworkAnchorsClientBeginCreateOrUpdateOptions) (*runtime.Poller[NetworkAnchorsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, networkAnchorName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[NetworkAnchorsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[NetworkAnchorsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create a NetworkAnchor +// If the operation fails it returns an *azcore.ResponseError type. +func (client *NetworkAnchorsClient) createOrUpdate(ctx context.Context, resourceGroupName string, networkAnchorName string, resource NetworkAnchor, options *NetworkAnchorsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "NetworkAnchorsClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, networkAnchorName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *NetworkAnchorsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, networkAnchorName string, resource NetworkAnchor, _ *NetworkAnchorsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/networkAnchors/{networkAnchorName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkAnchorName == "" { + return nil, errors.New("parameter networkAnchorName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkAnchorName}", url.PathEscape(networkAnchorName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a NetworkAnchor +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - networkAnchorName - The name of the NetworkAnchor +// - options - NetworkAnchorsClientBeginDeleteOptions contains the optional parameters for the NetworkAnchorsClient.BeginDelete +// method. +func (client *NetworkAnchorsClient) BeginDelete(ctx context.Context, resourceGroupName string, networkAnchorName string, options *NetworkAnchorsClientBeginDeleteOptions) (*runtime.Poller[NetworkAnchorsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, networkAnchorName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[NetworkAnchorsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[NetworkAnchorsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a NetworkAnchor +// If the operation fails it returns an *azcore.ResponseError type. +func (client *NetworkAnchorsClient) deleteOperation(ctx context.Context, resourceGroupName string, networkAnchorName string, options *NetworkAnchorsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "NetworkAnchorsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, networkAnchorName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *NetworkAnchorsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, networkAnchorName string, _ *NetworkAnchorsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/networkAnchors/{networkAnchorName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkAnchorName == "" { + return nil, errors.New("parameter networkAnchorName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkAnchorName}", url.PathEscape(networkAnchorName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a NetworkAnchor +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - networkAnchorName - The name of the NetworkAnchor +// - options - NetworkAnchorsClientGetOptions contains the optional parameters for the NetworkAnchorsClient.Get method. +func (client *NetworkAnchorsClient) Get(ctx context.Context, resourceGroupName string, networkAnchorName string, options *NetworkAnchorsClientGetOptions) (NetworkAnchorsClientGetResponse, error) { + var err error + const operationName = "NetworkAnchorsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, networkAnchorName, options) + if err != nil { + return NetworkAnchorsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return NetworkAnchorsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return NetworkAnchorsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *NetworkAnchorsClient) getCreateRequest(ctx context.Context, resourceGroupName string, networkAnchorName string, _ *NetworkAnchorsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/networkAnchors/{networkAnchorName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkAnchorName == "" { + return nil, errors.New("parameter networkAnchorName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkAnchorName}", url.PathEscape(networkAnchorName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *NetworkAnchorsClient) getHandleResponse(resp *http.Response) (NetworkAnchorsClientGetResponse, error) { + result := NetworkAnchorsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.NetworkAnchor); err != nil { + return NetworkAnchorsClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - List NetworkAnchor resources by resource group +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - NetworkAnchorsClientListByResourceGroupOptions contains the optional parameters for the NetworkAnchorsClient.NewListByResourceGroupPager +// method. +func (client *NetworkAnchorsClient) NewListByResourceGroupPager(resourceGroupName string, options *NetworkAnchorsClientListByResourceGroupOptions) *runtime.Pager[NetworkAnchorsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[NetworkAnchorsClientListByResourceGroupResponse]{ + More: func(page NetworkAnchorsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *NetworkAnchorsClientListByResourceGroupResponse) (NetworkAnchorsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "NetworkAnchorsClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return NetworkAnchorsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *NetworkAnchorsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *NetworkAnchorsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/networkAnchors" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *NetworkAnchorsClient) listByResourceGroupHandleResponse(resp *http.Response) (NetworkAnchorsClientListByResourceGroupResponse, error) { + result := NetworkAnchorsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.NetworkAnchorListResult); err != nil { + return NetworkAnchorsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - List NetworkAnchor resources by subscription ID +// - options - NetworkAnchorsClientListBySubscriptionOptions contains the optional parameters for the NetworkAnchorsClient.NewListBySubscriptionPager +// method. +func (client *NetworkAnchorsClient) NewListBySubscriptionPager(options *NetworkAnchorsClientListBySubscriptionOptions) *runtime.Pager[NetworkAnchorsClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[NetworkAnchorsClientListBySubscriptionResponse]{ + More: func(page NetworkAnchorsClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *NetworkAnchorsClientListBySubscriptionResponse) (NetworkAnchorsClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "NetworkAnchorsClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return NetworkAnchorsClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *NetworkAnchorsClient) listBySubscriptionCreateRequest(ctx context.Context, _ *NetworkAnchorsClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/networkAnchors" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *NetworkAnchorsClient) listBySubscriptionHandleResponse(resp *http.Response) (NetworkAnchorsClientListBySubscriptionResponse, error) { + result := NetworkAnchorsClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.NetworkAnchorListResult); err != nil { + return NetworkAnchorsClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update a NetworkAnchor +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - networkAnchorName - The name of the NetworkAnchor +// - properties - The resource properties to be updated. +// - options - NetworkAnchorsClientBeginUpdateOptions contains the optional parameters for the NetworkAnchorsClient.BeginUpdate +// method. +func (client *NetworkAnchorsClient) BeginUpdate(ctx context.Context, resourceGroupName string, networkAnchorName string, properties NetworkAnchorUpdate, options *NetworkAnchorsClientBeginUpdateOptions) (*runtime.Poller[NetworkAnchorsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, networkAnchorName, properties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[NetworkAnchorsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[NetworkAnchorsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a NetworkAnchor +// If the operation fails it returns an *azcore.ResponseError type. +func (client *NetworkAnchorsClient) update(ctx context.Context, resourceGroupName string, networkAnchorName string, properties NetworkAnchorUpdate, options *NetworkAnchorsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "NetworkAnchorsClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, networkAnchorName, properties, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *NetworkAnchorsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, networkAnchorName string, properties NetworkAnchorUpdate, _ *NetworkAnchorsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/networkAnchors/{networkAnchorName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if networkAnchorName == "" { + return nil, errors.New("parameter networkAnchorName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{networkAnchorName}", url.PathEscape(networkAnchorName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armoracledatabase/zz_operations_client.go b/test/local/armoracledatabase/zz_operations_client.go new file mode 100644 index 000000000000..2b101141f8a2 --- /dev/null +++ b/test/local/armoracledatabase/zz_operations_client.go @@ -0,0 +1,85 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +// +// Generated from API version 2025-09-01 +type OperationsClient struct { + internal *arm.Client +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewOperationsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*OperationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OperationsClient{ + internal: cl, + } + return client, nil +} + +// NewListPager - List the operations for the provider +// - options - OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +func (client *OperationsClient) NewListPager(options *OperationsClientListOptions) *runtime.Pager[OperationsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[OperationsClientListResponse]{ + More: func(page OperationsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OperationsClientListResponse) (OperationsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OperationsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return OperationsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, _ *OperationsClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Oracle.Database/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsClientListResponse, error) { + result := OperationsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armoracledatabase/zz_options.go b/test/local/armoracledatabase/zz_options.go new file mode 100644 index 000000000000..7a9328c6215f --- /dev/null +++ b/test/local/armoracledatabase/zz_options.go @@ -0,0 +1,714 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +// AutonomousDatabaseBackupsClientBeginCreateOrUpdateOptions contains the optional parameters for the AutonomousDatabaseBackupsClient.BeginCreateOrUpdate +// method. +type AutonomousDatabaseBackupsClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// AutonomousDatabaseBackupsClientBeginDeleteOptions contains the optional parameters for the AutonomousDatabaseBackupsClient.BeginDelete +// method. +type AutonomousDatabaseBackupsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// AutonomousDatabaseBackupsClientBeginUpdateOptions contains the optional parameters for the AutonomousDatabaseBackupsClient.BeginUpdate +// method. +type AutonomousDatabaseBackupsClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// AutonomousDatabaseBackupsClientGetOptions contains the optional parameters for the AutonomousDatabaseBackupsClient.Get +// method. +type AutonomousDatabaseBackupsClientGetOptions struct { + // placeholder for future optional parameters +} + +// AutonomousDatabaseBackupsClientListByAutonomousDatabaseOptions contains the optional parameters for the AutonomousDatabaseBackupsClient.NewListByAutonomousDatabasePager +// method. +type AutonomousDatabaseBackupsClientListByAutonomousDatabaseOptions struct { + // placeholder for future optional parameters +} + +// AutonomousDatabaseCharacterSetsClientGetOptions contains the optional parameters for the AutonomousDatabaseCharacterSetsClient.Get +// method. +type AutonomousDatabaseCharacterSetsClientGetOptions struct { + // placeholder for future optional parameters +} + +// AutonomousDatabaseCharacterSetsClientListByLocationOptions contains the optional parameters for the AutonomousDatabaseCharacterSetsClient.NewListByLocationPager +// method. +type AutonomousDatabaseCharacterSetsClientListByLocationOptions struct { + // placeholder for future optional parameters +} + +// AutonomousDatabaseNationalCharacterSetsClientGetOptions contains the optional parameters for the AutonomousDatabaseNationalCharacterSetsClient.Get +// method. +type AutonomousDatabaseNationalCharacterSetsClientGetOptions struct { + // placeholder for future optional parameters +} + +// AutonomousDatabaseNationalCharacterSetsClientListByLocationOptions contains the optional parameters for the AutonomousDatabaseNationalCharacterSetsClient.NewListByLocationPager +// method. +type AutonomousDatabaseNationalCharacterSetsClientListByLocationOptions struct { + // placeholder for future optional parameters +} + +// AutonomousDatabaseVersionsClientGetOptions contains the optional parameters for the AutonomousDatabaseVersionsClient.Get +// method. +type AutonomousDatabaseVersionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// AutonomousDatabaseVersionsClientListByLocationOptions contains the optional parameters for the AutonomousDatabaseVersionsClient.NewListByLocationPager +// method. +type AutonomousDatabaseVersionsClientListByLocationOptions struct { + // placeholder for future optional parameters +} + +// AutonomousDatabasesClientBeginActionOptions contains the optional parameters for the AutonomousDatabasesClient.BeginAction +// method. +type AutonomousDatabasesClientBeginActionOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// AutonomousDatabasesClientBeginChangeDisasterRecoveryConfigurationOptions contains the optional parameters for the AutonomousDatabasesClient.BeginChangeDisasterRecoveryConfiguration +// method. +type AutonomousDatabasesClientBeginChangeDisasterRecoveryConfigurationOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// AutonomousDatabasesClientBeginCreateOrUpdateOptions contains the optional parameters for the AutonomousDatabasesClient.BeginCreateOrUpdate +// method. +type AutonomousDatabasesClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// AutonomousDatabasesClientBeginDeleteOptions contains the optional parameters for the AutonomousDatabasesClient.BeginDelete +// method. +type AutonomousDatabasesClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// AutonomousDatabasesClientBeginFailoverOptions contains the optional parameters for the AutonomousDatabasesClient.BeginFailover +// method. +type AutonomousDatabasesClientBeginFailoverOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// AutonomousDatabasesClientBeginRestoreOptions contains the optional parameters for the AutonomousDatabasesClient.BeginRestore +// method. +type AutonomousDatabasesClientBeginRestoreOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// AutonomousDatabasesClientBeginShrinkOptions contains the optional parameters for the AutonomousDatabasesClient.BeginShrink +// method. +type AutonomousDatabasesClientBeginShrinkOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// AutonomousDatabasesClientBeginSwitchoverOptions contains the optional parameters for the AutonomousDatabasesClient.BeginSwitchover +// method. +type AutonomousDatabasesClientBeginSwitchoverOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// AutonomousDatabasesClientBeginUpdateOptions contains the optional parameters for the AutonomousDatabasesClient.BeginUpdate +// method. +type AutonomousDatabasesClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// AutonomousDatabasesClientGenerateWalletOptions contains the optional parameters for the AutonomousDatabasesClient.GenerateWallet +// method. +type AutonomousDatabasesClientGenerateWalletOptions struct { + // placeholder for future optional parameters +} + +// AutonomousDatabasesClientGetOptions contains the optional parameters for the AutonomousDatabasesClient.Get method. +type AutonomousDatabasesClientGetOptions struct { + // placeholder for future optional parameters +} + +// AutonomousDatabasesClientListByResourceGroupOptions contains the optional parameters for the AutonomousDatabasesClient.NewListByResourceGroupPager +// method. +type AutonomousDatabasesClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// AutonomousDatabasesClientListBySubscriptionOptions contains the optional parameters for the AutonomousDatabasesClient.NewListBySubscriptionPager +// method. +type AutonomousDatabasesClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// CloudExadataInfrastructuresClientBeginAddStorageCapacityOptions contains the optional parameters for the CloudExadataInfrastructuresClient.BeginAddStorageCapacity +// method. +type CloudExadataInfrastructuresClientBeginAddStorageCapacityOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CloudExadataInfrastructuresClientBeginConfigureExascaleOptions contains the optional parameters for the CloudExadataInfrastructuresClient.BeginConfigureExascale +// method. +type CloudExadataInfrastructuresClientBeginConfigureExascaleOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CloudExadataInfrastructuresClientBeginCreateOrUpdateOptions contains the optional parameters for the CloudExadataInfrastructuresClient.BeginCreateOrUpdate +// method. +type CloudExadataInfrastructuresClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CloudExadataInfrastructuresClientBeginDeleteOptions contains the optional parameters for the CloudExadataInfrastructuresClient.BeginDelete +// method. +type CloudExadataInfrastructuresClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CloudExadataInfrastructuresClientBeginUpdateOptions contains the optional parameters for the CloudExadataInfrastructuresClient.BeginUpdate +// method. +type CloudExadataInfrastructuresClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CloudExadataInfrastructuresClientGetOptions contains the optional parameters for the CloudExadataInfrastructuresClient.Get +// method. +type CloudExadataInfrastructuresClientGetOptions struct { + // placeholder for future optional parameters +} + +// CloudExadataInfrastructuresClientListByResourceGroupOptions contains the optional parameters for the CloudExadataInfrastructuresClient.NewListByResourceGroupPager +// method. +type CloudExadataInfrastructuresClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// CloudExadataInfrastructuresClientListBySubscriptionOptions contains the optional parameters for the CloudExadataInfrastructuresClient.NewListBySubscriptionPager +// method. +type CloudExadataInfrastructuresClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// CloudVMClustersClientBeginAddVMsOptions contains the optional parameters for the CloudVMClustersClient.BeginAddVMs method. +type CloudVMClustersClientBeginAddVMsOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CloudVMClustersClientBeginCreateOrUpdateOptions contains the optional parameters for the CloudVMClustersClient.BeginCreateOrUpdate +// method. +type CloudVMClustersClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CloudVMClustersClientBeginDeleteOptions contains the optional parameters for the CloudVMClustersClient.BeginDelete method. +type CloudVMClustersClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CloudVMClustersClientBeginRemoveVMsOptions contains the optional parameters for the CloudVMClustersClient.BeginRemoveVMs +// method. +type CloudVMClustersClientBeginRemoveVMsOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CloudVMClustersClientBeginUpdateOptions contains the optional parameters for the CloudVMClustersClient.BeginUpdate method. +type CloudVMClustersClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// CloudVMClustersClientGetOptions contains the optional parameters for the CloudVMClustersClient.Get method. +type CloudVMClustersClientGetOptions struct { + // placeholder for future optional parameters +} + +// CloudVMClustersClientListByResourceGroupOptions contains the optional parameters for the CloudVMClustersClient.NewListByResourceGroupPager +// method. +type CloudVMClustersClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// CloudVMClustersClientListBySubscriptionOptions contains the optional parameters for the CloudVMClustersClient.NewListBySubscriptionPager +// method. +type CloudVMClustersClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// CloudVMClustersClientListPrivateIPAddressesOptions contains the optional parameters for the CloudVMClustersClient.ListPrivateIPAddresses +// method. +type CloudVMClustersClientListPrivateIPAddressesOptions struct { + // placeholder for future optional parameters +} + +// DNSPrivateViewsClientGetOptions contains the optional parameters for the DNSPrivateViewsClient.Get method. +type DNSPrivateViewsClientGetOptions struct { + // placeholder for future optional parameters +} + +// DNSPrivateViewsClientListByLocationOptions contains the optional parameters for the DNSPrivateViewsClient.NewListByLocationPager +// method. +type DNSPrivateViewsClientListByLocationOptions struct { + // placeholder for future optional parameters +} + +// DNSPrivateZonesClientGetOptions contains the optional parameters for the DNSPrivateZonesClient.Get method. +type DNSPrivateZonesClientGetOptions struct { + // placeholder for future optional parameters +} + +// DNSPrivateZonesClientListByLocationOptions contains the optional parameters for the DNSPrivateZonesClient.NewListByLocationPager +// method. +type DNSPrivateZonesClientListByLocationOptions struct { + // placeholder for future optional parameters +} + +// DbNodesClientBeginActionOptions contains the optional parameters for the DbNodesClient.BeginAction method. +type DbNodesClientBeginActionOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// DbNodesClientGetOptions contains the optional parameters for the DbNodesClient.Get method. +type DbNodesClientGetOptions struct { + // placeholder for future optional parameters +} + +// DbNodesClientListByCloudVMClusterOptions contains the optional parameters for the DbNodesClient.NewListByCloudVMClusterPager +// method. +type DbNodesClientListByCloudVMClusterOptions struct { + // placeholder for future optional parameters +} + +// DbServersClientGetOptions contains the optional parameters for the DbServersClient.Get method. +type DbServersClientGetOptions struct { + // placeholder for future optional parameters +} + +// DbServersClientListByCloudExadataInfrastructureOptions contains the optional parameters for the DbServersClient.NewListByCloudExadataInfrastructurePager +// method. +type DbServersClientListByCloudExadataInfrastructureOptions struct { + // placeholder for future optional parameters +} + +// DbSystemShapesClientGetOptions contains the optional parameters for the DbSystemShapesClient.Get method. +type DbSystemShapesClientGetOptions struct { + // placeholder for future optional parameters +} + +// DbSystemShapesClientListByLocationOptions contains the optional parameters for the DbSystemShapesClient.NewListByLocationPager +// method. +type DbSystemShapesClientListByLocationOptions struct { + // Filters the result for the given Shape Attribute, such as BLOCK_STORAGE or SMART_STORAGE. + ShapeAttribute *string + + // Filters the result for the given Azure Availability Zone + Zone *string +} + +// DbSystemsClientBeginCreateOrUpdateOptions contains the optional parameters for the DbSystemsClient.BeginCreateOrUpdate +// method. +type DbSystemsClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// DbSystemsClientBeginDeleteOptions contains the optional parameters for the DbSystemsClient.BeginDelete method. +type DbSystemsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// DbSystemsClientBeginUpdateOptions contains the optional parameters for the DbSystemsClient.BeginUpdate method. +type DbSystemsClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// DbSystemsClientGetOptions contains the optional parameters for the DbSystemsClient.Get method. +type DbSystemsClientGetOptions struct { + // placeholder for future optional parameters +} + +// DbSystemsClientListByResourceGroupOptions contains the optional parameters for the DbSystemsClient.NewListByResourceGroupPager +// method. +type DbSystemsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// DbSystemsClientListBySubscriptionOptions contains the optional parameters for the DbSystemsClient.NewListBySubscriptionPager +// method. +type DbSystemsClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// DbVersionsClientGetOptions contains the optional parameters for the DbVersionsClient.Get method. +type DbVersionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// DbVersionsClientListByLocationOptions contains the optional parameters for the DbVersionsClient.NewListByLocationPager +// method. +type DbVersionsClientListByLocationOptions struct { + // The DB system AzureId. If provided, filters the results to the set of database versions which are supported for the DB + // system. + DbSystemID *string + + // If provided, filters the results to the set of database versions which are supported for the given shape. e.g., VM.Standard.E5.Flex + DbSystemShape *BaseDbSystemShapes + + // If true, filters the results to the set of Oracle Database versions that are supported for the database software images. + IsDatabaseSoftwareImageSupported *bool + + // If true, filters the results to the set of database versions which are supported for Upgrade. + IsUpgradeSupported *bool + + // If provided, filters the results to the set of database versions which are supported for the given shape family. + ShapeFamily *ShapeFamilyType + + // The DB system storage management option. Used to list database versions available for that storage manager. Valid values + // are ASM and LVM. + StorageManagement *StorageManagementType +} + +// ExadbVMClustersClientBeginCreateOrUpdateOptions contains the optional parameters for the ExadbVMClustersClient.BeginCreateOrUpdate +// method. +type ExadbVMClustersClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ExadbVMClustersClientBeginDeleteOptions contains the optional parameters for the ExadbVMClustersClient.BeginDelete method. +type ExadbVMClustersClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ExadbVMClustersClientBeginRemoveVMsOptions contains the optional parameters for the ExadbVMClustersClient.BeginRemoveVMs +// method. +type ExadbVMClustersClientBeginRemoveVMsOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ExadbVMClustersClientBeginUpdateOptions contains the optional parameters for the ExadbVMClustersClient.BeginUpdate method. +type ExadbVMClustersClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ExadbVMClustersClientGetOptions contains the optional parameters for the ExadbVMClustersClient.Get method. +type ExadbVMClustersClientGetOptions struct { + // placeholder for future optional parameters +} + +// ExadbVMClustersClientListByResourceGroupOptions contains the optional parameters for the ExadbVMClustersClient.NewListByResourceGroupPager +// method. +type ExadbVMClustersClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// ExadbVMClustersClientListBySubscriptionOptions contains the optional parameters for the ExadbVMClustersClient.NewListBySubscriptionPager +// method. +type ExadbVMClustersClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// ExascaleDbNodesClientBeginActionOptions contains the optional parameters for the ExascaleDbNodesClient.BeginAction method. +type ExascaleDbNodesClientBeginActionOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ExascaleDbNodesClientGetOptions contains the optional parameters for the ExascaleDbNodesClient.Get method. +type ExascaleDbNodesClientGetOptions struct { + // placeholder for future optional parameters +} + +// ExascaleDbNodesClientListByParentOptions contains the optional parameters for the ExascaleDbNodesClient.NewListByParentPager +// method. +type ExascaleDbNodesClientListByParentOptions struct { + // placeholder for future optional parameters +} + +// ExascaleDbStorageVaultsClientBeginCreateOptions contains the optional parameters for the ExascaleDbStorageVaultsClient.BeginCreate +// method. +type ExascaleDbStorageVaultsClientBeginCreateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ExascaleDbStorageVaultsClientBeginDeleteOptions contains the optional parameters for the ExascaleDbStorageVaultsClient.BeginDelete +// method. +type ExascaleDbStorageVaultsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ExascaleDbStorageVaultsClientBeginUpdateOptions contains the optional parameters for the ExascaleDbStorageVaultsClient.BeginUpdate +// method. +type ExascaleDbStorageVaultsClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ExascaleDbStorageVaultsClientGetOptions contains the optional parameters for the ExascaleDbStorageVaultsClient.Get method. +type ExascaleDbStorageVaultsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ExascaleDbStorageVaultsClientListByResourceGroupOptions contains the optional parameters for the ExascaleDbStorageVaultsClient.NewListByResourceGroupPager +// method. +type ExascaleDbStorageVaultsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// ExascaleDbStorageVaultsClientListBySubscriptionOptions contains the optional parameters for the ExascaleDbStorageVaultsClient.NewListBySubscriptionPager +// method. +type ExascaleDbStorageVaultsClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// FlexComponentsClientGetOptions contains the optional parameters for the FlexComponentsClient.Get method. +type FlexComponentsClientGetOptions struct { + // placeholder for future optional parameters +} + +// FlexComponentsClientListByParentOptions contains the optional parameters for the FlexComponentsClient.NewListByParentPager +// method. +type FlexComponentsClientListByParentOptions struct { + // If provided, filters the results for the given shape + Shape *SystemShapes +} + +// GiMinorVersionsClientGetOptions contains the optional parameters for the GiMinorVersionsClient.Get method. +type GiMinorVersionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// GiMinorVersionsClientListByParentOptions contains the optional parameters for the GiMinorVersionsClient.NewListByParentPager +// method. +type GiMinorVersionsClientListByParentOptions struct { + // If provided, filters the results to the set of database versions which are supported for the given shape family. + ShapeFamily *ShapeFamily + + // Filters the result for the given Azure Availability Zone + Zone *string +} + +// GiVersionsClientGetOptions contains the optional parameters for the GiVersionsClient.Get method. +type GiVersionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// GiVersionsClientListByLocationOptions contains the optional parameters for the GiVersionsClient.NewListByLocationPager +// method. +type GiVersionsClientListByLocationOptions struct { + // If provided, filters the results for the given shape + Shape *SystemShapes + + // Filters the result for the given Shape Attribute, such as BLOCK_STORAGE or SMART_STORAGE. + ShapeAttribute *string + + // Filters the result for the given Azure Availability Zone + Zone *string +} + +// NetworkAnchorsClientBeginCreateOrUpdateOptions contains the optional parameters for the NetworkAnchorsClient.BeginCreateOrUpdate +// method. +type NetworkAnchorsClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// NetworkAnchorsClientBeginDeleteOptions contains the optional parameters for the NetworkAnchorsClient.BeginDelete method. +type NetworkAnchorsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// NetworkAnchorsClientBeginUpdateOptions contains the optional parameters for the NetworkAnchorsClient.BeginUpdate method. +type NetworkAnchorsClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// NetworkAnchorsClientGetOptions contains the optional parameters for the NetworkAnchorsClient.Get method. +type NetworkAnchorsClientGetOptions struct { + // placeholder for future optional parameters +} + +// NetworkAnchorsClientListByResourceGroupOptions contains the optional parameters for the NetworkAnchorsClient.NewListByResourceGroupPager +// method. +type NetworkAnchorsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// NetworkAnchorsClientListBySubscriptionOptions contains the optional parameters for the NetworkAnchorsClient.NewListBySubscriptionPager +// method. +type NetworkAnchorsClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// OperationsClientListOptions contains the optional parameters for the OperationsClient.NewListPager method. +type OperationsClientListOptions struct { + // placeholder for future optional parameters +} + +// OracleSubscriptionsClientBeginAddAzureSubscriptionsOptions contains the optional parameters for the OracleSubscriptionsClient.BeginAddAzureSubscriptions +// method. +type OracleSubscriptionsClientBeginAddAzureSubscriptionsOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// OracleSubscriptionsClientBeginCreateOrUpdateOptions contains the optional parameters for the OracleSubscriptionsClient.BeginCreateOrUpdate +// method. +type OracleSubscriptionsClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// OracleSubscriptionsClientBeginDeleteOptions contains the optional parameters for the OracleSubscriptionsClient.BeginDelete +// method. +type OracleSubscriptionsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// OracleSubscriptionsClientBeginListActivationLinksOptions contains the optional parameters for the OracleSubscriptionsClient.BeginListActivationLinks +// method. +type OracleSubscriptionsClientBeginListActivationLinksOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// OracleSubscriptionsClientBeginListCloudAccountDetailsOptions contains the optional parameters for the OracleSubscriptionsClient.BeginListCloudAccountDetails +// method. +type OracleSubscriptionsClientBeginListCloudAccountDetailsOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// OracleSubscriptionsClientBeginListSaasSubscriptionDetailsOptions contains the optional parameters for the OracleSubscriptionsClient.BeginListSaasSubscriptionDetails +// method. +type OracleSubscriptionsClientBeginListSaasSubscriptionDetailsOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// OracleSubscriptionsClientBeginUpdateOptions contains the optional parameters for the OracleSubscriptionsClient.BeginUpdate +// method. +type OracleSubscriptionsClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// OracleSubscriptionsClientGetOptions contains the optional parameters for the OracleSubscriptionsClient.Get method. +type OracleSubscriptionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// OracleSubscriptionsClientListBySubscriptionOptions contains the optional parameters for the OracleSubscriptionsClient.NewListBySubscriptionPager +// method. +type OracleSubscriptionsClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// ResourceAnchorsClientBeginCreateOrUpdateOptions contains the optional parameters for the ResourceAnchorsClient.BeginCreateOrUpdate +// method. +type ResourceAnchorsClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ResourceAnchorsClientBeginDeleteOptions contains the optional parameters for the ResourceAnchorsClient.BeginDelete method. +type ResourceAnchorsClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ResourceAnchorsClientBeginUpdateOptions contains the optional parameters for the ResourceAnchorsClient.BeginUpdate method. +type ResourceAnchorsClientBeginUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// ResourceAnchorsClientGetOptions contains the optional parameters for the ResourceAnchorsClient.Get method. +type ResourceAnchorsClientGetOptions struct { + // placeholder for future optional parameters +} + +// ResourceAnchorsClientListByResourceGroupOptions contains the optional parameters for the ResourceAnchorsClient.NewListByResourceGroupPager +// method. +type ResourceAnchorsClientListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// ResourceAnchorsClientListBySubscriptionOptions contains the optional parameters for the ResourceAnchorsClient.NewListBySubscriptionPager +// method. +type ResourceAnchorsClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// SystemVersionsClientGetOptions contains the optional parameters for the SystemVersionsClient.Get method. +type SystemVersionsClientGetOptions struct { + // placeholder for future optional parameters +} + +// SystemVersionsClientListByLocationOptions contains the optional parameters for the SystemVersionsClient.NewListByLocationPager +// method. +type SystemVersionsClientListByLocationOptions struct { + // placeholder for future optional parameters +} + +// VirtualNetworkAddressesClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualNetworkAddressesClient.BeginCreateOrUpdate +// method. +type VirtualNetworkAddressesClientBeginCreateOrUpdateOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// VirtualNetworkAddressesClientBeginDeleteOptions contains the optional parameters for the VirtualNetworkAddressesClient.BeginDelete +// method. +type VirtualNetworkAddressesClientBeginDeleteOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// VirtualNetworkAddressesClientGetOptions contains the optional parameters for the VirtualNetworkAddressesClient.Get method. +type VirtualNetworkAddressesClientGetOptions struct { + // placeholder for future optional parameters +} + +// VirtualNetworkAddressesClientListByCloudVMClusterOptions contains the optional parameters for the VirtualNetworkAddressesClient.NewListByCloudVMClusterPager +// method. +type VirtualNetworkAddressesClientListByCloudVMClusterOptions struct { + // placeholder for future optional parameters +} diff --git a/test/local/armoracledatabase/zz_oraclesubscriptions_client.go b/test/local/armoracledatabase/zz_oraclesubscriptions_client.go new file mode 100644 index 000000000000..b137ccec435a --- /dev/null +++ b/test/local/armoracledatabase/zz_oraclesubscriptions_client.go @@ -0,0 +1,594 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// OracleSubscriptionsClient contains the methods for the OracleSubscriptions group. +// Don't use this type directly, use NewOracleSubscriptionsClient() instead. +// +// Generated from API version 2025-09-01 +type OracleSubscriptionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewOracleSubscriptionsClient creates a new instance of OracleSubscriptionsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewOracleSubscriptionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*OracleSubscriptionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &OracleSubscriptionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginAddAzureSubscriptions - Add Azure Subscriptions +// If the operation fails it returns an *azcore.ResponseError type. +// - body - The content of the action request +// - options - OracleSubscriptionsClientBeginAddAzureSubscriptionsOptions contains the optional parameters for the OracleSubscriptionsClient.BeginAddAzureSubscriptions +// method. +func (client *OracleSubscriptionsClient) BeginAddAzureSubscriptions(ctx context.Context, body AzureSubscriptions, options *OracleSubscriptionsClientBeginAddAzureSubscriptionsOptions) (*runtime.Poller[OracleSubscriptionsClientAddAzureSubscriptionsResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.addAzureSubscriptions(ctx, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[OracleSubscriptionsClientAddAzureSubscriptionsResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[OracleSubscriptionsClientAddAzureSubscriptionsResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// AddAzureSubscriptions - Add Azure Subscriptions +// If the operation fails it returns an *azcore.ResponseError type. +func (client *OracleSubscriptionsClient) addAzureSubscriptions(ctx context.Context, body AzureSubscriptions, options *OracleSubscriptionsClientBeginAddAzureSubscriptionsOptions) (*http.Response, error) { + var err error + const operationName = "OracleSubscriptionsClient.BeginAddAzureSubscriptions" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.addAzureSubscriptionsCreateRequest(ctx, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// addAzureSubscriptionsCreateRequest creates the AddAzureSubscriptions request. +func (client *OracleSubscriptionsClient) addAzureSubscriptionsCreateRequest(ctx context.Context, body AzureSubscriptions, _ *OracleSubscriptionsClientBeginAddAzureSubscriptionsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/oracleSubscriptions/default/addAzureSubscriptions" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// BeginCreateOrUpdate - Create a OracleSubscription +// If the operation fails it returns an *azcore.ResponseError type. +// - resource - Resource create parameters. +// - options - OracleSubscriptionsClientBeginCreateOrUpdateOptions contains the optional parameters for the OracleSubscriptionsClient.BeginCreateOrUpdate +// method. +func (client *OracleSubscriptionsClient) BeginCreateOrUpdate(ctx context.Context, resource OracleSubscription, options *OracleSubscriptionsClientBeginCreateOrUpdateOptions) (*runtime.Poller[OracleSubscriptionsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[OracleSubscriptionsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[OracleSubscriptionsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create a OracleSubscription +// If the operation fails it returns an *azcore.ResponseError type. +func (client *OracleSubscriptionsClient) createOrUpdate(ctx context.Context, resource OracleSubscription, options *OracleSubscriptionsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "OracleSubscriptionsClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *OracleSubscriptionsClient) createOrUpdateCreateRequest(ctx context.Context, resource OracleSubscription, _ *OracleSubscriptionsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/oracleSubscriptions/default" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a OracleSubscription +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OracleSubscriptionsClientBeginDeleteOptions contains the optional parameters for the OracleSubscriptionsClient.BeginDelete +// method. +func (client *OracleSubscriptionsClient) BeginDelete(ctx context.Context, options *OracleSubscriptionsClientBeginDeleteOptions) (*runtime.Poller[OracleSubscriptionsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[OracleSubscriptionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[OracleSubscriptionsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a OracleSubscription +// If the operation fails it returns an *azcore.ResponseError type. +func (client *OracleSubscriptionsClient) deleteOperation(ctx context.Context, options *OracleSubscriptionsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "OracleSubscriptionsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *OracleSubscriptionsClient) deleteCreateRequest(ctx context.Context, _ *OracleSubscriptionsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/oracleSubscriptions/default" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a OracleSubscription +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OracleSubscriptionsClientGetOptions contains the optional parameters for the OracleSubscriptionsClient.Get method. +func (client *OracleSubscriptionsClient) Get(ctx context.Context, options *OracleSubscriptionsClientGetOptions) (OracleSubscriptionsClientGetResponse, error) { + var err error + const operationName = "OracleSubscriptionsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return OracleSubscriptionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return OracleSubscriptionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return OracleSubscriptionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *OracleSubscriptionsClient) getCreateRequest(ctx context.Context, _ *OracleSubscriptionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/oracleSubscriptions/default" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *OracleSubscriptionsClient) getHandleResponse(resp *http.Response) (OracleSubscriptionsClientGetResponse, error) { + result := OracleSubscriptionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OracleSubscription); err != nil { + return OracleSubscriptionsClientGetResponse{}, err + } + return result, nil +} + +// BeginListActivationLinks - List Activation Links +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OracleSubscriptionsClientBeginListActivationLinksOptions contains the optional parameters for the OracleSubscriptionsClient.BeginListActivationLinks +// method. +func (client *OracleSubscriptionsClient) BeginListActivationLinks(ctx context.Context, options *OracleSubscriptionsClientBeginListActivationLinksOptions) (*runtime.Poller[OracleSubscriptionsClientListActivationLinksResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.listActivationLinks(ctx, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[OracleSubscriptionsClientListActivationLinksResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[OracleSubscriptionsClientListActivationLinksResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ListActivationLinks - List Activation Links +// If the operation fails it returns an *azcore.ResponseError type. +func (client *OracleSubscriptionsClient) listActivationLinks(ctx context.Context, options *OracleSubscriptionsClientBeginListActivationLinksOptions) (*http.Response, error) { + var err error + const operationName = "OracleSubscriptionsClient.BeginListActivationLinks" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listActivationLinksCreateRequest(ctx, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// listActivationLinksCreateRequest creates the ListActivationLinks request. +func (client *OracleSubscriptionsClient) listActivationLinksCreateRequest(ctx context.Context, _ *OracleSubscriptionsClientBeginListActivationLinksOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/oracleSubscriptions/default/listActivationLinks" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// NewListBySubscriptionPager - List OracleSubscription resources by subscription ID +// - options - OracleSubscriptionsClientListBySubscriptionOptions contains the optional parameters for the OracleSubscriptionsClient.NewListBySubscriptionPager +// method. +func (client *OracleSubscriptionsClient) NewListBySubscriptionPager(options *OracleSubscriptionsClientListBySubscriptionOptions) *runtime.Pager[OracleSubscriptionsClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[OracleSubscriptionsClientListBySubscriptionResponse]{ + More: func(page OracleSubscriptionsClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *OracleSubscriptionsClientListBySubscriptionResponse) (OracleSubscriptionsClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "OracleSubscriptionsClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return OracleSubscriptionsClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *OracleSubscriptionsClient) listBySubscriptionCreateRequest(ctx context.Context, _ *OracleSubscriptionsClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/oracleSubscriptions" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *OracleSubscriptionsClient) listBySubscriptionHandleResponse(resp *http.Response) (OracleSubscriptionsClientListBySubscriptionResponse, error) { + result := OracleSubscriptionsClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.OracleSubscriptionListResult); err != nil { + return OracleSubscriptionsClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// BeginListCloudAccountDetails - List Cloud Account Details +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OracleSubscriptionsClientBeginListCloudAccountDetailsOptions contains the optional parameters for the OracleSubscriptionsClient.BeginListCloudAccountDetails +// method. +func (client *OracleSubscriptionsClient) BeginListCloudAccountDetails(ctx context.Context, options *OracleSubscriptionsClientBeginListCloudAccountDetailsOptions) (*runtime.Poller[OracleSubscriptionsClientListCloudAccountDetailsResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.listCloudAccountDetails(ctx, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[OracleSubscriptionsClientListCloudAccountDetailsResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[OracleSubscriptionsClientListCloudAccountDetailsResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ListCloudAccountDetails - List Cloud Account Details +// If the operation fails it returns an *azcore.ResponseError type. +func (client *OracleSubscriptionsClient) listCloudAccountDetails(ctx context.Context, options *OracleSubscriptionsClientBeginListCloudAccountDetailsOptions) (*http.Response, error) { + var err error + const operationName = "OracleSubscriptionsClient.BeginListCloudAccountDetails" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listCloudAccountDetailsCreateRequest(ctx, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// listCloudAccountDetailsCreateRequest creates the ListCloudAccountDetails request. +func (client *OracleSubscriptionsClient) listCloudAccountDetailsCreateRequest(ctx context.Context, _ *OracleSubscriptionsClientBeginListCloudAccountDetailsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/oracleSubscriptions/default/listCloudAccountDetails" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginListSaasSubscriptionDetails - List Saas Subscription Details +// If the operation fails it returns an *azcore.ResponseError type. +// - options - OracleSubscriptionsClientBeginListSaasSubscriptionDetailsOptions contains the optional parameters for the OracleSubscriptionsClient.BeginListSaasSubscriptionDetails +// method. +func (client *OracleSubscriptionsClient) BeginListSaasSubscriptionDetails(ctx context.Context, options *OracleSubscriptionsClientBeginListSaasSubscriptionDetailsOptions) (*runtime.Poller[OracleSubscriptionsClientListSaasSubscriptionDetailsResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.listSaasSubscriptionDetails(ctx, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[OracleSubscriptionsClientListSaasSubscriptionDetailsResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[OracleSubscriptionsClientListSaasSubscriptionDetailsResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ListSaasSubscriptionDetails - List Saas Subscription Details +// If the operation fails it returns an *azcore.ResponseError type. +func (client *OracleSubscriptionsClient) listSaasSubscriptionDetails(ctx context.Context, options *OracleSubscriptionsClientBeginListSaasSubscriptionDetailsOptions) (*http.Response, error) { + var err error + const operationName = "OracleSubscriptionsClient.BeginListSaasSubscriptionDetails" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listSaasSubscriptionDetailsCreateRequest(ctx, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// listSaasSubscriptionDetailsCreateRequest creates the ListSaasSubscriptionDetails request. +func (client *OracleSubscriptionsClient) listSaasSubscriptionDetailsCreateRequest(ctx context.Context, _ *OracleSubscriptionsClientBeginListSaasSubscriptionDetailsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/oracleSubscriptions/default/listSaasSubscriptionDetails" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// BeginUpdate - Update a OracleSubscription +// If the operation fails it returns an *azcore.ResponseError type. +// - properties - The resource properties to be updated. +// - options - OracleSubscriptionsClientBeginUpdateOptions contains the optional parameters for the OracleSubscriptionsClient.BeginUpdate +// method. +func (client *OracleSubscriptionsClient) BeginUpdate(ctx context.Context, properties OracleSubscriptionUpdate, options *OracleSubscriptionsClientBeginUpdateOptions) (*runtime.Poller[OracleSubscriptionsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, properties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[OracleSubscriptionsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[OracleSubscriptionsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a OracleSubscription +// If the operation fails it returns an *azcore.ResponseError type. +func (client *OracleSubscriptionsClient) update(ctx context.Context, properties OracleSubscriptionUpdate, options *OracleSubscriptionsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "OracleSubscriptionsClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, properties, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *OracleSubscriptionsClient) updateCreateRequest(ctx context.Context, properties OracleSubscriptionUpdate, _ *OracleSubscriptionsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/oracleSubscriptions/default" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armoracledatabase/zz_polymorphic_helpers.go b/test/local/armoracledatabase/zz_polymorphic_helpers.go new file mode 100644 index 000000000000..36ad8e3d840a --- /dev/null +++ b/test/local/armoracledatabase/zz_polymorphic_helpers.go @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import "encoding/json" + +func unmarshalAutonomousDatabaseBasePropertiesClassification(rawMsg json.RawMessage) (AutonomousDatabaseBasePropertiesClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b AutonomousDatabaseBasePropertiesClassification + switch m["dataBaseType"] { + case string(DataBaseTypeClone): + b = &AutonomousDatabaseCloneProperties{} + case string(DataBaseTypeCloneFromBackupTimestamp): + b = &AutonomousDatabaseFromBackupTimestampProperties{} + case string(DataBaseTypeCrossRegionDisasterRecovery): + b = &AutonomousDatabaseCrossRegionDisasterRecoveryProperties{} + case string(DataBaseTypeRegular): + b = &AutonomousDatabaseProperties{} + default: + b = &AutonomousDatabaseBaseProperties{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} diff --git a/test/local/armoracledatabase/zz_resourceanchors_client.go b/test/local/armoracledatabase/zz_resourceanchors_client.go new file mode 100644 index 000000000000..4bd866d2dd0f --- /dev/null +++ b/test/local/armoracledatabase/zz_resourceanchors_client.go @@ -0,0 +1,440 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ResourceAnchorsClient contains the methods for the ResourceAnchors group. +// Don't use this type directly, use NewResourceAnchorsClient() instead. +// +// Generated from API version 2025-09-01 +type ResourceAnchorsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewResourceAnchorsClient creates a new instance of ResourceAnchorsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewResourceAnchorsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ResourceAnchorsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ResourceAnchorsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create a ResourceAnchor +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - resourceAnchorName - The name of the ResourceAnchor +// - resource - Resource create parameters. +// - options - ResourceAnchorsClientBeginCreateOrUpdateOptions contains the optional parameters for the ResourceAnchorsClient.BeginCreateOrUpdate +// method. +func (client *ResourceAnchorsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, resourceAnchorName string, resource ResourceAnchor, options *ResourceAnchorsClientBeginCreateOrUpdateOptions) (*runtime.Poller[ResourceAnchorsClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, resourceAnchorName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ResourceAnchorsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ResourceAnchorsClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create a ResourceAnchor +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ResourceAnchorsClient) createOrUpdate(ctx context.Context, resourceGroupName string, resourceAnchorName string, resource ResourceAnchor, options *ResourceAnchorsClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ResourceAnchorsClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, resourceAnchorName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *ResourceAnchorsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, resourceAnchorName string, resource ResourceAnchor, _ *ResourceAnchorsClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/resourceAnchors/{resourceAnchorName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if resourceAnchorName == "" { + return nil, errors.New("parameter resourceAnchorName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceAnchorName}", url.PathEscape(resourceAnchorName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a ResourceAnchor +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - resourceAnchorName - The name of the ResourceAnchor +// - options - ResourceAnchorsClientBeginDeleteOptions contains the optional parameters for the ResourceAnchorsClient.BeginDelete +// method. +func (client *ResourceAnchorsClient) BeginDelete(ctx context.Context, resourceGroupName string, resourceAnchorName string, options *ResourceAnchorsClientBeginDeleteOptions) (*runtime.Poller[ResourceAnchorsClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, resourceAnchorName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ResourceAnchorsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ResourceAnchorsClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a ResourceAnchor +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ResourceAnchorsClient) deleteOperation(ctx context.Context, resourceGroupName string, resourceAnchorName string, options *ResourceAnchorsClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "ResourceAnchorsClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, resourceAnchorName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ResourceAnchorsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, resourceAnchorName string, _ *ResourceAnchorsClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/resourceAnchors/{resourceAnchorName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if resourceAnchorName == "" { + return nil, errors.New("parameter resourceAnchorName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceAnchorName}", url.PathEscape(resourceAnchorName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a ResourceAnchor +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - resourceAnchorName - The name of the ResourceAnchor +// - options - ResourceAnchorsClientGetOptions contains the optional parameters for the ResourceAnchorsClient.Get method. +func (client *ResourceAnchorsClient) Get(ctx context.Context, resourceGroupName string, resourceAnchorName string, options *ResourceAnchorsClientGetOptions) (ResourceAnchorsClientGetResponse, error) { + var err error + const operationName = "ResourceAnchorsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, resourceAnchorName, options) + if err != nil { + return ResourceAnchorsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ResourceAnchorsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ResourceAnchorsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *ResourceAnchorsClient) getCreateRequest(ctx context.Context, resourceGroupName string, resourceAnchorName string, _ *ResourceAnchorsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/resourceAnchors/{resourceAnchorName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if resourceAnchorName == "" { + return nil, errors.New("parameter resourceAnchorName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceAnchorName}", url.PathEscape(resourceAnchorName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ResourceAnchorsClient) getHandleResponse(resp *http.Response) (ResourceAnchorsClientGetResponse, error) { + result := ResourceAnchorsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ResourceAnchor); err != nil { + return ResourceAnchorsClientGetResponse{}, err + } + return result, nil +} + +// NewListByResourceGroupPager - List ResourceAnchor resources by resource group +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - ResourceAnchorsClientListByResourceGroupOptions contains the optional parameters for the ResourceAnchorsClient.NewListByResourceGroupPager +// method. +func (client *ResourceAnchorsClient) NewListByResourceGroupPager(resourceGroupName string, options *ResourceAnchorsClientListByResourceGroupOptions) *runtime.Pager[ResourceAnchorsClientListByResourceGroupResponse] { + return runtime.NewPager(runtime.PagingHandler[ResourceAnchorsClientListByResourceGroupResponse]{ + More: func(page ResourceAnchorsClientListByResourceGroupResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ResourceAnchorsClientListByResourceGroupResponse) (ResourceAnchorsClientListByResourceGroupResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ResourceAnchorsClient.NewListByResourceGroupPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, nil) + if err != nil { + return ResourceAnchorsClientListByResourceGroupResponse{}, err + } + return client.listByResourceGroupHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *ResourceAnchorsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, _ *ResourceAnchorsClientListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/resourceAnchors" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *ResourceAnchorsClient) listByResourceGroupHandleResponse(resp *http.Response) (ResourceAnchorsClientListByResourceGroupResponse, error) { + result := ResourceAnchorsClientListByResourceGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ResourceAnchorListResult); err != nil { + return ResourceAnchorsClientListByResourceGroupResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - List ResourceAnchor resources by subscription ID +// - options - ResourceAnchorsClientListBySubscriptionOptions contains the optional parameters for the ResourceAnchorsClient.NewListBySubscriptionPager +// method. +func (client *ResourceAnchorsClient) NewListBySubscriptionPager(options *ResourceAnchorsClientListBySubscriptionOptions) *runtime.Pager[ResourceAnchorsClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[ResourceAnchorsClientListBySubscriptionResponse]{ + More: func(page ResourceAnchorsClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ResourceAnchorsClientListBySubscriptionResponse) (ResourceAnchorsClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "ResourceAnchorsClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return ResourceAnchorsClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *ResourceAnchorsClient) listBySubscriptionCreateRequest(ctx context.Context, _ *ResourceAnchorsClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/resourceAnchors" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *ResourceAnchorsClient) listBySubscriptionHandleResponse(resp *http.Response) (ResourceAnchorsClientListBySubscriptionResponse, error) { + result := ResourceAnchorsClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ResourceAnchorListResult); err != nil { + return ResourceAnchorsClientListBySubscriptionResponse{}, err + } + return result, nil +} + +// BeginUpdate - Update a ResourceAnchor +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - resourceAnchorName - The name of the ResourceAnchor +// - properties - The resource properties to be updated. +// - options - ResourceAnchorsClientBeginUpdateOptions contains the optional parameters for the ResourceAnchorsClient.BeginUpdate +// method. +func (client *ResourceAnchorsClient) BeginUpdate(ctx context.Context, resourceGroupName string, resourceAnchorName string, properties ResourceAnchorUpdate, options *ResourceAnchorsClientBeginUpdateOptions) (*runtime.Poller[ResourceAnchorsClientUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.update(ctx, resourceGroupName, resourceAnchorName, properties, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[ResourceAnchorsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[ResourceAnchorsClientUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Update - Update a ResourceAnchor +// If the operation fails it returns an *azcore.ResponseError type. +func (client *ResourceAnchorsClient) update(ctx context.Context, resourceGroupName string, resourceAnchorName string, properties ResourceAnchorUpdate, options *ResourceAnchorsClientBeginUpdateOptions) (*http.Response, error) { + var err error + const operationName = "ResourceAnchorsClient.BeginUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateCreateRequest(ctx, resourceGroupName, resourceAnchorName, properties, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// updateCreateRequest creates the Update request. +func (client *ResourceAnchorsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, resourceAnchorName string, properties ResourceAnchorUpdate, _ *ResourceAnchorsClientBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/resourceAnchors/{resourceAnchorName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if resourceAnchorName == "" { + return nil, errors.New("parameter resourceAnchorName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceAnchorName}", url.PathEscape(resourceAnchorName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, properties); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armoracledatabase/zz_responses.go b/test/local/armoracledatabase/zz_responses.go new file mode 100644 index 000000000000..d91c8126b455 --- /dev/null +++ b/test/local/armoracledatabase/zz_responses.go @@ -0,0 +1,652 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +// AutonomousDatabaseBackupsClientCreateOrUpdateResponse contains the response from method AutonomousDatabaseBackupsClient.BeginCreateOrUpdate. +type AutonomousDatabaseBackupsClientCreateOrUpdateResponse struct { + // AutonomousDatabaseBackup resource definition + AutonomousDatabaseBackup +} + +// AutonomousDatabaseBackupsClientDeleteResponse contains the response from method AutonomousDatabaseBackupsClient.BeginDelete. +type AutonomousDatabaseBackupsClientDeleteResponse struct { + // placeholder for future response values +} + +// AutonomousDatabaseBackupsClientGetResponse contains the response from method AutonomousDatabaseBackupsClient.Get. +type AutonomousDatabaseBackupsClientGetResponse struct { + // AutonomousDatabaseBackup resource definition + AutonomousDatabaseBackup +} + +// AutonomousDatabaseBackupsClientListByAutonomousDatabaseResponse contains the response from method AutonomousDatabaseBackupsClient.NewListByAutonomousDatabasePager. +type AutonomousDatabaseBackupsClientListByAutonomousDatabaseResponse struct { + // The response of a AutonomousDatabaseBackup list operation. + AutonomousDatabaseBackupListResult +} + +// AutonomousDatabaseBackupsClientUpdateResponse contains the response from method AutonomousDatabaseBackupsClient.BeginUpdate. +type AutonomousDatabaseBackupsClientUpdateResponse struct { + // AutonomousDatabaseBackup resource definition + AutonomousDatabaseBackup +} + +// AutonomousDatabaseCharacterSetsClientGetResponse contains the response from method AutonomousDatabaseCharacterSetsClient.Get. +type AutonomousDatabaseCharacterSetsClientGetResponse struct { + // AutonomousDatabaseCharacterSets resource definition + AutonomousDatabaseCharacterSet +} + +// AutonomousDatabaseCharacterSetsClientListByLocationResponse contains the response from method AutonomousDatabaseCharacterSetsClient.NewListByLocationPager. +type AutonomousDatabaseCharacterSetsClientListByLocationResponse struct { + // The response of a AutonomousDatabaseCharacterSet list operation. + AutonomousDatabaseCharacterSetListResult +} + +// AutonomousDatabaseNationalCharacterSetsClientGetResponse contains the response from method AutonomousDatabaseNationalCharacterSetsClient.Get. +type AutonomousDatabaseNationalCharacterSetsClientGetResponse struct { + // AutonomousDatabaseNationalCharacterSets resource definition + AutonomousDatabaseNationalCharacterSet +} + +// AutonomousDatabaseNationalCharacterSetsClientListByLocationResponse contains the response from method AutonomousDatabaseNationalCharacterSetsClient.NewListByLocationPager. +type AutonomousDatabaseNationalCharacterSetsClientListByLocationResponse struct { + // The response of a AutonomousDatabaseNationalCharacterSet list operation. + AutonomousDatabaseNationalCharacterSetListResult +} + +// AutonomousDatabaseVersionsClientGetResponse contains the response from method AutonomousDatabaseVersionsClient.Get. +type AutonomousDatabaseVersionsClientGetResponse struct { + // AutonomousDbVersion resource definition + AutonomousDbVersion +} + +// AutonomousDatabaseVersionsClientListByLocationResponse contains the response from method AutonomousDatabaseVersionsClient.NewListByLocationPager. +type AutonomousDatabaseVersionsClientListByLocationResponse struct { + // The response of a AutonomousDbVersion list operation. + AutonomousDbVersionListResult +} + +// AutonomousDatabasesClientActionResponse contains the response from method AutonomousDatabasesClient.BeginAction. +type AutonomousDatabasesClientActionResponse struct { + // Autonomous Database resource model. + AutonomousDatabase +} + +// AutonomousDatabasesClientChangeDisasterRecoveryConfigurationResponse contains the response from method AutonomousDatabasesClient.BeginChangeDisasterRecoveryConfiguration. +type AutonomousDatabasesClientChangeDisasterRecoveryConfigurationResponse struct { + // Autonomous Database resource model. + AutonomousDatabase +} + +// AutonomousDatabasesClientCreateOrUpdateResponse contains the response from method AutonomousDatabasesClient.BeginCreateOrUpdate. +type AutonomousDatabasesClientCreateOrUpdateResponse struct { + // Autonomous Database resource model. + AutonomousDatabase +} + +// AutonomousDatabasesClientDeleteResponse contains the response from method AutonomousDatabasesClient.BeginDelete. +type AutonomousDatabasesClientDeleteResponse struct { + // placeholder for future response values +} + +// AutonomousDatabasesClientFailoverResponse contains the response from method AutonomousDatabasesClient.BeginFailover. +type AutonomousDatabasesClientFailoverResponse struct { + // Autonomous Database resource model. + AutonomousDatabase +} + +// AutonomousDatabasesClientGenerateWalletResponse contains the response from method AutonomousDatabasesClient.GenerateWallet. +type AutonomousDatabasesClientGenerateWalletResponse struct { + // Autonomous Database Wallet File resource model. + AutonomousDatabaseWalletFile +} + +// AutonomousDatabasesClientGetResponse contains the response from method AutonomousDatabasesClient.Get. +type AutonomousDatabasesClientGetResponse struct { + // Autonomous Database resource model. + AutonomousDatabase +} + +// AutonomousDatabasesClientListByResourceGroupResponse contains the response from method AutonomousDatabasesClient.NewListByResourceGroupPager. +type AutonomousDatabasesClientListByResourceGroupResponse struct { + // The response of a AutonomousDatabase list operation. + AutonomousDatabaseListResult +} + +// AutonomousDatabasesClientListBySubscriptionResponse contains the response from method AutonomousDatabasesClient.NewListBySubscriptionPager. +type AutonomousDatabasesClientListBySubscriptionResponse struct { + // The response of a AutonomousDatabase list operation. + AutonomousDatabaseListResult +} + +// AutonomousDatabasesClientRestoreResponse contains the response from method AutonomousDatabasesClient.BeginRestore. +type AutonomousDatabasesClientRestoreResponse struct { + // Autonomous Database resource model. + AutonomousDatabase +} + +// AutonomousDatabasesClientShrinkResponse contains the response from method AutonomousDatabasesClient.BeginShrink. +type AutonomousDatabasesClientShrinkResponse struct { + // Autonomous Database resource model. + AutonomousDatabase +} + +// AutonomousDatabasesClientSwitchoverResponse contains the response from method AutonomousDatabasesClient.BeginSwitchover. +type AutonomousDatabasesClientSwitchoverResponse struct { + // Autonomous Database resource model. + AutonomousDatabase +} + +// AutonomousDatabasesClientUpdateResponse contains the response from method AutonomousDatabasesClient.BeginUpdate. +type AutonomousDatabasesClientUpdateResponse struct { + // Autonomous Database resource model. + AutonomousDatabase +} + +// CloudExadataInfrastructuresClientAddStorageCapacityResponse contains the response from method CloudExadataInfrastructuresClient.BeginAddStorageCapacity. +type CloudExadataInfrastructuresClientAddStorageCapacityResponse struct { + // CloudExadataInfrastructure resource definition + CloudExadataInfrastructure +} + +// CloudExadataInfrastructuresClientConfigureExascaleResponse contains the response from method CloudExadataInfrastructuresClient.BeginConfigureExascale. +type CloudExadataInfrastructuresClientConfigureExascaleResponse struct { + // CloudExadataInfrastructure resource definition + CloudExadataInfrastructure +} + +// CloudExadataInfrastructuresClientCreateOrUpdateResponse contains the response from method CloudExadataInfrastructuresClient.BeginCreateOrUpdate. +type CloudExadataInfrastructuresClientCreateOrUpdateResponse struct { + // CloudExadataInfrastructure resource definition + CloudExadataInfrastructure +} + +// CloudExadataInfrastructuresClientDeleteResponse contains the response from method CloudExadataInfrastructuresClient.BeginDelete. +type CloudExadataInfrastructuresClientDeleteResponse struct { + // placeholder for future response values +} + +// CloudExadataInfrastructuresClientGetResponse contains the response from method CloudExadataInfrastructuresClient.Get. +type CloudExadataInfrastructuresClientGetResponse struct { + // CloudExadataInfrastructure resource definition + CloudExadataInfrastructure +} + +// CloudExadataInfrastructuresClientListByResourceGroupResponse contains the response from method CloudExadataInfrastructuresClient.NewListByResourceGroupPager. +type CloudExadataInfrastructuresClientListByResourceGroupResponse struct { + // The response of a CloudExadataInfrastructure list operation. + CloudExadataInfrastructureListResult +} + +// CloudExadataInfrastructuresClientListBySubscriptionResponse contains the response from method CloudExadataInfrastructuresClient.NewListBySubscriptionPager. +type CloudExadataInfrastructuresClientListBySubscriptionResponse struct { + // The response of a CloudExadataInfrastructure list operation. + CloudExadataInfrastructureListResult +} + +// CloudExadataInfrastructuresClientUpdateResponse contains the response from method CloudExadataInfrastructuresClient.BeginUpdate. +type CloudExadataInfrastructuresClientUpdateResponse struct { + // CloudExadataInfrastructure resource definition + CloudExadataInfrastructure +} + +// CloudVMClustersClientAddVMsResponse contains the response from method CloudVMClustersClient.BeginAddVMs. +type CloudVMClustersClientAddVMsResponse struct { + // CloudVmCluster resource definition + CloudVMCluster +} + +// CloudVMClustersClientCreateOrUpdateResponse contains the response from method CloudVMClustersClient.BeginCreateOrUpdate. +type CloudVMClustersClientCreateOrUpdateResponse struct { + // CloudVmCluster resource definition + CloudVMCluster +} + +// CloudVMClustersClientDeleteResponse contains the response from method CloudVMClustersClient.BeginDelete. +type CloudVMClustersClientDeleteResponse struct { + // placeholder for future response values +} + +// CloudVMClustersClientGetResponse contains the response from method CloudVMClustersClient.Get. +type CloudVMClustersClientGetResponse struct { + // CloudVmCluster resource definition + CloudVMCluster +} + +// CloudVMClustersClientListByResourceGroupResponse contains the response from method CloudVMClustersClient.NewListByResourceGroupPager. +type CloudVMClustersClientListByResourceGroupResponse struct { + // The response of a CloudVmCluster list operation. + CloudVMClusterListResult +} + +// CloudVMClustersClientListBySubscriptionResponse contains the response from method CloudVMClustersClient.NewListBySubscriptionPager. +type CloudVMClustersClientListBySubscriptionResponse struct { + // The response of a CloudVmCluster list operation. + CloudVMClusterListResult +} + +// CloudVMClustersClientListPrivateIPAddressesResponse contains the response from method CloudVMClustersClient.ListPrivateIPAddresses. +type CloudVMClustersClientListPrivateIPAddressesResponse struct { + PrivateIPAddressPropertiesArray []*PrivateIPAddressProperties +} + +// CloudVMClustersClientRemoveVMsResponse contains the response from method CloudVMClustersClient.BeginRemoveVMs. +type CloudVMClustersClientRemoveVMsResponse struct { + // CloudVmCluster resource definition + CloudVMCluster +} + +// CloudVMClustersClientUpdateResponse contains the response from method CloudVMClustersClient.BeginUpdate. +type CloudVMClustersClientUpdateResponse struct { + // CloudVmCluster resource definition + CloudVMCluster +} + +// DNSPrivateViewsClientGetResponse contains the response from method DNSPrivateViewsClient.Get. +type DNSPrivateViewsClientGetResponse struct { + // DnsPrivateView resource definition + DNSPrivateView +} + +// DNSPrivateViewsClientListByLocationResponse contains the response from method DNSPrivateViewsClient.NewListByLocationPager. +type DNSPrivateViewsClientListByLocationResponse struct { + // The response of a DnsPrivateView list operation. + DNSPrivateViewListResult +} + +// DNSPrivateZonesClientGetResponse contains the response from method DNSPrivateZonesClient.Get. +type DNSPrivateZonesClientGetResponse struct { + // DnsPrivateZone resource definition + DNSPrivateZone +} + +// DNSPrivateZonesClientListByLocationResponse contains the response from method DNSPrivateZonesClient.NewListByLocationPager. +type DNSPrivateZonesClientListByLocationResponse struct { + // The response of a DnsPrivateZone list operation. + DNSPrivateZoneListResult +} + +// DbNodesClientActionResponse contains the response from method DbNodesClient.BeginAction. +type DbNodesClientActionResponse struct { + // The DbNode resource belonging to vmCluster + DbNode +} + +// DbNodesClientGetResponse contains the response from method DbNodesClient.Get. +type DbNodesClientGetResponse struct { + // The DbNode resource belonging to vmCluster + DbNode +} + +// DbNodesClientListByCloudVMClusterResponse contains the response from method DbNodesClient.NewListByCloudVMClusterPager. +type DbNodesClientListByCloudVMClusterResponse struct { + // The response of a DbNode list operation. + DbNodeListResult +} + +// DbServersClientGetResponse contains the response from method DbServersClient.Get. +type DbServersClientGetResponse struct { + // DbServer resource model + DbServer +} + +// DbServersClientListByCloudExadataInfrastructureResponse contains the response from method DbServersClient.NewListByCloudExadataInfrastructurePager. +type DbServersClientListByCloudExadataInfrastructureResponse struct { + // The response of a DbServer list operation. + DbServerListResult +} + +// DbSystemShapesClientGetResponse contains the response from method DbSystemShapesClient.Get. +type DbSystemShapesClientGetResponse struct { + // DbSystemShape resource definition + DbSystemShape +} + +// DbSystemShapesClientListByLocationResponse contains the response from method DbSystemShapesClient.NewListByLocationPager. +type DbSystemShapesClientListByLocationResponse struct { + // The response of a DbSystemShape list operation. + DbSystemShapeListResult +} + +// DbSystemsClientCreateOrUpdateResponse contains the response from method DbSystemsClient.BeginCreateOrUpdate. +type DbSystemsClientCreateOrUpdateResponse struct { + // DbSystem resource definition + DbSystem +} + +// DbSystemsClientDeleteResponse contains the response from method DbSystemsClient.BeginDelete. +type DbSystemsClientDeleteResponse struct { + // placeholder for future response values +} + +// DbSystemsClientGetResponse contains the response from method DbSystemsClient.Get. +type DbSystemsClientGetResponse struct { + // DbSystem resource definition + DbSystem +} + +// DbSystemsClientListByResourceGroupResponse contains the response from method DbSystemsClient.NewListByResourceGroupPager. +type DbSystemsClientListByResourceGroupResponse struct { + // The response of a DbSystem list operation. + DbSystemListResult +} + +// DbSystemsClientListBySubscriptionResponse contains the response from method DbSystemsClient.NewListBySubscriptionPager. +type DbSystemsClientListBySubscriptionResponse struct { + // The response of a DbSystem list operation. + DbSystemListResult +} + +// DbSystemsClientUpdateResponse contains the response from method DbSystemsClient.BeginUpdate. +type DbSystemsClientUpdateResponse struct { + // DbSystem resource definition + DbSystem +} + +// DbVersionsClientGetResponse contains the response from method DbVersionsClient.Get. +type DbVersionsClientGetResponse struct { + // Oracle Database DbVersion resource definition + DbVersion +} + +// DbVersionsClientListByLocationResponse contains the response from method DbVersionsClient.NewListByLocationPager. +type DbVersionsClientListByLocationResponse struct { + // The response of a DbVersion list operation. + DbVersionListResult +} + +// ExadbVMClustersClientCreateOrUpdateResponse contains the response from method ExadbVMClustersClient.BeginCreateOrUpdate. +type ExadbVMClustersClientCreateOrUpdateResponse struct { + // ExadbVmCluster resource definition + ExadbVMCluster +} + +// ExadbVMClustersClientDeleteResponse contains the response from method ExadbVMClustersClient.BeginDelete. +type ExadbVMClustersClientDeleteResponse struct { + // placeholder for future response values +} + +// ExadbVMClustersClientGetResponse contains the response from method ExadbVMClustersClient.Get. +type ExadbVMClustersClientGetResponse struct { + // ExadbVmCluster resource definition + ExadbVMCluster +} + +// ExadbVMClustersClientListByResourceGroupResponse contains the response from method ExadbVMClustersClient.NewListByResourceGroupPager. +type ExadbVMClustersClientListByResourceGroupResponse struct { + // The response of a ExadbVmCluster list operation. + ExadbVMClusterListResult +} + +// ExadbVMClustersClientListBySubscriptionResponse contains the response from method ExadbVMClustersClient.NewListBySubscriptionPager. +type ExadbVMClustersClientListBySubscriptionResponse struct { + // The response of a ExadbVmCluster list operation. + ExadbVMClusterListResult +} + +// ExadbVMClustersClientRemoveVMsResponse contains the response from method ExadbVMClustersClient.BeginRemoveVMs. +type ExadbVMClustersClientRemoveVMsResponse struct { + // ExadbVmCluster resource definition + ExadbVMCluster +} + +// ExadbVMClustersClientUpdateResponse contains the response from method ExadbVMClustersClient.BeginUpdate. +type ExadbVMClustersClientUpdateResponse struct { + // ExadbVmCluster resource definition + ExadbVMCluster +} + +// ExascaleDbNodesClientActionResponse contains the response from method ExascaleDbNodesClient.BeginAction. +type ExascaleDbNodesClientActionResponse struct { + // ExascaleDbNode action response + DbActionResponse +} + +// ExascaleDbNodesClientGetResponse contains the response from method ExascaleDbNodesClient.Get. +type ExascaleDbNodesClientGetResponse struct { + // The DbNode resource belonging to ExadbVmCluster + ExascaleDbNode +} + +// ExascaleDbNodesClientListByParentResponse contains the response from method ExascaleDbNodesClient.NewListByParentPager. +type ExascaleDbNodesClientListByParentResponse struct { + // The response of a ExascaleDbNode list operation. + ExascaleDbNodeListResult +} + +// ExascaleDbStorageVaultsClientCreateResponse contains the response from method ExascaleDbStorageVaultsClient.BeginCreate. +type ExascaleDbStorageVaultsClientCreateResponse struct { + // ExascaleDbStorageVault resource definition + ExascaleDbStorageVault +} + +// ExascaleDbStorageVaultsClientDeleteResponse contains the response from method ExascaleDbStorageVaultsClient.BeginDelete. +type ExascaleDbStorageVaultsClientDeleteResponse struct { + // placeholder for future response values +} + +// ExascaleDbStorageVaultsClientGetResponse contains the response from method ExascaleDbStorageVaultsClient.Get. +type ExascaleDbStorageVaultsClientGetResponse struct { + // ExascaleDbStorageVault resource definition + ExascaleDbStorageVault +} + +// ExascaleDbStorageVaultsClientListByResourceGroupResponse contains the response from method ExascaleDbStorageVaultsClient.NewListByResourceGroupPager. +type ExascaleDbStorageVaultsClientListByResourceGroupResponse struct { + // The response of a ExascaleDbStorageVault list operation. + ExascaleDbStorageVaultListResult +} + +// ExascaleDbStorageVaultsClientListBySubscriptionResponse contains the response from method ExascaleDbStorageVaultsClient.NewListBySubscriptionPager. +type ExascaleDbStorageVaultsClientListBySubscriptionResponse struct { + // The response of a ExascaleDbStorageVault list operation. + ExascaleDbStorageVaultListResult +} + +// ExascaleDbStorageVaultsClientUpdateResponse contains the response from method ExascaleDbStorageVaultsClient.BeginUpdate. +type ExascaleDbStorageVaultsClientUpdateResponse struct { + // ExascaleDbStorageVault resource definition + ExascaleDbStorageVault +} + +// FlexComponentsClientGetResponse contains the response from method FlexComponentsClient.Get. +type FlexComponentsClientGetResponse struct { + // FlexComponent Resource Definition + FlexComponent +} + +// FlexComponentsClientListByParentResponse contains the response from method FlexComponentsClient.NewListByParentPager. +type FlexComponentsClientListByParentResponse struct { + // The response of a FlexComponent list operation. + FlexComponentListResult +} + +// GiMinorVersionsClientGetResponse contains the response from method GiMinorVersionsClient.Get. +type GiMinorVersionsClientGetResponse struct { + // The Oracle Grid Infrastructure (GI) minor version resource definition. + GiMinorVersion +} + +// GiMinorVersionsClientListByParentResponse contains the response from method GiMinorVersionsClient.NewListByParentPager. +type GiMinorVersionsClientListByParentResponse struct { + // The response of a GiMinorVersion list operation. + GiMinorVersionListResult +} + +// GiVersionsClientGetResponse contains the response from method GiVersionsClient.Get. +type GiVersionsClientGetResponse struct { + // GiVersion resource definition + GiVersion +} + +// GiVersionsClientListByLocationResponse contains the response from method GiVersionsClient.NewListByLocationPager. +type GiVersionsClientListByLocationResponse struct { + // The response of a GiVersion list operation. + GiVersionListResult +} + +// NetworkAnchorsClientCreateOrUpdateResponse contains the response from method NetworkAnchorsClient.BeginCreateOrUpdate. +type NetworkAnchorsClientCreateOrUpdateResponse struct { + // Network Anchor resource model. + NetworkAnchor +} + +// NetworkAnchorsClientDeleteResponse contains the response from method NetworkAnchorsClient.BeginDelete. +type NetworkAnchorsClientDeleteResponse struct { + // placeholder for future response values +} + +// NetworkAnchorsClientGetResponse contains the response from method NetworkAnchorsClient.Get. +type NetworkAnchorsClientGetResponse struct { + // Network Anchor resource model. + NetworkAnchor +} + +// NetworkAnchorsClientListByResourceGroupResponse contains the response from method NetworkAnchorsClient.NewListByResourceGroupPager. +type NetworkAnchorsClientListByResourceGroupResponse struct { + // The response of a NetworkAnchor list operation. + NetworkAnchorListResult +} + +// NetworkAnchorsClientListBySubscriptionResponse contains the response from method NetworkAnchorsClient.NewListBySubscriptionPager. +type NetworkAnchorsClientListBySubscriptionResponse struct { + // The response of a NetworkAnchor list operation. + NetworkAnchorListResult +} + +// NetworkAnchorsClientUpdateResponse contains the response from method NetworkAnchorsClient.BeginUpdate. +type NetworkAnchorsClientUpdateResponse struct { + // Network Anchor resource model. + NetworkAnchor +} + +// OperationsClientListResponse contains the response from method OperationsClient.NewListPager. +type OperationsClientListResponse struct { + // A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. + OperationListResult +} + +// OracleSubscriptionsClientAddAzureSubscriptionsResponse contains the response from method OracleSubscriptionsClient.BeginAddAzureSubscriptions. +type OracleSubscriptionsClientAddAzureSubscriptionsResponse struct { + // placeholder for future response values +} + +// OracleSubscriptionsClientCreateOrUpdateResponse contains the response from method OracleSubscriptionsClient.BeginCreateOrUpdate. +type OracleSubscriptionsClientCreateOrUpdateResponse struct { + // OracleSubscription resource definition + OracleSubscription +} + +// OracleSubscriptionsClientDeleteResponse contains the response from method OracleSubscriptionsClient.BeginDelete. +type OracleSubscriptionsClientDeleteResponse struct { + // placeholder for future response values +} + +// OracleSubscriptionsClientGetResponse contains the response from method OracleSubscriptionsClient.Get. +type OracleSubscriptionsClientGetResponse struct { + // OracleSubscription resource definition + OracleSubscription +} + +// OracleSubscriptionsClientListActivationLinksResponse contains the response from method OracleSubscriptionsClient.BeginListActivationLinks. +type OracleSubscriptionsClientListActivationLinksResponse struct { + // Activation Links model + ActivationLinks +} + +// OracleSubscriptionsClientListBySubscriptionResponse contains the response from method OracleSubscriptionsClient.NewListBySubscriptionPager. +type OracleSubscriptionsClientListBySubscriptionResponse struct { + // The response of a OracleSubscription list operation. + OracleSubscriptionListResult +} + +// OracleSubscriptionsClientListCloudAccountDetailsResponse contains the response from method OracleSubscriptionsClient.BeginListCloudAccountDetails. +type OracleSubscriptionsClientListCloudAccountDetailsResponse struct { + // Cloud Account Details model + CloudAccountDetails +} + +// OracleSubscriptionsClientListSaasSubscriptionDetailsResponse contains the response from method OracleSubscriptionsClient.BeginListSaasSubscriptionDetails. +type OracleSubscriptionsClientListSaasSubscriptionDetailsResponse struct { + // SaaS Subscription Details model + SaasSubscriptionDetails +} + +// OracleSubscriptionsClientUpdateResponse contains the response from method OracleSubscriptionsClient.BeginUpdate. +type OracleSubscriptionsClientUpdateResponse struct { + // OracleSubscription resource definition + OracleSubscription +} + +// ResourceAnchorsClientCreateOrUpdateResponse contains the response from method ResourceAnchorsClient.BeginCreateOrUpdate. +type ResourceAnchorsClientCreateOrUpdateResponse struct { + // Resource Anchor model. + ResourceAnchor +} + +// ResourceAnchorsClientDeleteResponse contains the response from method ResourceAnchorsClient.BeginDelete. +type ResourceAnchorsClientDeleteResponse struct { + // placeholder for future response values +} + +// ResourceAnchorsClientGetResponse contains the response from method ResourceAnchorsClient.Get. +type ResourceAnchorsClientGetResponse struct { + // Resource Anchor model. + ResourceAnchor +} + +// ResourceAnchorsClientListByResourceGroupResponse contains the response from method ResourceAnchorsClient.NewListByResourceGroupPager. +type ResourceAnchorsClientListByResourceGroupResponse struct { + // The response of a ResourceAnchor list operation. + ResourceAnchorListResult +} + +// ResourceAnchorsClientListBySubscriptionResponse contains the response from method ResourceAnchorsClient.NewListBySubscriptionPager. +type ResourceAnchorsClientListBySubscriptionResponse struct { + // The response of a ResourceAnchor list operation. + ResourceAnchorListResult +} + +// ResourceAnchorsClientUpdateResponse contains the response from method ResourceAnchorsClient.BeginUpdate. +type ResourceAnchorsClientUpdateResponse struct { + // Resource Anchor model. + ResourceAnchor +} + +// SystemVersionsClientGetResponse contains the response from method SystemVersionsClient.Get. +type SystemVersionsClientGetResponse struct { + // SystemVersion resource Definition + SystemVersion +} + +// SystemVersionsClientListByLocationResponse contains the response from method SystemVersionsClient.NewListByLocationPager. +type SystemVersionsClientListByLocationResponse struct { + // The response of a SystemVersion list operation. + SystemVersionListResult +} + +// VirtualNetworkAddressesClientCreateOrUpdateResponse contains the response from method VirtualNetworkAddressesClient.BeginCreateOrUpdate. +type VirtualNetworkAddressesClientCreateOrUpdateResponse struct { + // Virtual IP resource belonging to a vm cluster resource. + VirtualNetworkAddress +} + +// VirtualNetworkAddressesClientDeleteResponse contains the response from method VirtualNetworkAddressesClient.BeginDelete. +type VirtualNetworkAddressesClientDeleteResponse struct { + // placeholder for future response values +} + +// VirtualNetworkAddressesClientGetResponse contains the response from method VirtualNetworkAddressesClient.Get. +type VirtualNetworkAddressesClientGetResponse struct { + // Virtual IP resource belonging to a vm cluster resource. + VirtualNetworkAddress +} + +// VirtualNetworkAddressesClientListByCloudVMClusterResponse contains the response from method VirtualNetworkAddressesClient.NewListByCloudVMClusterPager. +type VirtualNetworkAddressesClientListByCloudVMClusterResponse struct { + // The response of a VirtualNetworkAddress list operation. + VirtualNetworkAddressListResult +} diff --git a/test/local/armoracledatabase/zz_systemversions_client.go b/test/local/armoracledatabase/zz_systemversions_client.go new file mode 100644 index 000000000000..ef32b932b531 --- /dev/null +++ b/test/local/armoracledatabase/zz_systemversions_client.go @@ -0,0 +1,162 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// SystemVersionsClient contains the methods for the SystemVersions group. +// Don't use this type directly, use NewSystemVersionsClient() instead. +// +// Generated from API version 2025-09-01 +type SystemVersionsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewSystemVersionsClient creates a new instance of SystemVersionsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewSystemVersionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*SystemVersionsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SystemVersionsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get a SystemVersion +// If the operation fails it returns an *azcore.ResponseError type. +// - location - The name of the Azure region. +// - systemversionname - SystemVersion name +// - options - SystemVersionsClientGetOptions contains the optional parameters for the SystemVersionsClient.Get method. +func (client *SystemVersionsClient) Get(ctx context.Context, location string, systemversionname string, options *SystemVersionsClientGetOptions) (SystemVersionsClientGetResponse, error) { + var err error + const operationName = "SystemVersionsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, location, systemversionname, options) + if err != nil { + return SystemVersionsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SystemVersionsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SystemVersionsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *SystemVersionsClient) getCreateRequest(ctx context.Context, location string, systemversionname string, _ *SystemVersionsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/locations/{location}/systemVersions/{systemversionname}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if systemversionname == "" { + return nil, errors.New("parameter systemversionname cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{systemversionname}", url.PathEscape(systemversionname)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *SystemVersionsClient) getHandleResponse(resp *http.Response) (SystemVersionsClientGetResponse, error) { + result := SystemVersionsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SystemVersion); err != nil { + return SystemVersionsClientGetResponse{}, err + } + return result, nil +} + +// NewListByLocationPager - List SystemVersion resources by SubscriptionLocationResource +// - location - The name of the Azure region. +// - options - SystemVersionsClientListByLocationOptions contains the optional parameters for the SystemVersionsClient.NewListByLocationPager +// method. +func (client *SystemVersionsClient) NewListByLocationPager(location string, options *SystemVersionsClientListByLocationOptions) *runtime.Pager[SystemVersionsClientListByLocationResponse] { + return runtime.NewPager(runtime.PagingHandler[SystemVersionsClientListByLocationResponse]{ + More: func(page SystemVersionsClientListByLocationResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SystemVersionsClientListByLocationResponse) (SystemVersionsClientListByLocationResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SystemVersionsClient.NewListByLocationPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByLocationCreateRequest(ctx, location, options) + }, nil) + if err != nil { + return SystemVersionsClientListByLocationResponse{}, err + } + return client.listByLocationHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByLocationCreateRequest creates the ListByLocation request. +func (client *SystemVersionsClient) listByLocationCreateRequest(ctx context.Context, location string, _ *SystemVersionsClientListByLocationOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Oracle.Database/locations/{location}/systemVersions" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByLocationHandleResponse handles the ListByLocation response. +func (client *SystemVersionsClient) listByLocationHandleResponse(resp *http.Response) (SystemVersionsClientListByLocationResponse, error) { + result := SystemVersionsClientListByLocationResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SystemVersionListResult); err != nil { + return SystemVersionsClientListByLocationResponse{}, err + } + return result, nil +} diff --git a/test/local/armoracledatabase/zz_version.go b/test/local/armoracledatabase/zz_version.go new file mode 100644 index 000000000000..3079c29fd322 --- /dev/null +++ b/test/local/armoracledatabase/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package armoracledatabase + +const ( + moduleName = "armoracledatabase" + moduleVersion = "v0.1.0" +) diff --git a/test/local/armoracledatabase/zz_virtualnetworkaddresses_client.go b/test/local/armoracledatabase/zz_virtualnetworkaddresses_client.go new file mode 100644 index 000000000000..a3bdf424eec8 --- /dev/null +++ b/test/local/armoracledatabase/zz_virtualnetworkaddresses_client.go @@ -0,0 +1,331 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armoracledatabase + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// VirtualNetworkAddressesClient contains the methods for the VirtualNetworkAddresses group. +// Don't use this type directly, use NewVirtualNetworkAddressesClient() instead. +// +// Generated from API version 2025-09-01 +type VirtualNetworkAddressesClient struct { + internal *arm.Client + subscriptionID string +} + +// NewVirtualNetworkAddressesClient creates a new instance of VirtualNetworkAddressesClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewVirtualNetworkAddressesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*VirtualNetworkAddressesClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &VirtualNetworkAddressesClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginCreateOrUpdate - Create a VirtualNetworkAddress +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudvmclustername - CloudVmCluster name +// - virtualnetworkaddressname - Virtual IP address hostname. +// - resource - Resource create parameters. +// - options - VirtualNetworkAddressesClientBeginCreateOrUpdateOptions contains the optional parameters for the VirtualNetworkAddressesClient.BeginCreateOrUpdate +// method. +func (client *VirtualNetworkAddressesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, cloudvmclustername string, virtualnetworkaddressname string, resource VirtualNetworkAddress, options *VirtualNetworkAddressesClientBeginCreateOrUpdateOptions) (*runtime.Poller[VirtualNetworkAddressesClientCreateOrUpdateResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.createOrUpdate(ctx, resourceGroupName, cloudvmclustername, virtualnetworkaddressname, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkAddressesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkAddressesClientCreateOrUpdateResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// CreateOrUpdate - Create a VirtualNetworkAddress +// If the operation fails it returns an *azcore.ResponseError type. +func (client *VirtualNetworkAddressesClient) createOrUpdate(ctx context.Context, resourceGroupName string, cloudvmclustername string, virtualnetworkaddressname string, resource VirtualNetworkAddress, options *VirtualNetworkAddressesClientBeginCreateOrUpdateOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkAddressesClient.BeginCreateOrUpdate" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, cloudvmclustername, virtualnetworkaddressname, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *VirtualNetworkAddressesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, cloudvmclustername string, virtualnetworkaddressname string, resource VirtualNetworkAddress, _ *VirtualNetworkAddressesClientBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/cloudVmClusters/{cloudvmclustername}/virtualNetworkAddresses/{virtualnetworkaddressname}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudvmclustername == "" { + return nil, errors.New("parameter cloudvmclustername cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudvmclustername}", url.PathEscape(cloudvmclustername)) + if virtualnetworkaddressname == "" { + return nil, errors.New("parameter virtualnetworkaddressname cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualnetworkaddressname}", url.PathEscape(virtualnetworkaddressname)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginDelete - Delete a VirtualNetworkAddress +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudvmclustername - CloudVmCluster name +// - virtualnetworkaddressname - Virtual IP address hostname. +// - options - VirtualNetworkAddressesClientBeginDeleteOptions contains the optional parameters for the VirtualNetworkAddressesClient.BeginDelete +// method. +func (client *VirtualNetworkAddressesClient) BeginDelete(ctx context.Context, resourceGroupName string, cloudvmclustername string, virtualnetworkaddressname string, options *VirtualNetworkAddressesClientBeginDeleteOptions) (*runtime.Poller[VirtualNetworkAddressesClientDeleteResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.deleteOperation(ctx, resourceGroupName, cloudvmclustername, virtualnetworkaddressname, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[VirtualNetworkAddressesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[VirtualNetworkAddressesClientDeleteResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// Delete - Delete a VirtualNetworkAddress +// If the operation fails it returns an *azcore.ResponseError type. +func (client *VirtualNetworkAddressesClient) deleteOperation(ctx context.Context, resourceGroupName string, cloudvmclustername string, virtualnetworkaddressname string, options *VirtualNetworkAddressesClientBeginDeleteOptions) (*http.Response, error) { + var err error + const operationName = "VirtualNetworkAddressesClient.BeginDelete" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteCreateRequest(ctx, resourceGroupName, cloudvmclustername, virtualnetworkaddressname, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *VirtualNetworkAddressesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, cloudvmclustername string, virtualnetworkaddressname string, _ *VirtualNetworkAddressesClientBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/cloudVmClusters/{cloudvmclustername}/virtualNetworkAddresses/{virtualnetworkaddressname}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudvmclustername == "" { + return nil, errors.New("parameter cloudvmclustername cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudvmclustername}", url.PathEscape(cloudvmclustername)) + if virtualnetworkaddressname == "" { + return nil, errors.New("parameter virtualnetworkaddressname cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualnetworkaddressname}", url.PathEscape(virtualnetworkaddressname)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// Get - Get a VirtualNetworkAddress +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudvmclustername - CloudVmCluster name +// - virtualnetworkaddressname - Virtual IP address hostname. +// - options - VirtualNetworkAddressesClientGetOptions contains the optional parameters for the VirtualNetworkAddressesClient.Get +// method. +func (client *VirtualNetworkAddressesClient) Get(ctx context.Context, resourceGroupName string, cloudvmclustername string, virtualnetworkaddressname string, options *VirtualNetworkAddressesClientGetOptions) (VirtualNetworkAddressesClientGetResponse, error) { + var err error + const operationName = "VirtualNetworkAddressesClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, cloudvmclustername, virtualnetworkaddressname, options) + if err != nil { + return VirtualNetworkAddressesClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VirtualNetworkAddressesClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VirtualNetworkAddressesClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *VirtualNetworkAddressesClient) getCreateRequest(ctx context.Context, resourceGroupName string, cloudvmclustername string, virtualnetworkaddressname string, _ *VirtualNetworkAddressesClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/cloudVmClusters/{cloudvmclustername}/virtualNetworkAddresses/{virtualnetworkaddressname}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudvmclustername == "" { + return nil, errors.New("parameter cloudvmclustername cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudvmclustername}", url.PathEscape(cloudvmclustername)) + if virtualnetworkaddressname == "" { + return nil, errors.New("parameter virtualnetworkaddressname cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{virtualnetworkaddressname}", url.PathEscape(virtualnetworkaddressname)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VirtualNetworkAddressesClient) getHandleResponse(resp *http.Response) (VirtualNetworkAddressesClientGetResponse, error) { + result := VirtualNetworkAddressesClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualNetworkAddress); err != nil { + return VirtualNetworkAddressesClientGetResponse{}, err + } + return result, nil +} + +// NewListByCloudVMClusterPager - List VirtualNetworkAddress resources by CloudVmCluster +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - cloudvmclustername - CloudVmCluster name +// - options - VirtualNetworkAddressesClientListByCloudVMClusterOptions contains the optional parameters for the VirtualNetworkAddressesClient.NewListByCloudVMClusterPager +// method. +func (client *VirtualNetworkAddressesClient) NewListByCloudVMClusterPager(resourceGroupName string, cloudvmclustername string, options *VirtualNetworkAddressesClientListByCloudVMClusterOptions) *runtime.Pager[VirtualNetworkAddressesClientListByCloudVMClusterResponse] { + return runtime.NewPager(runtime.PagingHandler[VirtualNetworkAddressesClientListByCloudVMClusterResponse]{ + More: func(page VirtualNetworkAddressesClientListByCloudVMClusterResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *VirtualNetworkAddressesClientListByCloudVMClusterResponse) (VirtualNetworkAddressesClientListByCloudVMClusterResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "VirtualNetworkAddressesClient.NewListByCloudVMClusterPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listByCloudVMClusterCreateRequest(ctx, resourceGroupName, cloudvmclustername, options) + }, nil) + if err != nil { + return VirtualNetworkAddressesClientListByCloudVMClusterResponse{}, err + } + return client.listByCloudVMClusterHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listByCloudVMClusterCreateRequest creates the ListByCloudVMCluster request. +func (client *VirtualNetworkAddressesClient) listByCloudVMClusterCreateRequest(ctx context.Context, resourceGroupName string, cloudvmclustername string, _ *VirtualNetworkAddressesClientListByCloudVMClusterOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Oracle.Database/cloudVmClusters/{cloudvmclustername}/virtualNetworkAddresses" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if cloudvmclustername == "" { + return nil, errors.New("parameter cloudvmclustername cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{cloudvmclustername}", url.PathEscape(cloudvmclustername)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250901) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listByCloudVMClusterHandleResponse handles the ListByCloudVMCluster response. +func (client *VirtualNetworkAddressesClient) listByCloudVMClusterHandleResponse(resp *http.Response) (VirtualNetworkAddressesClientListByCloudVMClusterResponse, error) { + result := VirtualNetworkAddressesClientListByCloudVMClusterResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualNetworkAddressListResult); err != nil { + return VirtualNetworkAddressesClientListByCloudVMClusterResponse{}, err + } + return result, nil +} diff --git a/test/local/armpageablelros/LICENSE.txt b/test/local/armpageablelros/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/local/armpageablelros/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/local/armpageablelros/fake/zz_internal.go b/test/local/armpageablelros/fake/zz_internal.go new file mode 100644 index 000000000000..590b4d743e97 --- /dev/null +++ b/test/local/armpageablelros/fake/zz_internal.go @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/local/armpageablelros/fake/zz_server.go b/test/local/armpageablelros/fake/zz_server.go new file mode 100644 index 000000000000..fbef1c0ca6d6 --- /dev/null +++ b/test/local/armpageablelros/fake/zz_server.go @@ -0,0 +1,133 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armpageablelros" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// Server is a fake server for instances of the armpageablelros.Client type. +type Server struct { + // BeginListPrivateEndPoints is the fake for method Client.BeginListPrivateEndPoints + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginListPrivateEndPoints func(ctx context.Context, apiVersion string, resourceGroupName string, resourceName string, options *armpageablelros.ClientBeginListPrivateEndPointsOptions) (resp azfake.PollerResponder[azfake.PagerResponder[armpageablelros.ClientListPrivateEndPointsResponse]], errResp azfake.ErrorResponder) +} + +// NewServerTransport creates a new instance of ServerTransport with the provided implementation. +// The returned ServerTransport instance is connected to an instance of armpageablelros.Client via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerTransport(srv *Server) *ServerTransport { + return &ServerTransport{ + srv: srv, + beginListPrivateEndPoints: newTracker[azfake.PollerResponder[azfake.PagerResponder[armpageablelros.ClientListPrivateEndPointsResponse]]](), + } +} + +// ServerTransport connects instances of armpageablelros.Client to instances of Server. +// Don't use this type directly, use NewServerTransport instead. +type ServerTransport struct { + srv *Server + beginListPrivateEndPoints *tracker[azfake.PollerResponder[azfake.PagerResponder[armpageablelros.ClientListPrivateEndPointsResponse]]] +} + +// Do implements the policy.Transporter interface for ServerTransport. +func (s *ServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if serverTransportInterceptor != nil { + res.resp, res.err, intercepted = serverTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "Client.BeginListPrivateEndPoints": + res.resp, res.err = s.dispatchBeginListPrivateEndPoints(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ServerTransport) dispatchBeginListPrivateEndPoints(req *http.Request) (*http.Response, error) { + if s.srv.BeginListPrivateEndPoints == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginListPrivateEndPoints not implemented")} + } + beginListPrivateEndPoints := s.beginListPrivateEndPoints.get(req) + if beginListPrivateEndPoints == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/PageableLROs/resourceSegment/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + resourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.BeginListPrivateEndPoints(req.Context(), qp.Get("api-version"), resourceGroupNameParam, resourceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginListPrivateEndPoints = &respr + s.beginListPrivateEndPoints.add(req, beginListPrivateEndPoints) + } + + resp, err := server.PollerResponderNext(beginListPrivateEndPoints, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + s.beginListPrivateEndPoints.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginListPrivateEndPoints) { + s.beginListPrivateEndPoints.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to ServerTransport +var serverTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armpageablelros/fake/zz_server_factory.go b/test/local/armpageablelros/fake/zz_server_factory.go new file mode 100644 index 000000000000..0169f40acc42 --- /dev/null +++ b/test/local/armpageablelros/fake/zz_server_factory.go @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armpageablelros.ClientFactory type. +type ServerFactory struct { + // Server contains the fakes for client Client + Server Server +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armpageablelros.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of armpageablelros.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trServer *ServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "Client": + initServer(&s.trMu, &s.trServer, func() *ServerTransport { return NewServerTransport(&s.srv.Server) }) + resp, err = s.trServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} diff --git a/test/local/armpageablelros/go.mod b/test/local/armpageablelros/go.mod new file mode 100644 index 000000000000..1ed3970a017e --- /dev/null +++ b/test/local/armpageablelros/go.mod @@ -0,0 +1,11 @@ +module armpageablelros + +go 1.25.0 + +require github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect +) diff --git a/test/local/armpageablelros/go.sum b/test/local/armpageablelros/go.sum new file mode 100644 index 000000000000..3fdb64caf441 --- /dev/null +++ b/test/local/armpageablelros/go.sum @@ -0,0 +1,16 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/local/armpageablelros/testdata/_metadata.json b/test/local/armpageablelros/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/local/armpageablelros/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/local/armpageablelros/zz_client.go b/test/local/armpageablelros/zz_client.go new file mode 100644 index 000000000000..27a076df85de --- /dev/null +++ b/test/local/armpageablelros/zz_client.go @@ -0,0 +1,138 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armpageablelros + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// Client contains the methods for the service. +// Don't use this type directly, use NewClient() instead. +type Client struct { + internal *arm.Client + subscriptionID string +} + +// NewClient creates a new instance of Client with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*Client, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &Client{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginListPrivateEndPoints - A long-running resource action. +// - apiVersion - The API version to use for this operation. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - resourceName - The name of the SomeResource +// - options - ClientBeginListPrivateEndPointsOptions contains the optional parameters for the Client.BeginListPrivateEndPoints +// method. +func (client *Client) BeginListPrivateEndPoints(ctx context.Context, apiVersion string, resourceGroupName string, resourceName string, options *ClientBeginListPrivateEndPointsOptions) (*runtime.Poller[*runtime.Pager[ClientListPrivateEndPointsResponse]], error) { + pager := runtime.NewPager(runtime.PagingHandler[ClientListPrivateEndPointsResponse]{ + More: func(page ClientListPrivateEndPointsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ClientListPrivateEndPointsResponse) (ClientListPrivateEndPointsResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "Client.BeginListPrivateEndPoints") + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), *page.NextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listPrivateEndPointsCreateRequest(ctx, apiVersion, resourceGroupName, resourceName, options) + }, nil) + if err != nil { + return ClientListPrivateEndPointsResponse{}, err + } + return client.listPrivateEndPointsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) + if options == nil || options.ResumeToken == "" { + resp, err := client.listPrivateEndPoints(ctx, apiVersion, resourceGroupName, resourceName, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[*runtime.Pager[ClientListPrivateEndPointsResponse]]{ + Response: &pager, + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[*runtime.Pager[ClientListPrivateEndPointsResponse]]{ + Response: &pager, + Tracer: client.internal.Tracer(), + }) + } +} + +// ListPrivateEndPoints - A long-running resource action. +func (client *Client) listPrivateEndPoints(ctx context.Context, apiVersion string, resourceGroupName string, resourceName string, options *ClientBeginListPrivateEndPointsOptions) (*http.Response, error) { + var err error + const operationName = "Client.BeginListPrivateEndPoints" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.listPrivateEndPointsCreateRequest(ctx, apiVersion, resourceGroupName, resourceName, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// listPrivateEndPointsCreateRequest creates the ListPrivateEndPoints request. +func (client *Client) listPrivateEndPointsCreateRequest(ctx context.Context, apiVersion string, resourceGroupName string, resourceName string, _ *ClientBeginListPrivateEndPointsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/PageableLROs/resourceSegment/{resourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if resourceName == "" { + return nil, errors.New("parameter resourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceName}", url.PathEscape(resourceName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", apiVersion) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listPrivateEndPointsHandleResponse handles the ListPrivateEndPoints response. +func (client *Client) listPrivateEndPointsHandleResponse(resp *http.Response) (ClientListPrivateEndPointsResponse, error) { + result := ClientListPrivateEndPointsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SomeResourceListResult); err != nil { + return ClientListPrivateEndPointsResponse{}, err + } + return result, nil +} diff --git a/test/local/armpageablelros/zz_client_factory.go b/test/local/armpageablelros/zz_client_factory.go new file mode 100644 index 000000000000..fe05aa20c81a --- /dev/null +++ b/test/local/armpageablelros/zz_client_factory.go @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armpageablelros + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + subscriptionID string + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, + internal: internal, + }, nil +} + +// NewClient creates a new instance of Client. +func (c *ClientFactory) NewClient() *Client { + return &Client{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} diff --git a/test/local/armpageablelros/zz_models.go b/test/local/armpageablelros/zz_models.go new file mode 100644 index 000000000000..b346110538df --- /dev/null +++ b/test/local/armpageablelros/zz_models.go @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armpageablelros + +type ReferencedResource struct { + ID *string +} + +type SomeResourceInfo struct { + Resources []*ReferencedResource +} + +// SomeResourceListResult - Paged collection of SomeResourceInfo items +type SomeResourceListResult struct { + // REQUIRED; The SomeResourceInfo items on this page + Value []*SomeResourceInfo + + // The link to the next page of items + NextLink *string +} diff --git a/test/local/armpageablelros/zz_models_serde.go b/test/local/armpageablelros/zz_models_serde.go new file mode 100644 index 000000000000..293e2156935a --- /dev/null +++ b/test/local/armpageablelros/zz_models_serde.go @@ -0,0 +1,117 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armpageablelros + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type ReferencedResource. +func (r ReferencedResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", r.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ReferencedResource. +func (r *ReferencedResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &r.ID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SomeResourceInfo. +func (s SomeResourceInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "resources", s.Resources) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SomeResourceInfo. +func (s *SomeResourceInfo) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "resources": + err = unpopulate(val, "Resources", &s.Resources) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SomeResourceListResult. +func (s SomeResourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SomeResourceListResult. +func (s *SomeResourceListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &s.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &s.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/local/armpageablelros/zz_options.go b/test/local/armpageablelros/zz_options.go new file mode 100644 index 000000000000..9513ad4fdff3 --- /dev/null +++ b/test/local/armpageablelros/zz_options.go @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armpageablelros + +// ClientBeginListPrivateEndPointsOptions contains the optional parameters for the Client.BeginListPrivateEndPoints method. +type ClientBeginListPrivateEndPointsOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} diff --git a/test/local/armpageablelros/zz_responses.go b/test/local/armpageablelros/zz_responses.go new file mode 100644 index 000000000000..b87781ae01f6 --- /dev/null +++ b/test/local/armpageablelros/zz_responses.go @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armpageablelros + +// ClientListPrivateEndPointsResponse contains the response from method Client.BeginListPrivateEndPoints. +type ClientListPrivateEndPointsResponse struct { + // Paged collection of SomeResourceInfo items + SomeResourceListResult +} diff --git a/test/local/armpageablelros/zz_version.go b/test/local/armpageablelros/zz_version.go new file mode 100644 index 000000000000..6ffb066043bc --- /dev/null +++ b/test/local/armpageablelros/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package armpageablelros + +const ( + moduleName = "armpageablelros" + moduleVersion = "v0.1.0" +) diff --git a/test/local/armrandom/LICENSE.txt b/test/local/armrandom/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/local/armrandom/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/local/armrandom/fake/zz_internal.go b/test/local/armrandom/fake/zz_internal.go new file mode 100644 index 000000000000..590b4d743e97 --- /dev/null +++ b/test/local/armrandom/fake/zz_internal.go @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/local/armrandom/fake/zz_server.go b/test/local/armrandom/fake/zz_server.go new file mode 100644 index 000000000000..9d7c1cda3c13 --- /dev/null +++ b/test/local/armrandom/fake/zz_server.go @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armrandom" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// Server is a fake server for instances of the armrandom.Client type. +type Server struct { + // Get is the fake for method Client.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, options *armrandom.ClientGetOptions) (resp azfake.Responder[armrandom.ClientGetResponse], errResp azfake.ErrorResponder) +} + +// NewServerTransport creates a new instance of ServerTransport with the provided implementation. +// The returned ServerTransport instance is connected to an instance of armrandom.Client via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerTransport(srv *Server) *ServerTransport { + return &ServerTransport{srv: srv} +} + +// ServerTransport connects instances of armrandom.Client to instances of Server. +// Don't use this type directly, use NewServerTransport instead. +type ServerTransport struct { + srv *Server +} + +// Do implements the policy.Transporter interface for ServerTransport. +func (s *ServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if serverTransportInterceptor != nil { + res.resp, res.err, intercepted = serverTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "Client.Get": + res.resp, res.err = s.dispatchGet(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if s.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Random` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Get(req.Context(), resourceGroupNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).FakeData, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ServerTransport +var serverTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armrandom/fake/zz_server_factory.go b/test/local/armrandom/fake/zz_server_factory.go new file mode 100644 index 000000000000..d080a5e5f797 --- /dev/null +++ b/test/local/armrandom/fake/zz_server_factory.go @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armrandom.ClientFactory type. +type ServerFactory struct { + // Server contains the fakes for client Client + Server Server + + // SomeServiceServer contains the fakes for client SomeServiceClient + SomeServiceServer SomeServiceServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armrandom.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of armrandom.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trServer *ServerTransport + trSomeServiceServer *SomeServiceServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "Client": + initServer(&s.trMu, &s.trServer, func() *ServerTransport { return NewServerTransport(&s.srv.Server) }) + resp, err = s.trServer.Do(req) + case "SomeServiceClient": + initServer(&s.trMu, &s.trSomeServiceServer, func() *SomeServiceServerTransport { return NewSomeServiceServerTransport(&s.srv.SomeServiceServer) }) + resp, err = s.trSomeServiceServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} diff --git a/test/local/armrandom/fake/zz_someservice_server.go b/test/local/armrandom/fake/zz_someservice_server.go new file mode 100644 index 000000000000..fa85ef342ddd --- /dev/null +++ b/test/local/armrandom/fake/zz_someservice_server.go @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armrandom" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "reflect" + "slices" +) + +// SomeServiceServer is a fake server for instances of the armrandom.SomeServiceClient type. +type SomeServiceServer struct { + // CheckTrialAvailability is the fake for method SomeServiceClient.CheckTrialAvailability + // HTTP status codes to indicate success: http.StatusOK + CheckTrialAvailability func(ctx context.Context, options *armrandom.SomeServiceClientCheckTrialAvailabilityOptions) (resp azfake.Responder[armrandom.SomeServiceClientCheckTrialAvailabilityResponse], errResp azfake.ErrorResponder) + + // NewListThingsPager is the fake for method SomeServiceClient.NewListThingsPager + // HTTP status codes to indicate success: http.StatusOK + NewListThingsPager func(options *armrandom.SomeServiceClientListThingsOptions) (resp azfake.PagerResponder[armrandom.SomeServiceClientListThingsResponse]) +} + +// NewSomeServiceServerTransport creates a new instance of SomeServiceServerTransport with the provided implementation. +// The returned SomeServiceServerTransport instance is connected to an instance of armrandom.SomeServiceClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewSomeServiceServerTransport(srv *SomeServiceServer) *SomeServiceServerTransport { + return &SomeServiceServerTransport{ + srv: srv, + newListThingsPager: newTracker[azfake.PagerResponder[armrandom.SomeServiceClientListThingsResponse]](), + } +} + +// SomeServiceServerTransport connects instances of armrandom.SomeServiceClient to instances of SomeServiceServer. +// Don't use this type directly, use NewSomeServiceServerTransport instead. +type SomeServiceServerTransport struct { + srv *SomeServiceServer + newListThingsPager *tracker[azfake.PagerResponder[armrandom.SomeServiceClientListThingsResponse]] +} + +// Do implements the policy.Transporter interface for SomeServiceServerTransport. +func (s *SomeServiceServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *SomeServiceServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if someServiceServerTransportInterceptor != nil { + res.resp, res.err, intercepted = someServiceServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "SomeServiceClient.CheckTrialAvailability": + res.resp, res.err = s.dispatchCheckTrialAvailability(req) + case "SomeServiceClient.NewListThingsPager": + res.resp, res.err = s.dispatchNewListThingsPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *SomeServiceServerTransport) dispatchCheckTrialAvailability(req *http.Request) (*http.Response, error) { + if s.srv.CheckTrialAvailability == nil { + return nil, &nonRetriableError{errors.New("fake for method CheckTrialAvailability not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[armrandom.SKU](req) + if err != nil { + return nil, err + } + var options *armrandom.SomeServiceClientCheckTrialAvailabilityOptions + if !reflect.ValueOf(body).IsZero() { + options = &armrandom.SomeServiceClientCheckTrialAvailabilityOptions{ + SKU: &body, + } + } + respr, errRespr := s.srv.CheckTrialAvailability(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Trial, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *SomeServiceServerTransport) dispatchNewListThingsPager(req *http.Request) (*http.Response, error) { + if s.srv.NewListThingsPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListThingsPager not implemented")} + } + newListThingsPager := s.newListThingsPager.get(req) + if newListThingsPager == nil { + resp := s.srv.NewListThingsPager(nil) + newListThingsPager = &resp + s.newListThingsPager.add(req, newListThingsPager) + server.PagerResponderInjectNextLinks(newListThingsPager, req, func(page *armrandom.SomeServiceClientListThingsResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListThingsPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + s.newListThingsPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListThingsPager) { + s.newListThingsPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to SomeServiceServerTransport +var someServiceServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armrandom/go.mod b/test/local/armrandom/go.mod new file mode 100644 index 000000000000..cc15d69b4226 --- /dev/null +++ b/test/local/armrandom/go.mod @@ -0,0 +1,11 @@ +module armrandom + +go 1.25.0 + +require github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect +) diff --git a/test/local/armrandom/go.sum b/test/local/armrandom/go.sum new file mode 100644 index 000000000000..3fdb64caf441 --- /dev/null +++ b/test/local/armrandom/go.sum @@ -0,0 +1,16 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/local/armrandom/testdata/_metadata.json b/test/local/armrandom/testdata/_metadata.json new file mode 100644 index 000000000000..5f1bf1b88dd0 --- /dev/null +++ b/test/local/armrandom/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Microsoft.Random": "2024-03-01" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/local/armrandom/zz_client.go b/test/local/armrandom/zz_client.go new file mode 100644 index 000000000000..5a4208fa5a9d --- /dev/null +++ b/test/local/armrandom/zz_client.go @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armrandom + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// Client contains the methods for the service. +// Don't use this type directly, use NewClient() instead. +// +// Generated from API version 2024-03-01 +type Client struct { + internal *arm.Client + subscriptionID string +} + +// NewClient creates a new instance of Client with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*Client, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &Client{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get details of a certificate profile. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - options - ClientGetOptions contains the optional parameters for the Client.Get method. +func (client *Client) Get(ctx context.Context, resourceGroupName string, options *ClientGetOptions) (ClientGetResponse, error) { + var err error + const operationName = "Client.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, options) + if err != nil { + return ClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *Client) getCreateRequest(ctx context.Context, resourceGroupName string, _ *ClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Random" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240301) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *Client) getHandleResponse(resp *http.Response) (ClientGetResponse, error) { + result := ClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.FakeData); err != nil { + return ClientGetResponse{}, err + } + return result, nil +} diff --git a/test/local/armrandom/zz_client_factory.go b/test/local/armrandom/zz_client_factory.go new file mode 100644 index 000000000000..5fb1605beb03 --- /dev/null +++ b/test/local/armrandom/zz_client_factory.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armrandom + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + subscriptionID string + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + subscriptionID: subscriptionID, + internal: internal, + }, nil +} + +// NewClient creates a new instance of Client. +func (c *ClientFactory) NewClient() *Client { + return &Client{ + subscriptionID: c.subscriptionID, + internal: c.internal, + } +} + +// NewSomeServiceClient creates a new instance of SomeServiceClient. +func (c *ClientFactory) NewSomeServiceClient() *SomeServiceClient { + return &SomeServiceClient{ + internal: c.internal, + } +} diff --git a/test/local/armrandom/zz_constants.go b/test/local/armrandom/zz_constants.go new file mode 100644 index 000000000000..a970dedbf1ec --- /dev/null +++ b/test/local/armrandom/zz_constants.go @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armrandom + +const ( + version20240301 string = "2024-03-01" +) + +// SKUTier - This field is required to be implemented by the Resource Provider if the service has more than one tier, but +// is not required on a PUT. +type SKUTier string + +const ( + // SKUTierBasic - The Basic service tier. + SKUTierBasic SKUTier = "Basic" + // SKUTierFree - The Free service tier. + SKUTierFree SKUTier = "Free" + // SKUTierPremium - The Premium service tier. + SKUTierPremium SKUTier = "Premium" + // SKUTierStandard - The Standard service tier. + SKUTierStandard SKUTier = "Standard" +) + +// PossibleSKUTierValues returns the possible values for the SKUTier const type. +func PossibleSKUTierValues() []SKUTier { + return []SKUTier{ + SKUTierBasic, + SKUTierFree, + SKUTierPremium, + SKUTierStandard, + } +} + +// TrialStatus - trial status +type TrialStatus string + +const ( + // TrialStatusTrialAvailable - is available + TrialStatusTrialAvailable TrialStatus = "TrialAvailable" + // TrialStatusTrialDisabled - is disabled + TrialStatusTrialDisabled TrialStatus = "TrialDisabled" + // TrialStatusTrialUsed - is used + TrialStatusTrialUsed TrialStatus = "TrialUsed" +) + +// PossibleTrialStatusValues returns the possible values for the TrialStatus const type. +func PossibleTrialStatusValues() []TrialStatus { + return []TrialStatus{ + TrialStatusTrialAvailable, + TrialStatusTrialDisabled, + TrialStatusTrialUsed, + } +} diff --git a/test/local/armrandom/zz_models.go b/test/local/armrandom/zz_models.go new file mode 100644 index 000000000000..0eb60c77118c --- /dev/null +++ b/test/local/armrandom/zz_models.go @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armrandom + +// FakeData - Response for fake things. +type FakeData struct { + // REQUIRED; Some floating point value + SomeFloat *float64 + + // REQUIRED; Some string value + SomeString *string +} + +// FakeInfo - Fake info that's referenced only via paged result. +type FakeInfo struct { + // REQUIRED; Some integer value + SomeNumber *int32 + + // REQUIRED; Some string value + SomeString *string +} + +// SKU - The resource model definition representing SKU +type SKU struct { + // REQUIRED; The name of the SKU. Ex - P3. It is typically a letter+number code + Name *string + + // If the SKU supports scale out/in then the capacity integer should be included. If scale out/in is not possible for the + // resource this may be omitted. + Capacity *int32 + + // If the service has different generations of hardware, for the same SKU, then that can be captured here. + Family *string + + // The SKU size. When the name field is the combination of tier and some other value, this would be the standalone code. + Size *string + + // This field is required to be implemented by the Resource Provider if the service has more than one tier, but is not required + // on a PUT. + Tier *SKUTier +} + +// ThingsListResult - List of made up things +type ThingsListResult struct { + // REQUIRED; The fake items on this page + Value []*FakeData + + // More fake things + MoreStuff []*FakeInfo + + // The link to the next page of items + NextLink *string +} + +// Trial - Subscription trial availability +type Trial struct { + // READ-ONLY; Number of trial hosts available + AvailableHosts *int32 + + // READ-ONLY; Trial status + Status *TrialStatus +} diff --git a/test/local/armrandom/zz_models_serde.go b/test/local/armrandom/zz_models_serde.go new file mode 100644 index 000000000000..792439a1a76e --- /dev/null +++ b/test/local/armrandom/zz_models_serde.go @@ -0,0 +1,203 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armrandom + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type FakeData. +func (f FakeData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "someFloat", f.SomeFloat) + populate(objectMap, "someString", f.SomeString) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FakeData. +func (f *FakeData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "someFloat": + err = unpopulate(val, "SomeFloat", &f.SomeFloat) + delete(rawMsg, key) + case "someString": + err = unpopulate(val, "SomeString", &f.SomeString) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type FakeInfo. +func (f FakeInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "someNumber", f.SomeNumber) + populate(objectMap, "someString", f.SomeString) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FakeInfo. +func (f *FakeInfo) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "someNumber": + err = unpopulate(val, "SomeNumber", &f.SomeNumber) + delete(rawMsg, key) + case "someString": + err = unpopulate(val, "SomeString", &f.SomeString) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", f, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SKU. +func (s SKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "capacity", s.Capacity) + populate(objectMap, "family", s.Family) + populate(objectMap, "name", s.Name) + populate(objectMap, "size", s.Size) + populate(objectMap, "tier", s.Tier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SKU. +func (s *SKU) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "capacity": + err = unpopulate(val, "Capacity", &s.Capacity) + delete(rawMsg, key) + case "family": + err = unpopulate(val, "Family", &s.Family) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + case "size": + err = unpopulate(val, "Size", &s.Size) + delete(rawMsg, key) + case "tier": + err = unpopulate(val, "Tier", &s.Tier) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ThingsListResult. +func (t ThingsListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "moreStuff", t.MoreStuff) + populate(objectMap, "nextLink", t.NextLink) + populate(objectMap, "value", t.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ThingsListResult. +func (t *ThingsListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "moreStuff": + err = unpopulate(val, "MoreStuff", &t.MoreStuff) + delete(rawMsg, key) + case "nextLink": + err = unpopulate(val, "NextLink", &t.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &t.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Trial. +func (t Trial) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "availableHosts", t.AvailableHosts) + populate(objectMap, "status", t.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Trial. +func (t *Trial) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "availableHosts": + err = unpopulate(val, "AvailableHosts", &t.AvailableHosts) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &t.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/local/armrandom/zz_options.go b/test/local/armrandom/zz_options.go new file mode 100644 index 000000000000..6a5d079095f3 --- /dev/null +++ b/test/local/armrandom/zz_options.go @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armrandom + +// ClientGetOptions contains the optional parameters for the Client.Get method. +type ClientGetOptions struct { + // placeholder for future optional parameters +} + +// SomeServiceClientCheckTrialAvailabilityOptions contains the optional parameters for the SomeServiceClient.CheckTrialAvailability +// method. +type SomeServiceClientCheckTrialAvailabilityOptions struct { + // Optionally, check for a specific SKU + SKU *SKU +} + +// SomeServiceClientListThingsOptions contains the optional parameters for the SomeServiceClient.NewListThingsPager method. +type SomeServiceClientListThingsOptions struct { + // placeholder for future optional parameters +} diff --git a/test/local/armrandom/zz_responses.go b/test/local/armrandom/zz_responses.go new file mode 100644 index 000000000000..1edb9e36b641 --- /dev/null +++ b/test/local/armrandom/zz_responses.go @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armrandom + +// ClientGetResponse contains the response from method Client.Get. +type ClientGetResponse struct { + // Response for fake things. + FakeData +} + +// SomeServiceClientCheckTrialAvailabilityResponse contains the response from method SomeServiceClient.CheckTrialAvailability. +type SomeServiceClientCheckTrialAvailabilityResponse struct { + // Subscription trial availability + Trial +} + +// SomeServiceClientListThingsResponse contains the response from method SomeServiceClient.NewListThingsPager. +type SomeServiceClientListThingsResponse struct { + // List of made up things + ThingsListResult +} diff --git a/test/local/armrandom/zz_someservice_client.go b/test/local/armrandom/zz_someservice_client.go new file mode 100644 index 000000000000..954991a658cd --- /dev/null +++ b/test/local/armrandom/zz_someservice_client.go @@ -0,0 +1,138 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armrandom + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" +) + +// SomeServiceClient contains the methods for the SomeService group. +// Don't use this type directly, use NewSomeServiceClient() instead. +// +// Generated from API version 2024-03-01 +type SomeServiceClient struct { + internal *arm.Client +} + +// NewSomeServiceClient creates a new instance of SomeServiceClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewSomeServiceClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*SomeServiceClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &SomeServiceClient{ + internal: cl, + } + return client, nil +} + +// CheckTrialAvailability - Return trial status for subscription by region +// If the operation fails it returns an *azcore.ResponseError type. +// - options - SomeServiceClientCheckTrialAvailabilityOptions contains the optional parameters for the SomeServiceClient.CheckTrialAvailability +// method. +func (client *SomeServiceClient) CheckTrialAvailability(ctx context.Context, options *SomeServiceClientCheckTrialAvailabilityOptions) (SomeServiceClientCheckTrialAvailabilityResponse, error) { + var err error + const operationName = "SomeServiceClient.CheckTrialAvailability" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.checkTrialAvailabilityCreateRequest(ctx, options) + if err != nil { + return SomeServiceClientCheckTrialAvailabilityResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SomeServiceClientCheckTrialAvailabilityResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SomeServiceClientCheckTrialAvailabilityResponse{}, err + } + resp, err := client.checkTrialAvailabilityHandleResponse(httpResp) + return resp, err +} + +// checkTrialAvailabilityCreateRequest creates the CheckTrialAvailability request. +func (client *SomeServiceClient) checkTrialAvailabilityCreateRequest(ctx context.Context, options *SomeServiceClientCheckTrialAvailabilityOptions) (*policy.Request, error) { + req, err := runtime.NewRequest(ctx, http.MethodPost, client.internal.Endpoint()) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.SKU != nil { + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, *options.SKU); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// checkTrialAvailabilityHandleResponse handles the CheckTrialAvailability response. +func (client *SomeServiceClient) checkTrialAvailabilityHandleResponse(resp *http.Response) (SomeServiceClientCheckTrialAvailabilityResponse, error) { + result := SomeServiceClientCheckTrialAvailabilityResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Trial); err != nil { + return SomeServiceClientCheckTrialAvailabilityResponse{}, err + } + return result, nil +} + +// NewListThingsPager - Misc test APIs +// - options - SomeServiceClientListThingsOptions contains the optional parameters for the SomeServiceClient.NewListThingsPager +// method. +func (client *SomeServiceClient) NewListThingsPager(options *SomeServiceClientListThingsOptions) *runtime.Pager[SomeServiceClientListThingsResponse] { + return runtime.NewPager(runtime.PagingHandler[SomeServiceClientListThingsResponse]{ + More: func(page SomeServiceClientListThingsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *SomeServiceClientListThingsResponse) (SomeServiceClientListThingsResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "SomeServiceClient.NewListThingsPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listThingsCreateRequest(ctx, options) + }, nil) + if err != nil { + return SomeServiceClientListThingsResponse{}, err + } + return client.listThingsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listThingsCreateRequest creates the ListThings request. +func (client *SomeServiceClient) listThingsCreateRequest(ctx context.Context, _ *SomeServiceClientListThingsOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Random/listThings" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20240301) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listThingsHandleResponse handles the ListThings response. +func (client *SomeServiceClient) listThingsHandleResponse(resp *http.Response) (SomeServiceClientListThingsResponse, error) { + result := SomeServiceClientListThingsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ThingsListResult); err != nil { + return SomeServiceClientListThingsResponse{}, err + } + return result, nil +} diff --git a/test/local/armrandom/zz_version.go b/test/local/armrandom/zz_version.go new file mode 100644 index 000000000000..9ef72a04a492 --- /dev/null +++ b/test/local/armrandom/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package armrandom + +const ( + moduleName = "armrandom" + moduleVersion = "v0.1.0" +) diff --git a/test/local/armtest/LICENSE.txt b/test/local/armtest/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/local/armtest/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/local/armtest/fake/zz_authorization_server.go b/test/local/armtest/fake/zz_authorization_server.go new file mode 100644 index 000000000000..933074bf8f4a --- /dev/null +++ b/test/local/armtest/fake/zz_authorization_server.go @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armtest/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// AuthorizationServer is a fake server for instances of the armtest.AuthorizationClient type. +type AuthorizationServer struct { + // Get is the fake for method AuthorizationClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, authorizationName string, options *armtest.AuthorizationClientGetOptions) (resp azfake.Responder[armtest.AuthorizationClientGetResponse], errResp azfake.ErrorResponder) +} + +// NewAuthorizationServerTransport creates a new instance of AuthorizationServerTransport with the provided implementation. +// The returned AuthorizationServerTransport instance is connected to an instance of armtest.AuthorizationClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAuthorizationServerTransport(srv *AuthorizationServer) *AuthorizationServerTransport { + return &AuthorizationServerTransport{srv: srv} +} + +// AuthorizationServerTransport connects instances of armtest.AuthorizationClient to instances of AuthorizationServer. +// Don't use this type directly, use NewAuthorizationServerTransport instead. +type AuthorizationServerTransport struct { + srv *AuthorizationServer +} + +// Do implements the policy.Transporter interface for AuthorizationServerTransport. +func (a *AuthorizationServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *AuthorizationServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if authorizationServerTransportInterceptor != nil { + res.resp, res.err, intercepted = authorizationServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "AuthorizationClient.Get": + res.resp, res.err = a.dispatchGet(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *AuthorizationServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/providers/Microsoft\.Test/authorizations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + authorizationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("authorizationName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Get(req.Context(), authorizationNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).AuthorizationResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to AuthorizationServerTransport +var authorizationServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armtest/fake/zz_authorizationserver_server.go b/test/local/armtest/fake/zz_authorizationserver_server.go new file mode 100644 index 000000000000..05cd3d17aef8 --- /dev/null +++ b/test/local/armtest/fake/zz_authorizationserver_server.go @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armtest/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// AuthorizationServerServer is a fake server for instances of the armtest.AuthorizationServerClient type. +type AuthorizationServerServer struct { + // Get is the fake for method AuthorizationServerClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, authorizationServerName string, options *armtest.AuthorizationServerClientGetOptions) (resp azfake.Responder[armtest.AuthorizationServerClientGetResponse], errResp azfake.ErrorResponder) +} + +// NewAuthorizationServerServerTransport creates a new instance of AuthorizationServerServerTransport with the provided implementation. +// The returned AuthorizationServerServerTransport instance is connected to an instance of armtest.AuthorizationServerClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewAuthorizationServerServerTransport(srv *AuthorizationServerServer) *AuthorizationServerServerTransport { + return &AuthorizationServerServerTransport{srv: srv} +} + +// AuthorizationServerServerTransport connects instances of armtest.AuthorizationServerClient to instances of AuthorizationServerServer. +// Don't use this type directly, use NewAuthorizationServerServerTransport instead. +type AuthorizationServerServerTransport struct { + srv *AuthorizationServerServer +} + +// Do implements the policy.Transporter interface for AuthorizationServerServerTransport. +func (a *AuthorizationServerServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return a.dispatchToMethodFake(req, method) +} + +func (a *AuthorizationServerServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if authorizationServerServerTransportInterceptor != nil { + res.resp, res.err, intercepted = authorizationServerServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "AuthorizationServerClient.Get": + res.resp, res.err = a.dispatchGet(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (a *AuthorizationServerServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if a.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/providers/Microsoft\.Test/authorizationServers/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + authorizationServerNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("authorizationServerName")]) + if err != nil { + return nil, err + } + respr, errRespr := a.srv.Get(req.Context(), authorizationServerNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).AuthorizationServerResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to AuthorizationServerServerTransport +var authorizationServerServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armtest/fake/zz_bodyroots_server.go b/test/local/armtest/fake/zz_bodyroots_server.go new file mode 100644 index 000000000000..9416760b395a --- /dev/null +++ b/test/local/armtest/fake/zz_bodyroots_server.go @@ -0,0 +1,203 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armtest/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// BodyRootsServer is a fake server for instances of the armtest.BodyRootsClient type. +type BodyRootsServer struct { + // Action is the fake for method BodyRootsClient.Action + // HTTP status codes to indicate success: http.StatusNoContent + Action func(ctx context.Context, resourceGroupName string, bodyRootName string, action armtest.ActionRequest, options *armtest.BodyRootsClientActionOptions) (resp azfake.Responder[armtest.BodyRootsClientActionResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method BodyRootsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, bodyRootName string, options *armtest.BodyRootsClientGetOptions) (resp azfake.Responder[armtest.BodyRootsClientGetResponse], errResp azfake.ErrorResponder) + + // Put is the fake for method BodyRootsClient.Put + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + Put func(ctx context.Context, resourceGroupName string, bodyRootName string, resource armtest.BodyRoot, options *armtest.BodyRootsClientPutOptions) (resp azfake.Responder[armtest.BodyRootsClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewBodyRootsServerTransport creates a new instance of BodyRootsServerTransport with the provided implementation. +// The returned BodyRootsServerTransport instance is connected to an instance of armtest.BodyRootsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewBodyRootsServerTransport(srv *BodyRootsServer) *BodyRootsServerTransport { + return &BodyRootsServerTransport{srv: srv} +} + +// BodyRootsServerTransport connects instances of armtest.BodyRootsClient to instances of BodyRootsServer. +// Don't use this type directly, use NewBodyRootsServerTransport instead. +type BodyRootsServerTransport struct { + srv *BodyRootsServer +} + +// Do implements the policy.Transporter interface for BodyRootsServerTransport. +func (b *BodyRootsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return b.dispatchToMethodFake(req, method) +} + +func (b *BodyRootsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if bodyRootsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = bodyRootsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "BodyRootsClient.Action": + res.resp, res.err = b.dispatchAction(req) + case "BodyRootsClient.Get": + res.resp, res.err = b.dispatchGet(req) + case "BodyRootsClient.Put": + res.resp, res.err = b.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (b *BodyRootsServerTransport) dispatchAction(req *http.Request) (*http.Response, error) { + if b.srv.Action == nil { + return nil, &nonRetriableError{errors.New("fake for method Action not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Test/bodyRoots/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/action` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armtest.ActionRequest](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + bodyRootNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("bodyRootName")]) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.Action(req.Context(), resourceGroupNameParam, bodyRootNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BodyRootsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if b.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Test/bodyRoots/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + bodyRootNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("bodyRootName")]) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.Get(req.Context(), resourceGroupNameParam, bodyRootNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BodyRoot, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (b *BodyRootsServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if b.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Test/bodyRoots/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armtest.BodyRoot](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + bodyRootNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("bodyRootName")]) + if err != nil { + return nil, err + } + respr, errRespr := b.srv.Put(req.Context(), resourceGroupNameParam, bodyRootNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BodyRoot, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to BodyRootsServerTransport +var bodyRootsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armtest/fake/zz_configurations_server.go b/test/local/armtest/fake/zz_configurations_server.go new file mode 100644 index 000000000000..5a6d5512fb13 --- /dev/null +++ b/test/local/armtest/fake/zz_configurations_server.go @@ -0,0 +1,241 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armtest/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "io" + "net/http" + "net/url" + "regexp" + "slices" +) + +// ConfigurationsServer is a fake server for instances of the armtest.ConfigurationsClient type. +type ConfigurationsServer struct { + // GetContent is the fake for method ConfigurationsClient.GetContent + // HTTP status codes to indicate success: http.StatusOK + GetContent func(ctx context.Context, resourceGroupName string, configurationName string, options *armtest.ConfigurationsClientGetContentOptions) (resp azfake.Responder[armtest.ConfigurationsClientGetContentResponse], errResp azfake.ErrorResponder) + + // GetStreamingContent is the fake for method ConfigurationsClient.GetStreamingContent + // HTTP status codes to indicate success: http.StatusOK + GetStreamingContent func(ctx context.Context, resourceGroupName string, configurationName string, options *armtest.ConfigurationsClientGetStreamingContentOptions) (resp azfake.Responder[armtest.ConfigurationsClientGetStreamingContentResponse], errResp azfake.ErrorResponder) + + // GetTextContent is the fake for method ConfigurationsClient.GetTextContent + // HTTP status codes to indicate success: http.StatusOK + GetTextContent func(ctx context.Context, resourceGroupName string, configurationName string, options *armtest.ConfigurationsClientGetTextContentOptions) (resp azfake.Responder[armtest.ConfigurationsClientGetTextContentResponse], errResp azfake.ErrorResponder) + + // PutStreamingContent is the fake for method ConfigurationsClient.PutStreamingContent + // HTTP status codes to indicate success: http.StatusNoContent + PutStreamingContent func(ctx context.Context, resourceGroupName string, configurationName string, body io.ReadSeekCloser, options *armtest.ConfigurationsClientPutStreamingContentOptions) (resp azfake.Responder[armtest.ConfigurationsClientPutStreamingContentResponse], errResp azfake.ErrorResponder) +} + +// NewConfigurationsServerTransport creates a new instance of ConfigurationsServerTransport with the provided implementation. +// The returned ConfigurationsServerTransport instance is connected to an instance of armtest.ConfigurationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewConfigurationsServerTransport(srv *ConfigurationsServer) *ConfigurationsServerTransport { + return &ConfigurationsServerTransport{srv: srv} +} + +// ConfigurationsServerTransport connects instances of armtest.ConfigurationsClient to instances of ConfigurationsServer. +// Don't use this type directly, use NewConfigurationsServerTransport instead. +type ConfigurationsServerTransport struct { + srv *ConfigurationsServer +} + +// Do implements the policy.Transporter interface for ConfigurationsServerTransport. +func (c *ConfigurationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return c.dispatchToMethodFake(req, method) +} + +func (c *ConfigurationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if configurationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = configurationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ConfigurationsClient.GetContent": + res.resp, res.err = c.dispatchGetContent(req) + case "ConfigurationsClient.GetStreamingContent": + res.resp, res.err = c.dispatchGetStreamingContent(req) + case "ConfigurationsClient.GetTextContent": + res.resp, res.err = c.dispatchGetTextContent(req) + case "ConfigurationsClient.PutStreamingContent": + res.resp, res.err = c.dispatchPutStreamingContent(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (c *ConfigurationsServerTransport) dispatchGetContent(req *http.Request) (*http.Response, error) { + if c.srv.GetContent == nil { + return nil, &nonRetriableError{errors.New("fake for method GetContent not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Test/configurations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + configurationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("configurationName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.GetContent(req.Context(), resourceGroupNameParam, configurationNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Configuration, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *ConfigurationsServerTransport) dispatchGetStreamingContent(req *http.Request) (*http.Response, error) { + if c.srv.GetStreamingContent == nil { + return nil, &nonRetriableError{errors.New("fake for method GetStreamingContent not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Test/configurations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/content` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + configurationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("configurationName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.GetStreamingContent(req.Context(), resourceGroupNameParam, configurationNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, &server.ResponseOptions{ + Body: server.GetResponse(respr).Body, + ContentType: req.Header.Get("Content-Type"), + }) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).ContentType; val != nil { + resp.Header.Set("Content-Type", "text/powershell") + } + return resp, nil +} + +func (c *ConfigurationsServerTransport) dispatchGetTextContent(req *http.Request) (*http.Response, error) { + if c.srv.GetTextContent == nil { + return nil, &nonRetriableError{errors.New("fake for method GetTextContent not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Test/configurations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/textContent` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + configurationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("configurationName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.GetTextContent(req.Context(), resourceGroupNameParam, configurationNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsText(respContent, server.GetResponse(respr).Value, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (c *ConfigurationsServerTransport) dispatchPutStreamingContent(req *http.Request) (*http.Response, error) { + if c.srv.PutStreamingContent == nil { + return nil, &nonRetriableError{errors.New("fake for method PutStreamingContent not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Test/configurations/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/putContent` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + configurationNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("configurationName")]) + if err != nil { + return nil, err + } + respr, errRespr := c.srv.PutStreamingContent(req.Context(), resourceGroupNameParam, configurationNameParam, req.Body.(io.ReadSeekCloser), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ConfigurationsServerTransport +var configurationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armtest/fake/zz_internal.go b/test/local/armtest/fake/zz_internal.go new file mode 100644 index 000000000000..f09fd1b96bd8 --- /dev/null +++ b/test/local/armtest/fake/zz_internal.go @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "io" + "net/http" + "reflect" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getHeaderValue(h http.Header, k string) string { + v := h[k] + if len(v) == 0 { + return "" + } + return v[0] +} + +func getOptional[T any](v T) *T { + if reflect.ValueOf(v).IsZero() { + return nil + } + return &v +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} + +func parseOptional[T any](v string, parse func(v string) (T, error)) (*T, error) { + if v == "" { + return nil, nil + } + t, err := parse(v) + if err != nil { + return nil, err + } + return &t, nil +} + +func readRequestBody(req *http.Request) ([]byte, error) { + if req.Body == nil { + return nil, nil + } + body, err := io.ReadAll(req.Body) + if err != nil { + return nil, err + } + req.Body.Close() + return body, nil +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/local/armtest/fake/zz_lro_server.go b/test/local/armtest/fake/zz_lro_server.go new file mode 100644 index 000000000000..d9c6f02517f4 --- /dev/null +++ b/test/local/armtest/fake/zz_lro_server.go @@ -0,0 +1,192 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armtest/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// LROServer is a fake server for instances of the armtest.LROClient type. +type LROServer struct { + // BeginOkResponseWithAsyncHeader is the fake for method LROClient.BeginOkResponseWithAsyncHeader + // HTTP status codes to indicate success: http.StatusOK, http.StatusCreated + BeginOkResponseWithAsyncHeader func(ctx context.Context, resourceGroupName string, lroModelName string, resource armtest.LROModel, options *armtest.LROClientBeginOkResponseWithAsyncHeaderOptions) (resp azfake.PollerResponder[armtest.LROClientOkResponseWithAsyncHeaderResponse], errResp azfake.ErrorResponder) + + // BeginScalarResult is the fake for method LROClient.BeginScalarResult + // HTTP status codes to indicate success: http.StatusOK, http.StatusAccepted + BeginScalarResult func(ctx context.Context, resourceGroupName string, lroModelName string, body armtest.ActionRequest, options *armtest.LROClientBeginScalarResultOptions) (resp azfake.PollerResponder[armtest.LROClientScalarResultResponse], errResp azfake.ErrorResponder) +} + +// NewLROServerTransport creates a new instance of LROServerTransport with the provided implementation. +// The returned LROServerTransport instance is connected to an instance of armtest.LROClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewLROServerTransport(srv *LROServer) *LROServerTransport { + return &LROServerTransport{ + srv: srv, + beginOkResponseWithAsyncHeader: newTracker[azfake.PollerResponder[armtest.LROClientOkResponseWithAsyncHeaderResponse]](), + beginScalarResult: newTracker[azfake.PollerResponder[armtest.LROClientScalarResultResponse]](), + } +} + +// LROServerTransport connects instances of armtest.LROClient to instances of LROServer. +// Don't use this type directly, use NewLROServerTransport instead. +type LROServerTransport struct { + srv *LROServer + beginOkResponseWithAsyncHeader *tracker[azfake.PollerResponder[armtest.LROClientOkResponseWithAsyncHeaderResponse]] + beginScalarResult *tracker[azfake.PollerResponder[armtest.LROClientScalarResultResponse]] +} + +// Do implements the policy.Transporter interface for LROServerTransport. +func (l *LROServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return l.dispatchToMethodFake(req, method) +} + +func (l *LROServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if lroServerTransportInterceptor != nil { + res.resp, res.err, intercepted = lroServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "LROClient.BeginOkResponseWithAsyncHeader": + res.resp, res.err = l.dispatchBeginOkResponseWithAsyncHeader(req) + case "LROClient.BeginScalarResult": + res.resp, res.err = l.dispatchBeginScalarResult(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (l *LROServerTransport) dispatchBeginOkResponseWithAsyncHeader(req *http.Request) (*http.Response, error) { + if l.srv.BeginOkResponseWithAsyncHeader == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginOkResponseWithAsyncHeader not implemented")} + } + beginOkResponseWithAsyncHeader := l.beginOkResponseWithAsyncHeader.get(req) + if beginOkResponseWithAsyncHeader == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Test/LROModels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armtest.LROModel](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + lroModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("LROModelName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.BeginOkResponseWithAsyncHeader(req.Context(), resourceGroupNameParam, lroModelNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginOkResponseWithAsyncHeader = &respr + l.beginOkResponseWithAsyncHeader.add(req, beginOkResponseWithAsyncHeader) + } + + resp, err := server.PollerResponderNext(beginOkResponseWithAsyncHeader, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusCreated}, resp.StatusCode) { + l.beginOkResponseWithAsyncHeader.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusCreated", resp.StatusCode)} + } + if !server.PollerResponderMore(beginOkResponseWithAsyncHeader) { + l.beginOkResponseWithAsyncHeader.remove(req) + } + + return resp, nil +} + +func (l *LROServerTransport) dispatchBeginScalarResult(req *http.Request) (*http.Response, error) { + if l.srv.BeginScalarResult == nil { + return nil, &nonRetriableError{errors.New("fake for method BeginScalarResult not implemented")} + } + beginScalarResult := l.beginScalarResult.get(req) + if beginScalarResult == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Test/LROModels/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/scalarResult` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armtest.ActionRequest](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + lroModelNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("LROModelName")]) + if err != nil { + return nil, err + } + respr, errRespr := l.srv.BeginScalarResult(req.Context(), resourceGroupNameParam, lroModelNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + beginScalarResult = &respr + l.beginScalarResult.add(req, beginScalarResult) + } + + resp, err := server.PollerResponderNext(beginScalarResult, req) + if err != nil { + return nil, err + } + + if !slices.Contains([]int{http.StatusOK, http.StatusAccepted}, resp.StatusCode) { + l.beginScalarResult.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK, http.StatusAccepted", resp.StatusCode)} + } + if !server.PollerResponderMore(beginScalarResult) { + l.beginScalarResult.remove(req) + } + + return resp, nil +} + +// set this to conditionally intercept incoming requests to LROServerTransport +var lroServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armtest/fake/zz_mixedscopewidgets_server.go b/test/local/armtest/fake/zz_mixedscopewidgets_server.go new file mode 100644 index 000000000000..57ad4c403f85 --- /dev/null +++ b/test/local/armtest/fake/zz_mixedscopewidgets_server.go @@ -0,0 +1,196 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armtest/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// MixedScopeWidgetsServer is a fake server for instances of the armtest.MixedScopeWidgetsClient type. +type MixedScopeWidgetsServer struct { + // Get is the fake for method MixedScopeWidgetsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, widgetName string, options *armtest.MixedScopeWidgetsClientGetOptions) (resp azfake.Responder[armtest.MixedScopeWidgetsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListAllPager is the fake for method MixedScopeWidgetsClient.NewListAllPager + // HTTP status codes to indicate success: http.StatusOK + NewListAllPager func(options *armtest.MixedScopeWidgetsClientListAllOptions) (resp azfake.PagerResponder[armtest.MixedScopeWidgetsClientListAllResponse]) + + // NewListBySubscriptionPager is the fake for method MixedScopeWidgetsClient.NewListBySubscriptionPager + // HTTP status codes to indicate success: http.StatusOK + NewListBySubscriptionPager func(options *armtest.MixedScopeWidgetsClientListBySubscriptionOptions) (resp azfake.PagerResponder[armtest.MixedScopeWidgetsClientListBySubscriptionResponse]) +} + +// NewMixedScopeWidgetsServerTransport creates a new instance of MixedScopeWidgetsServerTransport with the provided implementation. +// The returned MixedScopeWidgetsServerTransport instance is connected to an instance of armtest.MixedScopeWidgetsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewMixedScopeWidgetsServerTransport(srv *MixedScopeWidgetsServer) *MixedScopeWidgetsServerTransport { + return &MixedScopeWidgetsServerTransport{ + srv: srv, + newListAllPager: newTracker[azfake.PagerResponder[armtest.MixedScopeWidgetsClientListAllResponse]](), + newListBySubscriptionPager: newTracker[azfake.PagerResponder[armtest.MixedScopeWidgetsClientListBySubscriptionResponse]](), + } +} + +// MixedScopeWidgetsServerTransport connects instances of armtest.MixedScopeWidgetsClient to instances of MixedScopeWidgetsServer. +// Don't use this type directly, use NewMixedScopeWidgetsServerTransport instead. +type MixedScopeWidgetsServerTransport struct { + srv *MixedScopeWidgetsServer + newListAllPager *tracker[azfake.PagerResponder[armtest.MixedScopeWidgetsClientListAllResponse]] + newListBySubscriptionPager *tracker[azfake.PagerResponder[armtest.MixedScopeWidgetsClientListBySubscriptionResponse]] +} + +// Do implements the policy.Transporter interface for MixedScopeWidgetsServerTransport. +func (m *MixedScopeWidgetsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return m.dispatchToMethodFake(req, method) +} + +func (m *MixedScopeWidgetsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if mixedScopeWidgetsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = mixedScopeWidgetsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "MixedScopeWidgetsClient.Get": + res.resp, res.err = m.dispatchGet(req) + case "MixedScopeWidgetsClient.NewListAllPager": + res.resp, res.err = m.dispatchNewListAllPager(req) + case "MixedScopeWidgetsClient.NewListBySubscriptionPager": + res.resp, res.err = m.dispatchNewListBySubscriptionPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (m *MixedScopeWidgetsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if m.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Test/mixedScopeWidgets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + widgetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("widgetName")]) + if err != nil { + return nil, err + } + respr, errRespr := m.srv.Get(req.Context(), resourceGroupNameParam, widgetNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).MixedScopeWidget, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (m *MixedScopeWidgetsServerTransport) dispatchNewListAllPager(req *http.Request) (*http.Response, error) { + if m.srv.NewListAllPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListAllPager not implemented")} + } + newListAllPager := m.newListAllPager.get(req) + if newListAllPager == nil { + resp := m.srv.NewListAllPager(nil) + newListAllPager = &resp + m.newListAllPager.add(req, newListAllPager) + server.PagerResponderInjectNextLinks(newListAllPager, req, func(page *armtest.MixedScopeWidgetsClientListAllResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListAllPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + m.newListAllPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListAllPager) { + m.newListAllPager.remove(req) + } + return resp, nil +} + +func (m *MixedScopeWidgetsServerTransport) dispatchNewListBySubscriptionPager(req *http.Request) (*http.Response, error) { + if m.srv.NewListBySubscriptionPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListBySubscriptionPager not implemented")} + } + newListBySubscriptionPager := m.newListBySubscriptionPager.get(req) + if newListBySubscriptionPager == nil { + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Test/mixedScopeWidgets` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resp := m.srv.NewListBySubscriptionPager(nil) + newListBySubscriptionPager = &resp + m.newListBySubscriptionPager.add(req, newListBySubscriptionPager) + server.PagerResponderInjectNextLinks(newListBySubscriptionPager, req, func(page *armtest.MixedScopeWidgetsClientListBySubscriptionResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListBySubscriptionPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + m.newListBySubscriptionPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListBySubscriptionPager) { + m.newListBySubscriptionPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to MixedScopeWidgetsServerTransport +var mixedScopeWidgetsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armtest/fake/zz_parametergroupoperations_server.go b/test/local/armtest/fake/zz_parametergroupoperations_server.go new file mode 100644 index 000000000000..0a775dcad85d --- /dev/null +++ b/test/local/armtest/fake/zz_parametergroupoperations_server.go @@ -0,0 +1,282 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armtest/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" + "strconv" +) + +// ParameterGroupOperationsServer is a fake server for instances of the armtest.ParameterGroupOperationsClient type. +type ParameterGroupOperationsServer struct { + // NoParameterGroup is the fake for method ParameterGroupOperationsClient.NoParameterGroup + // HTTP status codes to indicate success: http.StatusOK + NoParameterGroup func(ctx context.Context, resourceGroupName string, widgetName string, options *armtest.ParameterGroupOperationsClientNoParameterGroupOptions) (resp azfake.Responder[armtest.ParameterGroupOperationsClientNoParameterGroupResponse], errResp azfake.ErrorResponder) + + // QueryParameterGroup is the fake for method ParameterGroupOperationsClient.QueryParameterGroup + // HTTP status codes to indicate success: http.StatusOK + QueryParameterGroup func(ctx context.Context, resourceGroupName string, widgetName string, params armtest.QueryParams, options *armtest.ParameterGroupOperationsClientQueryParameterGroupOptions) (resp azfake.Responder[armtest.ParameterGroupOperationsClientQueryParameterGroupResponse], errResp azfake.ErrorResponder) + + // SharedParameterGroup1 is the fake for method ParameterGroupOperationsClient.SharedParameterGroup1 + // HTTP status codes to indicate success: http.StatusOK + SharedParameterGroup1 func(ctx context.Context, resourceGroupName string, widgetName string, params armtest.ManagementRequestOptions, options *armtest.ParameterGroupOperationsClientSharedParameterGroup1Options) (resp azfake.Responder[armtest.ParameterGroupOperationsClientSharedParameterGroup1Response], errResp azfake.ErrorResponder) + + // SharedParameterGroup2 is the fake for method ParameterGroupOperationsClient.SharedParameterGroup2 + // HTTP status codes to indicate success: http.StatusOK + SharedParameterGroup2 func(ctx context.Context, resourceGroupName string, widgetName string, params armtest.ManagementRequestOptions, options *armtest.ParameterGroupOperationsClientSharedParameterGroup2Options) (resp azfake.Responder[armtest.ParameterGroupOperationsClientSharedParameterGroup2Response], errResp azfake.ErrorResponder) +} + +// NewParameterGroupOperationsServerTransport creates a new instance of ParameterGroupOperationsServerTransport with the provided implementation. +// The returned ParameterGroupOperationsServerTransport instance is connected to an instance of armtest.ParameterGroupOperationsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewParameterGroupOperationsServerTransport(srv *ParameterGroupOperationsServer) *ParameterGroupOperationsServerTransport { + return &ParameterGroupOperationsServerTransport{srv: srv} +} + +// ParameterGroupOperationsServerTransport connects instances of armtest.ParameterGroupOperationsClient to instances of ParameterGroupOperationsServer. +// Don't use this type directly, use NewParameterGroupOperationsServerTransport instead. +type ParameterGroupOperationsServerTransport struct { + srv *ParameterGroupOperationsServer +} + +// Do implements the policy.Transporter interface for ParameterGroupOperationsServerTransport. +func (p *ParameterGroupOperationsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return p.dispatchToMethodFake(req, method) +} + +func (p *ParameterGroupOperationsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if parameterGroupOperationsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = parameterGroupOperationsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "ParameterGroupOperationsClient.NoParameterGroup": + res.resp, res.err = p.dispatchNoParameterGroup(req) + case "ParameterGroupOperationsClient.QueryParameterGroup": + res.resp, res.err = p.dispatchQueryParameterGroup(req) + case "ParameterGroupOperationsClient.SharedParameterGroup1": + res.resp, res.err = p.dispatchSharedParameterGroup1(req) + case "ParameterGroupOperationsClient.SharedParameterGroup2": + res.resp, res.err = p.dispatchSharedParameterGroup2(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (p *ParameterGroupOperationsServerTransport) dispatchNoParameterGroup(req *http.Request) (*http.Response, error) { + if p.srv.NoParameterGroup == nil { + return nil, &nonRetriableError{errors.New("fake for method NoParameterGroup not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Test/widgets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/noParameterGroup` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + widgetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("widgetName")]) + if err != nil { + return nil, err + } + correlationIDParam := getOptional(getHeaderValue(req.Header, "x-ms-correlation-id")) + var options *armtest.ParameterGroupOperationsClientNoParameterGroupOptions + if correlationIDParam != nil { + options = &armtest.ParameterGroupOperationsClientNoParameterGroupOptions{ + CorrelationID: correlationIDParam, + } + } + respr, errRespr := p.srv.NoParameterGroup(req.Context(), resourceGroupNameParam, widgetNameParam, options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Widget, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (p *ParameterGroupOperationsServerTransport) dispatchQueryParameterGroup(req *http.Request) (*http.Response, error) { + if p.srv.QueryParameterGroup == nil { + return nil, &nonRetriableError{errors.New("fake for method QueryParameterGroup not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Test/widgets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/queryParameterGroup` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + widgetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("widgetName")]) + if err != nil { + return nil, err + } + maxCountParam, err := parseOptional(qp.Get("maxCount"), func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + params := armtest.QueryParams{ + FilterName: qp.Get("filterName"), + } + var options *armtest.ParameterGroupOperationsClientQueryParameterGroupOptions + if maxCountParam != nil { + options = &armtest.ParameterGroupOperationsClientQueryParameterGroupOptions{ + MaxCount: maxCountParam, + } + } + respr, errRespr := p.srv.QueryParameterGroup(req.Context(), resourceGroupNameParam, widgetNameParam, params, options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Widget, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (p *ParameterGroupOperationsServerTransport) dispatchSharedParameterGroup1(req *http.Request) (*http.Response, error) { + if p.srv.SharedParameterGroup1 == nil { + return nil, &nonRetriableError{errors.New("fake for method SharedParameterGroup1 not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Test/widgets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + widgetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("widgetName")]) + if err != nil { + return nil, err + } + correlationIDParam := getOptional(getHeaderValue(req.Header, "x-ms-correlation-id")) + params := armtest.ManagementRequestOptions{ + ClientRequestID: getHeaderValue(req.Header, "x-ms-client-request-id"), + } + var options *armtest.ParameterGroupOperationsClientSharedParameterGroup1Options + if correlationIDParam != nil { + options = &armtest.ParameterGroupOperationsClientSharedParameterGroup1Options{ + CorrelationID: correlationIDParam, + } + } + respr, errRespr := p.srv.SharedParameterGroup1(req.Context(), resourceGroupNameParam, widgetNameParam, params, options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Widget, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (p *ParameterGroupOperationsServerTransport) dispatchSharedParameterGroup2(req *http.Request) (*http.Response, error) { + if p.srv.SharedParameterGroup2 == nil { + return nil, &nonRetriableError{errors.New("fake for method SharedParameterGroup2 not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Test/widgets/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/sharedParameterGroup2` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + widgetNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("widgetName")]) + if err != nil { + return nil, err + } + correlationIDParam := getOptional(getHeaderValue(req.Header, "x-ms-correlation-id")) + params := armtest.ManagementRequestOptions{ + ClientRequestID: getHeaderValue(req.Header, "x-ms-client-request-id"), + } + var options *armtest.ParameterGroupOperationsClientSharedParameterGroup2Options + if correlationIDParam != nil { + options = &armtest.ParameterGroupOperationsClientSharedParameterGroup2Options{ + CorrelationID: correlationIDParam, + } + } + respr, errRespr := p.srv.SharedParameterGroup2(req.Context(), resourceGroupNameParam, widgetNameParam, params, options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Widget, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ParameterGroupOperationsServerTransport +var parameterGroupOperationsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armtest/fake/zz_pets_server.go b/test/local/armtest/fake/zz_pets_server.go new file mode 100644 index 000000000000..021883723dd0 --- /dev/null +++ b/test/local/armtest/fake/zz_pets_server.go @@ -0,0 +1,207 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armtest/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "regexp" + "slices" +) + +// PetsServer is a fake server for instances of the armtest.PetsClient type. +type PetsServer struct { + // AdoptCat is the fake for method PetsClient.AdoptCat + // HTTP status codes to indicate success: http.StatusOK + AdoptCat func(ctx context.Context, resourceGroupName string, petResourceName string, cat armtest.Cat, options *armtest.PetsClientAdoptCatOptions) (resp azfake.Responder[armtest.PetsClientAdoptCatResponse], errResp azfake.ErrorResponder) + + // AdoptPet is the fake for method PetsClient.AdoptPet + // HTTP status codes to indicate success: http.StatusOK + AdoptPet func(ctx context.Context, resourceGroupName string, petResourceName string, pet armtest.PetClassification, options *armtest.PetsClientAdoptPetOptions) (resp azfake.Responder[armtest.PetsClientAdoptPetResponse], errResp azfake.ErrorResponder) + + // Get is the fake for method PetsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, resourceGroupName string, petResourceName string, options *armtest.PetsClientGetOptions) (resp azfake.Responder[armtest.PetsClientGetResponse], errResp azfake.ErrorResponder) +} + +// NewPetsServerTransport creates a new instance of PetsServerTransport with the provided implementation. +// The returned PetsServerTransport instance is connected to an instance of armtest.PetsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewPetsServerTransport(srv *PetsServer) *PetsServerTransport { + return &PetsServerTransport{srv: srv} +} + +// PetsServerTransport connects instances of armtest.PetsClient to instances of PetsServer. +// Don't use this type directly, use NewPetsServerTransport instead. +type PetsServerTransport struct { + srv *PetsServer +} + +// Do implements the policy.Transporter interface for PetsServerTransport. +func (p *PetsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return p.dispatchToMethodFake(req, method) +} + +func (p *PetsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if petsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = petsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "PetsClient.AdoptCat": + res.resp, res.err = p.dispatchAdoptCat(req) + case "PetsClient.AdoptPet": + res.resp, res.err = p.dispatchAdoptPet(req) + case "PetsClient.Get": + res.resp, res.err = p.dispatchGet(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (p *PetsServerTransport) dispatchAdoptCat(req *http.Request) (*http.Response, error) { + if p.srv.AdoptCat == nil { + return nil, &nonRetriableError{errors.New("fake for method AdoptCat not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Test/petResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/adoptCat` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[armtest.Cat](req) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + petResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("petResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.AdoptCat(req.Context(), resourceGroupNameParam, petResourceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Cat, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (p *PetsServerTransport) dispatchAdoptPet(req *http.Request) (*http.Response, error) { + if p.srv.AdoptPet == nil { + return nil, &nonRetriableError{errors.New("fake for method AdoptPet not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Test/petResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/adoptPet` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + raw, err := readRequestBody(req) + if err != nil { + return nil, err + } + body, err := unmarshalPetClassification(raw) + if err != nil { + return nil, err + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + petResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("petResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.AdoptPet(req.Context(), resourceGroupNameParam, petResourceNameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).PetClassification, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (p *PetsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if p.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/subscriptions/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/resourceGroups/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/providers/Microsoft\.Test/petResources/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 4 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + resourceGroupNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("resourceGroupName")]) + if err != nil { + return nil, err + } + petResourceNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("petResourceName")]) + if err != nil { + return nil, err + } + respr, errRespr := p.srv.Get(req.Context(), resourceGroupNameParam, petResourceNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).PetResource, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to PetsServerTransport +var petsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armtest/fake/zz_polymorphic_helpers.go b/test/local/armtest/fake/zz_polymorphic_helpers.go new file mode 100644 index 000000000000..35c356274ec0 --- /dev/null +++ b/test/local/armtest/fake/zz_polymorphic_helpers.go @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armtest/v2" + "encoding/json" +) + +func unmarshalPetClassification(rawMsg json.RawMessage) (armtest.PetClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b armtest.PetClassification + switch m["kind"] { + case string(armtest.PetKindCat): + b = &armtest.Cat{} + case string(armtest.PetKindDog): + b = &armtest.Dog{} + default: + b = &armtest.Pet{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} diff --git a/test/local/armtest/fake/zz_server_factory.go b/test/local/armtest/fake/zz_server_factory.go new file mode 100644 index 000000000000..7e7cb2b541d1 --- /dev/null +++ b/test/local/armtest/fake/zz_server_factory.go @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// ServerFactory is a fake server for instances of the armtest.ClientFactory type. +type ServerFactory struct { + // AuthorizationServer contains the fakes for client AuthorizationClient + AuthorizationServer AuthorizationServer + + // AuthorizationServerServer contains the fakes for client AuthorizationServerClient + AuthorizationServerServer AuthorizationServerServer + + // BodyRootsServer contains the fakes for client BodyRootsClient + BodyRootsServer BodyRootsServer + + // ConfigurationsServer contains the fakes for client ConfigurationsClient + ConfigurationsServer ConfigurationsServer + + // LROServer contains the fakes for client LROClient + LROServer LROServer + + // MixedScopeWidgetsServer contains the fakes for client MixedScopeWidgetsClient + MixedScopeWidgetsServer MixedScopeWidgetsServer + + // ParameterGroupOperationsServer contains the fakes for client ParameterGroupOperationsClient + ParameterGroupOperationsServer ParameterGroupOperationsServer + + // PetsServer contains the fakes for client PetsClient + PetsServer PetsServer + + // TenantItemsServer contains the fakes for client TenantItemsClient + TenantItemsServer TenantItemsServer +} + +// NewServerFactoryTransport creates a new instance of ServerFactoryTransport with the provided implementation. +// The returned ServerFactoryTransport instance is connected to an instance of armtest.ClientFactory via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerFactoryTransport(srv *ServerFactory) *ServerFactoryTransport { + return &ServerFactoryTransport{ + srv: srv, + } +} + +// ServerFactoryTransport connects instances of armtest.ClientFactory to instances of ServerFactory. +// Don't use this type directly, use NewServerFactoryTransport instead. +type ServerFactoryTransport struct { + srv *ServerFactory + trMu sync.Mutex + trAuthorizationServer *AuthorizationServerTransport + trAuthorizationServerServer *AuthorizationServerServerTransport + trBodyRootsServer *BodyRootsServerTransport + trConfigurationsServer *ConfigurationsServerTransport + trLROServer *LROServerTransport + trMixedScopeWidgetsServer *MixedScopeWidgetsServerTransport + trParameterGroupOperationsServer *ParameterGroupOperationsServerTransport + trPetsServer *PetsServerTransport + trTenantItemsServer *TenantItemsServerTransport +} + +// Do implements the policy.Transporter interface for ServerFactoryTransport. +func (s *ServerFactoryTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + client := method[:strings.Index(method, ".")] + var resp *http.Response + var err error + + switch client { + case "AuthorizationClient": + initServer(&s.trMu, &s.trAuthorizationServer, func() *AuthorizationServerTransport { + return NewAuthorizationServerTransport(&s.srv.AuthorizationServer) + }) + resp, err = s.trAuthorizationServer.Do(req) + case "AuthorizationServerClient": + initServer(&s.trMu, &s.trAuthorizationServerServer, func() *AuthorizationServerServerTransport { + return NewAuthorizationServerServerTransport(&s.srv.AuthorizationServerServer) + }) + resp, err = s.trAuthorizationServerServer.Do(req) + case "BodyRootsClient": + initServer(&s.trMu, &s.trBodyRootsServer, func() *BodyRootsServerTransport { return NewBodyRootsServerTransport(&s.srv.BodyRootsServer) }) + resp, err = s.trBodyRootsServer.Do(req) + case "ConfigurationsClient": + initServer(&s.trMu, &s.trConfigurationsServer, func() *ConfigurationsServerTransport { + return NewConfigurationsServerTransport(&s.srv.ConfigurationsServer) + }) + resp, err = s.trConfigurationsServer.Do(req) + case "LROClient": + initServer(&s.trMu, &s.trLROServer, func() *LROServerTransport { return NewLROServerTransport(&s.srv.LROServer) }) + resp, err = s.trLROServer.Do(req) + case "MixedScopeWidgetsClient": + initServer(&s.trMu, &s.trMixedScopeWidgetsServer, func() *MixedScopeWidgetsServerTransport { + return NewMixedScopeWidgetsServerTransport(&s.srv.MixedScopeWidgetsServer) + }) + resp, err = s.trMixedScopeWidgetsServer.Do(req) + case "ParameterGroupOperationsClient": + initServer(&s.trMu, &s.trParameterGroupOperationsServer, func() *ParameterGroupOperationsServerTransport { + return NewParameterGroupOperationsServerTransport(&s.srv.ParameterGroupOperationsServer) + }) + resp, err = s.trParameterGroupOperationsServer.Do(req) + case "PetsClient": + initServer(&s.trMu, &s.trPetsServer, func() *PetsServerTransport { return NewPetsServerTransport(&s.srv.PetsServer) }) + resp, err = s.trPetsServer.Do(req) + case "TenantItemsClient": + initServer(&s.trMu, &s.trTenantItemsServer, func() *TenantItemsServerTransport { return NewTenantItemsServerTransport(&s.srv.TenantItemsServer) }) + resp, err = s.trTenantItemsServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + if err != nil { + return nil, err + } + + return resp, nil +} diff --git a/test/local/armtest/fake/zz_tenantitems_server.go b/test/local/armtest/fake/zz_tenantitems_server.go new file mode 100644 index 000000000000..61edcdb3ebff --- /dev/null +++ b/test/local/armtest/fake/zz_tenantitems_server.go @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "armtest/v2" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// TenantItemsServer is a fake server for instances of the armtest.TenantItemsClient type. +type TenantItemsServer struct { + // Get is the fake for method TenantItemsClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, tenantItemName string, options *armtest.TenantItemsClientGetOptions) (resp azfake.Responder[armtest.TenantItemsClientGetResponse], errResp azfake.ErrorResponder) + + // NewListPager is the fake for method TenantItemsClient.NewListPager + // HTTP status codes to indicate success: http.StatusOK + NewListPager func(options *armtest.TenantItemsClientListOptions) (resp azfake.PagerResponder[armtest.TenantItemsClientListResponse]) +} + +// NewTenantItemsServerTransport creates a new instance of TenantItemsServerTransport with the provided implementation. +// The returned TenantItemsServerTransport instance is connected to an instance of armtest.TenantItemsClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewTenantItemsServerTransport(srv *TenantItemsServer) *TenantItemsServerTransport { + return &TenantItemsServerTransport{ + srv: srv, + newListPager: newTracker[azfake.PagerResponder[armtest.TenantItemsClientListResponse]](), + } +} + +// TenantItemsServerTransport connects instances of armtest.TenantItemsClient to instances of TenantItemsServer. +// Don't use this type directly, use NewTenantItemsServerTransport instead. +type TenantItemsServerTransport struct { + srv *TenantItemsServer + newListPager *tracker[azfake.PagerResponder[armtest.TenantItemsClientListResponse]] +} + +// Do implements the policy.Transporter interface for TenantItemsServerTransport. +func (t *TenantItemsServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return t.dispatchToMethodFake(req, method) +} + +func (t *TenantItemsServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if tenantItemsServerTransportInterceptor != nil { + res.resp, res.err, intercepted = tenantItemsServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "TenantItemsClient.Get": + res.resp, res.err = t.dispatchGet(req) + case "TenantItemsClient.NewListPager": + res.resp, res.err = t.dispatchNewListPager(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (t *TenantItemsServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if t.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + const regexStr = `/providers/Microsoft\.Test/tenantItems/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + tenantItemNameParam, err := url.PathUnescape(matches[regex.SubexpIndex("tenantItemName")]) + if err != nil { + return nil, err + } + respr, errRespr := t.srv.Get(req.Context(), tenantItemNameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).TenantItem, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (t *TenantItemsServerTransport) dispatchNewListPager(req *http.Request) (*http.Response, error) { + if t.srv.NewListPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListPager not implemented")} + } + newListPager := t.newListPager.get(req) + if newListPager == nil { + resp := t.srv.NewListPager(nil) + newListPager = &resp + t.newListPager.add(req, newListPager) + server.PagerResponderInjectNextLinks(newListPager, req, func(page *armtest.TenantItemsClientListResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + t.newListPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListPager) { + t.newListPager.remove(req) + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to TenantItemsServerTransport +var tenantItemsServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/armtest/go.mod b/test/local/armtest/go.mod new file mode 100644 index 000000000000..e7cab876f1ae --- /dev/null +++ b/test/local/armtest/go.mod @@ -0,0 +1,11 @@ +module armtest/v2 + +go 1.25.0 + +require github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect +) diff --git a/test/local/armtest/go.sum b/test/local/armtest/go.sum new file mode 100644 index 000000000000..3fdb64caf441 --- /dev/null +++ b/test/local/armtest/go.sum @@ -0,0 +1,16 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/local/armtest/testdata/_metadata.json b/test/local/armtest/testdata/_metadata.json new file mode 100644 index 000000000000..91dbe52bc144 --- /dev/null +++ b/test/local/armtest/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Microsoft.Test": "2025-01-01" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/local/armtest/zz_authorization_client.go b/test/local/armtest/zz_authorization_client.go new file mode 100644 index 000000000000..2c87658943fc --- /dev/null +++ b/test/local/armtest/zz_authorization_client.go @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armtest + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// AuthorizationClient contains the methods for the Authorization group. +// Don't use this type directly, use NewAuthorizationClient() instead. +// +// Generated from API version 2025-01-01 +type AuthorizationClient struct { + internal *arm.Client +} + +// NewAuthorizationClient creates a new instance of AuthorizationClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewAuthorizationClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*AuthorizationClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AuthorizationClient{ + internal: cl, + } + return client, nil +} + +// Get - Get an authorization. +// If the operation fails it returns an *azcore.ResponseError type. +// - authorizationName - Authorization name. +// - options - AuthorizationClientGetOptions contains the optional parameters for the AuthorizationClient.Get method. +func (client *AuthorizationClient) Get(ctx context.Context, authorizationName string, options *AuthorizationClientGetOptions) (AuthorizationClientGetResponse, error) { + var err error + const operationName = "AuthorizationClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, authorizationName, options) + if err != nil { + return AuthorizationClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AuthorizationClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AuthorizationClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *AuthorizationClient) getCreateRequest(ctx context.Context, authorizationName string, _ *AuthorizationClientGetOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Test/authorizations/{authorizationName}" + if authorizationName == "" { + return nil, errors.New("parameter authorizationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationName}", url.PathEscape(authorizationName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *AuthorizationClient) getHandleResponse(resp *http.Response) (AuthorizationClientGetResponse, error) { + result := AuthorizationClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AuthorizationResource); err != nil { + return AuthorizationClientGetResponse{}, err + } + return result, nil +} diff --git a/test/local/armtest/zz_authorizationserver_client.go b/test/local/armtest/zz_authorizationserver_client.go new file mode 100644 index 000000000000..8567dc139b2c --- /dev/null +++ b/test/local/armtest/zz_authorizationserver_client.go @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armtest + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// AuthorizationServerClient contains the methods for the AuthorizationServer group. +// Don't use this type directly, use NewAuthorizationServerClient() instead. +// +// Generated from API version 2025-01-01 +type AuthorizationServerClient struct { + internal *arm.Client +} + +// NewAuthorizationServerClient creates a new instance of AuthorizationServerClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewAuthorizationServerClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*AuthorizationServerClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &AuthorizationServerClient{ + internal: cl, + } + return client, nil +} + +// Get - Get an authorization server. +// If the operation fails it returns an *azcore.ResponseError type. +// - authorizationServerName - Authorization server name. +// - options - AuthorizationServerClientGetOptions contains the optional parameters for the AuthorizationServerClient.Get method. +func (client *AuthorizationServerClient) Get(ctx context.Context, authorizationServerName string, options *AuthorizationServerClientGetOptions) (AuthorizationServerClientGetResponse, error) { + var err error + const operationName = "AuthorizationServerClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, authorizationServerName, options) + if err != nil { + return AuthorizationServerClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AuthorizationServerClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AuthorizationServerClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *AuthorizationServerClient) getCreateRequest(ctx context.Context, authorizationServerName string, _ *AuthorizationServerClientGetOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Test/authorizationServers/{authorizationServerName}" + if authorizationServerName == "" { + return nil, errors.New("parameter authorizationServerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationServerName}", url.PathEscape(authorizationServerName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *AuthorizationServerClient) getHandleResponse(resp *http.Response) (AuthorizationServerClientGetResponse, error) { + result := AuthorizationServerClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.AuthorizationServerResource); err != nil { + return AuthorizationServerClientGetResponse{}, err + } + return result, nil +} diff --git a/test/local/armtest/zz_bodyroots_client.go b/test/local/armtest/zz_bodyroots_client.go new file mode 100644 index 000000000000..96070502f102 --- /dev/null +++ b/test/local/armtest/zz_bodyroots_client.go @@ -0,0 +1,228 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armtest + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// BodyRootsClient contains the methods for the BodyRoots group. +// Don't use this type directly, use NewBodyRootsClient() instead. +// +// Generated from API version 2025-01-01 +type BodyRootsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewBodyRootsClient creates a new instance of BodyRootsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewBodyRootsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*BodyRootsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &BodyRootsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Action - Revoke a certificate under a certificate profile. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - bodyRootName - Body root resource name. +// - action - The content of the action request +// - options - BodyRootsClientActionOptions contains the optional parameters for the BodyRootsClient.Action method. +func (client *BodyRootsClient) Action(ctx context.Context, resourceGroupName string, bodyRootName string, action ActionRequest, options *BodyRootsClientActionOptions) (BodyRootsClientActionResponse, error) { + var err error + const operationName = "BodyRootsClient.Action" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.actionCreateRequest(ctx, resourceGroupName, bodyRootName, action, options) + if err != nil { + return BodyRootsClientActionResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BodyRootsClientActionResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return BodyRootsClientActionResponse{}, err + } + return BodyRootsClientActionResponse{}, nil +} + +// actionCreateRequest creates the Action request. +func (client *BodyRootsClient) actionCreateRequest(ctx context.Context, resourceGroupName string, bodyRootName string, action ActionRequest, _ *BodyRootsClientActionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Test/bodyRoots/{bodyRootName}/action" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if bodyRootName == "" { + return nil, errors.New("parameter bodyRootName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{bodyRootName}", url.PathEscape(bodyRootName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250101) + reqQP.Set("filter", "constantValue") + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, action); err != nil { + return nil, err + } + return req, nil +} + +// Get - Get details of a certificate profile. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - bodyRootName - Body root resource name. +// - options - BodyRootsClientGetOptions contains the optional parameters for the BodyRootsClient.Get method. +func (client *BodyRootsClient) Get(ctx context.Context, resourceGroupName string, bodyRootName string, options *BodyRootsClientGetOptions) (BodyRootsClientGetResponse, error) { + var err error + const operationName = "BodyRootsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, bodyRootName, options) + if err != nil { + return BodyRootsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BodyRootsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BodyRootsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *BodyRootsClient) getCreateRequest(ctx context.Context, resourceGroupName string, bodyRootName string, _ *BodyRootsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Test/bodyRoots/{bodyRootName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if bodyRootName == "" { + return nil, errors.New("parameter bodyRootName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{bodyRootName}", url.PathEscape(bodyRootName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *BodyRootsClient) getHandleResponse(resp *http.Response) (BodyRootsClientGetResponse, error) { + result := BodyRootsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BodyRoot); err != nil { + return BodyRootsClientGetResponse{}, err + } + return result, nil +} + +// Put - Create or update a body root resource. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - bodyRootName - Body root resource name. +// - resource - Resource create parameters. +// - options - BodyRootsClientPutOptions contains the optional parameters for the BodyRootsClient.Put method. +func (client *BodyRootsClient) Put(ctx context.Context, resourceGroupName string, bodyRootName string, resource BodyRoot, options *BodyRootsClientPutOptions) (BodyRootsClientPutResponse, error) { + var err error + const operationName = "BodyRootsClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, resourceGroupName, bodyRootName, resource, options) + if err != nil { + return BodyRootsClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BodyRootsClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return BodyRootsClientPutResponse{}, err + } + resp, err := client.putHandleResponse(httpResp) + return resp, err +} + +// putCreateRequest creates the Put request. +func (client *BodyRootsClient) putCreateRequest(ctx context.Context, resourceGroupName string, bodyRootName string, resource BodyRoot, _ *BodyRootsClientPutOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Test/bodyRoots/{bodyRootName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if bodyRootName == "" { + return nil, errors.New("parameter bodyRootName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{bodyRootName}", url.PathEscape(bodyRootName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// putHandleResponse handles the Put response. +func (client *BodyRootsClient) putHandleResponse(resp *http.Response) (BodyRootsClientPutResponse, error) { + result := BodyRootsClientPutResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BodyRoot); err != nil { + return BodyRootsClientPutResponse{}, err + } + return result, nil +} diff --git a/test/local/armtest/zz_client_factory.go b/test/local/armtest/zz_client_factory.go new file mode 100644 index 000000000000..9a32fd7a6f92 --- /dev/null +++ b/test/local/armtest/zz_client_factory.go @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armtest + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" +) + +// ClientFactory is a client factory used to create any client in this module. +// Don't use this type directly, use NewClientFactory instead. +type ClientFactory struct { + internal *arm.Client +} + +// NewClientFactory creates a new instance of ClientFactory with the specified values. +// The parameter values will be propagated to any client created from this factory. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - pass nil to accept the default values. +func NewClientFactory(credential azcore.TokenCredential, options *arm.ClientOptions) (*ClientFactory, error) { + internal, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + return &ClientFactory{ + internal: internal, + }, nil +} + +// NewAuthorizationClient creates a new instance of AuthorizationClient. +func (c *ClientFactory) NewAuthorizationClient() *AuthorizationClient { + return &AuthorizationClient{ + internal: c.internal, + } +} + +// NewAuthorizationServerClient creates a new instance of AuthorizationServerClient. +func (c *ClientFactory) NewAuthorizationServerClient() *AuthorizationServerClient { + return &AuthorizationServerClient{ + internal: c.internal, + } +} + +// NewBodyRootsClient creates a new instance of BodyRootsClient. +func (c *ClientFactory) NewBodyRootsClient(subscriptionID string) *BodyRootsClient { + return &BodyRootsClient{ + subscriptionID: subscriptionID, + internal: c.internal, + } +} + +// NewConfigurationsClient creates a new instance of ConfigurationsClient. +func (c *ClientFactory) NewConfigurationsClient(subscriptionID string) *ConfigurationsClient { + return &ConfigurationsClient{ + subscriptionID: subscriptionID, + internal: c.internal, + } +} + +// NewLROClient creates a new instance of LROClient. +func (c *ClientFactory) NewLROClient(subscriptionID string) *LROClient { + return &LROClient{ + subscriptionID: subscriptionID, + internal: c.internal, + } +} + +// NewMixedScopeWidgetsClient creates a new instance of MixedScopeWidgetsClient. +func (c *ClientFactory) NewMixedScopeWidgetsClient(subscriptionID string) *MixedScopeWidgetsClient { + return &MixedScopeWidgetsClient{ + subscriptionID: subscriptionID, + internal: c.internal, + } +} + +// NewParameterGroupOperationsClient creates a new instance of ParameterGroupOperationsClient. +func (c *ClientFactory) NewParameterGroupOperationsClient(subscriptionID string) *ParameterGroupOperationsClient { + return &ParameterGroupOperationsClient{ + subscriptionID: subscriptionID, + internal: c.internal, + } +} + +// NewPetsClient creates a new instance of PetsClient. +func (c *ClientFactory) NewPetsClient(subscriptionID string) *PetsClient { + return &PetsClient{ + subscriptionID: subscriptionID, + internal: c.internal, + } +} + +// NewTenantItemsClient creates a new instance of TenantItemsClient. +func (c *ClientFactory) NewTenantItemsClient() *TenantItemsClient { + return &TenantItemsClient{ + internal: c.internal, + } +} diff --git a/test/local/armtest/zz_configurations_client.go b/test/local/armtest/zz_configurations_client.go new file mode 100644 index 000000000000..2dad7153f16d --- /dev/null +++ b/test/local/armtest/zz_configurations_client.go @@ -0,0 +1,293 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armtest + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "io" + "net/http" + "net/url" + "strings" +) + +// ConfigurationsClient contains the methods for the Configurations group. +// Don't use this type directly, use NewConfigurationsClient() instead. +// +// Generated from API version 2025-01-01 +type ConfigurationsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewConfigurationsClient creates a new instance of ConfigurationsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewConfigurationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ConfigurationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ConfigurationsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// GetContent - Get the content of the configuration. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - configurationName - The configuration name. +// - options - ConfigurationsClientGetContentOptions contains the optional parameters for the ConfigurationsClient.GetContent +// method. +func (client *ConfigurationsClient) GetContent(ctx context.Context, resourceGroupName string, configurationName string, options *ConfigurationsClientGetContentOptions) (ConfigurationsClientGetContentResponse, error) { + var err error + const operationName = "ConfigurationsClient.GetContent" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getContentCreateRequest(ctx, resourceGroupName, configurationName, options) + if err != nil { + return ConfigurationsClientGetContentResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ConfigurationsClientGetContentResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ConfigurationsClientGetContentResponse{}, err + } + resp, err := client.getContentHandleResponse(httpResp) + return resp, err +} + +// getContentCreateRequest creates the GetContent request. +func (client *ConfigurationsClient) getContentCreateRequest(ctx context.Context, resourceGroupName string, configurationName string, _ *ConfigurationsClientGetContentOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Test/configurations/{configurationName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if configurationName == "" { + return nil, errors.New("parameter configurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{configurationName}", url.PathEscape(configurationName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getContentHandleResponse handles the GetContent response. +func (client *ConfigurationsClient) getContentHandleResponse(resp *http.Response) (ConfigurationsClientGetContentResponse, error) { + result := ConfigurationsClientGetContentResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Configuration); err != nil { + return ConfigurationsClientGetContentResponse{}, err + } + return result, nil +} + +// GetStreamingContent - Get the content of the configuration identified by configuration name. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - configurationName - The configuration name. +// - options - ConfigurationsClientGetStreamingContentOptions contains the optional parameters for the ConfigurationsClient.GetStreamingContent +// method. +func (client *ConfigurationsClient) GetStreamingContent(ctx context.Context, resourceGroupName string, configurationName string, options *ConfigurationsClientGetStreamingContentOptions) (ConfigurationsClientGetStreamingContentResponse, error) { + var err error + const operationName = "ConfigurationsClient.GetStreamingContent" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getStreamingContentCreateRequest(ctx, resourceGroupName, configurationName, options) + if err != nil { + return ConfigurationsClientGetStreamingContentResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ConfigurationsClientGetStreamingContentResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ConfigurationsClientGetStreamingContentResponse{}, err + } + resp, err := client.getStreamingContentHandleResponse(httpResp) + return resp, err +} + +// getStreamingContentCreateRequest creates the GetStreamingContent request. +func (client *ConfigurationsClient) getStreamingContentCreateRequest(ctx context.Context, resourceGroupName string, configurationName string, _ *ConfigurationsClientGetStreamingContentOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Test/configurations/{configurationName}/content" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if configurationName == "" { + return nil, errors.New("parameter configurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{configurationName}", url.PathEscape(configurationName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + runtime.SkipBodyDownload(req) + req.Raw().Header["Accept"] = []string{"text/powershell"} + return req, nil +} + +// getStreamingContentHandleResponse handles the GetStreamingContent response. +func (client *ConfigurationsClient) getStreamingContentHandleResponse(resp *http.Response) (ConfigurationsClientGetStreamingContentResponse, error) { + result := ConfigurationsClientGetStreamingContentResponse{Body: resp.Body} + if val := resp.Header.Get("Content-Type"); val != "" { + result.ContentType = &val + } + return result, nil +} + +// GetTextContent - Get the content of the configuration in text form. Returns a literal content-type response header that +// gets omitted from the response envelope. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - configurationName - The configuration name. +// - options - ConfigurationsClientGetTextContentOptions contains the optional parameters for the ConfigurationsClient.GetTextContent +// method. +func (client *ConfigurationsClient) GetTextContent(ctx context.Context, resourceGroupName string, configurationName string, options *ConfigurationsClientGetTextContentOptions) (ConfigurationsClientGetTextContentResponse, error) { + var err error + const operationName = "ConfigurationsClient.GetTextContent" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getTextContentCreateRequest(ctx, resourceGroupName, configurationName, options) + if err != nil { + return ConfigurationsClientGetTextContentResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ConfigurationsClientGetTextContentResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ConfigurationsClientGetTextContentResponse{}, err + } + resp, err := client.getTextContentHandleResponse(httpResp) + return resp, err +} + +// getTextContentCreateRequest creates the GetTextContent request. +func (client *ConfigurationsClient) getTextContentCreateRequest(ctx context.Context, resourceGroupName string, configurationName string, _ *ConfigurationsClientGetTextContentOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Test/configurations/{configurationName}/textContent" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if configurationName == "" { + return nil, errors.New("parameter configurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{configurationName}", url.PathEscape(configurationName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"text/plain"} + return req, nil +} + +// getTextContentHandleResponse handles the GetTextContent response. +func (client *ConfigurationsClient) getTextContentHandleResponse(resp *http.Response) (ConfigurationsClientGetTextContentResponse, error) { + result := ConfigurationsClientGetTextContentResponse{} + body, err := runtime.Payload(resp) + if err != nil { + return ConfigurationsClientGetTextContentResponse{}, err + } + txt := string(body) + result.Value = &txt + return result, nil +} + +// PutStreamingContent - Put the content of the configuration identified by configuration name. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - configurationName - The configuration name. +// - options - ConfigurationsClientPutStreamingContentOptions contains the optional parameters for the ConfigurationsClient.PutStreamingContent +// method. +func (client *ConfigurationsClient) PutStreamingContent(ctx context.Context, resourceGroupName string, configurationName string, body io.ReadSeekCloser, options *ConfigurationsClientPutStreamingContentOptions) (ConfigurationsClientPutStreamingContentResponse, error) { + var err error + const operationName = "ConfigurationsClient.PutStreamingContent" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putStreamingContentCreateRequest(ctx, resourceGroupName, configurationName, body, options) + if err != nil { + return ConfigurationsClientPutStreamingContentResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ConfigurationsClientPutStreamingContentResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ConfigurationsClientPutStreamingContentResponse{}, err + } + return ConfigurationsClientPutStreamingContentResponse{}, nil +} + +// putStreamingContentCreateRequest creates the PutStreamingContent request. +func (client *ConfigurationsClient) putStreamingContentCreateRequest(ctx context.Context, resourceGroupName string, configurationName string, body io.ReadSeekCloser, _ *ConfigurationsClientPutStreamingContentOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Test/configurations/{configurationName}/putContent" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if configurationName == "" { + return nil, errors.New("parameter configurationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{configurationName}", url.PathEscape(configurationName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Content-Type"] = []string{"application/octet-stream"} + if err := req.SetBody(body, "application/octet-stream"); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armtest/zz_constants.go b/test/local/armtest/zz_constants.go new file mode 100644 index 000000000000..a75421bd745f --- /dev/null +++ b/test/local/armtest/zz_constants.go @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armtest + +const ( + version20250101 string = "2025-01-01" +) + +// CreatedByType - The kind of entity that created the resource. +type CreatedByType string + +const ( + // CreatedByTypeApplication - The entity was created by an application. + CreatedByTypeApplication CreatedByType = "Application" + // CreatedByTypeKey - The entity was created by a key. + CreatedByTypeKey CreatedByType = "Key" + // CreatedByTypeManagedIdentity - The entity was created by a managed identity. + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + // CreatedByTypeUser - The entity was created by a user. + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// PetKind - The kind of the pet. +type PetKind string + +const ( + // PetKindCat - A cat. + PetKindCat PetKind = "Cat" + // PetKindDog - A dog. + PetKindDog PetKind = "Dog" +) + +// PossiblePetKindValues returns the possible values for the PetKind const type. +func PossiblePetKindValues() []PetKind { + return []PetKind{ + PetKindCat, + PetKindDog, + } +} + +// ProvisioningState - The status of the current operation. +type ProvisioningState string + +const ( + // ProvisioningStateAccepted - Resource creation started. + ProvisioningStateAccepted ProvisioningState = "Accepted" + // ProvisioningStateCanceled - Resource creation was canceled. + ProvisioningStateCanceled ProvisioningState = "Canceled" + // ProvisioningStateDeleting - Deletion in progress. + ProvisioningStateDeleting ProvisioningState = "Deleting" + // ProvisioningStateFailed - Resource creation failed. + ProvisioningStateFailed ProvisioningState = "Failed" + // ProvisioningStateSucceeded - Resource has been created. + ProvisioningStateSucceeded ProvisioningState = "Succeeded" + // ProvisioningStateUpdating - Updating in progress. + ProvisioningStateUpdating ProvisioningState = "Updating" +) + +// PossibleProvisioningStateValues returns the possible values for the ProvisioningState const type. +func PossibleProvisioningStateValues() []ProvisioningState { + return []ProvisioningState{ + ProvisioningStateAccepted, + ProvisioningStateCanceled, + ProvisioningStateDeleting, + ProvisioningStateFailed, + ProvisioningStateSucceeded, + ProvisioningStateUpdating, + } +} diff --git a/test/local/armtest/zz_interfaces.go b/test/local/armtest/zz_interfaces.go new file mode 100644 index 000000000000..6e8256f64aad --- /dev/null +++ b/test/local/armtest/zz_interfaces.go @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armtest + +// PetClassification provides polymorphic access to related types. +// Call the interface's GetPet() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *Cat, *Dog, *Pet +type PetClassification interface { + // GetPet returns the Pet content of the underlying type. + GetPet() *Pet +} diff --git a/test/local/armtest/zz_lro_client.go b/test/local/armtest/zz_lro_client.go new file mode 100644 index 000000000000..bad55efb2c08 --- /dev/null +++ b/test/local/armtest/zz_lro_client.go @@ -0,0 +1,195 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armtest + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// LROClient contains the methods for the LRO group. +// Don't use this type directly, use NewLROClient() instead. +// +// Generated from API version 2025-01-01 +type LROClient struct { + internal *arm.Client + subscriptionID string +} + +// NewLROClient creates a new instance of LROClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewLROClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*LROClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &LROClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// BeginOkResponseWithAsyncHeader - A sample LRO with Azure-AsyncOperation header in 200 response +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - lroModelName - LRO model resource name. +// - resource - Resource create parameters. +// - options - LROClientBeginOkResponseWithAsyncHeaderOptions contains the optional parameters for the LROClient.BeginOkResponseWithAsyncHeader +// method. +func (client *LROClient) BeginOkResponseWithAsyncHeader(ctx context.Context, resourceGroupName string, lroModelName string, resource LROModel, options *LROClientBeginOkResponseWithAsyncHeaderOptions) (*runtime.Poller[LROClientOkResponseWithAsyncHeaderResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.okResponseWithAsyncHeader(ctx, resourceGroupName, lroModelName, resource, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[LROClientOkResponseWithAsyncHeaderResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[LROClientOkResponseWithAsyncHeaderResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// OkResponseWithAsyncHeader - A sample LRO with Azure-AsyncOperation header in 200 response +// If the operation fails it returns an *azcore.ResponseError type. +func (client *LROClient) okResponseWithAsyncHeader(ctx context.Context, resourceGroupName string, lroModelName string, resource LROModel, options *LROClientBeginOkResponseWithAsyncHeaderOptions) (*http.Response, error) { + var err error + const operationName = "LROClient.BeginOkResponseWithAsyncHeader" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.okResponseWithAsyncHeaderCreateRequest(ctx, resourceGroupName, lroModelName, resource, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// okResponseWithAsyncHeaderCreateRequest creates the OkResponseWithAsyncHeader request. +func (client *LROClient) okResponseWithAsyncHeaderCreateRequest(ctx context.Context, resourceGroupName string, lroModelName string, resource LROModel, _ *LROClientBeginOkResponseWithAsyncHeaderOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Test/LROModels/{LROModelName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if lroModelName == "" { + return nil, errors.New("parameter lroModelName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{LROModelName}", url.PathEscape(lroModelName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, resource); err != nil { + return nil, err + } + return req, nil +} + +// BeginScalarResult - An LRO action that returns a scalar string result +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - lroModelName - LRO model resource name. +// - body - The content of the action request +// - options - LROClientBeginScalarResultOptions contains the optional parameters for the LROClient.BeginScalarResult method. +func (client *LROClient) BeginScalarResult(ctx context.Context, resourceGroupName string, lroModelName string, body ActionRequest, options *LROClientBeginScalarResultOptions) (*runtime.Poller[LROClientScalarResultResponse], error) { + if options == nil || options.ResumeToken == "" { + resp, err := client.scalarResult(ctx, resourceGroupName, lroModelName, body, options) + if err != nil { + return nil, err + } + poller, err := runtime.NewPoller(resp, client.internal.Pipeline(), &runtime.NewPollerOptions[LROClientScalarResultResponse]{ + Tracer: client.internal.Tracer(), + }) + return poller, err + } else { + return runtime.NewPollerFromResumeToken(options.ResumeToken, client.internal.Pipeline(), &runtime.NewPollerFromResumeTokenOptions[LROClientScalarResultResponse]{ + Tracer: client.internal.Tracer(), + }) + } +} + +// ScalarResult - An LRO action that returns a scalar string result +// If the operation fails it returns an *azcore.ResponseError type. +func (client *LROClient) scalarResult(ctx context.Context, resourceGroupName string, lroModelName string, body ActionRequest, options *LROClientBeginScalarResultOptions) (*http.Response, error) { + var err error + const operationName = "LROClient.BeginScalarResult" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.scalarResultCreateRequest(ctx, resourceGroupName, lroModelName, body, options) + if err != nil { + return nil, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return nil, err + } + return httpResp, nil +} + +// scalarResultCreateRequest creates the ScalarResult request. +func (client *LROClient) scalarResultCreateRequest(ctx context.Context, resourceGroupName string, lroModelName string, body ActionRequest, _ *LROClientBeginScalarResultOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Test/LROModels/{LROModelName}/scalarResult" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if lroModelName == "" { + return nil, errors.New("parameter lroModelName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{LROModelName}", url.PathEscape(lroModelName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"text/plain"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/armtest/zz_mixedscopewidgets_client.go b/test/local/armtest/zz_mixedscopewidgets_client.go new file mode 100644 index 000000000000..e124793694da --- /dev/null +++ b/test/local/armtest/zz_mixedscopewidgets_client.go @@ -0,0 +1,206 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armtest + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// MixedScopeWidgetsClient contains the methods for the MixedScopeWidgets group. +// Don't use this type directly, use NewMixedScopeWidgetsClient() instead. +// +// Generated from API version 2025-01-01 +type MixedScopeWidgetsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewMixedScopeWidgetsClient creates a new instance of MixedScopeWidgetsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewMixedScopeWidgetsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*MixedScopeWidgetsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &MixedScopeWidgetsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// Get - Get a widget at resource group level (uses subscriptionId). +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - widgetName - Widget name. +// - options - MixedScopeWidgetsClientGetOptions contains the optional parameters for the MixedScopeWidgetsClient.Get method. +func (client *MixedScopeWidgetsClient) Get(ctx context.Context, resourceGroupName string, widgetName string, options *MixedScopeWidgetsClientGetOptions) (MixedScopeWidgetsClientGetResponse, error) { + var err error + const operationName = "MixedScopeWidgetsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, widgetName, options) + if err != nil { + return MixedScopeWidgetsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return MixedScopeWidgetsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return MixedScopeWidgetsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *MixedScopeWidgetsClient) getCreateRequest(ctx context.Context, resourceGroupName string, widgetName string, _ *MixedScopeWidgetsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Test/mixedScopeWidgets/{widgetName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if widgetName == "" { + return nil, errors.New("parameter widgetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{widgetName}", url.PathEscape(widgetName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *MixedScopeWidgetsClient) getHandleResponse(resp *http.Response) (MixedScopeWidgetsClientGetResponse, error) { + result := MixedScopeWidgetsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.MixedScopeWidget); err != nil { + return MixedScopeWidgetsClientGetResponse{}, err + } + return result, nil +} + +// NewListAllPager - List all widgets at tenant level (no subscriptionId). +// - options - MixedScopeWidgetsClientListAllOptions contains the optional parameters for the MixedScopeWidgetsClient.NewListAllPager +// method. +func (client *MixedScopeWidgetsClient) NewListAllPager(options *MixedScopeWidgetsClientListAllOptions) *runtime.Pager[MixedScopeWidgetsClientListAllResponse] { + return runtime.NewPager(runtime.PagingHandler[MixedScopeWidgetsClientListAllResponse]{ + More: func(page MixedScopeWidgetsClientListAllResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *MixedScopeWidgetsClientListAllResponse) (MixedScopeWidgetsClientListAllResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "MixedScopeWidgetsClient.NewListAllPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listAllCreateRequest(ctx, options) + }, nil) + if err != nil { + return MixedScopeWidgetsClientListAllResponse{}, err + } + return client.listAllHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listAllCreateRequest creates the ListAll request. +func (client *MixedScopeWidgetsClient) listAllCreateRequest(ctx context.Context, _ *MixedScopeWidgetsClientListAllOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Test/mixedScopeWidgets" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listAllHandleResponse handles the ListAll response. +func (client *MixedScopeWidgetsClient) listAllHandleResponse(resp *http.Response) (MixedScopeWidgetsClientListAllResponse, error) { + result := MixedScopeWidgetsClientListAllResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.MixedScopeWidgetListResult); err != nil { + return MixedScopeWidgetsClientListAllResponse{}, err + } + return result, nil +} + +// NewListBySubscriptionPager - List widgets by subscription (uses subscriptionId). +// - options - MixedScopeWidgetsClientListBySubscriptionOptions contains the optional parameters for the MixedScopeWidgetsClient.NewListBySubscriptionPager +// method. +func (client *MixedScopeWidgetsClient) NewListBySubscriptionPager(options *MixedScopeWidgetsClientListBySubscriptionOptions) *runtime.Pager[MixedScopeWidgetsClientListBySubscriptionResponse] { + return runtime.NewPager(runtime.PagingHandler[MixedScopeWidgetsClientListBySubscriptionResponse]{ + More: func(page MixedScopeWidgetsClientListBySubscriptionResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *MixedScopeWidgetsClientListBySubscriptionResponse) (MixedScopeWidgetsClientListBySubscriptionResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "MixedScopeWidgetsClient.NewListBySubscriptionPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, nil) + if err != nil { + return MixedScopeWidgetsClientListBySubscriptionResponse{}, err + } + return client.listBySubscriptionHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *MixedScopeWidgetsClient) listBySubscriptionCreateRequest(ctx context.Context, _ *MixedScopeWidgetsClientListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Test/mixedScopeWidgets" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *MixedScopeWidgetsClient) listBySubscriptionHandleResponse(resp *http.Response) (MixedScopeWidgetsClientListBySubscriptionResponse, error) { + result := MixedScopeWidgetsClientListBySubscriptionResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.MixedScopeWidgetListResult); err != nil { + return MixedScopeWidgetsClientListBySubscriptionResponse{}, err + } + return result, nil +} diff --git a/test/local/armtest/zz_models.go b/test/local/armtest/zz_models.go new file mode 100644 index 000000000000..e530cb28fb44 --- /dev/null +++ b/test/local/armtest/zz_models.go @@ -0,0 +1,397 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armtest + +import "time" + +type ActionParameterBody struct { + // REQUIRED + Action *ActionRequest +} + +// ActionRequest - The request of the action. +type ActionRequest struct { + // REQUIRED; The prop of the action. + Prop *string +} + +// AuthorizationProperties - Properties of an authorization. +type AuthorizationProperties struct { + // The description. + Description *string + + // READ-ONLY; The provisioning state. + ProvisioningState *ProvisioningState +} + +// AuthorizationResource - A tenant-level authorization resource. +type AuthorizationResource struct { + // The resource-specific properties for this resource. + Properties *AuthorizationProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// AuthorizationServerProperties - Properties of an authorization server. +type AuthorizationServerProperties struct { + // The description. + Description *string + + // READ-ONLY; The provisioning state. + ProvisioningState *ProvisioningState +} + +// AuthorizationServerResource - A tenant-level authorization server resource. +type AuthorizationServerResource struct { + // The resource-specific properties for this resource. + Properties *AuthorizationServerProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// AvailabilityProperties - Properties of the availability resource. +type AvailabilityProperties struct { + // Indicates if the resource is in preview. + IsPreview *bool + + // FLAG; CONSTANT; The availability status code. + // Field has constant value 1, any specified value is ignored. + Status *int32 +} + +// BodyRoot - Body root resource. +type BodyRoot struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *BodyRootProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// BodyRootProperties - Properties of the trusted signing account. +type BodyRootProperties struct { + // The availability property. + Availability *AvailabilityProperties + + // The URI of the trusted signing account which is used during signing files. + Description *string + + // The value property. + Value any + + // READ-ONLY; Status of the current operation on trusted signing account. + ProvisioningState *ProvisioningState +} + +// Cat - A cat. +type Cat struct { + // CONSTANT; The kind of the pet. + // Field has constant value PetKindCat, any specified value is ignored. + Kind *PetKind + + // REQUIRED; The name of the pet. + Name *string + + // REQUIRED; Whether the cat purrs. + Purrs *bool +} + +// GetPet implements the PetClassification interface for type Cat. +func (c *Cat) GetPet() *Pet { + return &Pet{ + Kind: c.Kind, + Name: c.Name, + } +} + +// Configuration resource. +type Configuration struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *ConfigurationProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// ConfigurationProperties - Properties of the configuration resource. +type ConfigurationProperties struct { + // Description of the configuration. + Description *string + + // READ-ONLY; Status of the current operation on configuration. + ProvisioningState *ProvisioningState +} + +// Dog - A dog. +type Dog struct { + // REQUIRED; The breed of the dog. + Breed *string + + // CONSTANT; The kind of the pet. + // Field has constant value PetKindDog, any specified value is ignored. + Kind *PetKind + + // REQUIRED; The name of the pet. + Name *string +} + +// GetPet implements the PetClassification interface for type Dog. +func (d *Dog) GetPet() *Pet { + return &Pet{ + Kind: d.Kind, + Name: d.Name, + } +} + +// LROModel - LRO model resource. +type LROModel struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *BodyRootProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// MixedScopeWidget - A mixed scope resource that has operations at both subscription and tenant level. +type MixedScopeWidget struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *MixedScopeWidgetProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// MixedScopeWidgetListResult - The response of a MixedScopeWidget list operation. +type MixedScopeWidgetListResult struct { + // REQUIRED; The MixedScopeWidget items on this page + Value []*MixedScopeWidget + + // The link to the next page of items + NextLink *string +} + +// MixedScopeWidgetProperties - Properties of a mixed scope widget. +type MixedScopeWidgetProperties struct { + // The description. + Description *string + + // READ-ONLY; The status. + ProvisioningState *ProvisioningState +} + +// Pet - Base pet model. +type Pet struct { + // REQUIRED; The kind of the pet. + Kind *PetKind + + // REQUIRED; The name of the pet. + Name *string +} + +// GetPet implements the PetClassification interface for type Pet. +func (p *Pet) GetPet() *Pet { return p } + +// PetResource - Pet resource. +type PetResource struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *PetResourceProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// PetResourceProperties - Properties of the pet resource. +type PetResourceProperties struct { + // READ-ONLY; Status of the current operation. + ProvisioningState *ProvisioningState +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time + + // The identity that created the resource. + CreatedBy *string + + // The type of identity that created the resource. + CreatedByType *CreatedByType + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time + + // The identity that last modified the resource. + LastModifiedBy *string + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType +} + +// TenantItem - A tenant-level resource. +type TenantItem struct { + // The resource-specific properties for this resource. + Properties *TenantItemProperties + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// TenantItemListResult - The response of a TenantItem list operation. +type TenantItemListResult struct { + // REQUIRED; The TenantItem items on this page + Value []*TenantItem + + // The link to the next page of items + NextLink *string +} + +// TenantItemProperties - Properties of a tenant item. +type TenantItemProperties struct { + // The description. + Description *string + + // READ-ONLY; The status. + ProvisioningState *ProvisioningState +} + +// Widget resource for testing parameter groups +type Widget struct { + // REQUIRED; The geo-location where the resource lives + Location *string + + // The resource-specific properties for this resource. + Properties *WidgetProperties + + // Resource tags. + Tags map[string]*string + + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string + + // READ-ONLY; The name of the resource + Name *string + + // READ-ONLY; Azure Resource Manager metadata containing createdBy and modifiedBy information. + SystemData *SystemData + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string +} + +// WidgetProperties - Properties of the widget resource. +type WidgetProperties struct { + // The description of the widget. + Description *string + + // The name of the widget. + Name *string + + // READ-ONLY; Status of the current operation on widget. + ProvisioningState *ProvisioningState +} diff --git a/test/local/armtest/zz_models_serde.go b/test/local/armtest/zz_models_serde.go new file mode 100644 index 000000000000..92bd39da2da5 --- /dev/null +++ b/test/local/armtest/zz_models_serde.go @@ -0,0 +1,1060 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armtest + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type ActionParameterBody. +func (a ActionParameterBody) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "action", a.Action) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ActionParameterBody. +func (a *ActionParameterBody) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "action": + err = unpopulate(val, "Action", &a.Action) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ActionRequest. +func (a ActionRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "prop", a.Prop) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ActionRequest. +func (a *ActionRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "prop": + err = unpopulate(val, "Prop", &a.Prop) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AuthorizationProperties. +func (a AuthorizationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", a.Description) + populate(objectMap, "provisioningState", a.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AuthorizationProperties. +func (a *AuthorizationProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &a.Description) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AuthorizationResource. +func (a AuthorizationResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AuthorizationResource. +func (a *AuthorizationResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &a.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AuthorizationServerProperties. +func (a AuthorizationServerProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", a.Description) + populate(objectMap, "provisioningState", a.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AuthorizationServerProperties. +func (a *AuthorizationServerProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &a.Description) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &a.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AuthorizationServerResource. +func (a AuthorizationServerResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", a.ID) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AuthorizationServerResource. +func (a *AuthorizationServerResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &a.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &a.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &a.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &a.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &a.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type AvailabilityProperties. +func (a AvailabilityProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "isPreview", a.IsPreview) + if a.Status != nil { + objectMap["status"] = int32(1) + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AvailabilityProperties. +func (a *AvailabilityProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "isPreview": + err = unpopulate(val, "IsPreview", &a.IsPreview) + delete(rawMsg, key) + case "status": + err = unpopulate(val, "Status", &a.Status) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", a, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BodyRoot. +func (b BodyRoot) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", b.ID) + populate(objectMap, "location", b.Location) + populate(objectMap, "name", b.Name) + populate(objectMap, "properties", b.Properties) + populate(objectMap, "systemData", b.SystemData) + populate(objectMap, "tags", b.Tags) + populate(objectMap, "type", b.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BodyRoot. +func (b *BodyRoot) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &b.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &b.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &b.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &b.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &b.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &b.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &b.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type BodyRootProperties. +func (b BodyRootProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "availability", b.Availability) + populate(objectMap, "description", b.Description) + populate(objectMap, "provisioningState", b.ProvisioningState) + populateAny(objectMap, "value", b.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BodyRootProperties. +func (b *BodyRootProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "availability": + err = unpopulate(val, "Availability", &b.Availability) + delete(rawMsg, key) + case "description": + err = unpopulate(val, "Description", &b.Description) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &b.ProvisioningState) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &b.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Cat. +func (c Cat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + objectMap["kind"] = PetKindCat + populate(objectMap, "name", c.Name) + populate(objectMap, "purrs", c.Purrs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Cat. +func (c *Cat) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &c.Kind) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "purrs": + err = unpopulate(val, "Purrs", &c.Purrs) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Configuration. +func (c Configuration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", c.ID) + populate(objectMap, "location", c.Location) + populate(objectMap, "name", c.Name) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "systemData", c.SystemData) + populate(objectMap, "tags", c.Tags) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Configuration. +func (c *Configuration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &c.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &c.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &c.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &c.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &c.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &c.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &c.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ConfigurationProperties. +func (c ConfigurationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", c.Description) + populate(objectMap, "provisioningState", c.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ConfigurationProperties. +func (c *ConfigurationProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &c.Description) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &c.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Dog. +func (d Dog) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "breed", d.Breed) + objectMap["kind"] = PetKindDog + populate(objectMap, "name", d.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Dog. +func (d *Dog) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "breed": + err = unpopulate(val, "Breed", &d.Breed) + delete(rawMsg, key) + case "kind": + err = unpopulate(val, "Kind", &d.Kind) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LROModel. +func (l LROModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", l.ID) + populate(objectMap, "location", l.Location) + populate(objectMap, "name", l.Name) + populate(objectMap, "properties", l.Properties) + populate(objectMap, "systemData", l.SystemData) + populate(objectMap, "tags", l.Tags) + populate(objectMap, "type", l.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LROModel. +func (l *LROModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &l.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &l.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &l.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &l.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &l.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &l.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &l.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MixedScopeWidget. +func (m MixedScopeWidget) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", m.ID) + populate(objectMap, "location", m.Location) + populate(objectMap, "name", m.Name) + populate(objectMap, "properties", m.Properties) + populate(objectMap, "systemData", m.SystemData) + populate(objectMap, "tags", m.Tags) + populate(objectMap, "type", m.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MixedScopeWidget. +func (m *MixedScopeWidget) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &m.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &m.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &m.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &m.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &m.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &m.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &m.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MixedScopeWidgetListResult. +func (m MixedScopeWidgetListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", m.NextLink) + populate(objectMap, "value", m.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MixedScopeWidgetListResult. +func (m *MixedScopeWidgetListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &m.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &m.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type MixedScopeWidgetProperties. +func (m MixedScopeWidgetProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", m.Description) + populate(objectMap, "provisioningState", m.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MixedScopeWidgetProperties. +func (m *MixedScopeWidgetProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &m.Description) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &m.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", m, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Pet. +func (p Pet) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "kind", p.Kind) + populate(objectMap, "name", p.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Pet. +func (p *Pet) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "kind": + err = unpopulate(val, "Kind", &p.Kind) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PetResource. +func (p PetResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", p.ID) + populate(objectMap, "location", p.Location) + populate(objectMap, "name", p.Name) + populate(objectMap, "properties", p.Properties) + populate(objectMap, "systemData", p.SystemData) + populate(objectMap, "tags", p.Tags) + populate(objectMap, "type", p.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PetResource. +func (p *PetResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &p.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &p.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &p.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &p.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &p.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &p.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PetResourceProperties. +func (p PetResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "provisioningState", p.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PetResourceProperties. +func (p *PetResourceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &p.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.RFC3339](objectMap, "createdAt", s.CreatedAt) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populateTime[datetime.RFC3339](objectMap, "lastModifiedAt", s.LastModifiedAt) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + err = unpopulateTime[datetime.RFC3339](val, "CreatedAt", &s.CreatedAt) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, "CreatedBy", &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, "CreatedByType", &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + err = unpopulateTime[datetime.RFC3339](val, "LastModifiedAt", &s.LastModifiedAt) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TenantItem. +func (t TenantItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", t.ID) + populate(objectMap, "name", t.Name) + populate(objectMap, "properties", t.Properties) + populate(objectMap, "systemData", t.SystemData) + populate(objectMap, "type", t.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TenantItem. +func (t *TenantItem) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &t.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &t.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &t.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &t.SystemData) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &t.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TenantItemListResult. +func (t TenantItemListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", t.NextLink) + populate(objectMap, "value", t.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TenantItemListResult. +func (t *TenantItemListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &t.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &t.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type TenantItemProperties. +func (t TenantItemProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", t.Description) + populate(objectMap, "provisioningState", t.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TenantItemProperties. +func (t *TenantItemProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &t.Description) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &t.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", t, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Widget. +func (w Widget) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", w.ID) + populate(objectMap, "location", w.Location) + populate(objectMap, "name", w.Name) + populate(objectMap, "properties", w.Properties) + populate(objectMap, "systemData", w.SystemData) + populate(objectMap, "tags", w.Tags) + populate(objectMap, "type", w.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Widget. +func (w *Widget) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &w.ID) + delete(rawMsg, key) + case "location": + err = unpopulate(val, "Location", &w.Location) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &w.Name) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, "Properties", &w.Properties) + delete(rawMsg, key) + case "systemData": + err = unpopulate(val, "SystemData", &w.SystemData) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &w.Tags) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &w.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type WidgetProperties. +func (w WidgetProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "description", w.Description) + populate(objectMap, "name", w.Name) + populate(objectMap, "provisioningState", w.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WidgetProperties. +func (w *WidgetProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "description": + err = unpopulate(val, "Description", &w.Description) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &w.Name) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, "ProvisioningState", &w.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func populateAny(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/local/armtest/zz_options.go b/test/local/armtest/zz_options.go new file mode 100644 index 000000000000..1204a1b706b3 --- /dev/null +++ b/test/local/armtest/zz_options.go @@ -0,0 +1,148 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armtest + +// AuthorizationClientGetOptions contains the optional parameters for the AuthorizationClient.Get method. +type AuthorizationClientGetOptions struct { + // placeholder for future optional parameters +} + +// AuthorizationServerClientGetOptions contains the optional parameters for the AuthorizationServerClient.Get method. +type AuthorizationServerClientGetOptions struct { + // placeholder for future optional parameters +} + +// BodyRootsClientActionOptions contains the optional parameters for the BodyRootsClient.Action method. +type BodyRootsClientActionOptions struct { + // placeholder for future optional parameters +} + +// BodyRootsClientGetOptions contains the optional parameters for the BodyRootsClient.Get method. +type BodyRootsClientGetOptions struct { + // placeholder for future optional parameters +} + +// BodyRootsClientPutOptions contains the optional parameters for the BodyRootsClient.Put method. +type BodyRootsClientPutOptions struct { + // placeholder for future optional parameters +} + +// ConfigurationsClientGetContentOptions contains the optional parameters for the ConfigurationsClient.GetContent method. +type ConfigurationsClientGetContentOptions struct { + // placeholder for future optional parameters +} + +// ConfigurationsClientGetStreamingContentOptions contains the optional parameters for the ConfigurationsClient.GetStreamingContent +// method. +type ConfigurationsClientGetStreamingContentOptions struct { + // placeholder for future optional parameters +} + +// ConfigurationsClientGetTextContentOptions contains the optional parameters for the ConfigurationsClient.GetTextContent +// method. +type ConfigurationsClientGetTextContentOptions struct { + // placeholder for future optional parameters +} + +// ConfigurationsClientPutStreamingContentOptions contains the optional parameters for the ConfigurationsClient.PutStreamingContent +// method. +type ConfigurationsClientPutStreamingContentOptions struct { + // placeholder for future optional parameters +} + +// LROClientBeginOkResponseWithAsyncHeaderOptions contains the optional parameters for the LROClient.BeginOkResponseWithAsyncHeader +// method. +type LROClientBeginOkResponseWithAsyncHeaderOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// LROClientBeginScalarResultOptions contains the optional parameters for the LROClient.BeginScalarResult method. +type LROClientBeginScalarResultOptions struct { + // Resumes the long-running operation from the provided token. + ResumeToken string +} + +// Request options for test operations +type ManagementRequestOptions struct { + // Client request ID for tracking + ClientRequestID string +} + +// MixedScopeWidgetsClientGetOptions contains the optional parameters for the MixedScopeWidgetsClient.Get method. +type MixedScopeWidgetsClientGetOptions struct { + // placeholder for future optional parameters +} + +// MixedScopeWidgetsClientListAllOptions contains the optional parameters for the MixedScopeWidgetsClient.NewListAllPager +// method. +type MixedScopeWidgetsClientListAllOptions struct { + // placeholder for future optional parameters +} + +// MixedScopeWidgetsClientListBySubscriptionOptions contains the optional parameters for the MixedScopeWidgetsClient.NewListBySubscriptionPager +// method. +type MixedScopeWidgetsClientListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// ParameterGroupOperationsClientNoParameterGroupOptions contains the optional parameters for the ParameterGroupOperationsClient.NoParameterGroup +// method. +type ParameterGroupOperationsClientNoParameterGroupOptions struct { + // Optional correlation ID + CorrelationID *string +} + +// ParameterGroupOperationsClientQueryParameterGroupOptions contains the optional parameters for the ParameterGroupOperationsClient.QueryParameterGroup +// method. +type ParameterGroupOperationsClientQueryParameterGroupOptions struct { + // Optional max count + MaxCount *int32 +} + +// ParameterGroupOperationsClientSharedParameterGroup1Options contains the optional parameters for the ParameterGroupOperationsClient.SharedParameterGroup1 +// method. +type ParameterGroupOperationsClientSharedParameterGroup1Options struct { + // Optional correlation ID + CorrelationID *string +} + +// ParameterGroupOperationsClientSharedParameterGroup2Options contains the optional parameters for the ParameterGroupOperationsClient.SharedParameterGroup2 +// method. +type ParameterGroupOperationsClientSharedParameterGroup2Options struct { + // Optional correlation ID + CorrelationID *string +} + +// PetsClientAdoptCatOptions contains the optional parameters for the PetsClient.AdoptCat method. +type PetsClientAdoptCatOptions struct { + // placeholder for future optional parameters +} + +// PetsClientAdoptPetOptions contains the optional parameters for the PetsClient.AdoptPet method. +type PetsClientAdoptPetOptions struct { + // placeholder for future optional parameters +} + +// PetsClientGetOptions contains the optional parameters for the PetsClient.Get method. +type PetsClientGetOptions struct { + // placeholder for future optional parameters +} + +// Query parameter group with a required field +type QueryParams struct { + // The filter name + FilterName string +} + +// TenantItemsClientGetOptions contains the optional parameters for the TenantItemsClient.Get method. +type TenantItemsClientGetOptions struct { + // placeholder for future optional parameters +} + +// TenantItemsClientListOptions contains the optional parameters for the TenantItemsClient.NewListPager method. +type TenantItemsClientListOptions struct { + // placeholder for future optional parameters +} diff --git a/test/local/armtest/zz_parametergroupoperations_client.go b/test/local/armtest/zz_parametergroupoperations_client.go new file mode 100644 index 000000000000..a9bba5ec911c --- /dev/null +++ b/test/local/armtest/zz_parametergroupoperations_client.go @@ -0,0 +1,313 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armtest + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" +) + +// ParameterGroupOperationsClient contains the methods for the ParameterGroupOperations group. +// Don't use this type directly, use NewParameterGroupOperationsClient() instead. +// +// Generated from API version 2025-01-01 +type ParameterGroupOperationsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewParameterGroupOperationsClient creates a new instance of ParameterGroupOperationsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewParameterGroupOperationsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*ParameterGroupOperationsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &ParameterGroupOperationsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// NoParameterGroup - This operation should not emit parameter group since all parameters are optional +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - widgetName - The name of the widget +// - options - ParameterGroupOperationsClientNoParameterGroupOptions contains the optional parameters for the ParameterGroupOperationsClient.NoParameterGroup +// method. +func (client *ParameterGroupOperationsClient) NoParameterGroup(ctx context.Context, resourceGroupName string, widgetName string, options *ParameterGroupOperationsClientNoParameterGroupOptions) (ParameterGroupOperationsClientNoParameterGroupResponse, error) { + var err error + const operationName = "ParameterGroupOperationsClient.NoParameterGroup" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.noParameterGroupCreateRequest(ctx, resourceGroupName, widgetName, options) + if err != nil { + return ParameterGroupOperationsClientNoParameterGroupResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ParameterGroupOperationsClientNoParameterGroupResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ParameterGroupOperationsClientNoParameterGroupResponse{}, err + } + resp, err := client.noParameterGroupHandleResponse(httpResp) + return resp, err +} + +// noParameterGroupCreateRequest creates the NoParameterGroup request. +func (client *ParameterGroupOperationsClient) noParameterGroupCreateRequest(ctx context.Context, resourceGroupName string, widgetName string, options *ParameterGroupOperationsClientNoParameterGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Test/widgets/{widgetName}/noParameterGroup" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if widgetName == "" { + return nil, errors.New("parameter widgetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{widgetName}", url.PathEscape(widgetName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + if options != nil && options.CorrelationID != nil { + req.Raw().Header["x-ms-correlation-id"] = []string{*options.CorrelationID} + } + return req, nil +} + +// noParameterGroupHandleResponse handles the NoParameterGroup response. +func (client *ParameterGroupOperationsClient) noParameterGroupHandleResponse(resp *http.Response) (ParameterGroupOperationsClientNoParameterGroupResponse, error) { + result := ParameterGroupOperationsClientNoParameterGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Widget); err != nil { + return ParameterGroupOperationsClientNoParameterGroupResponse{}, err + } + return result, nil +} + +// QueryParameterGroup - This operation uses a required query parameter group +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - widgetName - The name of the widget +// - params - Query parameter group with a required field +// - options - ParameterGroupOperationsClientQueryParameterGroupOptions contains the optional parameters for the ParameterGroupOperationsClient.QueryParameterGroup +// method. +func (client *ParameterGroupOperationsClient) QueryParameterGroup(ctx context.Context, resourceGroupName string, widgetName string, params QueryParams, options *ParameterGroupOperationsClientQueryParameterGroupOptions) (ParameterGroupOperationsClientQueryParameterGroupResponse, error) { + var err error + const operationName = "ParameterGroupOperationsClient.QueryParameterGroup" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.queryParameterGroupCreateRequest(ctx, resourceGroupName, widgetName, params, options) + if err != nil { + return ParameterGroupOperationsClientQueryParameterGroupResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ParameterGroupOperationsClientQueryParameterGroupResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ParameterGroupOperationsClientQueryParameterGroupResponse{}, err + } + resp, err := client.queryParameterGroupHandleResponse(httpResp) + return resp, err +} + +// queryParameterGroupCreateRequest creates the QueryParameterGroup request. +func (client *ParameterGroupOperationsClient) queryParameterGroupCreateRequest(ctx context.Context, resourceGroupName string, widgetName string, params QueryParams, options *ParameterGroupOperationsClientQueryParameterGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Test/widgets/{widgetName}/queryParameterGroup" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if widgetName == "" { + return nil, errors.New("parameter widgetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{widgetName}", url.PathEscape(widgetName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250101) + reqQP.Set("filterName", params.FilterName) + if options != nil && options.MaxCount != nil { + reqQP.Set("maxCount", strconv.FormatInt(int64(*options.MaxCount), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// queryParameterGroupHandleResponse handles the QueryParameterGroup response. +func (client *ParameterGroupOperationsClient) queryParameterGroupHandleResponse(resp *http.Response) (ParameterGroupOperationsClientQueryParameterGroupResponse, error) { + result := ParameterGroupOperationsClientQueryParameterGroupResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Widget); err != nil { + return ParameterGroupOperationsClientQueryParameterGroupResponse{}, err + } + return result, nil +} + +// SharedParameterGroup1 - This operation using parameter group +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - widgetName - The name of the widget +// - params - Request options for test operations +// - options - ParameterGroupOperationsClientSharedParameterGroup1Options contains the optional parameters for the ParameterGroupOperationsClient.SharedParameterGroup1 +// method. +func (client *ParameterGroupOperationsClient) SharedParameterGroup1(ctx context.Context, resourceGroupName string, widgetName string, params ManagementRequestOptions, options *ParameterGroupOperationsClientSharedParameterGroup1Options) (ParameterGroupOperationsClientSharedParameterGroup1Response, error) { + var err error + const operationName = "ParameterGroupOperationsClient.SharedParameterGroup1" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.sharedParameterGroup1CreateRequest(ctx, resourceGroupName, widgetName, params, options) + if err != nil { + return ParameterGroupOperationsClientSharedParameterGroup1Response{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ParameterGroupOperationsClientSharedParameterGroup1Response{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ParameterGroupOperationsClientSharedParameterGroup1Response{}, err + } + resp, err := client.sharedParameterGroup1HandleResponse(httpResp) + return resp, err +} + +// sharedParameterGroup1CreateRequest creates the SharedParameterGroup1 request. +func (client *ParameterGroupOperationsClient) sharedParameterGroup1CreateRequest(ctx context.Context, resourceGroupName string, widgetName string, params ManagementRequestOptions, options *ParameterGroupOperationsClientSharedParameterGroup1Options) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Test/widgets/{widgetName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if widgetName == "" { + return nil, errors.New("parameter widgetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{widgetName}", url.PathEscape(widgetName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["x-ms-client-request-id"] = []string{params.ClientRequestID} + if options != nil && options.CorrelationID != nil { + req.Raw().Header["x-ms-correlation-id"] = []string{*options.CorrelationID} + } + return req, nil +} + +// sharedParameterGroup1HandleResponse handles the SharedParameterGroup1 response. +func (client *ParameterGroupOperationsClient) sharedParameterGroup1HandleResponse(resp *http.Response) (ParameterGroupOperationsClientSharedParameterGroup1Response, error) { + result := ParameterGroupOperationsClientSharedParameterGroup1Response{} + if err := runtime.UnmarshalAsJSON(resp, &result.Widget); err != nil { + return ParameterGroupOperationsClientSharedParameterGroup1Response{}, err + } + return result, nil +} + +// SharedParameterGroup2 - This operation using the same parameter group - should reuse, not duplicate +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - widgetName - The name of the widget +// - params - Request options for test operations +// - options - ParameterGroupOperationsClientSharedParameterGroup2Options contains the optional parameters for the ParameterGroupOperationsClient.SharedParameterGroup2 +// method. +func (client *ParameterGroupOperationsClient) SharedParameterGroup2(ctx context.Context, resourceGroupName string, widgetName string, params ManagementRequestOptions, options *ParameterGroupOperationsClientSharedParameterGroup2Options) (ParameterGroupOperationsClientSharedParameterGroup2Response, error) { + var err error + const operationName = "ParameterGroupOperationsClient.SharedParameterGroup2" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.sharedParameterGroup2CreateRequest(ctx, resourceGroupName, widgetName, params, options) + if err != nil { + return ParameterGroupOperationsClientSharedParameterGroup2Response{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ParameterGroupOperationsClientSharedParameterGroup2Response{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ParameterGroupOperationsClientSharedParameterGroup2Response{}, err + } + resp, err := client.sharedParameterGroup2HandleResponse(httpResp) + return resp, err +} + +// sharedParameterGroup2CreateRequest creates the SharedParameterGroup2 request. +func (client *ParameterGroupOperationsClient) sharedParameterGroup2CreateRequest(ctx context.Context, resourceGroupName string, widgetName string, params ManagementRequestOptions, options *ParameterGroupOperationsClientSharedParameterGroup2Options) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Test/widgets/{widgetName}/sharedParameterGroup2" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if widgetName == "" { + return nil, errors.New("parameter widgetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{widgetName}", url.PathEscape(widgetName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["x-ms-client-request-id"] = []string{params.ClientRequestID} + if options != nil && options.CorrelationID != nil { + req.Raw().Header["x-ms-correlation-id"] = []string{*options.CorrelationID} + } + return req, nil +} + +// sharedParameterGroup2HandleResponse handles the SharedParameterGroup2 response. +func (client *ParameterGroupOperationsClient) sharedParameterGroup2HandleResponse(resp *http.Response) (ParameterGroupOperationsClientSharedParameterGroup2Response, error) { + result := ParameterGroupOperationsClientSharedParameterGroup2Response{} + if err := runtime.UnmarshalAsJSON(resp, &result.Widget); err != nil { + return ParameterGroupOperationsClientSharedParameterGroup2Response{}, err + } + return result, nil +} diff --git a/test/local/armtest/zz_pets_client.go b/test/local/armtest/zz_pets_client.go new file mode 100644 index 000000000000..6c95348102aa --- /dev/null +++ b/test/local/armtest/zz_pets_client.go @@ -0,0 +1,236 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armtest + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// PetsClient contains the methods for the Pets group. +// Don't use this type directly, use NewPetsClient() instead. +// +// Generated from API version 2025-01-01 +type PetsClient struct { + internal *arm.Client + subscriptionID string +} + +// NewPetsClient creates a new instance of PetsClient with the specified values. +// - subscriptionID - The ID of the target subscription. The value must be an UUID. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewPetsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*PetsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &PetsClient{ + subscriptionID: subscriptionID, + internal: cl, + } + return client, nil +} + +// AdoptCat - Adopt a pet using a concrete polymorphic model (Cat) as parameter. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - petResourceName - Pet resource name. +// - options - PetsClientAdoptCatOptions contains the optional parameters for the PetsClient.AdoptCat method. +func (client *PetsClient) AdoptCat(ctx context.Context, resourceGroupName string, petResourceName string, cat Cat, options *PetsClientAdoptCatOptions) (PetsClientAdoptCatResponse, error) { + var err error + const operationName = "PetsClient.AdoptCat" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.adoptCatCreateRequest(ctx, resourceGroupName, petResourceName, cat, options) + if err != nil { + return PetsClientAdoptCatResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PetsClientAdoptCatResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PetsClientAdoptCatResponse{}, err + } + resp, err := client.adoptCatHandleResponse(httpResp) + return resp, err +} + +// adoptCatCreateRequest creates the AdoptCat request. +func (client *PetsClient) adoptCatCreateRequest(ctx context.Context, resourceGroupName string, petResourceName string, cat Cat, _ *PetsClientAdoptCatOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Test/petResources/{petResourceName}/adoptCat" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if petResourceName == "" { + return nil, errors.New("parameter petResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{petResourceName}", url.PathEscape(petResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, cat); err != nil { + return nil, err + } + return req, nil +} + +// adoptCatHandleResponse handles the AdoptCat response. +func (client *PetsClient) adoptCatHandleResponse(resp *http.Response) (PetsClientAdoptCatResponse, error) { + result := PetsClientAdoptCatResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Cat); err != nil { + return PetsClientAdoptCatResponse{}, err + } + return result, nil +} + +// AdoptPet - Adopt a pet using the interface (discriminated base) as parameter. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - petResourceName - Pet resource name. +// - options - PetsClientAdoptPetOptions contains the optional parameters for the PetsClient.AdoptPet method. +func (client *PetsClient) AdoptPet(ctx context.Context, resourceGroupName string, petResourceName string, pet PetClassification, options *PetsClientAdoptPetOptions) (PetsClientAdoptPetResponse, error) { + var err error + const operationName = "PetsClient.AdoptPet" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.adoptPetCreateRequest(ctx, resourceGroupName, petResourceName, pet, options) + if err != nil { + return PetsClientAdoptPetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PetsClientAdoptPetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PetsClientAdoptPetResponse{}, err + } + resp, err := client.adoptPetHandleResponse(httpResp) + return resp, err +} + +// adoptPetCreateRequest creates the AdoptPet request. +func (client *PetsClient) adoptPetCreateRequest(ctx context.Context, resourceGroupName string, petResourceName string, pet PetClassification, _ *PetsClientAdoptPetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Test/petResources/{petResourceName}/adoptPet" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if petResourceName == "" { + return nil, errors.New("parameter petResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{petResourceName}", url.PathEscape(petResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, pet); err != nil { + return nil, err + } + return req, nil +} + +// adoptPetHandleResponse handles the AdoptPet response. +func (client *PetsClient) adoptPetHandleResponse(resp *http.Response) (PetsClientAdoptPetResponse, error) { + result := PetsClientAdoptPetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result); err != nil { + return PetsClientAdoptPetResponse{}, err + } + return result, nil +} + +// Get - Get a pet resource. +// If the operation fails it returns an *azcore.ResponseError type. +// - resourceGroupName - The name of the resource group. The name is case insensitive. +// - petResourceName - Pet resource name. +// - options - PetsClientGetOptions contains the optional parameters for the PetsClient.Get method. +func (client *PetsClient) Get(ctx context.Context, resourceGroupName string, petResourceName string, options *PetsClientGetOptions) (PetsClientGetResponse, error) { + var err error + const operationName = "PetsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, resourceGroupName, petResourceName, options) + if err != nil { + return PetsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PetsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PetsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *PetsClient) getCreateRequest(ctx context.Context, resourceGroupName string, petResourceName string, _ *PetsClientGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Test/petResources/{petResourceName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if petResourceName == "" { + return nil, errors.New("parameter petResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{petResourceName}", url.PathEscape(petResourceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *PetsClient) getHandleResponse(resp *http.Response) (PetsClientGetResponse, error) { + result := PetsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.PetResource); err != nil { + return PetsClientGetResponse{}, err + } + return result, nil +} diff --git a/test/local/armtest/zz_polymorphic_helpers.go b/test/local/armtest/zz_polymorphic_helpers.go new file mode 100644 index 000000000000..362bf9d75e96 --- /dev/null +++ b/test/local/armtest/zz_polymorphic_helpers.go @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armtest + +import "encoding/json" + +func unmarshalPetClassification(rawMsg json.RawMessage) (PetClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b PetClassification + switch m["kind"] { + case string(PetKindCat): + b = &Cat{} + case string(PetKindDog): + b = &Dog{} + default: + b = &Pet{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} diff --git a/test/local/armtest/zz_responses.go b/test/local/armtest/zz_responses.go new file mode 100644 index 000000000000..735ffc46942c --- /dev/null +++ b/test/local/armtest/zz_responses.go @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armtest + +import "io" + +// AuthorizationClientGetResponse contains the response from method AuthorizationClient.Get. +type AuthorizationClientGetResponse struct { + // A tenant-level authorization resource. + AuthorizationResource +} + +// AuthorizationServerClientGetResponse contains the response from method AuthorizationServerClient.Get. +type AuthorizationServerClientGetResponse struct { + // A tenant-level authorization server resource. + AuthorizationServerResource +} + +// BodyRootsClientActionResponse contains the response from method BodyRootsClient.Action. +type BodyRootsClientActionResponse struct { + // placeholder for future response values +} + +// BodyRootsClientGetResponse contains the response from method BodyRootsClient.Get. +type BodyRootsClientGetResponse struct { + // Body root resource. + BodyRoot +} + +// BodyRootsClientPutResponse contains the response from method BodyRootsClient.Put. +type BodyRootsClientPutResponse struct { + // Body root resource. + BodyRoot +} + +// ConfigurationsClientGetContentResponse contains the response from method ConfigurationsClient.GetContent. +type ConfigurationsClientGetContentResponse struct { + // Configuration resource. + Configuration +} + +// ConfigurationsClientGetStreamingContentResponse contains the response from method ConfigurationsClient.GetStreamingContent. +type ConfigurationsClientGetStreamingContentResponse struct { + // Body contains the streaming response. + Body io.ReadCloser + ContentType *string +} + +// ConfigurationsClientGetTextContentResponse contains the response from method ConfigurationsClient.GetTextContent. +type ConfigurationsClientGetTextContentResponse struct { + Value *string +} + +// ConfigurationsClientPutStreamingContentResponse contains the response from method ConfigurationsClient.PutStreamingContent. +type ConfigurationsClientPutStreamingContentResponse struct { + // placeholder for future response values +} + +// LROClientOkResponseWithAsyncHeaderResponse contains the response from method LROClient.BeginOkResponseWithAsyncHeader. +type LROClientOkResponseWithAsyncHeaderResponse struct { + // LRO model resource. + LROModel +} + +// LROClientScalarResultResponse contains the response from method LROClient.BeginScalarResult. +type LROClientScalarResultResponse struct { + Value *string +} + +// MixedScopeWidgetsClientGetResponse contains the response from method MixedScopeWidgetsClient.Get. +type MixedScopeWidgetsClientGetResponse struct { + // A mixed scope resource that has operations at both subscription and tenant level. + MixedScopeWidget +} + +// MixedScopeWidgetsClientListAllResponse contains the response from method MixedScopeWidgetsClient.NewListAllPager. +type MixedScopeWidgetsClientListAllResponse struct { + // The response of a MixedScopeWidget list operation. + MixedScopeWidgetListResult +} + +// MixedScopeWidgetsClientListBySubscriptionResponse contains the response from method MixedScopeWidgetsClient.NewListBySubscriptionPager. +type MixedScopeWidgetsClientListBySubscriptionResponse struct { + // The response of a MixedScopeWidget list operation. + MixedScopeWidgetListResult +} + +// ParameterGroupOperationsClientNoParameterGroupResponse contains the response from method ParameterGroupOperationsClient.NoParameterGroup. +type ParameterGroupOperationsClientNoParameterGroupResponse struct { + // Widget resource for testing parameter groups + Widget +} + +// ParameterGroupOperationsClientQueryParameterGroupResponse contains the response from method ParameterGroupOperationsClient.QueryParameterGroup. +type ParameterGroupOperationsClientQueryParameterGroupResponse struct { + // Widget resource for testing parameter groups + Widget +} + +// ParameterGroupOperationsClientSharedParameterGroup1Response contains the response from method ParameterGroupOperationsClient.SharedParameterGroup1. +type ParameterGroupOperationsClientSharedParameterGroup1Response struct { + // Widget resource for testing parameter groups + Widget +} + +// ParameterGroupOperationsClientSharedParameterGroup2Response contains the response from method ParameterGroupOperationsClient.SharedParameterGroup2. +type ParameterGroupOperationsClientSharedParameterGroup2Response struct { + // Widget resource for testing parameter groups + Widget +} + +// PetsClientAdoptCatResponse contains the response from method PetsClient.AdoptCat. +type PetsClientAdoptCatResponse struct { + // A cat. + Cat +} + +// PetsClientAdoptPetResponse contains the response from method PetsClient.AdoptPet. +type PetsClientAdoptPetResponse struct { + // Base pet model. + PetClassification +} + +// PetsClientGetResponse contains the response from method PetsClient.Get. +type PetsClientGetResponse struct { + // Pet resource. + PetResource +} + +// TenantItemsClientGetResponse contains the response from method TenantItemsClient.Get. +type TenantItemsClientGetResponse struct { + // A tenant-level resource. + TenantItem +} + +// TenantItemsClientListResponse contains the response from method TenantItemsClient.NewListPager. +type TenantItemsClientListResponse struct { + // The response of a TenantItem list operation. + TenantItemListResult +} diff --git a/test/local/armtest/zz_responses_serde.go b/test/local/armtest/zz_responses_serde.go new file mode 100644 index 000000000000..a45d86c68646 --- /dev/null +++ b/test/local/armtest/zz_responses_serde.go @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armtest + +import "encoding/json" + +// UnmarshalJSON implements the json.Unmarshaller interface for type LROClientScalarResultResponse. +func (l *LROClientScalarResultResponse) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, &l.Value) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PetsClientAdoptPetResponse. +func (p *PetsClientAdoptPetResponse) UnmarshalJSON(data []byte) error { + res, err := unmarshalPetClassification(data) + if err != nil { + return err + } + p.PetClassification = res + return nil +} diff --git a/test/local/armtest/zz_tenantitems_client.go b/test/local/armtest/zz_tenantitems_client.go new file mode 100644 index 000000000000..cef814d3777d --- /dev/null +++ b/test/local/armtest/zz_tenantitems_client.go @@ -0,0 +1,140 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package armtest + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// TenantItemsClient contains the methods for the TenantItems group. +// Don't use this type directly, use NewTenantItemsClient() instead. +// +// Generated from API version 2025-01-01 +type TenantItemsClient struct { + internal *arm.Client +} + +// NewTenantItemsClient creates a new instance of TenantItemsClient with the specified values. +// - credential - used to authorize requests. Usually a credential from azidentity. +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewTenantItemsClient(credential azcore.TokenCredential, options *arm.ClientOptions) (*TenantItemsClient, error) { + cl, err := arm.NewClient(moduleName, moduleVersion, credential, options) + if err != nil { + return nil, err + } + client := &TenantItemsClient{ + internal: cl, + } + return client, nil +} + +// Get - Get a tenant item. +// If the operation fails it returns an *azcore.ResponseError type. +// - tenantItemName - Tenant item name. +// - options - TenantItemsClientGetOptions contains the optional parameters for the TenantItemsClient.Get method. +func (client *TenantItemsClient) Get(ctx context.Context, tenantItemName string, options *TenantItemsClientGetOptions) (TenantItemsClientGetResponse, error) { + var err error + const operationName = "TenantItemsClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, tenantItemName, options) + if err != nil { + return TenantItemsClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return TenantItemsClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return TenantItemsClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *TenantItemsClient) getCreateRequest(ctx context.Context, tenantItemName string, _ *TenantItemsClientGetOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Test/tenantItems/{tenantItemName}" + if tenantItemName == "" { + return nil, errors.New("parameter tenantItemName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{tenantItemName}", url.PathEscape(tenantItemName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *TenantItemsClient) getHandleResponse(resp *http.Response) (TenantItemsClientGetResponse, error) { + result := TenantItemsClientGetResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.TenantItem); err != nil { + return TenantItemsClientGetResponse{}, err + } + return result, nil +} + +// NewListPager - List tenant items. +// - options - TenantItemsClientListOptions contains the optional parameters for the TenantItemsClient.NewListPager method. +func (client *TenantItemsClient) NewListPager(options *TenantItemsClientListOptions) *runtime.Pager[TenantItemsClientListResponse] { + return runtime.NewPager(runtime.PagingHandler[TenantItemsClientListResponse]{ + More: func(page TenantItemsClientListResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *TenantItemsClientListResponse) (TenantItemsClientListResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "TenantItemsClient.NewListPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, nil) + if err != nil { + return TenantItemsClientListResponse{}, err + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the List request. +func (client *TenantItemsClient) listCreateRequest(ctx context.Context, _ *TenantItemsClientListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Test/tenantItems" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20250101) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the List response. +func (client *TenantItemsClient) listHandleResponse(resp *http.Response) (TenantItemsClientListResponse, error) { + result := TenantItemsClientListResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.TenantItemListResult); err != nil { + return TenantItemsClientListResponse{}, err + } + return result, nil +} diff --git a/test/local/armtest/zz_version.go b/test/local/armtest/zz_version.go new file mode 100644 index 000000000000..f6753226623d --- /dev/null +++ b/test/local/armtest/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package armtest + +const ( + moduleName = "armtest" + moduleVersion = "v0.1.0" +) diff --git a/test/local/azblob/LICENSE.txt b/test/local/azblob/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/local/azblob/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/local/azblob/client.go b/test/local/azblob/client.go new file mode 100644 index 000000000000..13d69a9fe0e7 --- /dev/null +++ b/test/local/azblob/client.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package azblob + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +func NewClient(url string, options *azcore.ClientOptions) (*Client, error) { + client, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, options) + if err != nil { + return nil, err + } + return &Client{ + internal: client, + url: url, + }, nil +} diff --git a/test/local/azblob/go.mod b/test/local/azblob/go.mod new file mode 100644 index 000000000000..c10393413394 --- /dev/null +++ b/test/local/azblob/go.mod @@ -0,0 +1,11 @@ +module azblob + +go 1.25.0 + +require github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect +) diff --git a/test/local/azblob/go.sum b/test/local/azblob/go.sum new file mode 100644 index 000000000000..3fdb64caf441 --- /dev/null +++ b/test/local/azblob/go.sum @@ -0,0 +1,16 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/local/azblob/models_serde_test.go b/test/local/azblob/models_serde_test.go new file mode 100644 index 000000000000..18e7ce2527ca --- /dev/null +++ b/test/local/azblob/models_serde_test.go @@ -0,0 +1,1276 @@ +package azblob + +import ( + "encoding/xml" + "strings" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" +) + +func timeRFC7231(s string) *time.Time { + t, err := time.Parse(time.RFC1123, s) + if err != nil { + panic(err) + } + return &t +} + +func timeRFC3339(s string) *time.Time { + t, err := time.Parse(time.RFC3339, s) + if err != nil { + panic(err) + } + return &t +} + +// TestStorageServicePropertiesRoundTrip tests marshal/unmarshal of StorageServiceProperties +// using the example response body from Get Blob Service Properties. +// https://learn.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties +func TestStorageServicePropertiesRoundTrip(t *testing.T) { + // From the sample response in the docs + xmlData := ` + + 1.0 + true + false + true + + true + 7 + + + + 1.0 + true + false + + true + 7 + + + + 1.0 + true + true + + true + 7 + + + + + http://www.fabrikam.com,http://www.contoso.com + GET,PUT + 500 + x-ms-meta-data*,x-ms-meta-customheader + x-ms-meta-target*,x-ms-meta-customheader + + + 2017-07-29 + + true + 5 + + + true + index.html + error/404.html + +` + + var props StorageServiceProperties + if err := xml.Unmarshal([]byte(xmlData), &props); err != nil { + t.Fatal(err) + } + + // Verify Logging + if props.Logging == nil { + t.Fatal("Logging is nil") + } + assertEqual(t, "Logging.Version", *props.Logging.Version, "1.0") + assertEqual(t, "Logging.Delete", *props.Logging.Delete, true) + assertEqual(t, "Logging.Read", *props.Logging.Read, false) + assertEqual(t, "Logging.Write", *props.Logging.Write, true) + assertEqual(t, "Logging.RetentionPolicy.Enabled", *props.Logging.RetentionPolicy.Enabled, true) + assertEqual(t, "Logging.RetentionPolicy.Days", *props.Logging.RetentionPolicy.Days, int32(7)) + + // Verify HourMetrics + if props.HourMetrics == nil { + t.Fatal("HourMetrics is nil") + } + assertEqual(t, "HourMetrics.IncludeAPIs", *props.HourMetrics.IncludeAPIs, false) + + // Verify MinuteMetrics + if props.MinuteMetrics == nil { + t.Fatal("MinuteMetrics is nil") + } + assertEqual(t, "MinuteMetrics.IncludeAPIs", *props.MinuteMetrics.IncludeAPIs, true) + + // Verify CORS + if len(props.CORS) != 1 { + t.Fatalf("expected 1 CorsRule, got %d", len(props.CORS)) + } + assertEqual(t, "CorsRule.AllowedOrigins", *props.CORS[0].AllowedOrigins, "http://www.fabrikam.com,http://www.contoso.com") + assertEqual(t, "CorsRule.AllowedMethods", *props.CORS[0].AllowedMethods, "GET,PUT") + assertEqual(t, "CorsRule.MaxAgeInSeconds", *props.CORS[0].MaxAgeInSeconds, int32(500)) + + // Verify DefaultServiceVersion + assertEqual(t, "DefaultServiceVersion", *props.DefaultServiceVersion, "2017-07-29") + + // Verify DeleteRetentionPolicy + assertEqual(t, "DeleteRetentionPolicy.Enabled", *props.DeleteRetentionPolicy.Enabled, true) + assertEqual(t, "DeleteRetentionPolicy.Days", *props.DeleteRetentionPolicy.Days, int32(5)) + + // Verify StaticWebsite + assertEqual(t, "StaticWebsite.Enabled", *props.StaticWebsite.Enabled, true) + assertEqual(t, "StaticWebsite.IndexDocument", *props.StaticWebsite.IndexDocument, "index.html") + assertEqual(t, "StaticWebsite.ErrorDocument404Path", *props.StaticWebsite.ErrorDocument404Path, "error/404.html") + + // Re-marshal and unmarshal to verify round-trip + out, err := xml.Marshal(props) + if err != nil { + t.Fatal(err) + } + var props2 StorageServiceProperties + if err := xml.Unmarshal(out, &props2); err != nil { + t.Fatal(err) + } + assertEqual(t, "round-trip Logging.Version", *props2.Logging.Version, "1.0") + assertEqual(t, "round-trip CorsRule.AllowedOrigins", *props2.CORS[0].AllowedOrigins, "http://www.fabrikam.com,http://www.contoso.com") + assertEqual(t, "round-trip StaticWebsite.Enabled", *props2.StaticWebsite.Enabled, true) +} + +// TestListContainersSegmentResponseRoundTrip tests marshal/unmarshal of ListContainersSegmentResponse +// using the example response body from List Containers. +// https://learn.microsoft.com/en-us/rest/api/storageservices/list-containers2 +func TestListContainersSegmentResponseRoundTrip(t *testing.T) { + xmlData := ` + 3 + + + audio + + Wed, 26 Oct 2016 20:39:39 GMT + 0x8CACB9BD7C6B1B2 + container + + + + images + + Wed, 26 Oct 2016 20:39:39 GMT + 0x8CACB9BD7C1EEEC + + + + textfiles + + Wed, 26 Oct 2016 20:39:39 GMT + 0x8CACB9BD7BACAC3 + + + + video +` + + var resp ListContainersSegmentResponse + if err := xml.Unmarshal([]byte(xmlData), &resp); err != nil { + t.Fatal(err) + } + + assertEqual(t, "ServiceEndpoint", *resp.ServiceEndpoint, "https://myaccount.blob.core.windows.net/") + assertEqual(t, "MaxResults", *resp.MaxResults, int32(3)) + assertEqual(t, "NextMarker", *resp.NextMarker, "video") + + if len(resp.ContainerItems) != 3 { + t.Fatalf("expected 3 containers, got %d", len(resp.ContainerItems)) + } + + assertEqual(t, "Container[0].Name", *resp.ContainerItems[0].Name, "audio") + assertEqual(t, "Container[0].Etag", string(*resp.ContainerItems[0].Properties.ETag), "0x8CACB9BD7C6B1B2") + assertEqual(t, "Container[0].PublicAccess", string(*resp.ContainerItems[0].Properties.PublicAccess), "container") + + assertEqual(t, "Container[1].Name", *resp.ContainerItems[1].Name, "images") + assertEqual(t, "Container[2].Name", *resp.ContainerItems[2].Name, "textfiles") + + // Verify time parsing + expectedTime := timeRFC7231("Wed, 26 Oct 2016 20:39:39 GMT") + if !resp.ContainerItems[0].Properties.LastModified.Equal(*expectedTime) { + t.Fatalf("expected Last-Modified %v, got %v", expectedTime, resp.ContainerItems[0].Properties.LastModified) + } + + // Round-trip + out, err := xml.Marshal(resp) + if err != nil { + t.Fatal(err) + } + var resp2 ListContainersSegmentResponse + if err := xml.Unmarshal(out, &resp2); err != nil { + t.Fatal(err) + } + assertEqual(t, "round-trip ServiceEndpoint", *resp2.ServiceEndpoint, "https://myaccount.blob.core.windows.net/") + if len(resp2.ContainerItems) != 3 { + t.Fatalf("round-trip expected 3 containers, got %d", len(resp2.ContainerItems)) + } + assertEqual(t, "round-trip Container[0].Name", *resp2.ContainerItems[0].Name, "audio") +} + +// TestContainerItemWithMetadataRoundTrip tests marshal/unmarshal of ContainerItem with Metadata. +// https://learn.microsoft.com/en-us/rest/api/storageservices/list-containers2 +func TestContainerItemWithMetadataRoundTrip(t *testing.T) { + xmlData := ` + mycontainer + + Wed, 26 Oct 2016 20:39:39 GMT + 0x8CACB9BD7C6B1B2 + unlocked + available + false + false + + + first value + second value + +` + + var item ContainerItem + if err := xml.Unmarshal([]byte(xmlData), &item); err != nil { + t.Fatal(err) + } + + assertEqual(t, "Name", *item.Name, "mycontainer") + assertEqual(t, "Etag", string(*item.Properties.ETag), "0x8CACB9BD7C6B1B2") + assertEqual(t, "LeaseStatus", string(*item.Properties.LeaseStatus), "unlocked") + assertEqual(t, "LeaseState", string(*item.Properties.LeaseState), "available") + assertEqual(t, "HasImmutabilityPolicy", *item.Properties.HasImmutabilityPolicy, false) + assertEqual(t, "HasLegalHold", *item.Properties.HasLegalHold, false) + + if len(item.Metadata) != 2 { + t.Fatalf("expected 2 metadata entries, got %d", len(item.Metadata)) + } + + // Round-trip + out, err := xml.Marshal(item) + if err != nil { + t.Fatal(err) + } + var item2 ContainerItem + if err := xml.Unmarshal(out, &item2); err != nil { + t.Fatal(err) + } + assertEqual(t, "round-trip Name", *item2.Name, "mycontainer") + if len(item2.Metadata) != 2 { + t.Fatalf("round-trip expected 2 metadata entries, got %d", len(item2.Metadata)) + } +} + +// TestBlockListRoundTrip tests marshal/unmarshal of BlockList +// using the example response body from Get Block List. +// https://learn.microsoft.com/en-us/rest/api/storageservices/get-block-list +func TestBlockListRoundTrip(t *testing.T) { + xmlData := ` + + + QmxvY2tJZDAwMQ== + 4194304 + + + QmxvY2tJZDAwMg== + 4194304 + + + + + QmxvY2tJZDAwMw== + 4194304 + + + QmxvY2tJZDAwNA== + 1024000 + + +` + + var blockList BlockList + if err := xml.Unmarshal([]byte(xmlData), &blockList); err != nil { + t.Fatal(err) + } + + if len(blockList.CommittedBlocks) != 2 { + t.Fatalf("expected 2 committed blocks, got %d", len(blockList.CommittedBlocks)) + } + if len(blockList.UncommittedBlocks) != 2 { + t.Fatalf("expected 2 uncommitted blocks, got %d", len(blockList.UncommittedBlocks)) + } + assertEqual(t, "CommittedBlocks[0].Name", *blockList.CommittedBlocks[0].Name, "QmxvY2tJZDAwMQ==") + assertEqual(t, "CommittedBlocks[0].Size", *blockList.CommittedBlocks[0].Size, int64(4194304)) + assertEqual(t, "CommittedBlocks[1].Name", *blockList.CommittedBlocks[1].Name, "QmxvY2tJZDAwMg==") + assertEqual(t, "UncommittedBlocks[0].Name", *blockList.UncommittedBlocks[0].Name, "QmxvY2tJZDAwMw==") + assertEqual(t, "UncommittedBlocks[1].Name", *blockList.UncommittedBlocks[1].Name, "QmxvY2tJZDAwNA==") + assertEqual(t, "UncommittedBlocks[1].Size", *blockList.UncommittedBlocks[1].Size, int64(1024000)) + + // Round-trip + out, err := xml.Marshal(blockList) + if err != nil { + t.Fatal(err) + } + var blockList2 BlockList + if err := xml.Unmarshal(out, &blockList2); err != nil { + t.Fatal(err) + } + if len(blockList2.CommittedBlocks) != 2 { + t.Fatalf("round-trip expected 2 committed blocks, got %d", len(blockList2.CommittedBlocks)) + } + if len(blockList2.UncommittedBlocks) != 2 { + t.Fatalf("round-trip expected 2 uncommitted blocks, got %d", len(blockList2.UncommittedBlocks)) + } +} + +// TestBlockLookupListRoundTrip tests marshal/unmarshal of BlockLookupList +// using the example request body from Put Block List. +// https://learn.microsoft.com/en-us/rest/api/storageservices/put-block-list +func TestBlockLookupListRoundTrip(t *testing.T) { + xmlData := ` + AAAAAA== + AQAAAA== + AZAAAA== +` + + var bll BlockLookupList + if err := xml.Unmarshal([]byte(xmlData), &bll); err != nil { + t.Fatal(err) + } + + if len(bll.Latest) != 3 { + t.Fatalf("expected 3 latest blocks, got %d", len(bll.Latest)) + } + assertEqual(t, "Latest[0]", *bll.Latest[0], "AAAAAA==") + assertEqual(t, "Latest[1]", *bll.Latest[1], "AQAAAA==") + assertEqual(t, "Latest[2]", *bll.Latest[2], "AZAAAA==") + + // Round-trip + out, err := xml.Marshal(bll) + if err != nil { + t.Fatal(err) + } + var bll2 BlockLookupList + if err := xml.Unmarshal(out, &bll2); err != nil { + t.Fatal(err) + } + if len(bll2.Latest) != 3 { + t.Fatalf("round-trip expected 3 latest blocks, got %d", len(bll2.Latest)) + } +} + +// TestBlockLookupListMixedRoundTrip tests mixed committed/uncommitted block lists. +// https://learn.microsoft.com/en-us/rest/api/storageservices/put-block-list +func TestBlockLookupListMixedRoundTrip(t *testing.T) { + xmlData := ` + ANAAAA== + AQAAAA== + AZAAAA== +` + + var bll BlockLookupList + if err := xml.Unmarshal([]byte(xmlData), &bll); err != nil { + t.Fatal(err) + } + + if len(bll.Uncommitted) != 2 { + t.Fatalf("expected 2 uncommitted blocks, got %d", len(bll.Uncommitted)) + } + if len(bll.Committed) != 1 { + t.Fatalf("expected 1 committed block, got %d", len(bll.Committed)) + } + assertEqual(t, "Uncommitted[0]", *bll.Uncommitted[0], "ANAAAA==") + assertEqual(t, "Committed[0]", *bll.Committed[0], "AQAAAA==") + + // Round-trip + out, err := xml.Marshal(bll) + if err != nil { + t.Fatal(err) + } + var bll2 BlockLookupList + if err := xml.Unmarshal(out, &bll2); err != nil { + t.Fatal(err) + } + if len(bll2.Uncommitted) != 2 { + t.Fatalf("round-trip expected 2 uncommitted blocks, got %d", len(bll2.Uncommitted)) + } + if len(bll2.Committed) != 1 { + t.Fatalf("round-trip expected 1 committed block, got %d", len(bll2.Committed)) + } +} + +// TestPageListRoundTrip tests marshal/unmarshal of PageList +// using the example response body from Get Page Ranges. +// https://learn.microsoft.com/en-us/rest/api/storageservices/get-page-ranges +func TestPageListRoundTrip(t *testing.T) { + xmlData := ` + + 0 + 511 + + + 1024 + 1535 + +` + + var pageList PageList + if err := xml.Unmarshal([]byte(xmlData), &pageList); err != nil { + t.Fatal(err) + } + + if len(pageList.PageRange) != 2 { + t.Fatalf("expected 2 page ranges, got %d", len(pageList.PageRange)) + } + assertEqual(t, "PageRange[0].Start", *pageList.PageRange[0].Start, int64(0)) + assertEqual(t, "PageRange[0].End", *pageList.PageRange[0].End, int64(511)) + assertEqual(t, "PageRange[1].Start", *pageList.PageRange[1].Start, int64(1024)) + assertEqual(t, "PageRange[1].End", *pageList.PageRange[1].End, int64(1535)) + + // Round-trip + out, err := xml.Marshal(pageList) + if err != nil { + t.Fatal(err) + } + var pageList2 PageList + if err := xml.Unmarshal(out, &pageList2); err != nil { + t.Fatal(err) + } + if len(pageList2.PageRange) != 2 { + t.Fatalf("round-trip expected 2 page ranges, got %d", len(pageList2.PageRange)) + } +} + +// TestPageListWithClearRangesRoundTrip tests diff page ranges with clear ranges. +// https://learn.microsoft.com/en-us/rest/api/storageservices/get-page-ranges +func TestPageListWithClearRangesRoundTrip(t *testing.T) { + xmlData := ` + + 0 + 511 + + + 512 + 1023 + + + 1024 + 1535 + +` + + var pageList PageList + if err := xml.Unmarshal([]byte(xmlData), &pageList); err != nil { + t.Fatal(err) + } + + if len(pageList.PageRange) != 2 { + t.Fatalf("expected 2 page ranges, got %d", len(pageList.PageRange)) + } + if len(pageList.ClearRange) != 1 { + t.Fatalf("expected 1 clear range, got %d", len(pageList.ClearRange)) + } + assertEqual(t, "ClearRange[0].Start", *pageList.ClearRange[0].Start, int64(512)) + assertEqual(t, "ClearRange[0].End", *pageList.ClearRange[0].End, int64(1023)) + + // Round-trip + out, err := xml.Marshal(pageList) + if err != nil { + t.Fatal(err) + } + var pageList2 PageList + if err := xml.Unmarshal(out, &pageList2); err != nil { + t.Fatal(err) + } + if len(pageList2.PageRange) != 2 { + t.Fatalf("round-trip expected 2 page ranges, got %d", len(pageList2.PageRange)) + } + if len(pageList2.ClearRange) != 1 { + t.Fatalf("round-trip expected 1 clear range, got %d", len(pageList2.ClearRange)) + } +} + +// TestFilterBlobSegmentRoundTrip tests marshal/unmarshal of FilterBlobSegment +// using the example response body from Find Blobs by Tags. +// https://learn.microsoft.com/en-us/rest/api/storageservices/find-blobs-by-tags +func TestFilterBlobSegmentRoundTrip(t *testing.T) { + xmlData := ` + Status = 'In Progress' + + + my-blob + my-container + + + + Status + In Progress + + + + + + +` + + var resp FilterBlobSegment + if err := xml.Unmarshal([]byte(xmlData), &resp); err != nil { + t.Fatal(err) + } + + assertEqual(t, "ServiceEndpoint", *resp.ServiceEndpoint, "http://myaccount.blob.core.windows.net/") + assertEqual(t, "Where", *resp.Where, "Status = 'In Progress'") + if len(resp.Blobs) != 1 { + t.Fatalf("expected 1 blob, got %d", len(resp.Blobs)) + } + assertEqual(t, "Blobs[0].Name", *resp.Blobs[0].Name, "my-blob") + assertEqual(t, "Blobs[0].ContainerName", *resp.Blobs[0].ContainerName, "my-container") + if len(resp.Blobs[0].Tags.BlobTagSet) != 1 { + t.Fatalf("expected 1 tag, got %d", len(resp.Blobs[0].Tags.BlobTagSet)) + } + assertEqual(t, "Tag.Key", *resp.Blobs[0].Tags.BlobTagSet[0].Key, "Status") + assertEqual(t, "Tag.Value", *resp.Blobs[0].Tags.BlobTagSet[0].Value, "In Progress") + + // Round-trip + out, err := xml.Marshal(resp) + if err != nil { + t.Fatal(err) + } + var resp2 FilterBlobSegment + if err := xml.Unmarshal(out, &resp2); err != nil { + t.Fatal(err) + } + assertEqual(t, "round-trip Where", *resp2.Where, "Status = 'In Progress'") + if len(resp2.Blobs) != 1 { + t.Fatalf("round-trip expected 1 blob, got %d", len(resp2.Blobs)) + } +} + +// TestListBlobsFlatSegmentResponseRoundTrip tests marshal/unmarshal of ListBlobsFlatSegmentResponse +// using the example response body from List Blobs. +// https://learn.microsoft.com/en-us/rest/api/storageservices/list-blobs +func TestListBlobsFlatSegmentResponseRoundTrip(t *testing.T) { + xmlData := ` + my + 10 + + + my-blob.txt + + false + + Wed, 26 Oct 2016 20:39:39 GMT + Wed, 26 Oct 2016 20:39:39 GMT + 0x8CACB9BD7C6B1B2 + 1024 + application/octet-stream + BlockBlob + Hot + unlocked + available + true + + + + + TagName + TagValue + + + + + + +` + + var resp ListBlobsFlatSegmentResponse + if err := xml.Unmarshal([]byte(xmlData), &resp); err != nil { + t.Fatal(err) + } + + assertEqual(t, "ServiceEndpoint", *resp.ServiceEndpoint, "http://myaccount.blob.core.windows.net/") + assertEqual(t, "ContainerName", *resp.ContainerName, "mycontainer") + assertEqual(t, "Prefix", *resp.Prefix, "my") + assertEqual(t, "MaxResults", *resp.MaxResults, int32(10)) + + if resp.Segment == nil || len(resp.Segment.BlobItems) != 1 { + t.Fatal("expected 1 blob item") + } + blob := resp.Segment.BlobItems[0] + assertEqual(t, "Blob.Name", *blob.Name, "my-blob.txt") + assertEqual(t, "Blob.Deleted", *blob.Deleted, false) + assertEqual(t, "Blob.Properties.ETag", string(*blob.Properties.ETag), "0x8CACB9BD7C6B1B2") + assertEqual(t, "Blob.Properties.ContentLength", *blob.Properties.ContentLength, int64(1024)) + assertEqual(t, "Blob.Properties.ContentType", *blob.Properties.ContentType, "application/octet-stream") + assertEqual(t, "Blob.Properties.BlobType", string(*blob.Properties.BlobType), "BlockBlob") + assertEqual(t, "Blob.Properties.AccessTier", string(*blob.Properties.AccessTier), "Hot") + assertEqual(t, "Blob.Properties.ServerEncrypted", *blob.Properties.ServerEncrypted, true) + + // Tags + if blob.BlobTags == nil || len(blob.BlobTags.BlobTagSet) != 1 { + t.Fatal("expected 1 blob tag") + } + assertEqual(t, "Tag.Key", *blob.BlobTags.BlobTagSet[0].Key, "TagName") + assertEqual(t, "Tag.Value", *blob.BlobTags.BlobTagSet[0].Value, "TagValue") + +} + +// TestListBlobsHierarchySegmentResponseRoundTrip tests marshal/unmarshal of ListBlobsHierarchySegmentResponse. +// https://learn.microsoft.com/en-us/rest/api/storageservices/list-blobs +func TestListBlobsHierarchySegmentResponseRoundTrip(t *testing.T) { + xmlData := ` + / + + + file1.txt + + false + + Wed, 26 Oct 2016 20:39:39 GMT + 0x8CACB9BD7C6B1B2 + 512 + text/plain + BlockBlob + unlocked + available + + + + subdir/ + + + +` + + var resp ListBlobsHierarchySegmentResponse + if err := xml.Unmarshal([]byte(xmlData), &resp); err != nil { + t.Fatal(err) + } + + assertEqual(t, "Delimiter", *resp.Delimiter, "/") + if resp.Segment == nil { + t.Fatal("Segment is nil") + } + if len(resp.Segment.BlobItems) != 1 { + t.Fatalf("expected 1 blob item, got %d", len(resp.Segment.BlobItems)) + } + if len(resp.Segment.BlobPrefixes) != 1 { + t.Fatalf("expected 1 blob prefix, got %d", len(resp.Segment.BlobPrefixes)) + } + assertEqual(t, "BlobPrefix[0].Name", *resp.Segment.BlobPrefixes[0].Name, "subdir/") +} + +// TestGeoReplicationRoundTrip tests marshal/unmarshal of GeoReplication with RFC1123 time. +func TestGeoReplicationRoundTrip(t *testing.T) { + xmlData := ` + live + Wed, 26 Oct 2016 20:39:39 GMT +` + + var geo GeoReplication + if err := xml.Unmarshal([]byte(xmlData), &geo); err != nil { + t.Fatal(err) + } + + assertEqual(t, "Status", string(*geo.Status), "live") + expectedTime := timeRFC7231("Wed, 26 Oct 2016 20:39:39 GMT") + if !geo.LastSyncTime.Equal(*expectedTime) { + t.Fatalf("expected LastSyncTime %v, got %v", expectedTime, geo.LastSyncTime) + } + + // Round-trip + out, err := xml.Marshal(geo) + if err != nil { + t.Fatal(err) + } + var geo2 GeoReplication + if err := xml.Unmarshal(out, &geo2); err != nil { + t.Fatal(err) + } + assertEqual(t, "round-trip Status", string(*geo2.Status), "live") + if !geo2.LastSyncTime.Equal(*expectedTime) { + t.Fatalf("round-trip expected LastSyncTime %v, got %v", expectedTime, geo2.LastSyncTime) + } +} + +// TestUserDelegationKeyRoundTrip tests marshal/unmarshal of UserDelegationKey with RFC3339 time. +func TestUserDelegationKeyRoundTrip(t *testing.T) { + xmlData := ` + 00000000-0000-0000-0000-000000000000 + 00000000-0000-0000-0000-000000000001 + 2020-01-01T00:00:00Z + 2020-01-02T00:00:00Z + b + 2019-12-12 + dGVzdGtleQ== +` + + var key UserDelegationKey + if err := xml.Unmarshal([]byte(xmlData), &key); err != nil { + t.Fatal(err) + } + + assertEqual(t, "SignedOid", *key.SignedOID, "00000000-0000-0000-0000-000000000000") + assertEqual(t, "SignedTid", *key.SignedTID, "00000000-0000-0000-0000-000000000001") + assertEqual(t, "SignedService", *key.SignedService, "b") + assertEqual(t, "SignedVersion", *key.SignedVersion, "2019-12-12") + assertEqual(t, "Value", *key.Value, "dGVzdGtleQ==") + + expectedStart := timeRFC3339("2020-01-01T00:00:00Z") + if !key.SignedStart.Equal(*expectedStart) { + t.Fatalf("expected SignedStart %v, got %v", expectedStart, key.SignedStart) + } + expectedExpiry := timeRFC3339("2020-01-02T00:00:00Z") + if !key.SignedExpiry.Equal(*expectedExpiry) { + t.Fatalf("expected SignedExpiry %v, got %v", expectedExpiry, key.SignedExpiry) + } + + // Round-trip + out, err := xml.Marshal(key) + if err != nil { + t.Fatal(err) + } + var key2 UserDelegationKey + if err := xml.Unmarshal(out, &key2); err != nil { + t.Fatal(err) + } + assertEqual(t, "round-trip SignedOid", *key2.SignedOID, "00000000-0000-0000-0000-000000000000") + if !key2.SignedStart.Equal(*expectedStart) { + t.Fatalf("round-trip expected SignedStart %v, got %v", expectedStart, key2.SignedStart) + } +} + +// TestTagsRoundTrip tests marshal/unmarshal of Tags. +func TestTagsRoundTrip(t *testing.T) { + xmlData := ` + + + Project + Contoso + + + Status + Active + + +` + + var tags Tags + if err := xml.Unmarshal([]byte(xmlData), &tags); err != nil { + t.Fatal(err) + } + + if len(tags.BlobTagSet) != 2 { + t.Fatalf("expected 2 tags, got %d", len(tags.BlobTagSet)) + } + assertEqual(t, "Tag[0].Key", *tags.BlobTagSet[0].Key, "Project") + assertEqual(t, "Tag[0].Value", *tags.BlobTagSet[0].Value, "Contoso") + assertEqual(t, "Tag[1].Key", *tags.BlobTagSet[1].Key, "Status") + assertEqual(t, "Tag[1].Value", *tags.BlobTagSet[1].Value, "Active") + + // Round-trip + out, err := xml.Marshal(tags) + if err != nil { + t.Fatal(err) + } + var tags2 Tags + if err := xml.Unmarshal(out, &tags2); err != nil { + t.Fatal(err) + } + if len(tags2.BlobTagSet) != 2 { + t.Fatalf("round-trip expected 2 tags, got %d", len(tags2.BlobTagSet)) + } +} + +// TestSignedIdentifierRoundTrip tests marshal/unmarshal of SignedIdentifier with time values. +func TestSignedIdentifierRoundTrip(t *testing.T) { + xmlData := ` + MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI= + + 2009-09-28T08:49:37.0000000Z + 2009-09-29T08:49:37.0000000Z + rwd + +` + + var si SignedIdentifier + if err := xml.Unmarshal([]byte(xmlData), &si); err != nil { + t.Fatal(err) + } + + assertEqual(t, "Id", *si.ID, "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=") + assertEqual(t, "Permission", *si.AccessPolicy.Permission, "rwd") + + // Round-trip + out, err := xml.Marshal(si) + if err != nil { + t.Fatal(err) + } + var si2 SignedIdentifier + if err := xml.Unmarshal(out, &si2); err != nil { + t.Fatal(err) + } + assertEqual(t, "round-trip Id", *si2.ID, "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=") + assertEqual(t, "round-trip Permission", *si2.AccessPolicy.Permission, "rwd") +} + +// TestStorageServicePropertiesMarshal tests that constructing a StorageServiceProperties and marshaling +// produces valid XML matching the Set Blob Service Properties request body. +// https://learn.microsoft.com/en-us/rest/api/storageservices/set-blob-service-properties +func TestStorageServicePropertiesMarshal(t *testing.T) { + props := StorageServiceProperties{ + Logging: &Logging{ + Version: to.Ptr("1.0"), + Delete: to.Ptr(true), + Read: to.Ptr(false), + Write: to.Ptr(true), + RetentionPolicy: &RetentionPolicy{ + Enabled: to.Ptr(true), + Days: to.Ptr(int32(7)), + }, + }, + HourMetrics: &Metrics{ + Version: to.Ptr("1.0"), + Enabled: to.Ptr(true), + IncludeAPIs: to.Ptr(false), + RetentionPolicy: &RetentionPolicy{ + Enabled: to.Ptr(true), + Days: to.Ptr(int32(7)), + }, + }, + CORS: []*CORSRule{ + { + AllowedOrigins: to.Ptr("http://www.fabrikam.com,http://www.contoso.com"), + AllowedMethods: to.Ptr("GET,PUT"), + MaxAgeInSeconds: to.Ptr(int32(500)), + ExposedHeaders: to.Ptr("x-ms-meta-data*,x-ms-meta-customheader"), + AllowedHeaders: to.Ptr("x-ms-meta-target*,x-ms-meta-customheader"), + }, + }, + DefaultServiceVersion: to.Ptr("2018-03-28"), + DeleteRetentionPolicy: &RetentionPolicy{ + Enabled: to.Ptr(true), + Days: to.Ptr(int32(5)), + }, + StaticWebsite: &StaticWebsite{ + Enabled: to.Ptr(true), + IndexDocument: to.Ptr("index.html"), + ErrorDocument404Path: to.Ptr("error/404.html"), + }, + } + + data, err := xml.Marshal(props) + if err != nil { + t.Fatal(err) + } + + // Unmarshal back and verify + var props2 StorageServiceProperties + if err := xml.Unmarshal(data, &props2); err != nil { + t.Fatal(err) + } + + assertEqual(t, "Logging.Version", *props2.Logging.Version, "1.0") + assertEqual(t, "Logging.Delete", *props2.Logging.Delete, true) + if len(props2.CORS) != 1 { + t.Fatalf("expected 1 CorsRule, got %d", len(props2.CORS)) + } + assertEqual(t, "CorsRule.MaxAgeInSeconds", *props2.CORS[0].MaxAgeInSeconds, int32(500)) + assertEqual(t, "DefaultServiceVersion", *props2.DefaultServiceVersion, "2018-03-28") + if props2.DeleteRetentionPolicy == nil { + t.Fatal("DeleteRetentionPolicy is nil after round-trip") + } + assertEqual(t, "DeleteRetentionPolicy.Enabled", *props2.DeleteRetentionPolicy.Enabled, true) + if props2.StaticWebsite == nil { + t.Fatal("StaticWebsite is nil after round-trip") + } + assertEqual(t, "StaticWebsite.IndexDocument", *props2.StaticWebsite.IndexDocument, "index.html") +} + +// TestPropertiesInternalTimeFieldsRoundTrip tests that time fields on PropertiesInternal +// round-trip correctly through XML. +func TestPropertiesInternalTimeFieldsRoundTrip(t *testing.T) { + xmlData := ` + Wed, 26 Oct 2016 20:39:39 GMT + Thu, 27 Oct 2016 10:00:00 GMT + 0x8CACB9BD7C6B1B2 + 2048 + text/plain + BlockBlob + Hot + true + true + unlocked + available +` + + var props Properties + if err := xml.Unmarshal([]byte(xmlData), &props); err != nil { + t.Fatal(err) + } + + assertEqual(t, "Etag", string(*props.ETag), "0x8CACB9BD7C6B1B2") + assertEqual(t, "ContentLength", *props.ContentLength, int64(2048)) + assertEqual(t, "ContentType", *props.ContentType, "text/plain") + assertEqual(t, "BlobType", string(*props.BlobType), "BlockBlob") + assertEqual(t, "AccessTier", string(*props.AccessTier), "Hot") + assertEqual(t, "AccessTierInferred", *props.AccessTierInferred, true) + assertEqual(t, "ServerEncrypted", *props.ServerEncrypted, true) + + expectedCreation := timeRFC7231("Wed, 26 Oct 2016 20:39:39 GMT") + if !props.CreationTime.Equal(*expectedCreation) { + t.Fatalf("expected CreationTime %v, got %v", expectedCreation, props.CreationTime) + } + expectedModified := timeRFC7231("Thu, 27 Oct 2016 10:00:00 GMT") + if !props.LastModified.Equal(*expectedModified) { + t.Fatalf("expected LastModified %v, got %v", expectedModified, props.LastModified) + } + + // Round-trip + out, err := xml.Marshal(props) + if err != nil { + t.Fatal(err) + } + var props2 Properties + if err := xml.Unmarshal(out, &props2); err != nil { + t.Fatal(err) + } + if !props2.CreationTime.Equal(*expectedCreation) { + t.Fatalf("round-trip expected CreationTime %v, got %v", expectedCreation, props2.CreationTime) + } + if !props2.LastModified.Equal(*expectedModified) { + t.Fatalf("round-trip expected LastModified %v, got %v", expectedModified, props2.LastModified) + } +} + +// TestArrowConfigurationRoundTrip tests marshal/unmarshal of ArrowConfiguration. +func TestArrowConfigurationRoundTrip(t *testing.T) { + xmlData := ` + + + INT64 + id + + + DOUBLE + value + 10 + 2 + + +` + + var ac ArrowConfiguration + if err := xml.Unmarshal([]byte(xmlData), &ac); err != nil { + t.Fatal(err) + } + + if len(ac.Schema) != 2 { + t.Fatalf("expected 2 fields, got %d", len(ac.Schema)) + } + assertEqual(t, "Field[0].Type", *ac.Schema[0].Type, "INT64") + assertEqual(t, "Field[0].Name", *ac.Schema[0].Name, "id") + assertEqual(t, "Field[1].Type", *ac.Schema[1].Type, "DOUBLE") + assertEqual(t, "Field[1].Precision", *ac.Schema[1].Precision, int32(10)) + assertEqual(t, "Field[1].Scale", *ac.Schema[1].Scale, int32(2)) + + // Round-trip + out, err := xml.Marshal(ac) + if err != nil { + t.Fatal(err) + } + var ac2 ArrowConfiguration + if err := xml.Unmarshal(out, &ac2); err != nil { + t.Fatal(err) + } + if len(ac2.Schema) != 2 { + t.Fatalf("round-trip expected 2 fields, got %d", len(ac2.Schema)) + } + assertEqual(t, "round-trip Field[0].Type", *ac2.Schema[0].Type, "INT64") +} + +// TestStorageServiceStatsRoundTrip tests StorageServiceStats with GeoReplication. +func TestStorageServiceStatsRoundTrip(t *testing.T) { + xmlData := ` + + live + Wed, 26 Oct 2016 20:39:39 GMT + +` + + var stats StorageServiceStats + if err := xml.Unmarshal([]byte(xmlData), &stats); err != nil { + t.Fatal(err) + } + + if stats.GeoReplication == nil { + t.Fatal("GeoReplication is nil") + } + assertEqual(t, "Status", string(*stats.GeoReplication.Status), "live") + + // Round-trip + out, err := xml.Marshal(stats) + if err != nil { + t.Fatal(err) + } + var stats2 StorageServiceStats + if err := xml.Unmarshal(out, &stats2); err != nil { + t.Fatal(err) + } + assertEqual(t, "round-trip Status", string(*stats2.GeoReplication.Status), "live") +} + +// TestBlockListCommittedOnlyUnmarshal tests that committed-only block list responses parse correctly. +// https://learn.microsoft.com/en-us/rest/api/storageservices/get-block-list +func TestBlockListCommittedOnlyUnmarshal(t *testing.T) { + xmlData := ` + + + QmxvY2tJZDAwMQ== + 4194304 + + + QmxvY2tJZDAwMg== + 4194304 + + +` + + var blockList BlockList + if err := xml.Unmarshal([]byte(xmlData), &blockList); err != nil { + t.Fatal(err) + } + + if len(blockList.CommittedBlocks) != 2 { + t.Fatalf("expected 2 committed blocks, got %d", len(blockList.CommittedBlocks)) + } + if blockList.UncommittedBlocks != nil { + t.Fatalf("expected nil uncommitted blocks, got %d", len(blockList.UncommittedBlocks)) + } +} + +// TestEmptySlicesRoundTrip tests that empty/nil slices are handled gracefully. +func TestEmptySlicesRoundTrip(t *testing.T) { + props := StorageServiceProperties{ + Logging: &Logging{ + Version: to.Ptr("1.0"), + Delete: to.Ptr(false), + Read: to.Ptr(false), + Write: to.Ptr(false), + RetentionPolicy: &RetentionPolicy{ + Enabled: to.Ptr(false), + }, + }, + } + + data, err := xml.Marshal(props) + if err != nil { + t.Fatal(err) + } + + xmlStr := string(data) + assertNotContains(t, "StorageServiceProperties with nil CORS", xmlStr, "") + + var props2 StorageServiceProperties + if err := xml.Unmarshal(data, &props2); err != nil { + t.Fatal(err) + } + + assertEqual(t, "Logging.Version", *props2.Logging.Version, "1.0") + if props2.CORS != nil { + t.Fatalf("expected nil Cors, got %d rules", len(props2.CORS)) + } +} + +// TestNilSlicesOmitXMLTags tests that nil slices omit their XML wrapper tags during marshaling. +func TestNilSlicesOmitXMLTags(t *testing.T) { + // ArrowConfiguration with nil Schema + ac := ArrowConfiguration{} + data, err := xml.Marshal(ac) + if err != nil { + t.Fatal(err) + } + assertNotContains(t, "ArrowConfiguration with nil Schema", string(data), "") + + // BlockList with nil CommittedBlocks and UncommittedBlocks + bl := BlockList{} + data, err = xml.Marshal(bl) + if err != nil { + t.Fatal(err) + } + xmlStr := string(data) + assertNotContains(t, "BlockList with nil CommittedBlocks", xmlStr, "") + assertNotContains(t, "BlockList with nil UncommittedBlocks", xmlStr, "") + + // BlockLookupList with nil slices + bll := BlockLookupList{} + data, err = xml.Marshal(bll) + if err != nil { + t.Fatal(err) + } + xmlStr = string(data) + assertNotContains(t, "BlockLookupList with nil Committed", xmlStr, "") + assertNotContains(t, "BlockLookupList with nil Latest", xmlStr, "") + assertNotContains(t, "BlockLookupList with nil Uncommitted", xmlStr, "") + + // FilterBlobSegment with nil Blobs + fbs := FilterBlobSegment{ + ServiceEndpoint: to.Ptr("https://example.com/"), + Where: to.Ptr("tag = 'value'"), + } + data, err = xml.Marshal(fbs) + if err != nil { + t.Fatal(err) + } + assertNotContains(t, "FilterBlobSegment with nil Blobs", string(data), "") + + // PageList with nil PageRange and ClearRange + pl := PageList{} + data, err = xml.Marshal(pl) + if err != nil { + t.Fatal(err) + } + xmlStr = string(data) + assertNotContains(t, "PageList with nil PageRange", xmlStr, "") + assertNotContains(t, "PageList with nil ClearRange", xmlStr, "") + + // Tags with nil BlobTagSet + tags := Tags{} + data, err = xml.Marshal(tags) + if err != nil { + t.Fatal(err) + } + assertNotContains(t, "Tags with nil BlobTagSet", string(data), "") + + // ListContainersSegmentResponse with nil ContainerItems + lcsr := ListContainersSegmentResponse{ + ServiceEndpoint: to.Ptr("https://example.com/"), + } + data, err = xml.Marshal(lcsr) + if err != nil { + t.Fatal(err) + } + assertNotContains(t, "ListContainersSegmentResponse with nil ContainerItems", string(data), "") + + // SignedIdentifiers with nil Items + type wrapper struct { + XMLName xml.Name `xml:"SignedIdentifiers"` + ContainerACL *[]*SignedIdentifier `xml:"SignedIdentifier"` + } + data, err = xml.Marshal(wrapper{}) + if err != nil { + t.Fatal(err) + } + assertNotContains(t, "SignedIdentifiers with nil Items", string(data), "") +} + +// TestKeyInfoRoundTrip tests marshal/unmarshal of KeyInfo. +func TestKeyInfoRoundTrip(t *testing.T) { + xmlData := ` + 2020-01-01T00:00:00Z + 2020-01-02T00:00:00Z +` + + var ki KeyInfo + if err := xml.Unmarshal([]byte(xmlData), &ki); err != nil { + t.Fatal(err) + } + + assertEqual(t, "Start", *ki.Start, "2020-01-01T00:00:00Z") + assertEqual(t, "Expiry", *ki.Expiry, "2020-01-02T00:00:00Z") + + // Round-trip + out, err := xml.Marshal(ki) + if err != nil { + t.Fatal(err) + } + var ki2 KeyInfo + if err := xml.Unmarshal(out, &ki2); err != nil { + t.Fatal(err) + } + assertEqual(t, "round-trip Start", *ki2.Start, "2020-01-01T00:00:00Z") + assertEqual(t, "round-trip Expiry", *ki2.Expiry, "2020-01-02T00:00:00Z") +} + +// TestQueryRequestRoundTrip tests marshal/unmarshal of QueryRequest. +func TestQueryRequestRoundTrip(t *testing.T) { + queryType := QueryRequestType("SQL") + qr := QueryRequest{ + QueryType: &queryType, + Expression: to.Ptr("SELECT * FROM BlobStorage"), + } + + data, err := xml.Marshal(qr) //nolint:staticcheck // we use custom helper for map[string]any + if err != nil { + t.Fatal(err) + } + + var qr2 QueryRequest + if err := xml.Unmarshal(data, &qr2); err != nil { + t.Fatal(err) + } + + assertEqual(t, "QueryType", string(*qr2.QueryType), "SQL") + assertEqual(t, "Expression", *qr2.Expression, "SELECT * FROM BlobStorage") +} + +// TestJSONTextConfigurationMarshalElementName tests that JSONTextConfiguration.MarshalXML +// produces the correct element name "JsonTextConfiguration". +func TestJSONTextConfigurationMarshalElementName(t *testing.T) { + jtc := JSONTextConfiguration{ + RecordSeparator: to.Ptr("\n"), + } + + data, err := xml.Marshal(jtc) + if err != nil { + t.Fatal(err) + } + + // Verify the element name is "JsonTextConfiguration", not "JSONTextConfiguration" + xmlStr := string(data) + if !strings.Contains(xmlStr, "") { + t.Fatalf("expected element name JsonTextConfiguration, got: %s", xmlStr) + } + + // Round-trip via QueryFormat which embeds JSONTextConfiguration + formatType := QueryFormatType("json") + qf := QueryFormat{ + Type: &formatType, + JSONTextConfiguration: &jtc, + } + + data, err = xml.Marshal(qf) //nolint:staticcheck // we use custom helper for map[string]any + if err != nil { + t.Fatal(err) + } + + var qf2 QueryFormat + if err := xml.Unmarshal(data, &qf2); err != nil { + t.Fatal(err) + } + assertEqual(t, "QueryFormat.Type", string(*qf2.Type), "json") + if qf2.JSONTextConfiguration == nil { + t.Fatal("JSONTextConfiguration is nil after round-trip") + } + assertEqual(t, "RecordSeparator", *qf2.JSONTextConfiguration.RecordSeparator, "\n") +} + +func assertEqual[T comparable](t *testing.T, name string, got, want T) { + t.Helper() + if got != want { + t.Fatalf("%s: got %v, want %v", name, got, want) + } +} + +func assertNotContains(t *testing.T, context, xmlStr, forbidden string) { + t.Helper() + if strings.Contains(xmlStr, forbidden) { + t.Fatalf("%s: XML should not contain %q, got: %s", context, forbidden, xmlStr) + } +} diff --git a/test/local/azblob/testdata/_metadata.json b/test/local/azblob/testdata/_metadata.json new file mode 100644 index 000000000000..52e9a9ebcb1a --- /dev/null +++ b/test/local/azblob/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Storage.Blob": "2026-06-06" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/local/azblob/zz_appendblob_client.go b/test/local/azblob/zz_appendblob_client.go new file mode 100644 index 000000000000..70d7c2bab92a --- /dev/null +++ b/test/local/azblob/zz_appendblob_client.go @@ -0,0 +1,646 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azblob + +import ( + "context" + "encoding/base64" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "io" + "net/http" + "strconv" + "strings" + "time" +) + +// AppendBlobClient contains the methods for the AppendBlob group. +// Don't use this type directly, use a constructor function instead. +// +// Generated from API version 2026-06-06 +type AppendBlobClient struct { + internal *azcore.Client + url string +} + +// AppendBlock - Uploads a new block of data to the end of an append blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - body - The body of the request. +// - contentLength - The length of the request. +// - options - AppendBlobClientAppendBlockOptions contains the optional parameters for the AppendBlobClient.AppendBlock method. +func (client *AppendBlobClient) AppendBlock(ctx context.Context, body io.ReadSeekCloser, contentLength int64, options *AppendBlobClientAppendBlockOptions) (AppendBlobClientAppendBlockResponse, error) { + var err error + req, err := client.appendBlockCreateRequest(ctx, body, contentLength, options) + if err != nil { + return AppendBlobClientAppendBlockResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AppendBlobClientAppendBlockResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return AppendBlobClientAppendBlockResponse{}, err + } + resp, err := client.appendBlockHandleResponse(httpResp) + return resp, err +} + +// appendBlockCreateRequest creates the AppendBlock request. +func (client *AppendBlobClient) appendBlockCreateRequest(ctx context.Context, body io.ReadSeekCloser, contentLength int64, options *AppendBlobClientAppendBlockOptions) (*policy.Request, error) { + urlPath := "?comp=appendblock" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Content-Length"] = []string{strconv.FormatInt(contentLength, 10)} + if options != nil && options.TransactionalContentMD5 != nil { + req.Raw().Header["Content-MD5"] = []string{base64.StdEncoding.EncodeToString(options.TransactionalContentMD5)} + } + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.AppendPosition != nil { + req.Raw().Header["x-ms-blob-condition-appendpos"] = []string{strconv.FormatInt(*options.AppendPosition, 10)} + } + if options != nil && options.MaxSize != nil { + req.Raw().Header["x-ms-blob-condition-maxsize"] = []string{strconv.FormatInt(*options.MaxSize, 10)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.TransactionalContentCRC64 != nil { + req.Raw().Header["x-ms-content-crc64"] = []string{base64.StdEncoding.EncodeToString(options.TransactionalContentCRC64)} + } + if options != nil && options.EncryptionAlgorithm != nil { + req.Raw().Header["x-ms-encryption-algorithm"] = []string{string(*options.EncryptionAlgorithm)} + } + if options != nil && options.EncryptionKey != nil { + req.Raw().Header["x-ms-encryption-key"] = []string{*options.EncryptionKey} + } + if options != nil && options.EncryptionKeySHA256 != nil { + req.Raw().Header["x-ms-encryption-key-sha256"] = []string{*options.EncryptionKeySHA256} + } + if options != nil && options.EncryptionScope != nil { + req.Raw().Header["x-ms-encryption-scope"] = []string{*options.EncryptionScope} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + if options != nil && options.StructuredBodyType != nil { + req.Raw().Header["x-ms-structured-body"] = []string{*options.StructuredBodyType} + } + if options != nil && options.StructuredContentLength != nil { + req.Raw().Header["x-ms-structured-content-length"] = []string{strconv.FormatInt(*options.StructuredContentLength, 10)} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + req.Raw().Header["Content-Type"] = []string{"application/octet-stream"} + if err := req.SetBody(body, "application/octet-stream"); err != nil { + return nil, err + } + return req, nil +} + +// appendBlockHandleResponse handles the AppendBlock response. +func (client *AppendBlobClient) appendBlockHandleResponse(resp *http.Response) (AppendBlobClientAppendBlockResponse, error) { + result := AppendBlobClientAppendBlockResponse{} + if val := resp.Header.Get("x-ms-blob-append-offset"); val != "" { + result.BlobAppendOffset = &val + } + if val := resp.Header.Get("x-ms-blob-committed-block-count"); val != "" { + blobCommittedBlockCount32, err := strconv.ParseInt(val, 10, 32) + blobCommittedBlockCount := int32(blobCommittedBlockCount32) + if err != nil { + return AppendBlobClientAppendBlockResponse{}, err + } + result.BlobCommittedBlockCount = &blobCommittedBlockCount + } + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("x-ms-content-crc64"); val != "" { + contentCRC64, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return AppendBlobClientAppendBlockResponse{}, err + } + result.ContentCRC64 = contentCRC64 + } + if val := resp.Header.Get("Content-MD5"); val != "" { + contentMD5, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return AppendBlobClientAppendBlockResponse{}, err + } + result.ContentMD5 = contentMD5 + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return AppendBlobClientAppendBlockResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("x-ms-encryption-key-sha256"); val != "" { + result.EncryptionKeySHA256 = &val + } + if val := resp.Header.Get("x-ms-encryption-scope"); val != "" { + result.EncryptionScope = &val + } + if val := resp.Header.Get("x-ms-request-server-encrypted"); val != "" { + isServerEncrypted, err := strconv.ParseBool(val) + if err != nil { + return AppendBlobClientAppendBlockResponse{}, err + } + result.IsServerEncrypted = &isServerEncrypted + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return AppendBlobClientAppendBlockResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-structured-body"); val != "" { + result.StructuredBodyType = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// AppendBlockFromURL - Uploads a new block of data from the specified URL to the end of an append blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - sourceURL - Specifies the URL of the source. +// - contentLength - The length of the request. +// - options - AppendBlobClientAppendBlockFromURLOptions contains the optional parameters for the AppendBlobClient.AppendBlockFromURL +// method. +func (client *AppendBlobClient) AppendBlockFromURL(ctx context.Context, sourceURL string, contentLength int64, options *AppendBlobClientAppendBlockFromURLOptions) (AppendBlobClientAppendBlockFromURLResponse, error) { + var err error + req, err := client.appendBlockFromURLCreateRequest(ctx, sourceURL, contentLength, options) + if err != nil { + return AppendBlobClientAppendBlockFromURLResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AppendBlobClientAppendBlockFromURLResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return AppendBlobClientAppendBlockFromURLResponse{}, err + } + resp, err := client.appendBlockFromURLHandleResponse(httpResp) + return resp, err +} + +// appendBlockFromURLCreateRequest creates the AppendBlockFromURL request. +func (client *AppendBlobClient) appendBlockFromURLCreateRequest(ctx context.Context, sourceURL string, contentLength int64, options *AppendBlobClientAppendBlockFromURLOptions) (*policy.Request, error) { + urlPath := "?comp=appendblock" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Content-Length"] = []string{strconv.FormatInt(contentLength, 10)} + if options != nil && options.TransactionalContentMD5 != nil { + req.Raw().Header["Content-MD5"] = []string{base64.StdEncoding.EncodeToString(options.TransactionalContentMD5)} + } + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.AppendPosition != nil { + req.Raw().Header["x-ms-blob-condition-appendpos"] = []string{strconv.FormatInt(*options.AppendPosition, 10)} + } + if options != nil && options.MaxSize != nil { + req.Raw().Header["x-ms-blob-condition-maxsize"] = []string{strconv.FormatInt(*options.MaxSize, 10)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-copy-source"] = []string{sourceURL} + if options != nil && options.CopySourceAuthorization != nil { + req.Raw().Header["x-ms-copy-source-authorization"] = []string{*options.CopySourceAuthorization} + } + if options != nil && options.EncryptionAlgorithm != nil { + req.Raw().Header["x-ms-encryption-algorithm"] = []string{string(*options.EncryptionAlgorithm)} + } + if options != nil && options.EncryptionKey != nil { + req.Raw().Header["x-ms-encryption-key"] = []string{*options.EncryptionKey} + } + if options != nil && options.EncryptionKeySHA256 != nil { + req.Raw().Header["x-ms-encryption-key-sha256"] = []string{*options.EncryptionKeySHA256} + } + if options != nil && options.EncryptionScope != nil { + req.Raw().Header["x-ms-encryption-scope"] = []string{*options.EncryptionScope} + } + if options != nil && options.FileRequestIntent != nil { + req.Raw().Header["x-ms-file-request-intent"] = []string{string(*options.FileRequestIntent)} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + if options != nil && options.SourceContentCRC64 != nil { + req.Raw().Header["x-ms-source-content-crc64"] = []string{base64.StdEncoding.EncodeToString(options.SourceContentCRC64)} + } + if options != nil && options.SourceContentMD5 != nil { + req.Raw().Header["x-ms-source-content-md5"] = []string{base64.StdEncoding.EncodeToString(options.SourceContentMD5)} + } + if options != nil && options.SourceEncryptionAlgorithm != nil { + req.Raw().Header["x-ms-source-encryption-algorithm"] = []string{string(*options.SourceEncryptionAlgorithm)} + } + if options != nil && options.SourceEncryptionKey != nil { + req.Raw().Header["x-ms-source-encryption-key"] = []string{*options.SourceEncryptionKey} + } + if options != nil && options.SourceEncryptionKeySHA256 != nil { + req.Raw().Header["x-ms-source-encryption-key-sha256"] = []string{*options.SourceEncryptionKeySHA256} + } + if options != nil && options.SourceIfMatch != nil { + req.Raw().Header["x-ms-source-if-match"] = []string{string(*options.SourceIfMatch)} + } + if options != nil && options.SourceIfModifiedSince != nil { + req.Raw().Header["x-ms-source-if-modified-since"] = []string{datetime.RFC7231(*options.SourceIfModifiedSince).String()} + } + if options != nil && options.SourceIfNoneMatch != nil { + req.Raw().Header["x-ms-source-if-none-match"] = []string{string(*options.SourceIfNoneMatch)} + } + if options != nil && options.SourceIfUnmodifiedSince != nil { + req.Raw().Header["x-ms-source-if-unmodified-since"] = []string{datetime.RFC7231(*options.SourceIfUnmodifiedSince).String()} + } + if options != nil && options.SourceRange != nil { + req.Raw().Header["x-ms-source-range"] = []string{*options.SourceRange} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// appendBlockFromURLHandleResponse handles the AppendBlockFromURL response. +func (client *AppendBlobClient) appendBlockFromURLHandleResponse(resp *http.Response) (AppendBlobClientAppendBlockFromURLResponse, error) { + result := AppendBlobClientAppendBlockFromURLResponse{} + if val := resp.Header.Get("x-ms-blob-append-offset"); val != "" { + result.BlobAppendOffset = &val + } + if val := resp.Header.Get("x-ms-blob-committed-block-count"); val != "" { + blobCommittedBlockCount32, err := strconv.ParseInt(val, 10, 32) + blobCommittedBlockCount := int32(blobCommittedBlockCount32) + if err != nil { + return AppendBlobClientAppendBlockFromURLResponse{}, err + } + result.BlobCommittedBlockCount = &blobCommittedBlockCount + } + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("x-ms-content-crc64"); val != "" { + contentCRC64, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return AppendBlobClientAppendBlockFromURLResponse{}, err + } + result.ContentCRC64 = contentCRC64 + } + if val := resp.Header.Get("Content-MD5"); val != "" { + contentMD5, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return AppendBlobClientAppendBlockFromURLResponse{}, err + } + result.ContentMD5 = contentMD5 + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return AppendBlobClientAppendBlockFromURLResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("x-ms-encryption-key-sha256"); val != "" { + result.EncryptionKeySHA256 = &val + } + if val := resp.Header.Get("x-ms-encryption-scope"); val != "" { + result.EncryptionScope = &val + } + if val := resp.Header.Get("x-ms-request-server-encrypted"); val != "" { + isServerEncrypted, err := strconv.ParseBool(val) + if err != nil { + return AppendBlobClientAppendBlockFromURLResponse{}, err + } + result.IsServerEncrypted = &isServerEncrypted + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return AppendBlobClientAppendBlockFromURLResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// Create - Creates a new append blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - AppendBlobClientCreateOptions contains the optional parameters for the AppendBlobClient.Create method. +func (client *AppendBlobClient) Create(ctx context.Context, options *AppendBlobClientCreateOptions) (AppendBlobClientCreateResponse, error) { + var err error + req, err := client.createCreateRequest(ctx, options) + if err != nil { + return AppendBlobClientCreateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AppendBlobClientCreateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return AppendBlobClientCreateResponse{}, err + } + resp, err := client.createHandleResponse(httpResp) + return resp, err +} + +// createCreateRequest creates the Create request. +func (client *AppendBlobClient) createCreateRequest(ctx context.Context, options *AppendBlobClientCreateOptions) (*policy.Request, error) { + req, err := runtime.NewRequest(ctx, http.MethodPut, client.url) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Content-Length"] = []string{"0"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.BlobCacheControl != nil { + req.Raw().Header["x-ms-blob-cache-control"] = []string{*options.BlobCacheControl} + } + if options != nil && options.BlobContentDisposition != nil { + req.Raw().Header["x-ms-blob-content-disposition"] = []string{*options.BlobContentDisposition} + } + if options != nil && options.BlobContentEncoding != nil { + req.Raw().Header["x-ms-blob-content-encoding"] = []string{*options.BlobContentEncoding} + } + if options != nil && options.BlobContentLanguage != nil { + req.Raw().Header["x-ms-blob-content-language"] = []string{*options.BlobContentLanguage} + } + if options != nil && options.BlobContentMD5 != nil { + req.Raw().Header["x-ms-blob-content-md5"] = []string{base64.StdEncoding.EncodeToString(options.BlobContentMD5)} + } + if options != nil && options.BlobContentType != nil { + req.Raw().Header["x-ms-blob-content-type"] = []string{*options.BlobContentType} + } + req.Raw().Header["x-ms-blob-type"] = []string{"AppendBlob"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.EncryptionAlgorithm != nil { + req.Raw().Header["x-ms-encryption-algorithm"] = []string{string(*options.EncryptionAlgorithm)} + } + if options != nil && options.EncryptionKey != nil { + req.Raw().Header["x-ms-encryption-key"] = []string{*options.EncryptionKey} + } + if options != nil && options.EncryptionKeySHA256 != nil { + req.Raw().Header["x-ms-encryption-key-sha256"] = []string{*options.EncryptionKeySHA256} + } + if options != nil && options.EncryptionScope != nil { + req.Raw().Header["x-ms-encryption-scope"] = []string{*options.EncryptionScope} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + if options != nil && options.ImmutabilityPolicyMode != nil { + req.Raw().Header["x-ms-immutability-policy-mode"] = []string{string(*options.ImmutabilityPolicyMode)} + } + if options != nil && options.ImmutabilityPolicyExpiry != nil { + req.Raw().Header["x-ms-immutability-policy-until-date"] = []string{datetime.RFC7231(*options.ImmutabilityPolicyExpiry).String()} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + if options != nil && options.LegalHold != nil { + req.Raw().Header["x-ms-legal-hold"] = []string{strconv.FormatBool(*options.LegalHold)} + } + if options != nil && options.Metadata != nil { + for k, v := range options.Metadata { + if v != nil { + req.Raw().Header["x-ms-meta-"+k] = []string{*v} + } + } + } + if options != nil && options.BlobTagsString != nil { + req.Raw().Header["x-ms-tags"] = []string{*options.BlobTagsString} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// createHandleResponse handles the Create response. +func (client *AppendBlobClient) createHandleResponse(resp *http.Response) (AppendBlobClientCreateResponse, error) { + result := AppendBlobClientCreateResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Content-MD5"); val != "" { + contentMD5, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return AppendBlobClientCreateResponse{}, err + } + result.ContentMD5 = contentMD5 + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return AppendBlobClientCreateResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("x-ms-encryption-key-sha256"); val != "" { + result.EncryptionKeySHA256 = &val + } + if val := resp.Header.Get("x-ms-encryption-scope"); val != "" { + result.EncryptionScope = &val + } + if val := resp.Header.Get("x-ms-request-server-encrypted"); val != "" { + isServerEncrypted, err := strconv.ParseBool(val) + if err != nil { + return AppendBlobClientCreateResponse{}, err + } + result.IsServerEncrypted = &isServerEncrypted + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return AppendBlobClientCreateResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + if val := resp.Header.Get("x-ms-version-id"); val != "" { + result.VersionID = &val + } + return result, nil +} + +// Seal - Seals the append blob to make it read-only. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - AppendBlobClientSealOptions contains the optional parameters for the AppendBlobClient.Seal method. +func (client *AppendBlobClient) Seal(ctx context.Context, options *AppendBlobClientSealOptions) (AppendBlobClientSealResponse, error) { + var err error + req, err := client.sealCreateRequest(ctx, options) + if err != nil { + return AppendBlobClientSealResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return AppendBlobClientSealResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return AppendBlobClientSealResponse{}, err + } + resp, err := client.sealHandleResponse(httpResp) + return resp, err +} + +// sealCreateRequest creates the Seal request. +func (client *AppendBlobClient) sealCreateRequest(ctx context.Context, options *AppendBlobClientSealOptions) (*policy.Request, error) { + urlPath := "?comp=seal" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.AppendPosition != nil { + req.Raw().Header["x-ms-blob-condition-appendpos"] = []string{strconv.FormatInt(*options.AppendPosition, 10)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// sealHandleResponse handles the Seal response. +func (client *AppendBlobClient) sealHandleResponse(resp *http.Response) (AppendBlobClientSealResponse, error) { + result := AppendBlobClientSealResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return AppendBlobClientSealResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("x-ms-blob-sealed"); val != "" { + isSealed, err := strconv.ParseBool(val) + if err != nil { + return AppendBlobClientSealResponse{}, err + } + result.IsSealed = &isSealed + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return AppendBlobClientSealResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} diff --git a/test/local/azblob/zz_blockblob_client.go b/test/local/azblob/zz_blockblob_client.go new file mode 100644 index 000000000000..16fdf0f1ec82 --- /dev/null +++ b/test/local/azblob/zz_blockblob_client.go @@ -0,0 +1,1211 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azblob + +import ( + "context" + "encoding/base64" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "io" + "net/http" + "strconv" + "strings" + "time" +) + +// BlockBlobClient contains the methods for the BlockBlob group. +// Don't use this type directly, use a constructor function instead. +// +// Generated from API version 2026-06-06 +type BlockBlobClient struct { + internal *azcore.Client + url string +} + +// CommitBlockList - Writes to the block blob by specifying the list of block IDs that make up the blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - blocks - Blob blocks. +// - options - BlockBlobClientCommitBlockListOptions contains the optional parameters for the BlockBlobClient.CommitBlockList +// method. +func (client *BlockBlobClient) CommitBlockList(ctx context.Context, blocks BlockLookupList, options *BlockBlobClientCommitBlockListOptions) (BlockBlobClientCommitBlockListResponse, error) { + var err error + req, err := client.commitBlockListCreateRequest(ctx, blocks, options) + if err != nil { + return BlockBlobClientCommitBlockListResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BlockBlobClientCommitBlockListResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return BlockBlobClientCommitBlockListResponse{}, err + } + resp, err := client.commitBlockListHandleResponse(httpResp) + return resp, err +} + +// commitBlockListCreateRequest creates the CommitBlockList request. +func (client *BlockBlobClient) commitBlockListCreateRequest(ctx context.Context, blocks BlockLookupList, options *BlockBlobClientCommitBlockListOptions) (*policy.Request, error) { + urlPath := "?comp=blocklist" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.TransactionalContentMD5 != nil { + req.Raw().Header["Content-MD5"] = []string{base64.StdEncoding.EncodeToString(options.TransactionalContentMD5)} + } + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.Tier != nil { + req.Raw().Header["x-ms-access-tier"] = []string{string(*options.Tier)} + } + if options != nil && options.BlobCacheControl != nil { + req.Raw().Header["x-ms-blob-cache-control"] = []string{*options.BlobCacheControl} + } + if options != nil && options.BlobContentDisposition != nil { + req.Raw().Header["x-ms-blob-content-disposition"] = []string{*options.BlobContentDisposition} + } + if options != nil && options.BlobContentEncoding != nil { + req.Raw().Header["x-ms-blob-content-encoding"] = []string{*options.BlobContentEncoding} + } + if options != nil && options.BlobContentLanguage != nil { + req.Raw().Header["x-ms-blob-content-language"] = []string{*options.BlobContentLanguage} + } + if options != nil && options.BlobContentMD5 != nil { + req.Raw().Header["x-ms-blob-content-md5"] = []string{base64.StdEncoding.EncodeToString(options.BlobContentMD5)} + } + if options != nil && options.BlobContentType != nil { + req.Raw().Header["x-ms-blob-content-type"] = []string{*options.BlobContentType} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.TransactionalContentCRC64 != nil { + req.Raw().Header["x-ms-content-crc64"] = []string{base64.StdEncoding.EncodeToString(options.TransactionalContentCRC64)} + } + if options != nil && options.EncryptionAlgorithm != nil { + req.Raw().Header["x-ms-encryption-algorithm"] = []string{string(*options.EncryptionAlgorithm)} + } + if options != nil && options.EncryptionKey != nil { + req.Raw().Header["x-ms-encryption-key"] = []string{*options.EncryptionKey} + } + if options != nil && options.EncryptionKeySHA256 != nil { + req.Raw().Header["x-ms-encryption-key-sha256"] = []string{*options.EncryptionKeySHA256} + } + if options != nil && options.EncryptionScope != nil { + req.Raw().Header["x-ms-encryption-scope"] = []string{*options.EncryptionScope} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + if options != nil && options.ImmutabilityPolicyMode != nil { + req.Raw().Header["x-ms-immutability-policy-mode"] = []string{string(*options.ImmutabilityPolicyMode)} + } + if options != nil && options.ImmutabilityPolicyExpiry != nil { + req.Raw().Header["x-ms-immutability-policy-until-date"] = []string{datetime.RFC7231(*options.ImmutabilityPolicyExpiry).String()} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + if options != nil && options.LegalHold != nil { + req.Raw().Header["x-ms-legal-hold"] = []string{strconv.FormatBool(*options.LegalHold)} + } + if options != nil && options.Metadata != nil { + for k, v := range options.Metadata { + if v != nil { + req.Raw().Header["x-ms-meta-"+k] = []string{*v} + } + } + } + if options != nil && options.BlobTagsString != nil { + req.Raw().Header["x-ms-tags"] = []string{*options.BlobTagsString} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, blocks); err != nil { + return nil, err + } + return req, nil +} + +// commitBlockListHandleResponse handles the CommitBlockList response. +func (client *BlockBlobClient) commitBlockListHandleResponse(resp *http.Response) (BlockBlobClientCommitBlockListResponse, error) { + result := BlockBlobClientCommitBlockListResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("x-ms-content-crc64"); val != "" { + contentCRC64, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return BlockBlobClientCommitBlockListResponse{}, err + } + result.ContentCRC64 = contentCRC64 + } + if val := resp.Header.Get("Content-MD5"); val != "" { + contentMD5, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return BlockBlobClientCommitBlockListResponse{}, err + } + result.ContentMD5 = contentMD5 + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return BlockBlobClientCommitBlockListResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("x-ms-encryption-key-sha256"); val != "" { + result.EncryptionKeySHA256 = &val + } + if val := resp.Header.Get("x-ms-encryption-scope"); val != "" { + result.EncryptionScope = &val + } + if val := resp.Header.Get("x-ms-request-server-encrypted"); val != "" { + isServerEncrypted, err := strconv.ParseBool(val) + if err != nil { + return BlockBlobClientCommitBlockListResponse{}, err + } + result.IsServerEncrypted = &isServerEncrypted + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return BlockBlobClientCommitBlockListResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + if val := resp.Header.Get("x-ms-version-id"); val != "" { + result.VersionID = &val + } + return result, nil +} + +// GetBlockList - Retrieves the list of blocks that have been uploaded as part of the block blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - listType - Specifies whether to return the list of committed blocks, the list of uncommitted blocks, or both lists together. +// - options - BlockBlobClientGetBlockListOptions contains the optional parameters for the BlockBlobClient.GetBlockList method. +func (client *BlockBlobClient) GetBlockList(ctx context.Context, listType BlockListType, options *BlockBlobClientGetBlockListOptions) (BlockBlobClientGetBlockListResponse, error) { + var err error + req, err := client.getBlockListCreateRequest(ctx, listType, options) + if err != nil { + return BlockBlobClientGetBlockListResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BlockBlobClientGetBlockListResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BlockBlobClientGetBlockListResponse{}, err + } + resp, err := client.getBlockListHandleResponse(httpResp) + return resp, err +} + +// getBlockListCreateRequest creates the GetBlockList request. +func (client *BlockBlobClient) getBlockListCreateRequest(ctx context.Context, listType BlockListType, options *BlockBlobClientGetBlockListOptions) (*policy.Request, error) { + urlPath := "?comp=blocklist" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("blocklisttype", string(listType)) + if options != nil && options.Snapshot != nil { + reqQP.Set("snapshot", *options.Snapshot) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/xml"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// getBlockListHandleResponse handles the GetBlockList response. +func (client *BlockBlobClient) getBlockListHandleResponse(resp *http.Response) (BlockBlobClientGetBlockListResponse, error) { + result := BlockBlobClientGetBlockListResponse{} + if val := resp.Header.Get("x-ms-blob-content-length"); val != "" { + blobContentLength, err := strconv.ParseInt(val, 10, 64) + if err != nil { + return BlockBlobClientGetBlockListResponse{}, err + } + result.BlobContentLength = &blobContentLength + } + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return BlockBlobClientGetBlockListResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return BlockBlobClientGetBlockListResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + if err := runtime.UnmarshalAsXML(resp, &result.BlockList); err != nil { + return BlockBlobClientGetBlockListResponse{}, err + } + return result, nil +} + +// Query - Queries the data of the specified blob with the provided query expressions. +// If the operation fails it returns an *azcore.ResponseError type. +// - queryRequest - The query request. +// - options - BlockBlobClientQueryOptions contains the optional parameters for the BlockBlobClient.Query method. +func (client *BlockBlobClient) Query(ctx context.Context, queryRequest QueryRequest, options *BlockBlobClientQueryOptions) (BlockBlobClientQueryResponse, error) { + var err error + req, err := client.queryCreateRequest(ctx, queryRequest, options) + if err != nil { + return BlockBlobClientQueryResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BlockBlobClientQueryResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusPartialContent) { + err = runtime.NewResponseError(httpResp) + return BlockBlobClientQueryResponse{}, err + } + resp, err := client.queryHandleResponse(httpResp) + return resp, err +} + +// queryCreateRequest creates the Query request. +func (client *BlockBlobClient) queryCreateRequest(ctx context.Context, queryRequest QueryRequest, options *BlockBlobClientQueryOptions) (*policy.Request, error) { + urlPath := "?comp=query" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Snapshot != nil { + reqQP.Set("snapshot", *options.Snapshot) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + runtime.SkipBodyDownload(req) + req.Raw().Header["Accept"] = []string{"application/octet-stream"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.EncryptionAlgorithm != nil { + req.Raw().Header["x-ms-encryption-algorithm"] = []string{string(*options.EncryptionAlgorithm)} + } + if options != nil && options.EncryptionKey != nil { + req.Raw().Header["x-ms-encryption-key"] = []string{*options.EncryptionKey} + } + if options != nil && options.EncryptionKeySHA256 != nil { + req.Raw().Header["x-ms-encryption-key-sha256"] = []string{*options.EncryptionKeySHA256} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, queryRequest); err != nil { + return nil, err + } + return req, nil +} + +// queryHandleResponse handles the Query response. +func (client *BlockBlobClient) queryHandleResponse(resp *http.Response) (BlockBlobClientQueryResponse, error) { + result := BlockBlobClientQueryResponse{Body: resp.Body} + if val := resp.Header.Get("Accept-Ranges"); val != "" { + result.AcceptRanges = &val + } + if val := resp.Header.Get("x-ms-blob-committed-block-count"); val != "" { + blobCommittedBlockCount32, err := strconv.ParseInt(val, 10, 32) + blobCommittedBlockCount := int32(blobCommittedBlockCount32) + if err != nil { + return BlockBlobClientQueryResponse{}, err + } + result.BlobCommittedBlockCount = &blobCommittedBlockCount + } + if val := resp.Header.Get("x-ms-blob-content-md5"); val != "" { + blobContentMD5, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return BlockBlobClientQueryResponse{}, err + } + result.BlobContentMD5 = blobContentMD5 + } + if val := resp.Header.Get("x-ms-blob-sequence-number"); val != "" { + blobSequenceNumber, err := strconv.ParseInt(val, 10, 64) + if err != nil { + return BlockBlobClientQueryResponse{}, err + } + result.BlobSequenceNumber = &blobSequenceNumber + } + if val := resp.Header.Get("x-ms-blob-type"); val != "" { + result.BlobType = (*Type)(&val) + } + if val := resp.Header.Get("Cache-Control"); val != "" { + result.CacheControl = &val + } + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("x-ms-content-crc64"); val != "" { + contentCRC64, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return BlockBlobClientQueryResponse{}, err + } + result.ContentCRC64 = contentCRC64 + } + if val := resp.Header.Get("Content-Disposition"); val != "" { + result.ContentDisposition = &val + } + if val := resp.Header.Get("Content-Encoding"); val != "" { + result.ContentEncoding = &val + } + if val := resp.Header.Get("Content-Language"); val != "" { + result.ContentLanguage = &val + } + if val := resp.Header.Get("Content-Length"); val != "" { + contentLength, err := strconv.ParseInt(val, 10, 64) + if err != nil { + return BlockBlobClientQueryResponse{}, err + } + result.ContentLength = &contentLength + } + if val := resp.Header.Get("Content-MD5"); val != "" { + contentMD5, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return BlockBlobClientQueryResponse{}, err + } + result.ContentMD5 = contentMD5 + } + if val := resp.Header.Get("Content-Range"); val != "" { + result.ContentRange = &val + } + if val := resp.Header.Get("Content-Type"); val != "" { + result.ContentType = &val + } + if val := resp.Header.Get("x-ms-copy-completion-time"); val != "" { + copyCompletionTime, err := time.Parse(time.RFC1123, val) + if err != nil { + return BlockBlobClientQueryResponse{}, err + } + result.CopyCompletionTime = ©CompletionTime + } + if val := resp.Header.Get("x-ms-copy-id"); val != "" { + result.CopyID = &val + } + if val := resp.Header.Get("x-ms-copy-progress"); val != "" { + result.CopyProgress = &val + } + if val := resp.Header.Get("x-ms-copy-source"); val != "" { + result.CopySource = &val + } + if val := resp.Header.Get("x-ms-copy-status"); val != "" { + result.CopyStatus = (*CopyStatusType)(&val) + } + if val := resp.Header.Get("x-ms-copy-status-description"); val != "" { + result.CopyStatusDescription = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return BlockBlobClientQueryResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("x-ms-encryption-key-sha256"); val != "" { + result.EncryptionKeySHA256 = &val + } + if val := resp.Header.Get("x-ms-encryption-scope"); val != "" { + result.EncryptionScope = &val + } + if val := resp.Header.Get("x-ms-server-encrypted"); val != "" { + isServerEncrypted, err := strconv.ParseBool(val) + if err != nil { + return BlockBlobClientQueryResponse{}, err + } + result.IsServerEncrypted = &isServerEncrypted + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return BlockBlobClientQueryResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-lease-duration"); val != "" { + result.LeaseDuration = (*LeaseDurationType)(&val) + } + if val := resp.Header.Get("x-ms-lease-state"); val != "" { + result.LeaseState = (*LeaseStateType)(&val) + } + if val := resp.Header.Get("x-ms-lease-status"); val != "" { + result.LeaseStatus = (*LeaseStatusType)(&val) + } + for hh := range resp.Header { + if len(hh) > len("x-ms-meta-") && strings.EqualFold(hh[:len("x-ms-meta-")], "x-ms-meta-") { + if result.Metadata == nil { + result.Metadata = map[string]*string{} + } + result.Metadata[hh[len("x-ms-meta-"):]] = to.Ptr(resp.Header.Get(hh)) + } + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// StageBlock - Creates a new block of data to be committed as part of a blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - blockID - A Base64 value that identifies the block. Prior to encoding, the string must be less than or equal to 64 bytes +// in size. For a given blob, the length of the value specified for the blockid parameter must be the same size for each block. +// - contentLength - The length of the request. +// - body - The body of the request. +// - options - BlockBlobClientStageBlockOptions contains the optional parameters for the BlockBlobClient.StageBlock method. +func (client *BlockBlobClient) StageBlock(ctx context.Context, blockID string, contentLength int64, body io.ReadSeekCloser, options *BlockBlobClientStageBlockOptions) (BlockBlobClientStageBlockResponse, error) { + var err error + req, err := client.stageBlockCreateRequest(ctx, blockID, contentLength, body, options) + if err != nil { + return BlockBlobClientStageBlockResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BlockBlobClientStageBlockResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return BlockBlobClientStageBlockResponse{}, err + } + resp, err := client.stageBlockHandleResponse(httpResp) + return resp, err +} + +// stageBlockCreateRequest creates the StageBlock request. +func (client *BlockBlobClient) stageBlockCreateRequest(ctx context.Context, blockID string, contentLength int64, body io.ReadSeekCloser, options *BlockBlobClientStageBlockOptions) (*policy.Request, error) { + urlPath := "?comp=block" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("blockid", blockID) + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Content-Length"] = []string{strconv.FormatInt(contentLength, 10)} + if options != nil && options.TransactionalContentMD5 != nil { + req.Raw().Header["Content-MD5"] = []string{base64.StdEncoding.EncodeToString(options.TransactionalContentMD5)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.TransactionalContentCRC64 != nil { + req.Raw().Header["x-ms-content-crc64"] = []string{base64.StdEncoding.EncodeToString(options.TransactionalContentCRC64)} + } + if options != nil && options.EncryptionAlgorithm != nil { + req.Raw().Header["x-ms-encryption-algorithm"] = []string{string(*options.EncryptionAlgorithm)} + } + if options != nil && options.EncryptionKey != nil { + req.Raw().Header["x-ms-encryption-key"] = []string{*options.EncryptionKey} + } + if options != nil && options.EncryptionKeySHA256 != nil { + req.Raw().Header["x-ms-encryption-key-sha256"] = []string{*options.EncryptionKeySHA256} + } + if options != nil && options.EncryptionScope != nil { + req.Raw().Header["x-ms-encryption-scope"] = []string{*options.EncryptionScope} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + if options != nil && options.StructuredBodyType != nil { + req.Raw().Header["x-ms-structured-body"] = []string{*options.StructuredBodyType} + } + if options != nil && options.StructuredContentLength != nil { + req.Raw().Header["x-ms-structured-content-length"] = []string{strconv.FormatInt(*options.StructuredContentLength, 10)} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + req.Raw().Header["Content-Type"] = []string{"application/octet-stream"} + if err := req.SetBody(body, "application/octet-stream"); err != nil { + return nil, err + } + return req, nil +} + +// stageBlockHandleResponse handles the StageBlock response. +func (client *BlockBlobClient) stageBlockHandleResponse(resp *http.Response) (BlockBlobClientStageBlockResponse, error) { + result := BlockBlobClientStageBlockResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("x-ms-content-crc64"); val != "" { + contentCRC64, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return BlockBlobClientStageBlockResponse{}, err + } + result.ContentCRC64 = contentCRC64 + } + if val := resp.Header.Get("Content-MD5"); val != "" { + contentMD5, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return BlockBlobClientStageBlockResponse{}, err + } + result.ContentMD5 = contentMD5 + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return BlockBlobClientStageBlockResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-encryption-key-sha256"); val != "" { + result.EncryptionKeySHA256 = &val + } + if val := resp.Header.Get("x-ms-encryption-scope"); val != "" { + result.EncryptionScope = &val + } + if val := resp.Header.Get("x-ms-request-server-encrypted"); val != "" { + isServerEncrypted, err := strconv.ParseBool(val) + if err != nil { + return BlockBlobClientStageBlockResponse{}, err + } + result.IsServerEncrypted = &isServerEncrypted + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-structured-body"); val != "" { + result.StructuredBodyType = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// StageBlockFromURL - Creates a new block of data from the specified URL to be committed as part of a blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - blockID - A Base64 value that identifies the block. Prior to encoding, the string must be less than or equal to 64 bytes +// in size. For a given blob, the length of the value specified for the blockid parameter must be the same size for each block. +// - contentLength - The length of the request. +// - sourceURL - Specifies the URL of the source. +// - options - BlockBlobClientStageBlockFromURLOptions contains the optional parameters for the BlockBlobClient.StageBlockFromURL +// method. +func (client *BlockBlobClient) StageBlockFromURL(ctx context.Context, blockID string, contentLength int64, sourceURL string, options *BlockBlobClientStageBlockFromURLOptions) (BlockBlobClientStageBlockFromURLResponse, error) { + var err error + req, err := client.stageBlockFromURLCreateRequest(ctx, blockID, contentLength, sourceURL, options) + if err != nil { + return BlockBlobClientStageBlockFromURLResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BlockBlobClientStageBlockFromURLResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return BlockBlobClientStageBlockFromURLResponse{}, err + } + resp, err := client.stageBlockFromURLHandleResponse(httpResp) + return resp, err +} + +// stageBlockFromURLCreateRequest creates the StageBlockFromURL request. +func (client *BlockBlobClient) stageBlockFromURLCreateRequest(ctx context.Context, blockID string, contentLength int64, sourceURL string, options *BlockBlobClientStageBlockFromURLOptions) (*policy.Request, error) { + urlPath := "?comp=block" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("blockid", blockID) + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Content-Length"] = []string{strconv.FormatInt(contentLength, 10)} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-copy-source"] = []string{sourceURL} + if options != nil && options.CopySourceAuthorization != nil { + req.Raw().Header["x-ms-copy-source-authorization"] = []string{*options.CopySourceAuthorization} + } + if options != nil && options.EncryptionAlgorithm != nil { + req.Raw().Header["x-ms-encryption-algorithm"] = []string{string(*options.EncryptionAlgorithm)} + } + if options != nil && options.EncryptionKey != nil { + req.Raw().Header["x-ms-encryption-key"] = []string{*options.EncryptionKey} + } + if options != nil && options.EncryptionKeySHA256 != nil { + req.Raw().Header["x-ms-encryption-key-sha256"] = []string{*options.EncryptionKeySHA256} + } + if options != nil && options.EncryptionScope != nil { + req.Raw().Header["x-ms-encryption-scope"] = []string{*options.EncryptionScope} + } + if options != nil && options.FileRequestIntent != nil { + req.Raw().Header["x-ms-file-request-intent"] = []string{string(*options.FileRequestIntent)} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + if options != nil && options.SourceContentCRC64 != nil { + req.Raw().Header["x-ms-source-content-crc64"] = []string{base64.StdEncoding.EncodeToString(options.SourceContentCRC64)} + } + if options != nil && options.SourceContentMD5 != nil { + req.Raw().Header["x-ms-source-content-md5"] = []string{base64.StdEncoding.EncodeToString(options.SourceContentMD5)} + } + if options != nil && options.SourceEncryptionAlgorithm != nil { + req.Raw().Header["x-ms-source-encryption-algorithm"] = []string{string(*options.SourceEncryptionAlgorithm)} + } + if options != nil && options.SourceEncryptionKey != nil { + req.Raw().Header["x-ms-source-encryption-key"] = []string{*options.SourceEncryptionKey} + } + if options != nil && options.SourceEncryptionKeySHA256 != nil { + req.Raw().Header["x-ms-source-encryption-key-sha256"] = []string{*options.SourceEncryptionKeySHA256} + } + if options != nil && options.SourceIfMatch != nil { + req.Raw().Header["x-ms-source-if-match"] = []string{string(*options.SourceIfMatch)} + } + if options != nil && options.SourceIfModifiedSince != nil { + req.Raw().Header["x-ms-source-if-modified-since"] = []string{datetime.RFC7231(*options.SourceIfModifiedSince).String()} + } + if options != nil && options.SourceIfNoneMatch != nil { + req.Raw().Header["x-ms-source-if-none-match"] = []string{string(*options.SourceIfNoneMatch)} + } + if options != nil && options.SourceIfUnmodifiedSince != nil { + req.Raw().Header["x-ms-source-if-unmodified-since"] = []string{datetime.RFC7231(*options.SourceIfUnmodifiedSince).String()} + } + if options != nil && options.SourceRange != nil { + req.Raw().Header["x-ms-source-range"] = []string{*options.SourceRange} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// stageBlockFromURLHandleResponse handles the StageBlockFromURL response. +func (client *BlockBlobClient) stageBlockFromURLHandleResponse(resp *http.Response) (BlockBlobClientStageBlockFromURLResponse, error) { + result := BlockBlobClientStageBlockFromURLResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("x-ms-content-crc64"); val != "" { + contentCRC64, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return BlockBlobClientStageBlockFromURLResponse{}, err + } + result.ContentCRC64 = contentCRC64 + } + if val := resp.Header.Get("Content-MD5"); val != "" { + contentMD5, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return BlockBlobClientStageBlockFromURLResponse{}, err + } + result.ContentMD5 = contentMD5 + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return BlockBlobClientStageBlockFromURLResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-encryption-key-sha256"); val != "" { + result.EncryptionKeySHA256 = &val + } + if val := resp.Header.Get("x-ms-encryption-scope"); val != "" { + result.EncryptionScope = &val + } + if val := resp.Header.Get("x-ms-request-server-encrypted"); val != "" { + isServerEncrypted, err := strconv.ParseBool(val) + if err != nil { + return BlockBlobClientStageBlockFromURLResponse{}, err + } + result.IsServerEncrypted = &isServerEncrypted + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// Upload - Uploads the content to the specified block blob. If the blob already exists, the data and any existing metadata +// will be overwritten. +// If the operation fails it returns an *azcore.ResponseError type. +// - body - The body of the request. +// - contentLength - The length of the request. +// - options - BlockBlobClientUploadOptions contains the optional parameters for the BlockBlobClient.Upload method. +func (client *BlockBlobClient) Upload(ctx context.Context, body io.ReadSeekCloser, contentLength int64, options *BlockBlobClientUploadOptions) (BlockBlobClientUploadResponse, error) { + var err error + req, err := client.uploadCreateRequest(ctx, body, contentLength, options) + if err != nil { + return BlockBlobClientUploadResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BlockBlobClientUploadResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return BlockBlobClientUploadResponse{}, err + } + resp, err := client.uploadHandleResponse(httpResp) + return resp, err +} + +// uploadCreateRequest creates the Upload request. +func (client *BlockBlobClient) uploadCreateRequest(ctx context.Context, body io.ReadSeekCloser, contentLength int64, options *BlockBlobClientUploadOptions) (*policy.Request, error) { + req, err := runtime.NewRequest(ctx, http.MethodPut, client.url) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Content-Length"] = []string{strconv.FormatInt(contentLength, 10)} + if options != nil && options.TransactionalContentMD5 != nil { + req.Raw().Header["Content-MD5"] = []string{base64.StdEncoding.EncodeToString(options.TransactionalContentMD5)} + } + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.Tier != nil { + req.Raw().Header["x-ms-access-tier"] = []string{string(*options.Tier)} + } + if options != nil && options.BlobCacheControl != nil { + req.Raw().Header["x-ms-blob-cache-control"] = []string{*options.BlobCacheControl} + } + if options != nil && options.BlobContentDisposition != nil { + req.Raw().Header["x-ms-blob-content-disposition"] = []string{*options.BlobContentDisposition} + } + if options != nil && options.BlobContentEncoding != nil { + req.Raw().Header["x-ms-blob-content-encoding"] = []string{*options.BlobContentEncoding} + } + if options != nil && options.BlobContentLanguage != nil { + req.Raw().Header["x-ms-blob-content-language"] = []string{*options.BlobContentLanguage} + } + if options != nil && options.BlobContentMD5 != nil { + req.Raw().Header["x-ms-blob-content-md5"] = []string{base64.StdEncoding.EncodeToString(options.BlobContentMD5)} + } + if options != nil && options.BlobContentType != nil { + req.Raw().Header["x-ms-blob-content-type"] = []string{*options.BlobContentType} + } + req.Raw().Header["x-ms-blob-type"] = []string{"BlockBlob"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.TransactionalContentCRC64 != nil { + req.Raw().Header["x-ms-content-crc64"] = []string{base64.StdEncoding.EncodeToString(options.TransactionalContentCRC64)} + } + if options != nil && options.EncryptionAlgorithm != nil { + req.Raw().Header["x-ms-encryption-algorithm"] = []string{string(*options.EncryptionAlgorithm)} + } + if options != nil && options.EncryptionKey != nil { + req.Raw().Header["x-ms-encryption-key"] = []string{*options.EncryptionKey} + } + if options != nil && options.EncryptionKeySHA256 != nil { + req.Raw().Header["x-ms-encryption-key-sha256"] = []string{*options.EncryptionKeySHA256} + } + if options != nil && options.EncryptionScope != nil { + req.Raw().Header["x-ms-encryption-scope"] = []string{*options.EncryptionScope} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + if options != nil && options.ImmutabilityPolicyMode != nil { + req.Raw().Header["x-ms-immutability-policy-mode"] = []string{string(*options.ImmutabilityPolicyMode)} + } + if options != nil && options.ImmutabilityPolicyExpiry != nil { + req.Raw().Header["x-ms-immutability-policy-until-date"] = []string{datetime.RFC7231(*options.ImmutabilityPolicyExpiry).String()} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + if options != nil && options.LegalHold != nil { + req.Raw().Header["x-ms-legal-hold"] = []string{strconv.FormatBool(*options.LegalHold)} + } + if options != nil && options.Metadata != nil { + for k, v := range options.Metadata { + if v != nil { + req.Raw().Header["x-ms-meta-"+k] = []string{*v} + } + } + } + if options != nil && options.StructuredBodyType != nil { + req.Raw().Header["x-ms-structured-body"] = []string{*options.StructuredBodyType} + } + if options != nil && options.StructuredContentLength != nil { + req.Raw().Header["x-ms-structured-content-length"] = []string{strconv.FormatInt(*options.StructuredContentLength, 10)} + } + if options != nil && options.BlobTagsString != nil { + req.Raw().Header["x-ms-tags"] = []string{*options.BlobTagsString} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + req.Raw().Header["Content-Type"] = []string{"application/octet-stream"} + if err := req.SetBody(body, "application/octet-stream"); err != nil { + return nil, err + } + return req, nil +} + +// uploadHandleResponse handles the Upload response. +func (client *BlockBlobClient) uploadHandleResponse(resp *http.Response) (BlockBlobClientUploadResponse, error) { + result := BlockBlobClientUploadResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("x-ms-content-crc64"); val != "" { + contentCRC64, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return BlockBlobClientUploadResponse{}, err + } + result.ContentCRC64 = contentCRC64 + } + if val := resp.Header.Get("Content-MD5"); val != "" { + contentMD5, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return BlockBlobClientUploadResponse{}, err + } + result.ContentMD5 = contentMD5 + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return BlockBlobClientUploadResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("x-ms-encryption-key-sha256"); val != "" { + result.EncryptionKeySHA256 = &val + } + if val := resp.Header.Get("x-ms-encryption-scope"); val != "" { + result.EncryptionScope = &val + } + if val := resp.Header.Get("x-ms-request-server-encrypted"); val != "" { + isServerEncrypted, err := strconv.ParseBool(val) + if err != nil { + return BlockBlobClientUploadResponse{}, err + } + result.IsServerEncrypted = &isServerEncrypted + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return BlockBlobClientUploadResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-structured-body"); val != "" { + result.StructuredBodyType = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + if val := resp.Header.Get("x-ms-version-id"); val != "" { + result.VersionID = &val + } + return result, nil +} + +// UploadBlobFromURL - Uploads the content from the specified URL to the block blob. If the blob already exists, the data +// and any existing metadata will be overwritten. +// If the operation fails it returns an *azcore.ResponseError type. +// - copySource - Specifies the name of the source URL for the copy operation. The value should be URL-encoded as it would appear +// in a request URI. +// - options - BlockBlobClientUploadBlobFromURLOptions contains the optional parameters for the BlockBlobClient.UploadBlobFromURL +// method. +func (client *BlockBlobClient) UploadBlobFromURL(ctx context.Context, copySource string, options *BlockBlobClientUploadBlobFromURLOptions) (BlockBlobClientUploadBlobFromURLResponse, error) { + var err error + req, err := client.uploadBlobFromURLCreateRequest(ctx, copySource, options) + if err != nil { + return BlockBlobClientUploadBlobFromURLResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BlockBlobClientUploadBlobFromURLResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return BlockBlobClientUploadBlobFromURLResponse{}, err + } + resp, err := client.uploadBlobFromURLHandleResponse(httpResp) + return resp, err +} + +// uploadBlobFromURLCreateRequest creates the UploadBlobFromURL request. +func (client *BlockBlobClient) uploadBlobFromURLCreateRequest(ctx context.Context, copySource string, options *BlockBlobClientUploadBlobFromURLOptions) (*policy.Request, error) { + req, err := runtime.NewRequest(ctx, http.MethodPut, client.url) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Content-Length"] = []string{"0"} + if options != nil && options.TransactionalContentMD5 != nil { + req.Raw().Header["Content-MD5"] = []string{base64.StdEncoding.EncodeToString(options.TransactionalContentMD5)} + } + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.Tier != nil { + req.Raw().Header["x-ms-access-tier"] = []string{string(*options.Tier)} + } + if options != nil && options.BlobCacheControl != nil { + req.Raw().Header["x-ms-blob-cache-control"] = []string{*options.BlobCacheControl} + } + if options != nil && options.BlobContentDisposition != nil { + req.Raw().Header["x-ms-blob-content-disposition"] = []string{*options.BlobContentDisposition} + } + if options != nil && options.BlobContentEncoding != nil { + req.Raw().Header["x-ms-blob-content-encoding"] = []string{*options.BlobContentEncoding} + } + if options != nil && options.BlobContentLanguage != nil { + req.Raw().Header["x-ms-blob-content-language"] = []string{*options.BlobContentLanguage} + } + if options != nil && options.BlobContentMD5 != nil { + req.Raw().Header["x-ms-blob-content-md5"] = []string{base64.StdEncoding.EncodeToString(options.BlobContentMD5)} + } + if options != nil && options.BlobContentType != nil { + req.Raw().Header["x-ms-blob-content-type"] = []string{*options.BlobContentType} + } + req.Raw().Header["x-ms-blob-type"] = []string{"BlockBlob"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-copy-source"] = []string{copySource} + if options != nil && options.CopySourceAuthorization != nil { + req.Raw().Header["x-ms-copy-source-authorization"] = []string{*options.CopySourceAuthorization} + } + if options != nil && options.CopySourceBlobProperties != nil { + req.Raw().Header["x-ms-copy-source-blob-properties"] = []string{strconv.FormatBool(*options.CopySourceBlobProperties)} + } + if options != nil && options.CopySourceTags != nil { + req.Raw().Header["x-ms-copy-source-tag-option"] = []string{string(*options.CopySourceTags)} + } + if options != nil && options.EncryptionAlgorithm != nil { + req.Raw().Header["x-ms-encryption-algorithm"] = []string{string(*options.EncryptionAlgorithm)} + } + if options != nil && options.EncryptionKey != nil { + req.Raw().Header["x-ms-encryption-key"] = []string{*options.EncryptionKey} + } + if options != nil && options.EncryptionKeySHA256 != nil { + req.Raw().Header["x-ms-encryption-key-sha256"] = []string{*options.EncryptionKeySHA256} + } + if options != nil && options.EncryptionScope != nil { + req.Raw().Header["x-ms-encryption-scope"] = []string{*options.EncryptionScope} + } + if options != nil && options.FileRequestIntent != nil { + req.Raw().Header["x-ms-file-request-intent"] = []string{string(*options.FileRequestIntent)} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + if options != nil && options.Metadata != nil { + for k, v := range options.Metadata { + if v != nil { + req.Raw().Header["x-ms-meta-"+k] = []string{*v} + } + } + } + if options != nil && options.SourceContentMD5 != nil { + req.Raw().Header["x-ms-source-content-md5"] = []string{base64.StdEncoding.EncodeToString(options.SourceContentMD5)} + } + if options != nil && options.SourceEncryptionAlgorithm != nil { + req.Raw().Header["x-ms-source-encryption-algorithm"] = []string{string(*options.SourceEncryptionAlgorithm)} + } + if options != nil && options.SourceEncryptionKey != nil { + req.Raw().Header["x-ms-source-encryption-key"] = []string{*options.SourceEncryptionKey} + } + if options != nil && options.SourceEncryptionKeySHA256 != nil { + req.Raw().Header["x-ms-source-encryption-key-sha256"] = []string{*options.SourceEncryptionKeySHA256} + } + if options != nil && options.SourceIfMatch != nil { + req.Raw().Header["x-ms-source-if-match"] = []string{string(*options.SourceIfMatch)} + } + if options != nil && options.SourceIfModifiedSince != nil { + req.Raw().Header["x-ms-source-if-modified-since"] = []string{datetime.RFC7231(*options.SourceIfModifiedSince).String()} + } + if options != nil && options.SourceIfNoneMatch != nil { + req.Raw().Header["x-ms-source-if-none-match"] = []string{string(*options.SourceIfNoneMatch)} + } + if options != nil && options.SourceIfTags != nil { + req.Raw().Header["x-ms-source-if-tags"] = []string{*options.SourceIfTags} + } + if options != nil && options.SourceIfUnmodifiedSince != nil { + req.Raw().Header["x-ms-source-if-unmodified-since"] = []string{datetime.RFC7231(*options.SourceIfUnmodifiedSince).String()} + } + if options != nil && options.BlobTagsString != nil { + req.Raw().Header["x-ms-tags"] = []string{*options.BlobTagsString} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// uploadBlobFromURLHandleResponse handles the UploadBlobFromURL response. +func (client *BlockBlobClient) uploadBlobFromURLHandleResponse(resp *http.Response) (BlockBlobClientUploadBlobFromURLResponse, error) { + result := BlockBlobClientUploadBlobFromURLResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Content-MD5"); val != "" { + contentMD5, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return BlockBlobClientUploadBlobFromURLResponse{}, err + } + result.ContentMD5 = contentMD5 + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return BlockBlobClientUploadBlobFromURLResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("x-ms-encryption-key-sha256"); val != "" { + result.EncryptionKeySHA256 = &val + } + if val := resp.Header.Get("x-ms-encryption-scope"); val != "" { + result.EncryptionScope = &val + } + if val := resp.Header.Get("x-ms-request-server-encrypted"); val != "" { + isServerEncrypted, err := strconv.ParseBool(val) + if err != nil { + return BlockBlobClientUploadBlobFromURLResponse{}, err + } + result.IsServerEncrypted = &isServerEncrypted + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return BlockBlobClientUploadBlobFromURLResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + if val := resp.Header.Get("x-ms-version-id"); val != "" { + result.VersionID = &val + } + return result, nil +} diff --git a/test/local/azblob/zz_client.go b/test/local/azblob/zz_client.go new file mode 100644 index 000000000000..fcab680c4e61 --- /dev/null +++ b/test/local/azblob/zz_client.go @@ -0,0 +1,2682 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azblob + +import ( + "context" + "encoding/base64" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "strconv" + "strings" + "time" +) + +// Client contains the methods for the service. +// Don't use this type directly, use a constructor function instead. +// +// Generated from API version 2026-06-06 +type Client struct { + internal *azcore.Client + url string +} + +// AbortCopyFromURL - Aborts a pending asynchronous copy operation and leaves a destination blob with zero length and full +// metadata. +// If the operation fails it returns an *azcore.ResponseError type. +// - copyID - The ID of the copy to be aborted. +// - options - ClientAbortCopyFromURLOptions contains the optional parameters for the Client.AbortCopyFromURL method. +func (client *Client) AbortCopyFromURL(ctx context.Context, copyID string, options *ClientAbortCopyFromURLOptions) (ClientAbortCopyFromURLResponse, error) { + var err error + req, err := client.abortCopyFromURLCreateRequest(ctx, copyID, options) + if err != nil { + return ClientAbortCopyFromURLResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientAbortCopyFromURLResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ClientAbortCopyFromURLResponse{}, err + } + resp, err := client.abortCopyFromURLHandleResponse(httpResp) + return resp, err +} + +// abortCopyFromURLCreateRequest creates the AbortCopyFromURL request. +func (client *Client) abortCopyFromURLCreateRequest(ctx context.Context, copyID string, options *ClientAbortCopyFromURLOptions) (*policy.Request, error) { + urlPath := "?comp=copy" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("copyid", copyID) + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-copy-action"] = []string{"abort"} + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// abortCopyFromURLHandleResponse handles the AbortCopyFromURL response. +func (client *Client) abortCopyFromURLHandleResponse(resp *http.Response) (ClientAbortCopyFromURLResponse, error) { + result := ClientAbortCopyFromURLResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientAbortCopyFromURLResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// AcquireLease - Requests a new lease on the specified blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - duration - Specifies the duration of the lease, in seconds, or negative one (-1) for a lease that never expires. A non-infinite +// lease can be between 15 and 60 seconds. +// - options - ClientAcquireLeaseOptions contains the optional parameters for the Client.AcquireLease method. +func (client *Client) AcquireLease(ctx context.Context, duration int32, options *ClientAcquireLeaseOptions) (ClientAcquireLeaseResponse, error) { + var err error + req, err := client.acquireLeaseCreateRequest(ctx, duration, options) + if err != nil { + return ClientAcquireLeaseResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientAcquireLeaseResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return ClientAcquireLeaseResponse{}, err + } + resp, err := client.acquireLeaseHandleResponse(httpResp) + return resp, err +} + +// acquireLeaseCreateRequest creates the AcquireLease request. +func (client *Client) acquireLeaseCreateRequest(ctx context.Context, duration int32, options *ClientAcquireLeaseOptions) (*policy.Request, error) { + urlPath := "?comp=lease" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + req.Raw().Header["x-ms-lease-action"] = []string{"acquire"} + req.Raw().Header["x-ms-lease-duration"] = []string{strconv.FormatInt(int64(duration), 10)} + if options != nil && options.ProposedLeaseID != nil { + req.Raw().Header["x-ms-proposed-lease-id"] = []string{*options.ProposedLeaseID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// acquireLeaseHandleResponse handles the AcquireLease response. +func (client *Client) acquireLeaseHandleResponse(resp *http.Response) (ClientAcquireLeaseResponse, error) { + result := ClientAcquireLeaseResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientAcquireLeaseResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientAcquireLeaseResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-lease-id"); val != "" { + result.LeaseID = &val + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// BreakLease - Ends a lease and ensures that another client can't acquire a new lease until the current lease period has +// expired. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientBreakLeaseOptions contains the optional parameters for the Client.BreakLease method. +func (client *Client) BreakLease(ctx context.Context, options *ClientBreakLeaseOptions) (ClientBreakLeaseResponse, error) { + var err error + req, err := client.breakLeaseCreateRequest(ctx, options) + if err != nil { + return ClientBreakLeaseResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientBreakLeaseResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return ClientBreakLeaseResponse{}, err + } + resp, err := client.breakLeaseHandleResponse(httpResp) + return resp, err +} + +// breakLeaseCreateRequest creates the BreakLease request. +func (client *Client) breakLeaseCreateRequest(ctx context.Context, options *ClientBreakLeaseOptions) (*policy.Request, error) { + urlPath := "?comp=lease" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + req.Raw().Header["x-ms-lease-action"] = []string{"break"} + if options != nil && options.BreakPeriod != nil { + req.Raw().Header["x-ms-lease-break-period"] = []string{strconv.FormatInt(int64(*options.BreakPeriod), 10)} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// breakLeaseHandleResponse handles the BreakLease response. +func (client *Client) breakLeaseHandleResponse(resp *http.Response) (ClientBreakLeaseResponse, error) { + result := ClientBreakLeaseResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientBreakLeaseResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientBreakLeaseResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-lease-time"); val != "" { + leaseTime32, err := strconv.ParseInt(val, 10, 32) + leaseTime := int32(leaseTime32) + if err != nil { + return ClientBreakLeaseResponse{}, err + } + result.LeaseTime = &leaseTime + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// ChangeLease - Change the ID of an existing lease. +// If the operation fails it returns an *azcore.ResponseError type. +// - leaseID - A lease ID for the resource. The resource must have an active lease and the lease ID must match. +// - proposedLeaseID - The proposed lease ID for the lease. +// - options - ClientChangeLeaseOptions contains the optional parameters for the Client.ChangeLease method. +func (client *Client) ChangeLease(ctx context.Context, leaseID string, proposedLeaseID string, options *ClientChangeLeaseOptions) (ClientChangeLeaseResponse, error) { + var err error + req, err := client.changeLeaseCreateRequest(ctx, leaseID, proposedLeaseID, options) + if err != nil { + return ClientChangeLeaseResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientChangeLeaseResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientChangeLeaseResponse{}, err + } + resp, err := client.changeLeaseHandleResponse(httpResp) + return resp, err +} + +// changeLeaseCreateRequest creates the ChangeLease request. +func (client *Client) changeLeaseCreateRequest(ctx context.Context, leaseID string, proposedLeaseID string, options *ClientChangeLeaseOptions) (*policy.Request, error) { + urlPath := "?comp=lease" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + req.Raw().Header["x-ms-lease-action"] = []string{"change"} + req.Raw().Header["x-ms-lease-id"] = []string{leaseID} + req.Raw().Header["x-ms-proposed-lease-id"] = []string{proposedLeaseID} + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// changeLeaseHandleResponse handles the ChangeLease response. +func (client *Client) changeLeaseHandleResponse(resp *http.Response) (ClientChangeLeaseResponse, error) { + result := ClientChangeLeaseResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientChangeLeaseResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientChangeLeaseResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-lease-id"); val != "" { + result.LeaseID = &val + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// CopyFromURL - Synchronously copies a blob from a source URL to the destination blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - copySource - Specifies the name of the source URL for the copy operation. The value should be URL-encoded as it would appear +// in a request URI. +// - options - ClientCopyFromURLOptions contains the optional parameters for the Client.CopyFromURL method. +func (client *Client) CopyFromURL(ctx context.Context, copySource string, options *ClientCopyFromURLOptions) (ClientCopyFromURLResponse, error) { + var err error + req, err := client.copyFromURLCreateRequest(ctx, copySource, options) + if err != nil { + return ClientCopyFromURLResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientCopyFromURLResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return ClientCopyFromURLResponse{}, err + } + resp, err := client.copyFromURLHandleResponse(httpResp) + return resp, err +} + +// copyFromURLCreateRequest creates the CopyFromURL request. +func (client *Client) copyFromURLCreateRequest(ctx context.Context, copySource string, options *ClientCopyFromURLOptions) (*policy.Request, error) { + req, err := runtime.NewRequest(ctx, http.MethodPut, client.url) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.Tier != nil { + req.Raw().Header["x-ms-access-tier"] = []string{string(*options.Tier)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-copy-source"] = []string{copySource} + if options != nil && options.CopySourceAuthorization != nil { + req.Raw().Header["x-ms-copy-source-authorization"] = []string{*options.CopySourceAuthorization} + } + if options != nil && options.CopySourceTags != nil { + req.Raw().Header["x-ms-copy-source-tag-option"] = []string{string(*options.CopySourceTags)} + } + if options != nil && options.EncryptionScope != nil { + req.Raw().Header["x-ms-encryption-scope"] = []string{*options.EncryptionScope} + } + if options != nil && options.FileRequestIntent != nil { + req.Raw().Header["x-ms-file-request-intent"] = []string{string(*options.FileRequestIntent)} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + if options != nil && options.ImmutabilityPolicyMode != nil { + req.Raw().Header["x-ms-immutability-policy-mode"] = []string{string(*options.ImmutabilityPolicyMode)} + } + if options != nil && options.ImmutabilityPolicyExpiry != nil { + req.Raw().Header["x-ms-immutability-policy-until-date"] = []string{datetime.RFC7231(*options.ImmutabilityPolicyExpiry).String()} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + if options != nil && options.LegalHold != nil { + req.Raw().Header["x-ms-legal-hold"] = []string{strconv.FormatBool(*options.LegalHold)} + } + if options != nil && options.Metadata != nil { + for k, v := range options.Metadata { + if v != nil { + req.Raw().Header["x-ms-meta-"+k] = []string{*v} + } + } + } + req.Raw().Header["x-ms-requires-sync"] = []string{"true"} + if options != nil && options.SourceContentMD5 != nil { + req.Raw().Header["x-ms-source-content-md5"] = []string{base64.StdEncoding.EncodeToString(options.SourceContentMD5)} + } + if options != nil && options.SourceIfMatch != nil { + req.Raw().Header["x-ms-source-if-match"] = []string{string(*options.SourceIfMatch)} + } + if options != nil && options.SourceIfModifiedSince != nil { + req.Raw().Header["x-ms-source-if-modified-since"] = []string{datetime.RFC7231(*options.SourceIfModifiedSince).String()} + } + if options != nil && options.SourceIfNoneMatch != nil { + req.Raw().Header["x-ms-source-if-none-match"] = []string{string(*options.SourceIfNoneMatch)} + } + if options != nil && options.SourceIfUnmodifiedSince != nil { + req.Raw().Header["x-ms-source-if-unmodified-since"] = []string{datetime.RFC7231(*options.SourceIfUnmodifiedSince).String()} + } + if options != nil && options.BlobTagsString != nil { + req.Raw().Header["x-ms-tags"] = []string{*options.BlobTagsString} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// copyFromURLHandleResponse handles the CopyFromURL response. +func (client *Client) copyFromURLHandleResponse(resp *http.Response) (ClientCopyFromURLResponse, error) { + result := ClientCopyFromURLResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("x-ms-content-crc64"); val != "" { + contentCRC64, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return ClientCopyFromURLResponse{}, err + } + result.ContentCRC64 = contentCRC64 + } + if val := resp.Header.Get("Content-MD5"); val != "" { + contentMD5, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return ClientCopyFromURLResponse{}, err + } + result.ContentMD5 = contentMD5 + } + if val := resp.Header.Get("x-ms-copy-id"); val != "" { + result.CopyID = &val + } + if val := resp.Header.Get("x-ms-copy-status"); val != "" { + result.CopyStatus = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientCopyFromURLResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("x-ms-encryption-scope"); val != "" { + result.EncryptionScope = &val + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientCopyFromURLResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + if val := resp.Header.Get("x-ms-version-id"); val != "" { + result.VersionID = &val + } + return result, nil +} + +// CreateSnapshot - Creates a read-only snapshot of the specified blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientCreateSnapshotOptions contains the optional parameters for the Client.CreateSnapshot method. +func (client *Client) CreateSnapshot(ctx context.Context, options *ClientCreateSnapshotOptions) (ClientCreateSnapshotResponse, error) { + var err error + req, err := client.createSnapshotCreateRequest(ctx, options) + if err != nil { + return ClientCreateSnapshotResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientCreateSnapshotResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return ClientCreateSnapshotResponse{}, err + } + resp, err := client.createSnapshotHandleResponse(httpResp) + return resp, err +} + +// createSnapshotCreateRequest creates the CreateSnapshot request. +func (client *Client) createSnapshotCreateRequest(ctx context.Context, options *ClientCreateSnapshotOptions) (*policy.Request, error) { + urlPath := "?comp=snapshot" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.EncryptionAlgorithm != nil { + req.Raw().Header["x-ms-encryption-algorithm"] = []string{string(*options.EncryptionAlgorithm)} + } + if options != nil && options.EncryptionKey != nil { + req.Raw().Header["x-ms-encryption-key"] = []string{*options.EncryptionKey} + } + if options != nil && options.EncryptionKeySHA256 != nil { + req.Raw().Header["x-ms-encryption-key-sha256"] = []string{*options.EncryptionKeySHA256} + } + if options != nil && options.EncryptionScope != nil { + req.Raw().Header["x-ms-encryption-scope"] = []string{*options.EncryptionScope} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + if options != nil && options.Metadata != nil { + for k, v := range options.Metadata { + if v != nil { + req.Raw().Header["x-ms-meta-"+k] = []string{*v} + } + } + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// createSnapshotHandleResponse handles the CreateSnapshot response. +func (client *Client) createSnapshotHandleResponse(resp *http.Response) (ClientCreateSnapshotResponse, error) { + result := ClientCreateSnapshotResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientCreateSnapshotResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("x-ms-request-server-encrypted"); val != "" { + isServerEncrypted, err := strconv.ParseBool(val) + if err != nil { + return ClientCreateSnapshotResponse{}, err + } + result.IsServerEncrypted = &isServerEncrypted + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientCreateSnapshotResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-snapshot"); val != "" { + result.Snapshot = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + if val := resp.Header.Get("x-ms-version-id"); val != "" { + result.VersionID = &val + } + return result, nil +} + +// Delete - Deletes the specified blob. If blob soft delete is enabled, the blob is marked for deletion and can be recovered +// until the retention period expires. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientDeleteOptions contains the optional parameters for the Client.Delete method. +func (client *Client) Delete(ctx context.Context, options *ClientDeleteOptions) (ClientDeleteResponse, error) { + var err error + req, err := client.deleteCreateRequest(ctx, options) + if err != nil { + return ClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return ClientDeleteResponse{}, err + } + resp, err := client.deleteHandleResponse(httpResp) + return resp, err +} + +// deleteCreateRequest creates the Delete request. +func (client *Client) deleteCreateRequest(ctx context.Context, options *ClientDeleteOptions) (*policy.Request, error) { + req, err := runtime.NewRequest(ctx, http.MethodDelete, client.url) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.BlobDeleteType != nil { + reqQP.Set("deletetype", string(*options.BlobDeleteType)) + } + if options != nil && options.Snapshot != nil { + reqQP.Set("snapshot", *options.Snapshot) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + if options != nil && options.VersionID != nil { + reqQP.Set("versionid", *options.VersionID) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.AccessTierIfModifiedSince != nil { + req.Raw().Header["x-ms-access-tier-if-modified-since"] = []string{datetime.RFC7231(*options.AccessTierIfModifiedSince).String()} + } + if options != nil && options.AccessTierIfUnmodifiedSince != nil { + req.Raw().Header["x-ms-access-tier-if-unmodified-since"] = []string{datetime.RFC7231(*options.AccessTierIfUnmodifiedSince).String()} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.DeleteSnapshots != nil { + req.Raw().Header["x-ms-delete-snapshots"] = []string{string(*options.DeleteSnapshots)} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// deleteHandleResponse handles the Delete response. +func (client *Client) deleteHandleResponse(resp *http.Response) (ClientDeleteResponse, error) { + result := ClientDeleteResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientDeleteResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// DeleteImmutabilityPolicy - Deletes the immutability policy on the specified blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientDeleteImmutabilityPolicyOptions contains the optional parameters for the Client.DeleteImmutabilityPolicy +// method. +func (client *Client) DeleteImmutabilityPolicy(ctx context.Context, options *ClientDeleteImmutabilityPolicyOptions) (ClientDeleteImmutabilityPolicyResponse, error) { + var err error + req, err := client.deleteImmutabilityPolicyCreateRequest(ctx, options) + if err != nil { + return ClientDeleteImmutabilityPolicyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientDeleteImmutabilityPolicyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientDeleteImmutabilityPolicyResponse{}, err + } + resp, err := client.deleteImmutabilityPolicyHandleResponse(httpResp) + return resp, err +} + +// deleteImmutabilityPolicyCreateRequest creates the DeleteImmutabilityPolicy request. +func (client *Client) deleteImmutabilityPolicyCreateRequest(ctx context.Context, options *ClientDeleteImmutabilityPolicyOptions) (*policy.Request, error) { + urlPath := "?comp=immutabilityPolicies" + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Snapshot != nil { + reqQP.Set("snapshot", *options.Snapshot) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + if options != nil && options.VersionID != nil { + reqQP.Set("versionid", *options.VersionID) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// deleteImmutabilityPolicyHandleResponse handles the DeleteImmutabilityPolicy response. +func (client *Client) deleteImmutabilityPolicyHandleResponse(resp *http.Response) (ClientDeleteImmutabilityPolicyResponse, error) { + result := ClientDeleteImmutabilityPolicyResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientDeleteImmutabilityPolicyResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// Download - Downloads the specified blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientDownloadOptions contains the optional parameters for the Client.Download method. +func (client *Client) Download(ctx context.Context, options *ClientDownloadOptions) (BlobClientDownloadResponseInternal, error) { + var err error + req, err := client.downloadCreateRequest(ctx, options) + if err != nil { + return BlobClientDownloadResponseInternal{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BlobClientDownloadResponseInternal{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusPartialContent) { + err = runtime.NewResponseError(httpResp) + return BlobClientDownloadResponseInternal{}, err + } + resp, err := client.downloadHandleResponse(httpResp) + return resp, err +} + +// downloadCreateRequest creates the Download request. +func (client *Client) downloadCreateRequest(ctx context.Context, options *ClientDownloadOptions) (*policy.Request, error) { + req, err := runtime.NewRequest(ctx, http.MethodGet, client.url) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Snapshot != nil { + reqQP.Set("snapshot", *options.Snapshot) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + if options != nil && options.VersionID != nil { + reqQP.Set("versionid", *options.VersionID) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + runtime.SkipBodyDownload(req) + req.Raw().Header["Accept"] = []string{"application/octet-stream"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.Range != nil { + req.Raw().Header["Range"] = []string{*options.Range} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.EncryptionAlgorithm != nil { + req.Raw().Header["x-ms-encryption-algorithm"] = []string{string(*options.EncryptionAlgorithm)} + } + if options != nil && options.EncryptionKey != nil { + req.Raw().Header["x-ms-encryption-key"] = []string{*options.EncryptionKey} + } + if options != nil && options.EncryptionKeySHA256 != nil { + req.Raw().Header["x-ms-encryption-key-sha256"] = []string{*options.EncryptionKeySHA256} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + if options != nil && options.RangeGetContentCRC64 != nil { + req.Raw().Header["x-ms-range-get-content-crc64"] = []string{strconv.FormatBool(*options.RangeGetContentCRC64)} + } + if options != nil && options.RangeGetContentMD5 != nil { + req.Raw().Header["x-ms-range-get-content-md5"] = []string{strconv.FormatBool(*options.RangeGetContentMD5)} + } + if options != nil && options.StructuredBodyType != nil { + req.Raw().Header["x-ms-structured-body"] = []string{*options.StructuredBodyType} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// downloadHandleResponse handles the Download response. +func (client *Client) downloadHandleResponse(resp *http.Response) (BlobClientDownloadResponseInternal, error) { + result := BlobClientDownloadResponseInternal{Body: resp.Body} + if val := resp.Header.Get("Accept-Ranges"); val != "" { + result.AcceptRanges = &val + } + if val := resp.Header.Get("x-ms-blob-committed-block-count"); val != "" { + blobCommittedBlockCount32, err := strconv.ParseInt(val, 10, 32) + blobCommittedBlockCount := int32(blobCommittedBlockCount32) + if err != nil { + return BlobClientDownloadResponseInternal{}, err + } + result.BlobCommittedBlockCount = &blobCommittedBlockCount + } + if val := resp.Header.Get("x-ms-blob-content-md5"); val != "" { + blobContentMD5, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return BlobClientDownloadResponseInternal{}, err + } + result.BlobContentMD5 = blobContentMD5 + } + if val := resp.Header.Get("x-ms-blob-sequence-number"); val != "" { + blobSequenceNumber, err := strconv.ParseInt(val, 10, 64) + if err != nil { + return BlobClientDownloadResponseInternal{}, err + } + result.BlobSequenceNumber = &blobSequenceNumber + } + if val := resp.Header.Get("x-ms-blob-type"); val != "" { + result.BlobType = (*Type)(&val) + } + if val := resp.Header.Get("Cache-Control"); val != "" { + result.CacheControl = &val + } + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("x-ms-content-crc64"); val != "" { + contentCRC64, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return BlobClientDownloadResponseInternal{}, err + } + result.ContentCRC64 = contentCRC64 + } + if val := resp.Header.Get("Content-Disposition"); val != "" { + result.ContentDisposition = &val + } + if val := resp.Header.Get("Content-Encoding"); val != "" { + result.ContentEncoding = &val + } + if val := resp.Header.Get("Content-Language"); val != "" { + result.ContentLanguage = &val + } + if val := resp.Header.Get("Content-Length"); val != "" { + contentLength, err := strconv.ParseInt(val, 10, 64) + if err != nil { + return BlobClientDownloadResponseInternal{}, err + } + result.ContentLength = &contentLength + } + if val := resp.Header.Get("Content-MD5"); val != "" { + contentMD5, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return BlobClientDownloadResponseInternal{}, err + } + result.ContentMD5 = contentMD5 + } + if val := resp.Header.Get("Content-Range"); val != "" { + result.ContentRange = &val + } + if val := resp.Header.Get("Content-Type"); val != "" { + result.ContentType = &val + } + if val := resp.Header.Get("x-ms-copy-completion-time"); val != "" { + copyCompletionTime, err := time.Parse(time.RFC1123, val) + if err != nil { + return BlobClientDownloadResponseInternal{}, err + } + result.CopyCompletionTime = ©CompletionTime + } + if val := resp.Header.Get("x-ms-copy-id"); val != "" { + result.CopyID = &val + } + if val := resp.Header.Get("x-ms-copy-progress"); val != "" { + result.CopyProgress = &val + } + if val := resp.Header.Get("x-ms-copy-source"); val != "" { + result.CopySource = &val + } + if val := resp.Header.Get("x-ms-copy-status"); val != "" { + result.CopyStatus = (*CopyStatusType)(&val) + } + if val := resp.Header.Get("x-ms-copy-status-description"); val != "" { + result.CopyStatusDescription = &val + } + if val := resp.Header.Get("x-ms-creation-time"); val != "" { + creationTime, err := time.Parse(time.RFC1123, val) + if err != nil { + return BlobClientDownloadResponseInternal{}, err + } + result.CreationTime = &creationTime + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return BlobClientDownloadResponseInternal{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("x-ms-encryption-key-sha256"); val != "" { + result.EncryptionKeySHA256 = &val + } + if val := resp.Header.Get("x-ms-encryption-scope"); val != "" { + result.EncryptionScope = &val + } + if val := resp.Header.Get("x-ms-immutability-policy-until-date"); val != "" { + immutabilityPolicyExpiresOn, err := time.Parse(time.RFC1123, val) + if err != nil { + return BlobClientDownloadResponseInternal{}, err + } + result.ImmutabilityPolicyExpiresOn = &immutabilityPolicyExpiresOn + } + if val := resp.Header.Get("x-ms-immutability-policy-mode"); val != "" { + result.ImmutabilityPolicyMode = (*ImmutabilityPolicyMode)(&val) + } + if val := resp.Header.Get("x-ms-is-current-version"); val != "" { + isCurrentVersion, err := strconv.ParseBool(val) + if err != nil { + return BlobClientDownloadResponseInternal{}, err + } + result.IsCurrentVersion = &isCurrentVersion + } + if val := resp.Header.Get("x-ms-blob-sealed"); val != "" { + isSealed, err := strconv.ParseBool(val) + if err != nil { + return BlobClientDownloadResponseInternal{}, err + } + result.IsSealed = &isSealed + } + if val := resp.Header.Get("x-ms-server-encrypted"); val != "" { + isServerEncrypted, err := strconv.ParseBool(val) + if err != nil { + return BlobClientDownloadResponseInternal{}, err + } + result.IsServerEncrypted = &isServerEncrypted + } + if val := resp.Header.Get("x-ms-last-access-time"); val != "" { + lastAccessed, err := time.Parse(time.RFC1123, val) + if err != nil { + return BlobClientDownloadResponseInternal{}, err + } + result.LastAccessed = &lastAccessed + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return BlobClientDownloadResponseInternal{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-lease-duration"); val != "" { + result.LeaseDuration = (*LeaseDurationType)(&val) + } + if val := resp.Header.Get("x-ms-lease-state"); val != "" { + result.LeaseState = (*LeaseStateType)(&val) + } + if val := resp.Header.Get("x-ms-lease-status"); val != "" { + result.LeaseStatus = (*LeaseStatusType)(&val) + } + if val := resp.Header.Get("x-ms-legal-hold"); val != "" { + legalHold, err := strconv.ParseBool(val) + if err != nil { + return BlobClientDownloadResponseInternal{}, err + } + result.LegalHold = &legalHold + } + for hh := range resp.Header { + if len(hh) > len("x-ms-meta-") && strings.EqualFold(hh[:len("x-ms-meta-")], "x-ms-meta-") { + if result.Metadata == nil { + result.Metadata = map[string]*string{} + } + result.Metadata[hh[len("x-ms-meta-"):]] = to.Ptr(resp.Header.Get(hh)) + } + } + if val := resp.Header.Get("x-ms-or-policy-id"); val != "" { + result.ObjectReplicationPolicyID = &val + } + for hh := range resp.Header { + if len(hh) > len("x-ms-or-") && strings.EqualFold(hh[:len("x-ms-or-")], "x-ms-or-") { + if result.ObjectReplicationRules == nil { + result.ObjectReplicationRules = map[string]*string{} + } + result.ObjectReplicationRules[hh[len("x-ms-or-"):]] = to.Ptr(resp.Header.Get(hh)) + } + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-structured-body"); val != "" { + result.StructuredBodyType = &val + } + if val := resp.Header.Get("x-ms-structured-content-length"); val != "" { + structuredContentLength, err := strconv.ParseInt(val, 10, 64) + if err != nil { + return BlobClientDownloadResponseInternal{}, err + } + result.StructuredContentLength = &structuredContentLength + } + if val := resp.Header.Get("x-ms-tag-count"); val != "" { + tagCount, err := strconv.ParseInt(val, 10, 64) + if err != nil { + return BlobClientDownloadResponseInternal{}, err + } + result.TagCount = &tagCount + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + if val := resp.Header.Get("x-ms-version-id"); val != "" { + result.VersionID = &val + } + return result, nil +} + +// GetAccountInfo - Returns information about the storage account. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientGetAccountInfoOptions contains the optional parameters for the Client.GetAccountInfo method. +func (client *Client) GetAccountInfo(ctx context.Context, options *ClientGetAccountInfoOptions) (ClientGetAccountInfoResponse, error) { + var err error + req, err := client.getAccountInfoCreateRequest(ctx, options) + if err != nil { + return ClientGetAccountInfoResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientGetAccountInfoResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientGetAccountInfoResponse{}, err + } + resp, err := client.getAccountInfoHandleResponse(httpResp) + return resp, err +} + +// getAccountInfoCreateRequest creates the GetAccountInfo request. +func (client *Client) getAccountInfoCreateRequest(ctx context.Context, options *ClientGetAccountInfoOptions) (*policy.Request, error) { + urlPath := "?restype=account&comp=properties" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// getAccountInfoHandleResponse handles the GetAccountInfo response. +func (client *Client) getAccountInfoHandleResponse(resp *http.Response) (ClientGetAccountInfoResponse, error) { + result := ClientGetAccountInfoResponse{} + if val := resp.Header.Get("x-ms-account-kind"); val != "" { + result.AccountKind = (*AccountKind)(&val) + } + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientGetAccountInfoResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-is-hns-enabled"); val != "" { + isHierarchicalNamespaceEnabled, err := strconv.ParseBool(val) + if err != nil { + return ClientGetAccountInfoResponse{}, err + } + result.IsHierarchicalNamespaceEnabled = &isHierarchicalNamespaceEnabled + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-sku-name"); val != "" { + result.SKUName = (*SKUName)(&val) + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// GetProperties - Returns all user-defined metadata, standard HTTP properties, and system properties for the specified blob. +// It does not return the content of the blob. +// - options - ClientGetPropertiesOptions contains the optional parameters for the Client.GetProperties method. +func (client *Client) GetProperties(ctx context.Context, options *ClientGetPropertiesOptions) (ClientGetPropertiesResponse, error) { + var err error + req, err := client.getPropertiesCreateRequest(ctx, options) + if err != nil { + return ClientGetPropertiesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientGetPropertiesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientGetPropertiesResponse{}, err + } + resp, err := client.getPropertiesHandleResponse(httpResp) + return resp, err +} + +// getPropertiesCreateRequest creates the GetProperties request. +func (client *Client) getPropertiesCreateRequest(ctx context.Context, options *ClientGetPropertiesOptions) (*policy.Request, error) { + req, err := runtime.NewRequest(ctx, http.MethodHead, client.url) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Snapshot != nil { + reqQP.Set("snapshot", *options.Snapshot) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + if options != nil && options.VersionID != nil { + reqQP.Set("versionid", *options.VersionID) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.EncryptionAlgorithm != nil { + req.Raw().Header["x-ms-encryption-algorithm"] = []string{string(*options.EncryptionAlgorithm)} + } + if options != nil && options.EncryptionKey != nil { + req.Raw().Header["x-ms-encryption-key"] = []string{*options.EncryptionKey} + } + if options != nil && options.EncryptionKeySHA256 != nil { + req.Raw().Header["x-ms-encryption-key-sha256"] = []string{*options.EncryptionKeySHA256} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// getPropertiesHandleResponse handles the GetProperties response. +func (client *Client) getPropertiesHandleResponse(resp *http.Response) (ClientGetPropertiesResponse, error) { + result := ClientGetPropertiesResponse{Success: resp.StatusCode >= 200 && resp.StatusCode < 300} + if val := resp.Header.Get("Accept-Ranges"); val != "" { + result.AcceptRanges = &val + } + if val := resp.Header.Get("x-ms-access-tier"); val != "" { + result.AccessTier = &val + } + if val := resp.Header.Get("x-ms-access-tier-change-time"); val != "" { + accessTierChangeTime, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientGetPropertiesResponse{}, err + } + result.AccessTierChangeTime = &accessTierChangeTime + } + if val := resp.Header.Get("x-ms-access-tier-inferred"); val != "" { + accessTierInferred, err := strconv.ParseBool(val) + if err != nil { + return ClientGetPropertiesResponse{}, err + } + result.AccessTierInferred = &accessTierInferred + } + if val := resp.Header.Get("x-ms-archive-status"); val != "" { + result.ArchiveStatus = &val + } + if val := resp.Header.Get("x-ms-blob-committed-block-count"); val != "" { + blobCommittedBlockCount32, err := strconv.ParseInt(val, 10, 32) + blobCommittedBlockCount := int32(blobCommittedBlockCount32) + if err != nil { + return ClientGetPropertiesResponse{}, err + } + result.BlobCommittedBlockCount = &blobCommittedBlockCount + } + if val := resp.Header.Get("x-ms-blob-sequence-number"); val != "" { + blobSequenceNumber, err := strconv.ParseInt(val, 10, 64) + if err != nil { + return ClientGetPropertiesResponse{}, err + } + result.BlobSequenceNumber = &blobSequenceNumber + } + if val := resp.Header.Get("x-ms-blob-type"); val != "" { + result.BlobType = (*Type)(&val) + } + if val := resp.Header.Get("Cache-Control"); val != "" { + result.CacheControl = &val + } + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Content-Disposition"); val != "" { + result.ContentDisposition = &val + } + if val := resp.Header.Get("Content-Encoding"); val != "" { + result.ContentEncoding = &val + } + if val := resp.Header.Get("Content-Language"); val != "" { + result.ContentLanguage = &val + } + if val := resp.Header.Get("Content-Length"); val != "" { + contentLength, err := strconv.ParseInt(val, 10, 64) + if err != nil { + return ClientGetPropertiesResponse{}, err + } + result.ContentLength = &contentLength + } + if val := resp.Header.Get("Content-MD5"); val != "" { + contentMD5, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return ClientGetPropertiesResponse{}, err + } + result.ContentMD5 = contentMD5 + } + if val := resp.Header.Get("Content-Type"); val != "" { + result.ContentType = &val + } + if val := resp.Header.Get("x-ms-copy-completion-time"); val != "" { + copyCompletionTime, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientGetPropertiesResponse{}, err + } + result.CopyCompletionTime = ©CompletionTime + } + if val := resp.Header.Get("x-ms-copy-id"); val != "" { + result.CopyID = &val + } + if val := resp.Header.Get("x-ms-copy-progress"); val != "" { + result.CopyProgress = &val + } + if val := resp.Header.Get("x-ms-copy-source"); val != "" { + result.CopySource = &val + } + if val := resp.Header.Get("x-ms-copy-status"); val != "" { + result.CopyStatus = (*CopyStatusType)(&val) + } + if val := resp.Header.Get("x-ms-copy-status-description"); val != "" { + result.CopyStatusDescription = &val + } + if val := resp.Header.Get("x-ms-creation-time"); val != "" { + creationTime, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientGetPropertiesResponse{}, err + } + result.CreationTime = &creationTime + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientGetPropertiesResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-copy-destination-snapshot"); val != "" { + result.DestinationSnapshot = &val + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("x-ms-encryption-key-sha256"); val != "" { + result.EncryptionKeySHA256 = &val + } + if val := resp.Header.Get("x-ms-encryption-scope"); val != "" { + result.EncryptionScope = &val + } + if val := resp.Header.Get("x-ms-expiry-time"); val != "" { + expiresOn, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientGetPropertiesResponse{}, err + } + result.ExpiresOn = &expiresOn + } + if val := resp.Header.Get("x-ms-immutability-policy-until-date"); val != "" { + immutabilityPolicyExpiresOn, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientGetPropertiesResponse{}, err + } + result.ImmutabilityPolicyExpiresOn = &immutabilityPolicyExpiresOn + } + if val := resp.Header.Get("x-ms-immutability-policy-mode"); val != "" { + result.ImmutabilityPolicyMode = (*ImmutabilityPolicyMode)(&val) + } + if val := resp.Header.Get("x-ms-is-current-version"); val != "" { + isCurrentVersion, err := strconv.ParseBool(val) + if err != nil { + return ClientGetPropertiesResponse{}, err + } + result.IsCurrentVersion = &isCurrentVersion + } + if val := resp.Header.Get("x-ms-incremental-copy"); val != "" { + isIncrementalCopy, err := strconv.ParseBool(val) + if err != nil { + return ClientGetPropertiesResponse{}, err + } + result.IsIncrementalCopy = &isIncrementalCopy + } + if val := resp.Header.Get("x-ms-blob-sealed"); val != "" { + isSealed, err := strconv.ParseBool(val) + if err != nil { + return ClientGetPropertiesResponse{}, err + } + result.IsSealed = &isSealed + } + if val := resp.Header.Get("x-ms-server-encrypted"); val != "" { + isServerEncrypted, err := strconv.ParseBool(val) + if err != nil { + return ClientGetPropertiesResponse{}, err + } + result.IsServerEncrypted = &isServerEncrypted + } + if val := resp.Header.Get("x-ms-last-access-time"); val != "" { + lastAccessed, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientGetPropertiesResponse{}, err + } + result.LastAccessed = &lastAccessed + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientGetPropertiesResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-lease-duration"); val != "" { + result.LeaseDuration = (*LeaseDurationType)(&val) + } + if val := resp.Header.Get("x-ms-lease-state"); val != "" { + result.LeaseState = (*LeaseStateType)(&val) + } + if val := resp.Header.Get("x-ms-lease-status"); val != "" { + result.LeaseStatus = (*LeaseStatusType)(&val) + } + if val := resp.Header.Get("x-ms-legal-hold"); val != "" { + legalHold, err := strconv.ParseBool(val) + if err != nil { + return ClientGetPropertiesResponse{}, err + } + result.LegalHold = &legalHold + } + for hh := range resp.Header { + if len(hh) > len("x-ms-meta-") && strings.EqualFold(hh[:len("x-ms-meta-")], "x-ms-meta-") { + if result.Metadata == nil { + result.Metadata = map[string]*string{} + } + result.Metadata[hh[len("x-ms-meta-"):]] = to.Ptr(resp.Header.Get(hh)) + } + } + if val := resp.Header.Get("x-ms-or-policy-id"); val != "" { + result.ObjectReplicationPolicyID = &val + } + for hh := range resp.Header { + if len(hh) > len("x-ms-or-") && strings.EqualFold(hh[:len("x-ms-or-")], "x-ms-or-") { + if result.ObjectReplicationRules == nil { + result.ObjectReplicationRules = map[string]*string{} + } + result.ObjectReplicationRules[hh[len("x-ms-or-"):]] = to.Ptr(resp.Header.Get(hh)) + } + } + if val := resp.Header.Get("x-ms-rehydrate-priority"); val != "" { + result.RehydratePriority = &val + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-smart-access-tier"); val != "" { + result.SmartAccessTier = &val + } + if val := resp.Header.Get("x-ms-tag-count"); val != "" { + tagCount, err := strconv.ParseInt(val, 10, 64) + if err != nil { + return ClientGetPropertiesResponse{}, err + } + result.TagCount = &tagCount + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + if val := resp.Header.Get("x-ms-version-id"); val != "" { + result.VersionID = &val + } + return result, nil +} + +// GetTags - Gets the tags of the specified blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientGetTagsOptions contains the optional parameters for the Client.GetTags method. +func (client *Client) GetTags(ctx context.Context, options *ClientGetTagsOptions) (ClientGetTagsResponse, error) { + var err error + req, err := client.getTagsCreateRequest(ctx, options) + if err != nil { + return ClientGetTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientGetTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientGetTagsResponse{}, err + } + resp, err := client.getTagsHandleResponse(httpResp) + return resp, err +} + +// getTagsCreateRequest creates the GetTags request. +func (client *Client) getTagsCreateRequest(ctx context.Context, options *ClientGetTagsOptions) (*policy.Request, error) { + urlPath := "?comp=tags" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Snapshot != nil { + reqQP.Set("snapshot", *options.Snapshot) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + if options != nil && options.VersionID != nil { + reqQP.Set("versionid", *options.VersionID) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/xml"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["x-ms-blob-if-match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["x-ms-blob-if-modified-since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["x-ms-blob-if-none-match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["x-ms-blob-if-unmodified-since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// getTagsHandleResponse handles the GetTags response. +func (client *Client) getTagsHandleResponse(resp *http.Response) (ClientGetTagsResponse, error) { + result := ClientGetTagsResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientGetTagsResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + if err := runtime.UnmarshalAsXML(resp, &result.Tags); err != nil { + return ClientGetTagsResponse{}, err + } + return result, nil +} + +// ReleaseLease - Frees the lease if it's no longer needed, so that another client can immediately acquire a lease against +// the blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - leaseID - A lease ID for the resource. The resource must have an active lease and the lease ID must match. +// - options - ClientReleaseLeaseOptions contains the optional parameters for the Client.ReleaseLease method. +func (client *Client) ReleaseLease(ctx context.Context, leaseID string, options *ClientReleaseLeaseOptions) (ClientReleaseLeaseResponse, error) { + var err error + req, err := client.releaseLeaseCreateRequest(ctx, leaseID, options) + if err != nil { + return ClientReleaseLeaseResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientReleaseLeaseResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientReleaseLeaseResponse{}, err + } + resp, err := client.releaseLeaseHandleResponse(httpResp) + return resp, err +} + +// releaseLeaseCreateRequest creates the ReleaseLease request. +func (client *Client) releaseLeaseCreateRequest(ctx context.Context, leaseID string, options *ClientReleaseLeaseOptions) (*policy.Request, error) { + urlPath := "?comp=lease" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + req.Raw().Header["x-ms-lease-action"] = []string{"release"} + req.Raw().Header["x-ms-lease-id"] = []string{leaseID} + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// releaseLeaseHandleResponse handles the ReleaseLease response. +func (client *Client) releaseLeaseHandleResponse(resp *http.Response) (ClientReleaseLeaseResponse, error) { + result := ClientReleaseLeaseResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientReleaseLeaseResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientReleaseLeaseResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// RenewLease - Renews an existing lease. +// If the operation fails it returns an *azcore.ResponseError type. +// - leaseID - A lease ID for the resource. The resource must have an active lease and the lease ID must match. +// - options - ClientRenewLeaseOptions contains the optional parameters for the Client.RenewLease method. +func (client *Client) RenewLease(ctx context.Context, leaseID string, options *ClientRenewLeaseOptions) (ClientRenewLeaseResponse, error) { + var err error + req, err := client.renewLeaseCreateRequest(ctx, leaseID, options) + if err != nil { + return ClientRenewLeaseResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientRenewLeaseResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientRenewLeaseResponse{}, err + } + resp, err := client.renewLeaseHandleResponse(httpResp) + return resp, err +} + +// renewLeaseCreateRequest creates the RenewLease request. +func (client *Client) renewLeaseCreateRequest(ctx context.Context, leaseID string, options *ClientRenewLeaseOptions) (*policy.Request, error) { + urlPath := "?comp=lease" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + req.Raw().Header["x-ms-lease-action"] = []string{"renew"} + req.Raw().Header["x-ms-lease-id"] = []string{leaseID} + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// renewLeaseHandleResponse handles the RenewLease response. +func (client *Client) renewLeaseHandleResponse(resp *http.Response) (ClientRenewLeaseResponse, error) { + result := ClientRenewLeaseResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientRenewLeaseResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientRenewLeaseResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-lease-id"); val != "" { + result.LeaseID = &val + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// SetExpiry - Set the expiration time of the specified blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - expiryOptions - Indicates the mode of the expiry time. +// - options - ClientSetExpiryOptions contains the optional parameters for the Client.SetExpiry method. +func (client *Client) SetExpiry(ctx context.Context, expiryOptions ExpiryOptions, options *ClientSetExpiryOptions) (ClientSetExpiryResponse, error) { + var err error + req, err := client.setExpiryCreateRequest(ctx, expiryOptions, options) + if err != nil { + return ClientSetExpiryResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientSetExpiryResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientSetExpiryResponse{}, err + } + resp, err := client.setExpiryHandleResponse(httpResp) + return resp, err +} + +// setExpiryCreateRequest creates the SetExpiry request. +func (client *Client) setExpiryCreateRequest(ctx context.Context, expiryOptions ExpiryOptions, options *ClientSetExpiryOptions) (*policy.Request, error) { + urlPath := "?comp=expiry" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-expiry-option"] = []string{string(expiryOptions)} + if options != nil && options.ExpiresOn != nil { + req.Raw().Header["x-ms-expiry-time"] = []string{*options.ExpiresOn} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// setExpiryHandleResponse handles the SetExpiry response. +func (client *Client) setExpiryHandleResponse(resp *http.Response) (ClientSetExpiryResponse, error) { + result := ClientSetExpiryResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientSetExpiryResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientSetExpiryResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// SetHTTPHeaders - Sets system properties on the specified blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientSetHTTPHeadersOptions contains the optional parameters for the Client.SetHTTPHeaders method. +func (client *Client) SetHTTPHeaders(ctx context.Context, options *ClientSetHTTPHeadersOptions) (ClientSetHTTPHeadersResponse, error) { + var err error + req, err := client.setHTTPHeadersCreateRequest(ctx, options) + if err != nil { + return ClientSetHTTPHeadersResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientSetHTTPHeadersResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientSetHTTPHeadersResponse{}, err + } + resp, err := client.setHTTPHeadersHandleResponse(httpResp) + return resp, err +} + +// setHTTPHeadersCreateRequest creates the SetHTTPHeaders request. +func (client *Client) setHTTPHeadersCreateRequest(ctx context.Context, options *ClientSetHTTPHeadersOptions) (*policy.Request, error) { + urlPath := "?comp=properties" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.BlobCacheControl != nil { + req.Raw().Header["x-ms-blob-cache-control"] = []string{*options.BlobCacheControl} + } + if options != nil && options.BlobContentDisposition != nil { + req.Raw().Header["x-ms-blob-content-disposition"] = []string{*options.BlobContentDisposition} + } + if options != nil && options.BlobContentEncoding != nil { + req.Raw().Header["x-ms-blob-content-encoding"] = []string{*options.BlobContentEncoding} + } + if options != nil && options.BlobContentLanguage != nil { + req.Raw().Header["x-ms-blob-content-language"] = []string{*options.BlobContentLanguage} + } + if options != nil && options.BlobContentMD5 != nil { + req.Raw().Header["x-ms-blob-content-md5"] = []string{base64.StdEncoding.EncodeToString(options.BlobContentMD5)} + } + if options != nil && options.BlobContentType != nil { + req.Raw().Header["x-ms-blob-content-type"] = []string{*options.BlobContentType} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// setHTTPHeadersHandleResponse handles the SetHTTPHeaders response. +func (client *Client) setHTTPHeadersHandleResponse(resp *http.Response) (ClientSetHTTPHeadersResponse, error) { + result := ClientSetHTTPHeadersResponse{} + if val := resp.Header.Get("x-ms-blob-sequence-number"); val != "" { + blobSequenceNumber, err := strconv.ParseInt(val, 10, 64) + if err != nil { + return ClientSetHTTPHeadersResponse{}, err + } + result.BlobSequenceNumber = &blobSequenceNumber + } + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientSetHTTPHeadersResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientSetHTTPHeadersResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// SetImmutabilityPolicy - Set the immutability policy on the specified blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - expiry - The date-time that indicates the time at which the blob immutability policy will expire. +// - options - ClientSetImmutabilityPolicyOptions contains the optional parameters for the Client.SetImmutabilityPolicy method. +func (client *Client) SetImmutabilityPolicy(ctx context.Context, expiry time.Time, options *ClientSetImmutabilityPolicyOptions) (ClientSetImmutabilityPolicyResponse, error) { + var err error + req, err := client.setImmutabilityPolicyCreateRequest(ctx, expiry, options) + if err != nil { + return ClientSetImmutabilityPolicyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientSetImmutabilityPolicyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientSetImmutabilityPolicyResponse{}, err + } + resp, err := client.setImmutabilityPolicyHandleResponse(httpResp) + return resp, err +} + +// setImmutabilityPolicyCreateRequest creates the SetImmutabilityPolicy request. +func (client *Client) setImmutabilityPolicyCreateRequest(ctx context.Context, expiry time.Time, options *ClientSetImmutabilityPolicyOptions) (*policy.Request, error) { + urlPath := "?comp=immutabilityPolicies" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Snapshot != nil { + reqQP.Set("snapshot", *options.Snapshot) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + if options != nil && options.VersionID != nil { + reqQP.Set("versionid", *options.VersionID) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.ImmutabilityPolicyMode != nil { + req.Raw().Header["x-ms-immutability-policy-mode"] = []string{string(*options.ImmutabilityPolicyMode)} + } + req.Raw().Header["x-ms-immutability-policy-until-date"] = []string{datetime.RFC7231(expiry).String()} + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// setImmutabilityPolicyHandleResponse handles the SetImmutabilityPolicy response. +func (client *Client) setImmutabilityPolicyHandleResponse(resp *http.Response) (ClientSetImmutabilityPolicyResponse, error) { + result := ClientSetImmutabilityPolicyResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientSetImmutabilityPolicyResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-immutability-policy-until-date"); val != "" { + immutabilityPolicyExpiry, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientSetImmutabilityPolicyResponse{}, err + } + result.ImmutabilityPolicyExpiry = &immutabilityPolicyExpiry + } + if val := resp.Header.Get("x-ms-immutability-policy-mode"); val != "" { + result.ImmutabilityPolicyMode = (*ImmutabilityPolicyMode)(&val) + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// SetLegalHold - Sets a legal hold on the specified blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - legalHold - Indicates whether the blob has a legal hold. +// - options - ClientSetLegalHoldOptions contains the optional parameters for the Client.SetLegalHold method. +func (client *Client) SetLegalHold(ctx context.Context, legalHold bool, options *ClientSetLegalHoldOptions) (ClientSetLegalHoldResponse, error) { + var err error + req, err := client.setLegalHoldCreateRequest(ctx, legalHold, options) + if err != nil { + return ClientSetLegalHoldResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientSetLegalHoldResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientSetLegalHoldResponse{}, err + } + resp, err := client.setLegalHoldHandleResponse(httpResp) + return resp, err +} + +// setLegalHoldCreateRequest creates the SetLegalHold request. +func (client *Client) setLegalHoldCreateRequest(ctx context.Context, legalHold bool, options *ClientSetLegalHoldOptions) (*policy.Request, error) { + urlPath := "?comp=legalhold" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Snapshot != nil { + reqQP.Set("snapshot", *options.Snapshot) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + if options != nil && options.VersionID != nil { + reqQP.Set("versionid", *options.VersionID) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-legal-hold"] = []string{strconv.FormatBool(legalHold)} + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// setLegalHoldHandleResponse handles the SetLegalHold response. +func (client *Client) setLegalHoldHandleResponse(resp *http.Response) (ClientSetLegalHoldResponse, error) { + result := ClientSetLegalHoldResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientSetLegalHoldResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-legal-hold"); val != "" { + legalHold, err := strconv.ParseBool(val) + if err != nil { + return ClientSetLegalHoldResponse{}, err + } + result.LegalHold = &legalHold + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// SetMetadata - Sets user-defined metadata for the specified blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientSetMetadataOptions contains the optional parameters for the Client.SetMetadata method. +func (client *Client) SetMetadata(ctx context.Context, options *ClientSetMetadataOptions) (ClientSetMetadataResponse, error) { + var err error + req, err := client.setMetadataCreateRequest(ctx, options) + if err != nil { + return ClientSetMetadataResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientSetMetadataResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientSetMetadataResponse{}, err + } + resp, err := client.setMetadataHandleResponse(httpResp) + return resp, err +} + +// setMetadataCreateRequest creates the SetMetadata request. +func (client *Client) setMetadataCreateRequest(ctx context.Context, options *ClientSetMetadataOptions) (*policy.Request, error) { + urlPath := "?comp=metadata" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.EncryptionAlgorithm != nil { + req.Raw().Header["x-ms-encryption-algorithm"] = []string{string(*options.EncryptionAlgorithm)} + } + if options != nil && options.EncryptionKey != nil { + req.Raw().Header["x-ms-encryption-key"] = []string{*options.EncryptionKey} + } + if options != nil && options.EncryptionKeySHA256 != nil { + req.Raw().Header["x-ms-encryption-key-sha256"] = []string{*options.EncryptionKeySHA256} + } + if options != nil && options.EncryptionScope != nil { + req.Raw().Header["x-ms-encryption-scope"] = []string{*options.EncryptionScope} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + if options != nil && options.Metadata != nil { + for k, v := range options.Metadata { + if v != nil { + req.Raw().Header["x-ms-meta-"+k] = []string{*v} + } + } + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// setMetadataHandleResponse handles the SetMetadata response. +func (client *Client) setMetadataHandleResponse(resp *http.Response) (ClientSetMetadataResponse, error) { + result := ClientSetMetadataResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientSetMetadataResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("x-ms-encryption-key-sha256"); val != "" { + result.EncryptionKeySHA256 = &val + } + if val := resp.Header.Get("x-ms-encryption-scope"); val != "" { + result.EncryptionScope = &val + } + if val := resp.Header.Get("x-ms-request-server-encrypted"); val != "" { + isServerEncrypted, err := strconv.ParseBool(val) + if err != nil { + return ClientSetMetadataResponse{}, err + } + result.IsServerEncrypted = &isServerEncrypted + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientSetMetadataResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + if val := resp.Header.Get("x-ms-version-id"); val != "" { + result.VersionID = &val + } + return result, nil +} + +// SetTags - Sets the tags of the specified blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - tags - The blob tags. +// - options - ClientSetTagsOptions contains the optional parameters for the Client.SetTags method. +func (client *Client) SetTags(ctx context.Context, tags Tags, options *ClientSetTagsOptions) (ClientSetTagsResponse, error) { + var err error + req, err := client.setTagsCreateRequest(ctx, tags, options) + if err != nil { + return ClientSetTagsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientSetTagsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ClientSetTagsResponse{}, err + } + resp, err := client.setTagsHandleResponse(httpResp) + return resp, err +} + +// setTagsCreateRequest creates the SetTags request. +func (client *Client) setTagsCreateRequest(ctx context.Context, tags Tags, options *ClientSetTagsOptions) (*policy.Request, error) { + urlPath := "?comp=tags" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + if options != nil && options.VersionID != nil { + reqQP.Set("versionid", *options.VersionID) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.TransactionalContentMD5 != nil { + req.Raw().Header["Content-MD5"] = []string{base64.StdEncoding.EncodeToString(options.TransactionalContentMD5)} + } + if options != nil && options.IfMatch != nil { + req.Raw().Header["x-ms-blob-if-match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["x-ms-blob-if-modified-since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["x-ms-blob-if-none-match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["x-ms-blob-if-unmodified-since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.TransactionalContentCRC64 != nil { + req.Raw().Header["x-ms-content-crc64"] = []string{base64.StdEncoding.EncodeToString(options.TransactionalContentCRC64)} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, tags); err != nil { + return nil, err + } + return req, nil +} + +// setTagsHandleResponse handles the SetTags response. +func (client *Client) setTagsHandleResponse(resp *http.Response) (ClientSetTagsResponse, error) { + result := ClientSetTagsResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientSetTagsResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// SetTier - Sets the tier of the specified blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - tier - Indicates the tier to be set on the blob. +// - options - ClientSetTierOptions contains the optional parameters for the Client.SetTier method. +func (client *Client) SetTier(ctx context.Context, tier AccessTier, options *ClientSetTierOptions) (ClientSetTierResponse, error) { + var err error + req, err := client.setTierCreateRequest(ctx, tier, options) + if err != nil { + return ClientSetTierResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientSetTierResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return ClientSetTierResponse{}, err + } + resp, err := client.setTierHandleResponse(httpResp) + return resp, err +} + +// setTierCreateRequest creates the SetTier request. +func (client *Client) setTierCreateRequest(ctx context.Context, tier AccessTier, options *ClientSetTierOptions) (*policy.Request, error) { + urlPath := "?comp=tier" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Snapshot != nil { + reqQP.Set("snapshot", *options.Snapshot) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + if options != nil && options.VersionID != nil { + reqQP.Set("versionid", *options.VersionID) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["x-ms-access-tier"] = []string{string(tier)} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + if options != nil && options.RehydratePriority != nil { + req.Raw().Header["x-ms-rehydrate-priority"] = []string{string(*options.RehydratePriority)} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// setTierHandleResponse handles the SetTier response. +func (client *Client) setTierHandleResponse(resp *http.Response) (ClientSetTierResponse, error) { + result := ClientSetTierResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientSetTierResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// StartCopyFromURL - Starts an asynchronous copy from a source URL to a destination blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - copySource - Specifies the name of the source URL for the copy operation. The value should be URL-encoded as it would appear +// in a request URI. +// - options - ClientStartCopyFromURLOptions contains the optional parameters for the Client.StartCopyFromURL method. +func (client *Client) StartCopyFromURL(ctx context.Context, copySource string, options *ClientStartCopyFromURLOptions) (ClientStartCopyFromURLResponse, error) { + var err error + req, err := client.startCopyFromURLCreateRequest(ctx, copySource, options) + if err != nil { + return ClientStartCopyFromURLResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientStartCopyFromURLResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return ClientStartCopyFromURLResponse{}, err + } + resp, err := client.startCopyFromURLHandleResponse(httpResp) + return resp, err +} + +// startCopyFromURLCreateRequest creates the StartCopyFromURL request. +func (client *Client) startCopyFromURLCreateRequest(ctx context.Context, copySource string, options *ClientStartCopyFromURLOptions) (*policy.Request, error) { + req, err := runtime.NewRequest(ctx, http.MethodPut, client.url) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.Tier != nil { + req.Raw().Header["x-ms-access-tier"] = []string{string(*options.Tier)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-copy-source"] = []string{copySource} + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + if options != nil && options.ImmutabilityPolicyMode != nil { + req.Raw().Header["x-ms-immutability-policy-mode"] = []string{string(*options.ImmutabilityPolicyMode)} + } + if options != nil && options.ImmutabilityPolicyExpiry != nil { + req.Raw().Header["x-ms-immutability-policy-until-date"] = []string{datetime.RFC7231(*options.ImmutabilityPolicyExpiry).String()} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + if options != nil && options.LegalHold != nil { + req.Raw().Header["x-ms-legal-hold"] = []string{strconv.FormatBool(*options.LegalHold)} + } + if options != nil && options.Metadata != nil { + for k, v := range options.Metadata { + if v != nil { + req.Raw().Header["x-ms-meta-"+k] = []string{*v} + } + } + } + if options != nil && options.RehydratePriority != nil { + req.Raw().Header["x-ms-rehydrate-priority"] = []string{string(*options.RehydratePriority)} + } + if options != nil && options.SealBlob != nil { + req.Raw().Header["x-ms-seal-blob"] = []string{strconv.FormatBool(*options.SealBlob)} + } + if options != nil && options.SourceIfMatch != nil { + req.Raw().Header["x-ms-source-if-match"] = []string{string(*options.SourceIfMatch)} + } + if options != nil && options.SourceIfModifiedSince != nil { + req.Raw().Header["x-ms-source-if-modified-since"] = []string{datetime.RFC7231(*options.SourceIfModifiedSince).String()} + } + if options != nil && options.SourceIfNoneMatch != nil { + req.Raw().Header["x-ms-source-if-none-match"] = []string{string(*options.SourceIfNoneMatch)} + } + if options != nil && options.SourceIfTags != nil { + req.Raw().Header["x-ms-source-if-tags"] = []string{*options.SourceIfTags} + } + if options != nil && options.SourceIfUnmodifiedSince != nil { + req.Raw().Header["x-ms-source-if-unmodified-since"] = []string{datetime.RFC7231(*options.SourceIfUnmodifiedSince).String()} + } + if options != nil && options.BlobTagsString != nil { + req.Raw().Header["x-ms-tags"] = []string{*options.BlobTagsString} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// startCopyFromURLHandleResponse handles the StartCopyFromURL response. +func (client *Client) startCopyFromURLHandleResponse(resp *http.Response) (ClientStartCopyFromURLResponse, error) { + result := ClientStartCopyFromURLResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("x-ms-copy-id"); val != "" { + result.CopyID = &val + } + if val := resp.Header.Get("x-ms-copy-status"); val != "" { + result.CopyStatus = (*CopyStatusType)(&val) + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientStartCopyFromURLResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientStartCopyFromURLResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + if val := resp.Header.Get("x-ms-version-id"); val != "" { + result.VersionID = &val + } + return result, nil +} + +// Undelete - Undelete the specified previously soft deleted blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientUndeleteOptions contains the optional parameters for the Client.Undelete method. +func (client *Client) Undelete(ctx context.Context, options *ClientUndeleteOptions) (ClientUndeleteResponse, error) { + var err error + req, err := client.undeleteCreateRequest(ctx, options) + if err != nil { + return ClientUndeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientUndeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientUndeleteResponse{}, err + } + resp, err := client.undeleteHandleResponse(httpResp) + return resp, err +} + +// undeleteCreateRequest creates the Undelete request. +func (client *Client) undeleteCreateRequest(ctx context.Context, options *ClientUndeleteOptions) (*policy.Request, error) { + urlPath := "?comp=undelete" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// undeleteHandleResponse handles the Undelete response. +func (client *Client) undeleteHandleResponse(resp *http.Response) (ClientUndeleteResponse, error) { + result := ClientUndeleteResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ClientUndeleteResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} diff --git a/test/local/azblob/zz_constants.go b/test/local/azblob/zz_constants.go new file mode 100644 index 000000000000..24627e6729fa --- /dev/null +++ b/test/local/azblob/zz_constants.go @@ -0,0 +1,1046 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azblob + +const ( + version20260606 string = "2026-06-06" +) + +// AccessTier - The access tiers. +type AccessTier string + +const ( + // AccessTierArchive - The Archive access tier. + AccessTierArchive AccessTier = "Archive" + // AccessTierCold - The Cold access tier. + AccessTierCold AccessTier = "Cold" + // AccessTierCool - The Cool access tier. + AccessTierCool AccessTier = "Cool" + // AccessTierHot - The Hot access tier. + AccessTierHot AccessTier = "Hot" + // AccessTierP10 - The P10 access tier. + AccessTierP10 AccessTier = "P10" + // AccessTierP15 - The P15 access tier. + AccessTierP15 AccessTier = "P15" + // AccessTierP20 - The P20 access tier. + AccessTierP20 AccessTier = "P20" + // AccessTierP30 - The P30 access tier. + AccessTierP30 AccessTier = "P30" + // AccessTierP4 - The P4 access tier. + AccessTierP4 AccessTier = "P4" + // AccessTierP40 - The P40 access tier. + AccessTierP40 AccessTier = "P40" + // AccessTierP50 - The P50 access tier. + AccessTierP50 AccessTier = "P50" + // AccessTierP6 - The P6 access tier. + AccessTierP6 AccessTier = "P6" + // AccessTierP60 - The P60 access tier. + AccessTierP60 AccessTier = "P60" + // AccessTierP70 - The P70 access tier. + AccessTierP70 AccessTier = "P70" + // AccessTierP80 - The P80 access tier. + AccessTierP80 AccessTier = "P80" + // AccessTierPremium - The Premium access tier. + AccessTierPremium AccessTier = "Premium" + // AccessTierSmart - The Smart access tier. + AccessTierSmart AccessTier = "Smart" +) + +// PossibleAccessTierValues returns the possible values for the AccessTier const type. +func PossibleAccessTierValues() []AccessTier { + return []AccessTier{ + AccessTierArchive, + AccessTierCold, + AccessTierCool, + AccessTierHot, + AccessTierP10, + AccessTierP15, + AccessTierP20, + AccessTierP30, + AccessTierP4, + AccessTierP40, + AccessTierP50, + AccessTierP6, + AccessTierP60, + AccessTierP70, + AccessTierP80, + AccessTierPremium, + AccessTierSmart, + } +} + +// AccountKind - The account kind. +type AccountKind string + +const ( + // AccountKindBlobStorage - A blob storage account. + AccountKindBlobStorage AccountKind = "BlobStorage" + // AccountKindBlockBlobStorage - A block blob storage account. + AccountKindBlockBlobStorage AccountKind = "BlockBlobStorage" + // AccountKindFileStorage - A file storage account. + AccountKindFileStorage AccountKind = "FileStorage" + // AccountKindStorage - A general-purpose account. + AccountKindStorage AccountKind = "Storage" + // AccountKindStorageV2 - A storage V2 account. + AccountKindStorageV2 AccountKind = "StorageV2" +) + +// PossibleAccountKindValues returns the possible values for the AccountKind const type. +func PossibleAccountKindValues() []AccountKind { + return []AccountKind{ + AccountKindBlobStorage, + AccountKindBlockBlobStorage, + AccountKindFileStorage, + AccountKindStorage, + AccountKindStorageV2, + } +} + +// ArchiveStatus - The archive status. +type ArchiveStatus string + +const ( + // ArchiveStatusRehydratePendingToCold - The archive status is rehydrating pending to Cold. + ArchiveStatusRehydratePendingToCold ArchiveStatus = "rehydrate-pending-to-cold" + // ArchiveStatusRehydratePendingToCool - The archive status is rehydrating pending to Cool. + ArchiveStatusRehydratePendingToCool ArchiveStatus = "rehydrate-pending-to-cool" + // ArchiveStatusRehydratePendingToHot - The archive status is rehydrating pending to Hot. + ArchiveStatusRehydratePendingToHot ArchiveStatus = "rehydrate-pending-to-hot" + // ArchiveStatusRehydratePendingToSmart - The archive status is rehydrating pending to Smart. + ArchiveStatusRehydratePendingToSmart ArchiveStatus = "rehydrate-pending-to-smart" +) + +// PossibleArchiveStatusValues returns the possible values for the ArchiveStatus const type. +func PossibleArchiveStatusValues() []ArchiveStatus { + return []ArchiveStatus{ + ArchiveStatusRehydratePendingToCold, + ArchiveStatusRehydratePendingToCool, + ArchiveStatusRehydratePendingToHot, + ArchiveStatusRehydratePendingToSmart, + } +} + +// BlockListType - The block list types. +type BlockListType string + +const ( + // BlockListTypeAll - Both committed and uncommitted blocks. + BlockListTypeAll BlockListType = "all" + // BlockListTypeCommitted - Committed blocks. + BlockListTypeCommitted BlockListType = "committed" + // BlockListTypeUncommitted - Uncommitted blocks. + BlockListTypeUncommitted BlockListType = "uncommitted" +) + +// PossibleBlockListTypeValues returns the possible values for the BlockListType const type. +func PossibleBlockListTypeValues() []BlockListType { + return []BlockListType{ + BlockListTypeAll, + BlockListTypeCommitted, + BlockListTypeUncommitted, + } +} + +// CopySourceTags - The blob copy source tags types. +type CopySourceTags string + +const ( + // CopySourceTagsCOPY - The blob tags will be copied from the source. + CopySourceTagsCOPY CopySourceTags = "COPY" + // CopySourceTagsREPLACE - The blob tags will be replaced. + CopySourceTagsREPLACE CopySourceTags = "REPLACE" +) + +// PossibleCopySourceTagsValues returns the possible values for the CopySourceTags const type. +func PossibleCopySourceTagsValues() []CopySourceTags { + return []CopySourceTags{ + CopySourceTagsCOPY, + CopySourceTagsREPLACE, + } +} + +// CopyStatusType - The copy status. +type CopyStatusType string + +const ( + // CopyStatusTypeAborted - The copy operation was aborted. + CopyStatusTypeAborted CopyStatusType = "aborted" + // CopyStatusTypeFailed - The copy operation failed. + CopyStatusTypeFailed CopyStatusType = "failed" + // CopyStatusTypePending - The copy operation is pending. + CopyStatusTypePending CopyStatusType = "pending" + // CopyStatusTypeSuccess - The copy operation succeeded. + CopyStatusTypeSuccess CopyStatusType = "success" +) + +// PossibleCopyStatusTypeValues returns the possible values for the CopyStatusType const type. +func PossibleCopyStatusTypeValues() []CopyStatusType { + return []CopyStatusType{ + CopyStatusTypeAborted, + CopyStatusTypeFailed, + CopyStatusTypePending, + CopyStatusTypeSuccess, + } +} + +// DeleteSnapshotsOptionType - Specifies the delete behavior of blob snapshots. +type DeleteSnapshotsOptionType string + +const ( + // DeleteSnapshotsOptionTypeInclude - Delete the blob and snapshots. + DeleteSnapshotsOptionTypeInclude DeleteSnapshotsOptionType = "include" + // DeleteSnapshotsOptionTypeOnly - Only delete the snapshots. + DeleteSnapshotsOptionTypeOnly DeleteSnapshotsOptionType = "only" +) + +// PossibleDeleteSnapshotsOptionTypeValues returns the possible values for the DeleteSnapshotsOptionType const type. +func PossibleDeleteSnapshotsOptionTypeValues() []DeleteSnapshotsOptionType { + return []DeleteSnapshotsOptionType{ + DeleteSnapshotsOptionTypeInclude, + DeleteSnapshotsOptionTypeOnly, + } +} + +// DeleteType - The type of blob deletions. +type DeleteType string + +const ( + // DeleteTypeNone - None. + DeleteTypeNone DeleteType = "None" + // DeleteTypePermanent - Permanently delete the blob. + DeleteTypePermanent DeleteType = "Permanent" +) + +// PossibleDeleteTypeValues returns the possible values for the DeleteType const type. +func PossibleDeleteTypeValues() []DeleteType { + return []DeleteType{ + DeleteTypeNone, + DeleteTypePermanent, + } +} + +// EncryptionAlgorithmType - The algorithm used to produce the encryption key hash. Currently, the only accepted value is +// \"AES256\". Must be provided if the x-ms-encryption-key header is provided. +type EncryptionAlgorithmType string + +const ( + // EncryptionAlgorithmTypeAES256 - AES256 + EncryptionAlgorithmTypeAES256 EncryptionAlgorithmType = "AES256" + // EncryptionAlgorithmTypeNone - Deprecated + EncryptionAlgorithmTypeNone EncryptionAlgorithmType = "None" +) + +// PossibleEncryptionAlgorithmTypeValues returns the possible values for the EncryptionAlgorithmType const type. +func PossibleEncryptionAlgorithmTypeValues() []EncryptionAlgorithmType { + return []EncryptionAlgorithmType{ + EncryptionAlgorithmTypeAES256, + EncryptionAlgorithmTypeNone, + } +} + +// ExpiryOptions - The blob expiry options. +type ExpiryOptions string + +const ( + // ExpiryOptionsAbsolute - Absolute time. + ExpiryOptionsAbsolute ExpiryOptions = "Absolute" + // ExpiryOptionsNeverExpire - Never expire. + ExpiryOptionsNeverExpire ExpiryOptions = "NeverExpire" + // ExpiryOptionsRelativeToCreation - Relative to creation time. + ExpiryOptionsRelativeToCreation ExpiryOptions = "RelativeToCreation" + // ExpiryOptionsRelativeToNow - Relative to now. + ExpiryOptionsRelativeToNow ExpiryOptions = "RelativeToNow" +) + +// PossibleExpiryOptionsValues returns the possible values for the ExpiryOptions const type. +func PossibleExpiryOptionsValues() []ExpiryOptions { + return []ExpiryOptions{ + ExpiryOptionsAbsolute, + ExpiryOptionsNeverExpire, + ExpiryOptionsRelativeToCreation, + ExpiryOptionsRelativeToNow, + } +} + +// FileShareTokenIntent - The file share token intent types. +type FileShareTokenIntent string + +const ( + // FileShareTokenIntentBackup - The file share token intent is backup. + FileShareTokenIntentBackup FileShareTokenIntent = "backup" +) + +// PossibleFileShareTokenIntentValues returns the possible values for the FileShareTokenIntent const type. +func PossibleFileShareTokenIntentValues() []FileShareTokenIntent { + return []FileShareTokenIntent{ + FileShareTokenIntentBackup, + } +} + +// FilterBlobsIncludeItem - Specifies what type of blobs should be returned as part of the filter operation. +type FilterBlobsIncludeItem string + +const ( + // FilterBlobsIncludeItemNone - The filter includes no versions. + FilterBlobsIncludeItemNone FilterBlobsIncludeItem = "none" + // FilterBlobsIncludeItemVersions - The filter includes versions. + FilterBlobsIncludeItemVersions FilterBlobsIncludeItem = "versions" +) + +// PossibleFilterBlobsIncludeItemValues returns the possible values for the FilterBlobsIncludeItem const type. +func PossibleFilterBlobsIncludeItemValues() []FilterBlobsIncludeItem { + return []FilterBlobsIncludeItem{ + FilterBlobsIncludeItemNone, + FilterBlobsIncludeItemVersions, + } +} + +// GeoReplicationStatus - The geo-replication status. +type GeoReplicationStatus string + +const ( + // GeoReplicationStatusBootstrap - Geo-replication is bootstrap. + GeoReplicationStatusBootstrap GeoReplicationStatus = "bootstrap" + // GeoReplicationStatusLive - Geo-replication is live. + GeoReplicationStatusLive GeoReplicationStatus = "live" + // GeoReplicationStatusUnavailable - Geo-replication is unavailable. + GeoReplicationStatusUnavailable GeoReplicationStatus = "unavailable" +) + +// PossibleGeoReplicationStatusValues returns the possible values for the GeoReplicationStatus const type. +func PossibleGeoReplicationStatusValues() []GeoReplicationStatus { + return []GeoReplicationStatus{ + GeoReplicationStatusBootstrap, + GeoReplicationStatusLive, + GeoReplicationStatusUnavailable, + } +} + +// ImmutabilityPolicyMode - The immutability policy mode. +type ImmutabilityPolicyMode string + +const ( + // ImmutabilityPolicyModeLocked - The immutability policy is locked. + ImmutabilityPolicyModeLocked ImmutabilityPolicyMode = "locked" + // ImmutabilityPolicyModeMutable - Response only. The immutability policy is mutable. + ImmutabilityPolicyModeMutable ImmutabilityPolicyMode = "mutable" + // ImmutabilityPolicyModeUnlocked - The immutability policy is unlocked. + ImmutabilityPolicyModeUnlocked ImmutabilityPolicyMode = "unlocked" +) + +// PossibleImmutabilityPolicyModeValues returns the possible values for the ImmutabilityPolicyMode const type. +func PossibleImmutabilityPolicyModeValues() []ImmutabilityPolicyMode { + return []ImmutabilityPolicyMode{ + ImmutabilityPolicyModeLocked, + ImmutabilityPolicyModeMutable, + ImmutabilityPolicyModeUnlocked, + } +} + +// ImmutabilityPolicySetting - The immutability policy mode used in requests and responses. +type ImmutabilityPolicySetting string + +const ( + // ImmutabilityPolicySettingLocked - The immutability policy is locked. + ImmutabilityPolicySettingLocked ImmutabilityPolicySetting = "Locked" + // ImmutabilityPolicySettingUnlocked - The immutability policy is unlocked. + ImmutabilityPolicySettingUnlocked ImmutabilityPolicySetting = "Unlocked" +) + +// PossibleImmutabilityPolicySettingValues returns the possible values for the ImmutabilityPolicySetting const type. +func PossibleImmutabilityPolicySettingValues() []ImmutabilityPolicySetting { + return []ImmutabilityPolicySetting{ + ImmutabilityPolicySettingLocked, + ImmutabilityPolicySettingUnlocked, + } +} + +// LeaseDurationType - The lease duration. +type LeaseDurationType string + +const ( + // LeaseDurationTypeFixed - The lease is of fixed duration. + LeaseDurationTypeFixed LeaseDurationType = "fixed" + // LeaseDurationTypeInfinite - The lease is of infinite duration. + LeaseDurationTypeInfinite LeaseDurationType = "infinite" +) + +// PossibleLeaseDurationTypeValues returns the possible values for the LeaseDurationType const type. +func PossibleLeaseDurationTypeValues() []LeaseDurationType { + return []LeaseDurationType{ + LeaseDurationTypeFixed, + LeaseDurationTypeInfinite, + } +} + +// LeaseStateType - The lease state. +type LeaseStateType string + +const ( + // LeaseStateTypeAvailable - The lease is available. + LeaseStateTypeAvailable LeaseStateType = "available" + // LeaseStateTypeBreaking - The lease is breaking. + LeaseStateTypeBreaking LeaseStateType = "breaking" + // LeaseStateTypeBroken - The lease is broken. + LeaseStateTypeBroken LeaseStateType = "broken" + // LeaseStateTypeExpired - The lease is expired. + LeaseStateTypeExpired LeaseStateType = "expired" + // LeaseStateTypeLeased - The lease is currently leased. + LeaseStateTypeLeased LeaseStateType = "leased" +) + +// PossibleLeaseStateTypeValues returns the possible values for the LeaseStateType const type. +func PossibleLeaseStateTypeValues() []LeaseStateType { + return []LeaseStateType{ + LeaseStateTypeAvailable, + LeaseStateTypeBreaking, + LeaseStateTypeBroken, + LeaseStateTypeExpired, + LeaseStateTypeLeased, + } +} + +// LeaseStatusType - The lease status. +type LeaseStatusType string + +const ( + // LeaseStatusTypeLocked - The lease is locked. + LeaseStatusTypeLocked LeaseStatusType = "locked" + // LeaseStatusTypeUnlocked - The lease is unlocked. + LeaseStatusTypeUnlocked LeaseStatusType = "unlocked" +) + +// PossibleLeaseStatusTypeValues returns the possible values for the LeaseStatusType const type. +func PossibleLeaseStatusTypeValues() []LeaseStatusType { + return []LeaseStatusType{ + LeaseStatusTypeLocked, + LeaseStatusTypeUnlocked, + } +} + +// ListBlobsIncludeItem - The list blob includes parameter values. +type ListBlobsIncludeItem string + +const ( + // ListBlobsIncludeItemCopy - The include copies. + ListBlobsIncludeItemCopy ListBlobsIncludeItem = "copy" + // ListBlobsIncludeItemDeleted - The include deleted blobs. + ListBlobsIncludeItemDeleted ListBlobsIncludeItem = "deleted" + // ListBlobsIncludeItemDeletedWithVersions - The include deleted with versions. + ListBlobsIncludeItemDeletedWithVersions ListBlobsIncludeItem = "deletedwithversions" + // ListBlobsIncludeItemImmutabilityPolicy - The include immutable policy. + ListBlobsIncludeItemImmutabilityPolicy ListBlobsIncludeItem = "immutabilitypolicy" + // ListBlobsIncludeItemLegalHold - The include legal hold. + ListBlobsIncludeItemLegalHold ListBlobsIncludeItem = "legalhold" + // ListBlobsIncludeItemMetadata - The include metadata. + ListBlobsIncludeItemMetadata ListBlobsIncludeItem = "metadata" + // ListBlobsIncludeItemPermissions - Deprecated + ListBlobsIncludeItemPermissions ListBlobsIncludeItem = "permissions" + // ListBlobsIncludeItemSnapshots - The include snapshots. + ListBlobsIncludeItemSnapshots ListBlobsIncludeItem = "snapshots" + // ListBlobsIncludeItemTags - The include tags. + ListBlobsIncludeItemTags ListBlobsIncludeItem = "tags" + // ListBlobsIncludeItemUncommittedBlobs - The include uncommitted blobs. + ListBlobsIncludeItemUncommittedBlobs ListBlobsIncludeItem = "uncommittedblobs" + // ListBlobsIncludeItemVersions - The include versions. + ListBlobsIncludeItemVersions ListBlobsIncludeItem = "versions" +) + +// PossibleListBlobsIncludeItemValues returns the possible values for the ListBlobsIncludeItem const type. +func PossibleListBlobsIncludeItemValues() []ListBlobsIncludeItem { + return []ListBlobsIncludeItem{ + ListBlobsIncludeItemCopy, + ListBlobsIncludeItemDeleted, + ListBlobsIncludeItemDeletedWithVersions, + ListBlobsIncludeItemImmutabilityPolicy, + ListBlobsIncludeItemLegalHold, + ListBlobsIncludeItemMetadata, + ListBlobsIncludeItemPermissions, + ListBlobsIncludeItemSnapshots, + ListBlobsIncludeItemTags, + ListBlobsIncludeItemUncommittedBlobs, + ListBlobsIncludeItemVersions, + } +} + +// ListContainersIncludeType - Specifies what additional information should be returned as part of the list operation. +type ListContainersIncludeType string + +const ( + // ListContainersIncludeTypeDeleted - Include soft-deleted containers. + ListContainersIncludeTypeDeleted ListContainersIncludeType = "deleted" + // ListContainersIncludeTypeMetadata - Include metadata. + ListContainersIncludeTypeMetadata ListContainersIncludeType = "metadata" + // ListContainersIncludeTypeSystem - Include system containers. + ListContainersIncludeTypeSystem ListContainersIncludeType = "system" +) + +// PossibleListContainersIncludeTypeValues returns the possible values for the ListContainersIncludeType const type. +func PossibleListContainersIncludeTypeValues() []ListContainersIncludeType { + return []ListContainersIncludeType{ + ListContainersIncludeTypeDeleted, + ListContainersIncludeTypeMetadata, + ListContainersIncludeTypeSystem, + } +} + +// PremiumPageBlobAccessTier - The premium page blob access tier types. +type PremiumPageBlobAccessTier string + +const ( + // PremiumPageBlobAccessTierP10 - The premium page blob access tier is P10. + PremiumPageBlobAccessTierP10 PremiumPageBlobAccessTier = "P10" + // PremiumPageBlobAccessTierP15 - The premium page blob access tier is P15. + PremiumPageBlobAccessTierP15 PremiumPageBlobAccessTier = "P15" + // PremiumPageBlobAccessTierP20 - The premium page blob access tier is P20. + PremiumPageBlobAccessTierP20 PremiumPageBlobAccessTier = "P20" + // PremiumPageBlobAccessTierP30 - The premium page blob access tier is P30. + PremiumPageBlobAccessTierP30 PremiumPageBlobAccessTier = "P30" + // PremiumPageBlobAccessTierP4 - The premium page blob access tier is P4. + PremiumPageBlobAccessTierP4 PremiumPageBlobAccessTier = "P4" + // PremiumPageBlobAccessTierP40 - The premium page blob access tier is P40. + PremiumPageBlobAccessTierP40 PremiumPageBlobAccessTier = "P40" + // PremiumPageBlobAccessTierP50 - The premium page blob access tier is P50. + PremiumPageBlobAccessTierP50 PremiumPageBlobAccessTier = "P50" + // PremiumPageBlobAccessTierP6 - The premium page blob access tier is P6. + PremiumPageBlobAccessTierP6 PremiumPageBlobAccessTier = "P6" + // PremiumPageBlobAccessTierP60 - The premium page blob access tier is P60. + PremiumPageBlobAccessTierP60 PremiumPageBlobAccessTier = "P60" + // PremiumPageBlobAccessTierP70 - The premium page blob access tier is P70. + PremiumPageBlobAccessTierP70 PremiumPageBlobAccessTier = "P70" + // PremiumPageBlobAccessTierP80 - The premium page blob access tier is P80. + PremiumPageBlobAccessTierP80 PremiumPageBlobAccessTier = "P80" +) + +// PossiblePremiumPageBlobAccessTierValues returns the possible values for the PremiumPageBlobAccessTier const type. +func PossiblePremiumPageBlobAccessTierValues() []PremiumPageBlobAccessTier { + return []PremiumPageBlobAccessTier{ + PremiumPageBlobAccessTierP10, + PremiumPageBlobAccessTierP15, + PremiumPageBlobAccessTierP20, + PremiumPageBlobAccessTierP30, + PremiumPageBlobAccessTierP4, + PremiumPageBlobAccessTierP40, + PremiumPageBlobAccessTierP50, + PremiumPageBlobAccessTierP6, + PremiumPageBlobAccessTierP60, + PremiumPageBlobAccessTierP70, + PremiumPageBlobAccessTierP80, + } +} + +// PublicAccessType - The public access type. +type PublicAccessType string + +const ( + // PublicAccessTypeBlob - Blob access. + PublicAccessTypeBlob PublicAccessType = "blob" + // PublicAccessTypeContainer - Container access. + PublicAccessTypeContainer PublicAccessType = "container" +) + +// PossiblePublicAccessTypeValues returns the possible values for the PublicAccessType const type. +func PossiblePublicAccessTypeValues() []PublicAccessType { + return []PublicAccessType{ + PublicAccessTypeBlob, + PublicAccessTypeContainer, + } +} + +// QueryFormatType - The query format type. +type QueryFormatType string + +const ( + // QueryFormatTypeArrow - The query format type is Apache Arrow. + QueryFormatTypeArrow QueryFormatType = "arrow" + // QueryFormatTypeDelimited - The query format type is delimited. + QueryFormatTypeDelimited QueryFormatType = "delimited" + // QueryFormatTypeJSON - The query format type is JSON. + QueryFormatTypeJSON QueryFormatType = "json" + // QueryFormatTypeParquet - The query format type is Parquet. + QueryFormatTypeParquet QueryFormatType = "parquet" +) + +// PossibleQueryFormatTypeValues returns the possible values for the QueryFormatType const type. +func PossibleQueryFormatTypeValues() []QueryFormatType { + return []QueryFormatType{ + QueryFormatTypeArrow, + QueryFormatTypeDelimited, + QueryFormatTypeJSON, + QueryFormatTypeParquet, + } +} + +// QueryRequestType - The query request type. +type QueryRequestType string + +const ( + // QueryRequestTypeSQL - The SQL request query type. + QueryRequestTypeSQL QueryRequestType = "SQL" +) + +// PossibleQueryRequestTypeValues returns the possible values for the QueryRequestType const type. +func PossibleQueryRequestTypeValues() []QueryRequestType { + return []QueryRequestType{ + QueryRequestTypeSQL, + } +} + +// RehydratePriority - The priority of the rehydrate operation. +type RehydratePriority string + +const ( + // RehydratePriorityHigh - The rehydrate priority is high. + RehydratePriorityHigh RehydratePriority = "High" + // RehydratePriorityStandard - The rehydrate priority is standard. + RehydratePriorityStandard RehydratePriority = "Standard" +) + +// PossibleRehydratePriorityValues returns the possible values for the RehydratePriority const type. +func PossibleRehydratePriorityValues() []RehydratePriority { + return []RehydratePriority{ + RehydratePriorityHigh, + RehydratePriorityStandard, + } +} + +// SKUName - The account SKU. +type SKUName string + +const ( + // SKUNamePremiumLRS - The premium LRS SKU. + SKUNamePremiumLRS SKUName = "Premium_LRS" + // SKUNamePremiumZRS - The premium ZRS SKU. + SKUNamePremiumZRS SKUName = "Premium_ZRS" + // SKUNameStandardGRS - The standard GRS SKU. + SKUNameStandardGRS SKUName = "Standard_GRS" + // SKUNameStandardGZRS - The standard GZRS SKU. + SKUNameStandardGZRS SKUName = "Standard_GZRS" + // SKUNameStandardLRS - The standard LRS SKU. + SKUNameStandardLRS SKUName = "Standard_LRS" + // SKUNameStandardRAGRS - The standard RAGRS SKU. + SKUNameStandardRAGRS SKUName = "Standard_RAGRS" + // SKUNameStandardRAGZRS - The standard RAGZRS SKU. + SKUNameStandardRAGZRS SKUName = "Standard_RAGZRS" + // SKUNameStandardZRS - The standard ZRS SKU. + SKUNameStandardZRS SKUName = "Standard_ZRS" +) + +// PossibleSKUNameValues returns the possible values for the SKUName const type. +func PossibleSKUNameValues() []SKUName { + return []SKUName{ + SKUNamePremiumLRS, + SKUNamePremiumZRS, + SKUNameStandardGRS, + SKUNameStandardGZRS, + SKUNameStandardLRS, + SKUNameStandardRAGRS, + SKUNameStandardRAGZRS, + SKUNameStandardZRS, + } +} + +// SequenceNumberActionType - The sequence number actions. +type SequenceNumberActionType string + +const ( + // SequenceNumberActionTypeIncrement - Increment the sequence number. + SequenceNumberActionTypeIncrement SequenceNumberActionType = "increment" + // SequenceNumberActionTypeMax - Set the maximum for the sequence number. + SequenceNumberActionTypeMax SequenceNumberActionType = "max" + // SequenceNumberActionTypeUpdate - Update the sequence number. + SequenceNumberActionTypeUpdate SequenceNumberActionType = "update" +) + +// PossibleSequenceNumberActionTypeValues returns the possible values for the SequenceNumberActionType const type. +func PossibleSequenceNumberActionTypeValues() []SequenceNumberActionType { + return []SequenceNumberActionType{ + SequenceNumberActionTypeIncrement, + SequenceNumberActionTypeMax, + SequenceNumberActionTypeUpdate, + } +} + +// StorageErrorCode - Error codes returned by the Azure Blob Storage service. +type StorageErrorCode string + +const ( + // StorageErrorCodeAccountAlreadyExists - Account already exists. + StorageErrorCodeAccountAlreadyExists StorageErrorCode = "AccountAlreadyExists" + // StorageErrorCodeAccountBeingCreated - Account is being created. + StorageErrorCodeAccountBeingCreated StorageErrorCode = "AccountBeingCreated" + // StorageErrorCodeAccountIsDisabled - Account is disabled. + StorageErrorCodeAccountIsDisabled StorageErrorCode = "AccountIsDisabled" + // StorageErrorCodeAppendPositionConditionNotMet - Append position condition not met. + StorageErrorCodeAppendPositionConditionNotMet StorageErrorCode = "AppendPositionConditionNotMet" + // StorageErrorCodeAuthenticationFailed - Authentication failed. + StorageErrorCodeAuthenticationFailed StorageErrorCode = "AuthenticationFailed" + // StorageErrorCodeAuthorizationFailure - Authorization failure. + StorageErrorCodeAuthorizationFailure StorageErrorCode = "AuthorizationFailure" + // StorageErrorCodeAuthorizationPermissionMismatch - Authorization permission mismatch. + StorageErrorCodeAuthorizationPermissionMismatch StorageErrorCode = "AuthorizationPermissionMismatch" + // StorageErrorCodeAuthorizationProtocolMismatch - Authorization protocol mismatch. + StorageErrorCodeAuthorizationProtocolMismatch StorageErrorCode = "AuthorizationProtocolMismatch" + // StorageErrorCodeAuthorizationResourceTypeMismatch - Authorization resource type mismatch. + StorageErrorCodeAuthorizationResourceTypeMismatch StorageErrorCode = "AuthorizationResourceTypeMismatch" + // StorageErrorCodeAuthorizationServiceMismatch - Authorization service mismatch. + StorageErrorCodeAuthorizationServiceMismatch StorageErrorCode = "AuthorizationServiceMismatch" + // StorageErrorCodeAuthorizationSourceIPMismatch - Authorization source IP mismatch. + StorageErrorCodeAuthorizationSourceIPMismatch StorageErrorCode = "AuthorizationSourceIPMismatch" + // StorageErrorCodeBlobAccessTierNotSupportedForAccountType - Blob access tier not supported for account type. + StorageErrorCodeBlobAccessTierNotSupportedForAccountType StorageErrorCode = "BlobAccessTierNotSupportedForAccountType" + // StorageErrorCodeBlobAlreadyExists - Blob already exists. + StorageErrorCodeBlobAlreadyExists StorageErrorCode = "BlobAlreadyExists" + // StorageErrorCodeBlobArchived - Blob archived. + StorageErrorCodeBlobArchived StorageErrorCode = "BlobArchived" + // StorageErrorCodeBlobBeingRehydrated - Blob being rehydrated. + StorageErrorCodeBlobBeingRehydrated StorageErrorCode = "BlobBeingRehydrated" + // StorageErrorCodeBlobImmutableDueToPolicy - Blob is immutable due to policy. + StorageErrorCodeBlobImmutableDueToPolicy StorageErrorCode = "BlobImmutableDueToPolicy" + // StorageErrorCodeBlobNotArchived - Blob not archived. + StorageErrorCodeBlobNotArchived StorageErrorCode = "BlobNotArchived" + // StorageErrorCodeBlobNotFound - Blob not found. + StorageErrorCodeBlobNotFound StorageErrorCode = "BlobNotFound" + // StorageErrorCodeBlobOverwritten - Blob overwritten. + StorageErrorCodeBlobOverwritten StorageErrorCode = "BlobOverwritten" + // StorageErrorCodeBlobTierInadequateForContentLength - Blob tier inadequate for content length. + StorageErrorCodeBlobTierInadequateForContentLength StorageErrorCode = "BlobTierInadequateForContentLength" + // StorageErrorCodeBlobUsesCustomerSpecifiedEncryption - Blob uses customer specified encryption. + StorageErrorCodeBlobUsesCustomerSpecifiedEncryption StorageErrorCode = "BlobUsesCustomerSpecifiedEncryption" + // StorageErrorCodeBlockCountExceedsLimit - Block count exceeds limit. + StorageErrorCodeBlockCountExceedsLimit StorageErrorCode = "BlockCountExceedsLimit" + // StorageErrorCodeBlockListTooLong - Block list too long. + StorageErrorCodeBlockListTooLong StorageErrorCode = "BlockListTooLong" + // StorageErrorCodeCannotChangeToLowerTier - Cannot change to lower tier. + StorageErrorCodeCannotChangeToLowerTier StorageErrorCode = "CannotChangeToLowerTier" + // StorageErrorCodeCannotVerifyCopySource - Cannot verify copy source. + StorageErrorCodeCannotVerifyCopySource StorageErrorCode = "CannotVerifyCopySource" + // StorageErrorCodeConditionHeadersNotSupported - Condition headers not supported. + StorageErrorCodeConditionHeadersNotSupported StorageErrorCode = "ConditionHeadersNotSupported" + // StorageErrorCodeConditionNotMet - Condition not met. + StorageErrorCodeConditionNotMet StorageErrorCode = "ConditionNotMet" + // StorageErrorCodeContainerAlreadyExists - Container already exists. + StorageErrorCodeContainerAlreadyExists StorageErrorCode = "ContainerAlreadyExists" + // StorageErrorCodeContainerBeingDeleted - Container being deleted. + StorageErrorCodeContainerBeingDeleted StorageErrorCode = "ContainerBeingDeleted" + // StorageErrorCodeContainerDisabled - Container disabled. + StorageErrorCodeContainerDisabled StorageErrorCode = "ContainerDisabled" + // StorageErrorCodeContainerNotFound - Container not found. + StorageErrorCodeContainerNotFound StorageErrorCode = "ContainerNotFound" + // StorageErrorCodeContentLengthLargerThanTierLimit - Content length larger than tier limit. + StorageErrorCodeContentLengthLargerThanTierLimit StorageErrorCode = "ContentLengthLargerThanTierLimit" + // StorageErrorCodeCopyAcrossAccountsNotSupported - Copy across accounts not supported. + StorageErrorCodeCopyAcrossAccountsNotSupported StorageErrorCode = "CopyAcrossAccountsNotSupported" + // StorageErrorCodeCopyIDMismatch - Copy ID mismatch. + StorageErrorCodeCopyIDMismatch StorageErrorCode = "CopyIdMismatch" + // StorageErrorCodeEmptyMetadataKey - Empty metadata key. + StorageErrorCodeEmptyMetadataKey StorageErrorCode = "EmptyMetadataKey" + // StorageErrorCodeFeatureVersionMismatch - Feature version mismatch. + StorageErrorCodeFeatureVersionMismatch StorageErrorCode = "FeatureVersionMismatch" + // StorageErrorCodeIncrementalCopyBlobMismatch - Incremental copy blob mismatch. + StorageErrorCodeIncrementalCopyBlobMismatch StorageErrorCode = "IncrementalCopyBlobMismatch" + // StorageErrorCodeIncrementalCopyOfEarlierSnapshotNotAllowed - Incremental copy of an earlier snapshot is not allowed. + StorageErrorCodeIncrementalCopyOfEarlierSnapshotNotAllowed StorageErrorCode = "IncrementalCopyOfEarlierSnapshotNotAllowed" + // StorageErrorCodeIncrementalCopyOfEarlierVersionSnapshotNotAllowed - Incremental copy of an earlier version snapshot is + // not allowed. + StorageErrorCodeIncrementalCopyOfEarlierVersionSnapshotNotAllowed StorageErrorCode = "IncrementalCopyOfEarlierVersionSnapshotNotAllowed" + // StorageErrorCodeIncrementalCopySourceMustBeSnapshot - Incremental copy source must be snapshot. + StorageErrorCodeIncrementalCopySourceMustBeSnapshot StorageErrorCode = "IncrementalCopySourceMustBeSnapshot" + // StorageErrorCodeInfiniteLeaseDurationRequired - Infinite lease duration required. + StorageErrorCodeInfiniteLeaseDurationRequired StorageErrorCode = "InfiniteLeaseDurationRequired" + // StorageErrorCodeInsufficientAccountPermissions - Insufficient account permissions. + StorageErrorCodeInsufficientAccountPermissions StorageErrorCode = "InsufficientAccountPermissions" + // StorageErrorCodeInternalError - Internal error. + StorageErrorCodeInternalError StorageErrorCode = "InternalError" + // StorageErrorCodeInvalidAuthenticationInfo - Invalid authentication information. + StorageErrorCodeInvalidAuthenticationInfo StorageErrorCode = "InvalidAuthenticationInfo" + // StorageErrorCodeInvalidBlobOrBlock - Invalid blob or block. + StorageErrorCodeInvalidBlobOrBlock StorageErrorCode = "InvalidBlobOrBlock" + // StorageErrorCodeInvalidBlobTier - Invalid blob tier. + StorageErrorCodeInvalidBlobTier StorageErrorCode = "InvalidBlobTier" + // StorageErrorCodeInvalidBlobType - Invalid blob type. + StorageErrorCodeInvalidBlobType StorageErrorCode = "InvalidBlobType" + // StorageErrorCodeInvalidBlockID - Invalid block ID. + StorageErrorCodeInvalidBlockID StorageErrorCode = "InvalidBlockId" + // StorageErrorCodeInvalidBlockList - Invalid block list. + StorageErrorCodeInvalidBlockList StorageErrorCode = "InvalidBlockList" + // StorageErrorCodeInvalidHTTPVerb - Invalid HTTP verb. + StorageErrorCodeInvalidHTTPVerb StorageErrorCode = "InvalidHttpVerb" + // StorageErrorCodeInvalidHeaderValue - Invalid header value. + StorageErrorCodeInvalidHeaderValue StorageErrorCode = "InvalidHeaderValue" + // StorageErrorCodeInvalidInput - Invalid input. + StorageErrorCodeInvalidInput StorageErrorCode = "InvalidInput" + // StorageErrorCodeInvalidMD5 - Invalid MD5. + StorageErrorCodeInvalidMD5 StorageErrorCode = "InvalidMd5" + // StorageErrorCodeInvalidMetadata - Invalid metadata. + StorageErrorCodeInvalidMetadata StorageErrorCode = "InvalidMetadata" + // StorageErrorCodeInvalidOperation - Invalid operation. + StorageErrorCodeInvalidOperation StorageErrorCode = "InvalidOperation" + // StorageErrorCodeInvalidPageRange - Invalid page range. + StorageErrorCodeInvalidPageRange StorageErrorCode = "InvalidPageRange" + // StorageErrorCodeInvalidQueryParameterValue - Invalid query parameter value. + StorageErrorCodeInvalidQueryParameterValue StorageErrorCode = "InvalidQueryParameterValue" + // StorageErrorCodeInvalidRange - Invalid range. + StorageErrorCodeInvalidRange StorageErrorCode = "InvalidRange" + // StorageErrorCodeInvalidRequestURL - Invalid request URL. + StorageErrorCodeInvalidRequestURL StorageErrorCode = "InvalidRequestUrl" + // StorageErrorCodeInvalidResourceName - Invalid resource name. + StorageErrorCodeInvalidResourceName StorageErrorCode = "InvalidResourceName" + // StorageErrorCodeInvalidSourceBlobType - Invalid source blob type. + StorageErrorCodeInvalidSourceBlobType StorageErrorCode = "InvalidSourceBlobType" + // StorageErrorCodeInvalidSourceBlobURL - Invalid source blob URL. + StorageErrorCodeInvalidSourceBlobURL StorageErrorCode = "InvalidSourceBlobUrl" + // StorageErrorCodeInvalidURI - Invalid URI. + StorageErrorCodeInvalidURI StorageErrorCode = "InvalidUri" + // StorageErrorCodeInvalidVersionForPageBlobOperation - Invalid version for page blob operation. + StorageErrorCodeInvalidVersionForPageBlobOperation StorageErrorCode = "InvalidVersionForPageBlobOperation" + // StorageErrorCodeInvalidXMLDocument - Invalid XML document. + StorageErrorCodeInvalidXMLDocument StorageErrorCode = "InvalidXmlDocument" + // StorageErrorCodeInvalidXMLNodeValue - Invalid XML node value. + StorageErrorCodeInvalidXMLNodeValue StorageErrorCode = "InvalidXmlNodeValue" + // StorageErrorCodeLeaseAlreadyBroken - Lease already broken. + StorageErrorCodeLeaseAlreadyBroken StorageErrorCode = "LeaseAlreadyBroken" + // StorageErrorCodeLeaseAlreadyPresent - Lease already present. + StorageErrorCodeLeaseAlreadyPresent StorageErrorCode = "LeaseAlreadyPresent" + // StorageErrorCodeLeaseIDMismatchWithBlobOperation - Lease ID mismatch with blob operation. + StorageErrorCodeLeaseIDMismatchWithBlobOperation StorageErrorCode = "LeaseIdMismatchWithBlobOperation" + // StorageErrorCodeLeaseIDMismatchWithContainerOperation - Lease ID mismatch with container operation. + StorageErrorCodeLeaseIDMismatchWithContainerOperation StorageErrorCode = "LeaseIdMismatchWithContainerOperation" + // StorageErrorCodeLeaseIDMismatchWithLeaseOperation - Lease ID mismatch with lease operation. + StorageErrorCodeLeaseIDMismatchWithLeaseOperation StorageErrorCode = "LeaseIdMismatchWithLeaseOperation" + // StorageErrorCodeLeaseIDMissing - Lease ID missing. + StorageErrorCodeLeaseIDMissing StorageErrorCode = "LeaseIdMissing" + // StorageErrorCodeLeaseIsBreakingAndCannotBeAcquired - Lease is breaking and cannot be acquired. + StorageErrorCodeLeaseIsBreakingAndCannotBeAcquired StorageErrorCode = "LeaseIsBreakingAndCannotBeAcquired" + // StorageErrorCodeLeaseIsBreakingAndCannotBeChanged - Lease is breaking and cannot be changed. + StorageErrorCodeLeaseIsBreakingAndCannotBeChanged StorageErrorCode = "LeaseIsBreakingAndCannotBeChanged" + // StorageErrorCodeLeaseIsBrokenAndCannotBeRenewed - Lease is broken and cannot be renewed. + StorageErrorCodeLeaseIsBrokenAndCannotBeRenewed StorageErrorCode = "LeaseIsBrokenAndCannotBeRenewed" + // StorageErrorCodeLeaseLost - Lease lost. + StorageErrorCodeLeaseLost StorageErrorCode = "LeaseLost" + // StorageErrorCodeLeaseNotPresentWithBlobOperation - Lease not present with blob operation. + StorageErrorCodeLeaseNotPresentWithBlobOperation StorageErrorCode = "LeaseNotPresentWithBlobOperation" + // StorageErrorCodeLeaseNotPresentWithContainerOperation - Lease not present with container operation. + StorageErrorCodeLeaseNotPresentWithContainerOperation StorageErrorCode = "LeaseNotPresentWithContainerOperation" + // StorageErrorCodeLeaseNotPresentWithLeaseOperation - Lease not present with lease operation. + StorageErrorCodeLeaseNotPresentWithLeaseOperation StorageErrorCode = "LeaseNotPresentWithLeaseOperation" + // StorageErrorCodeMD5Mismatch - MD5 mismatch. + StorageErrorCodeMD5Mismatch StorageErrorCode = "Md5Mismatch" + // StorageErrorCodeMaxBlobSizeConditionNotMet - Maximum blob size condition not met. + StorageErrorCodeMaxBlobSizeConditionNotMet StorageErrorCode = "MaxBlobSizeConditionNotMet" + // StorageErrorCodeMetadataTooLarge - Metadata too large. + StorageErrorCodeMetadataTooLarge StorageErrorCode = "MetadataTooLarge" + // StorageErrorCodeMissingContentLengthHeader - Missing content length header. + StorageErrorCodeMissingContentLengthHeader StorageErrorCode = "MissingContentLengthHeader" + // StorageErrorCodeMissingRequiredHeader - Missing required header. + StorageErrorCodeMissingRequiredHeader StorageErrorCode = "MissingRequiredHeader" + // StorageErrorCodeMissingRequiredQueryParameter - Missing required query parameter. + StorageErrorCodeMissingRequiredQueryParameter StorageErrorCode = "MissingRequiredQueryParameter" + // StorageErrorCodeMissingRequiredXMLNode - Missing required XML node. + StorageErrorCodeMissingRequiredXMLNode StorageErrorCode = "MissingRequiredXmlNode" + // StorageErrorCodeMultipleConditionHeadersNotSupported - Multiple condition headers not supported. + StorageErrorCodeMultipleConditionHeadersNotSupported StorageErrorCode = "MultipleConditionHeadersNotSupported" + // StorageErrorCodeNoAuthenticationInformation - No authentication information. + StorageErrorCodeNoAuthenticationInformation StorageErrorCode = "NoAuthenticationInformation" + // StorageErrorCodeNoPendingCopyOperation - No pending copy operation. + StorageErrorCodeNoPendingCopyOperation StorageErrorCode = "NoPendingCopyOperation" + // StorageErrorCodeOperationNotAllowedOnIncrementalCopyBlob - Operation not allowed on incremental copy blob. + StorageErrorCodeOperationNotAllowedOnIncrementalCopyBlob StorageErrorCode = "OperationNotAllowedOnIncrementalCopyBlob" + // StorageErrorCodeOperationTimedOut - Operation timed out. + StorageErrorCodeOperationTimedOut StorageErrorCode = "OperationTimedOut" + // StorageErrorCodeOutOfRangeInput - Out of range input. + StorageErrorCodeOutOfRangeInput StorageErrorCode = "OutOfRangeInput" + // StorageErrorCodeOutOfRangeQueryParameterValue - Out of range query parameter value. + StorageErrorCodeOutOfRangeQueryParameterValue StorageErrorCode = "OutOfRangeQueryParameterValue" + // StorageErrorCodePendingCopyOperation - Pending copy operation. + StorageErrorCodePendingCopyOperation StorageErrorCode = "PendingCopyOperation" + // StorageErrorCodePreviousSnapshotCannotBeNewer - Previous snapshot cannot be newer. + StorageErrorCodePreviousSnapshotCannotBeNewer StorageErrorCode = "PreviousSnapshotCannotBeNewer" + // StorageErrorCodePreviousSnapshotNotFound - Previous snapshot not found. + StorageErrorCodePreviousSnapshotNotFound StorageErrorCode = "PreviousSnapshotNotFound" + // StorageErrorCodePreviousSnapshotOperationNotSupported - Previous snapshot operation not supported. + StorageErrorCodePreviousSnapshotOperationNotSupported StorageErrorCode = "PreviousSnapshotOperationNotSupported" + // StorageErrorCodeRequestBodyTooLarge - Request body too large. + StorageErrorCodeRequestBodyTooLarge StorageErrorCode = "RequestBodyTooLarge" + // StorageErrorCodeRequestURLFailedToParse - Request URL failed to parse. + StorageErrorCodeRequestURLFailedToParse StorageErrorCode = "RequestUrlFailedToParse" + // StorageErrorCodeResourceAlreadyExists - Resource already exists. + StorageErrorCodeResourceAlreadyExists StorageErrorCode = "ResourceAlreadyExists" + // StorageErrorCodeResourceNotFound - Resource not found. + StorageErrorCodeResourceNotFound StorageErrorCode = "ResourceNotFound" + // StorageErrorCodeResourceTypeMismatch - Resource type mismatch. + StorageErrorCodeResourceTypeMismatch StorageErrorCode = "ResourceTypeMismatch" + // StorageErrorCodeSequenceNumberConditionNotMet - Sequence number condition not met. + StorageErrorCodeSequenceNumberConditionNotMet StorageErrorCode = "SequenceNumberConditionNotMet" + // StorageErrorCodeSequenceNumberIncrementTooLarge - Sequence number increment too large. + StorageErrorCodeSequenceNumberIncrementTooLarge StorageErrorCode = "SequenceNumberIncrementTooLarge" + // StorageErrorCodeServerBusy - Server busy. + StorageErrorCodeServerBusy StorageErrorCode = "ServerBusy" + // StorageErrorCodeSnapshotCountExceeded - Snapshot count exceeded. + StorageErrorCodeSnapshotCountExceeded StorageErrorCode = "SnapshotCountExceeded" + // StorageErrorCodeSnapshotOperationRateExceeded - Snapshot operation rate exceeded. + StorageErrorCodeSnapshotOperationRateExceeded StorageErrorCode = "SnapshotOperationRateExceeded" + // StorageErrorCodeSnapshotsPresent - Snapshots present. + StorageErrorCodeSnapshotsPresent StorageErrorCode = "SnapshotsPresent" + // StorageErrorCodeSourceConditionNotMet - Source condition not met. + StorageErrorCodeSourceConditionNotMet StorageErrorCode = "SourceConditionNotMet" + // StorageErrorCodeSystemInUse - System in use. + StorageErrorCodeSystemInUse StorageErrorCode = "SystemInUse" + // StorageErrorCodeTargetConditionNotMet - Target condition not met. + StorageErrorCodeTargetConditionNotMet StorageErrorCode = "TargetConditionNotMet" + // StorageErrorCodeUnauthorizedBlobOverwrite - Unauthorized blob overwrite. + StorageErrorCodeUnauthorizedBlobOverwrite StorageErrorCode = "UnauthorizedBlobOverwrite" + // StorageErrorCodeUnsupportedHTTPVerb - Unsupported HTTP verb. + StorageErrorCodeUnsupportedHTTPVerb StorageErrorCode = "UnsupportedHttpVerb" + // StorageErrorCodeUnsupportedHeader - Unsupported header. + StorageErrorCodeUnsupportedHeader StorageErrorCode = "UnsupportedHeader" + // StorageErrorCodeUnsupportedQueryParameter - Unsupported query parameter. + StorageErrorCodeUnsupportedQueryParameter StorageErrorCode = "UnsupportedQueryParameter" + // StorageErrorCodeUnsupportedXMLNode - Unsupported XML node. + StorageErrorCodeUnsupportedXMLNode StorageErrorCode = "UnsupportedXmlNode" +) + +// PossibleStorageErrorCodeValues returns the possible values for the StorageErrorCode const type. +func PossibleStorageErrorCodeValues() []StorageErrorCode { + return []StorageErrorCode{ + StorageErrorCodeAccountAlreadyExists, + StorageErrorCodeAccountBeingCreated, + StorageErrorCodeAccountIsDisabled, + StorageErrorCodeAppendPositionConditionNotMet, + StorageErrorCodeAuthenticationFailed, + StorageErrorCodeAuthorizationFailure, + StorageErrorCodeAuthorizationPermissionMismatch, + StorageErrorCodeAuthorizationProtocolMismatch, + StorageErrorCodeAuthorizationResourceTypeMismatch, + StorageErrorCodeAuthorizationServiceMismatch, + StorageErrorCodeAuthorizationSourceIPMismatch, + StorageErrorCodeBlobAccessTierNotSupportedForAccountType, + StorageErrorCodeBlobAlreadyExists, + StorageErrorCodeBlobArchived, + StorageErrorCodeBlobBeingRehydrated, + StorageErrorCodeBlobImmutableDueToPolicy, + StorageErrorCodeBlobNotArchived, + StorageErrorCodeBlobNotFound, + StorageErrorCodeBlobOverwritten, + StorageErrorCodeBlobTierInadequateForContentLength, + StorageErrorCodeBlobUsesCustomerSpecifiedEncryption, + StorageErrorCodeBlockCountExceedsLimit, + StorageErrorCodeBlockListTooLong, + StorageErrorCodeCannotChangeToLowerTier, + StorageErrorCodeCannotVerifyCopySource, + StorageErrorCodeConditionHeadersNotSupported, + StorageErrorCodeConditionNotMet, + StorageErrorCodeContainerAlreadyExists, + StorageErrorCodeContainerBeingDeleted, + StorageErrorCodeContainerDisabled, + StorageErrorCodeContainerNotFound, + StorageErrorCodeContentLengthLargerThanTierLimit, + StorageErrorCodeCopyAcrossAccountsNotSupported, + StorageErrorCodeCopyIDMismatch, + StorageErrorCodeEmptyMetadataKey, + StorageErrorCodeFeatureVersionMismatch, + StorageErrorCodeIncrementalCopyBlobMismatch, + StorageErrorCodeIncrementalCopyOfEarlierSnapshotNotAllowed, + StorageErrorCodeIncrementalCopyOfEarlierVersionSnapshotNotAllowed, + StorageErrorCodeIncrementalCopySourceMustBeSnapshot, + StorageErrorCodeInfiniteLeaseDurationRequired, + StorageErrorCodeInsufficientAccountPermissions, + StorageErrorCodeInternalError, + StorageErrorCodeInvalidAuthenticationInfo, + StorageErrorCodeInvalidBlobOrBlock, + StorageErrorCodeInvalidBlobTier, + StorageErrorCodeInvalidBlobType, + StorageErrorCodeInvalidBlockID, + StorageErrorCodeInvalidBlockList, + StorageErrorCodeInvalidHTTPVerb, + StorageErrorCodeInvalidHeaderValue, + StorageErrorCodeInvalidInput, + StorageErrorCodeInvalidMD5, + StorageErrorCodeInvalidMetadata, + StorageErrorCodeInvalidOperation, + StorageErrorCodeInvalidPageRange, + StorageErrorCodeInvalidQueryParameterValue, + StorageErrorCodeInvalidRange, + StorageErrorCodeInvalidRequestURL, + StorageErrorCodeInvalidResourceName, + StorageErrorCodeInvalidSourceBlobType, + StorageErrorCodeInvalidSourceBlobURL, + StorageErrorCodeInvalidURI, + StorageErrorCodeInvalidVersionForPageBlobOperation, + StorageErrorCodeInvalidXMLDocument, + StorageErrorCodeInvalidXMLNodeValue, + StorageErrorCodeLeaseAlreadyBroken, + StorageErrorCodeLeaseAlreadyPresent, + StorageErrorCodeLeaseIDMismatchWithBlobOperation, + StorageErrorCodeLeaseIDMismatchWithContainerOperation, + StorageErrorCodeLeaseIDMismatchWithLeaseOperation, + StorageErrorCodeLeaseIDMissing, + StorageErrorCodeLeaseIsBreakingAndCannotBeAcquired, + StorageErrorCodeLeaseIsBreakingAndCannotBeChanged, + StorageErrorCodeLeaseIsBrokenAndCannotBeRenewed, + StorageErrorCodeLeaseLost, + StorageErrorCodeLeaseNotPresentWithBlobOperation, + StorageErrorCodeLeaseNotPresentWithContainerOperation, + StorageErrorCodeLeaseNotPresentWithLeaseOperation, + StorageErrorCodeMD5Mismatch, + StorageErrorCodeMaxBlobSizeConditionNotMet, + StorageErrorCodeMetadataTooLarge, + StorageErrorCodeMissingContentLengthHeader, + StorageErrorCodeMissingRequiredHeader, + StorageErrorCodeMissingRequiredQueryParameter, + StorageErrorCodeMissingRequiredXMLNode, + StorageErrorCodeMultipleConditionHeadersNotSupported, + StorageErrorCodeNoAuthenticationInformation, + StorageErrorCodeNoPendingCopyOperation, + StorageErrorCodeOperationNotAllowedOnIncrementalCopyBlob, + StorageErrorCodeOperationTimedOut, + StorageErrorCodeOutOfRangeInput, + StorageErrorCodeOutOfRangeQueryParameterValue, + StorageErrorCodePendingCopyOperation, + StorageErrorCodePreviousSnapshotCannotBeNewer, + StorageErrorCodePreviousSnapshotNotFound, + StorageErrorCodePreviousSnapshotOperationNotSupported, + StorageErrorCodeRequestBodyTooLarge, + StorageErrorCodeRequestURLFailedToParse, + StorageErrorCodeResourceAlreadyExists, + StorageErrorCodeResourceNotFound, + StorageErrorCodeResourceTypeMismatch, + StorageErrorCodeSequenceNumberConditionNotMet, + StorageErrorCodeSequenceNumberIncrementTooLarge, + StorageErrorCodeServerBusy, + StorageErrorCodeSnapshotCountExceeded, + StorageErrorCodeSnapshotOperationRateExceeded, + StorageErrorCodeSnapshotsPresent, + StorageErrorCodeSourceConditionNotMet, + StorageErrorCodeSystemInUse, + StorageErrorCodeTargetConditionNotMet, + StorageErrorCodeUnauthorizedBlobOverwrite, + StorageErrorCodeUnsupportedHTTPVerb, + StorageErrorCodeUnsupportedHeader, + StorageErrorCodeUnsupportedQueryParameter, + StorageErrorCodeUnsupportedXMLNode, + } +} + +// Type - The blob type. +type Type string + +const ( + // TypeAppendBlob - The blob is an append blob. + TypeAppendBlob Type = "AppendBlob" + // TypeBlockBlob - The blob is a block blob. + TypeBlockBlob Type = "BlockBlob" + // TypePageBlob - The blob is a page blob. + TypePageBlob Type = "PageBlob" +) + +// PossibleTypeValues returns the possible values for the Type const type. +func PossibleTypeValues() []Type { + return []Type{ + TypeAppendBlob, + TypeBlockBlob, + TypePageBlob, + } +} diff --git a/test/local/azblob/zz_container_client.go b/test/local/azblob/zz_container_client.go new file mode 100644 index 000000000000..7584789f409c --- /dev/null +++ b/test/local/azblob/zz_container_client.go @@ -0,0 +1,1542 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azblob + +import ( + "context" + "encoding/xml" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "io" + "net/http" + "strconv" + "strings" + "time" +) + +// ContainerClient contains the methods for the Container group. +// Don't use this type directly, use a constructor function instead. +// +// Generated from API version 2026-06-06 +type ContainerClient struct { + internal *azcore.Client + url string +} + +// AcquireLease - Requests a new lease on the specified container. +// If the operation fails it returns an *azcore.ResponseError type. +// - duration - Specifies the duration of the lease, in seconds, or negative one (-1) for a lease that never expires. A non-infinite +// lease can be between 15 and 60 seconds. +// - options - ContainerClientAcquireLeaseOptions contains the optional parameters for the ContainerClient.AcquireLease method. +func (client *ContainerClient) AcquireLease(ctx context.Context, duration int32, options *ContainerClientAcquireLeaseOptions) (ContainerClientAcquireLeaseResponse, error) { + var err error + req, err := client.acquireLeaseCreateRequest(ctx, duration, options) + if err != nil { + return ContainerClientAcquireLeaseResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ContainerClientAcquireLeaseResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return ContainerClientAcquireLeaseResponse{}, err + } + resp, err := client.acquireLeaseHandleResponse(httpResp) + return resp, err +} + +// acquireLeaseCreateRequest creates the AcquireLease request. +func (client *ContainerClient) acquireLeaseCreateRequest(ctx context.Context, duration int32, options *ContainerClientAcquireLeaseOptions) (*policy.Request, error) { + urlPath := "?comp=lease&restype=container" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-lease-action"] = []string{"acquire"} + req.Raw().Header["x-ms-lease-duration"] = []string{strconv.FormatInt(int64(duration), 10)} + if options != nil && options.ProposedLeaseID != nil { + req.Raw().Header["x-ms-proposed-lease-id"] = []string{*options.ProposedLeaseID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// acquireLeaseHandleResponse handles the AcquireLease response. +func (client *ContainerClient) acquireLeaseHandleResponse(resp *http.Response) (ContainerClientAcquireLeaseResponse, error) { + result := ContainerClientAcquireLeaseResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ContainerClientAcquireLeaseResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ContainerClientAcquireLeaseResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-lease-id"); val != "" { + result.LeaseID = &val + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// BreakLease - Ends a lease and ensures that another client can't acquire a new lease until the current lease period has +// expired. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ContainerClientBreakLeaseOptions contains the optional parameters for the ContainerClient.BreakLease method. +func (client *ContainerClient) BreakLease(ctx context.Context, options *ContainerClientBreakLeaseOptions) (ContainerClientBreakLeaseResponse, error) { + var err error + req, err := client.breakLeaseCreateRequest(ctx, options) + if err != nil { + return ContainerClientBreakLeaseResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ContainerClientBreakLeaseResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return ContainerClientBreakLeaseResponse{}, err + } + resp, err := client.breakLeaseHandleResponse(httpResp) + return resp, err +} + +// breakLeaseCreateRequest creates the BreakLease request. +func (client *ContainerClient) breakLeaseCreateRequest(ctx context.Context, options *ContainerClientBreakLeaseOptions) (*policy.Request, error) { + urlPath := "?comp=lease&restype=container" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-lease-action"] = []string{"break"} + if options != nil && options.BreakPeriod != nil { + req.Raw().Header["x-ms-lease-break-period"] = []string{strconv.FormatInt(int64(*options.BreakPeriod), 10)} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// breakLeaseHandleResponse handles the BreakLease response. +func (client *ContainerClient) breakLeaseHandleResponse(resp *http.Response) (ContainerClientBreakLeaseResponse, error) { + result := ContainerClientBreakLeaseResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ContainerClientBreakLeaseResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ContainerClientBreakLeaseResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-lease-time"); val != "" { + leaseTime32, err := strconv.ParseInt(val, 10, 32) + leaseTime := int32(leaseTime32) + if err != nil { + return ContainerClientBreakLeaseResponse{}, err + } + result.LeaseTime = &leaseTime + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// ChangeLease - Change the ID of an existing lease. +// If the operation fails it returns an *azcore.ResponseError type. +// - leaseID - A lease ID for the resource. The resource must have an active lease and the lease ID must match. +// - proposedLeaseID - The proposed lease ID for the lease. +// - options - ContainerClientChangeLeaseOptions contains the optional parameters for the ContainerClient.ChangeLease method. +func (client *ContainerClient) ChangeLease(ctx context.Context, leaseID string, proposedLeaseID string, options *ContainerClientChangeLeaseOptions) (ContainerClientChangeLeaseResponse, error) { + var err error + req, err := client.changeLeaseCreateRequest(ctx, leaseID, proposedLeaseID, options) + if err != nil { + return ContainerClientChangeLeaseResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ContainerClientChangeLeaseResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ContainerClientChangeLeaseResponse{}, err + } + resp, err := client.changeLeaseHandleResponse(httpResp) + return resp, err +} + +// changeLeaseCreateRequest creates the ChangeLease request. +func (client *ContainerClient) changeLeaseCreateRequest(ctx context.Context, leaseID string, proposedLeaseID string, options *ContainerClientChangeLeaseOptions) (*policy.Request, error) { + urlPath := "?comp=lease&restype=container" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-lease-action"] = []string{"change"} + req.Raw().Header["x-ms-lease-id"] = []string{leaseID} + req.Raw().Header["x-ms-proposed-lease-id"] = []string{proposedLeaseID} + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// changeLeaseHandleResponse handles the ChangeLease response. +func (client *ContainerClient) changeLeaseHandleResponse(resp *http.Response) (ContainerClientChangeLeaseResponse, error) { + result := ContainerClientChangeLeaseResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ContainerClientChangeLeaseResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ContainerClientChangeLeaseResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-lease-id"); val != "" { + result.LeaseID = &val + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// Create - Creates a new container in the specified account. If the container with the same name already exists, the operation +// fails. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ContainerClientCreateOptions contains the optional parameters for the ContainerClient.Create method. +func (client *ContainerClient) Create(ctx context.Context, options *ContainerClientCreateOptions) (ContainerClientCreateResponse, error) { + var err error + req, err := client.createCreateRequest(ctx, options) + if err != nil { + return ContainerClientCreateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ContainerClientCreateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return ContainerClientCreateResponse{}, err + } + resp, err := client.createHandleResponse(httpResp) + return resp, err +} + +// createCreateRequest creates the Create request. +func (client *ContainerClient) createCreateRequest(ctx context.Context, options *ContainerClientCreateOptions) (*policy.Request, error) { + urlPath := "?restype=container" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.Access != nil { + req.Raw().Header["x-ms-blob-public-access"] = []string{string(*options.Access)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.DefaultEncryptionScope != nil { + req.Raw().Header["x-ms-default-encryption-scope"] = []string{*options.DefaultEncryptionScope} + } + if options != nil && options.PreventEncryptionScopeOverride != nil { + req.Raw().Header["x-ms-deny-encryption-scope-override"] = []string{strconv.FormatBool(*options.PreventEncryptionScopeOverride)} + } + if options != nil && options.Metadata != nil { + for k, v := range options.Metadata { + if v != nil { + req.Raw().Header["x-ms-meta-"+k] = []string{*v} + } + } + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// createHandleResponse handles the Create response. +func (client *ContainerClient) createHandleResponse(resp *http.Response) (ContainerClientCreateResponse, error) { + result := ContainerClientCreateResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ContainerClientCreateResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ContainerClientCreateResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// Delete - Deletes the specified container. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ContainerClientDeleteOptions contains the optional parameters for the ContainerClient.Delete method. +func (client *ContainerClient) Delete(ctx context.Context, options *ContainerClientDeleteOptions) (ContainerClientDeleteResponse, error) { + var err error + req, err := client.deleteCreateRequest(ctx, options) + if err != nil { + return ContainerClientDeleteResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ContainerClientDeleteResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return ContainerClientDeleteResponse{}, err + } + resp, err := client.deleteHandleResponse(httpResp) + return resp, err +} + +// deleteCreateRequest creates the Delete request. +func (client *ContainerClient) deleteCreateRequest(ctx context.Context, options *ContainerClientDeleteOptions) (*policy.Request, error) { + urlPath := "?restype=container" + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// deleteHandleResponse handles the Delete response. +func (client *ContainerClient) deleteHandleResponse(resp *http.Response) (ContainerClientDeleteResponse, error) { + result := ContainerClientDeleteResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ContainerClientDeleteResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// FilterBlobs - Lists blobs in the specified container whose tags match a given search expression. +// If the operation fails it returns an *azcore.ResponseError type. +// - filterExpression - Filters the results to return only blobs whose tags match the specified expression. +// - options - ContainerClientFilterBlobsOptions contains the optional parameters for the ContainerClient.FilterBlobs method. +func (client *ContainerClient) FilterBlobs(ctx context.Context, filterExpression string, options *ContainerClientFilterBlobsOptions) (ContainerClientFilterBlobsResponse, error) { + var err error + req, err := client.filterBlobsCreateRequest(ctx, filterExpression, options) + if err != nil { + return ContainerClientFilterBlobsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ContainerClientFilterBlobsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ContainerClientFilterBlobsResponse{}, err + } + resp, err := client.filterBlobsHandleResponse(httpResp) + return resp, err +} + +// filterBlobsCreateRequest creates the FilterBlobs request. +func (client *ContainerClient) filterBlobsCreateRequest(ctx context.Context, filterExpression string, options *ContainerClientFilterBlobsOptions) (*policy.Request, error) { + urlPath := "?restype=container&comp=blobs" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Include != nil { + reqQP.Set("include", strings.Join(strings.Fields(strings.Trim(fmt.Sprint(options.Include), "[]")), ",")) + } + if options != nil && options.Marker != nil { + reqQP.Set("marker", *options.Marker) + } + if options != nil && options.Maxresults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.Maxresults), 10)) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + reqQP.Set("where", filterExpression) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/xml"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// filterBlobsHandleResponse handles the FilterBlobs response. +func (client *ContainerClient) filterBlobsHandleResponse(resp *http.Response) (ContainerClientFilterBlobsResponse, error) { + result := ContainerClientFilterBlobsResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ContainerClientFilterBlobsResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + if err := runtime.UnmarshalAsXML(resp, &result.FilterBlobSegment); err != nil { + return ContainerClientFilterBlobsResponse{}, err + } + return result, nil +} + +// GetAccessPolicy - Gets the permissions for the specified container. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ContainerClientGetAccessPolicyOptions contains the optional parameters for the ContainerClient.GetAccessPolicy +// method. +func (client *ContainerClient) GetAccessPolicy(ctx context.Context, options *ContainerClientGetAccessPolicyOptions) (ContainerClientGetAccessPolicyResponse, error) { + var err error + req, err := client.getAccessPolicyCreateRequest(ctx, options) + if err != nil { + return ContainerClientGetAccessPolicyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ContainerClientGetAccessPolicyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ContainerClientGetAccessPolicyResponse{}, err + } + resp, err := client.getAccessPolicyHandleResponse(httpResp) + return resp, err +} + +// getAccessPolicyCreateRequest creates the GetAccessPolicy request. +func (client *ContainerClient) getAccessPolicyCreateRequest(ctx context.Context, options *ContainerClientGetAccessPolicyOptions) (*policy.Request, error) { + urlPath := "?restype=container&comp=acl" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/xml"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// getAccessPolicyHandleResponse handles the GetAccessPolicy response. +func (client *ContainerClient) getAccessPolicyHandleResponse(resp *http.Response) (ContainerClientGetAccessPolicyResponse, error) { + result := ContainerClientGetAccessPolicyResponse{} + if val := resp.Header.Get("x-ms-blob-public-access"); val != "" { + result.BlobPublicAccess = (*PublicAccessType)(&val) + } + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ContainerClientGetAccessPolicyResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ContainerClientGetAccessPolicyResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + if err := runtime.UnmarshalAsXML(resp, &result); err != nil { + return ContainerClientGetAccessPolicyResponse{}, err + } + return result, nil +} + +// GetAccountInfo - Returns information about the storage account. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ContainerClientGetAccountInfoOptions contains the optional parameters for the ContainerClient.GetAccountInfo +// method. +func (client *ContainerClient) GetAccountInfo(ctx context.Context, options *ContainerClientGetAccountInfoOptions) (ContainerClientGetAccountInfoResponse, error) { + var err error + req, err := client.getAccountInfoCreateRequest(ctx, options) + if err != nil { + return ContainerClientGetAccountInfoResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ContainerClientGetAccountInfoResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ContainerClientGetAccountInfoResponse{}, err + } + resp, err := client.getAccountInfoHandleResponse(httpResp) + return resp, err +} + +// getAccountInfoCreateRequest creates the GetAccountInfo request. +func (client *ContainerClient) getAccountInfoCreateRequest(ctx context.Context, options *ContainerClientGetAccountInfoOptions) (*policy.Request, error) { + urlPath := "?restype=account&comp=properties" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// getAccountInfoHandleResponse handles the GetAccountInfo response. +func (client *ContainerClient) getAccountInfoHandleResponse(resp *http.Response) (ContainerClientGetAccountInfoResponse, error) { + result := ContainerClientGetAccountInfoResponse{} + if val := resp.Header.Get("x-ms-account-kind"); val != "" { + result.AccountKind = (*AccountKind)(&val) + } + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ContainerClientGetAccountInfoResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-is-hns-enabled"); val != "" { + isHierarchicalNamespaceEnabled, err := strconv.ParseBool(val) + if err != nil { + return ContainerClientGetAccountInfoResponse{}, err + } + result.IsHierarchicalNamespaceEnabled = &isHierarchicalNamespaceEnabled + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-sku-name"); val != "" { + result.SKUName = (*SKUName)(&val) + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// GetProperties - Returns all user-defined metadata and system properties for the specified container. The data returned +// does not include the container's list of blobs. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ContainerClientGetPropertiesOptions contains the optional parameters for the ContainerClient.GetProperties method. +func (client *ContainerClient) GetProperties(ctx context.Context, options *ContainerClientGetPropertiesOptions) (ContainerClientGetPropertiesResponse, error) { + var err error + req, err := client.getPropertiesCreateRequest(ctx, options) + if err != nil { + return ContainerClientGetPropertiesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ContainerClientGetPropertiesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ContainerClientGetPropertiesResponse{}, err + } + resp, err := client.getPropertiesHandleResponse(httpResp) + return resp, err +} + +// getPropertiesCreateRequest creates the GetProperties request. +func (client *ContainerClient) getPropertiesCreateRequest(ctx context.Context, options *ContainerClientGetPropertiesOptions) (*policy.Request, error) { + urlPath := "?restype=container" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// getPropertiesHandleResponse handles the GetProperties response. +func (client *ContainerClient) getPropertiesHandleResponse(resp *http.Response) (ContainerClientGetPropertiesResponse, error) { + result := ContainerClientGetPropertiesResponse{} + if val := resp.Header.Get("x-ms-blob-public-access"); val != "" { + result.BlobPublicAccess = (*PublicAccessType)(&val) + } + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ContainerClientGetPropertiesResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-default-encryption-scope"); val != "" { + result.DefaultEncryptionScope = &val + } + if val := resp.Header.Get("x-ms-deny-encryption-scope-override"); val != "" { + denyEncryptionScopeOverride, err := strconv.ParseBool(val) + if err != nil { + return ContainerClientGetPropertiesResponse{}, err + } + result.DenyEncryptionScopeOverride = &denyEncryptionScopeOverride + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("x-ms-has-immutability-policy"); val != "" { + hasImmutabilityPolicy, err := strconv.ParseBool(val) + if err != nil { + return ContainerClientGetPropertiesResponse{}, err + } + result.HasImmutabilityPolicy = &hasImmutabilityPolicy + } + if val := resp.Header.Get("x-ms-has-legal-hold"); val != "" { + hasLegalHold, err := strconv.ParseBool(val) + if err != nil { + return ContainerClientGetPropertiesResponse{}, err + } + result.HasLegalHold = &hasLegalHold + } + if val := resp.Header.Get("x-ms-immutable-storage-with-versioning-enabled"); val != "" { + isImmutableStorageWithVersioningEnabled, err := strconv.ParseBool(val) + if err != nil { + return ContainerClientGetPropertiesResponse{}, err + } + result.IsImmutableStorageWithVersioningEnabled = &isImmutableStorageWithVersioningEnabled + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ContainerClientGetPropertiesResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-lease-duration"); val != "" { + result.LeaseDuration = (*LeaseDurationType)(&val) + } + if val := resp.Header.Get("x-ms-lease-state"); val != "" { + result.LeaseState = (*LeaseStateType)(&val) + } + if val := resp.Header.Get("x-ms-lease-status"); val != "" { + result.LeaseStatus = (*LeaseStatusType)(&val) + } + for hh := range resp.Header { + if len(hh) > len("x-ms-meta-") && strings.EqualFold(hh[:len("x-ms-meta-")], "x-ms-meta-") { + if result.Metadata == nil { + result.Metadata = map[string]*string{} + } + result.Metadata[hh[len("x-ms-meta-"):]] = to.Ptr(resp.Header.Get(hh)) + } + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// ListBlobFlatSegment - Returns a list of the blobs in the specified container. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ContainerClientListBlobFlatSegmentOptions contains the optional parameters for the ContainerClient.ListBlobFlatSegment +// method. +func (client *ContainerClient) ListBlobFlatSegment(ctx context.Context, options *ContainerClientListBlobFlatSegmentOptions) (ContainerClientListBlobFlatSegmentResponse, error) { + var err error + req, err := client.listBlobFlatSegmentCreateRequest(ctx, options) + if err != nil { + return ContainerClientListBlobFlatSegmentResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ContainerClientListBlobFlatSegmentResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ContainerClientListBlobFlatSegmentResponse{}, err + } + resp, err := client.listBlobFlatSegmentHandleResponse(httpResp) + return resp, err +} + +// listBlobFlatSegmentCreateRequest creates the ListBlobFlatSegment request. +func (client *ContainerClient) listBlobFlatSegmentCreateRequest(ctx context.Context, options *ContainerClientListBlobFlatSegmentOptions) (*policy.Request, error) { + urlPath := "?restype=container&comp=list" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Include != nil { + reqQP.Set("include", strings.Join(strings.Fields(strings.Trim(fmt.Sprint(options.Include), "[]")), ",")) + } + if options != nil && options.Marker != nil { + reqQP.Set("marker", *options.Marker) + } + if options != nil && options.Maxresults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.Maxresults), 10)) + } + if options != nil && options.Prefix != nil { + reqQP.Set("prefix", *options.Prefix) + } + if options != nil && options.StartFrom != nil { + reqQP.Set("startFrom", *options.StartFrom) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/xml"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// listBlobFlatSegmentHandleResponse handles the ListBlobFlatSegment response. +func (client *ContainerClient) listBlobFlatSegmentHandleResponse(resp *http.Response) (ContainerClientListBlobFlatSegmentResponse, error) { + result := ContainerClientListBlobFlatSegmentResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ContainerClientListBlobFlatSegmentResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + if err := runtime.UnmarshalAsXML(resp, &result.ListBlobsFlatSegmentResponse); err != nil { + return ContainerClientListBlobFlatSegmentResponse{}, err + } + return result, nil +} + +// NewListBlobHierarchySegmentPager - Returns a list of the blobs in the specified container. A delimiter can be used to traverse +// a virtual hierarchy of blobs as though it were a file system. +// - delimiter - If specified, the operation returns a BlobPrefix element that acts as a placeholder for all blobs whose names +// begin with the same substring up to the appearance of the delimiter character. The delimiter may be a single character +// or a string. +// - options - ContainerClientListBlobHierarchySegmentOptions contains the optional parameters for the ContainerClient.NewListBlobHierarchySegmentPager +// method. +func (client *ContainerClient) NewListBlobHierarchySegmentPager(delimiter string, options *ContainerClientListBlobHierarchySegmentOptions) *runtime.Pager[ContainerClientListBlobHierarchySegmentResponse] { + return runtime.NewPager(runtime.PagingHandler[ContainerClientListBlobHierarchySegmentResponse]{ + More: func(page ContainerClientListBlobHierarchySegmentResponse) bool { + return page.NextMarker != nil && len(*page.NextMarker) > 0 + }, + Fetcher: func(ctx context.Context, page *ContainerClientListBlobHierarchySegmentResponse) (ContainerClientListBlobHierarchySegmentResponse, error) { + nextOpts := ContainerClientListBlobHierarchySegmentOptions{} + if options != nil { + nextOpts = *options + } + if page != nil { + nextOpts.Marker = page.NextMarker + } + req, err := client.listBlobHierarchySegmentCreateRequest(ctx, delimiter, &nextOpts) + if err != nil { + return ContainerClientListBlobHierarchySegmentResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ContainerClientListBlobHierarchySegmentResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ContainerClientListBlobHierarchySegmentResponse{}, runtime.NewResponseError(resp) + } + return client.listBlobHierarchySegmentHandleResponse(resp) + }, + }) +} + +// listBlobHierarchySegmentCreateRequest creates the ListBlobHierarchySegment request. +func (client *ContainerClient) listBlobHierarchySegmentCreateRequest(ctx context.Context, delimiter string, options *ContainerClientListBlobHierarchySegmentOptions) (*policy.Request, error) { + urlPath := "?restype=container&comp=list" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("delimiter", delimiter) + if options != nil && options.Include != nil { + reqQP.Set("include", strings.Join(strings.Fields(strings.Trim(fmt.Sprint(options.Include), "[]")), ",")) + } + if options != nil && options.Marker != nil { + reqQP.Set("marker", *options.Marker) + } + if options != nil && options.Maxresults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.Maxresults), 10)) + } + if options != nil && options.Prefix != nil { + reqQP.Set("prefix", *options.Prefix) + } + if options != nil && options.StartFrom != nil { + reqQP.Set("startFrom", *options.StartFrom) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/xml"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// listBlobHierarchySegmentHandleResponse handles the ListBlobHierarchySegment response. +func (client *ContainerClient) listBlobHierarchySegmentHandleResponse(resp *http.Response) (ContainerClientListBlobHierarchySegmentResponse, error) { + result := ContainerClientListBlobHierarchySegmentResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ContainerClientListBlobHierarchySegmentResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + if err := runtime.UnmarshalAsXML(resp, &result.ListBlobsHierarchySegmentResponse); err != nil { + return ContainerClientListBlobHierarchySegmentResponse{}, err + } + return result, nil +} + +// ReleaseLease - Frees the lease if it's no longer needed, so that another client can immediately acquire a lease against +// the container. +// If the operation fails it returns an *azcore.ResponseError type. +// - leaseID - A lease ID for the resource. The resource must have an active lease and the lease ID must match. +// - options - ContainerClientReleaseLeaseOptions contains the optional parameters for the ContainerClient.ReleaseLease method. +func (client *ContainerClient) ReleaseLease(ctx context.Context, leaseID string, options *ContainerClientReleaseLeaseOptions) (ContainerClientReleaseLeaseResponse, error) { + var err error + req, err := client.releaseLeaseCreateRequest(ctx, leaseID, options) + if err != nil { + return ContainerClientReleaseLeaseResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ContainerClientReleaseLeaseResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ContainerClientReleaseLeaseResponse{}, err + } + resp, err := client.releaseLeaseHandleResponse(httpResp) + return resp, err +} + +// releaseLeaseCreateRequest creates the ReleaseLease request. +func (client *ContainerClient) releaseLeaseCreateRequest(ctx context.Context, leaseID string, options *ContainerClientReleaseLeaseOptions) (*policy.Request, error) { + urlPath := "?comp=lease&restype=container" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-lease-action"] = []string{"release"} + req.Raw().Header["x-ms-lease-id"] = []string{leaseID} + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// releaseLeaseHandleResponse handles the ReleaseLease response. +func (client *ContainerClient) releaseLeaseHandleResponse(resp *http.Response) (ContainerClientReleaseLeaseResponse, error) { + result := ContainerClientReleaseLeaseResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ContainerClientReleaseLeaseResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ContainerClientReleaseLeaseResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// Rename - Renames the specified existing container. +// If the operation fails it returns an *azcore.ResponseError type. +// - sourceContainerName - Specifies the name of the container to rename. +// - options - ContainerClientRenameOptions contains the optional parameters for the ContainerClient.Rename method. +func (client *ContainerClient) Rename(ctx context.Context, sourceContainerName string, options *ContainerClientRenameOptions) (ContainerClientRenameResponse, error) { + var err error + req, err := client.renameCreateRequest(ctx, sourceContainerName, options) + if err != nil { + return ContainerClientRenameResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ContainerClientRenameResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ContainerClientRenameResponse{}, err + } + resp, err := client.renameHandleResponse(httpResp) + return resp, err +} + +// renameCreateRequest creates the Rename request. +func (client *ContainerClient) renameCreateRequest(ctx context.Context, sourceContainerName string, options *ContainerClientRenameOptions) (*policy.Request, error) { + urlPath := "?restype=container&comp=rename" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-source-container-name"] = []string{sourceContainerName} + if options != nil && options.SourceLeaseID != nil { + req.Raw().Header["x-ms-source-lease-id"] = []string{*options.SourceLeaseID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// renameHandleResponse handles the Rename response. +func (client *ContainerClient) renameHandleResponse(resp *http.Response) (ContainerClientRenameResponse, error) { + result := ContainerClientRenameResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ContainerClientRenameResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// RenewLease - Renews an existing lease. +// If the operation fails it returns an *azcore.ResponseError type. +// - leaseID - A lease ID for the resource. The resource must have an active lease and the lease ID must match. +// - options - ContainerClientRenewLeaseOptions contains the optional parameters for the ContainerClient.RenewLease method. +func (client *ContainerClient) RenewLease(ctx context.Context, leaseID string, options *ContainerClientRenewLeaseOptions) (ContainerClientRenewLeaseResponse, error) { + var err error + req, err := client.renewLeaseCreateRequest(ctx, leaseID, options) + if err != nil { + return ContainerClientRenewLeaseResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ContainerClientRenewLeaseResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ContainerClientRenewLeaseResponse{}, err + } + resp, err := client.renewLeaseHandleResponse(httpResp) + return resp, err +} + +// renewLeaseCreateRequest creates the RenewLease request. +func (client *ContainerClient) renewLeaseCreateRequest(ctx context.Context, leaseID string, options *ContainerClientRenewLeaseOptions) (*policy.Request, error) { + urlPath := "?comp=lease&restype=container" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-lease-action"] = []string{"renew"} + req.Raw().Header["x-ms-lease-id"] = []string{leaseID} + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// renewLeaseHandleResponse handles the RenewLease response. +func (client *ContainerClient) renewLeaseHandleResponse(resp *http.Response) (ContainerClientRenewLeaseResponse, error) { + result := ContainerClientRenewLeaseResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ContainerClientRenewLeaseResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ContainerClientRenewLeaseResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-lease-id"); val != "" { + result.LeaseID = &val + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// Restore - Restores the specified previously-deleted container. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ContainerClientRestoreOptions contains the optional parameters for the ContainerClient.Restore method. +func (client *ContainerClient) Restore(ctx context.Context, options *ContainerClientRestoreOptions) (ContainerClientRestoreResponse, error) { + var err error + req, err := client.restoreCreateRequest(ctx, options) + if err != nil { + return ContainerClientRestoreResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ContainerClientRestoreResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return ContainerClientRestoreResponse{}, err + } + resp, err := client.restoreHandleResponse(httpResp) + return resp, err +} + +// restoreCreateRequest creates the Restore request. +func (client *ContainerClient) restoreCreateRequest(ctx context.Context, options *ContainerClientRestoreOptions) (*policy.Request, error) { + urlPath := "?restype=container&comp=undelete" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.DeletedContainerName != nil { + req.Raw().Header["x-ms-deleted-container-name"] = []string{*options.DeletedContainerName} + } + if options != nil && options.DeletedContainerVersion != nil { + req.Raw().Header["x-ms-deleted-container-version"] = []string{*options.DeletedContainerVersion} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// restoreHandleResponse handles the Restore response. +func (client *ContainerClient) restoreHandleResponse(resp *http.Response) (ContainerClientRestoreResponse, error) { + result := ContainerClientRestoreResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ContainerClientRestoreResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// SetAccessPolicy - Sets the permissions for the specified container. +// If the operation fails it returns an *azcore.ResponseError type. +// - containerACL - The access control list for the container. +// - options - ContainerClientSetAccessPolicyOptions contains the optional parameters for the ContainerClient.SetAccessPolicy +// method. +func (client *ContainerClient) SetAccessPolicy(ctx context.Context, containerACL []*SignedIdentifier, options *ContainerClientSetAccessPolicyOptions) (ContainerClientSetAccessPolicyResponse, error) { + var err error + req, err := client.setAccessPolicyCreateRequest(ctx, containerACL, options) + if err != nil { + return ContainerClientSetAccessPolicyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ContainerClientSetAccessPolicyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ContainerClientSetAccessPolicyResponse{}, err + } + resp, err := client.setAccessPolicyHandleResponse(httpResp) + return resp, err +} + +// setAccessPolicyCreateRequest creates the SetAccessPolicy request. +func (client *ContainerClient) setAccessPolicyCreateRequest(ctx context.Context, containerACL []*SignedIdentifier, options *ContainerClientSetAccessPolicyOptions) (*policy.Request, error) { + urlPath := "?restype=container&comp=acl" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.Access != nil { + req.Raw().Header["x-ms-blob-public-access"] = []string{string(*options.Access)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + type wrapper struct { + XMLName xml.Name `xml:"SignedIdentifiers"` + ContainerACL *[]*SignedIdentifier `xml:"SignedIdentifier"` + } + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, wrapper{ContainerACL: &containerACL}); err != nil { + return nil, err + } + return req, nil +} + +// setAccessPolicyHandleResponse handles the SetAccessPolicy response. +func (client *ContainerClient) setAccessPolicyHandleResponse(resp *http.Response) (ContainerClientSetAccessPolicyResponse, error) { + result := ContainerClientSetAccessPolicyResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ContainerClientSetAccessPolicyResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ContainerClientSetAccessPolicyResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// SetMetadata - Sets user-defined metadata for the specified container. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ContainerClientSetMetadataOptions contains the optional parameters for the ContainerClient.SetMetadata method. +func (client *ContainerClient) SetMetadata(ctx context.Context, options *ContainerClientSetMetadataOptions) (ContainerClientSetMetadataResponse, error) { + var err error + req, err := client.setMetadataCreateRequest(ctx, options) + if err != nil { + return ContainerClientSetMetadataResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ContainerClientSetMetadataResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ContainerClientSetMetadataResponse{}, err + } + resp, err := client.setMetadataHandleResponse(httpResp) + return resp, err +} + +// setMetadataCreateRequest creates the SetMetadata request. +func (client *ContainerClient) setMetadataCreateRequest(ctx context.Context, options *ContainerClientSetMetadataOptions) (*policy.Request, error) { + urlPath := "?restype=container&comp=metadata" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + if options != nil && options.Metadata != nil { + for k, v := range options.Metadata { + if v != nil { + req.Raw().Header["x-ms-meta-"+k] = []string{*v} + } + } + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// setMetadataHandleResponse handles the SetMetadata response. +func (client *ContainerClient) setMetadataHandleResponse(resp *http.Response) (ContainerClientSetMetadataResponse, error) { + result := ContainerClientSetMetadataResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ContainerClientSetMetadataResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return ContainerClientSetMetadataResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// SubmitBatch - Allows multiple API calls to be embedded into a single HTTP request. +// If the operation fails it returns an *azcore.ResponseError type. +// - multipartContentType - The value of this header must be multipart/mixed with a batch boundary. Example header value: multipart/mixed; +// boundary=batch_ +// - contentLength - The length of the request. +// - body - The body of the request. +// - options - ContainerClientSubmitBatchOptions contains the optional parameters for the ContainerClient.SubmitBatch method. +func (client *ContainerClient) SubmitBatch(ctx context.Context, multipartContentType string, contentLength int64, body io.ReadSeekCloser, options *ContainerClientSubmitBatchOptions) (ContainerClientSubmitBatchResponse, error) { + var err error + req, err := client.submitBatchCreateRequest(ctx, multipartContentType, contentLength, body, options) + if err != nil { + return ContainerClientSubmitBatchResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ContainerClientSubmitBatchResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return ContainerClientSubmitBatchResponse{}, err + } + resp, err := client.submitBatchHandleResponse(httpResp) + return resp, err +} + +// submitBatchCreateRequest creates the SubmitBatch request. +func (client *ContainerClient) submitBatchCreateRequest(ctx context.Context, multipartContentType string, contentLength int64, body io.ReadSeekCloser, options *ContainerClientSubmitBatchOptions) (*policy.Request, error) { + urlPath := "?restype=container&comp=batch" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + runtime.SkipBodyDownload(req) + req.Raw().Header["Accept"] = []string{"multipart/mixed"} + req.Raw().Header["Content-Length"] = []string{strconv.FormatInt(contentLength, 10)} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + if err := req.SetBody(body, multipartContentType); err != nil { + return nil, err + } + return req, nil +} + +// submitBatchHandleResponse handles the SubmitBatch response. +func (client *ContainerClient) submitBatchHandleResponse(resp *http.Response) (ContainerClientSubmitBatchResponse, error) { + result := ContainerClientSubmitBatchResponse{Body: resp.Body} + if val := resp.Header.Get("Content-Type"); val != "" { + result.ContentType = &val + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} diff --git a/test/local/azblob/zz_models.go b/test/local/azblob/zz_models.go new file mode 100644 index 000000000000..5bc1552ae20b --- /dev/null +++ b/test/local/azblob/zz_models.go @@ -0,0 +1,710 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azblob + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "time" +) + +// AccessPolicy - Represents an access policy. +type AccessPolicy struct { + // The date-time the policy expires. + Expiry *time.Time `xml:"Expiry"` + + // The permissions for the policy. + Permission *string `xml:"Permission"` + + // The date-time the policy is active. + Start *time.Time `xml:"Start"` +} + +// ArrowConfiguration - Represents the Apache Arrow configuration. +type ArrowConfiguration struct { + // REQUIRED; The Apache Arrow schema. + Schema []*ArrowField `xml:"Schema>Field"` +} + +// ArrowField - Represents an Apache Arrow field. +type ArrowField struct { + // REQUIRED; The arrow field type. + Type *string `xml:"Type"` + + // The arrow field name. + Name *string `xml:"Name"` + + // The arrow field precision. + Precision *int32 `xml:"Precision"` + + // The arrow field scale. + Scale *int32 `xml:"Scale"` +} + +// Block - Represents a single block in a block blob. +type Block struct { + // REQUIRED; The base64 encoded block ID. + Name *string `xml:"Name"` + + // REQUIRED; The block size in bytes. + Size *int64 `xml:"Size"` +} + +// BlockList - Contains the committed and uncommitted blocks in a block blob. +type BlockList struct { + // The list of committed blocks. + CommittedBlocks []*Block `xml:"CommittedBlocks>Block"` + + // The list of uncommitted blocks. + UncommittedBlocks []*Block `xml:"UncommittedBlocks>Block"` +} + +// BlockLookupList - The block lookup list. +type BlockLookupList struct { + // The committed blocks. + Committed []*string `xml:"Committed"` + + // The latest blocks. + Latest []*string `xml:"Latest"` + + // The uncommitted blocks. + Uncommitted []*string `xml:"Uncommitted"` +} + +// CORSRule - A Cross-Origin Resource Sharing (CORS) rule. +type CORSRule struct { + // REQUIRED; The allowed headers. + AllowedHeaders *string `xml:"AllowedHeaders"` + + // REQUIRED; The allowed methods. + AllowedMethods *string `xml:"AllowedMethods"` + + // REQUIRED; The allowed origins. + AllowedOrigins *string `xml:"AllowedOrigins"` + + // REQUIRED; The exposed headers. + ExposedHeaders *string `xml:"ExposedHeaders"` + + // REQUIRED; The maximum age in seconds. + MaxAgeInSeconds *int32 `xml:"MaxAgeInSeconds"` +} + +// ClearRange - A clear range. +type ClearRange struct { + // REQUIRED; The end of the byte range. + End *int64 `xml:"End"` + + // REQUIRED; The start of the byte range. + Start *int64 `xml:"Start"` +} + +// ContainerItem - Represents a container. +type ContainerItem struct { + // REQUIRED; The name of the container. + Name *string `xml:"Name"` + + // REQUIRED; The properties of the container. + Properties *ContainerProperties `xml:"Properties"` + + // Whether the container is soft-deleted. + Deleted *bool `xml:"Deleted"` + + // The metadata of the container. + Metadata map[string]*string `xml:"Metadata"` + + // The version of the container. + Version *string `xml:"Version"` +} + +// ContainerProperties - The properties of a container. +type ContainerProperties struct { + // REQUIRED; The ETag of the container. + ETag *azcore.ETag `xml:"Etag"` + + // REQUIRED; The date-time that the container was last modified. + LastModified *time.Time `xml:"Last-Modified"` + + // The default encryption scope of the container. + DefaultEncryptionScope *string `xml:"DefaultEncryptionScope"` + + // The date-time the container was deleted. + DeletedTime *time.Time `xml:"DeletedTime"` + + // Whether the container has an immutability policy. + HasImmutabilityPolicy *bool `xml:"HasImmutabilityPolicy"` + + // Whether the container has a legal hold. + HasLegalHold *bool `xml:"HasLegalHold"` + + // Whether immutable storage with versioning is enabled. + IsImmutableStorageWithVersioningEnabled *bool `xml:"ImmutableStorageWithVersioningEnabled"` + + // The lease duration of the container. + LeaseDuration *LeaseDurationType `xml:"LeaseDuration"` + + // The lease state of the container. + LeaseState *LeaseStateType `xml:"LeaseState"` + + // The lease status of the container. + LeaseStatus *LeaseStatusType `xml:"LeaseStatus"` + + // Whether to prevent encryption scope override. + PreventEncryptionScopeOverride *bool `xml:"DenyEncryptionScopeOverride"` + + // The public access type of the container. + PublicAccess *PublicAccessType `xml:"PublicAccess"` + + // The remaining retention days of the container. + RemainingRetentionDays *int32 `xml:"RemainingRetentionDays"` +} + +// DelimitedTextConfiguration - Represents the delimited text configuration. +type DelimitedTextConfiguration struct { + // The string used to separate columns. + ColumnSeparator *string `xml:"ColumnSeparator"` + + // The string used to escape a quote character in a field. + EscapeChar *string `xml:"EscapeChar"` + + // The string used to quote a specific field. + FieldQuote *string `xml:"FieldQuote"` + + // Represents whether the data has headers. + HeadersPresent *bool `xml:"HasHeaders"` + + // The string used to separate records. + RecordSeparator *string `xml:"RecordSeparator"` +} + +// FilterBlobItem - The filtered blob item. +type FilterBlobItem struct { + // REQUIRED; The name of the container. + ContainerName *string `xml:"ContainerName"` + + // REQUIRED; The name of the blob. + Name *string `xml:"Name"` + + // Whether it is the current version of the blob. + IsCurrentVersion *bool `xml:"IsCurrentVersion"` + + // The tags of the blob. + Tags *Tags `xml:"Tags"` + + // The version ID of the blob. + VersionID *string `xml:"VersionId"` +} + +// FilterBlobSegment - The result of the Find Blobs by Tags API. +type FilterBlobSegment struct { + // REQUIRED; The list of filtered blobs. + Blobs []*FilterBlobItem `xml:"Blobs>Blob"` + + // REQUIRED; The service endpoint. + ServiceEndpoint *string `xml:"ServiceEndpoint,attr"` + + // REQUIRED; The filter expression for the blobs. + Where *string `xml:"Where"` + + // An opaque string value that identifies the portion of the result set to be returned with the next operation. Use this value + // in the next request to continue the listing operation. + NextMarker *string `xml:"NextMarker"` +} + +// FlatListSegment - The blob flat list segment. +type FlatListSegment struct { + // REQUIRED; The blob items. + BlobItems []*Item `xml:"Blob"` +} + +// GeoReplication - Geo-replication information for the secondary storage service. +type GeoReplication struct { + // REQUIRED; A date-time value that indicates where all primary writes preceding this value are guaranteed to be available + // for read operations at the secondary. Primary writes after this point in time may or may not be available for reads. + LastSyncTime *time.Time `xml:"LastSyncTime"` + + // REQUIRED; The status of the secondary location. + Status *GeoReplicationStatus `xml:"Status"` +} + +// HierarchyListSegment - Represents an array of blobs. +type HierarchyListSegment struct { + // REQUIRED; The blob items. + BlobItems []*Item `xml:"Blob"` + + // The blob prefixes. + BlobPrefixes []*Prefix `xml:"BlobPrefix"` +} + +// Item - Represents a blob. +type Item struct { + // REQUIRED; Whether the blob is deleted. + Deleted *bool `xml:"Deleted"` + + // REQUIRED; The name of the blob. + Name *string `xml:"Name"` + + // REQUIRED; The properties of the blob. + Properties *Properties `xml:"Properties"` + + // REQUIRED; The snapshot of the blob. + Snapshot *string `xml:"Snapshot"` + + // The tags of the blob. + BlobTags *Tags `xml:"Tags"` + + // Whether the blob has versions only. + HasVersionsOnly *bool `xml:"HasVersionsOnly"` + + // Whether the blob is the current version. + IsCurrentVersion *bool `xml:"IsCurrentVersion"` + + // The metadata of the blob. + Metadata map[string]*string `xml:"Metadata"` + + // The object replication metadata of the blob. + OrMetadata map[string]*string `xml:"OrMetadata"` + + // The version ID of the blob. + VersionID *string `xml:"VersionId"` +} + +// JSONTextConfiguration - Represents the JSON text configuration. +type JSONTextConfiguration struct { + // The string used to separate records. + RecordSeparator *string `xml:"RecordSeparator"` +} + +// KeyInfo - Key information. +type KeyInfo struct { + // REQUIRED; The date-time the key expires. + Expiry *string `xml:"Expiry"` + + // REQUIRED; The date-time the key is active. + Start *string `xml:"Start"` + + // The delegated user tenant ID in Entra ID. + DelegatedUserTenantID *string `xml:"DelegatedUserTid"` +} + +// ListBlobsFlatSegmentResponse - The result of the List Blobs API. +type ListBlobsFlatSegmentResponse struct { + // REQUIRED; The container name. + ContainerName *string `xml:"ContainerName,attr"` + + // REQUIRED; The list of blobs. + Segment *FlatListSegment `xml:"Blobs"` + + // REQUIRED; The service endpoint. + ServiceEndpoint *string `xml:"ServiceEndpoint,attr"` + + // An opaque string value that identifies the portion of the result set returned with this operation. + Marker *string `xml:"Marker"` + + // The maximum number of blobs to be returned with this operation. + MaxResults *int32 `xml:"MaxResults"` + + // An opaque string value that identifies the portion of the result set to be returned with the next operation. Use this value + // in the next request to continue the listing operation. + NextMarker *string `xml:"NextMarker"` + + // The prefix of the list operation. + Prefix *string `xml:"Prefix"` +} + +// ListBlobsHierarchySegmentResponse - The result of the List Blobs Hierarchical API. +type ListBlobsHierarchySegmentResponse struct { + // REQUIRED; The container name. + ContainerName *string `xml:"ContainerName,attr"` + + // REQUIRED; The list of hierarchical blobs. + Segment *HierarchyListSegment `xml:"Blobs"` + + // REQUIRED; The service endpoint. + ServiceEndpoint *string `xml:"ServiceEndpoint,attr"` + + // The delimiter of the blobs. + Delimiter *string `xml:"Delimiter"` + + // An opaque string value that identifies the portion of the result set returned with this operation. + Marker *string `xml:"Marker"` + + // The maximum number of blobs to be returned with this operation. + MaxResults *int32 `xml:"MaxResults"` + + // An opaque string value that identifies the portion of the result set to be returned with the next operation. Use this value + // in the next request to continue the listing operation. + NextMarker *string `xml:"NextMarker"` + + // The prefix of the blobs. + Prefix *string `xml:"Prefix"` +} + +// ListContainersSegmentResponse - The result of the List Containers API. +type ListContainersSegmentResponse struct { + // REQUIRED; The list of containers. + ContainerItems []*ContainerItem `xml:"Containers>Container"` + + // REQUIRED; The service endpoint. + ServiceEndpoint *string `xml:"ServiceEndpoint,attr"` + + // An opaque string value that identifies the portion of the result set returned with this operation. + Marker *string `xml:"Marker"` + + // The maximum number of containers to be returned with this operation. + MaxResults *int32 `xml:"MaxResults"` + + // An opaque string value that identifies the portion of the result set to be returned with the next operation. Use this value + // in the next request to continue the listing operation. + NextMarker *string `xml:"NextMarker"` + + // The prefix of the containers. + Prefix *string `xml:"Prefix"` +} + +// Logging - Azure Analytics logging settings. +type Logging struct { + // REQUIRED; Whether delete operation is logged. + Delete *bool `xml:"Delete"` + + // REQUIRED; Whether read operation is logged. + Read *bool `xml:"Read"` + + // REQUIRED; The retention policy of the logs. + RetentionPolicy *RetentionPolicy `xml:"RetentionPolicy"` + + // REQUIRED; The version of the logging properties. + Version *string `xml:"Version"` + + // REQUIRED; Whether write operation is logged. + Write *bool `xml:"Write"` +} + +// Metrics - The metrics properties. +type Metrics struct { + // REQUIRED; Whether the metrics are enabled. + Enabled *bool `xml:"Enabled"` + + // Whether to include API in the metrics. + IncludeAPIs *bool `xml:"IncludeAPIs"` + + // The retention policy of the metrics. + RetentionPolicy *RetentionPolicy `xml:"RetentionPolicy"` + + // The version of the metrics properties. + Version *string `xml:"Version"` +} + +// PageList - The result of the Get Pages API. +type PageList struct { + // The clear ranges. + ClearRange []*ClearRange `xml:"ClearRange"` + + // An opaque string value that identifies the portion of the result set to be returned with the next operation. Use this value + // in the next request to continue the listing operation. + NextMarker *string `xml:"NextMarker"` + + // The page ranges. + PageRange []*PageRange `xml:"PageRange"` +} + +// PageRange - A page range. +type PageRange struct { + // REQUIRED; The end of the byte range. + End *int64 `xml:"End"` + + // REQUIRED; The start of the byte range. + Start *int64 `xml:"Start"` +} + +// ParquetConfiguration - Represents the Parquet configuration. +type ParquetConfiguration struct { + AdditionalProperties map[string]any +} + +// Prefix - Represents a blob prefix. +type Prefix struct { + // REQUIRED; The blob name. + Name *string `xml:"Name"` + + // REQUIRED + Properties *Properties `xml:"Properties"` +} + +// Properties - The properties of a blob. +type Properties struct { + // REQUIRED; The blob ETag. + ETag *azcore.ETag `xml:"Etag"` + + // REQUIRED; The date-time the blob was last modified in RFC1123 format. + LastModified *time.Time `xml:"Last-Modified"` + ACL *string `xml:"Acl"` + + // The access tier of the blob. + AccessTier *AccessTier `xml:"AccessTier"` + + // The access tier change time of the blob. + AccessTierChangeTime *time.Time `xml:"AccessTierChangeTime"` + + // Whether the access tier is inferred. + AccessTierInferred *bool `xml:"AccessTierInferred"` + + // The archive status of the blob. + ArchiveStatus *ArchiveStatus `xml:"ArchiveStatus"` + + // The sequence number of the blob. + BlobSequenceNumber *int64 `xml:"x-ms-blob-sequence-number"` + + // The blob type. + BlobType *Type `xml:"BlobType"` + + // The cache control of the blob. + CacheControl *string `xml:"Cache-Control"` + + // The content disposition of the blob. + ContentDisposition *string `xml:"Content-Disposition"` + + // The content encoding of the blob. + ContentEncoding *string `xml:"Content-Encoding"` + + // The content language of the blob. + ContentLanguage *string `xml:"Content-Language"` + + // The content length of the blob. + ContentLength *int64 `xml:"Content-Length"` + + // The content MD5 of the blob. + ContentMD5 []byte `xml:"Content-MD5"` + + // The content type of the blob. + ContentType *string `xml:"Content-Type"` + + // The copy completion time of the blob. + CopyCompletionTime *time.Time `xml:"CopyCompletionTime"` + + // The copy ID of the blob. + CopyID *string `xml:"CopyId"` + + // The copy progress of the blob. + CopyProgress *string `xml:"CopyProgress"` + + // The copy source of the blob. + CopySource *string `xml:"CopySource"` + + // The copy status of the blob. + CopyStatus *CopyStatusType `xml:"CopyStatus"` + + // The copy status description of the blob. + CopyStatusDescription *string `xml:"CopyStatusDescription"` + + // The date-time the blob was created in RFC1123 format. + CreationTime *time.Time `xml:"Creation-Time"` + + // Customer provided key sha256 + CustomerProvidedKeySHA256 *string `xml:"CustomerProvidedKeySha256"` + + // The time the blob was deleted. + DeletedTime *time.Time `xml:"DeletedTime"` + + // The name of the destination snapshot. + DestinationSnapshot *string `xml:"DestinationSnapshot"` + + // The encryption scope of the blob. + EncryptionScope *string `xml:"EncryptionScope"` + + // The expire time of the blob. + ExpiresOn *time.Time `xml:"Expiry-Time"` + Group *string `xml:"Group"` + + // The immutability policy until time of the blob. + ImmutabilityPolicyExpiresOn *time.Time `xml:"ImmutabilityPolicyUntilDate"` + + // The immutability policy mode of the blob. + ImmutabilityPolicyMode *ImmutabilityPolicyMode `xml:"ImmutabilityPolicyMode"` + + // Whether the blob is incremental copy. + IncrementalCopy *bool `xml:"IncrementalCopy"` + + // Whether the blob is sealed. + IsSealed *bool `xml:"Sealed"` + + // The last access time of the blob. + LastAccessedOn *time.Time `xml:"LastAccessTime"` + + // The lease duration of the blob. + LeaseDuration *LeaseDurationType `xml:"LeaseDuration"` + + // The lease state of the blob. + LeaseState *LeaseStateType `xml:"LeaseState"` + + // The lease status of the blob. + LeaseStatus *LeaseStatusType `xml:"LeaseStatus"` + + // Whether the blob is under legal hold. + LegalHold *bool `xml:"LegalHold"` + Owner *string `xml:"Owner"` + Permissions *string `xml:"Permissions"` + + // The rehydrate priority of the blob. + RehydratePriority *RehydratePriority `xml:"RehydratePriority"` + + // The remaining retention days of the blob. + RemainingRetentionDays *int32 `xml:"RemainingRetentionDays"` + ResourceType *string `xml:"ResourceType"` + + // Whether the blob is encrypted on the server. + ServerEncrypted *bool `xml:"ServerEncrypted"` + + // The smart access tier of the blob. + SmartAccessTier *AccessTier `xml:"SmartAccessTier"` + + // The number of tags for the blob. + TagCount *int32 `xml:"TagCount"` +} + +// QueryFormat - The query format settings. +type QueryFormat struct { + // REQUIRED; The query type. + Type *QueryFormatType `xml:"Type"` + + // The Apache Arrow configuration. + ArrowConfiguration *ArrowConfiguration `xml:"ArrowConfiguration"` + + // The delimited text configuration. + DelimitedTextConfiguration *DelimitedTextConfiguration `xml:"DelimitedTextConfiguration"` + + // The JSON text configuration. + JSONTextConfiguration *JSONTextConfiguration `xml:"JsonTextConfiguration"` + + // The Parquet configuration. + ParquetTextConfiguration *ParquetConfiguration `xml:"ParquetTextConfiguration"` +} + +// QueryRequest - Groups the set of query request settings. +type QueryRequest struct { + // REQUIRED; The query expression. The maximum size of the query expression is 256KiB. + Expression *string `xml:"Expression"` + + // REQUIRED; Required. The type of the provided query expression. + QueryType *QueryRequestType `xml:"QueryType"` + + // The input serialization settings. + InputSerialization *QuerySerialization `xml:"InputSerialization"` + + // The output serialization settings. + OutputSerialization *QuerySerialization `xml:"OutputSerialization"` +} + +// QuerySerialization - The query serialization settings. +type QuerySerialization struct { + // REQUIRED; The query format. + Format *QueryFormat `xml:"Format"` +} + +// RetentionPolicy - The retention policy. +type RetentionPolicy struct { + // REQUIRED; Whether the policy is enabled. + Enabled *bool `xml:"Enabled"` + + // Whether to allow permanent delete. + AllowPermanentDelete *bool `xml:"AllowPermanentDelete"` + + // The number of days to retain the logs. + Days *int32 `xml:"Days"` +} + +// SignedIdentifier - A signed identifier. +type SignedIdentifier struct { + // REQUIRED; The unique ID for the signed identifier. + ID *string `xml:"Id"` + + // The access policy for the signed identifier. + AccessPolicy *AccessPolicy `xml:"AccessPolicy"` +} + +// StaticWebsite - The properties that enable an account to host a static website. +type StaticWebsite struct { + // REQUIRED; Indicates whether this account is hosting a static website. + Enabled *bool `xml:"Enabled"` + + // Absolute path of the default index page. + DefaultIndexDocumentPath *string `xml:"DefaultIndexDocumentPath"` + + // The error document. + ErrorDocument404Path *string `xml:"ErrorDocument404Path"` + + // The index document. + IndexDocument *string `xml:"IndexDocument"` +} + +// StorageServiceProperties - The blob service properties. +type StorageServiceProperties struct { + // The CORS properties. + CORS []*CORSRule `xml:"Cors>CorsRule"` + + // The default service version. + DefaultServiceVersion *string `xml:"DefaultServiceVersion"` + + // The delete retention policy. + DeleteRetentionPolicy *RetentionPolicy `xml:"DeleteRetentionPolicy"` + + // The hour metrics properties. + HourMetrics *Metrics `xml:"HourMetrics"` + + // The logging properties. + Logging *Logging `xml:"Logging"` + + // The minute metrics properties. + MinuteMetrics *Metrics `xml:"MinuteMetrics"` + + // The static website properties. + StaticWebsite *StaticWebsite `xml:"StaticWebsite"` +} + +// StorageServiceStats - Stats for the storage service. +type StorageServiceStats struct { + // The geo-replication stats. + GeoReplication *GeoReplication `xml:"GeoReplication"` +} + +// Tag - A key-value pair associated with a blob. +type Tag struct { + // REQUIRED; The key of the tag. + Key *string `xml:"Key"` + + // REQUIRED; The value of the tag. + Value *string `xml:"Value"` +} + +// Tags - A list of blob tags. +type Tags struct { + // REQUIRED; A list of blob tags. + BlobTagSet []*Tag `xml:"TagSet>Tag"` +} + +// UserDelegationKey - A user delegation key. +type UserDelegationKey struct { + // REQUIRED; The date-time the key expires. + SignedExpiry *time.Time `xml:"SignedExpiry"` + + // REQUIRED; The Entra ID object ID in GUID format. + SignedOID *string `xml:"SignedOid"` + + // REQUIRED; Abbreviation of the Azure Storage service that accepts the key. + SignedService *string `xml:"SignedService"` + + // REQUIRED; The date-time the key is active. + SignedStart *time.Time `xml:"SignedStart"` + + // REQUIRED; The Entra ID tenant ID in GUID format. + SignedTID *string `xml:"SignedTid"` + + // REQUIRED; The service version that created the key. + SignedVersion *string `xml:"SignedVersion"` + + // REQUIRED; The base64 encoded key value. + Value *string `xml:"Value"` + + // The delegated user tenant ID in Entra ID. Returned if DelegatedUserTid is specified. + SignedDelegatedUserTenantID *string `xml:"SignedDelegatedUserTid"` +} diff --git a/test/local/azblob/zz_models_serde.go b/test/local/azblob/zz_models_serde.go new file mode 100644 index 000000000000..bbaaa3962e97 --- /dev/null +++ b/test/local/azblob/zz_models_serde.go @@ -0,0 +1,527 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azblob + +import ( + "encoding/xml" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "time" +) + +// MarshalXML implements the xml.Marshaller interface for type AccessPolicy. +func (a AccessPolicy) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + type alias AccessPolicy + aux := &struct { + *alias + Expiry *datetime.RFC3339 `xml:"Expiry"` + Start *datetime.RFC3339 `xml:"Start"` + }{ + alias: (*alias)(&a), + Expiry: (*datetime.RFC3339)(a.Expiry), + Start: (*datetime.RFC3339)(a.Start), + } + return enc.EncodeElement(aux, start) +} + +// UnmarshalXML implements the xml.Unmarshaller interface for type AccessPolicy. +func (a *AccessPolicy) UnmarshalXML(dec *xml.Decoder, start xml.StartElement) error { + type alias AccessPolicy + aux := &struct { + *alias + Expiry *datetime.RFC3339 `xml:"Expiry"` + Start *datetime.RFC3339 `xml:"Start"` + }{ + alias: (*alias)(a), + } + if err := dec.DecodeElement(aux, &start); err != nil { + return err + } + if aux.Expiry != nil && !(*time.Time)(aux.Expiry).IsZero() { + a.Expiry = (*time.Time)(aux.Expiry) + } + if aux.Start != nil && !(*time.Time)(aux.Start).IsZero() { + a.Start = (*time.Time)(aux.Start) + } + return nil +} + +// MarshalXML implements the xml.Marshaller interface for type ArrowConfiguration. +func (a ArrowConfiguration) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + type alias ArrowConfiguration + aux := &struct { + *alias + Schema *[]*ArrowField `xml:"Schema>Field"` + }{ + alias: (*alias)(&a), + } + if a.Schema != nil { + aux.Schema = &a.Schema + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type ArrowField. +func (a ArrowField) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + start.Name.Local = "Field" + type alias ArrowField + aux := &struct { + *alias + }{ + alias: (*alias)(&a), + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type BlockList. +func (b BlockList) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + type alias BlockList + aux := &struct { + *alias + CommittedBlocks *[]*Block `xml:"CommittedBlocks>Block"` + UncommittedBlocks *[]*Block `xml:"UncommittedBlocks>Block"` + }{ + alias: (*alias)(&b), + } + if b.CommittedBlocks != nil { + aux.CommittedBlocks = &b.CommittedBlocks + } + if b.UncommittedBlocks != nil { + aux.UncommittedBlocks = &b.UncommittedBlocks + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type BlockLookupList. +func (b BlockLookupList) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + start.Name.Local = "BlockList" + type alias BlockLookupList + aux := &struct { + *alias + Committed *[]*string `xml:"Committed"` + Latest *[]*string `xml:"Latest"` + Uncommitted *[]*string `xml:"Uncommitted"` + }{ + alias: (*alias)(&b), + } + if b.Committed != nil { + aux.Committed = &b.Committed + } + if b.Latest != nil { + aux.Latest = &b.Latest + } + if b.Uncommitted != nil { + aux.Uncommitted = &b.Uncommitted + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type CORSRule. +func (c CORSRule) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + start.Name.Local = "CorsRule" + type alias CORSRule + aux := &struct { + *alias + }{ + alias: (*alias)(&c), + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type ContainerItem. +func (c ContainerItem) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + start.Name.Local = "Container" + type alias ContainerItem + aux := &struct { + *alias + Metadata additionalProperties `xml:"Metadata"` + }{ + alias: (*alias)(&c), + } + aux.Metadata = (additionalProperties)(c.Metadata) + return enc.EncodeElement(aux, start) +} + +// UnmarshalXML implements the xml.Unmarshaller interface for type ContainerItem. +func (c *ContainerItem) UnmarshalXML(dec *xml.Decoder, start xml.StartElement) error { + type alias ContainerItem + aux := &struct { + *alias + Metadata additionalProperties `xml:"Metadata"` + }{ + alias: (*alias)(c), + } + if err := dec.DecodeElement(aux, &start); err != nil { + return err + } + c.Metadata = (map[string]*string)(aux.Metadata) + return nil +} + +// MarshalXML implements the xml.Marshaller interface for type ContainerProperties. +func (c ContainerProperties) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + type alias ContainerProperties + aux := &struct { + *alias + DeletedTime *datetime.RFC7231 `xml:"DeletedTime"` + LastModified *datetime.RFC7231 `xml:"Last-Modified"` + }{ + alias: (*alias)(&c), + DeletedTime: (*datetime.RFC7231)(c.DeletedTime), + LastModified: (*datetime.RFC7231)(c.LastModified), + } + return enc.EncodeElement(aux, start) +} + +// UnmarshalXML implements the xml.Unmarshaller interface for type ContainerProperties. +func (c *ContainerProperties) UnmarshalXML(dec *xml.Decoder, start xml.StartElement) error { + type alias ContainerProperties + aux := &struct { + *alias + DeletedTime *datetime.RFC7231 `xml:"DeletedTime"` + LastModified *datetime.RFC7231 `xml:"Last-Modified"` + }{ + alias: (*alias)(c), + } + if err := dec.DecodeElement(aux, &start); err != nil { + return err + } + if aux.DeletedTime != nil && !(*time.Time)(aux.DeletedTime).IsZero() { + c.DeletedTime = (*time.Time)(aux.DeletedTime) + } + if aux.LastModified != nil && !(*time.Time)(aux.LastModified).IsZero() { + c.LastModified = (*time.Time)(aux.LastModified) + } + return nil +} + +// MarshalXML implements the xml.Marshaller interface for type FilterBlobItem. +func (f FilterBlobItem) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + start.Name.Local = "Blob" + type alias FilterBlobItem + aux := &struct { + *alias + }{ + alias: (*alias)(&f), + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type FilterBlobSegment. +func (f FilterBlobSegment) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + start.Name.Local = "EnumerationResults" + type alias FilterBlobSegment + aux := &struct { + *alias + Blobs *[]*FilterBlobItem `xml:"Blobs>Blob"` + }{ + alias: (*alias)(&f), + } + if f.Blobs != nil { + aux.Blobs = &f.Blobs + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type FlatListSegment. +func (f FlatListSegment) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + start.Name.Local = "BlobFlatListSegment" + type alias FlatListSegment + aux := &struct { + *alias + BlobItems *[]*Item `xml:"Blob"` + }{ + alias: (*alias)(&f), + } + if f.BlobItems != nil { + aux.BlobItems = &f.BlobItems + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type GeoReplication. +func (g GeoReplication) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + type alias GeoReplication + aux := &struct { + *alias + LastSyncTime *datetime.RFC7231 `xml:"LastSyncTime"` + }{ + alias: (*alias)(&g), + LastSyncTime: (*datetime.RFC7231)(g.LastSyncTime), + } + return enc.EncodeElement(aux, start) +} + +// UnmarshalXML implements the xml.Unmarshaller interface for type GeoReplication. +func (g *GeoReplication) UnmarshalXML(dec *xml.Decoder, start xml.StartElement) error { + type alias GeoReplication + aux := &struct { + *alias + LastSyncTime *datetime.RFC7231 `xml:"LastSyncTime"` + }{ + alias: (*alias)(g), + } + if err := dec.DecodeElement(aux, &start); err != nil { + return err + } + if aux.LastSyncTime != nil && !(*time.Time)(aux.LastSyncTime).IsZero() { + g.LastSyncTime = (*time.Time)(aux.LastSyncTime) + } + return nil +} + +// MarshalXML implements the xml.Marshaller interface for type HierarchyListSegment. +func (h HierarchyListSegment) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + start.Name.Local = "BlobHierarchyList" + type alias HierarchyListSegment + aux := &struct { + *alias + BlobItems *[]*Item `xml:"Blob"` + BlobPrefixes *[]*Prefix `xml:"BlobPrefix"` + }{ + alias: (*alias)(&h), + } + if h.BlobItems != nil { + aux.BlobItems = &h.BlobItems + } + if h.BlobPrefixes != nil { + aux.BlobPrefixes = &h.BlobPrefixes + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type JSONTextConfiguration. +func (j JSONTextConfiguration) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + start.Name.Local = "JsonTextConfiguration" + type alias JSONTextConfiguration + aux := &struct { + *alias + }{ + alias: (*alias)(&j), + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type ListBlobsFlatSegmentResponse. +func (l ListBlobsFlatSegmentResponse) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + start.Name.Local = "EnumerationResults" + type alias ListBlobsFlatSegmentResponse + aux := &struct { + *alias + }{ + alias: (*alias)(&l), + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type ListBlobsHierarchySegmentResponse. +func (l ListBlobsHierarchySegmentResponse) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + start.Name.Local = "EnumerationResults" + type alias ListBlobsHierarchySegmentResponse + aux := &struct { + *alias + }{ + alias: (*alias)(&l), + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type ListContainersSegmentResponse. +func (l ListContainersSegmentResponse) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + start.Name.Local = "EnumerationResults" + type alias ListContainersSegmentResponse + aux := &struct { + *alias + ContainerItems *[]*ContainerItem `xml:"Containers>Container"` + }{ + alias: (*alias)(&l), + } + if l.ContainerItems != nil { + aux.ContainerItems = &l.ContainerItems + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type PageList. +func (p PageList) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + type alias PageList + aux := &struct { + *alias + ClearRange *[]*ClearRange `xml:"ClearRange"` + PageRange *[]*PageRange `xml:"PageRange"` + }{ + alias: (*alias)(&p), + } + if p.ClearRange != nil { + aux.ClearRange = &p.ClearRange + } + if p.PageRange != nil { + aux.PageRange = &p.PageRange + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type Prefix. +func (p Prefix) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + start.Name.Local = "BlobPrefix" + type alias Prefix + aux := &struct { + *alias + }{ + alias: (*alias)(&p), + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type Properties. +func (p Properties) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + type alias Properties + aux := &struct { + *alias + AccessTierChangeTime *datetime.RFC7231 `xml:"AccessTierChangeTime"` + ContentMD5 *string `xml:"Content-MD5"` + CopyCompletionTime *datetime.RFC7231 `xml:"CopyCompletionTime"` + CreationTime *datetime.RFC7231 `xml:"Creation-Time"` + DeletedTime *datetime.RFC7231 `xml:"DeletedTime"` + ExpiresOn *datetime.RFC7231 `xml:"Expiry-Time"` + ImmutabilityPolicyExpiresOn *datetime.RFC7231 `xml:"ImmutabilityPolicyUntilDate"` + LastAccessedOn *datetime.RFC7231 `xml:"LastAccessTime"` + LastModified *datetime.RFC7231 `xml:"Last-Modified"` + }{ + alias: (*alias)(&p), + AccessTierChangeTime: (*datetime.RFC7231)(p.AccessTierChangeTime), + CopyCompletionTime: (*datetime.RFC7231)(p.CopyCompletionTime), + CreationTime: (*datetime.RFC7231)(p.CreationTime), + DeletedTime: (*datetime.RFC7231)(p.DeletedTime), + ExpiresOn: (*datetime.RFC7231)(p.ExpiresOn), + ImmutabilityPolicyExpiresOn: (*datetime.RFC7231)(p.ImmutabilityPolicyExpiresOn), + LastAccessedOn: (*datetime.RFC7231)(p.LastAccessedOn), + LastModified: (*datetime.RFC7231)(p.LastModified), + } + if p.ContentMD5 != nil { + encodedContentMD5 := runtime.EncodeByteArray(p.ContentMD5, runtime.Base64StdFormat) + aux.ContentMD5 = &encodedContentMD5 + } + return enc.EncodeElement(aux, start) +} + +// UnmarshalXML implements the xml.Unmarshaller interface for type Properties. +func (p *Properties) UnmarshalXML(dec *xml.Decoder, start xml.StartElement) error { + type alias Properties + aux := &struct { + *alias + AccessTierChangeTime *datetime.RFC7231 `xml:"AccessTierChangeTime"` + ContentMD5 *string `xml:"Content-MD5"` + CopyCompletionTime *datetime.RFC7231 `xml:"CopyCompletionTime"` + CreationTime *datetime.RFC7231 `xml:"Creation-Time"` + DeletedTime *datetime.RFC7231 `xml:"DeletedTime"` + ExpiresOn *datetime.RFC7231 `xml:"Expiry-Time"` + ImmutabilityPolicyExpiresOn *datetime.RFC7231 `xml:"ImmutabilityPolicyUntilDate"` + LastAccessedOn *datetime.RFC7231 `xml:"LastAccessTime"` + LastModified *datetime.RFC7231 `xml:"Last-Modified"` + }{ + alias: (*alias)(p), + } + if err := dec.DecodeElement(aux, &start); err != nil { + return err + } + if aux.AccessTierChangeTime != nil && !(*time.Time)(aux.AccessTierChangeTime).IsZero() { + p.AccessTierChangeTime = (*time.Time)(aux.AccessTierChangeTime) + } + if aux.ContentMD5 != nil { + if err := runtime.DecodeByteArray(*aux.ContentMD5, &p.ContentMD5, runtime.Base64StdFormat); err != nil { + return err + } + } + if aux.CopyCompletionTime != nil && !(*time.Time)(aux.CopyCompletionTime).IsZero() { + p.CopyCompletionTime = (*time.Time)(aux.CopyCompletionTime) + } + if aux.CreationTime != nil && !(*time.Time)(aux.CreationTime).IsZero() { + p.CreationTime = (*time.Time)(aux.CreationTime) + } + if aux.DeletedTime != nil && !(*time.Time)(aux.DeletedTime).IsZero() { + p.DeletedTime = (*time.Time)(aux.DeletedTime) + } + if aux.ExpiresOn != nil && !(*time.Time)(aux.ExpiresOn).IsZero() { + p.ExpiresOn = (*time.Time)(aux.ExpiresOn) + } + if aux.ImmutabilityPolicyExpiresOn != nil && !(*time.Time)(aux.ImmutabilityPolicyExpiresOn).IsZero() { + p.ImmutabilityPolicyExpiresOn = (*time.Time)(aux.ImmutabilityPolicyExpiresOn) + } + if aux.LastAccessedOn != nil && !(*time.Time)(aux.LastAccessedOn).IsZero() { + p.LastAccessedOn = (*time.Time)(aux.LastAccessedOn) + } + if aux.LastModified != nil && !(*time.Time)(aux.LastModified).IsZero() { + p.LastModified = (*time.Time)(aux.LastModified) + } + return nil +} + +// MarshalXML implements the xml.Marshaller interface for type StorageServiceProperties. +func (s StorageServiceProperties) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + type alias StorageServiceProperties + aux := &struct { + *alias + CORS *[]*CORSRule `xml:"Cors>CorsRule"` + }{ + alias: (*alias)(&s), + } + if s.CORS != nil { + aux.CORS = &s.CORS + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type Tags. +func (t Tags) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + type alias Tags + aux := &struct { + *alias + BlobTagSet *[]*Tag `xml:"TagSet>Tag"` + }{ + alias: (*alias)(&t), + } + if t.BlobTagSet != nil { + aux.BlobTagSet = &t.BlobTagSet + } + return enc.EncodeElement(aux, start) +} + +// MarshalXML implements the xml.Marshaller interface for type UserDelegationKey. +func (u UserDelegationKey) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + type alias UserDelegationKey + aux := &struct { + *alias + SignedExpiry *datetime.RFC3339 `xml:"SignedExpiry"` + SignedStart *datetime.RFC3339 `xml:"SignedStart"` + }{ + alias: (*alias)(&u), + SignedExpiry: (*datetime.RFC3339)(u.SignedExpiry), + SignedStart: (*datetime.RFC3339)(u.SignedStart), + } + return enc.EncodeElement(aux, start) +} + +// UnmarshalXML implements the xml.Unmarshaller interface for type UserDelegationKey. +func (u *UserDelegationKey) UnmarshalXML(dec *xml.Decoder, start xml.StartElement) error { + type alias UserDelegationKey + aux := &struct { + *alias + SignedExpiry *datetime.RFC3339 `xml:"SignedExpiry"` + SignedStart *datetime.RFC3339 `xml:"SignedStart"` + }{ + alias: (*alias)(u), + } + if err := dec.DecodeElement(aux, &start); err != nil { + return err + } + if aux.SignedExpiry != nil && !(*time.Time)(aux.SignedExpiry).IsZero() { + u.SignedExpiry = (*time.Time)(aux.SignedExpiry) + } + if aux.SignedStart != nil && !(*time.Time)(aux.SignedStart).IsZero() { + u.SignedStart = (*time.Time)(aux.SignedStart) + } + return nil +} diff --git a/test/local/azblob/zz_options.go b/test/local/azblob/zz_options.go new file mode 100644 index 000000000000..d05603094a89 --- /dev/null +++ b/test/local/azblob/zz_options.go @@ -0,0 +1,2333 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azblob + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "time" +) + +// AppendBlobClientAppendBlockFromURLOptions contains the optional parameters for the AppendBlobClient.AppendBlockFromURL +// method. +type AppendBlobClientAppendBlockFromURLOptions struct { + // A byte offset where the operation will only succeed if the append position is equal. If not, the request will fail with + // AppendPositionConditionNotMet. + AppendPosition *int64 + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Only the Bearer authorization scheme is supported, and the value must be a valid OAuth access token for the copy source. + CopySourceAuthorization *string + + // The algorithm used to produce the encryption key hash. Must be provided if the encryption key is provided. + EncryptionAlgorithm *EncryptionAlgorithmType + + // Specifies the encryption key to use to encrypt the data provided in the request. + EncryptionKey *string + + // The SHA-256 hash of the provided encryption key. Must be provided if the encryption key is provided. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Specifies the file request token intent. + FileRequestIntent *FileShareTokenIntent + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // The max length of the blob. If the operation would cause the blob to exceed that limit or if the blob size is already greater + // than the value specified, the request will fail with MaxBlobSizeConditionNotMet. + MaxSize *int64 + + // Specifies the CRC64 calculated for the range of bytes that must be read from the source. + SourceContentCRC64 []byte + + // Specifies the MD5 hash calculated for the range of bytes that must be read from the copy source. + SourceContentMD5 []byte + + // The algorithm used to produce the source encryption key hash. Must be provided if the source encryption key is provided. + SourceEncryptionAlgorithm *EncryptionAlgorithmType + + // Specifies the encryption key to use to decrypt the source data provided in the request. + SourceEncryptionKey *string + + // The SHA-256 hash of the provided source encryption key. Must be provided if the source encryption key is provided. + SourceEncryptionKeySHA256 *string + + // Specify this value to operate only on a source blob with a matching Etag value. + SourceIfMatch *azcore.ETag + + // Specify this value to operate only on a source blob if it has been modified since the specified date-time. + SourceIfModifiedSince *time.Time + + // Specify this value to operate only on a source blob with a non-matching Etag value. + SourceIfNoneMatch *azcore.ETag + + // Specify this header value to operate only on a blob if it has not been modified since the specified date-time. + SourceIfUnmodifiedSince *time.Time + + // Specifies the bytes of the source. + SourceRange *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 + + // Specifies the transactional MD5 hash for the body. + TransactionalContentMD5 []byte +} + +// AppendBlobClientAppendBlockOptions contains the optional parameters for the AppendBlobClient.AppendBlock method. +type AppendBlobClientAppendBlockOptions struct { + // A byte offset where the operation will only succeed if the append position is equal. If not, the request will fail with + // AppendPositionConditionNotMet. + AppendPosition *int64 + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The algorithm used to produce the encryption key hash. Must be provided if the encryption key is provided. + EncryptionAlgorithm *EncryptionAlgorithmType + + // Specifies the encryption key to use to encrypt the data provided in the request. + EncryptionKey *string + + // The SHA-256 hash of the provided encryption key. Must be provided if the encryption key is provided. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // The max length of the blob. If the operation would cause the blob to exceed that limit or if the blob size is already greater + // than the value specified, the request will fail with MaxBlobSizeConditionNotMet. + MaxSize *int64 + + // Required if the request body is a structured message. Specifies the message schema version and properties. + StructuredBodyType *string + + // Required if the request body is a structured message. Specifies the length of the blob/file content inside the message + // body. Will always be smaller than Content-Length. + StructuredContentLength *int64 + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 + + // Specifies the transactional CRC64 hash for the body. + TransactionalContentCRC64 []byte + + // Specifies the transactional MD5 hash for the body. + TransactionalContentMD5 []byte +} + +// AppendBlobClientCreateOptions contains the optional parameters for the AppendBlobClient.Create method. +type AppendBlobClientCreateOptions struct { + // Specifies the blob's Cache-Control. If specified, this property is stored with the blob and returned with a read request. + BlobCacheControl *string + + // Specifies the blob's Content-Disposition. If specified, this property is stored with the blob and returned with a read + // request. + BlobContentDisposition *string + + // Specifies the blob's Content-Encoding. If specified, this property is stored with the blob and returned with a read request. + BlobContentEncoding *string + + // Specifies the blob's Content-Language. If specified, this property is stored with the blob and returned with a read request. + BlobContentLanguage *string + + // The MD5 hash of the blob content that is stored as a property on the blob. Note: This hash is not validated. + BlobContentMD5 []byte + + // Specifies the blob's Content-Type. If specified, this property is stored with the blob and returned with a read request. + BlobContentType *string + + // The blob tags. + BlobTagsString *string + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The algorithm used to produce the encryption key hash. Must be provided if the encryption key is provided. + EncryptionAlgorithm *EncryptionAlgorithmType + + // Specifies the encryption key to use to encrypt the data provided in the request. + EncryptionKey *string + + // The SHA-256 hash of the provided encryption key. Must be provided if the encryption key is provided. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // The date-time that indicates the time at which the blob immutability policy will expire. + ImmutabilityPolicyExpiry *time.Time + + // Indicates the immutability policy mode of the blob. + ImmutabilityPolicyMode *ImmutabilityPolicySetting + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // Indicates whether the blob has a legal hold. + LegalHold *bool + + // The metadata headers. + Metadata map[string]*string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// AppendBlobClientSealOptions contains the optional parameters for the AppendBlobClient.Seal method. +type AppendBlobClientSealOptions struct { + // A byte offset where the operation will only succeed if the append position is equal. If not, the request will fail with + // AppendPositionConditionNotMet. + AppendPosition *int64 + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// BlockBlobClientCommitBlockListOptions contains the optional parameters for the BlockBlobClient.CommitBlockList method. +type BlockBlobClientCommitBlockListOptions struct { + // Specifies the blob's Cache-Control. If specified, this property is stored with the blob and returned with a read request. + BlobCacheControl *string + + // Specifies the blob's Content-Disposition. If specified, this property is stored with the blob and returned with a read + // request. + BlobContentDisposition *string + + // Specifies the blob's Content-Encoding. If specified, this property is stored with the blob and returned with a read request. + BlobContentEncoding *string + + // Specifies the blob's Content-Language. If specified, this property is stored with the blob and returned with a read request. + BlobContentLanguage *string + + // The MD5 hash of the blob content that is stored as a property on the blob. Note: This hash is not validated. + BlobContentMD5 []byte + + // Specifies the blob's Content-Type. If specified, this property is stored with the blob and returned with a read request. + BlobContentType *string + + // The blob tags. + BlobTagsString *string + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The algorithm used to produce the encryption key hash. Must be provided if the encryption key is provided. + EncryptionAlgorithm *EncryptionAlgorithmType + + // Specifies the encryption key to use to encrypt the data provided in the request. + EncryptionKey *string + + // The SHA-256 hash of the provided encryption key. Must be provided if the encryption key is provided. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // The date-time that indicates the time at which the blob immutability policy will expire. + ImmutabilityPolicyExpiry *time.Time + + // Indicates the immutability policy mode of the blob. + ImmutabilityPolicyMode *ImmutabilityPolicySetting + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // Indicates whether the blob has a legal hold. + LegalHold *bool + + // The metadata headers. + Metadata map[string]*string + + // The tier to be set on the blob. + Tier *AccessTier + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 + + // Specifies the transactional CRC64 hash for the body. + TransactionalContentCRC64 []byte + + // Specifies the transactional MD5 hash for the body. + TransactionalContentMD5 []byte +} + +// BlockBlobClientGetBlockListOptions contains the optional parameters for the BlockBlobClient.GetBlockList method. +type BlockBlobClientGetBlockListOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // Specifies the snapshot of the blob. + Snapshot *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// BlockBlobClientQueryOptions contains the optional parameters for the BlockBlobClient.Query method. +type BlockBlobClientQueryOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The algorithm used to produce the encryption key hash. Must be provided if the encryption key is provided. + EncryptionAlgorithm *EncryptionAlgorithmType + + // Specifies the encryption key to use to encrypt the data provided in the request. + EncryptionKey *string + + // The SHA-256 hash of the provided encryption key. Must be provided if the encryption key is provided. + EncryptionKeySHA256 *string + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // Specifies the snapshot of the blob. + Snapshot *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// BlockBlobClientStageBlockFromURLOptions contains the optional parameters for the BlockBlobClient.StageBlockFromURL method. +type BlockBlobClientStageBlockFromURLOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Only the Bearer authorization scheme is supported, and the value must be a valid OAuth access token for the copy source. + CopySourceAuthorization *string + + // The algorithm used to produce the encryption key hash. Must be provided if the encryption key is provided. + EncryptionAlgorithm *EncryptionAlgorithmType + + // Specifies the encryption key to use to encrypt the data provided in the request. + EncryptionKey *string + + // The SHA-256 hash of the provided encryption key. Must be provided if the encryption key is provided. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Specifies the file request token intent. + FileRequestIntent *FileShareTokenIntent + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // Specifies the CRC64 calculated for the range of bytes that must be read from the source. + SourceContentCRC64 []byte + + // Specifies the MD5 hash calculated for the range of bytes that must be read from the copy source. + SourceContentMD5 []byte + + // The algorithm used to produce the source encryption key hash. Must be provided if the source encryption key is provided. + SourceEncryptionAlgorithm *EncryptionAlgorithmType + + // Specifies the encryption key to use to decrypt the source data provided in the request. + SourceEncryptionKey *string + + // The SHA-256 hash of the provided source encryption key. Must be provided if the source encryption key is provided. + SourceEncryptionKeySHA256 *string + + // Specify this value to operate only on a source blob with a matching Etag value. + SourceIfMatch *azcore.ETag + + // Specify this value to operate only on a source blob if it has been modified since the specified date-time. + SourceIfModifiedSince *time.Time + + // Specify this value to operate only on a source blob with a non-matching Etag value. + SourceIfNoneMatch *azcore.ETag + + // Specify this header value to operate only on a blob if it has not been modified since the specified date-time. + SourceIfUnmodifiedSince *time.Time + + // Specifies the bytes of the source. + SourceRange *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// BlockBlobClientStageBlockOptions contains the optional parameters for the BlockBlobClient.StageBlock method. +type BlockBlobClientStageBlockOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The algorithm used to produce the encryption key hash. Must be provided if the encryption key is provided. + EncryptionAlgorithm *EncryptionAlgorithmType + + // Specifies the encryption key to use to encrypt the data provided in the request. + EncryptionKey *string + + // The SHA-256 hash of the provided encryption key. Must be provided if the encryption key is provided. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // Required if the request body is a structured message. Specifies the message schema version and properties. + StructuredBodyType *string + + // Required if the request body is a structured message. Specifies the length of the blob/file content inside the message + // body. Will always be smaller than Content-Length. + StructuredContentLength *int64 + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 + + // Specifies the transactional CRC64 hash for the body. + TransactionalContentCRC64 []byte + + // Specifies the transactional MD5 hash for the body. + TransactionalContentMD5 []byte +} + +// BlockBlobClientUploadBlobFromURLOptions contains the optional parameters for the BlockBlobClient.UploadBlobFromURL method. +type BlockBlobClientUploadBlobFromURLOptions struct { + // Specifies the blob's Cache-Control. If specified, this property is stored with the blob and returned with a read request. + BlobCacheControl *string + + // Specifies the blob's Content-Disposition. If specified, this property is stored with the blob and returned with a read + // request. + BlobContentDisposition *string + + // Specifies the blob's Content-Encoding. If specified, this property is stored with the blob and returned with a read request. + BlobContentEncoding *string + + // Specifies the blob's Content-Language. If specified, this property is stored with the blob and returned with a read request. + BlobContentLanguage *string + + // The MD5 hash of the blob content that is stored as a property on the blob. Note: This hash is not validated. + BlobContentMD5 []byte + + // Specifies the blob's Content-Type. If specified, this property is stored with the blob and returned with a read request. + BlobContentType *string + + // The blob tags. + BlobTagsString *string + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Only the Bearer authorization scheme is supported, and the value must be a valid OAuth access token for the copy source. + CopySourceAuthorization *string + + // Indicates if properties from the source blob should be copied. Default is true. + CopySourceBlobProperties *bool + + // Indicates if source tags should be copied or replaced with the tags specified. Default is 'Replace'. + CopySourceTags *CopySourceTags + + // The algorithm used to produce the encryption key hash. Must be provided if the encryption key is provided. + EncryptionAlgorithm *EncryptionAlgorithmType + + // Specifies the encryption key to use to encrypt the data provided in the request. + EncryptionKey *string + + // The SHA-256 hash of the provided encryption key. Must be provided if the encryption key is provided. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Specifies the file request token intent. + FileRequestIntent *FileShareTokenIntent + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // The metadata headers. + Metadata map[string]*string + + // Specifies the MD5 hash calculated for the range of bytes that must be read from the copy source. + SourceContentMD5 []byte + + // The algorithm used to produce the source encryption key hash. Must be provided if the source encryption key is provided. + SourceEncryptionAlgorithm *EncryptionAlgorithmType + + // Specifies the encryption key to use to decrypt the source data provided in the request. + SourceEncryptionKey *string + + // The SHA-256 hash of the provided source encryption key. Must be provided if the source encryption key is provided. + SourceEncryptionKeySHA256 *string + + // Specify this value to operate only on a source blob with a matching Etag value. + SourceIfMatch *azcore.ETag + + // Specify this value to operate only on a source blob if it has been modified since the specified date-time. + SourceIfModifiedSince *time.Time + + // Specify this value to operate only on a source blob with a non-matching Etag value. + SourceIfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a source blob with matching tags. + SourceIfTags *string + + // Specify this header value to operate only on a blob if it has not been modified since the specified date-time. + SourceIfUnmodifiedSince *time.Time + + // The tier to be set on the blob. + Tier *AccessTier + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 + + // Specifies the transactional MD5 hash for the body. + TransactionalContentMD5 []byte +} + +// BlockBlobClientUploadOptions contains the optional parameters for the BlockBlobClient.Upload method. +type BlockBlobClientUploadOptions struct { + // Specifies the blob's Cache-Control. If specified, this property is stored with the blob and returned with a read request. + BlobCacheControl *string + + // Specifies the blob's Content-Disposition. If specified, this property is stored with the blob and returned with a read + // request. + BlobContentDisposition *string + + // Specifies the blob's Content-Encoding. If specified, this property is stored with the blob and returned with a read request. + BlobContentEncoding *string + + // Specifies the blob's Content-Language. If specified, this property is stored with the blob and returned with a read request. + BlobContentLanguage *string + + // The MD5 hash of the blob content that is stored as a property on the blob. Note: This hash is not validated. + BlobContentMD5 []byte + + // Specifies the blob's Content-Type. If specified, this property is stored with the blob and returned with a read request. + BlobContentType *string + + // The blob tags. + BlobTagsString *string + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The algorithm used to produce the encryption key hash. Must be provided if the encryption key is provided. + EncryptionAlgorithm *EncryptionAlgorithmType + + // Specifies the encryption key to use to encrypt the data provided in the request. + EncryptionKey *string + + // The SHA-256 hash of the provided encryption key. Must be provided if the encryption key is provided. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // The date-time that indicates the time at which the blob immutability policy will expire. + ImmutabilityPolicyExpiry *time.Time + + // Indicates the immutability policy mode of the blob. + ImmutabilityPolicyMode *ImmutabilityPolicySetting + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // Indicates whether the blob has a legal hold. + LegalHold *bool + + // The metadata headers. + Metadata map[string]*string + + // Required if the request body is a structured message. Specifies the message schema version and properties. + StructuredBodyType *string + + // Required if the request body is a structured message. Specifies the length of the blob/file content inside the message + // body. Will always be smaller than Content-Length. + StructuredContentLength *int64 + + // The tier to be set on the blob. + Tier *AccessTier + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 + + // Specifies the transactional CRC64 hash for the body. + TransactionalContentCRC64 []byte + + // Specifies the transactional MD5 hash for the body. + TransactionalContentMD5 []byte +} + +// ClientAbortCopyFromURLOptions contains the optional parameters for the Client.AbortCopyFromURL method. +type ClientAbortCopyFromURLOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ClientAcquireLeaseOptions contains the optional parameters for the Client.AcquireLease method. +type ClientAcquireLeaseOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // The proposed lease ID for the lease. + ProposedLeaseID *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ClientBreakLeaseOptions contains the optional parameters for the Client.BreakLease method. +type ClientBreakLeaseOptions struct { + // Proposed duration the lease should continue before it is broken, in seconds, between 0 and 60. This break period is only + // used if it is shorter than the time remaining on the lease. If longer, the time remaining on the lease is used. + BreakPeriod *int32 + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ClientChangeLeaseOptions contains the optional parameters for the Client.ChangeLease method. +type ClientChangeLeaseOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ClientCopyFromURLOptions contains the optional parameters for the Client.CopyFromURL method. +type ClientCopyFromURLOptions struct { + // The blob tags. + BlobTagsString *string + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Only the Bearer authorization scheme is supported, and the value must be a valid OAuth access token for the copy source. + CopySourceAuthorization *string + + // Indicates if source tags should be copied or replaced with the tags specified. Default is 'Replace'. + CopySourceTags *CopySourceTags + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Specifies the file request token intent. + FileRequestIntent *FileShareTokenIntent + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // The date-time that indicates the time at which the blob immutability policy will expire. + ImmutabilityPolicyExpiry *time.Time + + // Indicates the immutability policy mode of the blob. + ImmutabilityPolicyMode *ImmutabilityPolicySetting + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // Indicates whether the blob has a legal hold. + LegalHold *bool + + // The metadata headers. + Metadata map[string]*string + + // Specifies the MD5 hash calculated for the range of bytes that must be read from the copy source. + SourceContentMD5 []byte + + // Specify this value to operate only on a source blob with a matching Etag value. + SourceIfMatch *azcore.ETag + + // Specify this value to operate only on a source blob if it has been modified since the specified date-time. + SourceIfModifiedSince *time.Time + + // Specify this value to operate only on a source blob with a non-matching Etag value. + SourceIfNoneMatch *azcore.ETag + + // Specify this header value to operate only on a blob if it has not been modified since the specified date-time. + SourceIfUnmodifiedSince *time.Time + + // The tier to be set on the blob. + Tier *AccessTier + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ClientCreateSnapshotOptions contains the optional parameters for the Client.CreateSnapshot method. +type ClientCreateSnapshotOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The algorithm used to produce the encryption key hash. Must be provided if the encryption key is provided. + EncryptionAlgorithm *EncryptionAlgorithmType + + // Specifies the encryption key to use to encrypt the data provided in the request. + EncryptionKey *string + + // The SHA-256 hash of the provided encryption key. Must be provided if the encryption key is provided. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // The metadata headers. + Metadata map[string]*string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ClientDeleteImmutabilityPolicyOptions contains the optional parameters for the Client.DeleteImmutabilityPolicy method. +type ClientDeleteImmutabilityPolicyOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specifies the snapshot of the blob. + Snapshot *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 + + // Specifies the version ID of the blob. + VersionID *string +} + +// ClientDeleteOptions contains the optional parameters for the Client.Delete method. +type ClientDeleteOptions struct { + // Specify this header value to operate only on a blob if the access-tier has been modified since the specified date-time. + AccessTierIfModifiedSince *time.Time + + // Specify this header value to operate only on a blob if the access-tier has not been modified since the specified date-time. + AccessTierIfUnmodifiedSince *time.Time + + // The delete type. + BlobDeleteType *DeleteType + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Required if the blob has associated snapshots. Specifies the delete behavior. + DeleteSnapshots *DeleteSnapshotsOptionType + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // Specifies the snapshot of the blob. + Snapshot *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 + + // Specifies the version ID of the blob. + VersionID *string +} + +// ClientDownloadOptions contains the optional parameters for the Client.Download method. +type ClientDownloadOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The algorithm used to produce the encryption key hash. Must be provided if the encryption key is provided. + EncryptionAlgorithm *EncryptionAlgorithmType + + // Specifies the encryption key to use to encrypt the data provided in the request. + EncryptionKey *string + + // The SHA-256 hash of the provided encryption key. Must be provided if the encryption key is provided. + EncryptionKeySHA256 *string + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // Specifies the range of the blob to operate on. + Range *string + + // When set to true and the request includes a Range header, the service returns the CRC64 hash for the range, as long as + // the range is less than or equal to 4 MiB in size. + RangeGetContentCRC64 *bool + + // When set to true and specified together with the `Range` header, the service returns the MD5 hash for the range, as long + // as the range is less than or equal to 4 MiB in size. + RangeGetContentMD5 *bool + + // Specifies the snapshot of the blob. + Snapshot *string + + // Specifies the response content should be returned as a structured message and specifies the message schema version and + // properties. + StructuredBodyType *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 + + // Specifies the version ID of the blob. + VersionID *string +} + +// ClientGetAccountInfoOptions contains the optional parameters for the Client.GetAccountInfo method. +type ClientGetAccountInfoOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ClientGetPropertiesOptions contains the optional parameters for the Client.GetProperties method. +type ClientGetPropertiesOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The algorithm used to produce the encryption key hash. Must be provided if the encryption key is provided. + EncryptionAlgorithm *EncryptionAlgorithmType + + // Specifies the encryption key to use to encrypt the data provided in the request. + EncryptionKey *string + + // The SHA-256 hash of the provided encryption key. Must be provided if the encryption key is provided. + EncryptionKeySHA256 *string + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // Specifies the snapshot of the blob. + Snapshot *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 + + // Specifies the version ID of the blob. + VersionID *string +} + +// ClientGetTagsOptions contains the optional parameters for the Client.GetTags method. +type ClientGetTagsOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // Specifies the snapshot of the blob. + Snapshot *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 + + // Specifies the version ID of the blob. + VersionID *string +} + +// ClientReleaseLeaseOptions contains the optional parameters for the Client.ReleaseLease method. +type ClientReleaseLeaseOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ClientRenewLeaseOptions contains the optional parameters for the Client.RenewLease method. +type ClientRenewLeaseOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ClientSetExpiryOptions contains the optional parameters for the Client.SetExpiry method. +type ClientSetExpiryOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The date-time this blob will expire. + ExpiresOn *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ClientSetHTTPHeadersOptions contains the optional parameters for the Client.SetHTTPHeaders method. +type ClientSetHTTPHeadersOptions struct { + // Specifies the blob's Cache-Control. If specified, this property is stored with the blob and returned with a read request. + BlobCacheControl *string + + // Specifies the blob's Content-Disposition. If specified, this property is stored with the blob and returned with a read + // request. + BlobContentDisposition *string + + // Specifies the blob's Content-Encoding. If specified, this property is stored with the blob and returned with a read request. + BlobContentEncoding *string + + // Specifies the blob's Content-Language. If specified, this property is stored with the blob and returned with a read request. + BlobContentLanguage *string + + // The MD5 hash of the blob content that is stored as a property on the blob. Note: This hash is not validated. + BlobContentMD5 []byte + + // Specifies the blob's Content-Type. If specified, this property is stored with the blob and returned with a read request. + BlobContentType *string + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ClientSetImmutabilityPolicyOptions contains the optional parameters for the Client.SetImmutabilityPolicy method. +type ClientSetImmutabilityPolicyOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // Indicates the immutability policy mode of the blob. + ImmutabilityPolicyMode *ImmutabilityPolicySetting + + // Specifies the snapshot of the blob. + Snapshot *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 + + // Specifies the version ID of the blob. + VersionID *string +} + +// ClientSetLegalHoldOptions contains the optional parameters for the Client.SetLegalHold method. +type ClientSetLegalHoldOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specifies the snapshot of the blob. + Snapshot *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 + + // Specifies the version ID of the blob. + VersionID *string +} + +// ClientSetMetadataOptions contains the optional parameters for the Client.SetMetadata method. +type ClientSetMetadataOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The algorithm used to produce the encryption key hash. Must be provided if the encryption key is provided. + EncryptionAlgorithm *EncryptionAlgorithmType + + // Specifies the encryption key to use to encrypt the data provided in the request. + EncryptionKey *string + + // The SHA-256 hash of the provided encryption key. Must be provided if the encryption key is provided. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // The metadata headers. + Metadata map[string]*string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ClientSetTagsOptions contains the optional parameters for the Client.SetTags method. +type ClientSetTagsOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 + + // Specifies the transactional CRC64 hash for the body. + TransactionalContentCRC64 []byte + + // Specifies the transactional MD5 hash for the body. + TransactionalContentMD5 []byte + + // Specifies the version ID of the blob. + VersionID *string +} + +// ClientSetTierOptions contains the optional parameters for the Client.SetTier method. +type ClientSetTierOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // The priority of the rehydration operation. + RehydratePriority *RehydratePriority + + // Specifies the snapshot of the blob. + Snapshot *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 + + // Specifies the version ID of the blob. + VersionID *string +} + +// ClientStartCopyFromURLOptions contains the optional parameters for the Client.StartCopyFromURL method. +type ClientStartCopyFromURLOptions struct { + // The blob tags. + BlobTagsString *string + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // The date-time that indicates the time at which the blob immutability policy will expire. + ImmutabilityPolicyExpiry *time.Time + + // Indicates the immutability policy mode of the blob. + ImmutabilityPolicyMode *ImmutabilityPolicySetting + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // Indicates whether the blob has a legal hold. + LegalHold *bool + + // The metadata headers. + Metadata map[string]*string + + // The priority of the rehydration operation. + RehydratePriority *RehydratePriority + + // Overrides the sealed state of the destination blob. + SealBlob *bool + + // Specify this value to operate only on a source blob with a matching Etag value. + SourceIfMatch *azcore.ETag + + // Specify this value to operate only on a source blob if it has been modified since the specified date-time. + SourceIfModifiedSince *time.Time + + // Specify this value to operate only on a source blob with a non-matching Etag value. + SourceIfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a source blob with matching tags. + SourceIfTags *string + + // Specify this header value to operate only on a blob if it has not been modified since the specified date-time. + SourceIfUnmodifiedSince *time.Time + + // The tier to be set on the blob. + Tier *AccessTier + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ClientUndeleteOptions contains the optional parameters for the Client.Undelete method. +type ClientUndeleteOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ContainerClientAcquireLeaseOptions contains the optional parameters for the ContainerClient.AcquireLease method. +type ContainerClientAcquireLeaseOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // The proposed lease ID for the lease. + ProposedLeaseID *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ContainerClientBreakLeaseOptions contains the optional parameters for the ContainerClient.BreakLease method. +type ContainerClientBreakLeaseOptions struct { + // Proposed duration the lease should continue before it is broken, in seconds, between 0 and 60. This break period is only + // used if it is shorter than the time remaining on the lease. If longer, the time remaining on the lease is used. + BreakPeriod *int32 + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ContainerClientChangeLeaseOptions contains the optional parameters for the ContainerClient.ChangeLease method. +type ContainerClientChangeLeaseOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ContainerClientCreateOptions contains the optional parameters for the ContainerClient.Create method. +type ContainerClientCreateOptions struct { + // The public access setting for the container. + Access *PublicAccessType + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specifies the default encryption scope to set on the container and use for all future requests. + DefaultEncryptionScope *string + + // The metadata headers. + Metadata map[string]*string + + // Whether to prevent encryption scope override. + PreventEncryptionScopeOverride *bool + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ContainerClientDeleteOptions contains the optional parameters for the ContainerClient.Delete method. +type ContainerClientDeleteOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ContainerClientFilterBlobsOptions contains the optional parameters for the ContainerClient.FilterBlobs method. +type ContainerClientFilterBlobsOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify to include additional, optional information. + Include []FilterBlobsIncludeItem + + // An opaque string value that identifies the portion of the result set to return with this operation. + Marker *string + + // Specifies the maximum number of resources to return. If the request does not specify maxresults, or specifies a value greater + // than 5000, the server will return up to 5000 items. + Maxresults *int32 + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ContainerClientGetAccessPolicyOptions contains the optional parameters for the ContainerClient.GetAccessPolicy method. +type ContainerClientGetAccessPolicyOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ContainerClientGetAccountInfoOptions contains the optional parameters for the ContainerClient.GetAccountInfo method. +type ContainerClientGetAccountInfoOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ContainerClientGetPropertiesOptions contains the optional parameters for the ContainerClient.GetProperties method. +type ContainerClientGetPropertiesOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ContainerClientListBlobFlatSegmentOptions contains the optional parameters for the ContainerClient.ListBlobFlatSegment +// method. +type ContainerClientListBlobFlatSegmentOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify to include additional, optional information. + Include []ListBlobsIncludeItem + + // An opaque string value that identifies the portion of the result set to return with this operation. + Marker *string + + // Specifies the maximum number of resources to return. If the request does not specify maxresults, or specifies a value greater + // than 5000, the server will return up to 5000 items. + Maxresults *int32 + + // Filters the results to return only resources whose name begins with the specified prefix. + Prefix *string + + // Specifies the relative path to list paths from. For non-recursive list, only one entity level is supported; for recursive + // list, multiple entity levels are supported. (Inclusive) + StartFrom *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ContainerClientListBlobHierarchySegmentOptions contains the optional parameters for the ContainerClient.NewListBlobHierarchySegmentPager +// method. +type ContainerClientListBlobHierarchySegmentOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify to include additional, optional information. + Include []ListBlobsIncludeItem + + // An opaque string value that identifies the portion of the result set to return with this operation. + Marker *string + + // Specifies the maximum number of resources to return. If the request does not specify maxresults, or specifies a value greater + // than 5000, the server will return up to 5000 items. + Maxresults *int32 + + // Filters the results to return only resources whose name begins with the specified prefix. + Prefix *string + + // Specifies the relative path to list paths from. For non-recursive list, only one entity level is supported; for recursive + // list, multiple entity levels are supported. (Inclusive) + StartFrom *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ContainerClientReleaseLeaseOptions contains the optional parameters for the ContainerClient.ReleaseLease method. +type ContainerClientReleaseLeaseOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ContainerClientRenameOptions contains the optional parameters for the ContainerClient.Rename method. +type ContainerClientRenameOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // A lease ID for the source path. If specified, the source path must have an active lease and the lease ID must match. + SourceLeaseID *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ContainerClientRenewLeaseOptions contains the optional parameters for the ContainerClient.RenewLease method. +type ContainerClientRenewLeaseOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ContainerClientRestoreOptions contains the optional parameters for the ContainerClient.Restore method. +type ContainerClientRestoreOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specifies the name of the deleted container to restore. + DeletedContainerName *string + + // Specifies the version of the deleted container to restore. + DeletedContainerVersion *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ContainerClientSetAccessPolicyOptions contains the optional parameters for the ContainerClient.SetAccessPolicy method. +type ContainerClientSetAccessPolicyOptions struct { + // The public access setting for the container. + Access *PublicAccessType + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ContainerClientSetMetadataOptions contains the optional parameters for the ContainerClient.SetMetadata method. +type ContainerClientSetMetadataOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // The metadata headers. + Metadata map[string]*string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ContainerClientSubmitBatchOptions contains the optional parameters for the ContainerClient.SubmitBatch method. +type ContainerClientSubmitBatchOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// PageBlobClientClearPagesOptions contains the optional parameters for the PageBlobClient.ClearPages method. +type PageBlobClientClearPagesOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The algorithm used to produce the encryption key hash. Must be provided if the encryption key is provided. + EncryptionAlgorithm *EncryptionAlgorithmType + + // Specifies the encryption key to use to encrypt the data provided in the request. + EncryptionKey *string + + // The SHA-256 hash of the provided encryption key. Must be provided if the encryption key is provided. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has the specified sequence number. + IfSequenceNumberEqualTo *int64 + + // Specify this value to operate only on a blob if it has a sequence number less than the specified. + IfSequenceNumberLessThan *int64 + + // Specify this value to operate only on a blob if it has a sequence number less than or equal to the specified. + IfSequenceNumberLessThanOrEqualTo *int64 + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// PageBlobClientCopyIncrementalOptions contains the optional parameters for the PageBlobClient.CopyIncremental method. +type PageBlobClientCopyIncrementalOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// PageBlobClientCreateOptions contains the optional parameters for the PageBlobClient.Create method. +type PageBlobClientCreateOptions struct { + // Specifies the blob's Cache-Control. If specified, this property is stored with the blob and returned with a read request. + BlobCacheControl *string + + // Specifies the blob's Content-Disposition. If specified, this property is stored with the blob and returned with a read + // request. + BlobContentDisposition *string + + // Specifies the blob's Content-Encoding. If specified, this property is stored with the blob and returned with a read request. + BlobContentEncoding *string + + // Specifies the blob's Content-Language. If specified, this property is stored with the blob and returned with a read request. + BlobContentLanguage *string + + // The MD5 hash of the blob content that is stored as a property on the blob. Note: This hash is not validated. + BlobContentMD5 []byte + + // Specifies the blob's Content-Type. If specified, this property is stored with the blob and returned with a read request. + BlobContentType *string + + // A value that can be used to track the request. The value of the sequence number must be between 0 and 2^63 - 1. + BlobSequenceNumber *int64 + + // The blob tags. + BlobTagsString *string + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The algorithm used to produce the encryption key hash. Must be provided if the encryption key is provided. + EncryptionAlgorithm *EncryptionAlgorithmType + + // Specifies the encryption key to use to encrypt the data provided in the request. + EncryptionKey *string + + // The SHA-256 hash of the provided encryption key. Must be provided if the encryption key is provided. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // The date-time that indicates the time at which the blob immutability policy will expire. + ImmutabilityPolicyExpiry *time.Time + + // Indicates the immutability policy mode of the blob. + ImmutabilityPolicyMode *ImmutabilityPolicySetting + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // Indicates whether the blob has a legal hold. + LegalHold *bool + + // The metadata headers. + Metadata map[string]*string + + // Indicates the tier to be set on the page blob. + Tier *PremiumPageBlobAccessTier + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// PageBlobClientGetPageRangesDiffOptions contains the optional parameters for the PageBlobClient.GetPageRangesDiff method. +type PageBlobClientGetPageRangesDiffOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // An opaque string value that identifies the portion of the result set to return with this operation. + Marker *string + + // Specifies the maximum number of resources to return. If the request does not specify maxresults, or specifies a value greater + // than 5000, the server will return up to 5000 items. + Maxresults *int32 + + // Specifies the previous snapshot URL to be compared in the diff. + PrevSnapshotURL *string + + // Specifies the previous snapshot to be compared in the diff. + Prevsnapshot *string + + // Specifies the range of the blob to operate on. + Range *string + + // Specifies the snapshot of the blob. + Snapshot *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// PageBlobClientGetPageRangesOptions contains the optional parameters for the PageBlobClient.GetPageRanges method. +type PageBlobClientGetPageRangesOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // An opaque string value that identifies the portion of the result set to return with this operation. + Marker *string + + // Specifies the maximum number of resources to return. If the request does not specify maxresults, or specifies a value greater + // than 5000, the server will return up to 5000 items. + Maxresults *int32 + + // Specifies the range of the blob to operate on. + Range *string + + // Specifies the snapshot of the blob. + Snapshot *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// PageBlobClientResizeOptions contains the optional parameters for the PageBlobClient.Resize method. +type PageBlobClientResizeOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The algorithm used to produce the encryption key hash. Must be provided if the encryption key is provided. + EncryptionAlgorithm *EncryptionAlgorithmType + + // Specifies the encryption key to use to encrypt the data provided in the request. + EncryptionKey *string + + // The SHA-256 hash of the provided encryption key. Must be provided if the encryption key is provided. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// PageBlobClientUpdateSequenceNumberOptions contains the optional parameters for the PageBlobClient.UpdateSequenceNumber +// method. +type PageBlobClientUpdateSequenceNumberOptions struct { + // A value that can be used to track the request. The value of the sequence number must be between 0 and 2^63 - 1. + BlobSequenceNumber *int64 + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// PageBlobClientUploadPagesFromURLOptions contains the optional parameters for the PageBlobClient.UploadPagesFromURL method. +type PageBlobClientUploadPagesFromURLOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Only the Bearer authorization scheme is supported, and the value must be a valid OAuth access token for the copy source. + CopySourceAuthorization *string + + // The algorithm used to produce the encryption key hash. Must be provided if the encryption key is provided. + EncryptionAlgorithm *EncryptionAlgorithmType + + // Specifies the encryption key to use to encrypt the data provided in the request. + EncryptionKey *string + + // The SHA-256 hash of the provided encryption key. Must be provided if the encryption key is provided. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Specifies the file request token intent. + FileRequestIntent *FileShareTokenIntent + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has the specified sequence number. + IfSequenceNumberEqualTo *int64 + + // Specify this value to operate only on a blob if it has a sequence number less than the specified. + IfSequenceNumberLessThan *int64 + + // Specify this value to operate only on a blob if it has a sequence number less than or equal to the specified. + IfSequenceNumberLessThanOrEqualTo *int64 + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // Specifies the CRC64 calculated for the range of bytes that must be read from the source. + SourceContentCRC64 []byte + + // Specifies the MD5 hash calculated for the range of bytes that must be read from the copy source. + SourceContentMD5 []byte + + // The algorithm used to produce the source encryption key hash. Must be provided if the source encryption key is provided. + SourceEncryptionAlgorithm *EncryptionAlgorithmType + + // Specifies the encryption key to use to decrypt the source data provided in the request. + SourceEncryptionKey *string + + // The SHA-256 hash of the provided source encryption key. Must be provided if the source encryption key is provided. + SourceEncryptionKeySHA256 *string + + // Specify this value to operate only on a source blob with a matching Etag value. + SourceIfMatch *azcore.ETag + + // Specify this value to operate only on a source blob if it has been modified since the specified date-time. + SourceIfModifiedSince *time.Time + + // Specify this value to operate only on a source blob with a non-matching Etag value. + SourceIfNoneMatch *azcore.ETag + + // Specify this header value to operate only on a blob if it has not been modified since the specified date-time. + SourceIfUnmodifiedSince *time.Time + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// PageBlobClientUploadPagesOptions contains the optional parameters for the PageBlobClient.UploadPages method. +type PageBlobClientUploadPagesOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The algorithm used to produce the encryption key hash. Must be provided if the encryption key is provided. + EncryptionAlgorithm *EncryptionAlgorithmType + + // Specifies the encryption key to use to encrypt the data provided in the request. + EncryptionKey *string + + // The SHA-256 hash of the provided encryption key. Must be provided if the encryption key is provided. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Specify this value to operate only on a blob with a matching Etag value. + IfMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has been modified since the specified date-time. + IfModifiedSince *time.Time + + // Specify this value to operate only on a blob with a non-matching Etag value. + IfNoneMatch *azcore.ETag + + // Specify this value to operate only on a blob if it has the specified sequence number. + IfSequenceNumberEqualTo *int64 + + // Specify this value to operate only on a blob if it has a sequence number less than the specified. + IfSequenceNumberLessThan *int64 + + // Specify this value to operate only on a blob if it has a sequence number less than or equal to the specified. + IfSequenceNumberLessThanOrEqualTo *int64 + + // Specifies a SQL-like where clause on blob tags to operate only on a blob with matching tags. + IfTags *string + + // Specify this value to operate only on a blob if it has not been modified since the specified date-time. + IfUnmodifiedSince *time.Time + + // If specified, the operation only succeeds if the resource's lease is active and matches this ID. + LeaseID *string + + // Required if the request body is a structured message. Specifies the message schema version and properties. + StructuredBodyType *string + + // Required if the request body is a structured message. Specifies the length of the blob/file content inside the message + // body. Will always be smaller than Content-Length. + StructuredContentLength *int64 + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 + + // Specifies the transactional CRC64 hash for the body. + TransactionalContentCRC64 []byte + + // Specifies the transactional MD5 hash for the body. + TransactionalContentMD5 []byte +} + +// ServiceClientFilterBlobsOptions contains the optional parameters for the ServiceClient.FilterBlobs method. +type ServiceClientFilterBlobsOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify to include additional, optional information. + Include []FilterBlobsIncludeItem + + // An opaque string value that identifies the portion of the result set to return with this operation. + Marker *string + + // Specifies the maximum number of resources to return. If the request does not specify maxresults, or specifies a value greater + // than 5000, the server will return up to 5000 items. + Maxresults *int32 + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ServiceClientGetAccountInfoOptions contains the optional parameters for the ServiceClient.GetAccountInfo method. +type ServiceClientGetAccountInfoOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ServiceClientGetPropertiesOptions contains the optional parameters for the ServiceClient.GetProperties method. +type ServiceClientGetPropertiesOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ServiceClientGetStatisticsOptions contains the optional parameters for the ServiceClient.GetStatistics method. +type ServiceClientGetStatisticsOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ServiceClientGetUserDelegationKeyOptions contains the optional parameters for the ServiceClient.GetUserDelegationKey method. +type ServiceClientGetUserDelegationKeyOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ServiceClientListContainersSegmentOptions contains the optional parameters for the ServiceClient.ListContainersSegment +// method. +type ServiceClientListContainersSegmentOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Specify to include additional, optional information. + Include []ListContainersIncludeType + + // An opaque string value that identifies the portion of the result set to return with this operation. + Marker *string + + // Specifies the maximum number of resources to return. If the request does not specify maxresults, or specifies a value greater + // than 5000, the server will return up to 5000 items. + Maxresults *int32 + + // Filters the results to return only resources whose name begins with the specified prefix. + Prefix *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ServiceClientSetPropertiesOptions contains the optional parameters for the ServiceClient.SetProperties method. +type ServiceClientSetPropertiesOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} + +// ServiceClientSubmitBatchOptions contains the optional parameters for the ServiceClient.SubmitBatch method. +type ServiceClientSubmitBatchOptions struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The timeout parameter is expressed in seconds. For more information, see Setting + // Timeouts for Blob Service Operations. + Timeout *int32 +} diff --git a/test/local/azblob/zz_pageblob_client.go b/test/local/azblob/zz_pageblob_client.go new file mode 100644 index 000000000000..83faa984fb74 --- /dev/null +++ b/test/local/azblob/zz_pageblob_client.go @@ -0,0 +1,1241 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azblob + +import ( + "context" + "encoding/base64" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "io" + "net/http" + "strconv" + "strings" + "time" +) + +// PageBlobClient contains the methods for the PageBlob group. +// Don't use this type directly, use a constructor function instead. +// +// Generated from API version 2026-06-06 +type PageBlobClient struct { + internal *azcore.Client + url string +} + +// ClearPages - Clears a range of pages from the specified page blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - rangeParam - Specifies the range of the blob to operate on. +// - options - PageBlobClientClearPagesOptions contains the optional parameters for the PageBlobClient.ClearPages method. +func (client *PageBlobClient) ClearPages(ctx context.Context, rangeParam string, options *PageBlobClientClearPagesOptions) (PageBlobClientClearPagesResponse, error) { + var err error + req, err := client.clearPagesCreateRequest(ctx, rangeParam, options) + if err != nil { + return PageBlobClientClearPagesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PageBlobClientClearPagesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return PageBlobClientClearPagesResponse{}, err + } + resp, err := client.clearPagesHandleResponse(httpResp) + return resp, err +} + +// clearPagesCreateRequest creates the ClearPages request. +func (client *PageBlobClient) clearPagesCreateRequest(ctx context.Context, rangeParam string, options *PageBlobClientClearPagesOptions) (*policy.Request, error) { + urlPath := "?comp=page" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Content-Length"] = []string{"0"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + req.Raw().Header["Range"] = []string{rangeParam} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.EncryptionAlgorithm != nil { + req.Raw().Header["x-ms-encryption-algorithm"] = []string{string(*options.EncryptionAlgorithm)} + } + if options != nil && options.EncryptionKey != nil { + req.Raw().Header["x-ms-encryption-key"] = []string{*options.EncryptionKey} + } + if options != nil && options.EncryptionKeySHA256 != nil { + req.Raw().Header["x-ms-encryption-key-sha256"] = []string{*options.EncryptionKeySHA256} + } + if options != nil && options.EncryptionScope != nil { + req.Raw().Header["x-ms-encryption-scope"] = []string{*options.EncryptionScope} + } + if options != nil && options.IfSequenceNumberEqualTo != nil { + req.Raw().Header["x-ms-if-sequence-number-eq"] = []string{strconv.FormatInt(*options.IfSequenceNumberEqualTo, 10)} + } + if options != nil && options.IfSequenceNumberLessThanOrEqualTo != nil { + req.Raw().Header["x-ms-if-sequence-number-le"] = []string{strconv.FormatInt(*options.IfSequenceNumberLessThanOrEqualTo, 10)} + } + if options != nil && options.IfSequenceNumberLessThan != nil { + req.Raw().Header["x-ms-if-sequence-number-lt"] = []string{strconv.FormatInt(*options.IfSequenceNumberLessThan, 10)} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + req.Raw().Header["x-ms-page-write"] = []string{"clear"} + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// clearPagesHandleResponse handles the ClearPages response. +func (client *PageBlobClient) clearPagesHandleResponse(resp *http.Response) (PageBlobClientClearPagesResponse, error) { + result := PageBlobClientClearPagesResponse{} + if val := resp.Header.Get("x-ms-blob-sequence-number"); val != "" { + blobSequenceNumber, err := strconv.ParseInt(val, 10, 64) + if err != nil { + return PageBlobClientClearPagesResponse{}, err + } + result.BlobSequenceNumber = &blobSequenceNumber + } + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("x-ms-content-crc64"); val != "" { + contentCRC64, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return PageBlobClientClearPagesResponse{}, err + } + result.ContentCRC64 = contentCRC64 + } + if val := resp.Header.Get("Content-MD5"); val != "" { + contentMD5, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return PageBlobClientClearPagesResponse{}, err + } + result.ContentMD5 = contentMD5 + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return PageBlobClientClearPagesResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return PageBlobClientClearPagesResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// CopyIncremental - Copies a snapshot of the source page blob to a destination page blob. The snapshot is copied such that +// only the differential changes between the previously copied snapshot are transferred to the destination. +// If the operation fails it returns an *azcore.ResponseError type. +// - copySource - Specifies the name of the source URL for the copy operation. The value should be URL-encoded as it would appear +// in a request URI. +// - options - PageBlobClientCopyIncrementalOptions contains the optional parameters for the PageBlobClient.CopyIncremental +// method. +func (client *PageBlobClient) CopyIncremental(ctx context.Context, copySource string, options *PageBlobClientCopyIncrementalOptions) (PageBlobClientCopyIncrementalResponse, error) { + var err error + req, err := client.copyIncrementalCreateRequest(ctx, copySource, options) + if err != nil { + return PageBlobClientCopyIncrementalResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PageBlobClientCopyIncrementalResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return PageBlobClientCopyIncrementalResponse{}, err + } + resp, err := client.copyIncrementalHandleResponse(httpResp) + return resp, err +} + +// copyIncrementalCreateRequest creates the CopyIncremental request. +func (client *PageBlobClient) copyIncrementalCreateRequest(ctx context.Context, copySource string, options *PageBlobClientCopyIncrementalOptions) (*policy.Request, error) { + urlPath := "?comp=incrementalcopy" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-copy-source"] = []string{copySource} + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// copyIncrementalHandleResponse handles the CopyIncremental response. +func (client *PageBlobClient) copyIncrementalHandleResponse(resp *http.Response) (PageBlobClientCopyIncrementalResponse, error) { + result := PageBlobClientCopyIncrementalResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("x-ms-copy-id"); val != "" { + result.CopyID = &val + } + if val := resp.Header.Get("x-ms-copy-status"); val != "" { + result.CopyStatus = (*CopyStatusType)(&val) + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return PageBlobClientCopyIncrementalResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return PageBlobClientCopyIncrementalResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// Create - Creates a new page blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - size - The maximum size for the page blob. Must be aligned to a 512-byte boundary. +// - options - PageBlobClientCreateOptions contains the optional parameters for the PageBlobClient.Create method. +func (client *PageBlobClient) Create(ctx context.Context, size int64, options *PageBlobClientCreateOptions) (PageBlobClientCreateResponse, error) { + var err error + req, err := client.createCreateRequest(ctx, size, options) + if err != nil { + return PageBlobClientCreateResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PageBlobClientCreateResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return PageBlobClientCreateResponse{}, err + } + resp, err := client.createHandleResponse(httpResp) + return resp, err +} + +// createCreateRequest creates the Create request. +func (client *PageBlobClient) createCreateRequest(ctx context.Context, size int64, options *PageBlobClientCreateOptions) (*policy.Request, error) { + req, err := runtime.NewRequest(ctx, http.MethodPut, client.url) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Content-Length"] = []string{"0"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.Tier != nil { + req.Raw().Header["x-ms-access-tier"] = []string{string(*options.Tier)} + } + if options != nil && options.BlobCacheControl != nil { + req.Raw().Header["x-ms-blob-cache-control"] = []string{*options.BlobCacheControl} + } + if options != nil && options.BlobContentDisposition != nil { + req.Raw().Header["x-ms-blob-content-disposition"] = []string{*options.BlobContentDisposition} + } + if options != nil && options.BlobContentEncoding != nil { + req.Raw().Header["x-ms-blob-content-encoding"] = []string{*options.BlobContentEncoding} + } + if options != nil && options.BlobContentLanguage != nil { + req.Raw().Header["x-ms-blob-content-language"] = []string{*options.BlobContentLanguage} + } + req.Raw().Header["x-ms-blob-content-length"] = []string{strconv.FormatInt(size, 10)} + if options != nil && options.BlobContentMD5 != nil { + req.Raw().Header["x-ms-blob-content-md5"] = []string{base64.StdEncoding.EncodeToString(options.BlobContentMD5)} + } + if options != nil && options.BlobContentType != nil { + req.Raw().Header["x-ms-blob-content-type"] = []string{*options.BlobContentType} + } + if options != nil && options.BlobSequenceNumber != nil { + req.Raw().Header["x-ms-blob-sequence-number"] = []string{strconv.FormatInt(*options.BlobSequenceNumber, 10)} + } + req.Raw().Header["x-ms-blob-type"] = []string{"PageBlob"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.EncryptionAlgorithm != nil { + req.Raw().Header["x-ms-encryption-algorithm"] = []string{string(*options.EncryptionAlgorithm)} + } + if options != nil && options.EncryptionKey != nil { + req.Raw().Header["x-ms-encryption-key"] = []string{*options.EncryptionKey} + } + if options != nil && options.EncryptionKeySHA256 != nil { + req.Raw().Header["x-ms-encryption-key-sha256"] = []string{*options.EncryptionKeySHA256} + } + if options != nil && options.EncryptionScope != nil { + req.Raw().Header["x-ms-encryption-scope"] = []string{*options.EncryptionScope} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + if options != nil && options.ImmutabilityPolicyMode != nil { + req.Raw().Header["x-ms-immutability-policy-mode"] = []string{string(*options.ImmutabilityPolicyMode)} + } + if options != nil && options.ImmutabilityPolicyExpiry != nil { + req.Raw().Header["x-ms-immutability-policy-until-date"] = []string{datetime.RFC7231(*options.ImmutabilityPolicyExpiry).String()} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + if options != nil && options.LegalHold != nil { + req.Raw().Header["x-ms-legal-hold"] = []string{strconv.FormatBool(*options.LegalHold)} + } + if options != nil && options.Metadata != nil { + for k, v := range options.Metadata { + if v != nil { + req.Raw().Header["x-ms-meta-"+k] = []string{*v} + } + } + } + if options != nil && options.BlobTagsString != nil { + req.Raw().Header["x-ms-tags"] = []string{*options.BlobTagsString} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// createHandleResponse handles the Create response. +func (client *PageBlobClient) createHandleResponse(resp *http.Response) (PageBlobClientCreateResponse, error) { + result := PageBlobClientCreateResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Content-MD5"); val != "" { + contentMD5, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return PageBlobClientCreateResponse{}, err + } + result.ContentMD5 = contentMD5 + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return PageBlobClientCreateResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("x-ms-encryption-key-sha256"); val != "" { + result.EncryptionKeySHA256 = &val + } + if val := resp.Header.Get("x-ms-encryption-scope"); val != "" { + result.EncryptionScope = &val + } + if val := resp.Header.Get("x-ms-request-server-encrypted"); val != "" { + isServerEncrypted, err := strconv.ParseBool(val) + if err != nil { + return PageBlobClientCreateResponse{}, err + } + result.IsServerEncrypted = &isServerEncrypted + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return PageBlobClientCreateResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + if val := resp.Header.Get("x-ms-version-id"); val != "" { + result.VersionID = &val + } + return result, nil +} + +// GetPageRanges - Returns the list of valid page ranges for the specified page blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - PageBlobClientGetPageRangesOptions contains the optional parameters for the PageBlobClient.GetPageRanges method. +func (client *PageBlobClient) GetPageRanges(ctx context.Context, options *PageBlobClientGetPageRangesOptions) (PageBlobClientGetPageRangesResponse, error) { + var err error + req, err := client.getPageRangesCreateRequest(ctx, options) + if err != nil { + return PageBlobClientGetPageRangesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PageBlobClientGetPageRangesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PageBlobClientGetPageRangesResponse{}, err + } + resp, err := client.getPageRangesHandleResponse(httpResp) + return resp, err +} + +// getPageRangesCreateRequest creates the GetPageRanges request. +func (client *PageBlobClient) getPageRangesCreateRequest(ctx context.Context, options *PageBlobClientGetPageRangesOptions) (*policy.Request, error) { + urlPath := "?comp=pagelist" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Marker != nil { + reqQP.Set("marker", *options.Marker) + } + if options != nil && options.Maxresults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.Maxresults), 10)) + } + if options != nil && options.Snapshot != nil { + reqQP.Set("snapshot", *options.Snapshot) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/xml"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.Range != nil { + req.Raw().Header["Range"] = []string{*options.Range} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// getPageRangesHandleResponse handles the GetPageRanges response. +func (client *PageBlobClient) getPageRangesHandleResponse(resp *http.Response) (PageBlobClientGetPageRangesResponse, error) { + result := PageBlobClientGetPageRangesResponse{} + if val := resp.Header.Get("x-ms-blob-content-length"); val != "" { + blobContentLength, err := strconv.ParseInt(val, 10, 64) + if err != nil { + return PageBlobClientGetPageRangesResponse{}, err + } + result.BlobContentLength = &blobContentLength + } + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return PageBlobClientGetPageRangesResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return PageBlobClientGetPageRangesResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + if err := runtime.UnmarshalAsXML(resp, &result.PageList); err != nil { + return PageBlobClientGetPageRangesResponse{}, err + } + return result, nil +} + +// GetPageRangesDiff - Returns the list of page ranges in the diff between the specified page blob and the specified previous +// snapshot. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - PageBlobClientGetPageRangesDiffOptions contains the optional parameters for the PageBlobClient.GetPageRangesDiff +// method. +func (client *PageBlobClient) GetPageRangesDiff(ctx context.Context, options *PageBlobClientGetPageRangesDiffOptions) (PageBlobClientGetPageRangesDiffResponse, error) { + var err error + req, err := client.getPageRangesDiffCreateRequest(ctx, options) + if err != nil { + return PageBlobClientGetPageRangesDiffResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PageBlobClientGetPageRangesDiffResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PageBlobClientGetPageRangesDiffResponse{}, err + } + resp, err := client.getPageRangesDiffHandleResponse(httpResp) + return resp, err +} + +// getPageRangesDiffCreateRequest creates the GetPageRangesDiff request. +func (client *PageBlobClient) getPageRangesDiffCreateRequest(ctx context.Context, options *PageBlobClientGetPageRangesDiffOptions) (*policy.Request, error) { + urlPath := "?comp=pagelist" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Marker != nil { + reqQP.Set("marker", *options.Marker) + } + if options != nil && options.Maxresults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.Maxresults), 10)) + } + if options != nil && options.Prevsnapshot != nil { + reqQP.Set("prevsnapshot", *options.Prevsnapshot) + } + if options != nil && options.Snapshot != nil { + reqQP.Set("snapshot", *options.Snapshot) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/xml"} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.Range != nil { + req.Raw().Header["Range"] = []string{*options.Range} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + if options != nil && options.PrevSnapshotURL != nil { + req.Raw().Header["x-ms-previous-snapshot-url"] = []string{*options.PrevSnapshotURL} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// getPageRangesDiffHandleResponse handles the GetPageRangesDiff response. +func (client *PageBlobClient) getPageRangesDiffHandleResponse(resp *http.Response) (PageBlobClientGetPageRangesDiffResponse, error) { + result := PageBlobClientGetPageRangesDiffResponse{} + if val := resp.Header.Get("x-ms-blob-content-length"); val != "" { + blobContentLength, err := strconv.ParseInt(val, 10, 64) + if err != nil { + return PageBlobClientGetPageRangesDiffResponse{}, err + } + result.BlobContentLength = &blobContentLength + } + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return PageBlobClientGetPageRangesDiffResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return PageBlobClientGetPageRangesDiffResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + if err := runtime.UnmarshalAsXML(resp, &result.PageList); err != nil { + return PageBlobClientGetPageRangesDiffResponse{}, err + } + return result, nil +} + +// Resize - Changes the size of the specified page blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - size - The maximum size for the page blob. Must be aligned to a 512-byte boundary. +// - options - PageBlobClientResizeOptions contains the optional parameters for the PageBlobClient.Resize method. +func (client *PageBlobClient) Resize(ctx context.Context, size int64, options *PageBlobClientResizeOptions) (PageBlobClientResizeResponse, error) { + var err error + req, err := client.resizeCreateRequest(ctx, size, options) + if err != nil { + return PageBlobClientResizeResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PageBlobClientResizeResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PageBlobClientResizeResponse{}, err + } + resp, err := client.resizeHandleResponse(httpResp) + return resp, err +} + +// resizeCreateRequest creates the Resize request. +func (client *PageBlobClient) resizeCreateRequest(ctx context.Context, size int64, options *PageBlobClientResizeOptions) (*policy.Request, error) { + urlPath := "?comp=properties" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + req.Raw().Header["x-ms-blob-content-length"] = []string{strconv.FormatInt(size, 10)} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.EncryptionAlgorithm != nil { + req.Raw().Header["x-ms-encryption-algorithm"] = []string{string(*options.EncryptionAlgorithm)} + } + if options != nil && options.EncryptionKey != nil { + req.Raw().Header["x-ms-encryption-key"] = []string{*options.EncryptionKey} + } + if options != nil && options.EncryptionKeySHA256 != nil { + req.Raw().Header["x-ms-encryption-key-sha256"] = []string{*options.EncryptionKeySHA256} + } + if options != nil && options.EncryptionScope != nil { + req.Raw().Header["x-ms-encryption-scope"] = []string{*options.EncryptionScope} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// resizeHandleResponse handles the Resize response. +func (client *PageBlobClient) resizeHandleResponse(resp *http.Response) (PageBlobClientResizeResponse, error) { + result := PageBlobClientResizeResponse{} + if val := resp.Header.Get("x-ms-blob-sequence-number"); val != "" { + blobSequenceNumber, err := strconv.ParseInt(val, 10, 64) + if err != nil { + return PageBlobClientResizeResponse{}, err + } + result.BlobSequenceNumber = &blobSequenceNumber + } + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return PageBlobClientResizeResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return PageBlobClientResizeResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// UpdateSequenceNumber - Updates the sequence number of the specified page blob. The operation will fail if the specified +// sequence number is less than the current sequence number of the blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - sequenceNumberAction - Required if the blob sequence number is provided. This property indicates how the service should +// modify the blob's sequence number. +// - options - PageBlobClientUpdateSequenceNumberOptions contains the optional parameters for the PageBlobClient.UpdateSequenceNumber +// method. +func (client *PageBlobClient) UpdateSequenceNumber(ctx context.Context, sequenceNumberAction SequenceNumberActionType, options *PageBlobClientUpdateSequenceNumberOptions) (PageBlobClientUpdateSequenceNumberResponse, error) { + var err error + req, err := client.updateSequenceNumberCreateRequest(ctx, sequenceNumberAction, options) + if err != nil { + return PageBlobClientUpdateSequenceNumberResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PageBlobClientUpdateSequenceNumberResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return PageBlobClientUpdateSequenceNumberResponse{}, err + } + resp, err := client.updateSequenceNumberHandleResponse(httpResp) + return resp, err +} + +// updateSequenceNumberCreateRequest creates the UpdateSequenceNumber request. +func (client *PageBlobClient) updateSequenceNumberCreateRequest(ctx context.Context, sequenceNumberAction SequenceNumberActionType, options *PageBlobClientUpdateSequenceNumberOptions) (*policy.Request, error) { + urlPath := "?comp=properties" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + if options != nil && options.BlobSequenceNumber != nil { + req.Raw().Header["x-ms-blob-sequence-number"] = []string{strconv.FormatInt(*options.BlobSequenceNumber, 10)} + } + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + req.Raw().Header["x-ms-sequence-number-action"] = []string{string(sequenceNumberAction)} + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// updateSequenceNumberHandleResponse handles the UpdateSequenceNumber response. +func (client *PageBlobClient) updateSequenceNumberHandleResponse(resp *http.Response) (PageBlobClientUpdateSequenceNumberResponse, error) { + result := PageBlobClientUpdateSequenceNumberResponse{} + if val := resp.Header.Get("x-ms-blob-sequence-number"); val != "" { + blobSequenceNumber, err := strconv.ParseInt(val, 10, 64) + if err != nil { + return PageBlobClientUpdateSequenceNumberResponse{}, err + } + result.BlobSequenceNumber = &blobSequenceNumber + } + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return PageBlobClientUpdateSequenceNumberResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return PageBlobClientUpdateSequenceNumberResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// UploadPages - Writes a range of pages to the specified page blob. +// If the operation fails it returns an *azcore.ResponseError type. +// - body - The body of the request. +// - contentLength - The length of the request. +// - rangeParam - Specifies the range of the blob to operate on. +// - options - PageBlobClientUploadPagesOptions contains the optional parameters for the PageBlobClient.UploadPages method. +func (client *PageBlobClient) UploadPages(ctx context.Context, body io.ReadSeekCloser, contentLength int64, rangeParam string, options *PageBlobClientUploadPagesOptions) (PageBlobClientUploadPagesResponse, error) { + var err error + req, err := client.uploadPagesCreateRequest(ctx, body, contentLength, rangeParam, options) + if err != nil { + return PageBlobClientUploadPagesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PageBlobClientUploadPagesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return PageBlobClientUploadPagesResponse{}, err + } + resp, err := client.uploadPagesHandleResponse(httpResp) + return resp, err +} + +// uploadPagesCreateRequest creates the UploadPages request. +func (client *PageBlobClient) uploadPagesCreateRequest(ctx context.Context, body io.ReadSeekCloser, contentLength int64, rangeParam string, options *PageBlobClientUploadPagesOptions) (*policy.Request, error) { + urlPath := "?comp=page" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Content-Length"] = []string{strconv.FormatInt(contentLength, 10)} + if options != nil && options.TransactionalContentMD5 != nil { + req.Raw().Header["Content-MD5"] = []string{base64.StdEncoding.EncodeToString(options.TransactionalContentMD5)} + } + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + req.Raw().Header["Range"] = []string{rangeParam} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + if options != nil && options.TransactionalContentCRC64 != nil { + req.Raw().Header["x-ms-content-crc64"] = []string{base64.StdEncoding.EncodeToString(options.TransactionalContentCRC64)} + } + if options != nil && options.EncryptionAlgorithm != nil { + req.Raw().Header["x-ms-encryption-algorithm"] = []string{string(*options.EncryptionAlgorithm)} + } + if options != nil && options.EncryptionKey != nil { + req.Raw().Header["x-ms-encryption-key"] = []string{*options.EncryptionKey} + } + if options != nil && options.EncryptionKeySHA256 != nil { + req.Raw().Header["x-ms-encryption-key-sha256"] = []string{*options.EncryptionKeySHA256} + } + if options != nil && options.EncryptionScope != nil { + req.Raw().Header["x-ms-encryption-scope"] = []string{*options.EncryptionScope} + } + if options != nil && options.IfSequenceNumberEqualTo != nil { + req.Raw().Header["x-ms-if-sequence-number-eq"] = []string{strconv.FormatInt(*options.IfSequenceNumberEqualTo, 10)} + } + if options != nil && options.IfSequenceNumberLessThanOrEqualTo != nil { + req.Raw().Header["x-ms-if-sequence-number-le"] = []string{strconv.FormatInt(*options.IfSequenceNumberLessThanOrEqualTo, 10)} + } + if options != nil && options.IfSequenceNumberLessThan != nil { + req.Raw().Header["x-ms-if-sequence-number-lt"] = []string{strconv.FormatInt(*options.IfSequenceNumberLessThan, 10)} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + req.Raw().Header["x-ms-page-write"] = []string{"update"} + if options != nil && options.StructuredBodyType != nil { + req.Raw().Header["x-ms-structured-body"] = []string{*options.StructuredBodyType} + } + if options != nil && options.StructuredContentLength != nil { + req.Raw().Header["x-ms-structured-content-length"] = []string{strconv.FormatInt(*options.StructuredContentLength, 10)} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + req.Raw().Header["Content-Type"] = []string{"application/octet-stream"} + if err := req.SetBody(body, "application/octet-stream"); err != nil { + return nil, err + } + return req, nil +} + +// uploadPagesHandleResponse handles the UploadPages response. +func (client *PageBlobClient) uploadPagesHandleResponse(resp *http.Response) (PageBlobClientUploadPagesResponse, error) { + result := PageBlobClientUploadPagesResponse{} + if val := resp.Header.Get("x-ms-blob-sequence-number"); val != "" { + blobSequenceNumber, err := strconv.ParseInt(val, 10, 64) + if err != nil { + return PageBlobClientUploadPagesResponse{}, err + } + result.BlobSequenceNumber = &blobSequenceNumber + } + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("x-ms-content-crc64"); val != "" { + contentCRC64, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return PageBlobClientUploadPagesResponse{}, err + } + result.ContentCRC64 = contentCRC64 + } + if val := resp.Header.Get("Content-MD5"); val != "" { + contentMD5, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return PageBlobClientUploadPagesResponse{}, err + } + result.ContentMD5 = contentMD5 + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return PageBlobClientUploadPagesResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("x-ms-encryption-key-sha256"); val != "" { + result.EncryptionKeySHA256 = &val + } + if val := resp.Header.Get("x-ms-encryption-scope"); val != "" { + result.EncryptionScope = &val + } + if val := resp.Header.Get("x-ms-request-server-encrypted"); val != "" { + isServerEncrypted, err := strconv.ParseBool(val) + if err != nil { + return PageBlobClientUploadPagesResponse{}, err + } + result.IsServerEncrypted = &isServerEncrypted + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return PageBlobClientUploadPagesResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-structured-body"); val != "" { + result.StructuredBodyType = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// UploadPagesFromURL - Writes a range of pages to the specified page blob where the contents are read from a URL. +// If the operation fails it returns an *azcore.ResponseError type. +// - sourceURL - Specifies the URL of the source. +// - sourceRange - Specifies the bytes of the source. +// - contentLength - The length of the request. +// - rangeParam - Specifies the range of the blob to operate on. +// - options - PageBlobClientUploadPagesFromURLOptions contains the optional parameters for the PageBlobClient.UploadPagesFromURL +// method. +func (client *PageBlobClient) UploadPagesFromURL(ctx context.Context, sourceURL string, sourceRange string, contentLength int64, rangeParam string, options *PageBlobClientUploadPagesFromURLOptions) (PageBlobClientUploadPagesFromURLResponse, error) { + var err error + req, err := client.uploadPagesFromURLCreateRequest(ctx, sourceURL, sourceRange, contentLength, rangeParam, options) + if err != nil { + return PageBlobClientUploadPagesFromURLResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PageBlobClientUploadPagesFromURLResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusCreated) { + err = runtime.NewResponseError(httpResp) + return PageBlobClientUploadPagesFromURLResponse{}, err + } + resp, err := client.uploadPagesFromURLHandleResponse(httpResp) + return resp, err +} + +// uploadPagesFromURLCreateRequest creates the UploadPagesFromURL request. +func (client *PageBlobClient) uploadPagesFromURLCreateRequest(ctx context.Context, sourceURL string, sourceRange string, contentLength int64, rangeParam string, options *PageBlobClientUploadPagesFromURLOptions) (*policy.Request, error) { + urlPath := "?comp=page" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Content-Length"] = []string{strconv.FormatInt(contentLength, 10)} + if options != nil && options.IfMatch != nil { + req.Raw().Header["If-Match"] = []string{string(*options.IfMatch)} + } + if options != nil && options.IfModifiedSince != nil { + req.Raw().Header["If-Modified-Since"] = []string{datetime.RFC7231(*options.IfModifiedSince).String()} + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header["If-None-Match"] = []string{string(*options.IfNoneMatch)} + } + if options != nil && options.IfUnmodifiedSince != nil { + req.Raw().Header["If-Unmodified-Since"] = []string{datetime.RFC7231(*options.IfUnmodifiedSince).String()} + } + req.Raw().Header["Range"] = []string{rangeParam} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-copy-source"] = []string{sourceURL} + if options != nil && options.CopySourceAuthorization != nil { + req.Raw().Header["x-ms-copy-source-authorization"] = []string{*options.CopySourceAuthorization} + } + if options != nil && options.EncryptionAlgorithm != nil { + req.Raw().Header["x-ms-encryption-algorithm"] = []string{string(*options.EncryptionAlgorithm)} + } + if options != nil && options.EncryptionKey != nil { + req.Raw().Header["x-ms-encryption-key"] = []string{*options.EncryptionKey} + } + if options != nil && options.EncryptionKeySHA256 != nil { + req.Raw().Header["x-ms-encryption-key-sha256"] = []string{*options.EncryptionKeySHA256} + } + if options != nil && options.EncryptionScope != nil { + req.Raw().Header["x-ms-encryption-scope"] = []string{*options.EncryptionScope} + } + if options != nil && options.FileRequestIntent != nil { + req.Raw().Header["x-ms-file-request-intent"] = []string{string(*options.FileRequestIntent)} + } + if options != nil && options.IfSequenceNumberEqualTo != nil { + req.Raw().Header["x-ms-if-sequence-number-eq"] = []string{strconv.FormatInt(*options.IfSequenceNumberEqualTo, 10)} + } + if options != nil && options.IfSequenceNumberLessThanOrEqualTo != nil { + req.Raw().Header["x-ms-if-sequence-number-le"] = []string{strconv.FormatInt(*options.IfSequenceNumberLessThanOrEqualTo, 10)} + } + if options != nil && options.IfSequenceNumberLessThan != nil { + req.Raw().Header["x-ms-if-sequence-number-lt"] = []string{strconv.FormatInt(*options.IfSequenceNumberLessThan, 10)} + } + if options != nil && options.IfTags != nil { + req.Raw().Header["x-ms-if-tags"] = []string{*options.IfTags} + } + if options != nil && options.LeaseID != nil { + req.Raw().Header["x-ms-lease-id"] = []string{*options.LeaseID} + } + req.Raw().Header["x-ms-page-write"] = []string{"update"} + if options != nil && options.SourceContentCRC64 != nil { + req.Raw().Header["x-ms-source-content-crc64"] = []string{base64.StdEncoding.EncodeToString(options.SourceContentCRC64)} + } + if options != nil && options.SourceContentMD5 != nil { + req.Raw().Header["x-ms-source-content-md5"] = []string{base64.StdEncoding.EncodeToString(options.SourceContentMD5)} + } + if options != nil && options.SourceEncryptionAlgorithm != nil { + req.Raw().Header["x-ms-source-encryption-algorithm"] = []string{string(*options.SourceEncryptionAlgorithm)} + } + if options != nil && options.SourceEncryptionKey != nil { + req.Raw().Header["x-ms-source-encryption-key"] = []string{*options.SourceEncryptionKey} + } + if options != nil && options.SourceEncryptionKeySHA256 != nil { + req.Raw().Header["x-ms-source-encryption-key-sha256"] = []string{*options.SourceEncryptionKeySHA256} + } + if options != nil && options.SourceIfMatch != nil { + req.Raw().Header["x-ms-source-if-match"] = []string{string(*options.SourceIfMatch)} + } + if options != nil && options.SourceIfModifiedSince != nil { + req.Raw().Header["x-ms-source-if-modified-since"] = []string{datetime.RFC7231(*options.SourceIfModifiedSince).String()} + } + if options != nil && options.SourceIfNoneMatch != nil { + req.Raw().Header["x-ms-source-if-none-match"] = []string{string(*options.SourceIfNoneMatch)} + } + if options != nil && options.SourceIfUnmodifiedSince != nil { + req.Raw().Header["x-ms-source-if-unmodified-since"] = []string{datetime.RFC7231(*options.SourceIfUnmodifiedSince).String()} + } + req.Raw().Header["x-ms-source-range"] = []string{sourceRange} + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// uploadPagesFromURLHandleResponse handles the UploadPagesFromURL response. +func (client *PageBlobClient) uploadPagesFromURLHandleResponse(resp *http.Response) (PageBlobClientUploadPagesFromURLResponse, error) { + result := PageBlobClientUploadPagesFromURLResponse{} + if val := resp.Header.Get("x-ms-blob-sequence-number"); val != "" { + blobSequenceNumber, err := strconv.ParseInt(val, 10, 64) + if err != nil { + return PageBlobClientUploadPagesFromURLResponse{}, err + } + result.BlobSequenceNumber = &blobSequenceNumber + } + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("x-ms-content-crc64"); val != "" { + contentCRC64, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return PageBlobClientUploadPagesFromURLResponse{}, err + } + result.ContentCRC64 = contentCRC64 + } + if val := resp.Header.Get("Content-MD5"); val != "" { + contentMD5, err := base64.StdEncoding.DecodeString(val) + if err != nil { + return PageBlobClientUploadPagesFromURLResponse{}, err + } + result.ContentMD5 = contentMD5 + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return PageBlobClientUploadPagesFromURLResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = (*azcore.ETag)(&val) + } + if val := resp.Header.Get("x-ms-encryption-key-sha256"); val != "" { + result.EncryptionKeySHA256 = &val + } + if val := resp.Header.Get("x-ms-encryption-scope"); val != "" { + result.EncryptionScope = &val + } + if val := resp.Header.Get("x-ms-request-server-encrypted"); val != "" { + isServerEncrypted, err := strconv.ParseBool(val) + if err != nil { + return PageBlobClientUploadPagesFromURLResponse{}, err + } + result.IsServerEncrypted = &isServerEncrypted + } + if val := resp.Header.Get("Last-Modified"); val != "" { + lastModified, err := time.Parse(time.RFC1123, val) + if err != nil { + return PageBlobClientUploadPagesFromURLResponse{}, err + } + result.LastModified = &lastModified + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} diff --git a/test/local/azblob/zz_responses.go b/test/local/azblob/zz_responses.go new file mode 100644 index 000000000000..d43af85046f8 --- /dev/null +++ b/test/local/azblob/zz_responses.go @@ -0,0 +1,2055 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azblob + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "io" + "time" +) + +// AppendBlobClientAppendBlockFromURLResponse contains the response from method AppendBlobClient.AppendBlockFromURL. +type AppendBlobClientAppendBlockFromURLResponse struct { + // The offset at which the block was committed, in bytes. + BlobAppendOffset *string + + // The number of committed blocks present in the blob. + BlobCommittedBlockCount *int32 + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The CRC64 hash of the content. + ContentCRC64 []byte + + // The blob content MD5 hash. Only returned if the full blob is read. + ContentMD5 []byte + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The SHA-256 hash of the provided encryption key. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Indicates whether the contents of the request are successfully encrypted. + IsServerEncrypted *bool + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// AppendBlobClientAppendBlockResponse contains the response from method AppendBlobClient.AppendBlock. +type AppendBlobClientAppendBlockResponse struct { + // The offset at which the block was committed, in bytes. + BlobAppendOffset *string + + // The number of committed blocks present in the blob. + BlobCommittedBlockCount *int32 + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The CRC64 hash of the content. + ContentCRC64 []byte + + // The blob content MD5 hash. Only returned if the full blob is read. + ContentMD5 []byte + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The SHA-256 hash of the provided encryption key. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Indicates whether the contents of the request are successfully encrypted. + IsServerEncrypted *bool + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Indicates if the response body contains a structured message and specifies the message schema version and properties. + StructuredBodyType *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// AppendBlobClientCreateResponse contains the response from method AppendBlobClient.Create. +type AppendBlobClientCreateResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The blob content MD5 hash. Only returned if the full blob is read. + ContentMD5 []byte + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The SHA-256 hash of the provided encryption key. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Indicates whether the contents of the request are successfully encrypted. + IsServerEncrypted *bool + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string + + // The version ID of the blob. + VersionID *string +} + +// AppendBlobClientSealResponse contains the response from method AppendBlobClient.Seal. +type AppendBlobClientSealResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // Whether the blob is sealed. + IsSealed *bool + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// BlobClientDownloadResponseInternal contains the response from method Client.Download. +type BlobClientDownloadResponseInternal struct { + // Indicates that the service supports requests for partial blob content. + AcceptRanges *string + + // The number of committed blocks present in the blob. + BlobCommittedBlockCount *int32 + + // MD5 hash of the full blob content only returned for ranged reads. This is the hash of the complete blob, not just the requested + // range. + BlobContentMD5 []byte + + // The current sequence number for a page blob. + BlobSequenceNumber *int64 + + // The type of the blob. + BlobType *Type + + // Body contains the streaming response. + Body io.ReadCloser + + // The Cache-Control of the blob. + CacheControl *string + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The CRC64 hash of the content. + ContentCRC64 []byte + + // The Content-Disposition of the blob. + ContentDisposition *string + + // The Content-Encoding of the blob. + ContentEncoding *string + + // The Content-Language of the blob. + ContentLanguage *string + + // The number of bytes present in the response body. + ContentLength *int64 + + // The blob content MD5 hash. Only returned if the full blob is read. + ContentMD5 []byte + + // Indicates the range of bytes returned in this response. + ContentRange *string + + // The content type of the body of the response. + ContentType *string + + // If this blob was the destination of a copy, specifies the completion time of the last attempted copy operation. + CopyCompletionTime *time.Time + + // Identifier for this copy operation. + CopyID *string + + // If this blob was the destination of a copy, specifies the number of bytes copied and the total bytes in the source. + CopyProgress *string + + // If this blob was the destination of a copy, specifies the source URL. + CopySource *string + + // Status of the copy operation. + CopyStatus *CopyStatusType + + // If this blob was the destination of a copy, specifies the cause of the copy operation failure. + CopyStatusDescription *string + + // The date-time the blob was created. + CreationTime *time.Time + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The SHA-256 hash of the provided encryption key. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // The date-time that indicates the time at which the blob immutability policy will expire. + ImmutabilityPolicyExpiresOn *time.Time + + // Indicates the immutability policy mode of the blob. + ImmutabilityPolicyMode *ImmutabilityPolicyMode + + // Indicates whether this is the current version of the blob. + IsCurrentVersion *bool + + // Whether the blob is sealed. + IsSealed *bool + + // Indicates whether the contents of the request are successfully encrypted. + IsServerEncrypted *bool + + // The date-time value that indicates the time at which the blob was last read or written. + LastAccessed *time.Time + + // The date-time that the resource was last modified. + LastModified *time.Time + + // Specifies the duration of the lease. + LeaseDuration *LeaseDurationType + + // The lease state of the blob. + LeaseState *LeaseStateType + + // The lease status of the blob. + LeaseStatus *LeaseStatusType + + // Indicates whether the blob has a legal hold. + LegalHold *bool + + // The metadata headers. + Metadata map[string]*string + + // The object replication policy ID. + ObjectReplicationPolicyID *string + + // The object replication status headers. + ObjectReplicationRules map[string]*string + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Indicates if the response body contains a structured message and specifies the message schema version and properties. + StructuredBodyType *string + + // The length of the blob/file content inside the message body when the response body is returned as a structured message. + // Will always be smaller than Content-Length. + StructuredContentLength *int64 + + // The number of tags associated with the blob. + TagCount *int64 + + // Specifies the version of the operation to use for this request. + Version *string + + // The version ID of the blob. + VersionID *string +} + +// BlockBlobClientCommitBlockListResponse contains the response from method BlockBlobClient.CommitBlockList. +type BlockBlobClientCommitBlockListResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The CRC64 hash of the content. + ContentCRC64 []byte + + // The blob content MD5 hash. Only returned if the full blob is read. + ContentMD5 []byte + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The SHA-256 hash of the provided encryption key. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Indicates whether the contents of the request are successfully encrypted. + IsServerEncrypted *bool + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string + + // The version ID of the blob. + VersionID *string +} + +// BlockBlobClientGetBlockListResponse contains the response from method BlockBlobClient.GetBlockList. +type BlockBlobClientGetBlockListResponse struct { + // Contains the committed and uncommitted blocks in a block blob. + BlockList + + // The size of the blob in bytes. + BlobContentLength *int64 + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// BlockBlobClientQueryResponse contains the response from method BlockBlobClient.Query. +type BlockBlobClientQueryResponse struct { + // Indicates that the service supports requests for partial blob content. + AcceptRanges *string + + // The number of committed blocks present in the blob. + BlobCommittedBlockCount *int32 + + // MD5 hash of the full blob content only returned for ranged reads. This is the hash of the complete blob, not just the requested + // range. + BlobContentMD5 []byte + + // The current sequence number for a page blob. + BlobSequenceNumber *int64 + + // The type of the blob. + BlobType *Type + + // Body contains the streaming response. + Body io.ReadCloser + + // The Cache-Control of the blob. + CacheControl *string + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The CRC64 hash of the content. + ContentCRC64 []byte + + // The Content-Disposition of the blob. + ContentDisposition *string + + // The Content-Encoding of the blob. + ContentEncoding *string + + // The Content-Language of the blob. + ContentLanguage *string + + // The number of bytes present in the response body. + ContentLength *int64 + + // The blob content MD5 hash. Only returned if the full blob is read. + ContentMD5 []byte + + // Indicates the range of bytes returned in this response. + ContentRange *string + + // Content-Type header + ContentType *string + + // If this blob was the destination of a copy, specifies the completion time of the last attempted copy operation. + CopyCompletionTime *time.Time + + // Identifier for this copy operation. + CopyID *string + + // If this blob was the destination of a copy, specifies the number of bytes copied and the total bytes in the source. + CopyProgress *string + + // If this blob was the destination of a copy, specifies the source URL. + CopySource *string + + // Status of the copy operation. + CopyStatus *CopyStatusType + + // If this blob was the destination of a copy, specifies the cause of the copy operation failure. + CopyStatusDescription *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The SHA-256 hash of the provided encryption key. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Indicates whether the contents of the request are successfully encrypted. + IsServerEncrypted *bool + + // The date-time that the resource was last modified. + LastModified *time.Time + + // Specifies the duration of the lease. + LeaseDuration *LeaseDurationType + + // The lease state of the blob. + LeaseState *LeaseStateType + + // The lease status of the blob. + LeaseStatus *LeaseStatusType + + // The metadata headers. + Metadata map[string]*string + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// BlockBlobClientStageBlockFromURLResponse contains the response from method BlockBlobClient.StageBlockFromURL. +type BlockBlobClientStageBlockFromURLResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The CRC64 hash of the content. + ContentCRC64 []byte + + // The blob content MD5 hash. Only returned if the full blob is read. + ContentMD5 []byte + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // The SHA-256 hash of the provided encryption key. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Indicates whether the contents of the request are successfully encrypted. + IsServerEncrypted *bool + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// BlockBlobClientStageBlockResponse contains the response from method BlockBlobClient.StageBlock. +type BlockBlobClientStageBlockResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The CRC64 hash of the content. + ContentCRC64 []byte + + // The blob content MD5 hash. Only returned if the full blob is read. + ContentMD5 []byte + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // The SHA-256 hash of the provided encryption key. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Indicates whether the contents of the request are successfully encrypted. + IsServerEncrypted *bool + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Indicates if the response body contains a structured message and specifies the message schema version and properties. + StructuredBodyType *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// BlockBlobClientUploadBlobFromURLResponse contains the response from method BlockBlobClient.UploadBlobFromURL. +type BlockBlobClientUploadBlobFromURLResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The blob content MD5 hash. Only returned if the full blob is read. + ContentMD5 []byte + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The SHA-256 hash of the provided encryption key. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Indicates whether the contents of the request are successfully encrypted. + IsServerEncrypted *bool + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string + + // The version ID of the blob. + VersionID *string +} + +// BlockBlobClientUploadResponse contains the response from method BlockBlobClient.Upload. +type BlockBlobClientUploadResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The CRC64 hash of the content. + ContentCRC64 []byte + + // The blob content MD5 hash. Only returned if the full blob is read. + ContentMD5 []byte + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The SHA-256 hash of the provided encryption key. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Indicates whether the contents of the request are successfully encrypted. + IsServerEncrypted *bool + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Indicates if the response body contains a structured message and specifies the message schema version and properties. + StructuredBodyType *string + + // Specifies the version of the operation to use for this request. + Version *string + + // The version ID of the blob. + VersionID *string +} + +// ClientAbortCopyFromURLResponse contains the response from method Client.AbortCopyFromURL. +type ClientAbortCopyFromURLResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ClientAcquireLeaseResponse contains the response from method Client.AcquireLease. +type ClientAcquireLeaseResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The date-time that the resource was last modified. + LastModified *time.Time + + // Uniquely identifies a blob's lease. + LeaseID *string + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ClientBreakLeaseResponse contains the response from method Client.BreakLease. +type ClientBreakLeaseResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The date-time that the resource was last modified. + LastModified *time.Time + + // Approximate time remaining in the lease period, in seconds. + LeaseTime *int32 + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ClientChangeLeaseResponse contains the response from method Client.ChangeLease. +type ClientChangeLeaseResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The date-time that the resource was last modified. + LastModified *time.Time + + // Uniquely identifies a blob's lease. + LeaseID *string + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ClientCopyFromURLResponse contains the response from method Client.CopyFromURL. +type ClientCopyFromURLResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The CRC64 hash of the content. + ContentCRC64 []byte + + // The blob content MD5 hash. Only returned if the full blob is read. + ContentMD5 []byte + + // Identifier for this copy operation. + CopyID *string + + // State of the copy operation. + CopyStatus *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string + + // The version ID of the blob. + VersionID *string +} + +// ClientCreateSnapshotResponse contains the response from method Client.CreateSnapshot. +type ClientCreateSnapshotResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // Indicates whether the contents of the request are successfully encrypted. + IsServerEncrypted *bool + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Uniquely identifies the snapshot and indicates the snapshot version. + Snapshot *string + + // Specifies the version of the operation to use for this request. + Version *string + + // The version ID of the blob. + VersionID *string +} + +// ClientDeleteImmutabilityPolicyResponse contains the response from method Client.DeleteImmutabilityPolicy. +type ClientDeleteImmutabilityPolicyResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ClientDeleteResponse contains the response from method Client.Delete. +type ClientDeleteResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ClientGetAccountInfoResponse contains the response from method Client.GetAccountInfo. +type ClientGetAccountInfoResponse struct { + // The account kind. + AccountKind *AccountKind + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // Indicates if the account has a hierarchical namespace enabled. + IsHierarchicalNamespaceEnabled *bool + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // The SKU name of the account. + SKUName *SKUName + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ClientGetPropertiesResponse contains the response from method Client.GetProperties. +type ClientGetPropertiesResponse struct { + // Indicates that the service supports requests for partial blob content. + AcceptRanges *string + + // The access tier of the blob. + AccessTier *string + + // The time the tier was changed on the blob. This is only returned if the tier on the blob was ever set. + AccessTierChangeTime *time.Time + + // Included if the access tier is inferred. + AccessTierInferred *bool + + // Included if the blob rehydrate operation is pending. Indicates the destination tier. + ArchiveStatus *string + + // The number of committed blocks present in the blob. + BlobCommittedBlockCount *int32 + + // The current sequence number for a page blob. + BlobSequenceNumber *int64 + + // The type of the blob. + BlobType *Type + + // The Cache-Control of the blob. + CacheControl *string + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The Content-Disposition of the blob. + ContentDisposition *string + + // The Content-Encoding of the blob. + ContentEncoding *string + + // The Content-Language of the blob. + ContentLanguage *string + + // The number of bytes present in the response body. + ContentLength *int64 + + // The blob content MD5 hash. Only returned if the full blob is read. + ContentMD5 []byte + + // Content-type. + ContentType *string + + // If this blob was the destination of a copy, specifies the completion time of the last attempted copy operation. + CopyCompletionTime *time.Time + + // Identifier for this copy operation. + CopyID *string + + // If this blob was the destination of a copy, specifies the number of bytes copied and the total bytes in the source. + CopyProgress *string + + // If this blob was the destination of a copy, specifies the source URL. + CopySource *string + + // Status of the copy operation. + CopyStatus *CopyStatusType + + // If this blob was the destination of a copy, specifies the cause of the copy operation failure. + CopyStatusDescription *string + + // The date-time the blob was created. + CreationTime *time.Time + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // Included if the blob is incremental copy blob or incremental copy snapshot, if x-ms-copy-status is success. + DestinationSnapshot *string + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The SHA-256 hash of the provided encryption key. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // The date-time this blob will expire. + ExpiresOn *time.Time + + // The date-time that indicates the time at which the blob immutability policy will expire. + ImmutabilityPolicyExpiresOn *time.Time + + // Indicates the immutability policy mode of the blob. + ImmutabilityPolicyMode *ImmutabilityPolicyMode + + // Indicates whether this is the current version of the blob. + IsCurrentVersion *bool + + // Included if the blob is incremental copy blob. + IsIncrementalCopy *bool + + // Whether the blob is sealed. + IsSealed *bool + + // Indicates whether the contents of the request are successfully encrypted. + IsServerEncrypted *bool + + // The date-time value that indicates the time at which the blob was last read or written. + LastAccessed *time.Time + + // The date-time that the resource was last modified. + LastModified *time.Time + + // Specifies the duration of the lease. + LeaseDuration *LeaseDurationType + + // The lease state of the blob. + LeaseState *LeaseStateType + + // The lease status of the blob. + LeaseStatus *LeaseStatusType + + // Indicates whether the blob has a legal hold. + LegalHold *bool + + // The metadata headers. + Metadata map[string]*string + + // The object replication policy ID. + ObjectReplicationPolicyID *string + + // The object replication status headers. + ObjectReplicationRules map[string]*string + + // The priority of the rehydration operation. + RehydratePriority *string + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // The underlying tier of a smart tier blob. Only returned if the blob is in Smart tier. + SmartAccessTier *string + + // Success indicates if the operation succeeded or failed. + Success bool + + // The number of tags associated with the blob. + TagCount *int64 + + // Specifies the version of the operation to use for this request. + Version *string + + // The version ID of the blob. + VersionID *string +} + +// ClientGetTagsResponse contains the response from method Client.GetTags. +type ClientGetTagsResponse struct { + // A list of blob tags. + Tags + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ClientReleaseLeaseResponse contains the response from method Client.ReleaseLease. +type ClientReleaseLeaseResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ClientRenewLeaseResponse contains the response from method Client.RenewLease. +type ClientRenewLeaseResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The date-time that the resource was last modified. + LastModified *time.Time + + // Uniquely identifies a blob's lease. + LeaseID *string + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ClientSetExpiryResponse contains the response from method Client.SetExpiry. +type ClientSetExpiryResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ClientSetHTTPHeadersResponse contains the response from method Client.SetHTTPHeaders. +type ClientSetHTTPHeadersResponse struct { + // The current sequence number for a page blob. + BlobSequenceNumber *int64 + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ClientSetImmutabilityPolicyResponse contains the response from method Client.SetImmutabilityPolicy. +type ClientSetImmutabilityPolicyResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // The date-time that indicates the time at which the blob immutability policy will expire. + ImmutabilityPolicyExpiry *time.Time + + // Indicates the immutability policy mode of the blob. + ImmutabilityPolicyMode *ImmutabilityPolicyMode + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ClientSetLegalHoldResponse contains the response from method Client.SetLegalHold. +type ClientSetLegalHoldResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // Indicates whether the blob has a legal hold. + LegalHold *bool + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ClientSetMetadataResponse contains the response from method Client.SetMetadata. +type ClientSetMetadataResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The SHA-256 hash of the provided encryption key. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Indicates whether the contents of the request are successfully encrypted. + IsServerEncrypted *bool + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string + + // The version ID of the blob. + VersionID *string +} + +// ClientSetTagsResponse contains the response from method Client.SetTags. +type ClientSetTagsResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ClientSetTierResponse contains the response from method Client.SetTier. +type ClientSetTierResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ClientStartCopyFromURLResponse contains the response from method Client.StartCopyFromURL. +type ClientStartCopyFromURLResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Identifier for this copy operation. + CopyID *string + + // Status of the copy operation. + CopyStatus *CopyStatusType + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string + + // The version ID of the blob. + VersionID *string +} + +// ClientUndeleteResponse contains the response from method Client.Undelete. +type ClientUndeleteResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ContainerClientAcquireLeaseResponse contains the response from method ContainerClient.AcquireLease. +type ContainerClientAcquireLeaseResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The date-time that the resource was last modified. + LastModified *time.Time + + // Uniquely identifies a blob's lease. + LeaseID *string + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ContainerClientBreakLeaseResponse contains the response from method ContainerClient.BreakLease. +type ContainerClientBreakLeaseResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The date-time that the resource was last modified. + LastModified *time.Time + + // Approximate time remaining in the lease period, in seconds. + LeaseTime *int32 + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ContainerClientChangeLeaseResponse contains the response from method ContainerClient.ChangeLease. +type ContainerClientChangeLeaseResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The date-time that the resource was last modified. + LastModified *time.Time + + // Uniquely identifies a blob's lease. + LeaseID *string + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ContainerClientCreateResponse contains the response from method ContainerClient.Create. +type ContainerClientCreateResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ContainerClientDeleteResponse contains the response from method ContainerClient.Delete. +type ContainerClientDeleteResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ContainerClientFilterBlobsResponse contains the response from method ContainerClient.FilterBlobs. +type ContainerClientFilterBlobsResponse struct { + // The result of the Find Blobs by Tags API. + FilterBlobSegment + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ContainerClientGetAccessPolicyResponse contains the response from method ContainerClient.GetAccessPolicy. +type ContainerClientGetAccessPolicyResponse struct { + // The public access setting for the container. + BlobPublicAccess *PublicAccessType + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + SignedIdentifiers []*SignedIdentifier `xml:"SignedIdentifier"` + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ContainerClientGetAccountInfoResponse contains the response from method ContainerClient.GetAccountInfo. +type ContainerClientGetAccountInfoResponse struct { + // The account kind. + AccountKind *AccountKind + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // Indicates if the account has a hierarchical namespace enabled. + IsHierarchicalNamespaceEnabled *bool + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // The SKU name of the account. + SKUName *SKUName + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ContainerClientGetPropertiesResponse contains the response from method ContainerClient.GetProperties. +type ContainerClientGetPropertiesResponse struct { + // The public access setting for the container. + BlobPublicAccess *PublicAccessType + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // The default encryption scope for the container. + DefaultEncryptionScope *string + + // Whether to prevent encryption scope override. + DenyEncryptionScopeOverride *bool + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // Indicates whether the container has an immutability policy set on it. + HasImmutabilityPolicy *bool + + // Indicates whether the container has a legal hold. + HasLegalHold *bool + + // Indicates whether version level WORM (Write Once, Read Many) is enabled on a container. + IsImmutableStorageWithVersioningEnabled *bool + + // The date-time that the resource was last modified. + LastModified *time.Time + + // Specifies the duration of the lease. + LeaseDuration *LeaseDurationType + + // The lease state of the blob. + LeaseState *LeaseStateType + + // The lease status of the blob. + LeaseStatus *LeaseStatusType + + // The metadata headers. + Metadata map[string]*string + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ContainerClientListBlobFlatSegmentResponse contains the response from method ContainerClient.ListBlobFlatSegment. +type ContainerClientListBlobFlatSegmentResponse struct { + // The result of the List Blobs API. + ListBlobsFlatSegmentResponse + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ContainerClientListBlobHierarchySegmentResponse contains the response from method ContainerClient.NewListBlobHierarchySegmentPager. +type ContainerClientListBlobHierarchySegmentResponse struct { + // The result of the List Blobs Hierarchical API. + ListBlobsHierarchySegmentResponse + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ContainerClientReleaseLeaseResponse contains the response from method ContainerClient.ReleaseLease. +type ContainerClientReleaseLeaseResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ContainerClientRenameResponse contains the response from method ContainerClient.Rename. +type ContainerClientRenameResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ContainerClientRenewLeaseResponse contains the response from method ContainerClient.RenewLease. +type ContainerClientRenewLeaseResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The date-time that the resource was last modified. + LastModified *time.Time + + // Uniquely identifies a blob's lease. + LeaseID *string + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ContainerClientRestoreResponse contains the response from method ContainerClient.Restore. +type ContainerClientRestoreResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ContainerClientSetAccessPolicyResponse contains the response from method ContainerClient.SetAccessPolicy. +type ContainerClientSetAccessPolicyResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ContainerClientSetMetadataResponse contains the response from method ContainerClient.SetMetadata. +type ContainerClientSetMetadataResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ContainerClientSubmitBatchResponse contains the response from method ContainerClient.SubmitBatch. +type ContainerClientSubmitBatchResponse struct { + // Body contains the streaming response. + Body io.ReadCloser + + // The value of this header must be multipart/mixed with a batch boundary. Example header value: multipart/mixed; boundary=batch_ + ContentType *string + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// PageBlobClientClearPagesResponse contains the response from method PageBlobClient.ClearPages. +type PageBlobClientClearPagesResponse struct { + // The current sequence number for a page blob. + BlobSequenceNumber *int64 + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The CRC64 hash of the content. + ContentCRC64 []byte + + // The blob content MD5 hash. Only returned if the full blob is read. + ContentMD5 []byte + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// PageBlobClientCopyIncrementalResponse contains the response from method PageBlobClient.CopyIncremental. +type PageBlobClientCopyIncrementalResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Identifier for this copy operation. + CopyID *string + + // Status of the copy operation. + CopyStatus *CopyStatusType + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// PageBlobClientCreateResponse contains the response from method PageBlobClient.Create. +type PageBlobClientCreateResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The blob content MD5 hash. Only returned if the full blob is read. + ContentMD5 []byte + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The SHA-256 hash of the provided encryption key. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Indicates whether the contents of the request are successfully encrypted. + IsServerEncrypted *bool + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string + + // The version ID of the blob. + VersionID *string +} + +// PageBlobClientGetPageRangesDiffResponse contains the response from method PageBlobClient.GetPageRangesDiff. +type PageBlobClientGetPageRangesDiffResponse struct { + // The result of the Get Pages API. + PageList + + // The size of the blob in bytes. + BlobContentLength *int64 + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// PageBlobClientGetPageRangesResponse contains the response from method PageBlobClient.GetPageRanges. +type PageBlobClientGetPageRangesResponse struct { + // The result of the Get Pages API. + PageList + + // The size of the blob in bytes. + BlobContentLength *int64 + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// PageBlobClientResizeResponse contains the response from method PageBlobClient.Resize. +type PageBlobClientResizeResponse struct { + // The current sequence number for a page blob. + BlobSequenceNumber *int64 + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// PageBlobClientUpdateSequenceNumberResponse contains the response from method PageBlobClient.UpdateSequenceNumber. +type PageBlobClientUpdateSequenceNumberResponse struct { + // The current sequence number for a page blob. + BlobSequenceNumber *int64 + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// PageBlobClientUploadPagesFromURLResponse contains the response from method PageBlobClient.UploadPagesFromURL. +type PageBlobClientUploadPagesFromURLResponse struct { + // The current sequence number for a page blob. + BlobSequenceNumber *int64 + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The CRC64 hash of the content. + ContentCRC64 []byte + + // The blob content MD5 hash. Only returned if the full blob is read. + ContentMD5 []byte + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The SHA-256 hash of the provided encryption key. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Indicates whether the contents of the request are successfully encrypted. + IsServerEncrypted *bool + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// PageBlobClientUploadPagesResponse contains the response from method PageBlobClient.UploadPages. +type PageBlobClientUploadPagesResponse struct { + // The current sequence number for a page blob. + BlobSequenceNumber *int64 + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The CRC64 hash of the content. + ContentCRC64 []byte + + // The blob content MD5 hash. Only returned if the full blob is read. + ContentMD5 []byte + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque identifier for the current state of the resource. + ETag *azcore.ETag + + // The SHA-256 hash of the provided encryption key. + EncryptionKeySHA256 *string + + // Specifies the encryption scope used to encrypt the data. + EncryptionScope *string + + // Indicates whether the contents of the request are successfully encrypted. + IsServerEncrypted *bool + + // The date-time that the resource was last modified. + LastModified *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Indicates if the response body contains a structured message and specifies the message schema version and properties. + StructuredBodyType *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ServiceClientFilterBlobsResponse contains the response from method ServiceClient.FilterBlobs. +type ServiceClientFilterBlobsResponse struct { + // The result of the Find Blobs by Tags API. + FilterBlobSegment + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ServiceClientGetAccountInfoResponse contains the response from method ServiceClient.GetAccountInfo. +type ServiceClientGetAccountInfoResponse struct { + // The account kind. + AccountKind *AccountKind + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // Indicates if the account has hierarchical namespace enabled. + IsHierarchicalNamespaceEnabled *bool + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // The SKU name of the account. + SKUName *SKUName + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ServiceClientGetPropertiesResponse contains the response from method ServiceClient.GetProperties. +type ServiceClientGetPropertiesResponse struct { + // The blob service properties. + StorageServiceProperties + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ServiceClientGetStatisticsResponse contains the response from method ServiceClient.GetStatistics. +type ServiceClientGetStatisticsResponse struct { + // Stats for the storage service. + StorageServiceStats + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ServiceClientGetUserDelegationKeyResponse contains the response from method ServiceClient.GetUserDelegationKey. +type ServiceClientGetUserDelegationKeyResponse struct { + // A user delegation key. + UserDelegationKey + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ServiceClientListContainersSegmentResponse contains the response from method ServiceClient.ListContainersSegment. +type ServiceClientListContainersSegmentResponse struct { + // The result of the List Containers API. + ListContainersSegmentResponse + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ServiceClientSetPropertiesResponse contains the response from method ServiceClient.SetProperties. +type ServiceClientSetPropertiesResponse struct { + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // Date-time value generated by the service that indicates the time at which the response was initiated. + Date *time.Time + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} + +// ServiceClientSubmitBatchResponse contains the response from method ServiceClient.SubmitBatch. +type ServiceClientSubmitBatchResponse struct { + // Body contains the streaming response. + Body io.ReadCloser + + // An opaque, globally-unique, client-generated string identifier for the request. + ClientRequestID *string + + // The media type of the body of the response. For batch requests, this is multipart/mixed; boundary=batchresponse_GUID + ContentType *string + + // An opaque, globally-unique, server-generated string identifier for the request. + RequestID *string + + // Specifies the version of the operation to use for this request. + Version *string +} diff --git a/test/local/azblob/zz_service_client.go b/test/local/azblob/zz_service_client.go new file mode 100644 index 000000000000..84f15761fd64 --- /dev/null +++ b/test/local/azblob/zz_service_client.go @@ -0,0 +1,601 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azblob + +import ( + "context" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "io" + "net/http" + "strconv" + "strings" + "time" +) + +// ServiceClient contains the methods for the Service group. +// Don't use this type directly, use a constructor function instead. +// +// Generated from API version 2026-06-06 +type ServiceClient struct { + internal *azcore.Client + url string +} + +// FilterBlobs - Lists blobs across all containers whose tags match a given search expression. +// If the operation fails it returns an *azcore.ResponseError type. +// - filterExpression - Filters the results to return only blobs whose tags match the specified expression. +// - options - ServiceClientFilterBlobsOptions contains the optional parameters for the ServiceClient.FilterBlobs method. +func (client *ServiceClient) FilterBlobs(ctx context.Context, filterExpression string, options *ServiceClientFilterBlobsOptions) (ServiceClientFilterBlobsResponse, error) { + var err error + req, err := client.filterBlobsCreateRequest(ctx, filterExpression, options) + if err != nil { + return ServiceClientFilterBlobsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServiceClientFilterBlobsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ServiceClientFilterBlobsResponse{}, err + } + resp, err := client.filterBlobsHandleResponse(httpResp) + return resp, err +} + +// filterBlobsCreateRequest creates the FilterBlobs request. +func (client *ServiceClient) filterBlobsCreateRequest(ctx context.Context, filterExpression string, options *ServiceClientFilterBlobsOptions) (*policy.Request, error) { + urlPath := "?comp=blobs" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Include != nil { + reqQP.Set("include", strings.Join(strings.Fields(strings.Trim(fmt.Sprint(options.Include), "[]")), ",")) + } + if options != nil && options.Marker != nil { + reqQP.Set("marker", *options.Marker) + } + if options != nil && options.Maxresults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.Maxresults), 10)) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + reqQP.Set("where", filterExpression) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/xml"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// filterBlobsHandleResponse handles the FilterBlobs response. +func (client *ServiceClient) filterBlobsHandleResponse(resp *http.Response) (ServiceClientFilterBlobsResponse, error) { + result := ServiceClientFilterBlobsResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ServiceClientFilterBlobsResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + if err := runtime.UnmarshalAsXML(resp, &result.FilterBlobSegment); err != nil { + return ServiceClientFilterBlobsResponse{}, err + } + return result, nil +} + +// GetAccountInfo - Returns information about the storage account. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ServiceClientGetAccountInfoOptions contains the optional parameters for the ServiceClient.GetAccountInfo method. +func (client *ServiceClient) GetAccountInfo(ctx context.Context, options *ServiceClientGetAccountInfoOptions) (ServiceClientGetAccountInfoResponse, error) { + var err error + req, err := client.getAccountInfoCreateRequest(ctx, options) + if err != nil { + return ServiceClientGetAccountInfoResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServiceClientGetAccountInfoResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ServiceClientGetAccountInfoResponse{}, err + } + resp, err := client.getAccountInfoHandleResponse(httpResp) + return resp, err +} + +// getAccountInfoCreateRequest creates the GetAccountInfo request. +func (client *ServiceClient) getAccountInfoCreateRequest(ctx context.Context, options *ServiceClientGetAccountInfoOptions) (*policy.Request, error) { + urlPath := "?restype=account&comp=properties" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// getAccountInfoHandleResponse handles the GetAccountInfo response. +func (client *ServiceClient) getAccountInfoHandleResponse(resp *http.Response) (ServiceClientGetAccountInfoResponse, error) { + result := ServiceClientGetAccountInfoResponse{} + if val := resp.Header.Get("x-ms-account-kind"); val != "" { + result.AccountKind = (*AccountKind)(&val) + } + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ServiceClientGetAccountInfoResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-is-hns-enabled"); val != "" { + isHierarchicalNamespaceEnabled, err := strconv.ParseBool(val) + if err != nil { + return ServiceClientGetAccountInfoResponse{}, err + } + result.IsHierarchicalNamespaceEnabled = &isHierarchicalNamespaceEnabled + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-sku-name"); val != "" { + result.SKUName = (*SKUName)(&val) + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// GetProperties - Retrieves properties of a storage account's Blob service, including properties for Storage Analytics and +// CORS (Cross-Origin Resource Sharing) rules. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ServiceClientGetPropertiesOptions contains the optional parameters for the ServiceClient.GetProperties method. +func (client *ServiceClient) GetProperties(ctx context.Context, options *ServiceClientGetPropertiesOptions) (ServiceClientGetPropertiesResponse, error) { + var err error + req, err := client.getPropertiesCreateRequest(ctx, options) + if err != nil { + return ServiceClientGetPropertiesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServiceClientGetPropertiesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ServiceClientGetPropertiesResponse{}, err + } + resp, err := client.getPropertiesHandleResponse(httpResp) + return resp, err +} + +// getPropertiesCreateRequest creates the GetProperties request. +func (client *ServiceClient) getPropertiesCreateRequest(ctx context.Context, options *ServiceClientGetPropertiesOptions) (*policy.Request, error) { + urlPath := "?restype=service&comp=properties" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/xml"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// getPropertiesHandleResponse handles the GetProperties response. +func (client *ServiceClient) getPropertiesHandleResponse(resp *http.Response) (ServiceClientGetPropertiesResponse, error) { + result := ServiceClientGetPropertiesResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ServiceClientGetPropertiesResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + if err := runtime.UnmarshalAsXML(resp, &result.StorageServiceProperties); err != nil { + return ServiceClientGetPropertiesResponse{}, err + } + return result, nil +} + +// GetStatistics - Retrieves statistics related to replication for the Blob service. It is only available on the secondary +// location endpoint when read-access geo-redundant replication is enabled for the storage account. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ServiceClientGetStatisticsOptions contains the optional parameters for the ServiceClient.GetStatistics method. +func (client *ServiceClient) GetStatistics(ctx context.Context, options *ServiceClientGetStatisticsOptions) (ServiceClientGetStatisticsResponse, error) { + var err error + req, err := client.getStatisticsCreateRequest(ctx, options) + if err != nil { + return ServiceClientGetStatisticsResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServiceClientGetStatisticsResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ServiceClientGetStatisticsResponse{}, err + } + resp, err := client.getStatisticsHandleResponse(httpResp) + return resp, err +} + +// getStatisticsCreateRequest creates the GetStatistics request. +func (client *ServiceClient) getStatisticsCreateRequest(ctx context.Context, options *ServiceClientGetStatisticsOptions) (*policy.Request, error) { + urlPath := "?restype=service&comp=stats" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/xml"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// getStatisticsHandleResponse handles the GetStatistics response. +func (client *ServiceClient) getStatisticsHandleResponse(resp *http.Response) (ServiceClientGetStatisticsResponse, error) { + result := ServiceClientGetStatisticsResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ServiceClientGetStatisticsResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + if err := runtime.UnmarshalAsXML(resp, &result.StorageServiceStats); err != nil { + return ServiceClientGetStatisticsResponse{}, err + } + return result, nil +} + +// GetUserDelegationKey - Retrieves a user delegation key for the Blob service. This is only a valid operation when using +// bearer token authentication. +// If the operation fails it returns an *azcore.ResponseError type. +// - keyInfo - Key information provided in the request. +// - options - ServiceClientGetUserDelegationKeyOptions contains the optional parameters for the ServiceClient.GetUserDelegationKey +// method. +func (client *ServiceClient) GetUserDelegationKey(ctx context.Context, keyInfo KeyInfo, options *ServiceClientGetUserDelegationKeyOptions) (ServiceClientGetUserDelegationKeyResponse, error) { + var err error + req, err := client.getUserDelegationKeyCreateRequest(ctx, keyInfo, options) + if err != nil { + return ServiceClientGetUserDelegationKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServiceClientGetUserDelegationKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ServiceClientGetUserDelegationKeyResponse{}, err + } + resp, err := client.getUserDelegationKeyHandleResponse(httpResp) + return resp, err +} + +// getUserDelegationKeyCreateRequest creates the GetUserDelegationKey request. +func (client *ServiceClient) getUserDelegationKeyCreateRequest(ctx context.Context, keyInfo KeyInfo, options *ServiceClientGetUserDelegationKeyOptions) (*policy.Request, error) { + urlPath := "?restype=service&comp=userdelegationkey" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/xml"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, keyInfo); err != nil { + return nil, err + } + return req, nil +} + +// getUserDelegationKeyHandleResponse handles the GetUserDelegationKey response. +func (client *ServiceClient) getUserDelegationKeyHandleResponse(resp *http.Response) (ServiceClientGetUserDelegationKeyResponse, error) { + result := ServiceClientGetUserDelegationKeyResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ServiceClientGetUserDelegationKeyResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + if err := runtime.UnmarshalAsXML(resp, &result.UserDelegationKey); err != nil { + return ServiceClientGetUserDelegationKeyResponse{}, err + } + return result, nil +} + +// ListContainersSegment - Returns a list of the containers in the specified account. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ServiceClientListContainersSegmentOptions contains the optional parameters for the ServiceClient.ListContainersSegment +// method. +func (client *ServiceClient) ListContainersSegment(ctx context.Context, options *ServiceClientListContainersSegmentOptions) (ServiceClientListContainersSegmentResponse, error) { + var err error + req, err := client.listContainersSegmentCreateRequest(ctx, options) + if err != nil { + return ServiceClientListContainersSegmentResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServiceClientListContainersSegmentResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ServiceClientListContainersSegmentResponse{}, err + } + resp, err := client.listContainersSegmentHandleResponse(httpResp) + return resp, err +} + +// listContainersSegmentCreateRequest creates the ListContainersSegment request. +func (client *ServiceClient) listContainersSegmentCreateRequest(ctx context.Context, options *ServiceClientListContainersSegmentOptions) (*policy.Request, error) { + urlPath := "?comp=list" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Include != nil { + reqQP.Set("include", strings.Join(strings.Fields(strings.Trim(fmt.Sprint(options.Include), "[]")), ",")) + } + if options != nil && options.Marker != nil { + reqQP.Set("marker", *options.Marker) + } + if options != nil && options.Maxresults != nil { + reqQP.Set("maxresults", strconv.FormatInt(int64(*options.Maxresults), 10)) + } + if options != nil && options.Prefix != nil { + reqQP.Set("prefix", *options.Prefix) + } + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/xml"} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + return req, nil +} + +// listContainersSegmentHandleResponse handles the ListContainersSegment response. +func (client *ServiceClient) listContainersSegmentHandleResponse(resp *http.Response) (ServiceClientListContainersSegmentResponse, error) { + result := ServiceClientListContainersSegmentResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ServiceClientListContainersSegmentResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + if err := runtime.UnmarshalAsXML(resp, &result.ListContainersSegmentResponse); err != nil { + return ServiceClientListContainersSegmentResponse{}, err + } + return result, nil +} + +// SetProperties - Sets properties for a storage account's Blob service endpoint, including properties for Storage Analytics +// and CORS (Cross-Origin Resource Sharing) rules. +// If the operation fails it returns an *azcore.ResponseError type. +// - storageServiceProperties - The storage service properties to set. +// - options - ServiceClientSetPropertiesOptions contains the optional parameters for the ServiceClient.SetProperties method. +func (client *ServiceClient) SetProperties(ctx context.Context, storageServiceProperties StorageServiceProperties, options *ServiceClientSetPropertiesOptions) (ServiceClientSetPropertiesResponse, error) { + var err error + req, err := client.setPropertiesCreateRequest(ctx, storageServiceProperties, options) + if err != nil { + return ServiceClientSetPropertiesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServiceClientSetPropertiesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return ServiceClientSetPropertiesResponse{}, err + } + resp, err := client.setPropertiesHandleResponse(httpResp) + return resp, err +} + +// setPropertiesCreateRequest creates the SetProperties request. +func (client *ServiceClient) setPropertiesCreateRequest(ctx context.Context, storageServiceProperties StorageServiceProperties, options *ServiceClientSetPropertiesOptions) (*policy.Request, error) { + urlPath := "?restype=service&comp=properties" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + req.Raw().Header["Content-Type"] = []string{"application/xml"} + if err := runtime.MarshalAsXML(req, storageServiceProperties); err != nil { + return nil, err + } + return req, nil +} + +// setPropertiesHandleResponse handles the SetProperties response. +func (client *ServiceClient) setPropertiesHandleResponse(resp *http.Response) (ServiceClientSetPropertiesResponse, error) { + result := ServiceClientSetPropertiesResponse{} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Date"); val != "" { + date, err := time.Parse(time.RFC1123, val) + if err != nil { + return ServiceClientSetPropertiesResponse{}, err + } + result.Date = &date + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} + +// SubmitBatch - Allows multiple API calls to be embedded into a single HTTP request. +// If the operation fails it returns an *azcore.ResponseError type. +// - multipartContentType - The value of this header must be multipart/mixed with a batch boundary. Example header value: multipart/mixed; +// boundary=batch_ +// - contentLength - The length of the request. +// - body - The body of the request. +// - options - ServiceClientSubmitBatchOptions contains the optional parameters for the ServiceClient.SubmitBatch method. +func (client *ServiceClient) SubmitBatch(ctx context.Context, multipartContentType string, contentLength int64, body io.ReadSeekCloser, options *ServiceClientSubmitBatchOptions) (ServiceClientSubmitBatchResponse, error) { + var err error + req, err := client.submitBatchCreateRequest(ctx, multipartContentType, contentLength, body, options) + if err != nil { + return ServiceClientSubmitBatchResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ServiceClientSubmitBatchResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusAccepted) { + err = runtime.NewResponseError(httpResp) + return ServiceClientSubmitBatchResponse{}, err + } + resp, err := client.submitBatchHandleResponse(httpResp) + return resp, err +} + +// submitBatchCreateRequest creates the SubmitBatch request. +func (client *ServiceClient) submitBatchCreateRequest(ctx context.Context, multipartContentType string, contentLength int64, body io.ReadSeekCloser, options *ServiceClientSubmitBatchOptions) (*policy.Request, error) { + urlPath := "?comp=batch" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.url, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Timeout != nil { + reqQP.Set("timeout", strconv.FormatInt(int64(*options.Timeout), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + runtime.SkipBodyDownload(req) + req.Raw().Header["Accept"] = []string{"multipart/mixed"} + req.Raw().Header["Content-Length"] = []string{strconv.FormatInt(contentLength, 10)} + if options != nil && options.ClientRequestID != nil { + req.Raw().Header["x-ms-client-request-id"] = []string{*options.ClientRequestID} + } + req.Raw().Header["x-ms-version"] = []string{version20260606} + if err := req.SetBody(body, multipartContentType); err != nil { + return nil, err + } + return req, nil +} + +// submitBatchHandleResponse handles the SubmitBatch response. +func (client *ServiceClient) submitBatchHandleResponse(resp *http.Response) (ServiceClientSubmitBatchResponse, error) { + result := ServiceClientSubmitBatchResponse{Body: resp.Body} + if val := resp.Header.Get("x-ms-client-request-id"); val != "" { + result.ClientRequestID = &val + } + if val := resp.Header.Get("Content-Type"); val != "" { + result.ContentType = &val + } + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.RequestID = &val + } + if val := resp.Header.Get("x-ms-version"); val != "" { + result.Version = &val + } + return result, nil +} diff --git a/test/local/azblob/zz_version.go b/test/local/azblob/zz_version.go new file mode 100644 index 000000000000..f88eec620e7d --- /dev/null +++ b/test/local/azblob/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package azblob + +const ( + moduleName = "azblob" + moduleVersion = "v0.1.0" +) diff --git a/test/local/azblob/zz_xml_helper.go b/test/local/azblob/zz_xml_helper.go new file mode 100644 index 000000000000..764bb9849a9e --- /dev/null +++ b/test/local/azblob/zz_xml_helper.go @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azblob + +import ( + "encoding/xml" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "io" + "strings" +) + +type additionalProperties map[string]*string + +// MarshalXML implements the xml.Marshaler interface for additionalProperties. +func (ap additionalProperties) MarshalXML(e *xml.Encoder, start xml.StartElement) error { + if err := e.EncodeToken(start); err != nil { + return err + } + for k, v := range ap { + err := e.EncodeToken(xml.StartElement{ + Name: xml.Name{ + Local: k, + }, + }) + if err != nil { + return err + } + if v != nil { + err = e.EncodeToken(xml.CharData(*v)) + if err != nil { + return err + } + } + err = e.EncodeToken(xml.EndElement{ + Name: xml.Name{ + Local: k, + }, + }) + if err != nil { + return err + } + } + return e.EncodeToken(xml.EndElement{ + Name: start.Name, + }) +} + +// UnmarshalXML implements the xml.Unmarshaler interface for additionalProperties. +func (ap *additionalProperties) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { + tokName := "" + tokValue := "" + for { + t, err := d.Token() + if errors.Is(err, io.EOF) { + break + } else if err != nil { + return err + } + switch tt := t.(type) { + case xml.StartElement: + tokName = strings.ToLower(tt.Name.Local) + tokValue = "" + case xml.CharData: + if tokName == "" { + continue + } + tokValue = string(tt) + case xml.EndElement: + if tokName == "" { + continue + } + if *ap == nil { + *ap = additionalProperties{} + } + (*ap)[tokName] = to.Ptr(tokValue) + tokName = "" + } + } + return nil +} diff --git a/test/local/azclientoption/LICENSE.txt b/test/local/azclientoption/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/local/azclientoption/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/local/azclientoption/fake/zz_internal.go b/test/local/azclientoption/fake/zz_internal.go new file mode 100644 index 000000000000..705f81eacafe --- /dev/null +++ b/test/local/azclientoption/fake/zz_internal.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import "net/http" + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} diff --git a/test/local/azclientoption/fake/zz_server.go b/test/local/azclientoption/fake/zz_server.go new file mode 100644 index 000000000000..edeb8b0de75e --- /dev/null +++ b/test/local/azclientoption/fake/zz_server.go @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "azclientoption" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "slices" +) + +// Server is a fake server for instances of the azclientoption.Client type. +type Server struct { + // CustomFieldName is the fake for method Client.CustomFieldName + // HTTP status codes to indicate success: http.StatusOK + CustomFieldName func(ctx context.Context, options *azclientoption.ClientCustomFieldNameOptions) (resp azfake.Responder[azclientoption.RenamedResponse], errResp azfake.ErrorResponder) + + // PreserveContentTypeHeader is the fake for method Client.PreserveContentTypeHeader + // HTTP status codes to indicate success: http.StatusOK + PreserveContentTypeHeader func(ctx context.Context, options *azclientoption.ClientPreserveContentTypeHeaderOptions) (resp azfake.Responder[azclientoption.ClientPreserveContentTypeHeaderResponse], errResp azfake.ErrorResponder) +} + +// NewServerTransport creates a new instance of ServerTransport with the provided implementation. +// The returned ServerTransport instance is connected to an instance of azclientoption.Client via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerTransport(srv *Server) *ServerTransport { + return &ServerTransport{srv: srv} +} + +// ServerTransport connects instances of azclientoption.Client to instances of Server. +// Don't use this type directly, use NewServerTransport instead. +type ServerTransport struct { + srv *Server +} + +// Do implements the policy.Transporter interface for ServerTransport. +func (s *ServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if serverTransportInterceptor != nil { + res.resp, res.err, intercepted = serverTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "Client.CustomFieldName": + res.resp, res.err = s.dispatchCustomFieldName(req) + case "Client.PreserveContentTypeHeader": + res.resp, res.err = s.dispatchPreserveContentTypeHeader(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ServerTransport) dispatchCustomFieldName(req *http.Request) (*http.Response, error) { + if s.srv.CustomFieldName == nil { + return nil, &nonRetriableError{errors.New("fake for method CustomFieldName not implemented")} + } + respr, errRespr := s.srv.CustomFieldName(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Users, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchPreserveContentTypeHeader(req *http.Request) (*http.Response, error) { + if s.srv.PreserveContentTypeHeader == nil { + return nil, &nonRetriableError{errors.New("fake for method PreserveContentTypeHeader not implemented")} + } + respr, errRespr := s.srv.PreserveContentTypeHeader(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).Value, req) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).ContentType; val != nil { + resp.Header.Set("content-type", "application/json") + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ServerTransport +var serverTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/azclientoption/go.mod b/test/local/azclientoption/go.mod new file mode 100644 index 000000000000..8f653314f47d --- /dev/null +++ b/test/local/azclientoption/go.mod @@ -0,0 +1,11 @@ +module azclientoption + +go 1.25.0 + +require github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect +) diff --git a/test/local/azclientoption/go.sum b/test/local/azclientoption/go.sum new file mode 100644 index 000000000000..3fdb64caf441 --- /dev/null +++ b/test/local/azclientoption/go.sum @@ -0,0 +1,16 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/local/azclientoption/testdata/_metadata.json b/test/local/azclientoption/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/local/azclientoption/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/local/azclientoption/zz_client.go b/test/local/azclientoption/zz_client.go new file mode 100644 index 000000000000..58f657e676c1 --- /dev/null +++ b/test/local/azclientoption/zz_client.go @@ -0,0 +1,137 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azclientoption + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// Client contains the methods for the service. +// Don't use this type directly, use NewClientWithNoCredential() instead. +type Client struct { + internal *azcore.Client + endpoint string +} + +// ClientOptions contains the optional values for creating a [Client]. +type ClientOptions struct { + azcore.ClientOptions +} + +// NewClientWithNoCredential creates a new instance of Client with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewClientWithNoCredential(endpoint string, options *ClientOptions) (*Client, error) { + if options == nil { + options = &ClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &Client{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// CustomFieldName - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientCustomFieldNameOptions contains the optional parameters for the Client.CustomFieldName method. +func (client *Client) CustomFieldName(ctx context.Context, options *ClientCustomFieldNameOptions) (RenamedResponse, error) { + var err error + const operationName = "Client.CustomFieldName" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.customFieldNameCreateRequest(ctx, options) + if err != nil { + return RenamedResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RenamedResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RenamedResponse{}, err + } + resp, err := client.customFieldNameHandleResponse(httpResp) + return resp, err +} + +// customFieldNameCreateRequest creates the CustomFieldName request. +func (client *Client) customFieldNameCreateRequest(ctx context.Context, _ *ClientCustomFieldNameOptions) (*policy.Request, error) { + urlPath := "/rename-monomorphic-field" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// customFieldNameHandleResponse handles the CustomFieldName response. +func (client *Client) customFieldNameHandleResponse(resp *http.Response) (RenamedResponse, error) { + result := RenamedResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.Users); err != nil { + return RenamedResponse{}, err + } + return result, nil +} + +// PreserveContentTypeHeader - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientPreserveContentTypeHeaderOptions contains the optional parameters for the Client.PreserveContentTypeHeader +// method. +func (client *Client) PreserveContentTypeHeader(ctx context.Context, options *ClientPreserveContentTypeHeaderOptions) (ClientPreserveContentTypeHeaderResponse, error) { + var err error + const operationName = "Client.PreserveContentTypeHeader" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.preserveContentTypeHeaderCreateRequest(ctx, options) + if err != nil { + return ClientPreserveContentTypeHeaderResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientPreserveContentTypeHeaderResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientPreserveContentTypeHeaderResponse{}, err + } + resp, err := client.preserveContentTypeHeaderHandleResponse(httpResp) + return resp, err +} + +// preserveContentTypeHeaderCreateRequest creates the PreserveContentTypeHeader request. +func (client *Client) preserveContentTypeHeaderCreateRequest(ctx context.Context, _ *ClientPreserveContentTypeHeaderOptions) (*policy.Request, error) { + urlPath := "/preserve-content-type-header" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// preserveContentTypeHeaderHandleResponse handles the PreserveContentTypeHeader response. +func (client *Client) preserveContentTypeHeaderHandleResponse(resp *http.Response) (ClientPreserveContentTypeHeaderResponse, error) { + result := ClientPreserveContentTypeHeaderResponse{} + if val := resp.Header.Get("content-type"); val != "" { + result.ContentType = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.Value); err != nil { + return ClientPreserveContentTypeHeaderResponse{}, err + } + return result, nil +} diff --git a/test/local/azclientoption/zz_models.go b/test/local/azclientoption/zz_models.go new file mode 100644 index 000000000000..ca33967b43b9 --- /dev/null +++ b/test/local/azclientoption/zz_models.go @@ -0,0 +1,13 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azclientoption + +type Person struct { + // REQUIRED + Age *int32 + + // REQUIRED + Name *string +} diff --git a/test/local/azclientoption/zz_options.go b/test/local/azclientoption/zz_options.go new file mode 100644 index 000000000000..2f04db17f8f1 --- /dev/null +++ b/test/local/azclientoption/zz_options.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azclientoption + +// ClientCustomFieldNameOptions contains the optional parameters for the Client.CustomFieldName method. +type ClientCustomFieldNameOptions struct { + // placeholder for future optional parameters +} + +// ClientPreserveContentTypeHeaderOptions contains the optional parameters for the Client.PreserveContentTypeHeader method. +type ClientPreserveContentTypeHeaderOptions struct { + // placeholder for future optional parameters +} diff --git a/test/local/azclientoption/zz_responses.go b/test/local/azclientoption/zz_responses.go new file mode 100644 index 000000000000..2756d1e3ab68 --- /dev/null +++ b/test/local/azclientoption/zz_responses.go @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azclientoption + +// ClientPreserveContentTypeHeaderResponse contains the response from method Client.PreserveContentTypeHeader. +type ClientPreserveContentTypeHeaderResponse struct { + ContentType *string + Value *string +} + +// RenamedResponse contains the response from method Client.CustomFieldName. +type RenamedResponse struct { + Users []*Person +} diff --git a/test/local/azclientoption/zz_version.go b/test/local/azclientoption/zz_version.go new file mode 100644 index 000000000000..429cd602f856 --- /dev/null +++ b/test/local/azclientoption/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package azclientoption + +const ( + moduleName = "azclientoption" + moduleVersion = "v0.1.0" +) diff --git a/test/local/azkeys/LICENSE.txt b/test/local/azkeys/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/local/azkeys/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/local/azkeys/custom_client.go b/test/local/azkeys/custom_client.go new file mode 100644 index 000000000000..1f4798ef85b5 --- /dev/null +++ b/test/local/azkeys/custom_client.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package azkeys + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +func NewClient(vaultURL string, options *azcore.ClientOptions) (*Client, error) { + client, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, options) + if err != nil { + return nil, err + } + return &Client{ + internal: client, + vaultBaseUrl: vaultURL, + }, nil +} diff --git a/test/local/azkeys/fake/zz_internal.go b/test/local/azkeys/fake/zz_internal.go new file mode 100644 index 000000000000..2f8b4aafab8d --- /dev/null +++ b/test/local/azkeys/fake/zz_internal.go @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func newTracker[T any]() *tracker[T] { + return &tracker[T]{ + items: map[string]*T{}, + } +} + +type tracker[T any] struct { + items map[string]*T + mu sync.Mutex +} + +func (p *tracker[T]) get(req *http.Request) *T { + p.mu.Lock() + defer p.mu.Unlock() + if item, ok := p.items[server.SanitizePagerPollerPath(req.URL.Path)]; ok { + return item + } + return nil +} + +func (p *tracker[T]) add(req *http.Request, item *T) { + p.mu.Lock() + defer p.mu.Unlock() + p.items[server.SanitizePagerPollerPath(req.URL.Path)] = item +} + +func (p *tracker[T]) remove(req *http.Request) { + p.mu.Lock() + defer p.mu.Unlock() + delete(p.items, server.SanitizePagerPollerPath(req.URL.Path)) +} diff --git a/test/local/azkeys/fake/zz_server.go b/test/local/azkeys/fake/zz_server.go new file mode 100644 index 000000000000..cd58adda1362 --- /dev/null +++ b/test/local/azkeys/fake/zz_server.go @@ -0,0 +1,1124 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "azkeys" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "net/http" + "net/url" + "regexp" + "slices" +) + +// Server is a fake server for instances of the azkeys.Client type. +type Server struct { + // BackupKey is the fake for method Client.BackupKey + // HTTP status codes to indicate success: http.StatusOK + BackupKey func(ctx context.Context, name string, options *azkeys.BackupKeyOptions) (resp azfake.Responder[azkeys.BackupKeyResponse], errResp azfake.ErrorResponder) + + // CreateKey is the fake for method Client.CreateKey + // HTTP status codes to indicate success: http.StatusOK + CreateKey func(ctx context.Context, name string, parameters azkeys.CreateKeyParameters, options *azkeys.CreateKeyOptions) (resp azfake.Responder[azkeys.CreateKeyResponse], errResp azfake.ErrorResponder) + + // Decrypt is the fake for method Client.Decrypt + // HTTP status codes to indicate success: http.StatusOK + Decrypt func(ctx context.Context, name string, version string, parameters azkeys.KeyOperationParameters, options *azkeys.DecryptOptions) (resp azfake.Responder[azkeys.DecryptResponse], errResp azfake.ErrorResponder) + + // DeleteKey is the fake for method Client.DeleteKey + // HTTP status codes to indicate success: http.StatusOK + DeleteKey func(ctx context.Context, name string, options *azkeys.DeleteKeyOptions) (resp azfake.Responder[azkeys.DeleteKeyResponse], errResp azfake.ErrorResponder) + + // Encrypt is the fake for method Client.Encrypt + // HTTP status codes to indicate success: http.StatusOK + Encrypt func(ctx context.Context, name string, version string, parameters azkeys.KeyOperationParameters, options *azkeys.EncryptOptions) (resp azfake.Responder[azkeys.EncryptResponse], errResp azfake.ErrorResponder) + + // GetDeletedKey is the fake for method Client.GetDeletedKey + // HTTP status codes to indicate success: http.StatusOK + GetDeletedKey func(ctx context.Context, name string, options *azkeys.GetDeletedKeyOptions) (resp azfake.Responder[azkeys.GetDeletedKeyResponse], errResp azfake.ErrorResponder) + + // GetKey is the fake for method Client.GetKey + // HTTP status codes to indicate success: http.StatusOK + GetKey func(ctx context.Context, name string, version string, options *azkeys.GetKeyOptions) (resp azfake.Responder[azkeys.GetKeyResponse], errResp azfake.ErrorResponder) + + // GetKeyAttestation is the fake for method Client.GetKeyAttestation + // HTTP status codes to indicate success: http.StatusOK + GetKeyAttestation func(ctx context.Context, name string, version string, options *azkeys.GetKeyAttestationOptions) (resp azfake.Responder[azkeys.GetKeyAttestationResponse], errResp azfake.ErrorResponder) + + // GetKeyRotationPolicy is the fake for method Client.GetKeyRotationPolicy + // HTTP status codes to indicate success: http.StatusOK + GetKeyRotationPolicy func(ctx context.Context, name string, options *azkeys.GetKeyRotationPolicyOptions) (resp azfake.Responder[azkeys.GetKeyRotationPolicyResponse], errResp azfake.ErrorResponder) + + // GetRandomBytes is the fake for method Client.GetRandomBytes + // HTTP status codes to indicate success: http.StatusOK + GetRandomBytes func(ctx context.Context, parameters azkeys.GetRandomBytesParameters, options *azkeys.GetRandomBytesOptions) (resp azfake.Responder[azkeys.GetRandomBytesResponse], errResp azfake.ErrorResponder) + + // ImportKey is the fake for method Client.ImportKey + // HTTP status codes to indicate success: http.StatusOK + ImportKey func(ctx context.Context, name string, parameters azkeys.ImportKeyParameters, options *azkeys.ImportKeyOptions) (resp azfake.Responder[azkeys.ImportKeyResponse], errResp azfake.ErrorResponder) + + // NewListDeletedKeyPropertiesPager is the fake for method Client.NewListDeletedKeyPropertiesPager + // HTTP status codes to indicate success: http.StatusOK + NewListDeletedKeyPropertiesPager func(options *azkeys.ListDeletedKeyPropertiesOptions) (resp azfake.PagerResponder[azkeys.ListDeletedKeyPropertiesResponse]) + + // NewListKeyPropertiesPager is the fake for method Client.NewListKeyPropertiesPager + // HTTP status codes to indicate success: http.StatusOK + NewListKeyPropertiesPager func(options *azkeys.ListKeyPropertiesOptions) (resp azfake.PagerResponder[azkeys.ListKeyPropertiesResponse]) + + // NewListKeyPropertiesVersionsPager is the fake for method Client.NewListKeyPropertiesVersionsPager + // HTTP status codes to indicate success: http.StatusOK + NewListKeyPropertiesVersionsPager func(name string, options *azkeys.ListKeyPropertiesVersionsOptions) (resp azfake.PagerResponder[azkeys.ListKeyPropertiesVersionsResponse]) + + // PurgeDeletedKey is the fake for method Client.PurgeDeletedKey + // HTTP status codes to indicate success: http.StatusNoContent + PurgeDeletedKey func(ctx context.Context, name string, options *azkeys.PurgeDeletedKeyOptions) (resp azfake.Responder[azkeys.PurgeDeletedKeyResponse], errResp azfake.ErrorResponder) + + // RecoverDeletedKey is the fake for method Client.RecoverDeletedKey + // HTTP status codes to indicate success: http.StatusOK + RecoverDeletedKey func(ctx context.Context, name string, options *azkeys.RecoverDeletedKeyOptions) (resp azfake.Responder[azkeys.RecoverDeletedKeyResponse], errResp azfake.ErrorResponder) + + // Release is the fake for method Client.Release + // HTTP status codes to indicate success: http.StatusOK + Release func(ctx context.Context, name string, version string, parameters azkeys.ReleaseParameters, options *azkeys.ReleaseOptions) (resp azfake.Responder[azkeys.ReleaseResponse], errResp azfake.ErrorResponder) + + // RestoreKey is the fake for method Client.RestoreKey + // HTTP status codes to indicate success: http.StatusOK + RestoreKey func(ctx context.Context, parameters azkeys.RestoreKeyParameters, options *azkeys.RestoreKeyOptions) (resp azfake.Responder[azkeys.RestoreKeyResponse], errResp azfake.ErrorResponder) + + // RotateKey is the fake for method Client.RotateKey + // HTTP status codes to indicate success: http.StatusOK + RotateKey func(ctx context.Context, name string, options *azkeys.RotateKeyOptions) (resp azfake.Responder[azkeys.RotateKeyResponse], errResp azfake.ErrorResponder) + + // SecureUnwrapKey is the fake for method Client.SecureUnwrapKey + // HTTP status codes to indicate success: http.StatusOK + SecureUnwrapKey func(ctx context.Context, name string, version string, parameters azkeys.SecureKeyUnWrapOperationParameters, options *azkeys.SecureUnwrapKeyOptions) (resp azfake.Responder[azkeys.SecureUnwrapKeyResponse], errResp azfake.ErrorResponder) + + // SecureWrapKey is the fake for method Client.SecureWrapKey + // HTTP status codes to indicate success: http.StatusOK + SecureWrapKey func(ctx context.Context, name string, version string, parameters azkeys.SecureKeyWrapOperationParameters, options *azkeys.SecureWrapKeyOptions) (resp azfake.Responder[azkeys.SecureWrapKeyResponse], errResp azfake.ErrorResponder) + + // Sign is the fake for method Client.Sign + // HTTP status codes to indicate success: http.StatusOK + Sign func(ctx context.Context, name string, version string, parameters azkeys.SignParameters, options *azkeys.SignOptions) (resp azfake.Responder[azkeys.SignResponse], errResp azfake.ErrorResponder) + + // UnwrapKey is the fake for method Client.UnwrapKey + // HTTP status codes to indicate success: http.StatusOK + UnwrapKey func(ctx context.Context, name string, version string, parameters azkeys.KeyOperationParameters, options *azkeys.UnwrapKeyOptions) (resp azfake.Responder[azkeys.UnwrapKeyResponse], errResp azfake.ErrorResponder) + + // UpdateKey is the fake for method Client.UpdateKey + // HTTP status codes to indicate success: http.StatusOK + UpdateKey func(ctx context.Context, name string, version string, parameters azkeys.UpdateKeyParameters, options *azkeys.UpdateKeyOptions) (resp azfake.Responder[azkeys.UpdateKeyResponse], errResp azfake.ErrorResponder) + + // UpdateKeyRotationPolicy is the fake for method Client.UpdateKeyRotationPolicy + // HTTP status codes to indicate success: http.StatusOK + UpdateKeyRotationPolicy func(ctx context.Context, name string, keyRotationPolicy azkeys.KeyRotationPolicy, options *azkeys.UpdateKeyRotationPolicyOptions) (resp azfake.Responder[azkeys.UpdateKeyRotationPolicyResponse], errResp azfake.ErrorResponder) + + // Verify is the fake for method Client.Verify + // HTTP status codes to indicate success: http.StatusOK + Verify func(ctx context.Context, name string, version string, parameters azkeys.VerifyParameters, options *azkeys.VerifyOptions) (resp azfake.Responder[azkeys.VerifyResponse], errResp azfake.ErrorResponder) + + // WrapKey is the fake for method Client.WrapKey + // HTTP status codes to indicate success: http.StatusOK + WrapKey func(ctx context.Context, name string, version string, parameters azkeys.KeyOperationParameters, options *azkeys.WrapKeyOptions) (resp azfake.Responder[azkeys.WrapKeyResponse], errResp azfake.ErrorResponder) +} + +// NewServerTransport creates a new instance of ServerTransport with the provided implementation. +// The returned ServerTransport instance is connected to an instance of azkeys.Client via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerTransport(srv *Server) *ServerTransport { + return &ServerTransport{ + srv: srv, + newListDeletedKeyPropertiesPager: newTracker[azfake.PagerResponder[azkeys.ListDeletedKeyPropertiesResponse]](), + newListKeyPropertiesPager: newTracker[azfake.PagerResponder[azkeys.ListKeyPropertiesResponse]](), + newListKeyPropertiesVersionsPager: newTracker[azfake.PagerResponder[azkeys.ListKeyPropertiesVersionsResponse]](), + } +} + +// ServerTransport connects instances of azkeys.Client to instances of Server. +// Don't use this type directly, use NewServerTransport instead. +type ServerTransport struct { + srv *Server + newListDeletedKeyPropertiesPager *tracker[azfake.PagerResponder[azkeys.ListDeletedKeyPropertiesResponse]] + newListKeyPropertiesPager *tracker[azfake.PagerResponder[azkeys.ListKeyPropertiesResponse]] + newListKeyPropertiesVersionsPager *tracker[azfake.PagerResponder[azkeys.ListKeyPropertiesVersionsResponse]] +} + +// Do implements the policy.Transporter interface for ServerTransport. +func (s *ServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if serverTransportInterceptor != nil { + res.resp, res.err, intercepted = serverTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "Client.BackupKey": + res.resp, res.err = s.dispatchBackupKey(req) + case "Client.CreateKey": + res.resp, res.err = s.dispatchCreateKey(req) + case "Client.Decrypt": + res.resp, res.err = s.dispatchDecrypt(req) + case "Client.DeleteKey": + res.resp, res.err = s.dispatchDeleteKey(req) + case "Client.Encrypt": + res.resp, res.err = s.dispatchEncrypt(req) + case "Client.GetDeletedKey": + res.resp, res.err = s.dispatchGetDeletedKey(req) + case "Client.GetKey": + res.resp, res.err = s.dispatchGetKey(req) + case "Client.GetKeyAttestation": + res.resp, res.err = s.dispatchGetKeyAttestation(req) + case "Client.GetKeyRotationPolicy": + res.resp, res.err = s.dispatchGetKeyRotationPolicy(req) + case "Client.GetRandomBytes": + res.resp, res.err = s.dispatchGetRandomBytes(req) + case "Client.ImportKey": + res.resp, res.err = s.dispatchImportKey(req) + case "Client.NewListDeletedKeyPropertiesPager": + res.resp, res.err = s.dispatchNewListDeletedKeyPropertiesPager(req) + case "Client.NewListKeyPropertiesPager": + res.resp, res.err = s.dispatchNewListKeyPropertiesPager(req) + case "Client.NewListKeyPropertiesVersionsPager": + res.resp, res.err = s.dispatchNewListKeyPropertiesVersionsPager(req) + case "Client.PurgeDeletedKey": + res.resp, res.err = s.dispatchPurgeDeletedKey(req) + case "Client.RecoverDeletedKey": + res.resp, res.err = s.dispatchRecoverDeletedKey(req) + case "Client.Release": + res.resp, res.err = s.dispatchRelease(req) + case "Client.RestoreKey": + res.resp, res.err = s.dispatchRestoreKey(req) + case "Client.RotateKey": + res.resp, res.err = s.dispatchRotateKey(req) + case "Client.SecureUnwrapKey": + res.resp, res.err = s.dispatchSecureUnwrapKey(req) + case "Client.SecureWrapKey": + res.resp, res.err = s.dispatchSecureWrapKey(req) + case "Client.Sign": + res.resp, res.err = s.dispatchSign(req) + case "Client.UnwrapKey": + res.resp, res.err = s.dispatchUnwrapKey(req) + case "Client.UpdateKey": + res.resp, res.err = s.dispatchUpdateKey(req) + case "Client.UpdateKeyRotationPolicy": + res.resp, res.err = s.dispatchUpdateKeyRotationPolicy(req) + case "Client.Verify": + res.resp, res.err = s.dispatchVerify(req) + case "Client.WrapKey": + res.resp, res.err = s.dispatchWrapKey(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ServerTransport) dispatchBackupKey(req *http.Request) (*http.Response, error) { + if s.srv.BackupKey == nil { + return nil, &nonRetriableError{errors.New("fake for method BackupKey not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/backup` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.BackupKey(req.Context(), nameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).BackupKeyResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchCreateKey(req *http.Request) (*http.Response, error) { + if s.srv.CreateKey == nil { + return nil, &nonRetriableError{errors.New("fake for method CreateKey not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/create` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[azkeys.CreateKeyParameters](req) + if err != nil { + return nil, err + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.CreateKey(req.Context(), nameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyBundle, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchDecrypt(req *http.Request) (*http.Response, error) { + if s.srv.Decrypt == nil { + return nil, &nonRetriableError{errors.New("fake for method Decrypt not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/decrypt` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[azkeys.KeyOperationParameters](req) + if err != nil { + return nil, err + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + versionParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_version")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Decrypt(req.Context(), nameParam, versionParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyOperationResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchDeleteKey(req *http.Request) (*http.Response, error) { + if s.srv.DeleteKey == nil { + return nil, &nonRetriableError{errors.New("fake for method DeleteKey not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.DeleteKey(req.Context(), nameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DeletedKey, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchEncrypt(req *http.Request) (*http.Response, error) { + if s.srv.Encrypt == nil { + return nil, &nonRetriableError{errors.New("fake for method Encrypt not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/encrypt` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[azkeys.KeyOperationParameters](req) + if err != nil { + return nil, err + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + versionParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_version")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Encrypt(req.Context(), nameParam, versionParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyOperationResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchGetDeletedKey(req *http.Request) (*http.Response, error) { + if s.srv.GetDeletedKey == nil { + return nil, &nonRetriableError{errors.New("fake for method GetDeletedKey not implemented")} + } + const regexStr = `/deletedkeys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.GetDeletedKey(req.Context(), nameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DeletedKey, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchGetKey(req *http.Request) (*http.Response, error) { + if s.srv.GetKey == nil { + return nil, &nonRetriableError{errors.New("fake for method GetKey not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + versionParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_version")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.GetKey(req.Context(), nameParam, versionParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyBundle, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchGetKeyAttestation(req *http.Request) (*http.Response, error) { + if s.srv.GetKeyAttestation == nil { + return nil, &nonRetriableError{errors.New("fake for method GetKeyAttestation not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/attestation` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + versionParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_version")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.GetKeyAttestation(req.Context(), nameParam, versionParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyBundle, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchGetKeyRotationPolicy(req *http.Request) (*http.Response, error) { + if s.srv.GetKeyRotationPolicy == nil { + return nil, &nonRetriableError{errors.New("fake for method GetKeyRotationPolicy not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/rotationpolicy` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.GetKeyRotationPolicy(req.Context(), nameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyRotationPolicy, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchGetRandomBytes(req *http.Request) (*http.Response, error) { + if s.srv.GetRandomBytes == nil { + return nil, &nonRetriableError{errors.New("fake for method GetRandomBytes not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[azkeys.GetRandomBytesParameters](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.GetRandomBytes(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).RandomBytes, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchImportKey(req *http.Request) (*http.Response, error) { + if s.srv.ImportKey == nil { + return nil, &nonRetriableError{errors.New("fake for method ImportKey not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[azkeys.ImportKeyParameters](req) + if err != nil { + return nil, err + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.ImportKey(req.Context(), nameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyBundle, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchNewListDeletedKeyPropertiesPager(req *http.Request) (*http.Response, error) { + if s.srv.NewListDeletedKeyPropertiesPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListDeletedKeyPropertiesPager not implemented")} + } + newListDeletedKeyPropertiesPager := s.newListDeletedKeyPropertiesPager.get(req) + if newListDeletedKeyPropertiesPager == nil { + resp := s.srv.NewListDeletedKeyPropertiesPager(nil) + newListDeletedKeyPropertiesPager = &resp + s.newListDeletedKeyPropertiesPager.add(req, newListDeletedKeyPropertiesPager) + server.PagerResponderInjectNextLinks(newListDeletedKeyPropertiesPager, req, func(page *azkeys.ListDeletedKeyPropertiesResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListDeletedKeyPropertiesPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + s.newListDeletedKeyPropertiesPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListDeletedKeyPropertiesPager) { + s.newListDeletedKeyPropertiesPager.remove(req) + } + return resp, nil +} + +func (s *ServerTransport) dispatchNewListKeyPropertiesPager(req *http.Request) (*http.Response, error) { + if s.srv.NewListKeyPropertiesPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListKeyPropertiesPager not implemented")} + } + newListKeyPropertiesPager := s.newListKeyPropertiesPager.get(req) + if newListKeyPropertiesPager == nil { + resp := s.srv.NewListKeyPropertiesPager(nil) + newListKeyPropertiesPager = &resp + s.newListKeyPropertiesPager.add(req, newListKeyPropertiesPager) + server.PagerResponderInjectNextLinks(newListKeyPropertiesPager, req, func(page *azkeys.ListKeyPropertiesResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListKeyPropertiesPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + s.newListKeyPropertiesPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListKeyPropertiesPager) { + s.newListKeyPropertiesPager.remove(req) + } + return resp, nil +} + +func (s *ServerTransport) dispatchNewListKeyPropertiesVersionsPager(req *http.Request) (*http.Response, error) { + if s.srv.NewListKeyPropertiesVersionsPager == nil { + return nil, &nonRetriableError{errors.New("fake for method NewListKeyPropertiesVersionsPager not implemented")} + } + newListKeyPropertiesVersionsPager := s.newListKeyPropertiesVersionsPager.get(req) + if newListKeyPropertiesVersionsPager == nil { + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/versions` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + resp := s.srv.NewListKeyPropertiesVersionsPager(nameParam, nil) + newListKeyPropertiesVersionsPager = &resp + s.newListKeyPropertiesVersionsPager.add(req, newListKeyPropertiesVersionsPager) + server.PagerResponderInjectNextLinks(newListKeyPropertiesVersionsPager, req, func(page *azkeys.ListKeyPropertiesVersionsResponse, createLink func() string) { + page.NextLink = to.Ptr(createLink()) + }) + } + resp, err := server.PagerResponderNext(newListKeyPropertiesVersionsPager, req) + if err != nil { + return nil, err + } + if !slices.Contains([]int{http.StatusOK}, resp.StatusCode) { + s.newListKeyPropertiesVersionsPager.remove(req) + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", resp.StatusCode)} + } + if !server.PagerResponderMore(newListKeyPropertiesVersionsPager) { + s.newListKeyPropertiesVersionsPager.remove(req) + } + return resp, nil +} + +func (s *ServerTransport) dispatchPurgeDeletedKey(req *http.Request) (*http.Response, error) { + if s.srv.PurgeDeletedKey == nil { + return nil, &nonRetriableError{errors.New("fake for method PurgeDeletedKey not implemented")} + } + const regexStr = `/deletedkeys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.PurgeDeletedKey(req.Context(), nameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchRecoverDeletedKey(req *http.Request) (*http.Response, error) { + if s.srv.RecoverDeletedKey == nil { + return nil, &nonRetriableError{errors.New("fake for method RecoverDeletedKey not implemented")} + } + const regexStr = `/deletedkeys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/recover` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.RecoverDeletedKey(req.Context(), nameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyBundle, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchRelease(req *http.Request) (*http.Response, error) { + if s.srv.Release == nil { + return nil, &nonRetriableError{errors.New("fake for method Release not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/release` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[azkeys.ReleaseParameters](req) + if err != nil { + return nil, err + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + versionParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_version")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Release(req.Context(), nameParam, versionParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyReleaseResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchRestoreKey(req *http.Request) (*http.Response, error) { + if s.srv.RestoreKey == nil { + return nil, &nonRetriableError{errors.New("fake for method RestoreKey not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[azkeys.RestoreKeyParameters](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.RestoreKey(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyBundle, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchRotateKey(req *http.Request) (*http.Response, error) { + if s.srv.RotateKey == nil { + return nil, &nonRetriableError{errors.New("fake for method RotateKey not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/rotate` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.RotateKey(req.Context(), nameParam, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyBundle, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchSecureUnwrapKey(req *http.Request) (*http.Response, error) { + if s.srv.SecureUnwrapKey == nil { + return nil, &nonRetriableError{errors.New("fake for method SecureUnwrapKey not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/secureunwrapkey` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[azkeys.SecureKeyUnWrapOperationParameters](req) + if err != nil { + return nil, err + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + versionParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_version")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.SecureUnwrapKey(req.Context(), nameParam, versionParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).SecureKeyOperationResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchSecureWrapKey(req *http.Request) (*http.Response, error) { + if s.srv.SecureWrapKey == nil { + return nil, &nonRetriableError{errors.New("fake for method SecureWrapKey not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/securewrapkey` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[azkeys.SecureKeyWrapOperationParameters](req) + if err != nil { + return nil, err + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + versionParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_version")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.SecureWrapKey(req.Context(), nameParam, versionParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).SecureKeyOperationResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchSign(req *http.Request) (*http.Response, error) { + if s.srv.Sign == nil { + return nil, &nonRetriableError{errors.New("fake for method Sign not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/sign` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[azkeys.SignParameters](req) + if err != nil { + return nil, err + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + versionParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_version")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Sign(req.Context(), nameParam, versionParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyOperationResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchUnwrapKey(req *http.Request) (*http.Response, error) { + if s.srv.UnwrapKey == nil { + return nil, &nonRetriableError{errors.New("fake for method UnwrapKey not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/unwrapkey` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[azkeys.KeyOperationParameters](req) + if err != nil { + return nil, err + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + versionParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_version")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.UnwrapKey(req.Context(), nameParam, versionParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyOperationResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchUpdateKey(req *http.Request) (*http.Response, error) { + if s.srv.UpdateKey == nil { + return nil, &nonRetriableError{errors.New("fake for method UpdateKey not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[azkeys.UpdateKeyParameters](req) + if err != nil { + return nil, err + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + versionParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_version")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.UpdateKey(req.Context(), nameParam, versionParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyBundle, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchUpdateKeyRotationPolicy(req *http.Request) (*http.Response, error) { + if s.srv.UpdateKeyRotationPolicy == nil { + return nil, &nonRetriableError{errors.New("fake for method UpdateKeyRotationPolicy not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/rotationpolicy` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[azkeys.KeyRotationPolicy](req) + if err != nil { + return nil, err + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.UpdateKeyRotationPolicy(req.Context(), nameParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyRotationPolicy, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchVerify(req *http.Request) (*http.Response, error) { + if s.srv.Verify == nil { + return nil, &nonRetriableError{errors.New("fake for method Verify not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/verify` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[azkeys.VerifyParameters](req) + if err != nil { + return nil, err + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + versionParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_version")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.Verify(req.Context(), nameParam, versionParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyVerifyResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchWrapKey(req *http.Request) (*http.Response, error) { + if s.srv.WrapKey == nil { + return nil, &nonRetriableError{errors.New("fake for method WrapKey not implemented")} + } + const regexStr = `/keys/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/wrapkey` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + body, err := server.UnmarshalRequestAsJSON[azkeys.KeyOperationParameters](req) + if err != nil { + return nil, err + } + nameParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_name")]) + if err != nil { + return nil, err + } + versionParam, err := url.PathUnescape(matches[regex.SubexpIndex("key_version")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WrapKey(req.Context(), nameParam, versionParam, body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).KeyOperationResult, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ServerTransport +var serverTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/azkeys/fake_test.go b/test/local/azkeys/fake_test.go new file mode 100644 index 000000000000..d2b3b8d30ef7 --- /dev/null +++ b/test/local/azkeys/fake_test.go @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package azkeys_test + +import ( + "azkeys" + "azkeys/fake" + "context" + "encoding/json" + "fmt" + "net/http" + "regexp" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/stretchr/testify/require" +) + +func TestFakeBackupKey(t *testing.T) { + const fakeKeyName = "fakeKey" + fakeKeyBlob := []byte{1, 2, 3} + server := fake.Server{ + BackupKey: func(ctx context.Context, keyName string, options *azkeys.BackupKeyOptions) (resp azfake.Responder[azkeys.BackupKeyResponse], errResp azfake.ErrorResponder) { + if keyName != fakeKeyName { + errResp.SetError(fmt.Errorf("bad fake key name %s", keyName)) + return + } + resp.SetResponse(http.StatusOK, azkeys.BackupKeyResponse{ + BackupKeyResult: azkeys.BackupKeyResult{ + Value: fakeKeyBlob, + }, + }, nil) + return + }, + } + + client, err := azkeys.NewClient("https://fake.vault.azure.net", &azcore.ClientOptions{ + Transport: fake.NewServerTransport(&server), + }) + require.NoError(t, err) + + resp, err := client.BackupKey(context.Background(), fakeKeyName, nil) + require.NoError(t, err) + testSerde(t, &resp) + require.Equal(t, fakeKeyBlob, resp.Value) +} + +type serdeModel interface { + json.Marshaler + json.Unmarshaler +} + +func testSerde[T serdeModel](t *testing.T, model T) { + data, err := model.MarshalJSON() + require.NoError(t, err) + err = model.UnmarshalJSON(data) + require.NoError(t, err) + + // testing unmarshal error scenarios + err = model.UnmarshalJSON(nil) + require.Error(t, err) + + m := regexp.MustCompile(":.*$") + modifiedData := m.ReplaceAllString(string(data), `:["test", "test1", "test2"]}`) + if modifiedData != "{}" { + data3 := []byte(modifiedData) + err = model.UnmarshalJSON(data3) + require.Error(t, err) + } +} diff --git a/test/local/azkeys/go.mod b/test/local/azkeys/go.mod new file mode 100644 index 000000000000..e844fbc32548 --- /dev/null +++ b/test/local/azkeys/go.mod @@ -0,0 +1,17 @@ +module azkeys + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/local/azkeys/go.sum b/test/local/azkeys/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/local/azkeys/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/local/azkeys/testdata/_metadata.json b/test/local/azkeys/testdata/_metadata.json new file mode 100644 index 000000000000..3c4d0116f821 --- /dev/null +++ b/test/local/azkeys/testdata/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "KeyVault": "2026-05-01-preview" + }, + "emitterVersion": "0.0.0" +} diff --git a/test/local/azkeys/zz_client.go b/test/local/azkeys/zz_client.go new file mode 100644 index 000000000000..6d31d8a442da --- /dev/null +++ b/test/local/azkeys/zz_client.go @@ -0,0 +1,1684 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azkeys + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// Client - The key vault client performs cryptographic key operations and vault operations against the Key Vault service. +// Don't use this type directly, use a constructor function instead. +// +// Generated from API version 2026-05-01-preview +type Client struct { + internal *azcore.Client + vaultBaseUrl string +} + +// BackupKey - Requests that a backup of the specified key be downloaded to the client. +// +// The Key Backup operation exports a key from Azure Key Vault in a protected form. Note that this operation does NOT return +// key material in a form that can be used outside the Azure Key Vault system, the returned key material is either protected +// to a Azure Key Vault HSM or to Azure Key Vault itself. The intent of this operation is to allow a client to GENERATE a +// key in one Azure Key Vault instance, BACKUP the key, and then RESTORE it into another Azure Key Vault instance. The BACKUP +// operation may be used to export, in protected form, any key type from Azure Key Vault. Individual versions of a key cannot +// be backed up. BACKUP / RESTORE can be performed within geographical boundaries only; meaning that a BACKUP from one geographical +// area cannot be restored to another geographical area. For example, a backup from the US geographical area cannot be restored +// in an EU geographical area. This operation requires the key/backup permission. +// If the operation fails it returns an *azcore.ResponseError type. +// - name - The name of the key. +// - options - BackupKeyOptions contains the optional parameters for the Client.BackupKey method. +func (client *Client) BackupKey(ctx context.Context, name string, options *BackupKeyOptions) (BackupKeyResponse, error) { + var err error + const operationName = "Client.BackupKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.backupKeyCreateRequest(ctx, name, options) + if err != nil { + return BackupKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return BackupKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return BackupKeyResponse{}, err + } + resp, err := client.backupKeyHandleResponse(httpResp) + return resp, err +} + +// backupKeyCreateRequest creates the BackupKey request. +func (client *Client) backupKeyCreateRequest(ctx context.Context, name string, _ *BackupKeyOptions) (*policy.Request, error) { + urlPath := "/keys/{key-name}/backup" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.vaultBaseUrl, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// backupKeyHandleResponse handles the BackupKey response. +func (client *Client) backupKeyHandleResponse(resp *http.Response) (BackupKeyResponse, error) { + result := BackupKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.BackupKeyResult); err != nil { + return BackupKeyResponse{}, err + } + return result, nil +} + +// CreateKey - Creates a new key, stores it, then returns key parameters and attributes to the client. +// +// The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, Azure +// Key Vault creates a new version of the key. It requires the keys/create permission. +// If the operation fails it returns an *azcore.ResponseError type. +// - name - The name for the new key. The system will generate the version name for the new key. The value you provide may be +// copied globally for the purpose of running the service. The value provided should not include personally identifiable or +// sensitive information. +// - parameters - The parameters to create a key. +// - options - CreateKeyOptions contains the optional parameters for the Client.CreateKey method. +func (client *Client) CreateKey(ctx context.Context, name string, parameters CreateKeyParameters, options *CreateKeyOptions) (CreateKeyResponse, error) { + var err error + const operationName = "Client.CreateKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.createKeyCreateRequest(ctx, name, parameters, options) + if err != nil { + return CreateKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return CreateKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return CreateKeyResponse{}, err + } + resp, err := client.createKeyHandleResponse(httpResp) + return resp, err +} + +// createKeyCreateRequest creates the CreateKey request. +func (client *Client) createKeyCreateRequest(ctx context.Context, name string, parameters CreateKeyParameters, _ *CreateKeyOptions) (*policy.Request, error) { + urlPath := "/keys/{key-name}/create" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.vaultBaseUrl, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// createKeyHandleResponse handles the CreateKey response. +func (client *Client) createKeyHandleResponse(resp *http.Response) (CreateKeyResponse, error) { + result := CreateKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyBundle); err != nil { + return CreateKeyResponse{}, err + } + return result, nil +} + +// Decrypt - Decrypts a single block of encrypted data. +// +// The DECRYPT operation decrypts a well-formed block of ciphertext using the target encryption key and specified algorithm. +// This operation is the reverse of the ENCRYPT operation; only a single block of data may be decrypted, the size of this +// block is dependent on the target key and the algorithm to be used. The DECRYPT operation applies to asymmetric and symmetric +// keys stored in Azure Key Vault since it uses the private portion of the key. This operation requires the keys/decrypt permission. +// Microsoft recommends not to use CBC algorithms for decryption without first ensuring the integrity of the ciphertext using +// an HMAC, for example. See https://learn.microsoft.com/dotnet/standard/security/vulnerabilities-cbc-mode for more information. +// If the operation fails it returns an *azcore.ResponseError type. +// - name - The name of the key. +// - version - The version of the key. +// - parameters - The parameters for the decryption operation. +// - options - DecryptOptions contains the optional parameters for the Client.Decrypt method. +func (client *Client) Decrypt(ctx context.Context, name string, version string, parameters KeyOperationParameters, options *DecryptOptions) (DecryptResponse, error) { + var err error + const operationName = "Client.Decrypt" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.decryptCreateRequest(ctx, name, version, parameters, options) + if err != nil { + return DecryptResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DecryptResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DecryptResponse{}, err + } + resp, err := client.decryptHandleResponse(httpResp) + return resp, err +} + +// decryptCreateRequest creates the Decrypt request. +func (client *Client) decryptCreateRequest(ctx context.Context, name string, version string, parameters KeyOperationParameters, _ *DecryptOptions) (*policy.Request, error) { + urlPath := "/keys/{key-name}/{key-version}/decrypt" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) + if version == "" { + return nil, errors.New("parameter version cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(version)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.vaultBaseUrl, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// decryptHandleResponse handles the Decrypt response. +func (client *Client) decryptHandleResponse(resp *http.Response) (DecryptResponse, error) { + result := DecryptResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyOperationResult); err != nil { + return DecryptResponse{}, err + } + return result, nil +} + +// DeleteKey - Deletes a key of any type from storage in Azure Key Vault. +// +// The delete key operation cannot be used to remove individual versions of a key. This operation removes the cryptographic +// material associated with the key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or Encrypt/Decrypt operations. +// This operation requires the keys/delete permission. +// If the operation fails it returns an *azcore.ResponseError type. +// - name - The name of the key to delete. +// - options - DeleteKeyOptions contains the optional parameters for the Client.DeleteKey method. +func (client *Client) DeleteKey(ctx context.Context, name string, options *DeleteKeyOptions) (DeleteKeyResponse, error) { + var err error + const operationName = "Client.DeleteKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.deleteKeyCreateRequest(ctx, name, options) + if err != nil { + return DeleteKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return DeleteKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return DeleteKeyResponse{}, err + } + resp, err := client.deleteKeyHandleResponse(httpResp) + return resp, err +} + +// deleteKeyCreateRequest creates the DeleteKey request. +func (client *Client) deleteKeyCreateRequest(ctx context.Context, name string, _ *DeleteKeyOptions) (*policy.Request, error) { + urlPath := "/keys/{key-name}" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.vaultBaseUrl, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// deleteKeyHandleResponse handles the DeleteKey response. +func (client *Client) deleteKeyHandleResponse(resp *http.Response) (DeleteKeyResponse, error) { + result := DeleteKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DeletedKey); err != nil { + return DeleteKeyResponse{}, err + } + return result, nil +} + +// Encrypt - Encrypts an arbitrary sequence of bytes using an encryption key that is stored in a key vault. +// +// The ENCRYPT operation encrypts an arbitrary sequence of bytes using an encryption key that is stored in Azure Key Vault. +// Note that the ENCRYPT operation only supports a single block of data, the size of which is dependent on the target key +// and the encryption algorithm to be used. The ENCRYPT operation is only strictly necessary for symmetric keys stored in +// Azure Key Vault since protection with an asymmetric key can be performed using public portion of the key. This operation +// is supported for asymmetric keys as a convenience for callers that have a key-reference but do not have access to the public +// key material. This operation requires the keys/encrypt permission. +// If the operation fails it returns an *azcore.ResponseError type. +// - name - The name of the key. +// - version - The version of the key. +// - parameters - The parameters for the encryption operation. +// - options - EncryptOptions contains the optional parameters for the Client.Encrypt method. +func (client *Client) Encrypt(ctx context.Context, name string, version string, parameters KeyOperationParameters, options *EncryptOptions) (EncryptResponse, error) { + var err error + const operationName = "Client.Encrypt" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.encryptCreateRequest(ctx, name, version, parameters, options) + if err != nil { + return EncryptResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return EncryptResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return EncryptResponse{}, err + } + resp, err := client.encryptHandleResponse(httpResp) + return resp, err +} + +// encryptCreateRequest creates the Encrypt request. +func (client *Client) encryptCreateRequest(ctx context.Context, name string, version string, parameters KeyOperationParameters, _ *EncryptOptions) (*policy.Request, error) { + urlPath := "/keys/{key-name}/{key-version}/encrypt" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) + if version == "" { + return nil, errors.New("parameter version cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(version)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.vaultBaseUrl, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// encryptHandleResponse handles the Encrypt response. +func (client *Client) encryptHandleResponse(resp *http.Response) (EncryptResponse, error) { + result := EncryptResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyOperationResult); err != nil { + return EncryptResponse{}, err + } + return result, nil +} + +// GetDeletedKey - Gets the public part of a deleted key. +// +// The Get Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked on any vault, +// it will return an error if invoked on a non soft-delete enabled vault. This operation requires the keys/get permission. +// If the operation fails it returns an *azcore.ResponseError type. +// - name - The name of the key. +// - options - GetDeletedKeyOptions contains the optional parameters for the Client.GetDeletedKey method. +func (client *Client) GetDeletedKey(ctx context.Context, name string, options *GetDeletedKeyOptions) (GetDeletedKeyResponse, error) { + var err error + const operationName = "Client.GetDeletedKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getDeletedKeyCreateRequest(ctx, name, options) + if err != nil { + return GetDeletedKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GetDeletedKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GetDeletedKeyResponse{}, err + } + resp, err := client.getDeletedKeyHandleResponse(httpResp) + return resp, err +} + +// getDeletedKeyCreateRequest creates the GetDeletedKey request. +func (client *Client) getDeletedKeyCreateRequest(ctx context.Context, name string, _ *GetDeletedKeyOptions) (*policy.Request, error) { + urlPath := "/deletedkeys/{key-name}" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.vaultBaseUrl, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getDeletedKeyHandleResponse handles the GetDeletedKey response. +func (client *Client) getDeletedKeyHandleResponse(resp *http.Response) (GetDeletedKeyResponse, error) { + result := GetDeletedKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DeletedKey); err != nil { + return GetDeletedKeyResponse{}, err + } + return result, nil +} + +// GetKey - Gets the public part of a stored key. +// +// The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is released +// in the response. This operation requires the keys/get permission. +// If the operation fails it returns an *azcore.ResponseError type. +// - name - The name of the key to get. +// - version - Adding the version parameter retrieves a specific version of a key. This URI fragment is optional. If not specified, +// the latest version of the key is returned. +// - options - GetKeyOptions contains the optional parameters for the Client.GetKey method. +func (client *Client) GetKey(ctx context.Context, name string, version string, options *GetKeyOptions) (GetKeyResponse, error) { + var err error + const operationName = "Client.GetKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getKeyCreateRequest(ctx, name, version, options) + if err != nil { + return GetKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GetKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GetKeyResponse{}, err + } + resp, err := client.getKeyHandleResponse(httpResp) + return resp, err +} + +// getKeyCreateRequest creates the GetKey request. +func (client *Client) getKeyCreateRequest(ctx context.Context, name string, version string, _ *GetKeyOptions) (*policy.Request, error) { + urlPath := "/keys/{key-name}/{key-version}" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) + if version == "" { + return nil, errors.New("parameter version cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(version)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.vaultBaseUrl, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getKeyHandleResponse handles the GetKey response. +func (client *Client) getKeyHandleResponse(resp *http.Response) (GetKeyResponse, error) { + result := GetKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyBundle); err != nil { + return GetKeyResponse{}, err + } + return result, nil +} + +// GetKeyAttestation - Gets the public part of a stored key along with its attestation blob. +// +// The get key attestation operation returns the key along with its attestation blob. This operation requires the keys/get +// permission. +// If the operation fails it returns an *azcore.ResponseError type. +// - name - The name of the key to retrieve attestation for. +// - version - Adding the version parameter retrieves attestation blob for specific version of a key. This URI fragment is optional. +// If not specified, the latest version of the key attestation blob is returned. +// - options - GetKeyAttestationOptions contains the optional parameters for the Client.GetKeyAttestation method. +func (client *Client) GetKeyAttestation(ctx context.Context, name string, version string, options *GetKeyAttestationOptions) (GetKeyAttestationResponse, error) { + var err error + const operationName = "Client.GetKeyAttestation" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getKeyAttestationCreateRequest(ctx, name, version, options) + if err != nil { + return GetKeyAttestationResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GetKeyAttestationResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GetKeyAttestationResponse{}, err + } + resp, err := client.getKeyAttestationHandleResponse(httpResp) + return resp, err +} + +// getKeyAttestationCreateRequest creates the GetKeyAttestation request. +func (client *Client) getKeyAttestationCreateRequest(ctx context.Context, name string, version string, _ *GetKeyAttestationOptions) (*policy.Request, error) { + urlPath := "/keys/{key-name}/{key-version}/attestation" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) + if version == "" { + return nil, errors.New("parameter version cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(version)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.vaultBaseUrl, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getKeyAttestationHandleResponse handles the GetKeyAttestation response. +func (client *Client) getKeyAttestationHandleResponse(resp *http.Response) (GetKeyAttestationResponse, error) { + result := GetKeyAttestationResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyBundle); err != nil { + return GetKeyAttestationResponse{}, err + } + return result, nil +} + +// GetKeyRotationPolicy - Lists the policy for a key. +// +// The GetKeyRotationPolicy operation returns the specified key policy resources in the specified key vault. This operation +// requires the keys/get permission. +// If the operation fails it returns an *azcore.ResponseError type. +// - name - The name of the key in a given key vault. +// - options - GetKeyRotationPolicyOptions contains the optional parameters for the Client.GetKeyRotationPolicy method. +func (client *Client) GetKeyRotationPolicy(ctx context.Context, name string, options *GetKeyRotationPolicyOptions) (GetKeyRotationPolicyResponse, error) { + var err error + const operationName = "Client.GetKeyRotationPolicy" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getKeyRotationPolicyCreateRequest(ctx, name, options) + if err != nil { + return GetKeyRotationPolicyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GetKeyRotationPolicyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GetKeyRotationPolicyResponse{}, err + } + resp, err := client.getKeyRotationPolicyHandleResponse(httpResp) + return resp, err +} + +// getKeyRotationPolicyCreateRequest creates the GetKeyRotationPolicy request. +func (client *Client) getKeyRotationPolicyCreateRequest(ctx context.Context, name string, _ *GetKeyRotationPolicyOptions) (*policy.Request, error) { + urlPath := "/keys/{key-name}/rotationpolicy" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.vaultBaseUrl, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getKeyRotationPolicyHandleResponse handles the GetKeyRotationPolicy response. +func (client *Client) getKeyRotationPolicyHandleResponse(resp *http.Response) (GetKeyRotationPolicyResponse, error) { + result := GetKeyRotationPolicyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyRotationPolicy); err != nil { + return GetKeyRotationPolicyResponse{}, err + } + return result, nil +} + +// GetRandomBytes - Get the requested number of bytes containing random values. +// +// Get the requested number of bytes containing random values from a managed HSM. +// If the operation fails it returns an *azcore.ResponseError type. +// - parameters - The request object to get random bytes. +// - options - GetRandomBytesOptions contains the optional parameters for the Client.GetRandomBytes method. +func (client *Client) GetRandomBytes(ctx context.Context, parameters GetRandomBytesParameters, options *GetRandomBytesOptions) (GetRandomBytesResponse, error) { + var err error + const operationName = "Client.GetRandomBytes" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getRandomBytesCreateRequest(ctx, parameters, options) + if err != nil { + return GetRandomBytesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return GetRandomBytesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return GetRandomBytesResponse{}, err + } + resp, err := client.getRandomBytesHandleResponse(httpResp) + return resp, err +} + +// getRandomBytesCreateRequest creates the GetRandomBytes request. +func (client *Client) getRandomBytesCreateRequest(ctx context.Context, parameters GetRandomBytesParameters, _ *GetRandomBytesOptions) (*policy.Request, error) { + urlPath := "/rng" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.vaultBaseUrl, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// getRandomBytesHandleResponse handles the GetRandomBytes response. +func (client *Client) getRandomBytesHandleResponse(resp *http.Response) (GetRandomBytesResponse, error) { + result := GetRandomBytesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.RandomBytes); err != nil { + return GetRandomBytesResponse{}, err + } + return result, nil +} + +// ImportKey - Imports an externally created key, stores it, and returns key parameters and attributes to the client. +// +// The import key operation may be used to import any key type into an Azure Key Vault. If the named key already exists, Azure +// Key Vault creates a new version of the key. This operation requires the keys/import permission. +// If the operation fails it returns an *azcore.ResponseError type. +// - name - Name for the imported key. The value you provide may be copied globally for the purpose of running the service. +// The value provided should not include personally identifiable or sensitive information. +// - parameters - The parameters to import a key. +// - options - ImportKeyOptions contains the optional parameters for the Client.ImportKey method. +func (client *Client) ImportKey(ctx context.Context, name string, parameters ImportKeyParameters, options *ImportKeyOptions) (ImportKeyResponse, error) { + var err error + const operationName = "Client.ImportKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.importKeyCreateRequest(ctx, name, parameters, options) + if err != nil { + return ImportKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ImportKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ImportKeyResponse{}, err + } + resp, err := client.importKeyHandleResponse(httpResp) + return resp, err +} + +// importKeyCreateRequest creates the ImportKey request. +func (client *Client) importKeyCreateRequest(ctx context.Context, name string, parameters ImportKeyParameters, _ *ImportKeyOptions) (*policy.Request, error) { + urlPath := "/keys/{key-name}" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.vaultBaseUrl, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// importKeyHandleResponse handles the ImportKey response. +func (client *Client) importKeyHandleResponse(resp *http.Response) (ImportKeyResponse, error) { + result := ImportKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyBundle); err != nil { + return ImportKeyResponse{}, err + } + return result, nil +} + +// NewListDeletedKeyPropertiesPager - Lists the deleted keys in the specified vault. +// +// Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a deleted key. +// This operation includes deletion-specific information. The Get Deleted Keys operation is applicable for vaults enabled +// for soft-delete. While the operation can be invoked on any vault, it will return an error if invoked on a non soft-delete +// enabled vault. This operation requires the keys/list permission. +// - options - ListDeletedKeyPropertiesOptions contains the optional parameters for the Client.NewListDeletedKeyPropertiesPager +// method. +func (client *Client) NewListDeletedKeyPropertiesPager(options *ListDeletedKeyPropertiesOptions) *runtime.Pager[ListDeletedKeyPropertiesResponse] { + return runtime.NewPager(runtime.PagingHandler[ListDeletedKeyPropertiesResponse]{ + More: func(page ListDeletedKeyPropertiesResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ListDeletedKeyPropertiesResponse) (ListDeletedKeyPropertiesResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "Client.NewListDeletedKeyPropertiesPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listDeletedKeyPropertiesCreateRequest(ctx, options) + }, nil) + if err != nil { + return ListDeletedKeyPropertiesResponse{}, err + } + return client.listDeletedKeyPropertiesHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listDeletedKeyPropertiesCreateRequest creates the ListDeletedKeyProperties request. +func (client *Client) listDeletedKeyPropertiesCreateRequest(ctx context.Context, _ *ListDeletedKeyPropertiesOptions) (*policy.Request, error) { + urlPath := "/deletedkeys" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.vaultBaseUrl, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listDeletedKeyPropertiesHandleResponse handles the ListDeletedKeyProperties response. +func (client *Client) listDeletedKeyPropertiesHandleResponse(resp *http.Response) (ListDeletedKeyPropertiesResponse, error) { + result := ListDeletedKeyPropertiesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.DeletedKeyPropertiesListResult); err != nil { + return ListDeletedKeyPropertiesResponse{}, err + } + return result, nil +} + +// NewListKeyPropertiesPager - List keys in the specified vault. +// +// Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a stored key. +// The LIST operation is applicable to all key types, however only the base key identifier, attributes, and tags are provided +// in the response. Individual versions of a key are not listed in the response. This operation requires the keys/list permission. +// - options - ListKeyPropertiesOptions contains the optional parameters for the Client.NewListKeyPropertiesPager method. +func (client *Client) NewListKeyPropertiesPager(options *ListKeyPropertiesOptions) *runtime.Pager[ListKeyPropertiesResponse] { + return runtime.NewPager(runtime.PagingHandler[ListKeyPropertiesResponse]{ + More: func(page ListKeyPropertiesResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ListKeyPropertiesResponse) (ListKeyPropertiesResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "Client.NewListKeyPropertiesPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listKeyPropertiesCreateRequest(ctx, options) + }, nil) + if err != nil { + return ListKeyPropertiesResponse{}, err + } + return client.listKeyPropertiesHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listKeyPropertiesCreateRequest creates the ListKeyProperties request. +func (client *Client) listKeyPropertiesCreateRequest(ctx context.Context, _ *ListKeyPropertiesOptions) (*policy.Request, error) { + urlPath := "/keys" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.vaultBaseUrl, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listKeyPropertiesHandleResponse handles the ListKeyProperties response. +func (client *Client) listKeyPropertiesHandleResponse(resp *http.Response) (ListKeyPropertiesResponse, error) { + result := ListKeyPropertiesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyPropertiesListResult); err != nil { + return ListKeyPropertiesResponse{}, err + } + return result, nil +} + +// NewListKeyPropertiesVersionsPager - Retrieves a list of individual key versions with the same key name. +// +// The full key identifier, attributes, and tags are provided in the response. This operation requires the keys/list permission. +// - name - The name of the key. +// - options - ListKeyPropertiesVersionsOptions contains the optional parameters for the Client.NewListKeyPropertiesVersionsPager +// method. +func (client *Client) NewListKeyPropertiesVersionsPager(name string, options *ListKeyPropertiesVersionsOptions) *runtime.Pager[ListKeyPropertiesVersionsResponse] { + return runtime.NewPager(runtime.PagingHandler[ListKeyPropertiesVersionsResponse]{ + More: func(page ListKeyPropertiesVersionsResponse) bool { + return page.NextLink != nil && len(*page.NextLink) > 0 + }, + Fetcher: func(ctx context.Context, page *ListKeyPropertiesVersionsResponse) (ListKeyPropertiesVersionsResponse, error) { + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, "Client.NewListKeyPropertiesVersionsPager") + nextLink := "" + if page != nil { + nextLink = *page.NextLink + } + resp, err := runtime.FetcherForNextLink(ctx, client.internal.Pipeline(), nextLink, func(ctx context.Context) (*policy.Request, error) { + return client.listKeyPropertiesVersionsCreateRequest(ctx, name, options) + }, nil) + if err != nil { + return ListKeyPropertiesVersionsResponse{}, err + } + return client.listKeyPropertiesVersionsHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listKeyPropertiesVersionsCreateRequest creates the ListKeyPropertiesVersions request. +func (client *Client) listKeyPropertiesVersionsCreateRequest(ctx context.Context, name string, _ *ListKeyPropertiesVersionsOptions) (*policy.Request, error) { + urlPath := "/keys/{key-name}/versions" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.vaultBaseUrl, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listKeyPropertiesVersionsHandleResponse handles the ListKeyPropertiesVersions response. +func (client *Client) listKeyPropertiesVersionsHandleResponse(resp *http.Response) (ListKeyPropertiesVersionsResponse, error) { + result := ListKeyPropertiesVersionsResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyPropertiesListResult); err != nil { + return ListKeyPropertiesVersionsResponse{}, err + } + return result, nil +} + +// PurgeDeletedKey - Permanently deletes the specified key. +// +// The Purge Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked on any +// vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the keys/purge permission. +// If the operation fails it returns an *azcore.ResponseError type. +// - name - The name of the key +// - options - PurgeDeletedKeyOptions contains the optional parameters for the Client.PurgeDeletedKey method. +func (client *Client) PurgeDeletedKey(ctx context.Context, name string, options *PurgeDeletedKeyOptions) (PurgeDeletedKeyResponse, error) { + var err error + const operationName = "Client.PurgeDeletedKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.purgeDeletedKeyCreateRequest(ctx, name, options) + if err != nil { + return PurgeDeletedKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return PurgeDeletedKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return PurgeDeletedKeyResponse{}, err + } + return PurgeDeletedKeyResponse{}, nil +} + +// purgeDeletedKeyCreateRequest creates the PurgeDeletedKey request. +func (client *Client) purgeDeletedKeyCreateRequest(ctx context.Context, name string, _ *PurgeDeletedKeyOptions) (*policy.Request, error) { + urlPath := "/deletedkeys/{key-name}" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.vaultBaseUrl, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// RecoverDeletedKey - Recovers the deleted key to its latest version. +// +// The Recover Deleted Key operation is applicable for deleted keys in soft-delete enabled vaults. It recovers the deleted +// key back to its latest version under /keys. An attempt to recover an non-deleted key will return an error. Consider this +// the inverse of the delete operation on soft-delete enabled vaults. This operation requires the keys/recover permission. +// If the operation fails it returns an *azcore.ResponseError type. +// - name - The name of the deleted key. +// - options - RecoverDeletedKeyOptions contains the optional parameters for the Client.RecoverDeletedKey method. +func (client *Client) RecoverDeletedKey(ctx context.Context, name string, options *RecoverDeletedKeyOptions) (RecoverDeletedKeyResponse, error) { + var err error + const operationName = "Client.RecoverDeletedKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.recoverDeletedKeyCreateRequest(ctx, name, options) + if err != nil { + return RecoverDeletedKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RecoverDeletedKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RecoverDeletedKeyResponse{}, err + } + resp, err := client.recoverDeletedKeyHandleResponse(httpResp) + return resp, err +} + +// recoverDeletedKeyCreateRequest creates the RecoverDeletedKey request. +func (client *Client) recoverDeletedKeyCreateRequest(ctx context.Context, name string, _ *RecoverDeletedKeyOptions) (*policy.Request, error) { + urlPath := "/deletedkeys/{key-name}/recover" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.vaultBaseUrl, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// recoverDeletedKeyHandleResponse handles the RecoverDeletedKey response. +func (client *Client) recoverDeletedKeyHandleResponse(resp *http.Response) (RecoverDeletedKeyResponse, error) { + result := RecoverDeletedKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyBundle); err != nil { + return RecoverDeletedKeyResponse{}, err + } + return result, nil +} + +// Release - Releases a key. +// +// The release key operation is applicable to all key types. The target key must be marked exportable. This operation requires +// the keys/release permission. +// If the operation fails it returns an *azcore.ResponseError type. +// - name - The name of the key to get. +// - version - Adding the version parameter retrieves a specific version of a key. +// - parameters - The parameters for the key release operation. +// - options - ReleaseOptions contains the optional parameters for the Client.Release method. +func (client *Client) Release(ctx context.Context, name string, version string, parameters ReleaseParameters, options *ReleaseOptions) (ReleaseResponse, error) { + var err error + const operationName = "Client.Release" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.releaseCreateRequest(ctx, name, version, parameters, options) + if err != nil { + return ReleaseResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ReleaseResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ReleaseResponse{}, err + } + resp, err := client.releaseHandleResponse(httpResp) + return resp, err +} + +// releaseCreateRequest creates the Release request. +func (client *Client) releaseCreateRequest(ctx context.Context, name string, version string, parameters ReleaseParameters, _ *ReleaseOptions) (*policy.Request, error) { + urlPath := "/keys/{key-name}/{key-version}/release" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) + if version == "" { + return nil, errors.New("parameter version cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(version)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.vaultBaseUrl, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// releaseHandleResponse handles the Release response. +func (client *Client) releaseHandleResponse(resp *http.Response) (ReleaseResponse, error) { + result := ReleaseResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyReleaseResult); err != nil { + return ReleaseResponse{}, err + } + return result, nil +} + +// RestoreKey - Restores a backed up key to a vault. +// +// Imports a previously backed up key into Azure Key Vault, restoring the key, its key identifier, attributes and access control +// policies. The RESTORE operation may be used to import a previously backed up key. Individual versions of a key cannot be +// restored. The key is restored in its entirety with the same key name as it had when it was backed up. If the key name is +// not available in the target Key Vault, the RESTORE operation will be rejected. While the key name is retained during restore, +// the final key identifier will change if the key is restored to a different vault. Restore will restore all versions and +// preserve version identifiers. The RESTORE operation is subject to security constraints: The target Key Vault must be owned +// by the same Microsoft Azure Subscription as the source Key Vault The user must have RESTORE permission in the target Key +// Vault. This operation requires the keys/restore permission. +// If the operation fails it returns an *azcore.ResponseError type. +// - parameters - The parameters to restore the key. +// - options - RestoreKeyOptions contains the optional parameters for the Client.RestoreKey method. +func (client *Client) RestoreKey(ctx context.Context, parameters RestoreKeyParameters, options *RestoreKeyOptions) (RestoreKeyResponse, error) { + var err error + const operationName = "Client.RestoreKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.restoreKeyCreateRequest(ctx, parameters, options) + if err != nil { + return RestoreKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RestoreKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RestoreKeyResponse{}, err + } + resp, err := client.restoreKeyHandleResponse(httpResp) + return resp, err +} + +// restoreKeyCreateRequest creates the RestoreKey request. +func (client *Client) restoreKeyCreateRequest(ctx context.Context, parameters RestoreKeyParameters, _ *RestoreKeyOptions) (*policy.Request, error) { + urlPath := "/keys/restore" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.vaultBaseUrl, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// restoreKeyHandleResponse handles the RestoreKey response. +func (client *Client) restoreKeyHandleResponse(resp *http.Response) (RestoreKeyResponse, error) { + result := RestoreKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyBundle); err != nil { + return RestoreKeyResponse{}, err + } + return result, nil +} + +// RotateKey - Creates a new key version, stores it, then returns key parameters, attributes and policy to the client. +// +// The operation will rotate the key based on the key policy. It requires the keys/rotate permission. +// If the operation fails it returns an *azcore.ResponseError type. +// - name - The name of key to be rotated. The system will generate a new version in the specified key. +// - options - RotateKeyOptions contains the optional parameters for the Client.RotateKey method. +func (client *Client) RotateKey(ctx context.Context, name string, options *RotateKeyOptions) (RotateKeyResponse, error) { + var err error + const operationName = "Client.RotateKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.rotateKeyCreateRequest(ctx, name, options) + if err != nil { + return RotateKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RotateKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RotateKeyResponse{}, err + } + resp, err := client.rotateKeyHandleResponse(httpResp) + return resp, err +} + +// rotateKeyCreateRequest creates the RotateKey request. +func (client *Client) rotateKeyCreateRequest(ctx context.Context, name string, _ *RotateKeyOptions) (*policy.Request, error) { + urlPath := "/keys/{key-name}/rotate" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.vaultBaseUrl, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// rotateKeyHandleResponse handles the RotateKey response. +func (client *Client) rotateKeyHandleResponse(resp *http.Response) (RotateKeyResponse, error) { + result := RotateKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyBundle); err != nil { + return RotateKeyResponse{}, err + } + return result, nil +} + +// SecureUnwrapKey - Securely unwraps a previously wrapped symmetric key using a specified key, ensuring TEE attestation via +// Microsoft Azure Attestation (MAA) before unwrapping. +// +// The SECURE UNWRAP operation supports decryption of a symmetric key using the target key encryption key. This operation +// is the reverse of the SECURE WRAP operation. The SECURE UNWRAP operation applies to asymmetric and symmetric keys stored +// in Azure Key Vault since it uses the private portion of the key. This operation requires the keys/unwrapKey permission. +// The SECURE UNWRAP operation ensures that MAA (Microsoft Azure Attestation Service) is used to attest the TEE (Trusted Execution +// Environment) before the key is unwrapped. +// If the operation fails it returns an *azcore.ResponseError type. +// - name - The name of the key. +// - version - The version of the key. +// - parameters - The parameters for unwrap operation. +// - options - SecureUnwrapKeyOptions contains the optional parameters for the Client.SecureUnwrapKey method. +func (client *Client) SecureUnwrapKey(ctx context.Context, name string, version string, parameters SecureKeyUnWrapOperationParameters, options *SecureUnwrapKeyOptions) (SecureUnwrapKeyResponse, error) { + var err error + const operationName = "Client.SecureUnwrapKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.secureUnwrapKeyCreateRequest(ctx, name, version, parameters, options) + if err != nil { + return SecureUnwrapKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SecureUnwrapKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SecureUnwrapKeyResponse{}, err + } + resp, err := client.secureUnwrapKeyHandleResponse(httpResp) + return resp, err +} + +// secureUnwrapKeyCreateRequest creates the SecureUnwrapKey request. +func (client *Client) secureUnwrapKeyCreateRequest(ctx context.Context, name string, version string, parameters SecureKeyUnWrapOperationParameters, _ *SecureUnwrapKeyOptions) (*policy.Request, error) { + urlPath := "/keys/{key-name}/{key-version}/secureunwrapkey" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) + if version == "" { + return nil, errors.New("parameter version cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(version)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.vaultBaseUrl, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// secureUnwrapKeyHandleResponse handles the SecureUnwrapKey response. +func (client *Client) secureUnwrapKeyHandleResponse(resp *http.Response) (SecureUnwrapKeyResponse, error) { + result := SecureUnwrapKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SecureKeyOperationResult); err != nil { + return SecureUnwrapKeyResponse{}, err + } + return result, nil +} + +// SecureWrapKey - Creates a new 256 bit AES key within the trusted execution environment and wraps this key using a specified +// key. +// +// The SECURE WRAP operation creates a new 256 bit AES key within the trusted execution environment(TEE) and encrypts the +// same with a key encryption key that has previously been stored in an Azure Key Vault. The WRAP operation is only strictly +// necessary for symmetric keys stored in Azure Key Vault since protection with an asymmetric key can be performed using the +// public portion of the key. This operation is supported for asymmetric keys as a convenience for callers that have a key-reference +// but do not have access to the public key material. This operation requires the keys/wrapKey permission. +// If the operation fails it returns an *azcore.ResponseError type. +// - name - The name of the key. +// - version - The version of the key. +// - parameters - The parameters for wrap operation. +// - options - SecureWrapKeyOptions contains the optional parameters for the Client.SecureWrapKey method. +func (client *Client) SecureWrapKey(ctx context.Context, name string, version string, parameters SecureKeyWrapOperationParameters, options *SecureWrapKeyOptions) (SecureWrapKeyResponse, error) { + var err error + const operationName = "Client.SecureWrapKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.secureWrapKeyCreateRequest(ctx, name, version, parameters, options) + if err != nil { + return SecureWrapKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SecureWrapKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SecureWrapKeyResponse{}, err + } + resp, err := client.secureWrapKeyHandleResponse(httpResp) + return resp, err +} + +// secureWrapKeyCreateRequest creates the SecureWrapKey request. +func (client *Client) secureWrapKeyCreateRequest(ctx context.Context, name string, version string, parameters SecureKeyWrapOperationParameters, _ *SecureWrapKeyOptions) (*policy.Request, error) { + urlPath := "/keys/{key-name}/{key-version}/securewrapkey" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) + if version == "" { + return nil, errors.New("parameter version cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(version)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.vaultBaseUrl, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// secureWrapKeyHandleResponse handles the SecureWrapKey response. +func (client *Client) secureWrapKeyHandleResponse(resp *http.Response) (SecureWrapKeyResponse, error) { + result := SecureWrapKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.SecureKeyOperationResult); err != nil { + return SecureWrapKeyResponse{}, err + } + return result, nil +} + +// Sign - Creates a signature from a digest using the specified key. +// +// The SIGN operation is applicable to asymmetric and symmetric keys stored in Azure Key Vault since this operation uses the +// private portion of the key. This operation requires the keys/sign permission. +// If the operation fails it returns an *azcore.ResponseError type. +// - name - The name of the key. +// - version - The version of the key. +// - parameters - The parameters for the signing operation. +// - options - SignOptions contains the optional parameters for the Client.Sign method. +func (client *Client) Sign(ctx context.Context, name string, version string, parameters SignParameters, options *SignOptions) (SignResponse, error) { + var err error + const operationName = "Client.Sign" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.signCreateRequest(ctx, name, version, parameters, options) + if err != nil { + return SignResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return SignResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return SignResponse{}, err + } + resp, err := client.signHandleResponse(httpResp) + return resp, err +} + +// signCreateRequest creates the Sign request. +func (client *Client) signCreateRequest(ctx context.Context, name string, version string, parameters SignParameters, _ *SignOptions) (*policy.Request, error) { + urlPath := "/keys/{key-name}/{key-version}/sign" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) + if version == "" { + return nil, errors.New("parameter version cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(version)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.vaultBaseUrl, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// signHandleResponse handles the Sign response. +func (client *Client) signHandleResponse(resp *http.Response) (SignResponse, error) { + result := SignResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyOperationResult); err != nil { + return SignResponse{}, err + } + return result, nil +} + +// UnwrapKey - Unwraps a symmetric key using the specified key that was initially used for wrapping that key. +// +// The UNWRAP operation supports decryption of a symmetric key using the target key encryption key. This operation is the +// reverse of the WRAP operation. The UNWRAP operation applies to asymmetric and symmetric keys stored in Azure Key Vault +// since it uses the private portion of the key. This operation requires the keys/unwrapKey permission. +// If the operation fails it returns an *azcore.ResponseError type. +// - name - The name of the key. +// - version - The version of the key. +// - parameters - The parameters for the key operation. +// - options - UnwrapKeyOptions contains the optional parameters for the Client.UnwrapKey method. +func (client *Client) UnwrapKey(ctx context.Context, name string, version string, parameters KeyOperationParameters, options *UnwrapKeyOptions) (UnwrapKeyResponse, error) { + var err error + const operationName = "Client.UnwrapKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.unwrapKeyCreateRequest(ctx, name, version, parameters, options) + if err != nil { + return UnwrapKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return UnwrapKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return UnwrapKeyResponse{}, err + } + resp, err := client.unwrapKeyHandleResponse(httpResp) + return resp, err +} + +// unwrapKeyCreateRequest creates the UnwrapKey request. +func (client *Client) unwrapKeyCreateRequest(ctx context.Context, name string, version string, parameters KeyOperationParameters, _ *UnwrapKeyOptions) (*policy.Request, error) { + urlPath := "/keys/{key-name}/{key-version}/unwrapkey" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) + if version == "" { + return nil, errors.New("parameter version cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(version)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.vaultBaseUrl, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// unwrapKeyHandleResponse handles the UnwrapKey response. +func (client *Client) unwrapKeyHandleResponse(resp *http.Response) (UnwrapKeyResponse, error) { + result := UnwrapKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyOperationResult); err != nil { + return UnwrapKeyResponse{}, err + } + return result, nil +} + +// UpdateKey - The update key operation changes specified attributes of a stored key and can be applied to any key type and +// key version stored in Azure Key Vault. +// +// In order to perform this operation, the key must already exist in the Key Vault. Note: The cryptographic material of a +// key itself cannot be changed. This operation requires the keys/update permission. +// If the operation fails it returns an *azcore.ResponseError type. +// - name - The name of key to update. +// - version - The version of the key to update. +// - parameters - The parameters of the key to update. +// - options - UpdateKeyOptions contains the optional parameters for the Client.UpdateKey method. +func (client *Client) UpdateKey(ctx context.Context, name string, version string, parameters UpdateKeyParameters, options *UpdateKeyOptions) (UpdateKeyResponse, error) { + var err error + const operationName = "Client.UpdateKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateKeyCreateRequest(ctx, name, version, parameters, options) + if err != nil { + return UpdateKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return UpdateKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return UpdateKeyResponse{}, err + } + resp, err := client.updateKeyHandleResponse(httpResp) + return resp, err +} + +// updateKeyCreateRequest creates the UpdateKey request. +func (client *Client) updateKeyCreateRequest(ctx context.Context, name string, version string, parameters UpdateKeyParameters, _ *UpdateKeyOptions) (*policy.Request, error) { + urlPath := "/keys/{key-name}/{key-version}" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) + if version == "" { + return nil, errors.New("parameter version cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(version)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.vaultBaseUrl, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// updateKeyHandleResponse handles the UpdateKey response. +func (client *Client) updateKeyHandleResponse(resp *http.Response) (UpdateKeyResponse, error) { + result := UpdateKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyBundle); err != nil { + return UpdateKeyResponse{}, err + } + return result, nil +} + +// UpdateKeyRotationPolicy - Updates the rotation policy for a key. +// +// Set specified members in the key policy. Leave others as undefined. This operation requires the keys/update permission. +// If the operation fails it returns an *azcore.ResponseError type. +// - name - The name of the key in the given vault. +// - keyRotationPolicy - The policy for the key. +// - options - UpdateKeyRotationPolicyOptions contains the optional parameters for the Client.UpdateKeyRotationPolicy method. +func (client *Client) UpdateKeyRotationPolicy(ctx context.Context, name string, keyRotationPolicy KeyRotationPolicy, options *UpdateKeyRotationPolicyOptions) (UpdateKeyRotationPolicyResponse, error) { + var err error + const operationName = "Client.UpdateKeyRotationPolicy" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.updateKeyRotationPolicyCreateRequest(ctx, name, keyRotationPolicy, options) + if err != nil { + return UpdateKeyRotationPolicyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return UpdateKeyRotationPolicyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return UpdateKeyRotationPolicyResponse{}, err + } + resp, err := client.updateKeyRotationPolicyHandleResponse(httpResp) + return resp, err +} + +// updateKeyRotationPolicyCreateRequest creates the UpdateKeyRotationPolicy request. +func (client *Client) updateKeyRotationPolicyCreateRequest(ctx context.Context, name string, keyRotationPolicy KeyRotationPolicy, _ *UpdateKeyRotationPolicyOptions) (*policy.Request, error) { + urlPath := "/keys/{key-name}/rotationpolicy" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.vaultBaseUrl, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, keyRotationPolicy); err != nil { + return nil, err + } + return req, nil +} + +// updateKeyRotationPolicyHandleResponse handles the UpdateKeyRotationPolicy response. +func (client *Client) updateKeyRotationPolicyHandleResponse(resp *http.Response) (UpdateKeyRotationPolicyResponse, error) { + result := UpdateKeyRotationPolicyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyRotationPolicy); err != nil { + return UpdateKeyRotationPolicyResponse{}, err + } + return result, nil +} + +// Verify - Verifies a signature using a specified key. +// +// The VERIFY operation is applicable to symmetric keys stored in Azure Key Vault. VERIFY is not strictly necessary for asymmetric +// keys stored in Azure Key Vault since signature verification can be performed using the public portion of the key but this +// operation is supported as a convenience for callers that only have a key-reference and not the public portion of the key. +// This operation requires the keys/verify permission. +// If the operation fails it returns an *azcore.ResponseError type. +// - name - The name of the key. +// - version - The version of the key. +// - parameters - The parameters for verify operations. +// - options - VerifyOptions contains the optional parameters for the Client.Verify method. +func (client *Client) Verify(ctx context.Context, name string, version string, parameters VerifyParameters, options *VerifyOptions) (VerifyResponse, error) { + var err error + const operationName = "Client.Verify" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.verifyCreateRequest(ctx, name, version, parameters, options) + if err != nil { + return VerifyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return VerifyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return VerifyResponse{}, err + } + resp, err := client.verifyHandleResponse(httpResp) + return resp, err +} + +// verifyCreateRequest creates the Verify request. +func (client *Client) verifyCreateRequest(ctx context.Context, name string, version string, parameters VerifyParameters, _ *VerifyOptions) (*policy.Request, error) { + urlPath := "/keys/{key-name}/{key-version}/verify" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) + if version == "" { + return nil, errors.New("parameter version cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(version)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.vaultBaseUrl, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// verifyHandleResponse handles the Verify response. +func (client *Client) verifyHandleResponse(resp *http.Response) (VerifyResponse, error) { + result := VerifyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyVerifyResult); err != nil { + return VerifyResponse{}, err + } + return result, nil +} + +// WrapKey - Wraps a symmetric key using a specified key. +// +// The WRAP operation supports encryption of a symmetric key using a key encryption key that has previously been stored in +// an Azure Key Vault. The WRAP operation is only strictly necessary for symmetric keys stored in Azure Key Vault since protection +// with an asymmetric key can be performed using the public portion of the key. This operation is supported for asymmetric +// keys as a convenience for callers that have a key-reference but do not have access to the public key material. This operation +// requires the keys/wrapKey permission. +// If the operation fails it returns an *azcore.ResponseError type. +// - name - The name of the key. +// - version - The version of the key. +// - parameters - The parameters for wrap operation. +// - options - WrapKeyOptions contains the optional parameters for the Client.WrapKey method. +func (client *Client) WrapKey(ctx context.Context, name string, version string, parameters KeyOperationParameters, options *WrapKeyOptions) (WrapKeyResponse, error) { + var err error + const operationName = "Client.WrapKey" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.wrapKeyCreateRequest(ctx, name, version, parameters, options) + if err != nil { + return WrapKeyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return WrapKeyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return WrapKeyResponse{}, err + } + resp, err := client.wrapKeyHandleResponse(httpResp) + return resp, err +} + +// wrapKeyCreateRequest creates the WrapKey request. +func (client *Client) wrapKeyCreateRequest(ctx context.Context, name string, version string, parameters KeyOperationParameters, _ *WrapKeyOptions) (*policy.Request, error) { + urlPath := "/keys/{key-name}/{key-version}/wrapkey" + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-name}", url.PathEscape(name)) + if version == "" { + return nil, errors.New("parameter version cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key-version}", url.PathEscape(version)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.vaultBaseUrl, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", version20260501Preview) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, parameters); err != nil { + return nil, err + } + return req, nil +} + +// wrapKeyHandleResponse handles the WrapKey response. +func (client *Client) wrapKeyHandleResponse(resp *http.Response) (WrapKeyResponse, error) { + result := WrapKeyResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.KeyOperationResult); err != nil { + return WrapKeyResponse{}, err + } + return result, nil +} diff --git a/test/local/azkeys/zz_constants.go b/test/local/azkeys/zz_constants.go new file mode 100644 index 000000000000..173a8d2b5c38 --- /dev/null +++ b/test/local/azkeys/zz_constants.go @@ -0,0 +1,331 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azkeys + +const ( + version20260501Preview string = "2026-05-01-preview" +) + +// AKPAlgorithm - The algorithm identifier for Algorithm Key Pair (AKP) keys. +type AKPAlgorithm string + +const ( + // AKPAlgorithmMLDSA44 - ML-DSA-44, as defined by FIPS 204 and draft-ietf-cose-dilithium. + AKPAlgorithmMLDSA44 AKPAlgorithm = "ML-DSA-44" + // AKPAlgorithmMLDSA65 - ML-DSA-65, as defined by FIPS 204 and draft-ietf-cose-dilithium. + AKPAlgorithmMLDSA65 AKPAlgorithm = "ML-DSA-65" + // AKPAlgorithmMLDSA87 - ML-DSA-87, as defined by FIPS 204 and draft-ietf-cose-dilithium. + AKPAlgorithmMLDSA87 AKPAlgorithm = "ML-DSA-87" +) + +// PossibleAKPAlgorithmValues returns the possible values for the AKPAlgorithm const type. +func PossibleAKPAlgorithmValues() []AKPAlgorithm { + return []AKPAlgorithm{ + AKPAlgorithmMLDSA44, + AKPAlgorithmMLDSA65, + AKPAlgorithmMLDSA87, + } +} + +// CurveName - Elliptic curve name. For valid values, see JsonWebKeyCurveName. +type CurveName string + +const ( + // CurveNameP256 - The NIST P-256 elliptic curve, AKA SECG curve SECP256R1. + CurveNameP256 CurveName = "P-256" + // CurveNameP256K - The SECG SECP256K1 elliptic curve. + CurveNameP256K CurveName = "P-256K" + // CurveNameP384 - The NIST P-384 elliptic curve, AKA SECG curve SECP384R1. + CurveNameP384 CurveName = "P-384" + // CurveNameP521 - The NIST P-521 elliptic curve, AKA SECG curve SECP521R1. + CurveNameP521 CurveName = "P-521" +) + +// PossibleCurveNameValues returns the possible values for the CurveName const type. +func PossibleCurveNameValues() []CurveName { + return []CurveName{ + CurveNameP256, + CurveNameP256K, + CurveNameP384, + CurveNameP521, + } +} + +// EncryptionAlgorithm - An algorithm used for encryption and decryption. +type EncryptionAlgorithm string + +const ( + // EncryptionAlgorithmA128CBC - 128-bit AES-CBC. + EncryptionAlgorithmA128CBC EncryptionAlgorithm = "A128CBC" + // EncryptionAlgorithmA128CBCPAD - 128-bit AES-CBC with PKCS padding. + EncryptionAlgorithmA128CBCPAD EncryptionAlgorithm = "A128CBCPAD" + // EncryptionAlgorithmA128GCM - 128-bit AES-GCM. + EncryptionAlgorithmA128GCM EncryptionAlgorithm = "A128GCM" + // EncryptionAlgorithmA128KW - 128-bit AES key wrap. + EncryptionAlgorithmA128KW EncryptionAlgorithm = "A128KW" + // EncryptionAlgorithmA192CBC - 192-bit AES-CBC. + EncryptionAlgorithmA192CBC EncryptionAlgorithm = "A192CBC" + // EncryptionAlgorithmA192CBCPAD - 192-bit AES-CBC with PKCS padding. + EncryptionAlgorithmA192CBCPAD EncryptionAlgorithm = "A192CBCPAD" + // EncryptionAlgorithmA192GCM - 192-bit AES-GCM. + EncryptionAlgorithmA192GCM EncryptionAlgorithm = "A192GCM" + // EncryptionAlgorithmA192KW - 192-bit AES key wrap. + EncryptionAlgorithmA192KW EncryptionAlgorithm = "A192KW" + // EncryptionAlgorithmA256CBC - 256-bit AES-CBC. + EncryptionAlgorithmA256CBC EncryptionAlgorithm = "A256CBC" + // EncryptionAlgorithmA256CBCPAD - 256-bit AES-CBC with PKCS padding. + EncryptionAlgorithmA256CBCPAD EncryptionAlgorithm = "A256CBCPAD" + // EncryptionAlgorithmA256GCM - 256-bit AES-GCM. + EncryptionAlgorithmA256GCM EncryptionAlgorithm = "A256GCM" + // EncryptionAlgorithmA256KW - 256-bit AES key wrap. + EncryptionAlgorithmA256KW EncryptionAlgorithm = "A256KW" + // EncryptionAlgorithmCKMAESKEYWRAP - CKM AES key wrap. + EncryptionAlgorithmCKMAESKEYWRAP EncryptionAlgorithm = "CKM_AES_KEY_WRAP" + // EncryptionAlgorithmCKMAESKEYWRAPPAD - CKM AES key wrap with padding. + EncryptionAlgorithmCKMAESKEYWRAPPAD EncryptionAlgorithm = "CKM_AES_KEY_WRAP_PAD" + // EncryptionAlgorithmRSA15 - [Not recommended] RSAES-PKCS1-V1_5 key encryption, as described in https://tools.ietf.org/html/rfc3447. + // Microsoft recommends using RSA_OAEP_256 or stronger algorithms for enhanced security. Microsoft does *not* recommend RSA_1_5, + // which is included solely for backwards compatibility. Cryptographic standards no longer consider RSA with the PKCS#1 v1.5 + // padding scheme secure for encryption. + EncryptionAlgorithmRSA15 EncryptionAlgorithm = "RSA1_5" + // EncryptionAlgorithmRSAOAEP - [Not recommended] RSAES using Optimal Asymmetric Encryption Padding (OAEP), as described in + // https://tools.ietf.org/html/rfc3447, with the default parameters specified by RFC 3447 in Section A.2.1. Those default + // parameters are using a hash function of SHA-1 and a mask generation function of MGF1 with SHA-1. Microsoft recommends using + // RSA_OAEP_256 or stronger algorithms for enhanced security. Microsoft does *not* recommend RSA_OAEP, which is included solely + // for backwards compatibility. RSA_OAEP utilizes SHA1, which has known collision problems. + EncryptionAlgorithmRSAOAEP EncryptionAlgorithm = "RSA-OAEP" + // EncryptionAlgorithmRSAOAEP256 - RSAES using Optimal Asymmetric Encryption Padding with a hash function of SHA-256 and a + // mask generation function of MGF1 with SHA-256. + EncryptionAlgorithmRSAOAEP256 EncryptionAlgorithm = "RSA-OAEP-256" +) + +// PossibleEncryptionAlgorithmValues returns the possible values for the EncryptionAlgorithm const type. +func PossibleEncryptionAlgorithmValues() []EncryptionAlgorithm { + return []EncryptionAlgorithm{ + EncryptionAlgorithmA128CBC, + EncryptionAlgorithmA128CBCPAD, + EncryptionAlgorithmA128GCM, + EncryptionAlgorithmA128KW, + EncryptionAlgorithmA192CBC, + EncryptionAlgorithmA192CBCPAD, + EncryptionAlgorithmA192GCM, + EncryptionAlgorithmA192KW, + EncryptionAlgorithmA256CBC, + EncryptionAlgorithmA256CBCPAD, + EncryptionAlgorithmA256GCM, + EncryptionAlgorithmA256KW, + EncryptionAlgorithmCKMAESKEYWRAP, + EncryptionAlgorithmCKMAESKEYWRAPPAD, + EncryptionAlgorithmRSA15, + EncryptionAlgorithmRSAOAEP, + EncryptionAlgorithmRSAOAEP256, + } +} + +// JSONWebKeyWrapAlgorithm - An algorithm used for key wrapping and unwrapping. +type JSONWebKeyWrapAlgorithm string + +const ( + // JSONWebKeyWrapAlgorithmA128KW - 128-bit AES key wrap. + JSONWebKeyWrapAlgorithmA128KW JSONWebKeyWrapAlgorithm = "A128KW" + // JSONWebKeyWrapAlgorithmA128KWPAD - 128-bit AES key wrap with padding. + JSONWebKeyWrapAlgorithmA128KWPAD JSONWebKeyWrapAlgorithm = "A128KWPAD" + // JSONWebKeyWrapAlgorithmA192KW - 192-bit AES key wrap. + JSONWebKeyWrapAlgorithmA192KW JSONWebKeyWrapAlgorithm = "A192KW" + // JSONWebKeyWrapAlgorithmA192KWPAD - 192-bit AES key wrap with padding. + JSONWebKeyWrapAlgorithmA192KWPAD JSONWebKeyWrapAlgorithm = "A192KWPAD" + // JSONWebKeyWrapAlgorithmA256KW - 256-bit AES key wrap. + JSONWebKeyWrapAlgorithmA256KW JSONWebKeyWrapAlgorithm = "A256KW" + // JSONWebKeyWrapAlgorithmA256KWPAD - 256-bit AES key wrap with padding. + JSONWebKeyWrapAlgorithmA256KWPAD JSONWebKeyWrapAlgorithm = "A256KWPAD" + // JSONWebKeyWrapAlgorithmCKMAESKEYWRAP - CKM AES key wrap. + JSONWebKeyWrapAlgorithmCKMAESKEYWRAP JSONWebKeyWrapAlgorithm = "CKM_AES_KEY_WRAP" + // JSONWebKeyWrapAlgorithmCKMAESKEYWRAPPAD - CKM AES key wrap with padding. + JSONWebKeyWrapAlgorithmCKMAESKEYWRAPPAD JSONWebKeyWrapAlgorithm = "CKM_AES_KEY_WRAP_PAD" + // JSONWebKeyWrapAlgorithmRSAOAEP256 - RSAES using Optimal Asymmetric Encryption Padding with a hash function of SHA-256 and + // a mask generation function of MGF1 with SHA-256. + JSONWebKeyWrapAlgorithmRSAOAEP256 JSONWebKeyWrapAlgorithm = "RSA-OAEP-256" +) + +// PossibleJSONWebKeyWrapAlgorithmValues returns the possible values for the JSONWebKeyWrapAlgorithm const type. +func PossibleJSONWebKeyWrapAlgorithmValues() []JSONWebKeyWrapAlgorithm { + return []JSONWebKeyWrapAlgorithm{ + JSONWebKeyWrapAlgorithmA128KW, + JSONWebKeyWrapAlgorithmA128KWPAD, + JSONWebKeyWrapAlgorithmA192KW, + JSONWebKeyWrapAlgorithmA192KWPAD, + JSONWebKeyWrapAlgorithmA256KW, + JSONWebKeyWrapAlgorithmA256KWPAD, + JSONWebKeyWrapAlgorithmCKMAESKEYWRAP, + JSONWebKeyWrapAlgorithmCKMAESKEYWRAPPAD, + JSONWebKeyWrapAlgorithmRSAOAEP256, + } +} + +// KeyEncryptionAlgorithm - The encryption algorithm to use to protected the exported key material +type KeyEncryptionAlgorithm string + +const ( + // KeyEncryptionAlgorithmCKMRSAAESKEYWRAP - The CKM_RSA_AES_KEY_WRAP key wrap mechanism. + KeyEncryptionAlgorithmCKMRSAAESKEYWRAP KeyEncryptionAlgorithm = "CKM_RSA_AES_KEY_WRAP" + // KeyEncryptionAlgorithmRSAAESKEYWRAP256 - The RSA_AES_KEY_WRAP_256 key wrap mechanism. + KeyEncryptionAlgorithmRSAAESKEYWRAP256 KeyEncryptionAlgorithm = "RSA_AES_KEY_WRAP_256" + // KeyEncryptionAlgorithmRSAAESKEYWRAP384 - The RSA_AES_KEY_WRAP_384 key wrap mechanism. + KeyEncryptionAlgorithmRSAAESKEYWRAP384 KeyEncryptionAlgorithm = "RSA_AES_KEY_WRAP_384" +) + +// PossibleKeyEncryptionAlgorithmValues returns the possible values for the KeyEncryptionAlgorithm const type. +func PossibleKeyEncryptionAlgorithmValues() []KeyEncryptionAlgorithm { + return []KeyEncryptionAlgorithm{ + KeyEncryptionAlgorithmCKMRSAAESKEYWRAP, + KeyEncryptionAlgorithmRSAAESKEYWRAP256, + KeyEncryptionAlgorithmRSAAESKEYWRAP384, + } +} + +// KeyOperation - JSON web key operations. For more information, see JsonWebKeyOperation. +type KeyOperation string + +const ( + // KeyOperationDecrypt - Indicates that the key can be used to decrypt. + KeyOperationDecrypt KeyOperation = "decrypt" + // KeyOperationEncrypt - Indicates that the key can be used to encrypt. + KeyOperationEncrypt KeyOperation = "encrypt" + // KeyOperationExport - Indicates that the private component of the key can be exported. + KeyOperationExport KeyOperation = "export" + // KeyOperationImport - Indicates that the key can be imported during creation. + KeyOperationImport KeyOperation = "import" + // KeyOperationSign - Indicates that the key can be used to sign. + KeyOperationSign KeyOperation = "sign" + // KeyOperationUnwrapKey - Indicates that the key can be used to unwrap another key. + KeyOperationUnwrapKey KeyOperation = "unwrapKey" + // KeyOperationVerify - Indicates that the key can be used to verify. + KeyOperationVerify KeyOperation = "verify" + // KeyOperationWrapKey - Indicates that the key can be used to wrap another key. + KeyOperationWrapKey KeyOperation = "wrapKey" +) + +// PossibleKeyOperationValues returns the possible values for the KeyOperation const type. +func PossibleKeyOperationValues() []KeyOperation { + return []KeyOperation{ + KeyOperationDecrypt, + KeyOperationEncrypt, + KeyOperationExport, + KeyOperationImport, + KeyOperationSign, + KeyOperationUnwrapKey, + KeyOperationVerify, + KeyOperationWrapKey, + } +} + +// KeyRotationPolicyAction - The type of the action. The value should be compared case-insensitively. +type KeyRotationPolicyAction string + +const ( + // KeyRotationPolicyActionNotify - Trigger Event Grid events. Defaults to 30 days before expiry. Key Vault only. + KeyRotationPolicyActionNotify KeyRotationPolicyAction = "Notify" + // KeyRotationPolicyActionRotate - Rotate the key based on the key policy. + KeyRotationPolicyActionRotate KeyRotationPolicyAction = "Rotate" +) + +// PossibleKeyRotationPolicyActionValues returns the possible values for the KeyRotationPolicyAction const type. +func PossibleKeyRotationPolicyActionValues() []KeyRotationPolicyAction { + return []KeyRotationPolicyAction{ + KeyRotationPolicyActionNotify, + KeyRotationPolicyActionRotate, + } +} + +// KeyType - JsonWebKey Key Type (kty), as defined in https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. +type KeyType string + +const ( + // KeyTypeAKP - Algorithm Key Pair. + KeyTypeAKP KeyType = "AKP" + // KeyTypeAKPHSM - Algorithm Key Pair with private key material stored in HSM. + KeyTypeAKPHSM KeyType = "AKP-HSM" + // KeyTypeEC - Elliptic Curve. + KeyTypeEC KeyType = "EC" + // KeyTypeECHSM - Elliptic Curve with a private key which is stored in the HSM. + KeyTypeECHSM KeyType = "EC-HSM" + // KeyTypeOct - Octet sequence (used to represent symmetric keys) + KeyTypeOct KeyType = "oct" + // KeyTypeOctHSM - Octet sequence (used to represent symmetric keys) which is stored the HSM. + KeyTypeOctHSM KeyType = "oct-HSM" + // KeyTypeRSA - RSA (https://tools.ietf.org/html/rfc3447) + KeyTypeRSA KeyType = "RSA" + // KeyTypeRSAHSM - RSA with a private key which is stored in the HSM. + KeyTypeRSAHSM KeyType = "RSA-HSM" +) + +// PossibleKeyTypeValues returns the possible values for the KeyType const type. +func PossibleKeyTypeValues() []KeyType { + return []KeyType{ + KeyTypeAKP, + KeyTypeAKPHSM, + KeyTypeEC, + KeyTypeECHSM, + KeyTypeOct, + KeyTypeOctHSM, + KeyTypeRSA, + KeyTypeRSAHSM, + } +} + +// SignatureAlgorithm - The signing/verification algorithm identifier. For more information on possible algorithm types, see +// JsonWebKeySignatureAlgorithm. +type SignatureAlgorithm string + +const ( + // SignatureAlgorithmES256 - ECDSA using P-256 and SHA-256, as described in https://tools.ietf.org/html/rfc7518. + SignatureAlgorithmES256 SignatureAlgorithm = "ES256" + // SignatureAlgorithmES256K - ECDSA using P-256K and SHA-256, as described in https://tools.ietf.org/html/rfc7518 + SignatureAlgorithmES256K SignatureAlgorithm = "ES256K" + // SignatureAlgorithmES384 - ECDSA using P-384 and SHA-384, as described in https://tools.ietf.org/html/rfc7518 + SignatureAlgorithmES384 SignatureAlgorithm = "ES384" + // SignatureAlgorithmES512 - ECDSA using P-521 and SHA-512, as described in https://tools.ietf.org/html/rfc7518 + SignatureAlgorithmES512 SignatureAlgorithm = "ES512" + // SignatureAlgorithmHS256 - HMAC using SHA-256, as described in https://tools.ietf.org/html/rfc7518 + SignatureAlgorithmHS256 SignatureAlgorithm = "HS256" + // SignatureAlgorithmHS384 - HMAC using SHA-384, as described in https://tools.ietf.org/html/rfc7518 + SignatureAlgorithmHS384 SignatureAlgorithm = "HS384" + // SignatureAlgorithmHS512 - HMAC using SHA-512, as described in https://tools.ietf.org/html/rfc7518 + SignatureAlgorithmHS512 SignatureAlgorithm = "HS512" + // SignatureAlgorithmPS256 - RSASSA-PSS using SHA-256 and MGF1 with SHA-256, as described in https://tools.ietf.org/html/rfc7518 + SignatureAlgorithmPS256 SignatureAlgorithm = "PS256" + // SignatureAlgorithmPS384 - RSASSA-PSS using SHA-384 and MGF1 with SHA-384, as described in https://tools.ietf.org/html/rfc7518 + SignatureAlgorithmPS384 SignatureAlgorithm = "PS384" + // SignatureAlgorithmPS512 - RSASSA-PSS using SHA-512 and MGF1 with SHA-512, as described in https://tools.ietf.org/html/rfc7518 + SignatureAlgorithmPS512 SignatureAlgorithm = "PS512" + // SignatureAlgorithmRS256 - RSASSA-PKCS1-v1_5 using SHA-256, as described in https://tools.ietf.org/html/rfc7518 + SignatureAlgorithmRS256 SignatureAlgorithm = "RS256" + // SignatureAlgorithmRS384 - RSASSA-PKCS1-v1_5 using SHA-384, as described in https://tools.ietf.org/html/rfc7518 + SignatureAlgorithmRS384 SignatureAlgorithm = "RS384" + // SignatureAlgorithmRS512 - RSASSA-PKCS1-v1_5 using SHA-512, as described in https://tools.ietf.org/html/rfc7518 + SignatureAlgorithmRS512 SignatureAlgorithm = "RS512" + // SignatureAlgorithmRSNULL - Reserved + SignatureAlgorithmRSNULL SignatureAlgorithm = "RSNULL" +) + +// PossibleSignatureAlgorithmValues returns the possible values for the SignatureAlgorithm const type. +func PossibleSignatureAlgorithmValues() []SignatureAlgorithm { + return []SignatureAlgorithm{ + SignatureAlgorithmES256, + SignatureAlgorithmES256K, + SignatureAlgorithmES384, + SignatureAlgorithmES512, + SignatureAlgorithmHS256, + SignatureAlgorithmHS384, + SignatureAlgorithmHS512, + SignatureAlgorithmPS256, + SignatureAlgorithmPS384, + SignatureAlgorithmPS512, + SignatureAlgorithmRS256, + SignatureAlgorithmRS384, + SignatureAlgorithmRS512, + SignatureAlgorithmRSNULL, + } +} diff --git a/test/local/azkeys/zz_models.go b/test/local/azkeys/zz_models.go new file mode 100644 index 000000000000..1b3855522290 --- /dev/null +++ b/test/local/azkeys/zz_models.go @@ -0,0 +1,514 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azkeys + +import "time" + +// BackupKeyResult - The backup key result, containing the backup blob. +type BackupKeyResult struct { + // READ-ONLY; The backup blob containing the backed up key. + Value []byte +} + +// CreateKeyParameters - The key create parameters. +type CreateKeyParameters struct { + // REQUIRED; The type of key to create. For valid values, see JsonWebKeyType. + Kty *KeyType + + // The algorithm for Algorithm Key Pair (AKP) keys. For valid values, see AKPAlgorithm. + Alg *AKPAlgorithm + + // Elliptic curve name. For valid values, see JsonWebKeyCurveName. + Curve *CurveName + + // The attributes of a key managed by the key vault service. + KeyAttributes *KeyAttributes + + // Json web key operations. For more information on possible key operations, see JsonWebKeyOperation. + KeyOps []*KeyOperation + + // The key size in bits. For example: 2048, 3072, or 4096 for RSA. + KeySize *int32 + + // The public exponent for a RSA key. + PublicExponent *int32 + + // The policy rules under which the key can be exported. + ReleasePolicy *KeyReleasePolicy + + // Application specific metadata in the form of key-value pairs. + Tags map[string]*string +} + +// DeletedKey - A DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info +type DeletedKey struct { + // The key management attributes. + Attributes *KeyAttributes + + // The Json web key. + Key *JSONWebKey + + // The url of the recovery object, used to identify and recover the deleted key. + RecoveryID *string + + // The policy rules under which the key can be exported. + ReleasePolicy *KeyReleasePolicy + + // Application specific metadata in the form of key-value pairs. + Tags map[string]*string + + // READ-ONLY; The time when the key was deleted, in UTC + DeletedDate *time.Time + + // READ-ONLY; True if the key's lifetime is managed by key vault. If this is a key backing a certificate, then managed will + // be true. + Managed *bool + + // READ-ONLY; The time when the key is scheduled to be purged, in UTC + ScheduledPurgeDate *time.Time +} + +// DeletedKeyProperties - The deleted key item containing the deleted key metadata and information about deletion. +type DeletedKeyProperties struct { + // The key management attributes. + Attributes *KeyAttributes + + // Key identifier. + KID *string + + // The url of the recovery object, used to identify and recover the deleted key. + RecoveryID *string + + // Application specific metadata in the form of key-value pairs. + Tags map[string]*string + + // READ-ONLY; The time when the key was deleted, in UTC + DeletedDate *time.Time + + // READ-ONLY; True if the key's lifetime is managed by key vault. If this is a key backing a certificate, then managed will + // be true. + Managed *bool + + // READ-ONLY; The time when the key is scheduled to be purged, in UTC + ScheduledPurgeDate *time.Time +} + +// DeletedKeyPropertiesListResult - A list of keys that have been deleted in this vault. +type DeletedKeyPropertiesListResult struct { + // READ-ONLY; The URL to get the next set of deleted keys. + NextLink *string + + // READ-ONLY; A response message containing a list of deleted keys in the key vault along with a link to the next page of + // deleted keys. + Value []*DeletedKeyProperties +} + +// ExternalKey - External Key parameters. +type ExternalKey struct { + // REQUIRED; The external key identifier. The valid id can only contain characters in the set [a-zA-Z0-9-]. Maximum length + // is 64 characters. + ID *string +} + +// GetRandomBytesParameters - The get random bytes request object. +type GetRandomBytesParameters struct { + // REQUIRED; The requested number of random bytes. + Count *int32 +} + +// ImportKeyParameters - The key import parameters. +type ImportKeyParameters struct { + // REQUIRED; The Json web key + Key *JSONWebKey + + // Whether to import as a hardware key (HSM) or software key. + HSM *bool + + // The key management attributes. + KeyAttributes *KeyAttributes + + // The policy rules under which the key can be exported. + ReleasePolicy *KeyReleasePolicy + + // Application specific metadata in the form of key-value pairs. + Tags map[string]*string +} + +// JSONWebKey - As of http://tools.ietf.org/html/draft-ietf-jose-json-web-key-18 +type JSONWebKey struct { + // The algorithm identifier. This parameter is required when kty is AKP. + Alg *AKPAlgorithm + + // Elliptic curve name. For valid values, see JsonWebKeyCurveName. + Crv *CurveName + + // RSA private exponent, or the D component of an EC private key. + D []byte + + // RSA private key parameter. + DP []byte + + // RSA private key parameter. + DQ []byte + + // RSA public exponent. + E []byte + + // Symmetric key. + K []byte + + // Key identifier. + KID *string + + // Json web key operations. For more information on possible key operations, see JsonWebKeyOperation. + KeyOps []*KeyOperation + + // JsonWebKey Key Type (kty), as defined in https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40. + Kty *KeyType + + // RSA modulus. + N []byte + + // RSA secret prime. + P []byte + + // The public key for Algorithm Key Pair (AKP) keys. + Pub []byte + + // RSA secret prime, with p < q. + Q []byte + + // RSA private key parameter. + QI []byte + + // Protected Key, used with 'Bring Your Own Key'. + T []byte + + // X component of an EC public key. + X []byte + + // Y component of an EC public key. + Y []byte +} + +// KeyAttestation - The key attestation information. +type KeyAttestation struct { + // A base64url-encoded string containing certificates in PEM format, used for attestation validation. + CertificatePEMFile []byte + + // The attestation blob bytes encoded as base64url string corresponding to a private key. + PrivateKeyAttestation []byte + + // The attestation blob bytes encoded as base64url string corresponding to a public key in case of asymmetric key. + PublicKeyAttestation []byte + + // The version of the attestation. + Version *string +} + +// KeyAttributes - The attributes of a key managed by the key vault service. +type KeyAttributes struct { + // Determines whether the object is enabled. + Enabled *bool + + // Expiry date in UTC. + Expires *time.Time + + // Indicates if the private key can be exported. Release policy must be provided when creating the first version of an exportable + // key. + Exportable *bool + + // The external key information. + ExternalKey *ExternalKey + + // Not before date in UTC. + NotBefore *time.Time + + // READ-ONLY; The key or key version attestation information. + Attestation *KeyAttestation + + // READ-ONLY; Creation time in UTC. + Created *time.Time + + // READ-ONLY; The underlying HSM Platform. + HSMPlatform *string + + // READ-ONLY; The optional key size in bits for symmetric keys. For example: 128, 192, or 256 for AES keys. + KeySize *int32 + + // READ-ONLY; softDelete data retention days. Value should be >=7 and <=90 when softDelete enabled, otherwise 0. + RecoverableDays *int32 + + // READ-ONLY; Reflects the deletion recovery level currently in effect for keys in the current vault. If it contains 'Purgeable' + // the key can be permanently deleted by a privileged user; otherwise, only the system can purge the key, at the end of the + // retention interval. + RecoveryLevel *string + + // READ-ONLY; Last updated time in UTC. + Updated *time.Time +} + +// KeyBundle - A KeyBundle consisting of a WebKey plus its attributes. +type KeyBundle struct { + // The key management attributes. + Attributes *KeyAttributes + + // The Json web key. + Key *JSONWebKey + + // The policy rules under which the key can be exported. + ReleasePolicy *KeyReleasePolicy + + // Application specific metadata in the form of key-value pairs. + Tags map[string]*string + + // READ-ONLY; True if the key's lifetime is managed by key vault. If this is a key backing a certificate, then managed will + // be true. + Managed *bool +} + +// KeyOperationParameters - The key operations parameters. +type KeyOperationParameters struct { + // REQUIRED; algorithm identifier + Algorithm *EncryptionAlgorithm + + // REQUIRED; The value to operate on. + Value []byte + + // Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. + AdditionalAuthenticatedData []byte + + // The tag to authenticate when performing decryption with an authenticated algorithm. + AuthenticationTag []byte + + // Cryptographically random, non-repeating initialization vector for symmetric algorithms. + IV []byte +} + +// KeyOperationResult - The key operation result. +type KeyOperationResult struct { + // READ-ONLY; Additional data to authenticate but not encrypt/decrypt when using authenticated crypto algorithms. + AdditionalAuthenticatedData []byte + + // READ-ONLY; The tag to authenticate when performing decryption with an authenticated algorithm. + AuthenticationTag []byte + + // READ-ONLY; Cryptographically random, non-repeating initialization vector for symmetric algorithms. + IV []byte + + // READ-ONLY; Key identifier + KID *string + + // READ-ONLY; The result of the operation. + Result []byte +} + +// KeyProperties - The key item containing key metadata. +type KeyProperties struct { + // The key management attributes. + Attributes *KeyAttributes + + // Key identifier. + KID *string + + // Application specific metadata in the form of key-value pairs. + Tags map[string]*string + + // READ-ONLY; True if the key's lifetime is managed by key vault. If this is a key backing a certificate, then managed will + // be true. + Managed *bool +} + +// KeyPropertiesListResult - The key list result. +type KeyPropertiesListResult struct { + // READ-ONLY; The URL to get the next set of keys. + NextLink *string + + // READ-ONLY; A response message containing a list of keys in the key vault along with a link to the next page of keys. + Value []*KeyProperties +} + +// KeyReleasePolicy - The policy rules under which the key can be exported. +type KeyReleasePolicy struct { + // Content type and version of key release policy + ContentType *string + + // Blob encoding the policy rules under which the key can be released. Blob must be base64 URL encoded. + EncodedPolicy []byte + + // Defines the mutability state of the policy. Once marked immutable, this flag cannot be reset and the policy cannot be changed + // under any circumstances. + Immutable *bool +} + +// KeyReleaseResult - The release result, containing the released key. +type KeyReleaseResult struct { + // READ-ONLY; A signed object containing the released key. + Value *string +} + +// KeyRotationPolicy - Management policy for a key. +type KeyRotationPolicy struct { + // The key rotation policy attributes. + Attributes *KeyRotationPolicyAttributes + + // Actions that will be performed by Key Vault over the lifetime of a key. For preview, lifetimeActions can only have two + // items at maximum: one for rotate, one for notify. Notification time would be default to 30 days before expiry and it is + // not configurable. + LifetimeActions []*LifetimeAction + + // READ-ONLY; The key policy id. + ID *string +} + +// KeyRotationPolicyAttributes - The key rotation policy attributes. +type KeyRotationPolicyAttributes struct { + // The expiryTime will be applied on the new key version. It should be at least 28 days. It will be in ISO 8601 Format. Examples: + // 90 days: P90D, 3 months: P3M, 48 hours: PT48H, 1 year and 10 days: P1Y10D + ExpiryTime *string + + // READ-ONLY; The key rotation policy created time in UTC. + Created *time.Time + + // READ-ONLY; The key rotation policy's last updated time in UTC. + Updated *time.Time +} + +// KeyVerifyResult - The key verify result. +type KeyVerifyResult struct { + // READ-ONLY; True if the signature is verified, otherwise false. + Value *bool +} + +// LifetimeAction - Action and its trigger that will be performed by Key Vault over the lifetime of a key. +type LifetimeAction struct { + // The action that will be executed. + Action *LifetimeActionType + + // The condition that will execute the action. + Trigger *LifetimeActionTrigger +} + +// LifetimeActionTrigger - A condition to be satisfied for an action to be executed. +type LifetimeActionTrigger struct { + // Time after creation to attempt to rotate. It only applies to rotate. It will be in ISO 8601 duration format. Example: 90 + // days : "P90D" + TimeAfterCreate *string + + // Time before expiry to attempt to rotate or notify. It will be in ISO 8601 duration format. Example: 90 days : "P90D" + TimeBeforeExpiry *string +} + +// LifetimeActionType - The action that will be executed. +type LifetimeActionType struct { + // The type of the action. The value should be compared case-insensitively. + Type *KeyRotationPolicyAction +} + +// RandomBytes - The get random bytes response object containing the bytes. +type RandomBytes struct { + // REQUIRED; The bytes encoded as a base64url string. + Value []byte +} + +// ReleaseParameters - The release key parameters. +type ReleaseParameters struct { + // REQUIRED; The attestation assertion for the target of the key release. + TargetAttestationToken *string + + // The encryption algorithm to use to protected the exported key material + Algorithm *KeyEncryptionAlgorithm + + // A client provided nonce for freshness. + Nonce *string +} + +// RestoreKeyParameters - The key restore parameters. +type RestoreKeyParameters struct { + // REQUIRED; The backup blob associated with a key bundle. + KeyBackup []byte +} + +// SecureKeyOperationResult - The secure key wrap operation result. +type SecureKeyOperationResult struct { + // REQUIRED; The algorithm used for the operation. + Algorithm *JSONWebKeyWrapAlgorithm + + // REQUIRED; Key identifier + Kid *string + + // REQUIRED; The result of the operation. + Value []byte +} + +// SecureKeyUnWrapOperationParameters - The Secure Key unwrap attributes. +type SecureKeyUnWrapOperationParameters struct { + // REQUIRED; algorithm identifier + Algorithm *JSONWebKeyWrapAlgorithm + + // REQUIRED; The attestation assertion for the target of the key release. + TargetAttestationToken *string + + // REQUIRED; The value to operate on. + Value []byte +} + +// SecureKeyWrapOperationParameters - The Secure Key wrap attributes. +type SecureKeyWrapOperationParameters struct { + // REQUIRED; algorithm identifier + Algorithm *JSONWebKeyWrapAlgorithm +} + +// SignParameters - The key operations parameters. +type SignParameters struct { + // The signing/verification algorithm identifier. For more information on possible algorithm types, see JsonWebKeySignatureAlgorithm. + Algorithm *SignatureAlgorithm + + // The application context string for ML-DSA signing (FIPS 204 Section 5.2). Must be 0-255 bytes. + // Must not be set when external_mu is specified. Only supported for ML-DSA (AKP) keys. + Context []byte + + // The pre-computed mu value for ML-DSA external mu mode (FIPS 204 Section 6.2). Must be exactly 64 bytes. + // When specified, the algorithm and value fields must not be set. Only supported for ML-DSA (AKP) keys. + ExternalMu []byte + + // The value to operate on. + Value []byte +} + +// UpdateKeyParameters - The key update parameters. +type UpdateKeyParameters struct { + // The attributes of a key managed by the key vault service. + KeyAttributes *KeyAttributes + + // Json web key operations. For more information on possible key operations, see JsonWebKeyOperation. + KeyOps []*KeyOperation + + // The policy rules under which the key can be exported. + ReleasePolicy *KeyReleasePolicy + + // Application specific metadata in the form of key-value pairs. + Tags map[string]*string +} + +// VerifyParameters - The key verify parameters. +type VerifyParameters struct { + // REQUIRED; The signature to be verified. + Signature []byte + + // The signing/verification algorithm. For more information on possible algorithm types, see JsonWebKeySignatureAlgorithm. + Algorithm *SignatureAlgorithm + + // The application context string for ML-DSA verification (FIPS 204 Section 5.2). Must be 0-255 bytes. + // Must not be set when external_mu is specified. Only supported for ML-DSA (AKP) keys. + Context []byte + + // The digest used for signing. + Digest []byte + + // The pre-computed mu value for ML-DSA external mu mode (FIPS 204 Section 6.2). Must be exactly 64 bytes. + // When specified, the algorithm and digest fields must not be set. Only supported for ML-DSA (AKP) keys. + ExternalMu []byte +} diff --git a/test/local/azkeys/zz_models_serde.go b/test/local/azkeys/zz_models_serde.go new file mode 100644 index 000000000000..596981475303 --- /dev/null +++ b/test/local/azkeys/zz_models_serde.go @@ -0,0 +1,1500 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azkeys + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime/datetime" + "reflect" + "time" +) + +// MarshalJSON implements the json.Marshaller interface for type BackupKeyResult. +func (b BackupKeyResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateByteArray(objectMap, "value", b.Value, func() any { + return runtime.EncodeByteArray(b.Value, runtime.Base64URLFormat) + }) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BackupKeyResult. +func (b *BackupKeyResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &b.Value, runtime.Base64URLFormat) + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", b, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type CreateKeyParameters. +func (c CreateKeyParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "alg", c.Alg) + populate(objectMap, "crv", c.Curve) + populate(objectMap, "attributes", c.KeyAttributes) + populate(objectMap, "key_ops", c.KeyOps) + populate(objectMap, "key_size", c.KeySize) + populate(objectMap, "kty", c.Kty) + populate(objectMap, "public_exponent", c.PublicExponent) + populate(objectMap, "release_policy", c.ReleasePolicy) + populate(objectMap, "tags", c.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CreateKeyParameters. +func (c *CreateKeyParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "alg": + err = unpopulate(val, "Alg", &c.Alg) + delete(rawMsg, key) + case "crv": + err = unpopulate(val, "Curve", &c.Curve) + delete(rawMsg, key) + case "attributes": + err = unpopulate(val, "KeyAttributes", &c.KeyAttributes) + delete(rawMsg, key) + case "key_ops": + err = unpopulate(val, "KeyOps", &c.KeyOps) + delete(rawMsg, key) + case "key_size": + err = unpopulate(val, "KeySize", &c.KeySize) + delete(rawMsg, key) + case "kty": + err = unpopulate(val, "Kty", &c.Kty) + delete(rawMsg, key) + case "public_exponent": + err = unpopulate(val, "PublicExponent", &c.PublicExponent) + delete(rawMsg, key) + case "release_policy": + err = unpopulate(val, "ReleasePolicy", &c.ReleasePolicy) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &c.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeletedKey. +func (d DeletedKey) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "attributes", d.Attributes) + populateTime[datetime.Unix](objectMap, "deletedDate", d.DeletedDate) + populate(objectMap, "key", d.Key) + populate(objectMap, "managed", d.Managed) + populate(objectMap, "recoveryId", d.RecoveryID) + populate(objectMap, "release_policy", d.ReleasePolicy) + populateTime[datetime.Unix](objectMap, "scheduledPurgeDate", d.ScheduledPurgeDate) + populate(objectMap, "tags", d.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeletedKey. +func (d *DeletedKey) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "attributes": + err = unpopulate(val, "Attributes", &d.Attributes) + delete(rawMsg, key) + case "deletedDate": + err = unpopulateTime[datetime.Unix](val, "DeletedDate", &d.DeletedDate) + delete(rawMsg, key) + case "key": + err = unpopulate(val, "Key", &d.Key) + delete(rawMsg, key) + case "managed": + err = unpopulate(val, "Managed", &d.Managed) + delete(rawMsg, key) + case "recoveryId": + err = unpopulate(val, "RecoveryID", &d.RecoveryID) + delete(rawMsg, key) + case "release_policy": + err = unpopulate(val, "ReleasePolicy", &d.ReleasePolicy) + delete(rawMsg, key) + case "scheduledPurgeDate": + err = unpopulateTime[datetime.Unix](val, "ScheduledPurgeDate", &d.ScheduledPurgeDate) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &d.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeletedKeyProperties. +func (d DeletedKeyProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "attributes", d.Attributes) + populateTime[datetime.Unix](objectMap, "deletedDate", d.DeletedDate) + populate(objectMap, "kid", d.KID) + populate(objectMap, "managed", d.Managed) + populate(objectMap, "recoveryId", d.RecoveryID) + populateTime[datetime.Unix](objectMap, "scheduledPurgeDate", d.ScheduledPurgeDate) + populate(objectMap, "tags", d.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeletedKeyProperties. +func (d *DeletedKeyProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "attributes": + err = unpopulate(val, "Attributes", &d.Attributes) + delete(rawMsg, key) + case "deletedDate": + err = unpopulateTime[datetime.Unix](val, "DeletedDate", &d.DeletedDate) + delete(rawMsg, key) + case "kid": + err = unpopulate(val, "KID", &d.KID) + delete(rawMsg, key) + case "managed": + err = unpopulate(val, "Managed", &d.Managed) + delete(rawMsg, key) + case "recoveryId": + err = unpopulate(val, "RecoveryID", &d.RecoveryID) + delete(rawMsg, key) + case "scheduledPurgeDate": + err = unpopulateTime[datetime.Unix](val, "ScheduledPurgeDate", &d.ScheduledPurgeDate) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &d.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DeletedKeyPropertiesListResult. +func (d DeletedKeyPropertiesListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", d.NextLink) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DeletedKeyPropertiesListResult. +func (d *DeletedKeyPropertiesListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &d.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &d.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ExternalKey. +func (e ExternalKey) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", e.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ExternalKey. +func (e *ExternalKey) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &e.ID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", e, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type GetRandomBytesParameters. +func (g GetRandomBytesParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "count", g.Count) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type GetRandomBytesParameters. +func (g *GetRandomBytesParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "count": + err = unpopulate(val, "Count", &g.Count) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", g, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ImportKeyParameters. +func (i ImportKeyParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "Hsm", i.HSM) + populate(objectMap, "key", i.Key) + populate(objectMap, "attributes", i.KeyAttributes) + populate(objectMap, "release_policy", i.ReleasePolicy) + populate(objectMap, "tags", i.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ImportKeyParameters. +func (i *ImportKeyParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "Hsm": + err = unpopulate(val, "HSM", &i.HSM) + delete(rawMsg, key) + case "key": + err = unpopulate(val, "Key", &i.Key) + delete(rawMsg, key) + case "attributes": + err = unpopulate(val, "KeyAttributes", &i.KeyAttributes) + delete(rawMsg, key) + case "release_policy": + err = unpopulate(val, "ReleasePolicy", &i.ReleasePolicy) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &i.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type JSONWebKey. +func (j JSONWebKey) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "alg", j.Alg) + populate(objectMap, "crv", j.Crv) + populateByteArray(objectMap, "d", j.D, func() any { + return runtime.EncodeByteArray(j.D, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "dp", j.DP, func() any { + return runtime.EncodeByteArray(j.DP, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "dq", j.DQ, func() any { + return runtime.EncodeByteArray(j.DQ, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "e", j.E, func() any { + return runtime.EncodeByteArray(j.E, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "k", j.K, func() any { + return runtime.EncodeByteArray(j.K, runtime.Base64URLFormat) + }) + populate(objectMap, "kid", j.KID) + populate(objectMap, "key_ops", j.KeyOps) + populate(objectMap, "kty", j.Kty) + populateByteArray(objectMap, "n", j.N, func() any { + return runtime.EncodeByteArray(j.N, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "p", j.P, func() any { + return runtime.EncodeByteArray(j.P, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "pub", j.Pub, func() any { + return runtime.EncodeByteArray(j.Pub, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "q", j.Q, func() any { + return runtime.EncodeByteArray(j.Q, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "qi", j.QI, func() any { + return runtime.EncodeByteArray(j.QI, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "key_hsm", j.T, func() any { + return runtime.EncodeByteArray(j.T, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "x", j.X, func() any { + return runtime.EncodeByteArray(j.X, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "y", j.Y, func() any { + return runtime.EncodeByteArray(j.Y, runtime.Base64URLFormat) + }) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JSONWebKey. +func (j *JSONWebKey) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", j, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "alg": + err = unpopulate(val, "Alg", &j.Alg) + delete(rawMsg, key) + case "crv": + err = unpopulate(val, "Crv", &j.Crv) + delete(rawMsg, key) + case "d": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.D, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "dp": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.DP, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "dq": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.DQ, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "e": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.E, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "k": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.K, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "kid": + err = unpopulate(val, "KID", &j.KID) + delete(rawMsg, key) + case "key_ops": + err = unpopulate(val, "KeyOps", &j.KeyOps) + delete(rawMsg, key) + case "kty": + err = unpopulate(val, "Kty", &j.Kty) + delete(rawMsg, key) + case "n": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.N, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "p": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.P, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "pub": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.Pub, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "q": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.Q, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "qi": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.QI, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "key_hsm": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.T, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "x": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.X, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "y": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &j.Y, runtime.Base64URLFormat) + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", j, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyAttestation. +func (k KeyAttestation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateByteArray(objectMap, "certificatePemFile", k.CertificatePEMFile, func() any { + return runtime.EncodeByteArray(k.CertificatePEMFile, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "privateKeyAttestation", k.PrivateKeyAttestation, func() any { + return runtime.EncodeByteArray(k.PrivateKeyAttestation, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "publicKeyAttestation", k.PublicKeyAttestation, func() any { + return runtime.EncodeByteArray(k.PublicKeyAttestation, runtime.Base64URLFormat) + }) + populate(objectMap, "version", k.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyAttestation. +func (k *KeyAttestation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "certificatePemFile": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.CertificatePEMFile, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "privateKeyAttestation": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.PrivateKeyAttestation, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "publicKeyAttestation": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.PublicKeyAttestation, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "version": + err = unpopulate(val, "Version", &k.Version) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyAttributes. +func (k KeyAttributes) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "attestation", k.Attestation) + populateTime[datetime.Unix](objectMap, "created", k.Created) + populate(objectMap, "enabled", k.Enabled) + populateTime[datetime.Unix](objectMap, "exp", k.Expires) + populate(objectMap, "exportable", k.Exportable) + populate(objectMap, "external_key", k.ExternalKey) + populate(objectMap, "hsmPlatform", k.HSMPlatform) + populate(objectMap, "key_size", k.KeySize) + populateTime[datetime.Unix](objectMap, "nbf", k.NotBefore) + populate(objectMap, "recoverableDays", k.RecoverableDays) + populate(objectMap, "recoveryLevel", k.RecoveryLevel) + populateTime[datetime.Unix](objectMap, "updated", k.Updated) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyAttributes. +func (k *KeyAttributes) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "attestation": + err = unpopulate(val, "Attestation", &k.Attestation) + delete(rawMsg, key) + case "created": + err = unpopulateTime[datetime.Unix](val, "Created", &k.Created) + delete(rawMsg, key) + case "enabled": + err = unpopulate(val, "Enabled", &k.Enabled) + delete(rawMsg, key) + case "exp": + err = unpopulateTime[datetime.Unix](val, "Expires", &k.Expires) + delete(rawMsg, key) + case "exportable": + err = unpopulate(val, "Exportable", &k.Exportable) + delete(rawMsg, key) + case "external_key": + err = unpopulate(val, "ExternalKey", &k.ExternalKey) + delete(rawMsg, key) + case "hsmPlatform": + err = unpopulate(val, "HSMPlatform", &k.HSMPlatform) + delete(rawMsg, key) + case "key_size": + err = unpopulate(val, "KeySize", &k.KeySize) + delete(rawMsg, key) + case "nbf": + err = unpopulateTime[datetime.Unix](val, "NotBefore", &k.NotBefore) + delete(rawMsg, key) + case "recoverableDays": + err = unpopulate(val, "RecoverableDays", &k.RecoverableDays) + delete(rawMsg, key) + case "recoveryLevel": + err = unpopulate(val, "RecoveryLevel", &k.RecoveryLevel) + delete(rawMsg, key) + case "updated": + err = unpopulateTime[datetime.Unix](val, "Updated", &k.Updated) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyBundle. +func (k KeyBundle) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "attributes", k.Attributes) + populate(objectMap, "key", k.Key) + populate(objectMap, "managed", k.Managed) + populate(objectMap, "release_policy", k.ReleasePolicy) + populate(objectMap, "tags", k.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyBundle. +func (k *KeyBundle) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "attributes": + err = unpopulate(val, "Attributes", &k.Attributes) + delete(rawMsg, key) + case "key": + err = unpopulate(val, "Key", &k.Key) + delete(rawMsg, key) + case "managed": + err = unpopulate(val, "Managed", &k.Managed) + delete(rawMsg, key) + case "release_policy": + err = unpopulate(val, "ReleasePolicy", &k.ReleasePolicy) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &k.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyOperationParameters. +func (k KeyOperationParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateByteArray(objectMap, "aad", k.AdditionalAuthenticatedData, func() any { + return runtime.EncodeByteArray(k.AdditionalAuthenticatedData, runtime.Base64URLFormat) + }) + populate(objectMap, "alg", k.Algorithm) + populateByteArray(objectMap, "tag", k.AuthenticationTag, func() any { + return runtime.EncodeByteArray(k.AuthenticationTag, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "iv", k.IV, func() any { + return runtime.EncodeByteArray(k.IV, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "value", k.Value, func() any { + return runtime.EncodeByteArray(k.Value, runtime.Base64URLFormat) + }) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyOperationParameters. +func (k *KeyOperationParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "aad": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.AdditionalAuthenticatedData, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "alg": + err = unpopulate(val, "Algorithm", &k.Algorithm) + delete(rawMsg, key) + case "tag": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.AuthenticationTag, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "iv": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.IV, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "value": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.Value, runtime.Base64URLFormat) + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyOperationResult. +func (k KeyOperationResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateByteArray(objectMap, "aad", k.AdditionalAuthenticatedData, func() any { + return runtime.EncodeByteArray(k.AdditionalAuthenticatedData, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "tag", k.AuthenticationTag, func() any { + return runtime.EncodeByteArray(k.AuthenticationTag, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "iv", k.IV, func() any { + return runtime.EncodeByteArray(k.IV, runtime.Base64URLFormat) + }) + populate(objectMap, "kid", k.KID) + populateByteArray(objectMap, "value", k.Result, func() any { + return runtime.EncodeByteArray(k.Result, runtime.Base64URLFormat) + }) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyOperationResult. +func (k *KeyOperationResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "aad": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.AdditionalAuthenticatedData, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "tag": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.AuthenticationTag, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "iv": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.IV, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "kid": + err = unpopulate(val, "KID", &k.KID) + delete(rawMsg, key) + case "value": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.Result, runtime.Base64URLFormat) + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyProperties. +func (k KeyProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "attributes", k.Attributes) + populate(objectMap, "kid", k.KID) + populate(objectMap, "managed", k.Managed) + populate(objectMap, "tags", k.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyProperties. +func (k *KeyProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "attributes": + err = unpopulate(val, "Attributes", &k.Attributes) + delete(rawMsg, key) + case "kid": + err = unpopulate(val, "KID", &k.KID) + delete(rawMsg, key) + case "managed": + err = unpopulate(val, "Managed", &k.Managed) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &k.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyPropertiesListResult. +func (k KeyPropertiesListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "nextLink", k.NextLink) + populate(objectMap, "value", k.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyPropertiesListResult. +func (k *KeyPropertiesListResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "nextLink": + err = unpopulate(val, "NextLink", &k.NextLink) + delete(rawMsg, key) + case "value": + err = unpopulate(val, "Value", &k.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyReleasePolicy. +func (k KeyReleasePolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "contentType", k.ContentType) + populateByteArray(objectMap, "data", k.EncodedPolicy, func() any { + return runtime.EncodeByteArray(k.EncodedPolicy, runtime.Base64URLFormat) + }) + populate(objectMap, "immutable", k.Immutable) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyReleasePolicy. +func (k *KeyReleasePolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "contentType": + err = unpopulate(val, "ContentType", &k.ContentType) + delete(rawMsg, key) + case "data": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &k.EncodedPolicy, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "immutable": + err = unpopulate(val, "Immutable", &k.Immutable) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyReleaseResult. +func (k KeyReleaseResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", k.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyReleaseResult. +func (k *KeyReleaseResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &k.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyRotationPolicy. +func (k KeyRotationPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "attributes", k.Attributes) + populate(objectMap, "id", k.ID) + populate(objectMap, "lifetimeActions", k.LifetimeActions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyRotationPolicy. +func (k *KeyRotationPolicy) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "attributes": + err = unpopulate(val, "Attributes", &k.Attributes) + delete(rawMsg, key) + case "id": + err = unpopulate(val, "ID", &k.ID) + delete(rawMsg, key) + case "lifetimeActions": + err = unpopulate(val, "LifetimeActions", &k.LifetimeActions) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyRotationPolicyAttributes. +func (k KeyRotationPolicyAttributes) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateTime[datetime.Unix](objectMap, "created", k.Created) + populate(objectMap, "expiryTime", k.ExpiryTime) + populateTime[datetime.Unix](objectMap, "updated", k.Updated) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyRotationPolicyAttributes. +func (k *KeyRotationPolicyAttributes) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "created": + err = unpopulateTime[datetime.Unix](val, "Created", &k.Created) + delete(rawMsg, key) + case "expiryTime": + err = unpopulate(val, "ExpiryTime", &k.ExpiryTime) + delete(rawMsg, key) + case "updated": + err = unpopulateTime[datetime.Unix](val, "Updated", &k.Updated) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type KeyVerifyResult. +func (k KeyVerifyResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "value", k.Value) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type KeyVerifyResult. +func (k *KeyVerifyResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + err = unpopulate(val, "Value", &k.Value) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", k, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LifetimeAction. +func (l LifetimeAction) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "action", l.Action) + populate(objectMap, "trigger", l.Trigger) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LifetimeAction. +func (l *LifetimeAction) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "action": + err = unpopulate(val, "Action", &l.Action) + delete(rawMsg, key) + case "trigger": + err = unpopulate(val, "Trigger", &l.Trigger) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LifetimeActionTrigger. +func (l LifetimeActionTrigger) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "timeAfterCreate", l.TimeAfterCreate) + populate(objectMap, "timeBeforeExpiry", l.TimeBeforeExpiry) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LifetimeActionTrigger. +func (l *LifetimeActionTrigger) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "timeAfterCreate": + err = unpopulate(val, "TimeAfterCreate", &l.TimeAfterCreate) + delete(rawMsg, key) + case "timeBeforeExpiry": + err = unpopulate(val, "TimeBeforeExpiry", &l.TimeBeforeExpiry) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type LifetimeActionType. +func (l LifetimeActionType) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "type", l.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LifetimeActionType. +func (l *LifetimeActionType) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "type": + err = unpopulate(val, "Type", &l.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", l, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RandomBytes. +func (r RandomBytes) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateByteArray(objectMap, "value", r.Value, func() any { + return runtime.EncodeByteArray(r.Value, runtime.Base64URLFormat) + }) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RandomBytes. +func (r *RandomBytes) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &r.Value, runtime.Base64URLFormat) + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type ReleaseParameters. +func (r ReleaseParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "enc", r.Algorithm) + populate(objectMap, "nonce", r.Nonce) + populate(objectMap, "target", r.TargetAttestationToken) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ReleaseParameters. +func (r *ReleaseParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "enc": + err = unpopulate(val, "Algorithm", &r.Algorithm) + delete(rawMsg, key) + case "nonce": + err = unpopulate(val, "Nonce", &r.Nonce) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "TargetAttestationToken", &r.TargetAttestationToken) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type RestoreKeyParameters. +func (r RestoreKeyParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populateByteArray(objectMap, "value", r.KeyBackup, func() any { + return runtime.EncodeByteArray(r.KeyBackup, runtime.Base64URLFormat) + }) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RestoreKeyParameters. +func (r *RestoreKeyParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "value": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &r.KeyBackup, runtime.Base64URLFormat) + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", r, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SecureKeyOperationResult. +func (s SecureKeyOperationResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "alg", s.Algorithm) + populate(objectMap, "kid", s.Kid) + populateByteArray(objectMap, "value", s.Value, func() any { + return runtime.EncodeByteArray(s.Value, runtime.Base64URLFormat) + }) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecureKeyOperationResult. +func (s *SecureKeyOperationResult) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "alg": + err = unpopulate(val, "Algorithm", &s.Algorithm) + delete(rawMsg, key) + case "kid": + err = unpopulate(val, "Kid", &s.Kid) + delete(rawMsg, key) + case "value": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &s.Value, runtime.Base64URLFormat) + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SecureKeyUnWrapOperationParameters. +func (s SecureKeyUnWrapOperationParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "alg", s.Algorithm) + populate(objectMap, "target", s.TargetAttestationToken) + populateByteArray(objectMap, "value", s.Value, func() any { + return runtime.EncodeByteArray(s.Value, runtime.Base64URLFormat) + }) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecureKeyUnWrapOperationParameters. +func (s *SecureKeyUnWrapOperationParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "alg": + err = unpopulate(val, "Algorithm", &s.Algorithm) + delete(rawMsg, key) + case "target": + err = unpopulate(val, "TargetAttestationToken", &s.TargetAttestationToken) + delete(rawMsg, key) + case "value": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &s.Value, runtime.Base64URLFormat) + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SecureKeyWrapOperationParameters. +func (s SecureKeyWrapOperationParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "alg", s.Algorithm) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SecureKeyWrapOperationParameters. +func (s *SecureKeyWrapOperationParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "alg": + err = unpopulate(val, "Algorithm", &s.Algorithm) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SignParameters. +func (s SignParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "alg", s.Algorithm) + populateByteArray(objectMap, "context", s.Context, func() any { + return runtime.EncodeByteArray(s.Context, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "external_mu", s.ExternalMu, func() any { + return runtime.EncodeByteArray(s.ExternalMu, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "value", s.Value, func() any { + return runtime.EncodeByteArray(s.Value, runtime.Base64URLFormat) + }) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SignParameters. +func (s *SignParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "alg": + err = unpopulate(val, "Algorithm", &s.Algorithm) + delete(rawMsg, key) + case "context": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &s.Context, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "external_mu": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &s.ExternalMu, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "value": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &s.Value, runtime.Base64URLFormat) + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type UpdateKeyParameters. +func (u UpdateKeyParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "attributes", u.KeyAttributes) + populate(objectMap, "key_ops", u.KeyOps) + populate(objectMap, "release_policy", u.ReleasePolicy) + populate(objectMap, "tags", u.Tags) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UpdateKeyParameters. +func (u *UpdateKeyParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "attributes": + err = unpopulate(val, "KeyAttributes", &u.KeyAttributes) + delete(rawMsg, key) + case "key_ops": + err = unpopulate(val, "KeyOps", &u.KeyOps) + delete(rawMsg, key) + case "release_policy": + err = unpopulate(val, "ReleasePolicy", &u.ReleasePolicy) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, "Tags", &u.Tags) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", u, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type VerifyParameters. +func (v VerifyParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "alg", v.Algorithm) + populateByteArray(objectMap, "context", v.Context, func() any { + return runtime.EncodeByteArray(v.Context, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "digest", v.Digest, func() any { + return runtime.EncodeByteArray(v.Digest, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "external_mu", v.ExternalMu, func() any { + return runtime.EncodeByteArray(v.ExternalMu, runtime.Base64URLFormat) + }) + populateByteArray(objectMap, "value", v.Signature, func() any { + return runtime.EncodeByteArray(v.Signature, runtime.Base64URLFormat) + }) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VerifyParameters. +func (v *VerifyParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "alg": + err = unpopulate(val, "Algorithm", &v.Algorithm) + delete(rawMsg, key) + case "context": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &v.Context, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "digest": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &v.Digest, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "external_mu": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &v.ExternalMu, runtime.Base64URLFormat) + } + delete(rawMsg, key) + case "value": + if val != nil && string(val) != "null" { + err = runtime.DecodeByteArray(string(val), &v.Signature, runtime.Base64URLFormat) + } + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", v, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateTime[T dateTimeConstraints](m map[string]any, k string, t *time.Time) { + if t == nil { + return + } else if azcore.IsNullValue(t) { + m[k] = nil + } else if !reflect.ValueOf(t).IsNil() { + newTime := T(*t) + m[k] = (*T)(&newTime) + } +} + +func populateByteArray[T any](m map[string]any, k string, b []T, convert func() any) { + if azcore.IsNullValue(b) { + m[k] = nil + } else if len(b) == 0 { + return + } else { + m[k] = convert() + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} + +func unpopulateTime[T dateTimeConstraints](data json.RawMessage, fn string, t **time.Time) error { + if data == nil || string(data) == "null" { + return nil + } + var aux T + if err := json.Unmarshal(data, &aux); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + newTime := time.Time(aux) + *t = &newTime + return nil +} + +type dateTimeConstraints interface { + datetime.PlainDate | datetime.PlainTime | datetime.RFC3339 | datetime.RFC7231 | datetime.Unix +} diff --git a/test/local/azkeys/zz_options.go b/test/local/azkeys/zz_options.go new file mode 100644 index 000000000000..2aa2968f9f54 --- /dev/null +++ b/test/local/azkeys/zz_options.go @@ -0,0 +1,140 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azkeys + +// BackupKeyOptions contains the optional parameters for the Client.BackupKey method. +type BackupKeyOptions struct { + // placeholder for future optional parameters +} + +// CreateKeyOptions contains the optional parameters for the Client.CreateKey method. +type CreateKeyOptions struct { + // placeholder for future optional parameters +} + +// DecryptOptions contains the optional parameters for the Client.Decrypt method. +type DecryptOptions struct { + // placeholder for future optional parameters +} + +// DeleteKeyOptions contains the optional parameters for the Client.DeleteKey method. +type DeleteKeyOptions struct { + // placeholder for future optional parameters +} + +// EncryptOptions contains the optional parameters for the Client.Encrypt method. +type EncryptOptions struct { + // placeholder for future optional parameters +} + +// GetDeletedKeyOptions contains the optional parameters for the Client.GetDeletedKey method. +type GetDeletedKeyOptions struct { + // placeholder for future optional parameters +} + +// GetKeyAttestationOptions contains the optional parameters for the Client.GetKeyAttestation method. +type GetKeyAttestationOptions struct { + // placeholder for future optional parameters +} + +// GetKeyOptions contains the optional parameters for the Client.GetKey method. +type GetKeyOptions struct { + // placeholder for future optional parameters +} + +// GetKeyRotationPolicyOptions contains the optional parameters for the Client.GetKeyRotationPolicy method. +type GetKeyRotationPolicyOptions struct { + // placeholder for future optional parameters +} + +// GetRandomBytesOptions contains the optional parameters for the Client.GetRandomBytes method. +type GetRandomBytesOptions struct { + // placeholder for future optional parameters +} + +// ImportKeyOptions contains the optional parameters for the Client.ImportKey method. +type ImportKeyOptions struct { + // placeholder for future optional parameters +} + +// ListDeletedKeyPropertiesOptions contains the optional parameters for the Client.NewListDeletedKeyPropertiesPager method. +type ListDeletedKeyPropertiesOptions struct { + // placeholder for future optional parameters +} + +// ListKeyPropertiesOptions contains the optional parameters for the Client.NewListKeyPropertiesPager method. +type ListKeyPropertiesOptions struct { + // placeholder for future optional parameters +} + +// ListKeyPropertiesVersionsOptions contains the optional parameters for the Client.NewListKeyPropertiesVersionsPager method. +type ListKeyPropertiesVersionsOptions struct { + // placeholder for future optional parameters +} + +// PurgeDeletedKeyOptions contains the optional parameters for the Client.PurgeDeletedKey method. +type PurgeDeletedKeyOptions struct { + // placeholder for future optional parameters +} + +// RecoverDeletedKeyOptions contains the optional parameters for the Client.RecoverDeletedKey method. +type RecoverDeletedKeyOptions struct { + // placeholder for future optional parameters +} + +// ReleaseOptions contains the optional parameters for the Client.Release method. +type ReleaseOptions struct { + // placeholder for future optional parameters +} + +// RestoreKeyOptions contains the optional parameters for the Client.RestoreKey method. +type RestoreKeyOptions struct { + // placeholder for future optional parameters +} + +// RotateKeyOptions contains the optional parameters for the Client.RotateKey method. +type RotateKeyOptions struct { + // placeholder for future optional parameters +} + +// SecureUnwrapKeyOptions contains the optional parameters for the Client.SecureUnwrapKey method. +type SecureUnwrapKeyOptions struct { + // placeholder for future optional parameters +} + +// SecureWrapKeyOptions contains the optional parameters for the Client.SecureWrapKey method. +type SecureWrapKeyOptions struct { + // placeholder for future optional parameters +} + +// SignOptions contains the optional parameters for the Client.Sign method. +type SignOptions struct { + // placeholder for future optional parameters +} + +// UnwrapKeyOptions contains the optional parameters for the Client.UnwrapKey method. +type UnwrapKeyOptions struct { + // placeholder for future optional parameters +} + +// UpdateKeyOptions contains the optional parameters for the Client.UpdateKey method. +type UpdateKeyOptions struct { + // placeholder for future optional parameters +} + +// UpdateKeyRotationPolicyOptions contains the optional parameters for the Client.UpdateKeyRotationPolicy method. +type UpdateKeyRotationPolicyOptions struct { + // placeholder for future optional parameters +} + +// VerifyOptions contains the optional parameters for the Client.Verify method. +type VerifyOptions struct { + // placeholder for future optional parameters +} + +// WrapKeyOptions contains the optional parameters for the Client.WrapKey method. +type WrapKeyOptions struct { + // placeholder for future optional parameters +} diff --git a/test/local/azkeys/zz_responses.go b/test/local/azkeys/zz_responses.go new file mode 100644 index 000000000000..1b8aa885f56b --- /dev/null +++ b/test/local/azkeys/zz_responses.go @@ -0,0 +1,166 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azkeys + +// BackupKeyResponse contains the response from method Client.BackupKey. +type BackupKeyResponse struct { + // The backup key result, containing the backup blob. + BackupKeyResult +} + +// CreateKeyResponse contains the response from method Client.CreateKey. +type CreateKeyResponse struct { + // A KeyBundle consisting of a WebKey plus its attributes. + KeyBundle +} + +// DecryptResponse contains the response from method Client.Decrypt. +type DecryptResponse struct { + // The key operation result. + KeyOperationResult +} + +// DeleteKeyResponse contains the response from method Client.DeleteKey. +type DeleteKeyResponse struct { + // A DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info + DeletedKey +} + +// EncryptResponse contains the response from method Client.Encrypt. +type EncryptResponse struct { + // The key operation result. + KeyOperationResult +} + +// GetDeletedKeyResponse contains the response from method Client.GetDeletedKey. +type GetDeletedKeyResponse struct { + // A DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info + DeletedKey +} + +// GetKeyAttestationResponse contains the response from method Client.GetKeyAttestation. +type GetKeyAttestationResponse struct { + // A KeyBundle consisting of a WebKey plus its attributes. + KeyBundle +} + +// GetKeyResponse contains the response from method Client.GetKey. +type GetKeyResponse struct { + // A KeyBundle consisting of a WebKey plus its attributes. + KeyBundle +} + +// GetKeyRotationPolicyResponse contains the response from method Client.GetKeyRotationPolicy. +type GetKeyRotationPolicyResponse struct { + // Management policy for a key. + KeyRotationPolicy +} + +// GetRandomBytesResponse contains the response from method Client.GetRandomBytes. +type GetRandomBytesResponse struct { + // The get random bytes response object containing the bytes. + RandomBytes +} + +// ImportKeyResponse contains the response from method Client.ImportKey. +type ImportKeyResponse struct { + // A KeyBundle consisting of a WebKey plus its attributes. + KeyBundle +} + +// ListDeletedKeyPropertiesResponse contains the response from method Client.NewListDeletedKeyPropertiesPager. +type ListDeletedKeyPropertiesResponse struct { + // A list of keys that have been deleted in this vault. + DeletedKeyPropertiesListResult +} + +// ListKeyPropertiesResponse contains the response from method Client.NewListKeyPropertiesPager. +type ListKeyPropertiesResponse struct { + // The key list result. + KeyPropertiesListResult +} + +// ListKeyPropertiesVersionsResponse contains the response from method Client.NewListKeyPropertiesVersionsPager. +type ListKeyPropertiesVersionsResponse struct { + // The key list result. + KeyPropertiesListResult +} + +// PurgeDeletedKeyResponse contains the response from method Client.PurgeDeletedKey. +type PurgeDeletedKeyResponse struct { + // placeholder for future response values +} + +// RecoverDeletedKeyResponse contains the response from method Client.RecoverDeletedKey. +type RecoverDeletedKeyResponse struct { + // A KeyBundle consisting of a WebKey plus its attributes. + KeyBundle +} + +// ReleaseResponse contains the response from method Client.Release. +type ReleaseResponse struct { + // The release result, containing the released key. + KeyReleaseResult +} + +// RestoreKeyResponse contains the response from method Client.RestoreKey. +type RestoreKeyResponse struct { + // A KeyBundle consisting of a WebKey plus its attributes. + KeyBundle +} + +// RotateKeyResponse contains the response from method Client.RotateKey. +type RotateKeyResponse struct { + // A KeyBundle consisting of a WebKey plus its attributes. + KeyBundle +} + +// SecureUnwrapKeyResponse contains the response from method Client.SecureUnwrapKey. +type SecureUnwrapKeyResponse struct { + // The secure key wrap operation result. + SecureKeyOperationResult +} + +// SecureWrapKeyResponse contains the response from method Client.SecureWrapKey. +type SecureWrapKeyResponse struct { + // The secure key wrap operation result. + SecureKeyOperationResult +} + +// SignResponse contains the response from method Client.Sign. +type SignResponse struct { + // The key operation result. + KeyOperationResult +} + +// UnwrapKeyResponse contains the response from method Client.UnwrapKey. +type UnwrapKeyResponse struct { + // The key operation result. + KeyOperationResult +} + +// UpdateKeyResponse contains the response from method Client.UpdateKey. +type UpdateKeyResponse struct { + // A KeyBundle consisting of a WebKey plus its attributes. + KeyBundle +} + +// UpdateKeyRotationPolicyResponse contains the response from method Client.UpdateKeyRotationPolicy. +type UpdateKeyRotationPolicyResponse struct { + // Management policy for a key. + KeyRotationPolicy +} + +// VerifyResponse contains the response from method Client.Verify. +type VerifyResponse struct { + // The key verify result. + KeyVerifyResult +} + +// WrapKeyResponse contains the response from method Client.WrapKey. +type WrapKeyResponse struct { + // The key operation result. + KeyOperationResult +} diff --git a/test/local/azkeys/zz_version.go b/test/local/azkeys/zz_version.go new file mode 100644 index 000000000000..06facb5046d1 --- /dev/null +++ b/test/local/azkeys/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package azkeys + +const ( + moduleName = "azkeys" + moduleVersion = "v0.1.0" +) diff --git a/test/local/azmodelsonly/LICENSE.txt b/test/local/azmodelsonly/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/local/azmodelsonly/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/local/azmodelsonly/go.mod b/test/local/azmodelsonly/go.mod new file mode 100644 index 000000000000..f39671bc7ede --- /dev/null +++ b/test/local/azmodelsonly/go.mod @@ -0,0 +1,11 @@ +module azmodelsonly + +go 1.25.0 + +require github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect +) diff --git a/test/local/azmodelsonly/go.sum b/test/local/azmodelsonly/go.sum new file mode 100644 index 000000000000..3fdb64caf441 --- /dev/null +++ b/test/local/azmodelsonly/go.sum @@ -0,0 +1,16 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/local/azmodelsonly/testdata/_metadata.json b/test/local/azmodelsonly/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/local/azmodelsonly/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/local/azmodelsonly/version.go b/test/local/azmodelsonly/version.go new file mode 100644 index 000000000000..c6fe0852b4b7 --- /dev/null +++ b/test/local/azmodelsonly/version.go @@ -0,0 +1,8 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package azmodelsonly + +// suppress unused vars lint +var _ = moduleName +var _ = moduleVersion diff --git a/test/local/azmodelsonly/zz_models.go b/test/local/azmodelsonly/zz_models.go new file mode 100644 index 000000000000..8120a6ad92a8 --- /dev/null +++ b/test/local/azmodelsonly/zz_models.go @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azmodelsonly + +type DerivedOne struct { + // REQUIRED + ID *int32 + + // REQUIRED + Name *string +} + +type DerivedTwo struct { + // REQUIRED + ID *int32 + + // REQUIRED + Name *string +} + +type PreservedBaseClass struct { + // REQUIRED + ID *int32 +} diff --git a/test/local/azmodelsonly/zz_models_serde.go b/test/local/azmodelsonly/zz_models_serde.go new file mode 100644 index 000000000000..3f8f37f5c57b --- /dev/null +++ b/test/local/azmodelsonly/zz_models_serde.go @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azmodelsonly + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type DerivedOne. +func (d DerivedOne) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", d.ID) + populate(objectMap, "name", d.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DerivedOne. +func (d *DerivedOne) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type DerivedTwo. +func (d DerivedTwo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", d.ID) + populate(objectMap, "name", d.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DerivedTwo. +func (d *DerivedTwo) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &d.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type PreservedBaseClass. +func (p PreservedBaseClass) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "id", p.ID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PreservedBaseClass. +func (p *PreservedBaseClass) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, "ID", &p.ID) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", p, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/local/azmodelsonly/zz_version.go b/test/local/azmodelsonly/zz_version.go new file mode 100644 index 000000000000..915b728ed067 --- /dev/null +++ b/test/local/azmodelsonly/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package azmodelsonly + +const ( + moduleName = "azmodelsonly" + moduleVersion = "v0.1.0" +) diff --git a/test/local/azregressions/LICENSE.txt b/test/local/azregressions/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/local/azregressions/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/local/azregressions/fake/zz_internal.go b/test/local/azregressions/fake/zz_internal.go new file mode 100644 index 000000000000..ea412051f8be --- /dev/null +++ b/test/local/azregressions/fake/zz_internal.go @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "reflect" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func getHeaderValue(h http.Header, k string) string { + v := h[k] + if len(v) == 0 { + return "" + } + return v[0] +} + +func getOptional[T any](v T) *T { + if reflect.ValueOf(v).IsZero() { + return nil + } + return &v +} + +func parseOptional[T any](v string, parse func(v string) (T, error)) (*T, error) { + if v == "" { + return nil, nil + } + t, err := parse(v) + if err != nil { + return nil, err + } + return &t, nil +} diff --git a/test/local/azregressions/fake/zz_server.go b/test/local/azregressions/fake/zz_server.go new file mode 100644 index 000000000000..69724b670ed4 --- /dev/null +++ b/test/local/azregressions/fake/zz_server.go @@ -0,0 +1,716 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "azregressions" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "io" + "net/http" + "net/url" + "reflect" + "regexp" + "slices" + "strconv" +) + +// Server is a fake server for instances of the azregressions.Client type. +type Server struct { + // BinaryBodyWithContentType is the fake for method Client.BinaryBodyWithContentType + // HTTP status codes to indicate success: http.StatusNoContent + BinaryBodyWithContentType func(ctx context.Context, payload io.ReadSeekCloser, contentType string, options *azregressions.ClientBinaryBodyWithContentTypeOptions) (resp azfake.Responder[azregressions.ClientBinaryBodyWithContentTypeResponse], errResp azfake.ErrorResponder) + + // BinaryResponseWithXMLContentType is the fake for method Client.BinaryResponseWithXMLContentType + // HTTP status codes to indicate success: http.StatusOK + BinaryResponseWithXMLContentType func(ctx context.Context, options *azregressions.ClientBinaryResponseWithXMLContentTypeOptions) (resp azfake.Responder[azregressions.ClientBinaryResponseWithXMLContentTypeResponse], errResp azfake.ErrorResponder) + + // DoubleDecode is the fake for method Client.DoubleDecode + // HTTP status codes to indicate success: http.StatusNoContent + DoubleDecode func(ctx context.Context, pathParam string, query string, options *azregressions.ClientDoubleDecodeOptions) (resp azfake.Responder[azregressions.ClientDoubleDecodeResponse], errResp azfake.ErrorResponder) + + // ForceRequiredBodyPatch is the fake for method Client.ForceRequiredBodyPatch + // HTTP status codes to indicate success: http.StatusNoContent + ForceRequiredBodyPatch func(ctx context.Context, body azregressions.SomeModel, options *azregressions.ClientForceRequiredBodyPatchOptions) (resp azfake.Responder[azregressions.ClientForceRequiredBodyPatchResponse], errResp azfake.ErrorResponder) + + // ForceRequiredBodyPut is the fake for method Client.ForceRequiredBodyPut + // HTTP status codes to indicate success: http.StatusNoContent + ForceRequiredBodyPut func(ctx context.Context, body azregressions.SomeModel, options *azregressions.ClientForceRequiredBodyPutOptions) (resp azfake.Responder[azregressions.ClientForceRequiredBodyPutResponse], errResp azfake.ErrorResponder) + + // GetBool is the fake for method Client.GetBool + // HTTP status codes to indicate success: http.StatusOK + GetBool func(ctx context.Context, options *azregressions.ClientGetBoolOptions) (resp azfake.Responder[azregressions.ClientGetBoolResponse], errResp azfake.ErrorResponder) + + // GetDiscriminatedNoSubTypes is the fake for method Client.GetDiscriminatedNoSubTypes + // HTTP status codes to indicate success: http.StatusOK + GetDiscriminatedNoSubTypes func(ctx context.Context, options *azregressions.ClientGetDiscriminatedNoSubTypesOptions) (resp azfake.Responder[azregressions.ClientGetDiscriminatedNoSubTypesResponse], errResp azfake.ErrorResponder) + + // GetFloat is the fake for method Client.GetFloat + // HTTP status codes to indicate success: http.StatusOK + GetFloat func(ctx context.Context, options *azregressions.ClientGetFloatOptions) (resp azfake.Responder[azregressions.ClientGetFloatResponse], errResp azfake.ErrorResponder) + + // GetInteger is the fake for method Client.GetInteger + // HTTP status codes to indicate success: http.StatusOK + GetInteger func(ctx context.Context, options *azregressions.ClientGetIntegerOptions) (resp azfake.Responder[azregressions.ClientGetIntegerResponse], errResp azfake.ErrorResponder) + + // GetQueue is the fake for method Client.GetQueue + // HTTP status codes to indicate success: http.StatusOK + GetQueue func(ctx context.Context, options *azregressions.ClientGetQueueOptions) (resp azfake.Responder[azregressions.ClientGetQueueResponse], errResp azfake.ErrorResponder) + + // GetXMLOne is the fake for method Client.GetXMLOne + // HTTP status codes to indicate success: http.StatusOK + GetXMLOne func(ctx context.Context, options *azregressions.ClientGetXMLOneOptions) (resp azfake.Responder[azregressions.ClientGetXMLOneResponse], errResp azfake.ErrorResponder) + + // GetXMLTwo is the fake for method Client.GetXMLTwo + // HTTP status codes to indicate success: http.StatusOK + GetXMLTwo func(ctx context.Context, options *azregressions.ClientGetXMLTwoOptions) (resp azfake.Responder[azregressions.ClientGetXMLTwoResponse], errResp azfake.ErrorResponder) + + // OptionalBinaryBody is the fake for method Client.OptionalBinaryBody + // HTTP status codes to indicate success: http.StatusNoContent + OptionalBinaryBody func(ctx context.Context, options *azregressions.ClientOptionalBinaryBodyOptions) (resp azfake.Responder[azregressions.ClientOptionalBinaryBodyResponse], errResp azfake.ErrorResponder) + + // OptionalBinaryBodyWithContentType is the fake for method Client.OptionalBinaryBodyWithContentType + // HTTP status codes to indicate success: http.StatusNoContent + OptionalBinaryBodyWithContentType func(ctx context.Context, options *azregressions.ClientOptionalBinaryBodyWithContentTypeOptions) (resp azfake.Responder[azregressions.ClientOptionalBinaryBodyWithContentTypeResponse], errResp azfake.ErrorResponder) + + // OptionalBodyPost is the fake for method Client.OptionalBodyPost + // HTTP status codes to indicate success: http.StatusNoContent + OptionalBodyPost func(ctx context.Context, options *azregressions.ClientOptionalBodyPostOptions) (resp azfake.Responder[azregressions.ClientOptionalBodyPostResponse], errResp azfake.ErrorResponder) + + // PayloadWithExplicitContentType is the fake for method Client.PayloadWithExplicitContentType + // HTTP status codes to indicate success: http.StatusNoContent + PayloadWithExplicitContentType func(ctx context.Context, contentType azregressions.PayloadWithExplicitContentTypeRequestContentType, thing azregressions.SomeModel, options *azregressions.ClientPayloadWithExplicitContentTypeOptions) (resp azfake.Responder[azregressions.ClientPayloadWithExplicitContentTypeResponse], errResp azfake.ErrorResponder) + + // SpreadWithModel is the fake for method Client.SpreadWithModel + // HTTP status codes to indicate success: http.StatusNoContent + SpreadWithModel func(ctx context.Context, name string, options *azregressions.ClientSpreadWithModelOptions) (resp azfake.Responder[azregressions.ClientSpreadWithModelResponse], errResp azfake.ErrorResponder) + + // WithClientDefaultModelField is the fake for method Client.WithClientDefaultModelField + // HTTP status codes to indicate success: http.StatusNoContent + WithClientDefaultModelField func(ctx context.Context, widget azregressions.Widget, options *azregressions.ClientWithClientDefaultModelFieldOptions) (resp azfake.Responder[azregressions.ClientWithClientDefaultModelFieldResponse], errResp azfake.ErrorResponder) + + // WithClientDefaultValues is the fake for method Client.WithClientDefaultValues + // HTTP status codes to indicate success: http.StatusNoContent + WithClientDefaultValues func(ctx context.Context, options *azregressions.ClientWithClientDefaultValuesOptions) (resp azfake.Responder[azregressions.ClientWithClientDefaultValuesResponse], errResp azfake.ErrorResponder) + + // WithExpandParam is the fake for method Client.WithExpandParam + // HTTP status codes to indicate success: http.StatusNoContent + WithExpandParam func(ctx context.Context, expand string, options *azregressions.ClientWithExpandParamOptions) (resp azfake.Responder[azregressions.ClientWithExpandParamResponse], errResp azfake.ErrorResponder) +} + +// NewServerTransport creates a new instance of ServerTransport with the provided implementation. +// The returned ServerTransport instance is connected to an instance of azregressions.Client via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewServerTransport(srv *Server) *ServerTransport { + return &ServerTransport{srv: srv} +} + +// ServerTransport connects instances of azregressions.Client to instances of Server. +// Don't use this type directly, use NewServerTransport instead. +type ServerTransport struct { + srv *Server +} + +// Do implements the policy.Transporter interface for ServerTransport. +func (s *ServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return s.dispatchToMethodFake(req, method) +} + +func (s *ServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if serverTransportInterceptor != nil { + res.resp, res.err, intercepted = serverTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "Client.BinaryBodyWithContentType": + res.resp, res.err = s.dispatchBinaryBodyWithContentType(req) + case "Client.BinaryResponseWithXMLContentType": + res.resp, res.err = s.dispatchBinaryResponseWithXMLContentType(req) + case "Client.DoubleDecode": + res.resp, res.err = s.dispatchDoubleDecode(req) + case "Client.ForceRequiredBodyPatch": + res.resp, res.err = s.dispatchForceRequiredBodyPatch(req) + case "Client.ForceRequiredBodyPut": + res.resp, res.err = s.dispatchForceRequiredBodyPut(req) + case "Client.GetBool": + res.resp, res.err = s.dispatchGetBool(req) + case "Client.GetDiscriminatedNoSubTypes": + res.resp, res.err = s.dispatchGetDiscriminatedNoSubTypes(req) + case "Client.GetFloat": + res.resp, res.err = s.dispatchGetFloat(req) + case "Client.GetInteger": + res.resp, res.err = s.dispatchGetInteger(req) + case "Client.GetQueue": + res.resp, res.err = s.dispatchGetQueue(req) + case "Client.GetXMLOne": + res.resp, res.err = s.dispatchGetXMLOne(req) + case "Client.GetXMLTwo": + res.resp, res.err = s.dispatchGetXMLTwo(req) + case "Client.OptionalBinaryBody": + res.resp, res.err = s.dispatchOptionalBinaryBody(req) + case "Client.OptionalBinaryBodyWithContentType": + res.resp, res.err = s.dispatchOptionalBinaryBodyWithContentType(req) + case "Client.OptionalBodyPost": + res.resp, res.err = s.dispatchOptionalBodyPost(req) + case "Client.PayloadWithExplicitContentType": + res.resp, res.err = s.dispatchPayloadWithExplicitContentType(req) + case "Client.SpreadWithModel": + res.resp, res.err = s.dispatchSpreadWithModel(req) + case "Client.WithClientDefaultModelField": + res.resp, res.err = s.dispatchWithClientDefaultModelField(req) + case "Client.WithClientDefaultValues": + res.resp, res.err = s.dispatchWithClientDefaultValues(req) + case "Client.WithExpandParam": + res.resp, res.err = s.dispatchWithExpandParam(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (s *ServerTransport) dispatchBinaryBodyWithContentType(req *http.Request) (*http.Response, error) { + if s.srv.BinaryBodyWithContentType == nil { + return nil, &nonRetriableError{errors.New("fake for method BinaryBodyWithContentType not implemented")} + } + respr, errRespr := s.srv.BinaryBodyWithContentType(req.Context(), req.Body.(io.ReadSeekCloser), getHeaderValue(req.Header, "Content-Type"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchBinaryResponseWithXMLContentType(req *http.Request) (*http.Response, error) { + if s.srv.BinaryResponseWithXMLContentType == nil { + return nil, &nonRetriableError{errors.New("fake for method BinaryResponseWithXMLContentType not implemented")} + } + respr, errRespr := s.srv.BinaryResponseWithXMLContentType(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, &server.ResponseOptions{ + Body: server.GetResponse(respr).Body, + ContentType: req.Header.Get("Content-Type"), + }) + if err != nil { + return nil, err + } + if val := server.GetResponse(respr).ContentType; val != nil { + resp.Header.Set("Content-Type", "application/xml") + } + return resp, nil +} + +func (s *ServerTransport) dispatchDoubleDecode(req *http.Request) (*http.Response, error) { + if s.srv.DoubleDecode == nil { + return nil, &nonRetriableError{errors.New("fake for method DoubleDecode not implemented")} + } + const regexStr = `/double-decode/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 2 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + qp := req.URL.Query() + pathParamParam, err := url.PathUnescape(matches[regex.SubexpIndex("path")]) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.DoubleDecode(req.Context(), pathParamParam, qp.Get("query"), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchForceRequiredBodyPatch(req *http.Request) (*http.Response, error) { + if s.srv.ForceRequiredBodyPatch == nil { + return nil, &nonRetriableError{errors.New("fake for method ForceRequiredBodyPatch not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[azregressions.SomeModel](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.ForceRequiredBodyPatch(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchForceRequiredBodyPut(req *http.Request) (*http.Response, error) { + if s.srv.ForceRequiredBodyPut == nil { + return nil, &nonRetriableError{errors.New("fake for method ForceRequiredBodyPut not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[azregressions.SomeModel](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.ForceRequiredBodyPut(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchGetBool(req *http.Request) (*http.Response, error) { + if s.srv.GetBool == nil { + return nil, &nonRetriableError{errors.New("fake for method GetBool not implemented")} + } + respr, errRespr := s.srv.GetBool(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + var formattedValue *string + if value := server.GetResponse(respr).Value; value != nil { + formattedValue = to.Ptr(strconv.FormatBool(*value)) + } + resp, err := server.MarshalResponseAsText(respContent, formattedValue, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchGetDiscriminatedNoSubTypes(req *http.Request) (*http.Response, error) { + if s.srv.GetDiscriminatedNoSubTypes == nil { + return nil, &nonRetriableError{errors.New("fake for method GetDiscriminatedNoSubTypes not implemented")} + } + respr, errRespr := s.srv.GetDiscriminatedNoSubTypes(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).DiscriminatedBaseNoSubTypesClassification, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchGetFloat(req *http.Request) (*http.Response, error) { + if s.srv.GetFloat == nil { + return nil, &nonRetriableError{errors.New("fake for method GetFloat not implemented")} + } + respr, errRespr := s.srv.GetFloat(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + var formattedValue *string + if value := server.GetResponse(respr).Value; value != nil { + formattedValue = to.Ptr(strconv.FormatFloat(*value, 'f', -1, 64)) + } + resp, err := server.MarshalResponseAsText(respContent, formattedValue, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchGetInteger(req *http.Request) (*http.Response, error) { + if s.srv.GetInteger == nil { + return nil, &nonRetriableError{errors.New("fake for method GetInteger not implemented")} + } + respr, errRespr := s.srv.GetInteger(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + var formattedValue *string + if value := server.GetResponse(respr).Value; value != nil { + formattedValue = to.Ptr(strconv.FormatInt(*value, 10)) + } + resp, err := server.MarshalResponseAsText(respContent, formattedValue, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchGetQueue(req *http.Request) (*http.Response, error) { + if s.srv.GetQueue == nil { + return nil, &nonRetriableError{errors.New("fake for method GetQueue not implemented")} + } + respr, errRespr := s.srv.GetQueue(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr).QueueItem, req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchGetXMLOne(req *http.Request) (*http.Response, error) { + if s.srv.GetXMLOne == nil { + return nil, &nonRetriableError{errors.New("fake for method GetXMLOne not implemented")} + } + respr, errRespr := s.srv.GetXMLOne(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr), req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchGetXMLTwo(req *http.Request) (*http.Response, error) { + if s.srv.GetXMLTwo == nil { + return nil, &nonRetriableError{errors.New("fake for method GetXMLTwo not implemented")} + } + respr, errRespr := s.srv.GetXMLTwo(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsXML(respContent, server.GetResponse(respr), req) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchOptionalBinaryBody(req *http.Request) (*http.Response, error) { + if s.srv.OptionalBinaryBody == nil { + return nil, &nonRetriableError{errors.New("fake for method OptionalBinaryBody not implemented")} + } + var options *azregressions.ClientOptionalBinaryBodyOptions + if req.Body != nil { + options = &azregressions.ClientOptionalBinaryBodyOptions{ + Payload: req.Body.(io.ReadSeekCloser), + } + } + respr, errRespr := s.srv.OptionalBinaryBody(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchOptionalBinaryBodyWithContentType(req *http.Request) (*http.Response, error) { + if s.srv.OptionalBinaryBodyWithContentType == nil { + return nil, &nonRetriableError{errors.New("fake for method OptionalBinaryBodyWithContentType not implemented")} + } + contentTypeParam := getOptional(getHeaderValue(req.Header, "Content-Type")) + var options *azregressions.ClientOptionalBinaryBodyWithContentTypeOptions + if req.Body != nil || contentTypeParam != nil { + options = &azregressions.ClientOptionalBinaryBodyWithContentTypeOptions{ + Payload: req.Body.(io.ReadSeekCloser), + ContentType: contentTypeParam, + } + } + respr, errRespr := s.srv.OptionalBinaryBodyWithContentType(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchOptionalBodyPost(req *http.Request) (*http.Response, error) { + if s.srv.OptionalBodyPost == nil { + return nil, &nonRetriableError{errors.New("fake for method OptionalBodyPost not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[azregressions.SomeModel](req) + if err != nil { + return nil, err + } + var options *azregressions.ClientOptionalBodyPostOptions + if !reflect.ValueOf(body).IsZero() { + options = &azregressions.ClientOptionalBodyPostOptions{ + Body: &body, + } + } + respr, errRespr := s.srv.OptionalBodyPost(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchPayloadWithExplicitContentType(req *http.Request) (*http.Response, error) { + if s.srv.PayloadWithExplicitContentType == nil { + return nil, &nonRetriableError{errors.New("fake for method PayloadWithExplicitContentType not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[azregressions.SomeModel](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.PayloadWithExplicitContentType(req.Context(), azregressions.PayloadWithExplicitContentTypeRequestContentType(getHeaderValue(req.Header, "Content-Type")), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchSpreadWithModel(req *http.Request) (*http.Response, error) { + if s.srv.SpreadWithModel == nil { + return nil, &nonRetriableError{errors.New("fake for method SpreadWithModel not implemented")} + } + type partialBodyParams struct { + Name string `json:"name"` + Color *string `json:"color"` + Inner *azregressions.InnerSpreadParam `json:"inner"` + } + body, err := server.UnmarshalRequestAsJSON[partialBodyParams](req) + if err != nil { + return nil, err + } + var options *azregressions.ClientSpreadWithModelOptions + if body.Color != nil || body.Inner != nil { + options = &azregressions.ClientSpreadWithModelOptions{ + Color: body.Color, + Inner: body.Inner, + } + } + respr, errRespr := s.srv.SpreadWithModel(req.Context(), body.Name, options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchWithClientDefaultModelField(req *http.Request) (*http.Response, error) { + if s.srv.WithClientDefaultModelField == nil { + return nil, &nonRetriableError{errors.New("fake for method WithClientDefaultModelField not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[azregressions.Widget](req) + if err != nil { + return nil, err + } + respr, errRespr := s.srv.WithClientDefaultModelField(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchWithClientDefaultValues(req *http.Request) (*http.Response, error) { + if s.srv.WithClientDefaultValues == nil { + return nil, &nonRetriableError{errors.New("fake for method WithClientDefaultValues not implemented")} + } + const regexStr = `/non-string-path-params/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)/(?P[!#&$-;=?-\[\]_a-zA-Z0-9~%@]+)` + regex := regexp.MustCompile(regexStr) + matches := regex.FindStringSubmatch(req.URL.EscapedPath()) + if len(matches) < 3 { + return nil, fmt.Errorf("failed to parse path %s", req.URL.Path) + } + colorUnescaped, err := url.PathUnescape(matches[regex.SubexpIndex("color")]) + if err != nil { + return nil, err + } + colorParam := getOptional(azregressions.Color(colorUnescaped)) + countUnescaped, err := url.PathUnescape(matches[regex.SubexpIndex("count")]) + if err != nil { + return nil, err + } + countParam, err := parseOptional(countUnescaped, func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + var options *azregressions.ClientWithClientDefaultValuesOptions + if colorParam != nil || countParam != nil { + options = &azregressions.ClientWithClientDefaultValuesOptions{ + Color: colorParam, + Count: countParam, + } + } + respr, errRespr := s.srv.WithClientDefaultValues(req.Context(), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +func (s *ServerTransport) dispatchWithExpandParam(req *http.Request) (*http.Response, error) { + if s.srv.WithExpandParam == nil { + return nil, &nonRetriableError{errors.New("fake for method WithExpandParam not implemented")} + } + qp := req.URL.Query() + topParam, err := parseOptional(qp.Get("$top"), func(v string) (int32, error) { + p, parseErr := strconv.ParseInt(v, 10, 32) + if parseErr != nil { + return 0, parseErr + } + return int32(p), nil + }) + if err != nil { + return nil, err + } + var options *azregressions.ClientWithExpandParamOptions + if topParam != nil { + options = &azregressions.ClientWithExpandParamOptions{ + Top: topParam, + } + } + respr, errRespr := s.srv.WithExpandParam(req.Context(), qp.Get("$expand"), options) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to ServerTransport +var serverTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/azregressions/go.mod b/test/local/azregressions/go.mod new file mode 100644 index 000000000000..010c2c14b49e --- /dev/null +++ b/test/local/azregressions/go.mod @@ -0,0 +1,17 @@ +module azregressions + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + github.com/stretchr/testify v1.11.1 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/test/local/azregressions/go.sum b/test/local/azregressions/go.sum new file mode 100644 index 000000000000..0dbf1c3f100b --- /dev/null +++ b/test/local/azregressions/go.sum @@ -0,0 +1,25 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/local/azregressions/server_test.go b/test/local/azregressions/server_test.go new file mode 100644 index 000000000000..21849f748453 --- /dev/null +++ b/test/local/azregressions/server_test.go @@ -0,0 +1,160 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package azregressions_test + +import ( + "azregressions" + "azregressions/fake" + "context" + "testing" + "time" + + "net/http" + + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/stretchr/testify/require" +) + +func newTestClient(t *testing.T) *azregressions.Client { + t.Helper() + client, err := azregressions.NewClientWithNoCredential("https://fake.endpoint", &azregressions.ClientOptions{ + ClientOptions: policy.ClientOptions{ + Transport: fake.NewServerTransport(&fake.Server{ + GetQueue: func(_ context.Context, _ *azregressions.ClientGetQueueOptions) (resp azfake.Responder[azregressions.ClientGetQueueResponse], errResp azfake.ErrorResponder) { + return + }, + }), + }, + }) + require.NoError(t, err) + return client +} + +// TestCancelledContextPanic reproduces issue https://github.com/Azure/azure-sdk-for-go/issues/25895. +// When the context is already cancelled before calling a fake server method, the outer select in +// dispatchToMethodFake returns immediately on <-req.Context().Done(), defer close(resultChan) +// fires, and then the goroutine tries to send on the now-closed channel, causing a panic. +func TestCancelledContextPanic(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() // cancel before calling any method + + client := newTestClient(t) + + for range 500 { + _, err := client.GetQueue(ctx, nil) + require.ErrorIs(t, err, context.Canceled) + } +} + +// TestContextCancelDuringDispatchRace reproduces the race condition identified in +// https://github.com/Azure/azure-sdk-for-go/pull/26444#discussion_r3010484579. +// When the context is cancelled while the goroutine is still dispatching, there is a data race +// between the deferred close(resultChan) in the outer function and the goroutine's send on resultChan. +func TestContextCancelDuringDispatchRace(t *testing.T) { + client := newTestClient(t) + + for range 500 { + // use a near-zero timeout so the context expires while the goroutine is mid-dispatch, + // triggering the race between close(resultChan) and the goroutine's send + ctx, cancel := context.WithTimeout(context.Background(), time.Nanosecond) + _, _ = client.GetQueue(ctx, nil) + cancel() + } +} + +// TestGetIntegerFake verifies that the GetInteger fake server round-trips an integer +// value correctly through the text/plain response body. +func TestGetIntegerFake(t *testing.T) { + const expected int64 = 42 + client, err := azregressions.NewClientWithNoCredential("https://fake.endpoint", &azregressions.ClientOptions{ + ClientOptions: policy.ClientOptions{ + Transport: fake.NewServerTransport(&fake.Server{ + GetInteger: func(_ context.Context, _ *azregressions.ClientGetIntegerOptions) (resp azfake.Responder[azregressions.ClientGetIntegerResponse], errResp azfake.ErrorResponder) { + resp.SetResponse(http.StatusOK, azregressions.ClientGetIntegerResponse{ + Value: to.Ptr(expected), + }, nil) + return + }, + }), + }, + }) + require.NoError(t, err) + + result, err := client.GetInteger(context.Background(), nil) + require.NoError(t, err) + require.NotNil(t, result.Value) + require.Equal(t, expected, *result.Value) +} + +// TestDoubleDecodeQueryParam verifies that query parameter values containing +// percent-encoded sequences (e.g. "foo%20bar") are not double-decoded by the fake server. +// The server's dispatchDoubleDecode calls url.QueryUnescape on a value that is already +// decoded by req.URL.Query(), so "foo%20bar" incorrectly becomes "foo bar". +func TestDoubleDecodeQueryParam(t *testing.T) { + const pathValue = "foo%20bar" + const queryValue = "baz%20qux" + + var receivedPath, receivedQuery string + client, err := azregressions.NewClientWithNoCredential("https://fake.endpoint", &azregressions.ClientOptions{ + ClientOptions: policy.ClientOptions{ + Transport: fake.NewServerTransport(&fake.Server{ + DoubleDecode: func(_ context.Context, pathParam string, query string, _ *azregressions.ClientDoubleDecodeOptions) (resp azfake.Responder[azregressions.ClientDoubleDecodeResponse], errResp azfake.ErrorResponder) { + receivedPath = pathParam + receivedQuery = query + resp.SetResponse(http.StatusNoContent, azregressions.ClientDoubleDecodeResponse{}, nil) + return + }, + }), + }, + }) + require.NoError(t, err) + + _, err = client.DoubleDecode(context.Background(), pathValue, queryValue, nil) + require.NoError(t, err) + require.Equal(t, pathValue, receivedPath, "path param was double-decoded") + require.Equal(t, queryValue, receivedQuery, "query param was double-decoded") +} + +// TestDoubleDecodeQueryParamPlusAndSpace verifies that query parameter values containing +// literal '+' characters and spaces round-trip correctly. Line 173 of zz_client.go replaces +// '+' (which url.Values.Encode uses for spaces) with '%20'. A literal '+' in the original +// value is encoded as '%2B' by Set and must not be corrupted by this replacement. +func TestDoubleDecodeQueryParamPlusAndSpace(t *testing.T) { + tests := []struct { + name string + path string + query string + }{ + {"literal plus", "path-value", "hello+world"}, + {"space", "path-value", "hello world"}, + {"plus and space", "path-value", "a + b = c"}, + {"encoded plus in path", "path+value", "query+value"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var receivedPath, receivedQuery string + client, err := azregressions.NewClientWithNoCredential("https://fake.endpoint", &azregressions.ClientOptions{ + ClientOptions: policy.ClientOptions{ + Transport: fake.NewServerTransport(&fake.Server{ + DoubleDecode: func(_ context.Context, pathParam string, query string, _ *azregressions.ClientDoubleDecodeOptions) (resp azfake.Responder[azregressions.ClientDoubleDecodeResponse], errResp azfake.ErrorResponder) { + receivedPath = pathParam + receivedQuery = query + resp.SetResponse(http.StatusNoContent, azregressions.ClientDoubleDecodeResponse{}, nil) + return + }, + }), + }, + }) + require.NoError(t, err) + + _, err = client.DoubleDecode(context.Background(), tt.path, tt.query, nil) + require.NoError(t, err) + require.Equal(t, tt.path, receivedPath, "path param mismatch") + require.Equal(t, tt.query, receivedQuery, "query param mismatch") + }) + } +} diff --git a/test/local/azregressions/testdata/_metadata.json b/test/local/azregressions/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/local/azregressions/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/local/azregressions/zz_client.go b/test/local/azregressions/zz_client.go new file mode 100644 index 000000000000..28c4741070df --- /dev/null +++ b/test/local/azregressions/zz_client.go @@ -0,0 +1,927 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azregressions + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "io" + "net/http" + "net/url" + "strconv" + "strings" +) + +// Client contains the methods for the service. +// Don't use this type directly, use NewClientWithNoCredential() instead. +type Client struct { + internal *azcore.Client + endpoint string +} + +// ClientOptions contains the optional values for creating a [Client]. +type ClientOptions struct { + azcore.ClientOptions +} + +// NewClientWithNoCredential creates a new instance of Client with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewClientWithNoCredential(endpoint string, options *ClientOptions) (*Client, error) { + if options == nil { + options = &ClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + endpoint = runtime.JoinPaths(endpoint, "supplemental-path") + client := &Client{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// BinaryBodyWithContentType - required contentType parameter is passed to req.SetBody() +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientBinaryBodyWithContentTypeOptions contains the optional parameters for the Client.BinaryBodyWithContentType +// method. +func (client *Client) BinaryBodyWithContentType(ctx context.Context, payload io.ReadSeekCloser, contentType string, options *ClientBinaryBodyWithContentTypeOptions) (ClientBinaryBodyWithContentTypeResponse, error) { + var err error + const operationName = "Client.BinaryBodyWithContentType" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.binaryBodyWithContentTypeCreateRequest(ctx, payload, contentType, options) + if err != nil { + return ClientBinaryBodyWithContentTypeResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientBinaryBodyWithContentTypeResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ClientBinaryBodyWithContentTypeResponse{}, err + } + return ClientBinaryBodyWithContentTypeResponse{}, nil +} + +// binaryBodyWithContentTypeCreateRequest creates the BinaryBodyWithContentType request. +func (client *Client) binaryBodyWithContentTypeCreateRequest(ctx context.Context, payload io.ReadSeekCloser, contentType string, _ *ClientBinaryBodyWithContentTypeOptions) (*policy.Request, error) { + urlPath := "/binary-payload-with-content-type" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + if err := req.SetBody(payload, contentType); err != nil { + return nil, err + } + return req, nil +} + +// BinaryResponseWithXMLContentType - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientBinaryResponseWithXMLContentTypeOptions contains the optional parameters for the Client.BinaryResponseWithXMLContentType +// method. +func (client *Client) BinaryResponseWithXMLContentType(ctx context.Context, options *ClientBinaryResponseWithXMLContentTypeOptions) (ClientBinaryResponseWithXMLContentTypeResponse, error) { + var err error + const operationName = "Client.BinaryResponseWithXMLContentType" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.binaryResponseWithXMLContentTypeCreateRequest(ctx, options) + if err != nil { + return ClientBinaryResponseWithXMLContentTypeResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientBinaryResponseWithXMLContentTypeResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientBinaryResponseWithXMLContentTypeResponse{}, err + } + resp, err := client.binaryResponseWithXMLContentTypeHandleResponse(httpResp) + return resp, err +} + +// binaryResponseWithXMLContentTypeCreateRequest creates the BinaryResponseWithXMLContentType request. +func (client *Client) binaryResponseWithXMLContentTypeCreateRequest(ctx context.Context, _ *ClientBinaryResponseWithXMLContentTypeOptions) (*policy.Request, error) { + urlPath := "/binary-response-with-xml-content-type" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + runtime.SkipBodyDownload(req) + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// binaryResponseWithXMLContentTypeHandleResponse handles the BinaryResponseWithXMLContentType response. +func (client *Client) binaryResponseWithXMLContentTypeHandleResponse(resp *http.Response) (ClientBinaryResponseWithXMLContentTypeResponse, error) { + result := ClientBinaryResponseWithXMLContentTypeResponse{Body: resp.Body} + if val := resp.Header.Get("Content-Type"); val != "" { + result.ContentType = &val + } + return result, nil +} + +// DoubleDecode - ensure that path and query parameters aren't double-decoded by the fake server +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientDoubleDecodeOptions contains the optional parameters for the Client.DoubleDecode method. +func (client *Client) DoubleDecode(ctx context.Context, pathParam string, query string, options *ClientDoubleDecodeOptions) (ClientDoubleDecodeResponse, error) { + var err error + const operationName = "Client.DoubleDecode" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.doubleDecodeCreateRequest(ctx, pathParam, query, options) + if err != nil { + return ClientDoubleDecodeResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientDoubleDecodeResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ClientDoubleDecodeResponse{}, err + } + return ClientDoubleDecodeResponse{}, nil +} + +// doubleDecodeCreateRequest creates the DoubleDecode request. +func (client *Client) doubleDecodeCreateRequest(ctx context.Context, pathParam string, query string, _ *ClientDoubleDecodeOptions) (*policy.Request, error) { + urlPath := "/double-decode/{path}" + if pathParam == "" { + return nil, errors.New("parameter pathParam cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{path}", url.PathEscape(pathParam)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("query", query) + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} + +// ForceRequiredBodyPatch - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientForceRequiredBodyPatchOptions contains the optional parameters for the Client.ForceRequiredBodyPatch method. +func (client *Client) ForceRequiredBodyPatch(ctx context.Context, body SomeModel, options *ClientForceRequiredBodyPatchOptions) (ClientForceRequiredBodyPatchResponse, error) { + var err error + const operationName = "Client.ForceRequiredBodyPatch" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.forceRequiredBodyPatchCreateRequest(ctx, body, options) + if err != nil { + return ClientForceRequiredBodyPatchResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientForceRequiredBodyPatchResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ClientForceRequiredBodyPatchResponse{}, err + } + return ClientForceRequiredBodyPatchResponse{}, nil +} + +// forceRequiredBodyPatchCreateRequest creates the ForceRequiredBodyPatch request. +func (client *Client) forceRequiredBodyPatchCreateRequest(ctx context.Context, body SomeModel, _ *ClientForceRequiredBodyPatchOptions) (*policy.Request, error) { + urlPath := "/force-required-body-patch" + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// ForceRequiredBodyPut - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientForceRequiredBodyPutOptions contains the optional parameters for the Client.ForceRequiredBodyPut method. +func (client *Client) ForceRequiredBodyPut(ctx context.Context, body SomeModel, options *ClientForceRequiredBodyPutOptions) (ClientForceRequiredBodyPutResponse, error) { + var err error + const operationName = "Client.ForceRequiredBodyPut" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.forceRequiredBodyPutCreateRequest(ctx, body, options) + if err != nil { + return ClientForceRequiredBodyPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientForceRequiredBodyPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ClientForceRequiredBodyPutResponse{}, err + } + return ClientForceRequiredBodyPutResponse{}, nil +} + +// forceRequiredBodyPutCreateRequest creates the ForceRequiredBodyPut request. +func (client *Client) forceRequiredBodyPutCreateRequest(ctx context.Context, body SomeModel, _ *ClientForceRequiredBodyPutOptions) (*policy.Request, error) { + urlPath := "/force-required-body-put" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// GetBool - returns a boolean as text/plain +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientGetBoolOptions contains the optional parameters for the Client.GetBool method. +func (client *Client) GetBool(ctx context.Context, options *ClientGetBoolOptions) (ClientGetBoolResponse, error) { + var err error + const operationName = "Client.GetBool" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getBoolCreateRequest(ctx, options) + if err != nil { + return ClientGetBoolResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientGetBoolResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientGetBoolResponse{}, err + } + resp, err := client.getBoolHandleResponse(httpResp) + return resp, err +} + +// getBoolCreateRequest creates the GetBool request. +func (client *Client) getBoolCreateRequest(ctx context.Context, _ *ClientGetBoolOptions) (*policy.Request, error) { + urlPath := "/text-body-as-bool" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"text/plain; charset=utf-8"} + return req, nil +} + +// getBoolHandleResponse handles the GetBool response. +func (client *Client) getBoolHandleResponse(resp *http.Response) (ClientGetBoolResponse, error) { + result := ClientGetBoolResponse{} + body, err := runtime.Payload(resp) + if err != nil { + return ClientGetBoolResponse{}, err + } + parsedBody, err := strconv.ParseBool(string(body)) + if err != nil { + return ClientGetBoolResponse{}, err + } + result.Value = &parsedBody + return result, nil +} + +// GetDiscriminatedNoSubTypes - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientGetDiscriminatedNoSubTypesOptions contains the optional parameters for the Client.GetDiscriminatedNoSubTypes +// method. +func (client *Client) GetDiscriminatedNoSubTypes(ctx context.Context, options *ClientGetDiscriminatedNoSubTypesOptions) (ClientGetDiscriminatedNoSubTypesResponse, error) { + var err error + const operationName = "Client.GetDiscriminatedNoSubTypes" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getDiscriminatedNoSubTypesCreateRequest(ctx, options) + if err != nil { + return ClientGetDiscriminatedNoSubTypesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientGetDiscriminatedNoSubTypesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientGetDiscriminatedNoSubTypesResponse{}, err + } + resp, err := client.getDiscriminatedNoSubTypesHandleResponse(httpResp) + return resp, err +} + +// getDiscriminatedNoSubTypesCreateRequest creates the GetDiscriminatedNoSubTypes request. +func (client *Client) getDiscriminatedNoSubTypesCreateRequest(ctx context.Context, _ *ClientGetDiscriminatedNoSubTypesOptions) (*policy.Request, error) { + urlPath := "/discriminated-no-subtypes" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getDiscriminatedNoSubTypesHandleResponse handles the GetDiscriminatedNoSubTypes response. +func (client *Client) getDiscriminatedNoSubTypesHandleResponse(resp *http.Response) (ClientGetDiscriminatedNoSubTypesResponse, error) { + result := ClientGetDiscriminatedNoSubTypesResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result); err != nil { + return ClientGetDiscriminatedNoSubTypesResponse{}, err + } + return result, nil +} + +// GetFloat - returns a floating point value as text/plain +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientGetFloatOptions contains the optional parameters for the Client.GetFloat method. +func (client *Client) GetFloat(ctx context.Context, options *ClientGetFloatOptions) (ClientGetFloatResponse, error) { + var err error + const operationName = "Client.GetFloat" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getFloatCreateRequest(ctx, options) + if err != nil { + return ClientGetFloatResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientGetFloatResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientGetFloatResponse{}, err + } + resp, err := client.getFloatHandleResponse(httpResp) + return resp, err +} + +// getFloatCreateRequest creates the GetFloat request. +func (client *Client) getFloatCreateRequest(ctx context.Context, _ *ClientGetFloatOptions) (*policy.Request, error) { + urlPath := "/text-body-as-float" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"text/plain; charset=utf-8"} + return req, nil +} + +// getFloatHandleResponse handles the GetFloat response. +func (client *Client) getFloatHandleResponse(resp *http.Response) (ClientGetFloatResponse, error) { + result := ClientGetFloatResponse{} + body, err := runtime.Payload(resp) + if err != nil { + return ClientGetFloatResponse{}, err + } + parsedBody, err := strconv.ParseFloat(string(body), 64) + if err != nil { + return ClientGetFloatResponse{}, err + } + result.Value = &parsedBody + return result, nil +} + +// GetInteger - returns an integer value as text/plain +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientGetIntegerOptions contains the optional parameters for the Client.GetInteger method. +func (client *Client) GetInteger(ctx context.Context, options *ClientGetIntegerOptions) (ClientGetIntegerResponse, error) { + var err error + const operationName = "Client.GetInteger" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getIntegerCreateRequest(ctx, options) + if err != nil { + return ClientGetIntegerResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientGetIntegerResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientGetIntegerResponse{}, err + } + resp, err := client.getIntegerHandleResponse(httpResp) + return resp, err +} + +// getIntegerCreateRequest creates the GetInteger request. +func (client *Client) getIntegerCreateRequest(ctx context.Context, _ *ClientGetIntegerOptions) (*policy.Request, error) { + urlPath := "/text-body-as-int" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"text/plain; charset=utf-8"} + return req, nil +} + +// getIntegerHandleResponse handles the GetInteger response. +func (client *Client) getIntegerHandleResponse(resp *http.Response) (ClientGetIntegerResponse, error) { + result := ClientGetIntegerResponse{} + body, err := runtime.Payload(resp) + if err != nil { + return ClientGetIntegerResponse{}, err + } + parsedBody, err := strconv.ParseInt(string(body), 10, 64) + if err != nil { + return ClientGetIntegerResponse{}, err + } + result.Value = &parsedBody + return result, nil +} + +// GetQueue - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientGetQueueOptions contains the optional parameters for the Client.GetQueue method. +func (client *Client) GetQueue(ctx context.Context, options *ClientGetQueueOptions) (ClientGetQueueResponse, error) { + var err error + const operationName = "Client.GetQueue" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getQueueCreateRequest(ctx, options) + if err != nil { + return ClientGetQueueResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientGetQueueResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientGetQueueResponse{}, err + } + resp, err := client.getQueueHandleResponse(httpResp) + return resp, err +} + +// getQueueCreateRequest creates the GetQueue request. +func (client *Client) getQueueCreateRequest(ctx context.Context, _ *ClientGetQueueOptions) (*policy.Request, error) { + urlPath := "/xml-get-queue" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getQueueHandleResponse handles the GetQueue response. +func (client *Client) getQueueHandleResponse(resp *http.Response) (ClientGetQueueResponse, error) { + result := ClientGetQueueResponse{} + if err := runtime.UnmarshalAsXML(resp, &result.QueueItem); err != nil { + return ClientGetQueueResponse{}, err + } + return result, nil +} + +// GetXMLOne - verify we can swap the default definition of SignedIdentifiers with a custom one +// that maintains the correct XML structure and tags. +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientGetXMLOneOptions contains the optional parameters for the Client.GetXMLOne method. +func (client *Client) GetXMLOne(ctx context.Context, options *ClientGetXMLOneOptions) (ClientGetXMLOneResponse, error) { + var err error + const operationName = "Client.GetXMLOne" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getXMLOneCreateRequest(ctx, options) + if err != nil { + return ClientGetXMLOneResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientGetXMLOneResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientGetXMLOneResponse{}, err + } + resp, err := client.getXMLOneHandleResponse(httpResp) + return resp, err +} + +// getXMLOneCreateRequest creates the GetXMLOne request. +func (client *Client) getXMLOneCreateRequest(ctx context.Context, _ *ClientGetXMLOneOptions) (*policy.Request, error) { + urlPath := "/xml-alternate-type-1" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getXMLOneHandleResponse handles the GetXMLOne response. +func (client *Client) getXMLOneHandleResponse(resp *http.Response) (ClientGetXMLOneResponse, error) { + result := ClientGetXMLOneResponse{} + if err := runtime.UnmarshalAsXML(resp, &result); err != nil { + return ClientGetXMLOneResponse{}, err + } + return result, nil +} + +// GetXMLTwo - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientGetXMLTwoOptions contains the optional parameters for the Client.GetXMLTwo method. +func (client *Client) GetXMLTwo(ctx context.Context, options *ClientGetXMLTwoOptions) (ClientGetXMLTwoResponse, error) { + var err error + const operationName = "Client.GetXMLTwo" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getXMLTwoCreateRequest(ctx, options) + if err != nil { + return ClientGetXMLTwoResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientGetXMLTwoResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return ClientGetXMLTwoResponse{}, err + } + resp, err := client.getXMLTwoHandleResponse(httpResp) + return resp, err +} + +// getXMLTwoCreateRequest creates the GetXMLTwo request. +func (client *Client) getXMLTwoCreateRequest(ctx context.Context, _ *ClientGetXMLTwoOptions) (*policy.Request, error) { + urlPath := "/xml-alternate-type-2" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/xml"} + return req, nil +} + +// getXMLTwoHandleResponse handles the GetXMLTwo response. +func (client *Client) getXMLTwoHandleResponse(resp *http.Response) (ClientGetXMLTwoResponse, error) { + result := ClientGetXMLTwoResponse{} + if err := runtime.UnmarshalAsXML(resp, &result); err != nil { + return ClientGetXMLTwoResponse{}, err + } + return result, nil +} + +// OptionalBinaryBody - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientOptionalBinaryBodyOptions contains the optional parameters for the Client.OptionalBinaryBody method. +func (client *Client) OptionalBinaryBody(ctx context.Context, options *ClientOptionalBinaryBodyOptions) (ClientOptionalBinaryBodyResponse, error) { + var err error + const operationName = "Client.OptionalBinaryBody" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.optionalBinaryBodyCreateRequest(ctx, options) + if err != nil { + return ClientOptionalBinaryBodyResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientOptionalBinaryBodyResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ClientOptionalBinaryBodyResponse{}, err + } + return ClientOptionalBinaryBodyResponse{}, nil +} + +// optionalBinaryBodyCreateRequest creates the OptionalBinaryBody request. +func (client *Client) optionalBinaryBodyCreateRequest(ctx context.Context, options *ClientOptionalBinaryBodyOptions) (*policy.Request, error) { + urlPath := "/optional-binary-payload" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + if options != nil && options.Payload != nil { + req.Raw().Header["Content-Type"] = []string{"application/octet-stream"} + if err := req.SetBody(options.Payload, "application/octet-stream"); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// OptionalBinaryBodyWithContentType - optional contentType parameter is passed to req.SetBody() IFF body is not nil +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientOptionalBinaryBodyWithContentTypeOptions contains the optional parameters for the Client.OptionalBinaryBodyWithContentType +// method. +func (client *Client) OptionalBinaryBodyWithContentType(ctx context.Context, options *ClientOptionalBinaryBodyWithContentTypeOptions) (ClientOptionalBinaryBodyWithContentTypeResponse, error) { + var err error + const operationName = "Client.OptionalBinaryBodyWithContentType" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.optionalBinaryBodyWithContentTypeCreateRequest(ctx, options) + if err != nil { + return ClientOptionalBinaryBodyWithContentTypeResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientOptionalBinaryBodyWithContentTypeResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ClientOptionalBinaryBodyWithContentTypeResponse{}, err + } + return ClientOptionalBinaryBodyWithContentTypeResponse{}, nil +} + +// optionalBinaryBodyWithContentTypeCreateRequest creates the OptionalBinaryBodyWithContentType request. +func (client *Client) optionalBinaryBodyWithContentTypeCreateRequest(ctx context.Context, options *ClientOptionalBinaryBodyWithContentTypeOptions) (*policy.Request, error) { + urlPath := "/optional-binary-payload-with-content-type" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + contentTypeDefault := "*/*" + if options != nil && options.ContentType != nil { + contentTypeDefault = *options.ContentType + } + if options != nil && options.Payload != nil { + if err := req.SetBody(options.Payload, contentTypeDefault); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// OptionalBodyPost - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientOptionalBodyPostOptions contains the optional parameters for the Client.OptionalBodyPost method. +func (client *Client) OptionalBodyPost(ctx context.Context, options *ClientOptionalBodyPostOptions) (ClientOptionalBodyPostResponse, error) { + var err error + const operationName = "Client.OptionalBodyPost" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.optionalBodyPostCreateRequest(ctx, options) + if err != nil { + return ClientOptionalBodyPostResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientOptionalBodyPostResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ClientOptionalBodyPostResponse{}, err + } + return ClientOptionalBodyPostResponse{}, nil +} + +// optionalBodyPostCreateRequest creates the OptionalBodyPost request. +func (client *Client) optionalBodyPostCreateRequest(ctx context.Context, options *ClientOptionalBodyPostOptions) (*policy.Request, error) { + urlPath := "/optional-body-post" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + if options != nil && options.Body != nil { + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, *options.Body); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// PayloadWithExplicitContentType - explicit content-type param is set when creating the request +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientPayloadWithExplicitContentTypeOptions contains the optional parameters for the Client.PayloadWithExplicitContentType +// method. +func (client *Client) PayloadWithExplicitContentType(ctx context.Context, contentType PayloadWithExplicitContentTypeRequestContentType, thing SomeModel, options *ClientPayloadWithExplicitContentTypeOptions) (ClientPayloadWithExplicitContentTypeResponse, error) { + var err error + const operationName = "Client.PayloadWithExplicitContentType" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.payloadWithExplicitContentTypeCreateRequest(ctx, contentType, thing, options) + if err != nil { + return ClientPayloadWithExplicitContentTypeResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientPayloadWithExplicitContentTypeResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ClientPayloadWithExplicitContentTypeResponse{}, err + } + return ClientPayloadWithExplicitContentTypeResponse{}, nil +} + +// payloadWithExplicitContentTypeCreateRequest creates the PayloadWithExplicitContentType request. +func (client *Client) payloadWithExplicitContentTypeCreateRequest(ctx context.Context, contentType PayloadWithExplicitContentTypeRequestContentType, thing SomeModel, _ *ClientPayloadWithExplicitContentTypeOptions) (*policy.Request, error) { + urlPath := "/payload-with-explicit-content-type" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{string(contentType)} + if err := runtime.MarshalAsJSON(req, thing); err != nil { + return nil, err + } + return req, nil +} + +// SpreadWithModel - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientSpreadWithModelOptions contains the optional parameters for the Client.SpreadWithModel method. +func (client *Client) SpreadWithModel(ctx context.Context, name string, options *ClientSpreadWithModelOptions) (ClientSpreadWithModelResponse, error) { + var err error + const operationName = "Client.SpreadWithModel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.spreadWithModelCreateRequest(ctx, name, options) + if err != nil { + return ClientSpreadWithModelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientSpreadWithModelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ClientSpreadWithModelResponse{}, err + } + return ClientSpreadWithModelResponse{}, nil +} + +// spreadWithModelCreateRequest creates the SpreadWithModel request. +func (client *Client) spreadWithModelCreateRequest(ctx context.Context, name string, options *ClientSpreadWithModelOptions) (*policy.Request, error) { + urlPath := "/spread-with-model" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + body := struct { + Name string `json:"name"` + Color *string `json:"color"` + Inner *InnerSpreadParam `json:"inner"` + }{ + Name: name, + } + if options != nil && options.Color != nil { + body.Color = options.Color + } + if options != nil && options.Inner != nil { + body.Inner = options.Inner + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// WithClientDefaultModelField - model with a client-side default that's an enum +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientWithClientDefaultModelFieldOptions contains the optional parameters for the Client.WithClientDefaultModelField +// method. +func (client *Client) WithClientDefaultModelField(ctx context.Context, widget Widget, options *ClientWithClientDefaultModelFieldOptions) (ClientWithClientDefaultModelFieldResponse, error) { + var err error + const operationName = "Client.WithClientDefaultModelField" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withClientDefaultModelFieldCreateRequest(ctx, widget, options) + if err != nil { + return ClientWithClientDefaultModelFieldResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientWithClientDefaultModelFieldResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ClientWithClientDefaultModelFieldResponse{}, err + } + return ClientWithClientDefaultModelFieldResponse{}, nil +} + +// withClientDefaultModelFieldCreateRequest creates the WithClientDefaultModelField request. +func (client *Client) withClientDefaultModelFieldCreateRequest(ctx context.Context, widget Widget, _ *ClientWithClientDefaultModelFieldOptions) (*policy.Request, error) { + urlPath := "/model-with-default-const" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, widget); err != nil { + return nil, err + } + return req, nil +} + +// WithClientDefaultValues - path params that aren't string types with client-side defaults +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientWithClientDefaultValuesOptions contains the optional parameters for the Client.WithClientDefaultValues +// method. +func (client *Client) WithClientDefaultValues(ctx context.Context, options *ClientWithClientDefaultValuesOptions) (ClientWithClientDefaultValuesResponse, error) { + var err error + const operationName = "Client.WithClientDefaultValues" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withClientDefaultValuesCreateRequest(ctx, options) + if err != nil { + return ClientWithClientDefaultValuesResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientWithClientDefaultValuesResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ClientWithClientDefaultValuesResponse{}, err + } + return ClientWithClientDefaultValuesResponse{}, nil +} + +// withClientDefaultValuesCreateRequest creates the WithClientDefaultValues request. +func (client *Client) withClientDefaultValuesCreateRequest(ctx context.Context, options *ClientWithClientDefaultValuesOptions) (*policy.Request, error) { + urlPath := "/non-string-path-params/{color}/{count}" + colorDefault := ColorBlue + if options != nil && options.Color != nil { + colorDefault = *options.Color + } + urlPath = strings.ReplaceAll(urlPath, "{color}", url.PathEscape(string(colorDefault))) + countDefault := int32(123) + if options != nil && options.Count != nil { + countDefault = *options.Count + } + urlPath = strings.ReplaceAll(urlPath, "{count}", url.PathEscape(strconv.FormatInt(int64(countDefault), 10))) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + return req, nil +} + +// WithExpandParam - ensure that parameter names that start with invalid Go identifiers are properly cased +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientWithExpandParamOptions contains the optional parameters for the Client.WithExpandParam method. +func (client *Client) WithExpandParam(ctx context.Context, expand string, options *ClientWithExpandParamOptions) (ClientWithExpandParamResponse, error) { + var err error + const operationName = "Client.WithExpandParam" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.withExpandParamCreateRequest(ctx, expand, options) + if err != nil { + return ClientWithExpandParamResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientWithExpandParamResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ClientWithExpandParamResponse{}, err + } + return ClientWithExpandParamResponse{}, nil +} + +// withExpandParamCreateRequest creates the WithExpandParam request. +func (client *Client) withExpandParamCreateRequest(ctx context.Context, expand string, options *ClientWithExpandParamOptions) (*policy.Request, error) { + urlPath := "/fixed-param-name" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("$expand", expand) + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + req.Raw().URL.RawQuery = strings.ReplaceAll(reqQP.Encode(), "+", "%20") + return req, nil +} diff --git a/test/local/azregressions/zz_constants.go b/test/local/azregressions/zz_constants.go new file mode 100644 index 000000000000..38c1fb2c8961 --- /dev/null +++ b/test/local/azregressions/zz_constants.go @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azregressions + +type Color string + +const ( + ColorBlue Color = "blue" + ColorGreen Color = "green" + ColorRed Color = "red" +) + +// PossibleColorValues returns the possible values for the Color const type. +func PossibleColorValues() []Color { + return []Color{ + ColorBlue, + ColorGreen, + ColorRed, + } +} + +// NetworkVersion - extensible enum (i.e. isFixed === false) used to verify that a +// client-side default value not present in the pre-defined values +// is still accepted (regression test for issue with property names +// like `networkApiVersion` whose default is the service API version). +type NetworkVersion string + +const ( + NetworkVersionV1 NetworkVersion = "2020-11-01" + NetworkVersionV2 NetworkVersion = "2022-11-01" +) + +// PossibleNetworkVersionValues returns the possible values for the NetworkVersion const type. +func PossibleNetworkVersionValues() []NetworkVersion { + return []NetworkVersion{ + NetworkVersionV1, + NetworkVersionV2, + } +} + +type PayloadWithExplicitContentTypeRequestContentType string + +const ( + PayloadWithExplicitContentTypeRequestContentTypeApplicationJSON PayloadWithExplicitContentTypeRequestContentType = "application/json" + PayloadWithExplicitContentTypeRequestContentTypeApplicationSnapshotJSON PayloadWithExplicitContentTypeRequestContentType = "application/snapshot+json" +) + +// PossiblePayloadWithExplicitContentTypeRequestContentTypeValues returns the possible values for the PayloadWithExplicitContentTypeRequestContentType const type. +func PossiblePayloadWithExplicitContentTypeRequestContentTypeValues() []PayloadWithExplicitContentTypeRequestContentType { + return []PayloadWithExplicitContentTypeRequestContentType{ + PayloadWithExplicitContentTypeRequestContentTypeApplicationJSON, + PayloadWithExplicitContentTypeRequestContentTypeApplicationSnapshotJSON, + } +} diff --git a/test/local/azregressions/zz_interfaces.go b/test/local/azregressions/zz_interfaces.go new file mode 100644 index 000000000000..f8dff15e2265 --- /dev/null +++ b/test/local/azregressions/zz_interfaces.go @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azregressions + +// DiscriminatedBaseNoSubTypesClassification provides polymorphic access to related types. +// Call the interface's GetDiscriminatedBaseNoSubTypes() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *DiscriminatedBaseNoSubTypes +type DiscriminatedBaseNoSubTypesClassification interface { + // GetDiscriminatedBaseNoSubTypes returns the DiscriminatedBaseNoSubTypes content of the underlying type. + GetDiscriminatedBaseNoSubTypes() *DiscriminatedBaseNoSubTypes +} diff --git a/test/local/azregressions/zz_models.go b/test/local/azregressions/zz_models.go new file mode 100644 index 000000000000..f57d3354073d --- /dev/null +++ b/test/local/azregressions/zz_models.go @@ -0,0 +1,61 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azregressions + +type DequeuedMessage struct { + // REQUIRED + MessageID *string `xml:"MessageId"` +} + +// DiscriminatedBaseNoSubTypes - A discriminated base type with no subtypes. +type DiscriminatedBaseNoSubTypes struct { + // REQUIRED; Some property. + Name *string + + // REQUIRED; The discriminator type. + Type *string +} + +// GetDiscriminatedBaseNoSubTypes implements the DiscriminatedBaseNoSubTypesClassification interface for type DiscriminatedBaseNoSubTypes. +func (d *DiscriminatedBaseNoSubTypes) GetDiscriminatedBaseNoSubTypes() *DiscriminatedBaseNoSubTypes { + return d +} + +type InnerSpreadParam struct { + // REQUIRED + Code *int32 + + // REQUIRED + Name *string +} + +type QueueItem struct { + // REQUIRED + Name *string `xml:"Name"` + Metadata map[string]*string `xml:"Metadata"` +} + +type SignedIdentifier struct { + // REQUIRED + ID *string `xml:"Id"` +} + +type SomeModel struct { + // REQUIRED + Name *string +} + +type Widget struct { + // The default value is ColorGreen. + // + // REQUIRED + Color *Color + + // REQUIRED + Name *string + + // The default value is NetworkVersion("2026-04-15-preview"). + NetworkVersion *NetworkVersion +} diff --git a/test/local/azregressions/zz_models_serde.go b/test/local/azregressions/zz_models_serde.go new file mode 100644 index 000000000000..be6c36c3e1cc --- /dev/null +++ b/test/local/azregressions/zz_models_serde.go @@ -0,0 +1,206 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azregressions + +import ( + "encoding/json" + "encoding/xml" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "reflect" +) + +// MarshalXML implements the xml.Marshaller interface for type DequeuedMessage. +func (d DequeuedMessage) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + start.Name.Local = "QueueMessage" + type alias DequeuedMessage + aux := &struct { + *alias + }{ + alias: (*alias)(&d), + } + return enc.EncodeElement(aux, start) +} + +// MarshalJSON implements the json.Marshaller interface for type DiscriminatedBaseNoSubTypes. +func (d DiscriminatedBaseNoSubTypes) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", d.Name) + populate(objectMap, "type", d.Type) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DiscriminatedBaseNoSubTypes. +func (d *DiscriminatedBaseNoSubTypes) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &d.Name) + delete(rawMsg, key) + case "type": + err = unpopulate(val, "Type", &d.Type) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", d, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type InnerSpreadParam. +func (i InnerSpreadParam) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "code", i.Code) + populate(objectMap, "name", i.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InnerSpreadParam. +func (i *InnerSpreadParam) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "code": + err = unpopulate(val, "Code", &i.Code) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &i.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", i, err) + } + } + return nil +} + +// MarshalXML implements the xml.Marshaller interface for type QueueItem. +func (q QueueItem) MarshalXML(enc *xml.Encoder, start xml.StartElement) error { + start.Name.Local = "Queue" + type alias QueueItem + aux := &struct { + *alias + Metadata additionalProperties `xml:"Metadata"` + }{ + alias: (*alias)(&q), + } + aux.Metadata = (additionalProperties)(q.Metadata) + return enc.EncodeElement(aux, start) +} + +// UnmarshalXML implements the xml.Unmarshaller interface for type QueueItem. +func (q *QueueItem) UnmarshalXML(dec *xml.Decoder, start xml.StartElement) error { + type alias QueueItem + aux := &struct { + *alias + Metadata additionalProperties `xml:"Metadata"` + }{ + alias: (*alias)(q), + } + if err := dec.DecodeElement(aux, &start); err != nil { + return err + } + q.Metadata = (map[string]*string)(aux.Metadata) + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type SomeModel. +func (s SomeModel) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "name", s.Name) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SomeModel. +func (s *SomeModel) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "name": + err = unpopulate(val, "Name", &s.Name) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", s, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type Widget. +func (w Widget) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + if w.Color == nil { + w.Color = to.Ptr(ColorGreen) + } + populate(objectMap, "color", w.Color) + populate(objectMap, "name", w.Name) + if w.NetworkVersion == nil { + w.NetworkVersion = to.Ptr(NetworkVersion("2026-04-15-preview")) + } + populate(objectMap, "networkVersion", w.NetworkVersion) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Widget. +func (w *Widget) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "color": + err = unpopulate(val, "Color", &w.Color) + delete(rawMsg, key) + case "name": + err = unpopulate(val, "Name", &w.Name) + delete(rawMsg, key) + case "networkVersion": + err = unpopulate(val, "NetworkVersion", &w.NetworkVersion) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/local/azregressions/zz_options.go b/test/local/azregressions/zz_options.go new file mode 100644 index 000000000000..fa951684a656 --- /dev/null +++ b/test/local/azregressions/zz_options.go @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azregressions + +import "io" + +// ClientBinaryBodyWithContentTypeOptions contains the optional parameters for the Client.BinaryBodyWithContentType method. +type ClientBinaryBodyWithContentTypeOptions struct { + // placeholder for future optional parameters +} + +// ClientBinaryResponseWithXMLContentTypeOptions contains the optional parameters for the Client.BinaryResponseWithXMLContentType +// method. +type ClientBinaryResponseWithXMLContentTypeOptions struct { + // placeholder for future optional parameters +} + +// ClientDoubleDecodeOptions contains the optional parameters for the Client.DoubleDecode method. +type ClientDoubleDecodeOptions struct { + // placeholder for future optional parameters +} + +// ClientForceRequiredBodyPatchOptions contains the optional parameters for the Client.ForceRequiredBodyPatch method. +type ClientForceRequiredBodyPatchOptions struct { + // placeholder for future optional parameters +} + +// ClientForceRequiredBodyPutOptions contains the optional parameters for the Client.ForceRequiredBodyPut method. +type ClientForceRequiredBodyPutOptions struct { + // placeholder for future optional parameters +} + +// ClientGetBoolOptions contains the optional parameters for the Client.GetBool method. +type ClientGetBoolOptions struct { + // placeholder for future optional parameters +} + +// ClientGetDiscriminatedNoSubTypesOptions contains the optional parameters for the Client.GetDiscriminatedNoSubTypes method. +type ClientGetDiscriminatedNoSubTypesOptions struct { + // placeholder for future optional parameters +} + +// ClientGetFloatOptions contains the optional parameters for the Client.GetFloat method. +type ClientGetFloatOptions struct { + // placeholder for future optional parameters +} + +// ClientGetIntegerOptions contains the optional parameters for the Client.GetInteger method. +type ClientGetIntegerOptions struct { + // placeholder for future optional parameters +} + +// ClientGetQueueOptions contains the optional parameters for the Client.GetQueue method. +type ClientGetQueueOptions struct { + // placeholder for future optional parameters +} + +// ClientGetXMLOneOptions contains the optional parameters for the Client.GetXMLOne method. +type ClientGetXMLOneOptions struct { + // placeholder for future optional parameters +} + +// ClientGetXMLTwoOptions contains the optional parameters for the Client.GetXMLTwo method. +type ClientGetXMLTwoOptions struct { + // placeholder for future optional parameters +} + +// ClientOptionalBinaryBodyOptions contains the optional parameters for the Client.OptionalBinaryBody method. +type ClientOptionalBinaryBodyOptions struct { + Payload io.ReadSeekCloser +} + +// ClientOptionalBinaryBodyWithContentTypeOptions contains the optional parameters for the Client.OptionalBinaryBodyWithContentType +// method. +type ClientOptionalBinaryBodyWithContentTypeOptions struct { + ContentType *string + Payload io.ReadSeekCloser +} + +// ClientOptionalBodyPostOptions contains the optional parameters for the Client.OptionalBodyPost method. +type ClientOptionalBodyPostOptions struct { + Body *SomeModel +} + +// ClientPayloadWithExplicitContentTypeOptions contains the optional parameters for the Client.PayloadWithExplicitContentType +// method. +type ClientPayloadWithExplicitContentTypeOptions struct { + // placeholder for future optional parameters +} + +// ClientSpreadWithModelOptions contains the optional parameters for the Client.SpreadWithModel method. +type ClientSpreadWithModelOptions struct { + Color *string + Inner *InnerSpreadParam +} + +// ClientWithClientDefaultModelFieldOptions contains the optional parameters for the Client.WithClientDefaultModelField method. +type ClientWithClientDefaultModelFieldOptions struct { + // placeholder for future optional parameters +} + +// ClientWithClientDefaultValuesOptions contains the optional parameters for the Client.WithClientDefaultValues method. +type ClientWithClientDefaultValuesOptions struct { + // The default value is ColorBlue. + Color *Color + + // The default value is 123. + Count *int32 +} + +// ClientWithExpandParamOptions contains the optional parameters for the Client.WithExpandParam method. +type ClientWithExpandParamOptions struct { + Top *int32 +} diff --git a/test/local/azregressions/zz_polymorphic_helpers.go b/test/local/azregressions/zz_polymorphic_helpers.go new file mode 100644 index 000000000000..0258b009a93f --- /dev/null +++ b/test/local/azregressions/zz_polymorphic_helpers.go @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azregressions + +import "encoding/json" + +func unmarshalDiscriminatedBaseNoSubTypesClassification(rawMsg json.RawMessage) (DiscriminatedBaseNoSubTypesClassification, error) { + if rawMsg == nil || string(rawMsg) == "null" { + return nil, nil + } + var m map[string]any + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b DiscriminatedBaseNoSubTypesClassification + switch m["type"] { + default: + b = &DiscriminatedBaseNoSubTypes{} + } + if err := json.Unmarshal(rawMsg, b); err != nil { + return nil, err + } + return b, nil +} diff --git a/test/local/azregressions/zz_responses.go b/test/local/azregressions/zz_responses.go new file mode 100644 index 000000000000..121ee7848e0e --- /dev/null +++ b/test/local/azregressions/zz_responses.go @@ -0,0 +1,110 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azregressions + +import "io" + +// ClientBinaryBodyWithContentTypeResponse contains the response from method Client.BinaryBodyWithContentType. +type ClientBinaryBodyWithContentTypeResponse struct { + // placeholder for future response values +} + +// ClientBinaryResponseWithXMLContentTypeResponse contains the response from method Client.BinaryResponseWithXMLContentType. +type ClientBinaryResponseWithXMLContentTypeResponse struct { + // Body contains the streaming response. + Body io.ReadCloser + ContentType *string +} + +// ClientDoubleDecodeResponse contains the response from method Client.DoubleDecode. +type ClientDoubleDecodeResponse struct { + // placeholder for future response values +} + +// ClientForceRequiredBodyPatchResponse contains the response from method Client.ForceRequiredBodyPatch. +type ClientForceRequiredBodyPatchResponse struct { + // placeholder for future response values +} + +// ClientForceRequiredBodyPutResponse contains the response from method Client.ForceRequiredBodyPut. +type ClientForceRequiredBodyPutResponse struct { + // placeholder for future response values +} + +// ClientGetBoolResponse contains the response from method Client.GetBool. +type ClientGetBoolResponse struct { + Value *bool +} + +// ClientGetDiscriminatedNoSubTypesResponse contains the response from method Client.GetDiscriminatedNoSubTypes. +type ClientGetDiscriminatedNoSubTypesResponse struct { + // A discriminated base type with no subtypes. + DiscriminatedBaseNoSubTypesClassification +} + +// ClientGetFloatResponse contains the response from method Client.GetFloat. +type ClientGetFloatResponse struct { + Value *float64 +} + +// ClientGetIntegerResponse contains the response from method Client.GetInteger. +type ClientGetIntegerResponse struct { + Value *int64 +} + +// ClientGetQueueResponse contains the response from method Client.GetQueue. +type ClientGetQueueResponse struct { + QueueItem +} + +// ClientGetXMLOneResponse contains the response from method Client.GetXMLOne. +type ClientGetXMLOneResponse struct { + SignedIdentifiers []*SignedIdentifier `xml:"SignedIdentifier"` +} + +// ClientGetXMLTwoResponse contains the response from method Client.GetXMLTwo. +type ClientGetXMLTwoResponse struct { + Messages []*DequeuedMessage `xml:"QueueMessage"` +} + +// ClientOptionalBinaryBodyResponse contains the response from method Client.OptionalBinaryBody. +type ClientOptionalBinaryBodyResponse struct { + // placeholder for future response values +} + +// ClientOptionalBinaryBodyWithContentTypeResponse contains the response from method Client.OptionalBinaryBodyWithContentType. +type ClientOptionalBinaryBodyWithContentTypeResponse struct { + // placeholder for future response values +} + +// ClientOptionalBodyPostResponse contains the response from method Client.OptionalBodyPost. +type ClientOptionalBodyPostResponse struct { + // placeholder for future response values +} + +// ClientPayloadWithExplicitContentTypeResponse contains the response from method Client.PayloadWithExplicitContentType. +type ClientPayloadWithExplicitContentTypeResponse struct { + // placeholder for future response values +} + +// ClientSpreadWithModelResponse contains the response from method Client.SpreadWithModel. +type ClientSpreadWithModelResponse struct { + // placeholder for future response values +} + +// ClientWithClientDefaultModelFieldResponse contains the response from method Client.WithClientDefaultModelField. +type ClientWithClientDefaultModelFieldResponse struct { + // placeholder for future response values +} + +// ClientWithClientDefaultValuesResponse contains the response from method Client.WithClientDefaultValues. +type ClientWithClientDefaultValuesResponse struct { + // placeholder for future response values +} + +// ClientWithExpandParamResponse contains the response from method Client.WithExpandParam. +type ClientWithExpandParamResponse struct { + // placeholder for future response values +} diff --git a/test/local/azregressions/zz_responses_serde.go b/test/local/azregressions/zz_responses_serde.go new file mode 100644 index 000000000000..bfcc0204208a --- /dev/null +++ b/test/local/azregressions/zz_responses_serde.go @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azregressions + +// UnmarshalJSON implements the json.Unmarshaller interface for type ClientGetDiscriminatedNoSubTypesResponse. +func (c *ClientGetDiscriminatedNoSubTypesResponse) UnmarshalJSON(data []byte) error { + res, err := unmarshalDiscriminatedBaseNoSubTypesClassification(data) + if err != nil { + return err + } + c.DiscriminatedBaseNoSubTypesClassification = res + return nil +} diff --git a/test/local/azregressions/zz_version.go b/test/local/azregressions/zz_version.go new file mode 100644 index 000000000000..8fde1637e6a4 --- /dev/null +++ b/test/local/azregressions/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package azregressions + +const ( + moduleName = "azregressions" + moduleVersion = "v0.1.0" +) diff --git a/test/local/azregressions/zz_xml_helper.go b/test/local/azregressions/zz_xml_helper.go new file mode 100644 index 000000000000..bb4156a38d48 --- /dev/null +++ b/test/local/azregressions/zz_xml_helper.go @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package azregressions + +import ( + "encoding/xml" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "io" + "strings" +) + +type additionalProperties map[string]*string + +// MarshalXML implements the xml.Marshaler interface for additionalProperties. +func (ap additionalProperties) MarshalXML(e *xml.Encoder, start xml.StartElement) error { + if err := e.EncodeToken(start); err != nil { + return err + } + for k, v := range ap { + err := e.EncodeToken(xml.StartElement{ + Name: xml.Name{ + Local: k, + }, + }) + if err != nil { + return err + } + if v != nil { + err = e.EncodeToken(xml.CharData(*v)) + if err != nil { + return err + } + } + err = e.EncodeToken(xml.EndElement{ + Name: xml.Name{ + Local: k, + }, + }) + if err != nil { + return err + } + } + return e.EncodeToken(xml.EndElement{ + Name: start.Name, + }) +} + +// UnmarshalXML implements the xml.Unmarshaler interface for additionalProperties. +func (ap *additionalProperties) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { + tokName := "" + tokValue := "" + for { + t, err := d.Token() + if errors.Is(err, io.EOF) { + break + } else if err != nil { + return err + } + switch tt := t.(type) { + case xml.StartElement: + tokName = strings.ToLower(tt.Name.Local) + tokValue = "" + case xml.CharData: + if tokName == "" { + continue + } + tokValue = string(tt) + case xml.EndElement: + if tokName == "" { + continue + } + if *ap == nil { + *ap = additionalProperties{} + } + (*ap)[tokName] = to.Ptr(tokValue) + tokName = "" + } + } + return nil +} diff --git a/test/local/internalpager/LICENSE.txt b/test/local/internalpager/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/local/internalpager/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/local/internalpager/go.mod b/test/local/internalpager/go.mod new file mode 100644 index 000000000000..dd2b2345ddcf --- /dev/null +++ b/test/local/internalpager/go.mod @@ -0,0 +1,11 @@ +module internalpager + +go 1.25.0 + +require github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect +) diff --git a/test/local/internalpager/go.sum b/test/local/internalpager/go.sum new file mode 100644 index 000000000000..3fdb64caf441 --- /dev/null +++ b/test/local/internalpager/go.sum @@ -0,0 +1,16 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/local/internalpager/testdata/_metadata.json b/test/local/internalpager/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/local/internalpager/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/local/internalpager/zz_constants.go b/test/local/internalpager/zz_constants.go new file mode 100644 index 000000000000..489fec316d35 --- /dev/null +++ b/test/local/internalpager/zz_constants.go @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package internalpager + +type widgetColor string + +const ( + widgetColorBlue widgetColor = "Blue" + widgetColorGreen widgetColor = "Green" + widgetColorRed widgetColor = "Red" +) + +// possiblewidgetColorValues returns the possible values for the widgetColor const type. +func possiblewidgetColorValues() []widgetColor { + return []widgetColor{ + widgetColorBlue, + widgetColorGreen, + widgetColorRed, + } +} diff --git a/test/local/internalpager/zz_models.go b/test/local/internalpager/zz_models.go new file mode 100644 index 000000000000..6d43d25f49e9 --- /dev/null +++ b/test/local/internalpager/zz_models.go @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package internalpager + +type widget struct { + // REQUIRED + Color *widgetColor + + // REQUIRED + Weight *int32 +} + +type widgetList struct { + // REQUIRED + Values []*widget +} diff --git a/test/local/internalpager/zz_models_serde.go b/test/local/internalpager/zz_models_serde.go new file mode 100644 index 000000000000..12aa057c1adf --- /dev/null +++ b/test/local/internalpager/zz_models_serde.go @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package internalpager + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type widget. +func (w widget) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "color", w.Color) + populate(objectMap, "weight", w.Weight) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type widget. +func (w *widget) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "color": + err = unpopulate(val, "Color", &w.Color) + delete(rawMsg, key) + case "weight": + err = unpopulate(val, "Weight", &w.Weight) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +// MarshalJSON implements the json.Marshaller interface for type widgetList. +func (w widgetList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "values", w.Values) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type widgetList. +func (w *widgetList) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "values": + err = unpopulate(val, "Values", &w.Values) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/local/internalpager/zz_options.go b/test/local/internalpager/zz_options.go new file mode 100644 index 000000000000..41d09f0a5ef6 --- /dev/null +++ b/test/local/internalpager/zz_options.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package internalpager + +// pagerWidgetsClientlistOptions contains the optional parameters for the PagerWidgetsClient.NewlistPager method. +type pagerWidgetsClientlistOptions struct { + // placeholder for future optional parameters +} diff --git a/test/local/internalpager/zz_pager_client.go b/test/local/internalpager/zz_pager_client.go new file mode 100644 index 000000000000..0a6a38b37635 --- /dev/null +++ b/test/local/internalpager/zz_pager_client.go @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package internalpager + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// PagerClient contains the methods for the Pager group. +// Don't use this type directly, use NewPagerClientWithNoCredential() instead. +type PagerClient struct { + internal *azcore.Client + endpoint string +} + +// PagerClientOptions contains the optional values for creating a [PagerClient]. +type PagerClientOptions struct { + azcore.ClientOptions +} + +// NewPagerClientWithNoCredential creates a new instance of PagerClient with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewPagerClientWithNoCredential(endpoint string, options *PagerClientOptions) (*PagerClient, error) { + if options == nil { + options = &PagerClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &PagerClient{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// NewPagerWidgetsClient creates a new instance of [PagerWidgetsClient]. +func (client *PagerClient) NewPagerWidgetsClient() *PagerWidgetsClient { + return &PagerWidgetsClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/local/internalpager/zz_pagerwidgets_client.go b/test/local/internalpager/zz_pagerwidgets_client.go new file mode 100644 index 000000000000..5a0b750431e3 --- /dev/null +++ b/test/local/internalpager/zz_pagerwidgets_client.go @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package internalpager + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// PagerWidgetsClient contains the methods for the PagerWidgets group. +// Don't use this type directly, use [PagerClient.NewPagerWidgetsClient] instead. +type PagerWidgetsClient struct { + internal *azcore.Client + endpoint string +} + +// - options - pagerWidgetsClientlistOptions contains the optional parameters for the PagerWidgetsClient.NewlistPager method. +func (client *PagerWidgetsClient) newListPager(options *pagerWidgetsClientlistOptions) *runtime.Pager[pagerWidgetsClientlistResponse] { + return runtime.NewPager(runtime.PagingHandler[pagerWidgetsClientlistResponse]{ + More: func(page pagerWidgetsClientlistResponse) bool { + return false + }, + Fetcher: func(ctx context.Context, page *pagerWidgetsClientlistResponse) (pagerWidgetsClientlistResponse, error) { + req, err := client.listCreateRequest(ctx, options) + if err != nil { + return pagerWidgetsClientlistResponse{}, err + } + resp, err := client.internal.Pipeline().Do(req) + if err != nil { + return pagerWidgetsClientlistResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return pagerWidgetsClientlistResponse{}, runtime.NewResponseError(resp) + } + return client.listHandleResponse(resp) + }, + Tracer: client.internal.Tracer(), + }) +} + +// listCreateRequest creates the list request. +func (client *PagerWidgetsClient) listCreateRequest(ctx context.Context, _ *pagerWidgetsClientlistOptions) (*policy.Request, error) { + urlPath := "/widgets" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// listHandleResponse handles the list response. +func (client *PagerWidgetsClient) listHandleResponse(resp *http.Response) (pagerWidgetsClientlistResponse, error) { + result := pagerWidgetsClientlistResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.widgetList); err != nil { + return pagerWidgetsClientlistResponse{}, err + } + return result, nil +} diff --git a/test/local/internalpager/zz_responses.go b/test/local/internalpager/zz_responses.go new file mode 100644 index 000000000000..c6edb824139c --- /dev/null +++ b/test/local/internalpager/zz_responses.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package internalpager + +// pagerWidgetsClientlistResponse contains the response from method PagerWidgetsClient.NewlistPager. +type pagerWidgetsClientlistResponse struct { + widgetList +} diff --git a/test/local/internalpager/zz_version.go b/test/local/internalpager/zz_version.go new file mode 100644 index 000000000000..291553ff46ba --- /dev/null +++ b/test/local/internalpager/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package internalpager + +const ( + moduleName = "internalpager" + moduleVersion = "v0.1.0" +) diff --git a/test/local/nooptionalbody/LICENSE.txt b/test/local/nooptionalbody/LICENSE.txt new file mode 100644 index 000000000000..48ea6616b5b8 --- /dev/null +++ b/test/local/nooptionalbody/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE diff --git a/test/local/nooptionalbody/after_generate.go b/test/local/nooptionalbody/after_generate.go new file mode 100644 index 000000000000..e027e57c6921 --- /dev/null +++ b/test/local/nooptionalbody/after_generate.go @@ -0,0 +1,6 @@ +//go:generate go run ./testdata/generate/transforms.go + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package nooptionalbody diff --git a/test/local/nooptionalbody/go.mod b/test/local/nooptionalbody/go.mod new file mode 100644 index 000000000000..470d703c13e6 --- /dev/null +++ b/test/local/nooptionalbody/go.mod @@ -0,0 +1,11 @@ +module nooptionalbody + +go 1.25.0 + +require github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/text v0.37.0 // indirect +) diff --git a/test/local/nooptionalbody/go.sum b/test/local/nooptionalbody/go.sum new file mode 100644 index 000000000000..3fdb64caf441 --- /dev/null +++ b/test/local/nooptionalbody/go.sum @@ -0,0 +1,16 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0/go.mod h1:7dCRMLwisfRH3dBupKeNCioWYUZ4SS09Z14H+7i8ZoY= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/local/nooptionalbody/testdata/_metadata.json b/test/local/nooptionalbody/testdata/_metadata.json new file mode 100644 index 000000000000..fe1d7908ede9 --- /dev/null +++ b/test/local/nooptionalbody/testdata/_metadata.json @@ -0,0 +1,3 @@ +{ + "emitterVersion": "0.0.0" +} diff --git a/test/local/nooptionalbody/testdata/generate/transforms.go b/test/local/nooptionalbody/testdata/generate/transforms.go new file mode 100644 index 000000000000..7eb2755a0ef3 --- /dev/null +++ b/test/local/nooptionalbody/testdata/generate/transforms.go @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package main + +import ( + "log" + "os" + "regexp" +) + +func regexReplace(fileName string, regex string, replace string) { + file, err := os.ReadFile(fileName) + if err != nil { + log.Fatal(err) + } + + r := regexp.MustCompile(regex) + file = r.ReplaceAll(file, []byte(replace)) + + err = os.WriteFile(fileName, file, 0644) + if err != nil { + log.Fatal(err) + } +} + +func main() { + regexReplace("zz_models.go", `REQUIRED`, "REQUIRED (transformed)") +} diff --git a/test/local/nooptionalbody/zz_client.go b/test/local/nooptionalbody/zz_client.go new file mode 100644 index 000000000000..c08d6b310162 --- /dev/null +++ b/test/local/nooptionalbody/zz_client.go @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nooptionalbody + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// Client contains the methods for the service. +// Don't use this type directly, use NewClientWithNoCredential() instead. +type Client struct { + internal *azcore.Client + endpoint string +} + +// ClientOptions contains the optional values for creating a [Client]. +type ClientOptions struct { + azcore.ClientOptions +} + +// NewClientWithNoCredential creates a new instance of Client with the specified values. +// - endpoint - Service host +// - options - Contains optional client configuration. Pass nil to accept the default values. +func NewClientWithNoCredential(endpoint string, options *ClientOptions) (*Client, error) { + if options == nil { + options = &ClientOptions{} + } + cl, err := azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, &options.ClientOptions) + if err != nil { + return nil, err + } + client := &Client{ + endpoint: endpoint, + internal: cl, + } + return client, nil +} + +// Patch - body should not be optional +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientPatchOptions contains the optional parameters for the Client.Patch method. +func (client *Client) Patch(ctx context.Context, body Widget, options *ClientPatchOptions) (ClientPatchResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.Patch", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.patchCreateRequest(ctx, body, options) + if err != nil { + return ClientPatchResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientPatchResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ClientPatchResponse{}, err + } + return ClientPatchResponse{}, nil +} + +// patchCreateRequest creates the Patch request. +func (client *Client) patchCreateRequest(ctx context.Context, body Widget, _ *ClientPatchOptions) (*policy.Request, error) { + req, err := runtime.NewRequest(ctx, http.MethodPatch, client.endpoint) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// Post - body should be optional +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientPostOptions contains the optional parameters for the Client.Post method. +func (client *Client) Post(ctx context.Context, options *ClientPostOptions) (ClientPostResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.Post", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.postCreateRequest(ctx, options) + if err != nil { + return ClientPostResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientPostResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ClientPostResponse{}, err + } + return ClientPostResponse{}, nil +} + +// postCreateRequest creates the Post request. +func (client *Client) postCreateRequest(ctx context.Context, options *ClientPostOptions) (*policy.Request, error) { + req, err := runtime.NewRequest(ctx, http.MethodPost, client.endpoint) + if err != nil { + return nil, err + } + if options != nil && options.Body != nil { + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, *options.Body); err != nil { + return nil, err + } + return req, nil + } + return req, nil +} + +// Put - body should not be optional +// If the operation fails it returns an *azcore.ResponseError type. +// - options - ClientPutOptions contains the optional parameters for the Client.Put method. +func (client *Client) Put(ctx context.Context, body Widget, options *ClientPutOptions) (ClientPutResponse, error) { + var err error + ctx, endSpan := runtime.StartSpan(ctx, "Client.Put", client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return ClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return ClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return ClientPutResponse{}, err + } + return ClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *Client) putCreateRequest(ctx context.Context, body Widget, _ *ClientPutOptions) (*policy.Request, error) { + req, err := runtime.NewRequest(ctx, http.MethodPut, client.endpoint) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/nooptionalbody/zz_models.go b/test/local/nooptionalbody/zz_models.go new file mode 100644 index 000000000000..565eacedf3d2 --- /dev/null +++ b/test/local/nooptionalbody/zz_models.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nooptionalbody + +type Widget struct { + // REQUIRED (transformed) + Weight *int32 +} diff --git a/test/local/nooptionalbody/zz_models_serde.go b/test/local/nooptionalbody/zz_models_serde.go new file mode 100644 index 000000000000..b1d37739a1fb --- /dev/null +++ b/test/local/nooptionalbody/zz_models_serde.go @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nooptionalbody + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type Widget. +func (w Widget) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "weight", w.Weight) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Widget. +func (w *Widget) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + for key, val := range rawMsg { + var err error + switch key { + case "weight": + err = unpopulate(val, "Weight", &w.Weight) + delete(rawMsg, key) + } + if err != nil { + return fmt.Errorf("unmarshalling type %T: %v", w, err) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, fn string, v any) error { + if data == nil || string(data) == "null" { + return nil + } + if err := json.Unmarshal(data, v); err != nil { + return fmt.Errorf("struct field %s: %v", fn, err) + } + return nil +} diff --git a/test/local/nooptionalbody/zz_options.go b/test/local/nooptionalbody/zz_options.go new file mode 100644 index 000000000000..6fb448a01a90 --- /dev/null +++ b/test/local/nooptionalbody/zz_options.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nooptionalbody + +// ClientPatchOptions contains the optional parameters for the Client.Patch method. +type ClientPatchOptions struct { + // placeholder for future optional parameters +} + +// ClientPostOptions contains the optional parameters for the Client.Post method. +type ClientPostOptions struct { + Body *Widget +} + +// ClientPutOptions contains the optional parameters for the Client.Put method. +type ClientPutOptions struct { + // placeholder for future optional parameters +} diff --git a/test/local/nooptionalbody/zz_responses.go b/test/local/nooptionalbody/zz_responses.go new file mode 100644 index 000000000000..91de77cc6cc1 --- /dev/null +++ b/test/local/nooptionalbody/zz_responses.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package nooptionalbody + +// ClientPatchResponse contains the response from method Client.Patch. +type ClientPatchResponse struct { + // placeholder for future response values +} + +// ClientPostResponse contains the response from method Client.Post. +type ClientPostResponse struct { + // placeholder for future response values +} + +// ClientPutResponse contains the response from method Client.Put. +type ClientPutResponse struct { + // placeholder for future response values +} diff --git a/test/local/nooptionalbody/zz_version.go b/test/local/nooptionalbody/zz_version.go new file mode 100644 index 000000000000..4a5105be8d47 --- /dev/null +++ b/test/local/nooptionalbody/zz_version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package nooptionalbody + +const ( + moduleName = "nooptionalbody" + moduleVersion = "v0.1.0" +) diff --git a/test/local/rawjson/client.go b/test/local/rawjson/client.go new file mode 100644 index 000000000000..fed442ccc04b --- /dev/null +++ b/test/local/rawjson/client.go @@ -0,0 +1,13 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +package rawjson + +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +func Parent(options *azcore.ClientOptions) (*azcore.Client, error) { + return azcore.NewClient(moduleName, moduleVersion, runtime.PipelineOptions{}, options) +} diff --git a/test/local/rawjson/go.mod b/test/local/rawjson/go.mod new file mode 100644 index 000000000000..5b1eb9fbe47c --- /dev/null +++ b/test/local/rawjson/go.mod @@ -0,0 +1,11 @@ +module rawjson/v2 + +go 1.24.0 + +require github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2 // indirect + golang.org/x/net v0.49.0 // indirect + golang.org/x/text v0.33.0 // indirect +) diff --git a/test/local/rawjson/go.sum b/test/local/rawjson/go.sum new file mode 100644 index 000000000000..84a581b2cc77 --- /dev/null +++ b/test/local/rawjson/go.sum @@ -0,0 +1,16 @@ +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.0 h1:fou+2+WFTib47nS+nz/ozhEBnvU96bKHy6LjRsY4E28= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.0/go.mod h1:t76Ruy8AHvUAC8GfMWJMa0ElSbuIcO03NLpynfbgsPA= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2 h1:9iefClla7iYpfYWdzPCRDozdmndjTm8DXdpCzPajMgA= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2/go.mod h1:XtLgD3ZD34DAaVIIAyG3objl5DynM3CQ/vMcbBNJZGI= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o= +golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8= +golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE= +golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/test/local/rawjson/subpkg/fake/zz_internal.go b/test/local/rawjson/subpkg/fake/zz_internal.go new file mode 100644 index 000000000000..d6b3e83b19e1 --- /dev/null +++ b/test/local/rawjson/subpkg/fake/zz_internal.go @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "net/http" + "sync" +) + +type result struct { + resp *http.Response + err error +} + +type nonRetriableError struct { + error +} + +func (nonRetriableError) NonRetriable() { + // marker method +} + +func initServer[T any](mu *sync.Mutex, dst **T, src func() *T) { + mu.Lock() + if *dst == nil { + *dst = src() + } + mu.Unlock() +} diff --git a/test/local/rawjson/subpkg/fake/zz_rawjson_server.go b/test/local/rawjson/subpkg/fake/zz_rawjson_server.go new file mode 100644 index 000000000000..b84025ccfd74 --- /dev/null +++ b/test/local/rawjson/subpkg/fake/zz_rawjson_server.go @@ -0,0 +1,87 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "strings" + "sync" +) + +// RawJSONServer is a fake server for instances of the subpkg.RawJSONClient type. +type RawJSONServer struct { + // RawJSONInputOnlyServer contains the fakes for client RawJSONInputOnlyClient + RawJSONInputOnlyServer RawJSONInputOnlyServer + + // RawJSONModelCaseServer contains the fakes for client RawJSONModelCaseClient + RawJSONModelCaseServer RawJSONModelCaseServer + + // RawJSONOutputOnlyServer contains the fakes for client RawJSONOutputOnlyClient + RawJSONOutputOnlyServer RawJSONOutputOnlyServer +} + +// NewRawJSONServerTransport creates a new instance of RawJSONServerTransport with the provided implementation. +// The returned RawJSONServerTransport instance is connected to an instance of subpkg.RawJSONClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewRawJSONServerTransport(srv *RawJSONServer) *RawJSONServerTransport { + return &RawJSONServerTransport{srv: srv} +} + +// RawJSONServerTransport connects instances of subpkg.RawJSONClient to instances of RawJSONServer. +// Don't use this type directly, use NewRawJSONServerTransport instead. +type RawJSONServerTransport struct { + srv *RawJSONServer + trMu sync.Mutex + trRawJSONInputOnlyServer *RawJSONInputOnlyServerTransport + trRawJSONModelCaseServer *RawJSONModelCaseServerTransport + trRawJSONOutputOnlyServer *RawJSONOutputOnlyServerTransport +} + +// Do implements the policy.Transporter interface for RawJSONServerTransport. +func (r *RawJSONServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return r.dispatchToClientFake(req, method[:strings.Index(method, ".")]) +} + +func (r *RawJSONServerTransport) dispatchToClientFake(req *http.Request, client string) (*http.Response, error) { + var resp *http.Response + var err error + + switch client { + case "RawJSONInputOnlyClient": + initServer(&r.trMu, &r.trRawJSONInputOnlyServer, func() *RawJSONInputOnlyServerTransport { + return NewRawJSONInputOnlyServerTransport(&r.srv.RawJSONInputOnlyServer) + }) + resp, err = r.trRawJSONInputOnlyServer.Do(req) + case "RawJSONModelCaseClient": + initServer(&r.trMu, &r.trRawJSONModelCaseServer, func() *RawJSONModelCaseServerTransport { + return NewRawJSONModelCaseServerTransport(&r.srv.RawJSONModelCaseServer) + }) + resp, err = r.trRawJSONModelCaseServer.Do(req) + case "RawJSONOutputOnlyClient": + initServer(&r.trMu, &r.trRawJSONOutputOnlyServer, func() *RawJSONOutputOnlyServerTransport { + return NewRawJSONOutputOnlyServerTransport(&r.srv.RawJSONOutputOnlyServer) + }) + resp, err = r.trRawJSONOutputOnlyServer.Do(req) + default: + err = fmt.Errorf("unhandled client %s", client) + } + + return resp, err +} + +// set this to conditionally intercept incoming requests to RawJSONServerTransport +var rawJsonServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/rawjson/subpkg/fake/zz_rawjsoninputonly_server.go b/test/local/rawjson/subpkg/fake/zz_rawjsoninputonly_server.go new file mode 100644 index 000000000000..247770218208 --- /dev/null +++ b/test/local/rawjson/subpkg/fake/zz_rawjsoninputonly_server.go @@ -0,0 +1,107 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "io" + "net/http" + "rawjson/v2/subpkg" + "slices" +) + +// RawJSONInputOnlyServer is a fake server for instances of the subpkg.RawJSONInputOnlyClient type. +type RawJSONInputOnlyServer struct { + // Put is the fake for method RawJSONInputOnlyClient.Put + // HTTP status codes to indicate success: http.StatusNoContent + Put func(ctx context.Context, body []byte, options *subpkg.RawJSONInputOnlyClientPutOptions) (resp azfake.Responder[subpkg.RawJSONInputOnlyClientPutResponse], errResp azfake.ErrorResponder) +} + +// NewRawJSONInputOnlyServerTransport creates a new instance of RawJSONInputOnlyServerTransport with the provided implementation. +// The returned RawJSONInputOnlyServerTransport instance is connected to an instance of subpkg.RawJSONInputOnlyClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewRawJSONInputOnlyServerTransport(srv *RawJSONInputOnlyServer) *RawJSONInputOnlyServerTransport { + return &RawJSONInputOnlyServerTransport{srv: srv} +} + +// RawJSONInputOnlyServerTransport connects instances of subpkg.RawJSONInputOnlyClient to instances of RawJSONInputOnlyServer. +// Don't use this type directly, use NewRawJSONInputOnlyServerTransport instead. +type RawJSONInputOnlyServerTransport struct { + srv *RawJSONInputOnlyServer +} + +// Do implements the policy.Transporter interface for RawJSONInputOnlyServerTransport. +func (r *RawJSONInputOnlyServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return r.dispatchToMethodFake(req, method) +} + +func (r *RawJSONInputOnlyServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if rawJsonInputOnlyServerTransportInterceptor != nil { + res.resp, res.err, intercepted = rawJsonInputOnlyServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "RawJSONInputOnlyClient.Put": + res.resp, res.err = r.dispatchPut(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (r *RawJSONInputOnlyServerTransport) dispatchPut(req *http.Request) (*http.Response, error) { + if r.srv.Put == nil { + return nil, &nonRetriableError{errors.New("fake for method Put not implemented")} + } + body, err := io.ReadAll(req.Body) + if err != nil { + return nil, err + } + req.Body.Close() + respr, errRespr := r.srv.Put(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusNoContent}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusNoContent", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, nil) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to RawJSONInputOnlyServerTransport +var rawJsonInputOnlyServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/rawjson/subpkg/fake/zz_rawjsonmodelcase_server.go b/test/local/rawjson/subpkg/fake/zz_rawjsonmodelcase_server.go new file mode 100644 index 000000000000..bc9b43573c07 --- /dev/null +++ b/test/local/rawjson/subpkg/fake/zz_rawjsonmodelcase_server.go @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "rawjson/v2/subpkg" + "slices" +) + +// RawJSONModelCaseServer is a fake server for instances of the subpkg.RawJSONModelCaseClient type. +type RawJSONModelCaseServer struct { + // ForModel is the fake for method RawJSONModelCaseClient.ForModel + // HTTP status codes to indicate success: http.StatusOK + ForModel func(ctx context.Context, body subpkg.ContainsRawJSON, options *subpkg.RawJSONModelCaseClientForModelOptions) (resp azfake.Responder[subpkg.RawJSONModelCaseClientForModelResponse], errResp azfake.ErrorResponder) +} + +// NewRawJSONModelCaseServerTransport creates a new instance of RawJSONModelCaseServerTransport with the provided implementation. +// The returned RawJSONModelCaseServerTransport instance is connected to an instance of subpkg.RawJSONModelCaseClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewRawJSONModelCaseServerTransport(srv *RawJSONModelCaseServer) *RawJSONModelCaseServerTransport { + return &RawJSONModelCaseServerTransport{srv: srv} +} + +// RawJSONModelCaseServerTransport connects instances of subpkg.RawJSONModelCaseClient to instances of RawJSONModelCaseServer. +// Don't use this type directly, use NewRawJSONModelCaseServerTransport instead. +type RawJSONModelCaseServerTransport struct { + srv *RawJSONModelCaseServer +} + +// Do implements the policy.Transporter interface for RawJSONModelCaseServerTransport. +func (r *RawJSONModelCaseServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return r.dispatchToMethodFake(req, method) +} + +func (r *RawJSONModelCaseServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if rawJsonModelCaseServerTransportInterceptor != nil { + res.resp, res.err, intercepted = rawJsonModelCaseServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "RawJSONModelCaseClient.ForModel": + res.resp, res.err = r.dispatchForModel(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (r *RawJSONModelCaseServerTransport) dispatchForModel(req *http.Request) (*http.Response, error) { + if r.srv.ForModel == nil { + return nil, &nonRetriableError{errors.New("fake for method ForModel not implemented")} + } + body, err := server.UnmarshalRequestAsJSON[subpkg.ContainsRawJSON](req) + if err != nil { + return nil, err + } + respr, errRespr := r.srv.ForModel(req.Context(), body, nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.MarshalResponseAsJSON(respContent, server.GetResponse(respr).ContainsRawJSON, req) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to RawJSONModelCaseServerTransport +var rawJsonModelCaseServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/rawjson/subpkg/fake/zz_rawjsonoutputonly_server.go b/test/local/rawjson/subpkg/fake/zz_rawjsonoutputonly_server.go new file mode 100644 index 000000000000..e952004e3cca --- /dev/null +++ b/test/local/rawjson/subpkg/fake/zz_rawjsonoutputonly_server.go @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package fake + +import ( + "bytes" + "context" + "errors" + "fmt" + azfake "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/fake/server" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "io" + "net/http" + "rawjson/v2/subpkg" + "slices" +) + +// RawJSONOutputOnlyServer is a fake server for instances of the subpkg.RawJSONOutputOnlyClient type. +type RawJSONOutputOnlyServer struct { + // Get is the fake for method RawJSONOutputOnlyClient.Get + // HTTP status codes to indicate success: http.StatusOK + Get func(ctx context.Context, options *subpkg.RawJSONOutputOnlyClientGetOptions) (resp azfake.Responder[subpkg.RawJSONOutputOnlyClientGetResponse], errResp azfake.ErrorResponder) +} + +// NewRawJSONOutputOnlyServerTransport creates a new instance of RawJSONOutputOnlyServerTransport with the provided implementation. +// The returned RawJSONOutputOnlyServerTransport instance is connected to an instance of subpkg.RawJSONOutputOnlyClient via the +// azcore.ClientOptions.Transporter field in the client's constructor parameters. +func NewRawJSONOutputOnlyServerTransport(srv *RawJSONOutputOnlyServer) *RawJSONOutputOnlyServerTransport { + return &RawJSONOutputOnlyServerTransport{srv: srv} +} + +// RawJSONOutputOnlyServerTransport connects instances of subpkg.RawJSONOutputOnlyClient to instances of RawJSONOutputOnlyServer. +// Don't use this type directly, use NewRawJSONOutputOnlyServerTransport instead. +type RawJSONOutputOnlyServerTransport struct { + srv *RawJSONOutputOnlyServer +} + +// Do implements the policy.Transporter interface for RawJSONOutputOnlyServerTransport. +func (r *RawJSONOutputOnlyServerTransport) Do(req *http.Request) (*http.Response, error) { + rawMethod := req.Context().Value(runtime.CtxAPINameKey{}) + method, ok := rawMethod.(string) + if !ok { + return nil, nonRetriableError{errors.New("unable to dispatch request, missing value for CtxAPINameKey")} + } + + return r.dispatchToMethodFake(req, method) +} + +func (r *RawJSONOutputOnlyServerTransport) dispatchToMethodFake(req *http.Request, method string) (*http.Response, error) { + resultChan := make(chan result, 1) + go func() { + var intercepted bool + var res result + if rawJsonOutputOnlyServerTransportInterceptor != nil { + res.resp, res.err, intercepted = rawJsonOutputOnlyServerTransportInterceptor.Do(req) + } + if !intercepted { + switch method { + case "RawJSONOutputOnlyClient.Get": + res.resp, res.err = r.dispatchGet(req) + default: + res.err = fmt.Errorf("unhandled API %s", method) + } + + } + resultChan <- res + }() + + select { + case <-req.Context().Done(): + return nil, req.Context().Err() + case res := <-resultChan: + return res.resp, res.err + } +} + +func (r *RawJSONOutputOnlyServerTransport) dispatchGet(req *http.Request) (*http.Response, error) { + if r.srv.Get == nil { + return nil, &nonRetriableError{errors.New("fake for method Get not implemented")} + } + respr, errRespr := r.srv.Get(req.Context(), nil) + if respErr := server.GetError(errRespr, req); respErr != nil { + return nil, respErr + } + respContent := server.GetResponseContent(respr) + if !slices.Contains([]int{http.StatusOK}, respContent.HTTPStatus) { + return nil, &nonRetriableError{fmt.Errorf("unexpected status code %d. acceptable values are http.StatusOK", respContent.HTTPStatus)} + } + resp, err := server.NewResponse(respContent, req, &server.ResponseOptions{ + Body: io.NopCloser(bytes.NewReader(server.GetResponse(respr).RawJSON)), + ContentType: "application/json", + }) + if err != nil { + return nil, err + } + return resp, nil +} + +// set this to conditionally intercept incoming requests to RawJSONOutputOnlyServerTransport +var rawJsonOutputOnlyServerTransportInterceptor interface { + // Do returns true if the server transport should use the returned response/error + Do(*http.Request) (*http.Response, error, bool) +} diff --git a/test/local/rawjson/subpkg/zz_models.go b/test/local/rawjson/subpkg/zz_models.go new file mode 100644 index 000000000000..e9d5c4356d34 --- /dev/null +++ b/test/local/rawjson/subpkg/zz_models.go @@ -0,0 +1,13 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package subpkg + +type ContainsRawJSON struct { + // REQUIRED; The contents of this field are raw JSON. + Anything1 []byte + + // REQUIRED; The contents of this field are raw JSON. + Anything2 []byte +} diff --git a/test/local/rawjson/subpkg/zz_models_serde.go b/test/local/rawjson/subpkg/zz_models_serde.go new file mode 100644 index 000000000000..de2bb232198c --- /dev/null +++ b/test/local/rawjson/subpkg/zz_models_serde.go @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package subpkg + +import ( + "encoding/json" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" +) + +// MarshalJSON implements the json.Marshaller interface for type ContainsRawJSON. +func (c ContainsRawJSON) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]any) + populate(objectMap, "anything1", json.RawMessage(c.Anything1)) + populate(objectMap, "anything2", json.RawMessage(c.Anything2)) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContainsRawJSON. +func (c *ContainsRawJSON) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return fmt.Errorf("unmarshalling type %T: %v", c, err) + } + for key, val := range rawMsg { + switch key { + case "anything1": + if string(val) != "null" { + c.Anything1 = val + } + delete(rawMsg, key) + case "anything2": + if string(val) != "null" { + c.Anything2 = val + } + delete(rawMsg, key) + } + } + return nil +} + +func populate(m map[string]any, k string, v any) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} diff --git a/test/local/rawjson/subpkg/zz_options.go b/test/local/rawjson/subpkg/zz_options.go new file mode 100644 index 000000000000..07837ac70b3b --- /dev/null +++ b/test/local/rawjson/subpkg/zz_options.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package subpkg + +// RawJSONInputOnlyClientPutOptions contains the optional parameters for the RawJSONInputOnlyClient.Put method. +type RawJSONInputOnlyClientPutOptions struct { + // placeholder for future optional parameters +} + +// RawJSONModelCaseClientForModelOptions contains the optional parameters for the RawJSONModelCaseClient.ForModel method. +type RawJSONModelCaseClientForModelOptions struct { + // placeholder for future optional parameters +} + +// RawJSONOutputOnlyClientGetOptions contains the optional parameters for the RawJSONOutputOnlyClient.Get method. +type RawJSONOutputOnlyClientGetOptions struct { + // placeholder for future optional parameters +} diff --git a/test/local/rawjson/subpkg/zz_rawjson_client.go b/test/local/rawjson/subpkg/zz_rawjson_client.go new file mode 100644 index 000000000000..843928f9bd99 --- /dev/null +++ b/test/local/rawjson/subpkg/zz_rawjson_client.go @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package subpkg + +import "github.com/Azure/azure-sdk-for-go/sdk/azcore" + +// RawJSONClient contains the methods for the RawJSON group. +// Don't use this type directly, use a constructor function instead. +type RawJSONClient struct { + internal *azcore.Client + endpoint string +} + +// NewRawJSONInputOnlyClient creates a new instance of [RawJSONInputOnlyClient]. +func (client *RawJSONClient) NewRawJSONInputOnlyClient() *RawJSONInputOnlyClient { + return &RawJSONInputOnlyClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewRawJSONModelCaseClient creates a new instance of [RawJSONModelCaseClient]. +func (client *RawJSONClient) NewRawJSONModelCaseClient() *RawJSONModelCaseClient { + return &RawJSONModelCaseClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} + +// NewRawJSONOutputOnlyClient creates a new instance of [RawJSONOutputOnlyClient]. +func (client *RawJSONClient) NewRawJSONOutputOnlyClient() *RawJSONOutputOnlyClient { + return &RawJSONOutputOnlyClient{ + endpoint: client.endpoint, + internal: client.internal, + } +} diff --git a/test/local/rawjson/subpkg/zz_rawjsoninputonly_client.go b/test/local/rawjson/subpkg/zz_rawjsoninputonly_client.go new file mode 100644 index 000000000000..107c54eed5ec --- /dev/null +++ b/test/local/rawjson/subpkg/zz_rawjsoninputonly_client.go @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package subpkg + +import ( + "bytes" + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming" + "net/http" +) + +// RawJSONInputOnlyClient contains the methods for the RawJSONInputOnly group. +// Don't use this type directly, use [RawJSONClient.NewRawJSONInputOnlyClient] instead. +type RawJSONInputOnlyClient struct { + internal *azcore.Client + endpoint string +} + +// Put - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - RawJSONInputOnlyClientPutOptions contains the optional parameters for the RawJSONInputOnlyClient.Put method. +func (client *RawJSONInputOnlyClient) Put(ctx context.Context, body []byte, options *RawJSONInputOnlyClientPutOptions) (RawJSONInputOnlyClientPutResponse, error) { + var err error + const operationName = "RawJSONInputOnlyClient.Put" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.putCreateRequest(ctx, body, options) + if err != nil { + return RawJSONInputOnlyClientPutResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RawJSONInputOnlyClientPutResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusNoContent) { + err = runtime.NewResponseError(httpResp) + return RawJSONInputOnlyClientPutResponse{}, err + } + return RawJSONInputOnlyClientPutResponse{}, nil +} + +// putCreateRequest creates the Put request. +func (client *RawJSONInputOnlyClient) putCreateRequest(ctx context.Context, body []byte, _ *RawJSONInputOnlyClientPutOptions) (*policy.Request, error) { + urlPath := "/input" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := req.SetBody(streaming.NopCloser(bytes.NewReader(body)), "application/json"); err != nil { + return nil, err + } + return req, nil +} diff --git a/test/local/rawjson/subpkg/zz_rawjsonmodelcase_client.go b/test/local/rawjson/subpkg/zz_rawjsonmodelcase_client.go new file mode 100644 index 000000000000..66bb37f2057e --- /dev/null +++ b/test/local/rawjson/subpkg/zz_rawjsonmodelcase_client.go @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package subpkg + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// RawJSONModelCaseClient contains the methods for the RawJSONModelCase group. +// Don't use this type directly, use [RawJSONClient.NewRawJSONModelCaseClient] instead. +type RawJSONModelCaseClient struct { + internal *azcore.Client + endpoint string +} + +// ForModel - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - RawJSONModelCaseClientForModelOptions contains the optional parameters for the RawJSONModelCaseClient.ForModel +// method. +func (client *RawJSONModelCaseClient) ForModel(ctx context.Context, body ContainsRawJSON, options *RawJSONModelCaseClientForModelOptions) (RawJSONModelCaseClientForModelResponse, error) { + var err error + const operationName = "RawJSONModelCaseClient.ForModel" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.forModelCreateRequest(ctx, body, options) + if err != nil { + return RawJSONModelCaseClientForModelResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RawJSONModelCaseClientForModelResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RawJSONModelCaseClientForModelResponse{}, err + } + resp, err := client.forModelHandleResponse(httpResp) + return resp, err +} + +// forModelCreateRequest creates the ForModel request. +func (client *RawJSONModelCaseClient) forModelCreateRequest(ctx context.Context, body ContainsRawJSON, _ *RawJSONModelCaseClientForModelOptions) (*policy.Request, error) { + urlPath := "/unknown2" + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + req.Raw().Header["Content-Type"] = []string{"application/json"} + if err := runtime.MarshalAsJSON(req, body); err != nil { + return nil, err + } + return req, nil +} + +// forModelHandleResponse handles the ForModel response. +func (client *RawJSONModelCaseClient) forModelHandleResponse(resp *http.Response) (RawJSONModelCaseClientForModelResponse, error) { + result := RawJSONModelCaseClientForModelResponse{} + if err := runtime.UnmarshalAsJSON(resp, &result.ContainsRawJSON); err != nil { + return RawJSONModelCaseClientForModelResponse{}, err + } + return result, nil +} diff --git a/test/local/rawjson/subpkg/zz_rawjsonoutputonly_client.go b/test/local/rawjson/subpkg/zz_rawjsonoutputonly_client.go new file mode 100644 index 000000000000..d4a72b7b9faa --- /dev/null +++ b/test/local/rawjson/subpkg/zz_rawjsonoutputonly_client.go @@ -0,0 +1,67 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package subpkg + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// RawJSONOutputOnlyClient contains the methods for the RawJSONOutputOnly group. +// Don't use this type directly, use [RawJSONClient.NewRawJSONOutputOnlyClient] instead. +type RawJSONOutputOnlyClient struct { + internal *azcore.Client + endpoint string +} + +// Get - +// If the operation fails it returns an *azcore.ResponseError type. +// - options - RawJSONOutputOnlyClientGetOptions contains the optional parameters for the RawJSONOutputOnlyClient.Get method. +func (client *RawJSONOutputOnlyClient) Get(ctx context.Context, options *RawJSONOutputOnlyClientGetOptions) (RawJSONOutputOnlyClientGetResponse, error) { + var err error + const operationName = "RawJSONOutputOnlyClient.Get" + ctx = context.WithValue(ctx, runtime.CtxAPINameKey{}, operationName) + ctx, endSpan := runtime.StartSpan(ctx, operationName, client.internal.Tracer(), nil) + defer func() { endSpan(err) }() + req, err := client.getCreateRequest(ctx, options) + if err != nil { + return RawJSONOutputOnlyClientGetResponse{}, err + } + httpResp, err := client.internal.Pipeline().Do(req) + if err != nil { + return RawJSONOutputOnlyClientGetResponse{}, err + } + if !runtime.HasStatusCode(httpResp, http.StatusOK) { + err = runtime.NewResponseError(httpResp) + return RawJSONOutputOnlyClientGetResponse{}, err + } + resp, err := client.getHandleResponse(httpResp) + return resp, err +} + +// getCreateRequest creates the Get request. +func (client *RawJSONOutputOnlyClient) getCreateRequest(ctx context.Context, _ *RawJSONOutputOnlyClientGetOptions) (*policy.Request, error) { + urlPath := "/output" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.endpoint, urlPath)) + if err != nil { + return nil, err + } + req.Raw().Header["Accept"] = []string{"application/json"} + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *RawJSONOutputOnlyClient) getHandleResponse(resp *http.Response) (RawJSONOutputOnlyClientGetResponse, error) { + result := RawJSONOutputOnlyClientGetResponse{} + body, err := runtime.Payload(resp) + if err != nil { + return RawJSONOutputOnlyClientGetResponse{}, err + } + result.RawJSON = body + return result, nil +} diff --git a/test/local/rawjson/subpkg/zz_responses.go b/test/local/rawjson/subpkg/zz_responses.go new file mode 100644 index 000000000000..f72f870186d3 --- /dev/null +++ b/test/local/rawjson/subpkg/zz_responses.go @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. DO NOT EDIT. + +package subpkg + +// RawJSONInputOnlyClientPutResponse contains the response from method RawJSONInputOnlyClient.Put. +type RawJSONInputOnlyClientPutResponse struct { + // placeholder for future response values +} + +// RawJSONModelCaseClientForModelResponse contains the response from method RawJSONModelCaseClient.ForModel. +type RawJSONModelCaseClientForModelResponse struct { + ContainsRawJSON +} + +// RawJSONOutputOnlyClientGetResponse contains the response from method RawJSONOutputOnlyClient.Get. +type RawJSONOutputOnlyClientGetResponse struct { + RawJSON []byte +} diff --git a/test/local/rawjson/version.go b/test/local/rawjson/version.go new file mode 100644 index 000000000000..7f83c312ace3 --- /dev/null +++ b/test/local/rawjson/version.go @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Code generated by Microsoft (R) Go Code Generator. + +package rawjson + +const ( + moduleName = "rawjson" + moduleVersion = "v2.0.3" +)